Skip to content
ContractSpec
Start here

Package manual · platform

·Billing, finance and economic evidence

lib.cost-tracking

API cost tracking and budgeting

platformlibraryv6.0.4stableservernode
@lssm-tech/lib.cost-tracking
bun add @lssm-tech/lib.cost-tracking
Package source ↗Manifest ↗

Manifest declarations describe the current workspace; they do not verify registry publication or runtime execution.

Package guide

Website: https://contractspec.io

API cost tracking and budgeting.

What It Provides

  • Layer: lib.
  • Consumers: bundles.
  • Related ContractSpec packages include @lssm-tech/tool.bun, @lssm-tech/tool.typescript.
  • Related ContractSpec packages include @lssm-tech/tool.bun, @lssm-tech/tool.typescript.

Installation

npm install @lssm-tech/lib.cost-tracking

or

bun add @lssm-tech/lib.cost-tracking

Usage

Import the root entrypoint from @lssm-tech/lib.cost-tracking. The current package export map exposes only the root . entrypoint, so consumers should avoid undocumented subpath imports.

Architecture

  • src/budget-alert-manager.ts is part of the package's public or composition surface.
  • src/cost-model.ts is part of the package's public or composition surface.
  • src/cost-tracker.ts is part of the package's public or composition surface.
  • src/exact-cost-calculator.ts deterministically multiplies integer usage by exact minor-unit or decimal-string rate cards.
  • src/economic-evidence*.ts provides additive neutral economic evidence helpers backed by @lssm-tech/lib.economic-evidence.
  • src/index.ts is the root public barrel and package entrypoint.
  • src/optimization-recommender.ts is part of the package's public or composition surface.
  • src/types.ts is shared public type definitions.

Shared AI spend budget (F4, D-241, D-242)

src/ai-spend-budget/ is the one AI spend budget port for every LLM consumer, exported from the root entrypoint. Amounts are integer micro-USD.

  • Scope: product, role (the lib.ai-providers roles plus embedding) and UTC day. A product daily cap spans all its roles; a role may also have its own daily cap (0 = the product cap). Each reservation is bounded by the role's per-call cap.
  • Semantics: reserve takes the worst case before any model call; one operation ref is one attempt. Reserving a ref again (a retry, a later day, open or settled) throws operation_already_reserved and reserves nothing, so no second model call runs under one reservation: give each attempt its own ref. settle replaces the reservation with the measured cost, or keeps it counted in full when the outcome is unknown; it settles once, refuses a ref the port did not issue (AI_SPEND_RESERVATION_INVALID) and records a cost sample only for the settle that changed the reservation. Caps are re-read at every reservation and default to 0 (OFF); refusals throw AiSpendRefusedErrorV1 (budget_off, budget_exhausted, product_budget_exhausted, per_call_cap_exceeded, operation_already_reserved, author_budget_exhausted).
  • Caps: parseAiSpendCapsV1(env, product, roles) reads AI_SPEND_<PRODUCT>_DAILY_MICROUSD, AI_SPEND_<PRODUCT>_<ROLE>_PER_CALL_MICROUSD and AI_SPEND_<PRODUCT>_<ROLE>_DAILY_MICROUSD (aiSpendCapEnvNamesV1 lists them for explicit host reads); malformed values throw. TAFIO_AI_SPEND_LAUNCH_CAPS_D234 records the D-234 launch values ($0.25 per call, $25 per day) as reference only.
  • Stores: AiSpendLedgerV1 with createInMemoryAiSpendLedgerV1 (one process) and createPostgresAiSpendLedgerV1 (all instances; advisory lock per deployment, product and day). A known ref returns existing_open or existing_settled; settle returns settled or unchanged. In PostgreSQL a reservation is keyed by (deployment_id, reservation_ref) and every query is scoped to the ledger's deployment, so deployments sharing a database never see each other's refs. The schema is the migration migrations/0001_aibudget_ai_spend_ledger.sql (series ai_spend, allocated by the g8 round-3b train; AI_SPEND_LEDGER_MIGRATION_V1, byte-identical, pinned by a PGlite test; the old AI_SPEND_LEDGER_MIGRATION_PROPOSAL_V1 name is an alias). The integrator allocates its number in the series of each database a host binds the ledger to (the Tafio CV governance series lists it in tafio-web/release/cv-governance-sql.ts) and applies it through the reviewed operator path; this library never migrates.
  • Monthly author budget (D-244): an authored reservation (author: the model author the call is routed to) counts toward that author's UTC month across every product and role of the deployment. It is refused with author_budget_exhausted when the author's monthly cap is spent (AI_SPEND_AUTHOR_<AUTHOR>_MONTHLY_MICROUSD, parseAiSpendAuthorMonthlyCapV1; unset = Anthropic 200 USD, no cap for other authors; 0 = no author cap; malformed throws) or when the Gateway reported the author's quota exhausted (reportAuthorQuotaExhausted, one mark per deployment, author and month in ai_spend.author_exhaustion). Both lapse when the UTC month rolls over; an operator who must clear a wrong mark earlier deletes its row. Routing asks exhaustedAuthors(authors, amount) / authorStatus(author, amount) before a call and promotes the fallback author (lib.ai-providers promoteAiGatewayRouteForBudget); settle({ servedAuthor }) re-attributes the spend to the author that actually served a Gateway fallback. The D-234 per-call and daily caps still apply to every authored reservation. The PostgreSQL ledger takes an advisory lock per (deployment, author, month) before the one per (deployment, product, day), always in that order (rehearsed on native PostgreSQL 18 as the least-privilege host login: concurrent reservations of one author across products never exceed its month, and a copy without the author lock fails that test; tafio-web/src/cv/ai-spend-ledger.host-pg.test.ts through the CV host's own pg pool, AI_SPEND_LEDGER_HOST_PG_URL). The cap is inclusive: spend exactly at the cap is admitted.
  • Ledgers of the earlier contract: the three author methods of AiSpendLedgerV1 (authorSpent, markAuthorExhausted, authorExhaustion) are optional, so a custom ledger written before D-244 keeps compiling and keeps serving unauthored calls exactly as before. Such a ledger cannot count an author's month, so the port fails closed for every authored call: reserve({ author }) refuses author_budget_exhausted before reaching the ledger, authorStatus reports exhausted: 'author_untracked' (every author is in exhaustedAuthors), and reportAuthorQuotaExhausted throws AI_SPEND_LEDGER_AUTHOR_UNSUPPORTED. The built-in ledgers implement all three (AiSpendAuthorLedgerV1, aiSpendLedgerTracksAuthorsV1).
  • Quota reports never mask the call: in runWithAiSpendBudgetV1 a failing classifier or reportAuthorQuotaExhausted is swallowed and the call's own error is rethrown (the reservation stays counted).
  • lib.cost-tracking: pass a CostTracker as tracker and every measured settle becomes a cost sample (ai.<role>, tenant = product).

Integration points (bound in the consumers, D-244):

ConsumerBinding
Tafio CV (tafio-web/src/cv/budget.ts, bound)cvBudgetLedgerV1 selects createAiSpendScopedDayLedgerV1({ ledger, scope: { product: 'tafio', role: 'generation' }, productDailyCapMicrousd }) when CAREER_CV_AI_SPEND_LEDGER=shared (default cv: the CV ledger, until the ai_spend migration is allocated and applied). It has the CvBudgetLedgerV1 shape, so createCvGenerationBudgetV1 keeps its refs and caps while the product-wide cap applies (0 = only the CV role cap; other roles' spend never counts against it). It keeps the CV existing answer for a known ref, which is safe only because the document pipeline claims the operation hash before reserving.
Tafio CV author budget (tafio-web/src/cv/budget.ts cvAiAuthorBudgetV1, server/cv-ports.server.ts)With shared, each request reads the month's exhausted authors before building routes and passes the generation author to the scoped ledger (author); a Gateway quota failure is reported through the routes' onQuotaExhausted. No independent critic left = ai_budget_month_exhausted before any reservation (cvBudgetedGatewayRoutesV1, cv/gateway-budget.ts). The CV reservation covers generation and critique and stays attributed to the generation route's primary author, deliberately: when the Gateway falls back for the generation (OpenAI served it), the critic is chosen by the other author, i.e. the primary (Anthropic), so moving the whole reservation to the served author would hide the primary author's critic share; keeping it on the primary over-counts that author (conservative for the only capped author by default).
p13 posting enrichment (osint-worker/src/public-job-enrichment/ai-spend.ts)JOB_ENRICHMENT_AI_SPEND_LEDGER=shared (default off): bindAiSpendScopeV1(port, { product: 'job-enrichment', role: 'enrichment' }) over the inventory database; the run's route drops exhausted authors, and each model call runs through runWithAiSpendBudgetV1 with one ref per attempt, the stage's own worst-case estimate and prices, the route author and the Gateway quota classifier. A shared refusal aborts the run (a budget stop, not the outage guard). The stage's own run/day caps (PaidStageBudgetV1) are unchanged.
p17 assistant (tafio-web/src/assistant/budget-shared.ts)CAREER_ASSISTANT_AI_SPEND_LEDGER=shared (default own): bindAiSpendScopeV1(port, { product: <brand key>, role: 'assistant' }); every turn reserves its per-turn cap in both ledgers (a refusal of either settles the other at zero), settles the measured spend to the served author, and the routes skip exhausted authors.

A binding's settle refuses a ref of another scope (AI_SPEND_RESERVATION_OUT_OF_SCOPE).

Why ai-cost-guard is not lifted into this port (D-244 item)

contracts-runtime-server-rest/src/ai-cost-guard.ts (AiQueryRateLimiter, AiAbuseDetector, AiCostGuardPolicy) does not fit the shared spend port cleanly, so it stays where it is:

  • it counts requests per user per minute and a 10-second burst flag, while the port counts money per product, role, author and UTC day/month;
  • its state is per process (Maps plus setInterval cleanup timers started in constructors, ambient Date.now()), while the port is durable and shared by every instance through its ledger; lifting it would either make the port stateful per process or require a second durable store with a different consistency model;
  • its abuse flag is an operator-cleared moderation state, not a budget that rolls over.

Per-subject money caps that do belong to spend already exist where the subject is known: the assistant's per-candidate daily cap (CAREER_ASSISTANT_BUDGET_CANDIDATE_DAILY_MICROUSD) and the CV per-generation cap. A durable per-user request limiter, if a host needs one across instances, is a separate port (rate limiting), not a spend budget.

Public Entry Points

  • Export . resolves through ./src/index.ts.
  • Economic evidence helpers are exported from the root entrypoint; keep subpath imports undocumented until the package export map intentionally changes.

Local Commands

  • bun run dev — contractspec-bun-build dev
  • bun run build — contractspec-bun-build build
  • bun run test — bun test --pass-with-no-tests
  • bun run lint — bun lint:fix
  • bun run lint:check — biome check .
  • bun run lint:fix — biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write .
  • bun run typecheck — tsgo --noEmit
  • bun run publish:pkg — bun publish --tolerate-republish --ignore-scripts --verbose
  • bun run publish:pkg:canary — bun publish:pkg --tag canary
  • bun run clean — rimraf dist .turbo
  • bun run build:bundle — contractspec-bun-build transpile
  • bun run build:types — contractspec-bun-build types
  • bun run prebuild — contractspec-bun-build prebuild

Recent Updates

  • Add the shared AI spend budget port (src/ai-spend-budget/) with in-memory and PostgreSQL ledgers.
  • Add neutral economic evidence bridge helpers that emit usage, cost, budget, and optimization projection refs without changing existing cost calculation semantics.
  • Replace eslint+prettier by biomejs to optimize speed.

Notes

  • Cost calculation logic must stay deterministic — no side effects or external calls during computation.
  • Budget threshold types are shared across consumers; changes require coordination.
  • Do not introduce floating-point arithmetic where precision matters; use integer cents or a decimal library.
  • Existing number-based cost totals are exposed to economic evidence as estimated_decimal_string values so downstream billing/finance surfaces cannot mistake them for exact money ledgers.
  • New authoritative paths should use calculateExactCostLinesV1; the existing number-based tracker remains a compatibility estimate calculator.

Relationships

THIS PACKAGElib.cost-tracking1 import paths

Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.

2 declarations

Declared capabilities

Lib Cost Tracking

API cost tracking and budgeting

Scripts

  • publish:pkgbun publish --tolerate-republish --ignore-scripts --verbose
  • publish:pkg:canarybun publish:pkg --tag canary
  • buildcontractspec-bun-build build
  • build:bundlecontractspec-bun-build transpile
  • build:typescontractspec-bun-build types
  • devcontractspec-bun-build dev
  • cleanrimraf dist .turbo
  • lintbun lint:fix
  • lint:fixnode ../../../../scripts/biome.cjs check --write --unsafe --only=nursery/useSortedClasses . && node ../../../../scripts/biome.cjs check --write .
  • lint:checknode ../../../../scripts/biome.cjs check .
  • testbun test --pass-with-no-tests
  • prebuildcontractspec-bun-build prebuild
  • typechecktsgo --noEmit