floe-guard 0.2.0 → 0.3.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/pricing.ts","../src/cost_map.json","../src/guard.ts","../src/middleware.ts"],"sourcesContent":["/**\n * floe-guard — a local budget guardrail for AI agents.\n *\n * Hard-stops your agent before its next LLM call when it would cross a USD spend\n * ceiling. This package is the Vercel AI SDK (TypeScript) adapter; the Python\n * package `floe-guard` (pip) carries the LiteLLM / CrewAI / LangChain adapters.\n */\n\nexport {\n BudgetGuard,\n type BudgetGuardOptions,\n type BudgetAdvisory,\n} from \"./guard.js\";\nexport {\n FloeGuardError,\n BudgetExceeded,\n UnpriceableModelError,\n} from \"./errors.js\";\nexport {\n budgetGuardMiddleware,\n type BudgetGuardMiddleware,\n} from \"./middleware.js\";\nexport {\n type ManualPrice,\n type PricedModel,\n resolvePrice,\n priceTokens,\n} from \"./pricing.js\";\n\nexport * as pricing from \"./pricing.js\";\n","/**\n * Exceptions for floe-guard.\n *\n * Everything derives from {@link FloeGuardError} (the package-root base) so callers\n * can catch the whole family with a single `catch (e) { if (e instanceof FloeGuardError) ... }`.\n *\n * Mirrors `src/floe_guard/errors.py` in the Python package — message formats are\n * kept byte-for-byte identical so both adapters read the same.\n */\n\n/** Base class for every error raised by floe-guard. */\nexport class FloeGuardError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FloeGuardError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown before an LLM call that would cross the configured spend ceiling.\n *\n * The guard throws this *instead of* letting the next call run, so a runaway loop\n * stops here rather than burning more money.\n */\nexport class BudgetExceeded extends FloeGuardError {\n readonly spentUsd: number;\n readonly limitUsd: number;\n\n constructor(spentUsd: number, limitUsd: number) {\n super(\n `BUDGET EXCEEDED — call blocked (spent $${spentUsd.toFixed(6)} of $${limitUsd.toFixed(6)} ceiling)`,\n );\n this.name = \"BudgetExceeded\";\n this.spentUsd = spentUsd;\n this.limitUsd = limitUsd;\n }\n}\n\n/**\n * Thrown when a model cannot be priced and the guard is fail-closed.\n *\n * We refuse rather than silently accrue $0 — \"we cannot cap what we cannot price\".\n * Pass a manual price (`priceOverrides` or `record(..., { price })`) to make the\n * model enforceable.\n */\nexport class UnpriceableModelError extends FloeGuardError {\n readonly model: string;\n\n constructor(model: string) {\n super(\n `Cannot price model '${model}': not in the bundled cost map and no ` +\n `manual price was given. The guard cannot enforce a budget on spend ` +\n `it cannot measure. Pass a price override to enable enforcement.`,\n );\n this.name = \"UnpriceableModelError\";\n this.model = model;\n }\n}\n","/**\n * Offline token pricing from a vendored LiteLLM cost map.\n *\n * Mirrors `src/floe_guard/pricing.py`: BOTH the input and output per-token prices\n * must be finite numbers, otherwise the model is treated as unpriceable. A\n * half-valid entry would silently undercharge — so we refuse it (fail-closed).\n *\n * No network. The cost map (`cost_map.json`) is a snapshot of LiteLLM's\n * `model_prices_and_context_window.json`; refresh it on a schedule or estimates\n * drift as vendors change prices.\n */\n\nimport costMapJson from \"./cost_map.json\";\n\n/** A user-supplied per-token price, in USD, for a model the map cannot price. */\nexport interface ManualPrice {\n inputCostPerToken: number;\n outputCostPerToken: number;\n}\n\n/** A resolved per-token price plus where it came from. */\nexport interface PricedModel {\n inputCostPerToken: number;\n outputCostPerToken: number;\n source: \"override\" | \"cost_map\";\n}\n\ninterface CostMapEntry {\n input_cost_per_token?: unknown;\n output_cost_per_token?: unknown;\n}\n\nconst COST_MAP = costMapJson as Record<string, CostMapEntry>;\n\n/** Strip an optional `provider/` prefix (LiteLLM convention, e.g. `openai/gpt-4o`). */\nfunction bareModel(model: string): string {\n const m = model.trim();\n const slash = m.lastIndexOf(\"/\");\n return slash === -1 ? m : m.slice(slash + 1);\n}\n\nfunction bothFinite(a: unknown, b: unknown): boolean {\n return (\n typeof a === \"number\" &&\n typeof b === \"number\" &&\n Number.isFinite(a) &&\n Number.isFinite(b)\n );\n}\n\n/**\n * Resolve a model to its per-token price, or `null` if it cannot be priced.\n *\n * Overrides win, then the bundled cost map (looked up by bare name, then the raw\n * field). Fail-closed: both prices must be finite, else `null`.\n */\nexport function resolvePrice(\n model: string,\n overrides?: Record<string, ManualPrice>,\n): PricedModel | null {\n const bare = bareModel(model);\n\n if (overrides) {\n const ov = overrides[bare] ?? overrides[model.trim()];\n if (ov !== undefined) {\n if (bothFinite(ov.inputCostPerToken, ov.outputCostPerToken)) {\n return {\n inputCostPerToken: ov.inputCostPerToken,\n outputCostPerToken: ov.outputCostPerToken,\n source: \"override\",\n };\n }\n return null;\n }\n }\n\n const entry = COST_MAP[bare] ?? COST_MAP[model.trim()];\n if (!entry) return null;\n\n const input = entry.input_cost_per_token;\n const output = entry.output_cost_per_token;\n if (!bothFinite(input, output)) return null;\n\n return {\n inputCostPerToken: input as number,\n outputCostPerToken: output as number,\n source: \"cost_map\",\n };\n}\n\n/** USD cost for token usage. Negative counts are clamped to zero. */\nexport function priceTokens(\n priced: PricedModel,\n promptTokens: number,\n completionTokens: number,\n): number {\n const p = Math.max(0, promptTokens);\n const c = Math.max(0, completionTokens);\n const cost = p * priced.inputCostPerToken + c * priced.outputCostPerToken;\n if (!Number.isFinite(cost)) {\n // Defense-in-depth: resolvePrice already guarantees finite rates.\n throw new Error(\"Non-finite LLM cost — pricing entry is invalid\");\n }\n return Math.max(0, cost);\n}\n","{\n \"chatgpt-4o-latest\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"claude-3-7-sonnet-20250219\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-3-haiku-20240307\": {\n \"input_cost_per_token\": 2.5e-7,\n \"output_cost_per_token\": 0.00000125,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-3-opus-20240229\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-4-opus-20250514\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-4-sonnet-20250514\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-fable-5\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00005,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-haiku-4-5\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000005,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-haiku-4-5-20251001\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000005,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-1\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-1-20250805\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-20250514\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-5\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-5-20251101\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-6\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-6-20260205\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-7\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-7-20260416\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-8\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-20250514\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-5\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-5-20250929\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-6\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo-0125\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo-0613\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo-1106\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4-0613\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4.1-2025-04-14\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000012,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4.1-mini-2025-04-14\": {\n \"input_cost_per_token\": 8e-7,\n \"output_cost_per_token\": 0.0000032,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4.1-nano-2025-04-14\": {\n \"input_cost_per_token\": 2e-7,\n \"output_cost_per_token\": 8e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4o-2024-08-06\": {\n \"input_cost_per_token\": 0.00000375,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4o-2024-11-20\": {\n \"input_cost_per_token\": 0.00000375,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4o-mini-2024-07-18\": {\n \"input_cost_per_token\": 3e-7,\n \"output_cost_per_token\": 0.0000012,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:o4-mini-2025-04-16\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo\": {\n \"input_cost_per_token\": 5e-7,\n \"output_cost_per_token\": 0.0000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo-0125\": {\n \"input_cost_per_token\": 5e-7,\n \"output_cost_per_token\": 0.0000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo-1106\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo-16k\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000004,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-0125-preview\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-0314\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-0613\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-1106-preview\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-turbo\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-turbo-2024-04-09\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-turbo-preview\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-2025-04-14\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-mini\": {\n \"input_cost_per_token\": 4e-7,\n \"output_cost_per_token\": 0.0000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-mini-2025-04-14\": {\n \"input_cost_per_token\": 4e-7,\n \"output_cost_per_token\": 0.0000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-nano\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-nano-2025-04-14\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-2024-05-13\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-2024-08-06\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-2024-11-20\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-audio-preview\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-audio-preview-2024-12-17\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-audio-preview-2025-06-03\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-2024-07-18\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-audio-preview\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-audio-preview-2024-12-17\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-realtime-preview\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-realtime-preview-2024-12-17\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-search-preview\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-search-preview-2025-03-11\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-realtime-preview\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-realtime-preview-2024-12-17\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-realtime-preview-2025-06-03\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-search-preview\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-search-preview-2025-03-11\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-2025-08-07\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-chat\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-chat-latest\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-mini\": {\n \"input_cost_per_token\": 2.5e-7,\n \"output_cost_per_token\": 0.000002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-mini-2025-08-07\": {\n \"input_cost_per_token\": 2.5e-7,\n \"output_cost_per_token\": 0.000002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-nano\": {\n \"input_cost_per_token\": 5e-8,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-nano-2025-08-07\": {\n \"input_cost_per_token\": 5e-8,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-search-api\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-search-api-2025-10-14\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.1\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.1-2025-11-13\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.1-chat-latest\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.2\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.2-2025-12-11\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.2-chat-latest\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.3-chat-latest\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-2026-03-05\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-mini\": {\n \"input_cost_per_token\": 7.5e-7,\n \"output_cost_per_token\": 0.0000045,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-mini-2026-03-17\": {\n \"input_cost_per_token\": 7.5e-7,\n \"output_cost_per_token\": 0.0000045,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-nano\": {\n \"input_cost_per_token\": 2e-7,\n \"output_cost_per_token\": 0.00000125,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-nano-2026-03-17\": {\n \"input_cost_per_token\": 2e-7,\n \"output_cost_per_token\": 0.00000125,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.5\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.5-2026-04-23\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-1.5\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-2025-08-28\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-mini\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-mini-2025-10-06\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-mini-2025-12-15\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-1.5\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-2\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-2025-08-28\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-mini\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-mini-2025-10-06\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-mini-2025-12-15\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"llama-3.1-8b-instant\": {\n \"input_cost_per_token\": 5e-8,\n \"output_cost_per_token\": 8e-8,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"llama-3.3-70b-versatile\": {\n \"input_cost_per_token\": 5.9e-7,\n \"output_cost_per_token\": 7.9e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"meta-llama/llama-4-scout-17b-16e-instruct\": {\n \"input_cost_per_token\": 1.1e-7,\n \"output_cost_per_token\": 3.4e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"o1\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o1-2024-12-17\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3-2025-04-16\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3-mini\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3-mini-2025-01-31\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o4-mini\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o4-mini-2025-04-16\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"qwen/qwen3-32b\": {\n \"input_cost_per_token\": 2.9e-7,\n \"output_cost_per_token\": 5.9e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"text-embedding-3-large\": {\n \"input_cost_per_token\": 1.3e-7,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n },\n \"text-embedding-3-small\": {\n \"input_cost_per_token\": 2e-8,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n },\n \"text-embedding-ada-002\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n },\n \"text-embedding-ada-002-v2\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n }\n}\n","/**\n * The local, in-process budget guard.\n *\n * `BudgetGuard` is a kill-switch that lives in the LLM call path. The contract:\n *\n * 1. Call {@link BudgetGuard.check} BEFORE every LLM call. If the *next* call\n * would cross the ceiling, it throws {@link BudgetExceeded} and the call never\n * runs.\n * 2. Call {@link BudgetGuard.record} AFTER every response, with the token usage.\n * It prices the tokens offline and accrues the USD into a running total.\n *\n * **Concurrency.** `check()` then `record()` is a check-then-act with an `await`\n * in between. Fire several model calls at once (e.g. `Promise.all`) and they all\n * `check()` against the same under-limit total before any `record()` lands, so\n * the ceiling is blown (see issue #18). {@link BudgetGuard.reserve} /\n * {@link BudgetGuard.settle} close that gap: `reserve()` holds the estimated cost\n * in flight (synchronously, before the await), so parallel callers each take\n * their own slice of the ceiling. JS is single-threaded, so an in-flight counter\n * is enough — no lock needed. The middleware uses it; `check`/`record` are\n * unchanged.\n *\n * This is a faithful port of `src/floe_guard/guard.py` — same prediction logic,\n * same epsilon handling, same fail-closed default.\n */\n\nimport { BudgetExceeded, UnpriceableModelError } from \"./errors.js\";\nimport {\n type ManualPrice,\n priceTokens,\n resolvePrice,\n} from \"./pricing.js\";\n\n/** Tolerance for float rounding in the running spend total (well below $0.000001). */\nconst EPS = 1e-12;\n\nexport interface BudgetGuardOptions {\n /** Per-model manual prices for models the bundled cost map cannot price. */\n priceOverrides?: Record<string, ManualPrice>;\n /**\n * When `true` (default), recording an unpriceable model without a manual price\n * warns loudly AND throws {@link UnpriceableModelError}. When `false`, it warns\n * and skips accrual (you have opted into un-enforced spend for that model).\n */\n failClosed?: boolean;\n /**\n * Optional callback invoked with `(spentUsd, limitUsd)` right before\n * {@link BudgetExceeded} is thrown. Defaults to printing the\n * `BUDGET EXCEEDED — call blocked` banner to stderr.\n */\n onBlock?: (spentUsd: number, limitUsd: number) => void;\n /**\n * Utilization (basis points, 0..10000) at which {@link BudgetGuard.advisory}\n * flags `nearLimit` so an agent can taper before the hard-stop. Default 8000.\n */\n nearLimitBps?: number;\n}\n\n/**\n * A context-aware spend signal for the single local budget.\n *\n * Mirrors the core fields of hosted Floe's `X-Floe-Budget-Advisory` header, so\n * agent logic that reads it (taper as you approach the cap, stop at it) ports\n * unchanged to the hosted path. Hosted adds what a local, single-budget guard\n * cannot know: which of several caps is tightest (`scope` across\n * `credit_line | session | task | api | vendor`), cross-vendor reasoning,\n * server-truth balances, and rolling-window reset timing.\n *\n * This is a **soft** signal — the model may ignore it. The hard-stop\n * ({@link BudgetGuard.check}) is what enforces the ceiling; the advisory is\n * upside (let the agent finish on budget rather than be cut off).\n */\nexport interface BudgetAdvisory {\n nearLimit: boolean;\n /** Utilization in basis points, 0..10000 (8500 = 85%). */\n usedBps: number;\n remainingUsd: number;\n limitUsd: number;\n spentUsd: number;\n /** Hosted reports the tightest cap across all scopes; local is always \"local\". */\n scope: \"local\";\n}\n\nexport class BudgetGuard {\n readonly limitUsd: number;\n spentUsd = 0;\n priceOverrides?: Record<string, ManualPrice>;\n failClosed: boolean;\n nearLimitBps: number;\n\n private readonly onBlock: (spentUsd: number, limitUsd: number) => void;\n /** Cost of the most recent priced call, used to predict the next one. */\n private lastCost = 0;\n /** USD held for in-flight calls (reserved, not yet settled). Counts toward the ceiling. */\n private reserved = 0;\n\n /**\n * @param limitUsd the spend ceiling, in USD. `0` blocks the very first call.\n */\n constructor(limitUsd: number, options: BudgetGuardOptions = {}) {\n if (!Number.isFinite(limitUsd) || limitUsd < 0) {\n // NaN/Infinity would make every check() comparison fail-open, silently\n // disabling the guard — reject them up front.\n throw new RangeError(\n `limitUsd must be a finite, non-negative number, got ${limitUsd}`,\n );\n }\n // `=== undefined` (not `??`) so an explicit null is rejected by validation\n // rather than silently defaulting — matches Python, which rejects None.\n const nearLimitBps = options.nearLimitBps === undefined ? 8000 : options.nearLimitBps;\n if (!Number.isInteger(nearLimitBps) || nearLimitBps < 0 || nearLimitBps > 10000) {\n throw new RangeError(\n `nearLimitBps must be an integer in 0..10000, got ${nearLimitBps}`,\n );\n }\n this.limitUsd = limitUsd;\n this.priceOverrides = options.priceOverrides;\n this.failClosed = options.failClosed ?? true;\n this.onBlock = options.onBlock ?? defaultOnBlock;\n this.nearLimitBps = nearLimitBps;\n }\n\n /**\n * Throw {@link BudgetExceeded} if the next call would cross the ceiling.\n *\n * Call this immediately before each LLM request. The \"next call\" is estimated\n * from the last recorded call's cost (override with `estimatedNextCost`); the\n * first call is always allowed unless the ceiling is already met. In-flight\n * reservations count toward the total, so this stays correct alongside\n * {@link BudgetGuard.reserve}.\n *\n * Note: `check` is a non-binding peek. For parallel calls, use `reserve()` /\n * `settle()`, which hold the estimate across the await.\n */\n check(estimatedNextCost?: number): void {\n const rawEstimate =\n estimatedNextCost === undefined ? this.lastCost : estimatedNextCost;\n if (!Number.isFinite(rawEstimate)) {\n // NaN/Infinity would poison the comparisons and fail-open — reject it\n // (parity with the constructor's Number.isFinite guard).\n throw new RangeError(\n `estimatedNextCost must be a finite number, got ${rawEstimate}`,\n );\n }\n const estimate = Math.max(0, rawEstimate);\n const committed = this.spentUsd + this.reserved;\n if (committed > this.limitUsd - EPS || committed + estimate > this.limitUsd + EPS) {\n this.onBlock(this.spentUsd, this.limitUsd);\n throw new BudgetExceeded(this.spentUsd, this.limitUsd);\n }\n }\n\n /**\n * Atomically check the ceiling AND hold the estimated cost in flight.\n *\n * The concurrency-safe enforcement path: call before the request and hold the\n * returned reservation across the await, so parallel callers can't all clear\n * the same stale total. Throws {@link BudgetExceeded} (without reserving) if\n * the reservation would cross the ceiling. Returns the reservation handle to\n * pass to {@link BudgetGuard.settle} (or {@link BudgetGuard.release} on error).\n * `estimatedCost` defaults to the last call's cost.\n */\n reserve(estimatedCost?: number): number {\n const rawEstimate = estimatedCost === undefined ? this.lastCost : estimatedCost;\n if (!Number.isFinite(rawEstimate)) {\n // NaN would poison this.reserved and fail-open the ceiling — reject it.\n throw new RangeError(\n `estimatedCost must be a finite number, got ${rawEstimate}`,\n );\n }\n const estimate = Math.max(0, rawEstimate);\n const committed = this.spentUsd + this.reserved;\n if (committed > this.limitUsd - EPS || committed + estimate > this.limitUsd + EPS) {\n this.onBlock(this.spentUsd, this.limitUsd);\n throw new BudgetExceeded(this.spentUsd, this.limitUsd);\n }\n this.reserved += estimate;\n return estimate;\n }\n\n /**\n * Release a reservation and record the actual cost. `record` is `settle` with\n * no reservation. Returns the USD cost of this call; unpriceable-model handling\n * matches {@link BudgetGuard.record}, and any held reservation is released even\n * on the warn-and-skip path.\n */\n settle(\n model: string,\n promptTokens: number,\n completionTokens: number,\n options: { reserved?: number; price?: ManualPrice } = {},\n ): number {\n const reserved = options.reserved ?? 0;\n // A bad reserved handle would corrupt this.reserved and break the ceiling for\n // OTHER in-flight calls (negative → phantom hold; Infinity → clears all holds).\n if (!Number.isFinite(reserved) || reserved < 0) {\n throw new RangeError(`reserved must be a finite, non-negative number, got ${reserved}`);\n }\n let overrides = this.priceOverrides;\n if (options.price !== undefined) {\n overrides = { ...(overrides ?? {}), [model]: options.price };\n }\n\n const priced = resolvePrice(model, overrides);\n if (priced === null) {\n console.warn(\n `Cannot price model '${model}': not in the bundled cost map and no ` +\n `manual price given. The budget guard cannot enforce a ceiling on ` +\n `spend it cannot measure — pass { price } or set it in priceOverrides.`,\n );\n // Release any held reservation on BOTH paths. Fail-closed must not leak\n // the in-flight hold, or reserved grows permanently and remainingUsd\n // shrinks until reserve() starts blocking everything.\n this.release(reserved);\n if (this.failClosed) {\n throw new UnpriceableModelError(model);\n }\n return 0;\n }\n\n let cost: number;\n try {\n cost = priceTokens(priced, promptTokens, completionTokens);\n } catch (err) {\n // priceTokens can throw (e.g. non-finite costs). Release the in-flight\n // hold before re-throwing so `reserved` doesn't leak and shrink\n // remainingUsd permanently — same fail-safe as the unpriceable path above.\n this.release(reserved);\n throw err;\n }\n if (reserved) {\n this.reserved = Math.max(0, this.reserved - reserved);\n }\n this.spentUsd += cost;\n // Clamp a sub-epsilon float overshoot back to the limit so the running total\n // never reports as having crossed the ceiling by a rounding artifact.\n if (this.spentUsd - this.limitUsd > 0 && this.spentUsd - this.limitUsd < EPS) {\n this.spentUsd = this.limitUsd;\n }\n this.lastCost = cost;\n return cost;\n }\n\n /**\n * Price one response's tokens offline and add the cost to the total.\n *\n * Returns the USD cost of this call. If the model is unpriceable and no `price`\n * is given, behaviour depends on `failClosed`: warn + throw (default), or\n * warn + skip accrual.\n */\n record(\n model: string,\n promptTokens: number,\n completionTokens: number,\n options: { price?: ManualPrice } = {},\n ): number {\n return this.settle(model, promptTokens, completionTokens, {\n reserved: 0,\n price: options.price,\n });\n }\n\n /**\n * Drop an in-flight reservation without recording spend (e.g. the call failed\n * before producing usage). Safe to call with `0`.\n */\n release(reserved: number): void {\n // Validate before the zero-check so a NaN handle throws instead of being\n // silently dropped (a leak); a bad handle corrupts the in-flight tally.\n if (!Number.isFinite(reserved) || reserved < 0) {\n throw new RangeError(`reserved must be a finite, non-negative number, got ${reserved}`);\n }\n if (!reserved) return;\n this.reserved = Math.max(0, this.reserved - reserved);\n }\n\n /** USD left before the ceiling, net of in-flight reservations (never negative). */\n get remainingUsd(): number {\n return Math.max(0, this.limitUsd - this.spentUsd - this.reserved);\n }\n\n /**\n * Context-aware spend advisory for this budget — see {@link BudgetAdvisory}.\n *\n * `nearLimit` flips once utilization reaches `nearLimitBps` (default 80%), so an\n * agent can taper *before* the hard-stop. Advisory only: read it to adapt;\n * {@link BudgetGuard.check} is what enforces the ceiling.\n */\n advisory(): BudgetAdvisory {\n // Floor (not round) so usedBps never over-reports utilization and nearLimit\n // flips exactly when the threshold is reached; the epsilon absorbs float noise\n // and Math.floor matches Python's int() exactly (round() would diverge).\n const usedBps =\n this.limitUsd <= 0\n ? 10000\n : Math.max(0, Math.min(10000, Math.floor((this.spentUsd / this.limitUsd) * 10000 + 1e-9)));\n return {\n nearLimit: usedBps >= this.nearLimitBps,\n usedBps,\n // Settled budget: limit minus accrued spend, deliberately NOT net of\n // in-flight reservations. Unlike the remainingUsd getter (which subtracts\n // `reserved`), the advisory is a soft utilization signal about money already\n // spent, while the getter reports what a new call can still claim.\n remainingUsd: Math.max(0, this.limitUsd - this.spentUsd),\n limitUsd: this.limitUsd,\n spentUsd: this.spentUsd,\n scope: \"local\",\n };\n }\n}\n\nfunction defaultOnBlock(spentUsd: number, limitUsd: number): void {\n console.error(\n \"BUDGET EXCEEDED — call blocked\\n\" +\n ` spent so far: $${spentUsd.toFixed(6)} | ceiling: $${limitUsd.toFixed(6)}\\n` +\n \" The next call would cross your budget; floe-guard stopped your agent \" +\n \"before it ran.\",\n );\n}\n","/**\n * Vercel AI SDK middleware that enforces a {@link BudgetGuard} in the call path.\n *\n * This is the TypeScript counterpart to the Python framework adapters. The AI SDK\n * is TypeScript-only, so it ships as its own npm package.\n *\n * Works with BOTH `ai@4` (`LanguageModelV1Middleware`) and `ai@5`\n * (`LanguageModelV2Middleware`). The two majors renamed the middleware type and\n * the usage fields (`promptTokens`/`completionTokens` → `inputTokens`/\n * `outputTokens`), so this module deliberately imports nothing from `ai`: the\n * middleware is typed structurally against the surface both majors share, and\n * usage is read from whichever field pair the installed SDK reports.\n *\n * - `wrapGenerate({ doGenerate, model })` — we `reserve()` (throws to hard-stop)\n * BEFORE calling `doGenerate()`, hold the reservation across the await, then\n * `settle()` from `result.usage`.\n * - `wrapStream({ doStream, model })` — we `reserve()` BEFORE `doStream()`, then\n * `settle()` from the `finish` part as the stream drains.\n *\n * Reserving before the await is what makes parallel calls (`Promise.all` over\n * several generations) honour the ceiling: each holds its slice instead of all\n * reading the same stale total (issue #18). The reservation is released if the\n * call throws, or if a stream ends without reporting usage.\n *\n * The model id used for pricing comes from `model.modelId`.\n */\n\nimport type { BudgetGuard } from \"./guard.js\";\n\n/**\n * The middleware call surface shared by `ai@4` and `ai@5`. Both majors invoke\n * `wrapGenerate`/`wrapStream` with an options object carrying these members\n * (plus richer `model` fields we don't read). `doGenerate`/`doStream` are\n * declared optional so every 4.x/5.x minor's options type stays assignable —\n * the SDK always provides the one each hook actually calls.\n */\ninterface MiddlewareCallOptions {\n doGenerate?: () => PromiseLike<any>;\n doStream?: () => PromiseLike<any>;\n model: { modelId: string };\n params?: unknown;\n}\n\n/**\n * Structural stand-in for `LanguageModelV1Middleware` (ai@4) and\n * `LanguageModelV2Middleware` (ai@5) — assignable to the `middleware` option of\n * `wrapLanguageModel` on either major.\n */\nexport interface BudgetGuardMiddleware {\n wrapGenerate: (options: MiddlewareCallOptions) => Promise<any>;\n wrapStream: (options: MiddlewareCallOptions) => Promise<any>;\n}\n\n/**\n * Read prompt/completion token counts from an ai@4 usage object\n * (`promptTokens`/`completionTokens`) or an ai@5 one (`inputTokens`/\n * `outputTokens`). Throws when either count is missing or non-numeric: the guard\n * cannot meter spend it cannot see, and treating it as $0 would fail open.\n */\nfunction usageTokens(\n modelId: string,\n usage: unknown,\n): { promptTokens: number; completionTokens: number } {\n const u = usage as\n | {\n promptTokens?: unknown;\n completionTokens?: unknown;\n inputTokens?: unknown;\n outputTokens?: unknown;\n }\n | null\n | undefined;\n const promptTokens = u?.promptTokens ?? u?.inputTokens;\n const completionTokens = u?.completionTokens ?? u?.outputTokens;\n if (typeof promptTokens !== \"number\" || typeof completionTokens !== \"number\") {\n throw new Error(\n `Model '${modelId}' reported no token usage — the budget guard cannot ` +\n `meter spend it cannot see, so this call is rejected rather than ` +\n `treated as free.`,\n );\n }\n return { promptTokens, completionTokens };\n}\n\n/**\n * Build a budget-guard middleware that hard-stops the model before a call\n * crosses the guard's USD ceiling, and records priced token usage after.\n * Compatible with `wrapLanguageModel` from both `ai@4` and `ai@5`.\n *\n * @example\n * import { wrapLanguageModel } from \"ai\";\n * import { openai } from \"@ai-sdk/openai\";\n * import { BudgetGuard, budgetGuardMiddleware } from \"floe-guard\";\n *\n * const guard = new BudgetGuard(5.00);\n * const model = wrapLanguageModel({\n * model: openai(\"gpt-4o\"),\n * middleware: budgetGuardMiddleware(guard),\n * });\n */\nexport function budgetGuardMiddleware(guard: BudgetGuard): BudgetGuardMiddleware {\n return {\n async wrapGenerate({ doGenerate, model }) {\n const reserved = guard.reserve(); // throws BudgetExceeded before the call runs\n let result: any;\n try {\n result = await doGenerate!();\n } catch (err) {\n guard.release(reserved); // the call failed before settle() took ownership\n throw err;\n }\n // From here settle() OWNS the reservation: it releases the hold on its own\n // throw (unpriceable / non-finite cost) and consumes it on success. Releasing\n // again would double-subtract and clear a concurrent call's in-flight hold.\n let handled = false;\n try {\n const { promptTokens, completionTokens } = usageTokens(\n model.modelId,\n result?.usage,\n );\n handled = true;\n guard.settle(model.modelId, promptTokens, completionTokens, { reserved });\n return result;\n } catch (err) {\n if (!handled) guard.release(reserved); // failed reading usage, before settle()\n throw err;\n }\n },\n\n async wrapStream({ doStream, model }) {\n const reserved = guard.reserve(); // throws BudgetExceeded before the stream starts\n let streamResult: any;\n try {\n streamResult = await doStream!();\n } catch (err) {\n guard.release(reserved); // the call failed before settle() took ownership\n throw err;\n }\n const { stream, ...rest } = streamResult as {\n stream: ReadableStream<any>;\n } & Record<string, unknown>;\n\n // `handled` flips once the reservation is disposed — settled on the finish\n // part, or released exactly once if the stream produced no usage (flush) or\n // ended early via error/cancellation (cancel). settle() owns disposal once\n // called, so nothing else may release after `handled` is set, or we'd\n // double-subtract and clear a concurrent call's hold.\n let handled = false;\n const guarded = stream.pipeThrough(\n new TransformStream<any, any>({\n transform(chunk, controller) {\n if (chunk?.type === \"finish\" && !handled) {\n try {\n const { promptTokens, completionTokens } = usageTokens(\n model.modelId,\n chunk.usage,\n );\n handled = true;\n guard.settle(model.modelId, promptTokens, completionTokens, { reserved });\n } catch (err) {\n // Release only if we never reached settle() (e.g. usage missing).\n // If settle() itself threw, it already released its own hold.\n if (!handled) {\n handled = true;\n guard.release(reserved);\n }\n throw err;\n }\n }\n controller.enqueue(chunk);\n },\n flush() {\n // Clean close with no finish/usage part — free the held budget.\n if (!handled) {\n handled = true;\n guard.release(reserved);\n }\n },\n cancel() {\n // Upstream error or consumer cancellation: flush() does not run here\n // (Web Streams: flush and cancel are mutually exclusive), so release\n // the still-held reservation.\n if (!handled) {\n handled = true;\n guard.release(reserved);\n }\n },\n // `cancel` is valid per the Streams spec and supported in Node 18+, but\n // TS's Transformer lib type lags and omits it — cast to keep the type check.\n } as Transformer<any, any>),\n );\n\n return { stream: guarded, ...rest };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAQO,IAAM,iBAAN,cAA6B,eAAe;AAAA,EACxC;AAAA,EACA;AAAA,EAET,YAAY,UAAkB,UAAkB;AAC9C;AAAA,MACE,+CAA0C,SAAS,QAAQ,CAAC,CAAC,QAAQ,SA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M;AAAA,cACR;AAAA,YACF;AACA,uBAAW,QAAQ,KAAK;AAAA,UAC1B;AAAA,UACA,QAAQ;AAEN,gBAAI,CAAC,SAAS;AACZ,wBAAU;AACV,oBAAM,QAAQ,QAAQ;AAAA,YACxB;AAAA,UACF;AAAA,UACA,SAAS;AAIP,gBAAI,CAAC,SAAS;AACZ,wBAAU;AACV,oBAAM,QAAQ,QAAQ;AAAA,YACxB;AAAA,UACF;AAAA;AAAA;AAAA,QAGF,CAA0B;AAAA,MAC5B;AAEA,aAAO,EAAE,QAAQ,SAAS,GAAG,KAAK;AAAA,IACpC;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/pricing.ts","../src/cost_map.json","../src/guard.ts","../src/middleware.ts"],"sourcesContent":["/**\n * floe-guard — a local budget guardrail for AI agents.\n *\n * Hard-stops your agent before its next LLM call when it would cross a USD spend\n * ceiling. This package is the Vercel AI SDK (TypeScript) adapter; the Python\n * package `floe-guard` (pip) carries the LiteLLM / CrewAI / LangChain adapters.\n */\n\nexport {\n BudgetGuard,\n type BudgetGuardOptions,\n type BudgetAdvisory,\n type SpendEvent,\n} from \"./guard.js\";\nexport {\n FloeGuardError,\n BudgetExceeded,\n UnpriceableModelError,\n} from \"./errors.js\";\nexport {\n budgetGuardMiddleware,\n type BudgetGuardMiddleware,\n} from \"./middleware.js\";\nexport {\n type ManualPrice,\n type PricedModel,\n resolvePrice,\n priceTokens,\n} from \"./pricing.js\";\n\nexport * as pricing from \"./pricing.js\";\n","/**\n * Exceptions for floe-guard.\n *\n * Everything derives from {@link FloeGuardError} (the package-root base) so callers\n * can catch the whole family with a single `catch (e) { if (e instanceof FloeGuardError) ... }`.\n *\n * Mirrors `src/floe_guard/errors.py` in the Python package — message formats are\n * kept byte-for-byte identical so both adapters read the same.\n */\n\n/** Base class for every error raised by floe-guard. */\nexport class FloeGuardError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FloeGuardError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown before an LLM call that would cross the configured spend ceiling.\n *\n * The guard throws this *instead of* letting the next call run, so a runaway loop\n * stops here rather than burning more money.\n */\nexport class BudgetExceeded extends FloeGuardError {\n readonly spentUsd: number;\n readonly limitUsd: number;\n\n constructor(spentUsd: number, limitUsd: number) {\n super(\n `BUDGET EXCEEDED — call blocked (spent $${spentUsd.toFixed(6)} of $${limitUsd.toFixed(6)} ceiling)`,\n );\n this.name = \"BudgetExceeded\";\n this.spentUsd = spentUsd;\n this.limitUsd = limitUsd;\n }\n}\n\n/**\n * Thrown when a model cannot be priced and the guard is fail-closed.\n *\n * We refuse rather than silently accrue $0 — \"we cannot cap what we cannot price\".\n * Pass a manual price (`priceOverrides` or `record(..., { price })`) to make the\n * model enforceable.\n */\nexport class UnpriceableModelError extends FloeGuardError {\n readonly model: string;\n\n constructor(model: string) {\n super(\n `Cannot price model '${model}': not in the bundled cost map and no ` +\n `manual price was given. The guard cannot enforce a budget on spend ` +\n `it cannot measure. Pass a price override to enable enforcement.`,\n );\n this.name = \"UnpriceableModelError\";\n this.model = model;\n }\n}\n","/**\n * Offline token pricing from a vendored LiteLLM cost map.\n *\n * Mirrors `src/floe_guard/pricing.py`: BOTH the input and output per-token prices\n * must be finite numbers, otherwise the model is treated as unpriceable. A\n * half-valid entry would silently undercharge — so we refuse it (fail-closed).\n *\n * No network. The cost map (`cost_map.json`) is a snapshot of LiteLLM's\n * `model_prices_and_context_window.json`; refresh it on a schedule or estimates\n * drift as vendors change prices.\n */\n\nimport costMapJson from \"./cost_map.json\";\n\n/** A user-supplied per-token price, in USD, for a model the map cannot price. */\nexport interface ManualPrice {\n inputCostPerToken: number;\n outputCostPerToken: number;\n}\n\n/** A resolved per-token price plus where it came from. */\nexport interface PricedModel {\n inputCostPerToken: number;\n outputCostPerToken: number;\n source: \"override\" | \"cost_map\";\n}\n\ninterface CostMapEntry {\n input_cost_per_token?: unknown;\n output_cost_per_token?: unknown;\n}\n\nconst COST_MAP = costMapJson as Record<string, CostMapEntry>;\n\n/**\n * The one `<provider>/` prefix that is safe to strip: the remainder of a\n * `groq/…` id is the ChatGroq id the map vendors (e.g. `groq/qwen/qwen3-32b` →\n * `qwen/qwen3-32b`). `openai/` and `anthropic/` are deliberately excluded:\n * their own model ids never contain slashes (single-segment remainders are\n * already covered by the bare-last-segment fallback), so a multi-segment\n * remainder under those prefixes is some OTHER vendor's model behind an\n * OpenAI-compatible endpoint (vLLM, OpenRouter, …) — bridging it into a\n * Groq-priced key would under-meter. Unknown prefixes fail closed the same way.\n */\nconst PROVIDER_PREFIXES = new Set([\"groq\"]);\n\n/**\n * A trailing dated-snapshot suffix: Anthropic's `-20250929` or OpenAI's\n * `-2024-08-06`. Vendors resolve alias ids to dated snapshots in responses, so a\n * snapshot the map doesn't list yet prices at its alias entry (same model, same\n * rate) instead of failing closed. (`\\d` is ASCII-only in JS; the Python regex\n * uses re.ASCII to match.)\n */\nconst DATE_SUFFIX = /-(?:\\d{8}|\\d{4}-\\d{2}-\\d{2})$/;\n\n/**\n * Lookup keys for a model id in two specificity groups, deduplicated.\n *\n * Group 1 (exact): the raw id, the id with a known `provider/` first segment\n * stripped, the bare last segment. Group 2 (date-stripped): the same forms\n * with a trailing dated-snapshot suffix removed. Kept separate so a\n * less-specific date-stripped key (in overrides OR the map) can never shadow\n * an exact dated entry — e.g. an alias override must not absorb a snapshot\n * the map prices differently.\n */\nfunction candidateGroups(model: string): [string[], string[]] {\n const m = model.trim();\n const base = [m];\n const firstSlash = m.indexOf(\"/\");\n if (firstSlash !== -1 && PROVIDER_PREFIXES.has(m.slice(0, firstSlash))) {\n base.push(m.slice(firstSlash + 1));\n }\n const lastSlash = m.lastIndexOf(\"/\");\n if (lastSlash !== -1) {\n base.push(m.slice(lastSlash + 1));\n }\n const exact: string[] = [];\n for (const cand of base) {\n if (cand && !exact.includes(cand)) exact.push(cand);\n }\n const stripped: string[] = [];\n for (const cand of exact) {\n const c = cand.replace(DATE_SUFFIX, \"\");\n if (c && !exact.includes(c) && !stripped.includes(c)) stripped.push(c);\n }\n return [exact, stripped];\n}\n\nfunction bothFinite(a: unknown, b: unknown): boolean {\n return (\n typeof a === \"number\" &&\n typeof b === \"number\" &&\n Number.isFinite(a) &&\n Number.isFinite(b)\n );\n}\n\n/**\n * Resolve a model to its per-token price, or `null` if it cannot be priced.\n *\n * Per specificity group (exact forms first, date-stripped fallbacks second):\n * overrides win, then the bundled cost map. Fail-closed: the first matching\n * entry must have finite prices, else `null`.\n */\nexport function resolvePrice(\n model: string,\n overrides?: Record<string, ManualPrice>,\n): PricedModel | null {\n for (const cands of candidateGroups(model)) {\n if (overrides) {\n for (const cand of cands) {\n // Own-property check so a key like \"constructor\" can't pull a function\n // off Object.prototype and be treated as a price entry.\n const ov = Object.prototype.hasOwnProperty.call(overrides, cand)\n ? overrides[cand]\n : undefined;\n if (ov !== undefined) {\n if (bothFinite(ov.inputCostPerToken, ov.outputCostPerToken)) {\n return {\n inputCostPerToken: ov.inputCostPerToken,\n outputCostPerToken: ov.outputCostPerToken,\n source: \"override\",\n };\n }\n return null;\n }\n }\n }\n\n for (const cand of cands) {\n const entry = Object.prototype.hasOwnProperty.call(COST_MAP, cand)\n ? COST_MAP[cand]\n : undefined;\n if (!entry) continue;\n\n const input = entry.input_cost_per_token;\n const output = entry.output_cost_per_token;\n if (!bothFinite(input, output)) return null;\n\n return {\n inputCostPerToken: input as number,\n outputCostPerToken: output as number,\n source: \"cost_map\",\n };\n }\n }\n return null;\n}\n\n/** USD cost for token usage. Negative counts are clamped to zero. */\nexport function priceTokens(\n priced: PricedModel,\n promptTokens: number,\n completionTokens: number,\n): number {\n const p = Math.max(0, promptTokens);\n const c = Math.max(0, completionTokens);\n const cost = p * priced.inputCostPerToken + c * priced.outputCostPerToken;\n if (!Number.isFinite(cost)) {\n // Defense-in-depth: resolvePrice already guarantees finite rates.\n throw new Error(\"Non-finite LLM cost — pricing entry is invalid\");\n }\n return Math.max(0, cost);\n}\n","{\n \"chatgpt-4o-latest\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"claude-3-7-sonnet-20250219\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-3-haiku-20240307\": {\n \"input_cost_per_token\": 2.5e-7,\n \"output_cost_per_token\": 0.00000125,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-3-opus-20240229\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-4-opus-20250514\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-4-sonnet-20250514\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-fable-5\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00005,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-haiku-4-5\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000005,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-haiku-4-5-20251001\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000005,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-1\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-1-20250805\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-20250514\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.000075,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-5\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-5-20251101\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-6\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-6-20260205\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-7\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-7-20260416\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-opus-4-8\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000025,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-20250514\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-5\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-5-20250929\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-4-6\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"claude-sonnet-5\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"anthropic\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo-0125\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo-0613\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-3.5-turbo-1106\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4-0613\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4.1-2025-04-14\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000012,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4.1-mini-2025-04-14\": {\n \"input_cost_per_token\": 8e-7,\n \"output_cost_per_token\": 0.0000032,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4.1-nano-2025-04-14\": {\n \"input_cost_per_token\": 2e-7,\n \"output_cost_per_token\": 8e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4o-2024-08-06\": {\n \"input_cost_per_token\": 0.00000375,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4o-2024-11-20\": {\n \"input_cost_per_token\": 0.00000375,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:gpt-4o-mini-2024-07-18\": {\n \"input_cost_per_token\": 3e-7,\n \"output_cost_per_token\": 0.0000012,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"ft:o4-mini-2025-04-16\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo\": {\n \"input_cost_per_token\": 5e-7,\n \"output_cost_per_token\": 0.0000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo-0125\": {\n \"input_cost_per_token\": 5e-7,\n \"output_cost_per_token\": 0.0000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo-1106\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-3.5-turbo-16k\": {\n \"input_cost_per_token\": 0.000003,\n \"output_cost_per_token\": 0.000004,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-0125-preview\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-0314\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-0613\": {\n \"input_cost_per_token\": 0.00003,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-1106-preview\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-turbo\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-turbo-2024-04-09\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4-turbo-preview\": {\n \"input_cost_per_token\": 0.00001,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-2025-04-14\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-mini\": {\n \"input_cost_per_token\": 4e-7,\n \"output_cost_per_token\": 0.0000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-mini-2025-04-14\": {\n \"input_cost_per_token\": 4e-7,\n \"output_cost_per_token\": 0.0000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-nano\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4.1-nano-2025-04-14\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-2024-05-13\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-2024-08-06\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-2024-11-20\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-audio-preview\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-audio-preview-2024-12-17\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-audio-preview-2025-06-03\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-2024-07-18\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-audio-preview\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-audio-preview-2024-12-17\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-realtime-preview\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-realtime-preview-2024-12-17\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-search-preview\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-mini-search-preview-2025-03-11\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-realtime-preview\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-realtime-preview-2024-12-17\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-realtime-preview-2025-06-03\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-search-preview\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-4o-search-preview-2025-03-11\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-2025-08-07\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-chat\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-chat-latest\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-mini\": {\n \"input_cost_per_token\": 2.5e-7,\n \"output_cost_per_token\": 0.000002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-mini-2025-08-07\": {\n \"input_cost_per_token\": 2.5e-7,\n \"output_cost_per_token\": 0.000002,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-nano\": {\n \"input_cost_per_token\": 5e-8,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-nano-2025-08-07\": {\n \"input_cost_per_token\": 5e-8,\n \"output_cost_per_token\": 4e-7,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-search-api\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5-search-api-2025-10-14\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.1\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.1-2025-11-13\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.1-chat-latest\": {\n \"input_cost_per_token\": 0.00000125,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.2\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.2-2025-12-11\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.2-chat-latest\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.3-chat-latest\": {\n \"input_cost_per_token\": 0.00000175,\n \"output_cost_per_token\": 0.000014,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-2026-03-05\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-mini\": {\n \"input_cost_per_token\": 7.5e-7,\n \"output_cost_per_token\": 0.0000045,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-mini-2026-03-17\": {\n \"input_cost_per_token\": 7.5e-7,\n \"output_cost_per_token\": 0.0000045,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-nano\": {\n \"input_cost_per_token\": 2e-7,\n \"output_cost_per_token\": 0.00000125,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.4-nano-2026-03-17\": {\n \"input_cost_per_token\": 2e-7,\n \"output_cost_per_token\": 0.00000125,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.5\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.5-2026-04-23\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.6\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.6-luna\": {\n \"input_cost_per_token\": 0.000001,\n \"output_cost_per_token\": 0.000006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.6-sol\": {\n \"input_cost_per_token\": 0.000005,\n \"output_cost_per_token\": 0.00003,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-5.6-terra\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.000015,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-1.5\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-2025-08-28\": {\n \"input_cost_per_token\": 0.0000025,\n \"output_cost_per_token\": 0.00001,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-mini\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-mini-2025-10-06\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-audio-mini-2025-12-15\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-1.5\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-2\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-2.1\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-2.1-mini\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-2025-08-28\": {\n \"input_cost_per_token\": 0.000004,\n \"output_cost_per_token\": 0.000016,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-mini\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-mini-2025-10-06\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"gpt-realtime-mini-2025-12-15\": {\n \"input_cost_per_token\": 6e-7,\n \"output_cost_per_token\": 0.0000024,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"llama-3.1-8b-instant\": {\n \"input_cost_per_token\": 5e-8,\n \"output_cost_per_token\": 8e-8,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"llama-3.3-70b-versatile\": {\n \"input_cost_per_token\": 5.9e-7,\n \"output_cost_per_token\": 7.9e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"meta-llama/llama-4-scout-17b-16e-instruct\": {\n \"input_cost_per_token\": 1.1e-7,\n \"output_cost_per_token\": 3.4e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"o1\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o1-2024-12-17\": {\n \"input_cost_per_token\": 0.000015,\n \"output_cost_per_token\": 0.00006,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3-2025-04-16\": {\n \"input_cost_per_token\": 0.000002,\n \"output_cost_per_token\": 0.000008,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3-mini\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o3-mini-2025-01-31\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o4-mini\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"o4-mini-2025-04-16\": {\n \"input_cost_per_token\": 0.0000011,\n \"output_cost_per_token\": 0.0000044,\n \"litellm_provider\": \"openai\",\n \"mode\": \"chat\"\n },\n \"openai/gpt-oss-120b\": {\n \"input_cost_per_token\": 1.5e-7,\n \"output_cost_per_token\": 6e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"openai/gpt-oss-20b\": {\n \"input_cost_per_token\": 7.5e-8,\n \"output_cost_per_token\": 3e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"openai/gpt-oss-safeguard-20b\": {\n \"input_cost_per_token\": 7.5e-8,\n \"output_cost_per_token\": 3e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"qwen/qwen3-32b\": {\n \"input_cost_per_token\": 2.9e-7,\n \"output_cost_per_token\": 5.9e-7,\n \"litellm_provider\": \"groq\",\n \"mode\": \"chat\"\n },\n \"text-embedding-3-large\": {\n \"input_cost_per_token\": 1.3e-7,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n },\n \"text-embedding-3-small\": {\n \"input_cost_per_token\": 2e-8,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n },\n \"text-embedding-ada-002\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n },\n \"text-embedding-ada-002-v2\": {\n \"input_cost_per_token\": 1e-7,\n \"output_cost_per_token\": 0,\n \"litellm_provider\": \"openai\",\n \"mode\": \"embedding\"\n }\n}\n","/**\n * The local, in-process budget guard.\n *\n * `BudgetGuard` is a kill-switch that lives in the LLM call path. The contract:\n *\n * 1. Call {@link BudgetGuard.check} BEFORE every LLM call. If the *next* call\n * would cross the ceiling, it throws {@link BudgetExceeded} and the call never\n * runs.\n * 2. Call {@link BudgetGuard.record} AFTER every response, with the token usage.\n * It prices the tokens offline and accrues the USD into a running total.\n *\n * **Concurrency.** `check()` then `record()` is a check-then-act with an `await`\n * in between. Fire several model calls at once (e.g. `Promise.all`) and they all\n * `check()` against the same under-limit total before any `record()` lands, so\n * the ceiling is blown (see issue #18). {@link BudgetGuard.reserve} /\n * {@link BudgetGuard.settle} close that gap: `reserve()` holds the estimated cost\n * in flight (synchronously, before the await), so parallel callers each take\n * their own slice of the ceiling. JS is single-threaded, so an in-flight counter\n * is enough — no lock needed. The middleware uses it; `check`/`record` are\n * unchanged.\n *\n * This is a faithful port of `src/floe_guard/guard.py` — same prediction logic,\n * same epsilon handling, same fail-closed default.\n */\n\nimport { BudgetExceeded, UnpriceableModelError } from \"./errors.js\";\nimport {\n type ManualPrice,\n priceTokens,\n resolvePrice,\n} from \"./pricing.js\";\n\n/** Tolerance for float rounding in the running spend total (well below $0.000001). */\nconst EPS = 1e-12;\n\n/**\n * One priced spend event in the guard's per-call ledger.\n *\n * Every {@link BudgetGuard.record} / {@link BudgetGuard.settle} /\n * {@link BudgetGuard.recordTool} that accrues spend appends exactly one event, so\n * the ledger's costs sum to `spentUsd` (unless a `maxLogEvents` ring buffer has\n * evicted old events). The schema is identical in the Python\n * package (`SpendEvent` in `src/floe_guard/guard.py`) and\n * {@link BudgetGuard.exportLog} serialises it with the same snake_case keys in\n * both languages, so every agent emits the same shape regardless of stack.\n */\nexport interface SpendEvent {\n /** Unix epoch seconds (UTC). */\n readonly timestamp: number;\n readonly kind: \"llm\" | \"tool\";\n readonly modelOrTool: string;\n /** `null` for tool events. */\n readonly promptTokens: number | null;\n /** `null` for tool events. */\n readonly completionTokens: number | null;\n readonly costUsd: number;\n /** Caller-supplied tag (agent/task name). */\n readonly label?: string;\n /** The reservation settled by this call, if any. */\n readonly reserved?: number;\n}\n\nexport interface BudgetGuardOptions {\n /** Per-model manual prices for models the bundled cost map cannot price. */\n priceOverrides?: Record<string, ManualPrice>;\n /**\n * When `true` (default), recording an unpriceable model without a manual price\n * warns loudly AND throws {@link UnpriceableModelError}. When `false`, it warns\n * and skips accrual (you have opted into un-enforced spend for that model).\n */\n failClosed?: boolean;\n /**\n * Optional callback invoked with `(spentUsd, limitUsd)` right before\n * {@link BudgetExceeded} is thrown. Defaults to printing the\n * `BUDGET EXCEEDED — call blocked` banner to stderr.\n */\n onBlock?: (spentUsd: number, limitUsd: number) => void;\n /**\n * Utilization (basis points, 0..10000) at which {@link BudgetGuard.advisory}\n * flags `nearLimit` so an agent can taper before the hard-stop. Default 8000.\n */\n nearLimitBps?: number;\n /**\n * Optional cap on the per-call spend ledger ({@link BudgetGuard.spendLog}).\n * When set, the ledger is a ring buffer keeping the most recent N events so a\n * long-running agent's memory stays bounded; the running totals are\n * unaffected. Default: keep every event.\n */\n maxLogEvents?: number;\n}\n\n/**\n * A context-aware spend signal for the single local budget.\n *\n * Mirrors the core fields of hosted Floe's `X-Floe-Budget-Advisory` header, so\n * agent logic that reads it (taper as you approach the cap, stop at it) ports\n * unchanged to the hosted path. Hosted adds what a local, single-budget guard\n * cannot know: which of several caps is tightest (`scope` across\n * `credit_line | session | task | api | vendor`), cross-vendor reasoning,\n * server-truth balances, and rolling-window reset timing.\n *\n * This is a **soft** signal — the model may ignore it. The hard-stop\n * ({@link BudgetGuard.check}) is what enforces the ceiling; the advisory is\n * upside (let the agent finish on budget rather than be cut off).\n */\nexport interface BudgetAdvisory {\n nearLimit: boolean;\n /** Utilization in basis points, 0..10000 (8500 = 85%). */\n usedBps: number;\n remainingUsd: number;\n limitUsd: number;\n spentUsd: number;\n /** Hosted reports the tightest cap across all scopes; local is always \"local\". */\n scope: \"local\";\n}\n\nexport class BudgetGuard {\n readonly limitUsd: number;\n spentUsd = 0;\n priceOverrides?: Record<string, ManualPrice>;\n failClosed: boolean;\n nearLimitBps: number;\n\n private readonly onBlock: (spentUsd: number, limitUsd: number) => void;\n /** Cost of the most recent priced call, used to predict the next one. */\n private lastCost = 0;\n /** USD held for in-flight calls (reserved, not yet settled). Counts toward the ceiling. */\n private reserved = 0;\n /** Per-call ledger, oldest first; a ring buffer when maxLogEvents is set. */\n private readonly spendEvents: SpendEvent[] = [];\n private readonly maxLogEvents?: number;\n\n /**\n * @param limitUsd the spend ceiling, in USD. `0` blocks the very first call.\n */\n constructor(limitUsd: number, options: BudgetGuardOptions = {}) {\n if (!Number.isFinite(limitUsd) || limitUsd < 0) {\n // NaN/Infinity would make every check() comparison fail-open, silently\n // disabling the guard — reject them up front.\n throw new RangeError(\n `limitUsd must be a finite, non-negative number, got ${limitUsd}`,\n );\n }\n // `=== undefined` (not `??`) so an explicit null is rejected by validation\n // rather than silently defaulting — matches Python, which rejects None.\n const nearLimitBps = options.nearLimitBps === undefined ? 8000 : options.nearLimitBps;\n if (!Number.isInteger(nearLimitBps) || nearLimitBps < 0 || nearLimitBps > 10000) {\n throw new RangeError(\n `nearLimitBps must be an integer in 0..10000, got ${nearLimitBps}`,\n );\n }\n if (\n options.maxLogEvents !== undefined &&\n (!Number.isInteger(options.maxLogEvents) || options.maxLogEvents < 0)\n ) {\n throw new RangeError(\n `maxLogEvents must be a non-negative integer, got ${options.maxLogEvents}`,\n );\n }\n this.limitUsd = limitUsd;\n this.maxLogEvents = options.maxLogEvents;\n this.priceOverrides = options.priceOverrides;\n this.failClosed = options.failClosed ?? true;\n this.onBlock = options.onBlock ?? defaultOnBlock;\n this.nearLimitBps = nearLimitBps;\n }\n\n /**\n * Throw {@link BudgetExceeded} if the next call would cross the ceiling.\n *\n * Call this immediately before each LLM request. The \"next call\" is estimated\n * from the last recorded call's cost (override with `estimatedNextCost`); the\n * first call is always allowed unless the ceiling is already met. In-flight\n * reservations count toward the total, so this stays correct alongside\n * {@link BudgetGuard.reserve}.\n *\n * Note: `check` is a non-binding peek. For parallel calls, use `reserve()` /\n * `settle()`, which hold the estimate across the await.\n */\n check(estimatedNextCost?: number): void {\n const rawEstimate =\n estimatedNextCost === undefined ? this.lastCost : estimatedNextCost;\n if (!Number.isFinite(rawEstimate)) {\n // NaN/Infinity would poison the comparisons and fail-open — reject it\n // (parity with the constructor's Number.isFinite guard).\n throw new RangeError(\n `estimatedNextCost must be a finite number, got ${rawEstimate}`,\n );\n }\n const estimate = Math.max(0, rawEstimate);\n const committed = this.spentUsd + this.reserved;\n if (committed > this.limitUsd - EPS || committed + estimate > this.limitUsd + EPS) {\n this.onBlock(this.spentUsd, this.limitUsd);\n throw new BudgetExceeded(this.spentUsd, this.limitUsd);\n }\n }\n\n /**\n * Atomically check the ceiling AND hold the estimated cost in flight.\n *\n * The concurrency-safe enforcement path: call before the request and hold the\n * returned reservation across the await, so parallel callers can't all clear\n * the same stale total. Throws {@link BudgetExceeded} (without reserving) if\n * the reservation would cross the ceiling. Returns the reservation handle to\n * pass to {@link BudgetGuard.settle} (or {@link BudgetGuard.release} on error).\n * `estimatedCost` defaults to the last call's cost.\n */\n reserve(estimatedCost?: number): number {\n const rawEstimate = estimatedCost === undefined ? this.lastCost : estimatedCost;\n if (!Number.isFinite(rawEstimate)) {\n // NaN would poison this.reserved and fail-open the ceiling — reject it.\n throw new RangeError(\n `estimatedCost must be a finite number, got ${rawEstimate}`,\n );\n }\n const estimate = Math.max(0, rawEstimate);\n const committed = this.spentUsd + this.reserved;\n if (committed > this.limitUsd - EPS || committed + estimate > this.limitUsd + EPS) {\n this.onBlock(this.spentUsd, this.limitUsd);\n throw new BudgetExceeded(this.spentUsd, this.limitUsd);\n }\n this.reserved += estimate;\n return estimate;\n }\n\n /**\n * Release a reservation and record the actual cost. `record` is `settle` with\n * no reservation. Returns the USD cost of this call; unpriceable-model handling\n * matches {@link BudgetGuard.record}, and any held reservation is released even\n * on the warn-and-skip path. A priced call appends one {@link SpendEvent} to\n * {@link BudgetGuard.spendLog} (`label` tags it, e.g. with an agent/task name);\n * the warn-and-skip path accrues nothing and logs nothing, so the ledger stays\n * in lockstep with `spentUsd`.\n */\n settle(\n model: string,\n promptTokens: number,\n completionTokens: number,\n options: { reserved?: number; price?: ManualPrice; label?: string } = {},\n ): number {\n const reserved = options.reserved ?? 0;\n // A bad reserved handle would corrupt this.reserved and break the ceiling for\n // OTHER in-flight calls (negative → phantom hold; Infinity → clears all holds).\n if (!Number.isFinite(reserved) || reserved < 0) {\n throw new RangeError(`reserved must be a finite, non-negative number, got ${reserved}`);\n }\n let overrides = this.priceOverrides;\n if (options.price !== undefined) {\n overrides = { ...(overrides ?? {}), [model]: options.price };\n }\n\n const priced = resolvePrice(model, overrides);\n if (priced === null) {\n console.warn(\n `Cannot price model '${model}': not in the bundled cost map and no ` +\n `manual price given. The budget guard cannot enforce a ceiling on ` +\n `spend it cannot measure — pass { price } or set it in priceOverrides.`,\n );\n // Release any held reservation on BOTH paths. Fail-closed must not leak\n // the in-flight hold, or reserved grows permanently and remainingUsd\n // shrinks until reserve() starts blocking everything.\n this.release(reserved);\n if (this.failClosed) {\n throw new UnpriceableModelError(model);\n }\n return 0;\n }\n\n let cost: number;\n try {\n cost = priceTokens(priced, promptTokens, completionTokens);\n } catch (err) {\n // priceTokens can throw (e.g. non-finite costs). Release the in-flight\n // hold before re-throwing so `reserved` doesn't leak and shrink\n // remainingUsd permanently — same fail-safe as the unpriceable path above.\n this.release(reserved);\n throw err;\n }\n if (reserved) {\n this.reserved = Math.max(0, this.reserved - reserved);\n }\n this.spentUsd += cost;\n // Clamp a sub-epsilon float overshoot back to the limit so the running total\n // never reports as having crossed the ceiling by a rounding artifact.\n if (this.spentUsd - this.limitUsd > 0 && this.spentUsd - this.limitUsd < EPS) {\n this.spentUsd = this.limitUsd;\n }\n this.lastCost = cost;\n this.appendEvent({\n timestamp: Date.now() / 1000,\n kind: \"llm\",\n modelOrTool: model,\n promptTokens,\n completionTokens,\n costUsd: cost,\n ...(options.label !== undefined ? { label: options.label } : {}),\n // 0 means \"no reservation\" (the plain record() path) — omit rather than\n // log a meaningless zero.\n ...(reserved ? { reserved } : {}),\n });\n return cost;\n }\n\n /**\n * Price one response's tokens offline and add the cost to the total.\n *\n * Returns the USD cost of this call. If the model is unpriceable and no `price`\n * is given, behaviour depends on `failClosed`: warn + throw (default), or\n * warn + skip accrual.\n */\n record(\n model: string,\n promptTokens: number,\n completionTokens: number,\n options: { price?: ManualPrice; label?: string } = {},\n ): number {\n return this.settle(model, promptTokens, completionTokens, {\n reserved: 0,\n price: options.price,\n label: options.label,\n });\n }\n\n /**\n * Accrue a non-LLM cost (a paid tool/API call) against the same ceiling.\n *\n * Tools with direct dollar costs — search APIs, scrapers, sandboxes — spend the\n * same budget the LLM calls do; `recordTool` folds them into `spentUsd` (so\n * `check()` / `reserve()` see them) and appends a `kind: \"tool\"`\n * {@link SpendEvent} to {@link BudgetGuard.spendLog}. The caller supplies the\n * cost: tools have no token usage to price. Deliberately does NOT update the\n * next-call estimate — that predicts the next *LLM* call, and a tool's price\n * would skew it. Returns `costUsd`.\n */\n recordTool(tool: string, costUsd: number, options: { label?: string } = {}): number {\n if (!Number.isFinite(costUsd) || costUsd < 0) {\n throw new RangeError(`costUsd must be a finite, non-negative number, got ${costUsd}`);\n }\n this.spentUsd += costUsd;\n // Same sub-epsilon clamp as settle(): never report a rounding-artifact\n // crossing of the ceiling.\n if (this.spentUsd - this.limitUsd > 0 && this.spentUsd - this.limitUsd < EPS) {\n this.spentUsd = this.limitUsd;\n }\n this.appendEvent({\n timestamp: Date.now() / 1000,\n kind: \"tool\",\n modelOrTool: tool,\n promptTokens: null,\n completionTokens: null,\n costUsd,\n ...(options.label !== undefined ? { label: options.label } : {}),\n });\n return costUsd;\n }\n\n /**\n * Drop an in-flight reservation without recording spend (e.g. the call failed\n * before producing usage). Safe to call with `0`.\n */\n release(reserved: number): void {\n // Validate before the zero-check so a NaN handle throws instead of being\n // silently dropped (a leak); a bad handle corrupts the in-flight tally.\n if (!Number.isFinite(reserved) || reserved < 0) {\n throw new RangeError(`reserved must be a finite, non-negative number, got ${reserved}`);\n }\n if (!reserved) return;\n this.reserved = Math.max(0, this.reserved - reserved);\n }\n\n /** USD left before the ceiling, net of in-flight reservations (never negative). */\n get remainingUsd(): number {\n return Math.max(0, this.limitUsd - this.spentUsd - this.reserved);\n }\n\n /**\n * The per-call spend ledger, oldest first — one {@link SpendEvent} per priced\n * `record()` / `settle()` / `recordTool()`. Returns a snapshot copy: mutating\n * it cannot corrupt the ledger.\n */\n get spendLog(): SpendEvent[] {\n return [...this.spendEvents];\n }\n\n /**\n * The spend ledger as JSONL — one event per line, newline-terminated.\n *\n * The schema is stable and language-independent (snake_case keys, fixed order;\n * optional fields omitted when absent), identical to the Python package's\n * `export_log()`, so heterogeneous agents produce logs you can concatenate and\n * analyse as one stream. (The *schema* is the contract, not the bytes: the two\n * runtimes may render the same float differently, e.g. JS `0.0000025` vs\n * Python `2.5e-06`.) Empty ledger yields `\"\"`.\n */\n exportLog(): string {\n return this.spendEvents\n .map((e) => {\n // snake_case wire shape, fixed key order — the cross-language schema.\n const row: Record<string, unknown> = {\n timestamp: e.timestamp,\n kind: e.kind,\n model_or_tool: e.modelOrTool,\n prompt_tokens: e.promptTokens,\n completion_tokens: e.completionTokens,\n cost_usd: e.costUsd,\n };\n if (e.label !== undefined) row.label = e.label;\n if (e.reserved !== undefined) row.reserved = e.reserved;\n return `${JSON.stringify(row)}\\n`;\n })\n .join(\"\");\n }\n\n private appendEvent(event: SpendEvent): void {\n // Frozen for parity with Python's frozen dataclass: spendLog copies the\n // array but shares the event objects, so an unfrozen event would let a\n // consumer silently rewrite logged history.\n this.spendEvents.push(Object.freeze(event));\n if (this.maxLogEvents !== undefined && this.spendEvents.length > this.maxLogEvents) {\n // Ring buffer: drop the oldest overflow (at most one per append).\n this.spendEvents.splice(0, this.spendEvents.length - this.maxLogEvents);\n }\n }\n\n /**\n * Context-aware spend advisory for this budget — see {@link BudgetAdvisory}.\n *\n * `nearLimit` flips once utilization reaches `nearLimitBps` (default 80%), so an\n * agent can taper *before* the hard-stop. Advisory only: read it to adapt;\n * {@link BudgetGuard.check} is what enforces the ceiling.\n */\n advisory(): BudgetAdvisory {\n // Floor (not round) so usedBps never over-reports utilization and nearLimit\n // flips exactly when the threshold is reached; the epsilon absorbs float noise\n // and Math.floor matches Python's int() exactly (round() would diverge).\n const usedBps =\n this.limitUsd <= 0\n ? 10000\n : Math.max(0, Math.min(10000, Math.floor((this.spentUsd / this.limitUsd) * 10000 + 1e-9)));\n return {\n nearLimit: usedBps >= this.nearLimitBps,\n usedBps,\n // Settled budget: limit minus accrued spend, deliberately NOT net of\n // in-flight reservations. Unlike the remainingUsd getter (which subtracts\n // `reserved`), the advisory is a soft utilization signal about money already\n // spent, while the getter reports what a new call can still claim.\n remainingUsd: Math.max(0, this.limitUsd - this.spentUsd),\n limitUsd: this.limitUsd,\n spentUsd: this.spentUsd,\n scope: \"local\",\n };\n }\n}\n\nfunction defaultOnBlock(spentUsd: number, limitUsd: number): void {\n console.error(\n \"BUDGET EXCEEDED — call blocked\\n\" +\n ` spent so far: $${spentUsd.toFixed(6)} | ceiling: $${limitUsd.toFixed(6)}\\n` +\n \" The next call would cross your budget; floe-guard stopped your agent \" +\n \"before it ran.\",\n );\n}\n","/**\n * Vercel AI SDK middleware that enforces a {@link BudgetGuard} in the call path.\n *\n * This is the TypeScript counterpart to the Python framework adapters. The AI SDK\n * is TypeScript-only, so it ships as its own npm package.\n *\n * Works with BOTH `ai@4` (`LanguageModelV1Middleware`) and `ai@5`\n * (`LanguageModelV2Middleware`). The two majors renamed the middleware type and\n * the usage fields (`promptTokens`/`completionTokens` → `inputTokens`/\n * `outputTokens`), so this module deliberately imports nothing from `ai`: the\n * middleware is typed structurally against the surface both majors share, and\n * usage is read from whichever field pair the installed SDK reports.\n *\n * - `wrapGenerate({ doGenerate, model })` — we `reserve()` (throws to hard-stop)\n * BEFORE calling `doGenerate()`, hold the reservation across the await, then\n * `settle()` from `result.usage`.\n * - `wrapStream({ doStream, model })` — we `reserve()` BEFORE `doStream()`, then\n * `settle()` from the `finish` part as the stream drains.\n *\n * Reserving before the await is what makes parallel calls (`Promise.all` over\n * several generations) honour the ceiling: each holds its slice instead of all\n * reading the same stale total (issue #18). The reservation is released if the\n * call throws, or if a stream ends without reporting usage.\n *\n * The model id used for pricing comes from `model.modelId`.\n */\n\nimport type { BudgetGuard } from \"./guard.js\";\n\n/**\n * The middleware call surface shared by `ai@4` and `ai@5`. Both majors invoke\n * `wrapGenerate`/`wrapStream` with an options object carrying these members\n * (plus richer `model` fields we don't read). `doGenerate`/`doStream` are\n * declared optional so every 4.x/5.x minor's options type stays assignable —\n * the SDK always provides the one each hook actually calls.\n */\ninterface MiddlewareCallOptions {\n doGenerate?: () => PromiseLike<any>;\n doStream?: () => PromiseLike<any>;\n model: { modelId: string };\n params?: unknown;\n}\n\n/**\n * Structural stand-in for `LanguageModelV1Middleware` (ai@4) and\n * `LanguageModelV2Middleware` (ai@5) — assignable to the `middleware` option of\n * `wrapLanguageModel` on either major.\n */\nexport interface BudgetGuardMiddleware {\n wrapGenerate: (options: MiddlewareCallOptions) => Promise<any>;\n wrapStream: (options: MiddlewareCallOptions) => Promise<any>;\n}\n\n/**\n * Read prompt/completion token counts from an ai@4 usage object\n * (`promptTokens`/`completionTokens`) or an ai@5 one (`inputTokens`/\n * `outputTokens`). Throws when either count is missing or non-numeric: the guard\n * cannot meter spend it cannot see, and treating it as $0 would fail open.\n */\nfunction usageTokens(\n modelId: string,\n usage: unknown,\n): { promptTokens: number; completionTokens: number } {\n const u = usage as\n | {\n promptTokens?: unknown;\n completionTokens?: unknown;\n inputTokens?: unknown;\n outputTokens?: unknown;\n }\n | null\n | undefined;\n const promptTokens = u?.promptTokens ?? u?.inputTokens;\n const completionTokens = u?.completionTokens ?? u?.outputTokens;\n if (typeof promptTokens !== \"number\" || typeof completionTokens !== \"number\") {\n throw new Error(\n `Model '${modelId}' reported no token usage — the budget guard cannot ` +\n `meter spend it cannot see, so this call is rejected rather than ` +\n `treated as free.`,\n );\n }\n return { promptTokens, completionTokens };\n}\n\n/**\n * Build a budget-guard middleware that hard-stops the model before a call\n * crosses the guard's USD ceiling, and records priced token usage after.\n * Compatible with `wrapLanguageModel` from both `ai@4` and `ai@5`.\n *\n * @example\n * import { wrapLanguageModel } from \"ai\";\n * import { openai } from \"@ai-sdk/openai\";\n * import { BudgetGuard, budgetGuardMiddleware } from \"floe-guard\";\n *\n * const guard = new BudgetGuard(5.00);\n * const model = wrapLanguageModel({\n * model: openai(\"gpt-4o\"),\n * middleware: budgetGuardMiddleware(guard),\n * });\n */\nexport function budgetGuardMiddleware(guard: BudgetGuard): BudgetGuardMiddleware {\n return {\n async wrapGenerate({ doGenerate, model }) {\n const reserved = guard.reserve(); // throws BudgetExceeded before the call runs\n let result: any;\n try {\n result = await doGenerate!();\n } catch (err) {\n guard.release(reserved); // the call failed before settle() took ownership\n throw err;\n }\n // From here settle() OWNS the reservation: it releases the hold on its own\n // throw (unpriceable / non-finite cost) and consumes it on success. Releasing\n // again would double-subtract and clear a concurrent call's in-flight hold.\n let handled = false;\n try {\n const { promptTokens, completionTokens } = usageTokens(\n model.modelId,\n result?.usage,\n );\n handled = true;\n guard.settle(model.modelId, promptTokens, completionTokens, { reserved });\n return result;\n } catch (err) {\n if (!handled) guard.release(reserved); // failed reading usage, before settle()\n throw err;\n }\n },\n\n async wrapStream({ doStream, model }) {\n const reserved = guard.reserve(); // throws BudgetExceeded before the stream starts\n let streamResult: any;\n try {\n streamResult = await doStream!();\n } catch (err) {\n guard.release(reserved); // the call failed before settle() took ownership\n throw err;\n }\n const { stream, ...rest } = streamResult as {\n stream: ReadableStream<any>;\n } & Record<string, unknown>;\n\n // `handled` flips once the reservation is disposed — settled on the finish\n // part, or released exactly once if the stream produced no usage (flush) or\n // ended early via error/cancellation (cancel). settle() owns disposal once\n // called, so nothing else may release after `handled` is set, or we'd\n // double-subtract and clear a concurrent call's hold.\n let handled = false;\n const guarded = stream.pipeThrough(\n new TransformStream<any, any>({\n transform(chunk, controller) {\n if (chunk?.type === \"finish\" && !handled) {\n try {\n const { promptTokens, completionTokens } = usageTokens(\n model.modelId,\n chunk.usage,\n );\n handled = true;\n guard.settle(model.modelId, promptTokens, completionTokens, { reserved });\n } catch (err) {\n // Release only if we never reached settle() (e.g. usage missing).\n // If settle() itself threw, it already released its own hold.\n if (!handled) {\n handled = true;\n guard.release(reserved);\n }\n throw err;\n }\n }\n controller.enqueue(chunk);\n },\n flush() {\n // Clean close with no finish/usage part — free the held budget.\n if (!handled) {\n handled = true;\n guard.release(reserved);\n }\n },\n cancel() {\n // Upstream error or consumer cancellation: flush() does not run here\n // (Web Streams: flush and cancel are mutually exclusive), so release\n // the still-held reservation.\n if (!handled) {\n handled = true;\n guard.release(reserved);\n }\n },\n // `cancel` is valid per the Streams spec and supported in Node 18+, but\n // TS's Transformer lib type lags and omits it — cast to keep the type check.\n } as Transformer<any, any>),\n );\n\n return { stream: guarded, ...rest };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAQO,IAAM,iBAAN,cAA6B,eAAe;AAAA,EACxC;AAAA,EACA;AAAA,EAET,YAAY,UAAkB,UAAkB;AAC9C;AAAA,MACE,+CAA0C,SAAS,QAAQ,CAAC,CAAC,QAAQ,SAAS,QAAQ,CAAC,CAAC;AAAA,IAC1F;AACA,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,WAAW;AAAA,EAClB;AACF;AASO,IAAM,wBAAN,cAAoC,eAAe;AAAA,EAC/C;AAAA,EAET,YAAY,OAAe;AACzB;AAAA,MACE,uBAAuB,KAAK;AAAA,IAG9B;AACA,SAAK,OAAO;AACZ,SAAK,QAAQ;AAAA,EACf;AACF;;;AC1DA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,qBAAqB;AAAA,IACnB,sBAAwB;AAAA,IACxB,uBAAyB;AAAA,IACzB,kBAAoB;AAAA,IACpB,MAAQ;AAAA,EACV;AAAA,EACA,8BAA8B;AAAA,IA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;AAAA;AAAA,QAGF,CAA0B;AAAA,MAC5B;AAEA,aAAO,EAAE,QAAQ,SAAS,GAAG,KAAK;AAAA,IACpC;AAAA,EACF;AACF;","names":[]}
package/dist/index.d.cts CHANGED
@@ -23,8 +23,9 @@ interface PricedModel {
23
23
  /**
24
24
  * Resolve a model to its per-token price, or `null` if it cannot be priced.
25
25
  *
26
- * Overrides win, then the bundled cost map (looked up by bare name, then the raw
27
- * field). Fail-closed: both prices must be finite, else `null`.
26
+ * Per specificity group (exact forms first, date-stripped fallbacks second):
27
+ * overrides win, then the bundled cost map. Fail-closed: the first matching
28
+ * entry must have finite prices, else `null`.
28
29
  */
29
30
  declare function resolvePrice(model: string, overrides?: Record<string, ManualPrice>): PricedModel | null;
30
31
  /** USD cost for token usage. Negative counts are clamped to zero. */
@@ -63,6 +64,32 @@ declare namespace pricing {
63
64
  * same epsilon handling, same fail-closed default.
64
65
  */
65
66
 
67
+ /**
68
+ * One priced spend event in the guard's per-call ledger.
69
+ *
70
+ * Every {@link BudgetGuard.record} / {@link BudgetGuard.settle} /
71
+ * {@link BudgetGuard.recordTool} that accrues spend appends exactly one event, so
72
+ * the ledger's costs sum to `spentUsd` (unless a `maxLogEvents` ring buffer has
73
+ * evicted old events). The schema is identical in the Python
74
+ * package (`SpendEvent` in `src/floe_guard/guard.py`) and
75
+ * {@link BudgetGuard.exportLog} serialises it with the same snake_case keys in
76
+ * both languages, so every agent emits the same shape regardless of stack.
77
+ */
78
+ interface SpendEvent {
79
+ /** Unix epoch seconds (UTC). */
80
+ readonly timestamp: number;
81
+ readonly kind: "llm" | "tool";
82
+ readonly modelOrTool: string;
83
+ /** `null` for tool events. */
84
+ readonly promptTokens: number | null;
85
+ /** `null` for tool events. */
86
+ readonly completionTokens: number | null;
87
+ readonly costUsd: number;
88
+ /** Caller-supplied tag (agent/task name). */
89
+ readonly label?: string;
90
+ /** The reservation settled by this call, if any. */
91
+ readonly reserved?: number;
92
+ }
66
93
  interface BudgetGuardOptions {
67
94
  /** Per-model manual prices for models the bundled cost map cannot price. */
68
95
  priceOverrides?: Record<string, ManualPrice>;
@@ -83,6 +110,13 @@ interface BudgetGuardOptions {
83
110
  * flags `nearLimit` so an agent can taper before the hard-stop. Default 8000.
84
111
  */
85
112
  nearLimitBps?: number;
113
+ /**
114
+ * Optional cap on the per-call spend ledger ({@link BudgetGuard.spendLog}).
115
+ * When set, the ledger is a ring buffer keeping the most recent N events so a
116
+ * long-running agent's memory stays bounded; the running totals are
117
+ * unaffected. Default: keep every event.
118
+ */
119
+ maxLogEvents?: number;
86
120
  }
87
121
  /**
88
122
  * A context-aware spend signal for the single local budget.
@@ -119,6 +153,9 @@ declare class BudgetGuard {
119
153
  private lastCost;
120
154
  /** USD held for in-flight calls (reserved, not yet settled). Counts toward the ceiling. */
121
155
  private reserved;
156
+ /** Per-call ledger, oldest first; a ring buffer when maxLogEvents is set. */
157
+ private readonly spendEvents;
158
+ private readonly maxLogEvents?;
122
159
  /**
123
160
  * @param limitUsd the spend ceiling, in USD. `0` blocks the very first call.
124
161
  */
@@ -151,11 +188,15 @@ declare class BudgetGuard {
151
188
  * Release a reservation and record the actual cost. `record` is `settle` with
152
189
  * no reservation. Returns the USD cost of this call; unpriceable-model handling
153
190
  * matches {@link BudgetGuard.record}, and any held reservation is released even
154
- * on the warn-and-skip path.
191
+ * on the warn-and-skip path. A priced call appends one {@link SpendEvent} to
192
+ * {@link BudgetGuard.spendLog} (`label` tags it, e.g. with an agent/task name);
193
+ * the warn-and-skip path accrues nothing and logs nothing, so the ledger stays
194
+ * in lockstep with `spentUsd`.
155
195
  */
156
196
  settle(model: string, promptTokens: number, completionTokens: number, options?: {
157
197
  reserved?: number;
158
198
  price?: ManualPrice;
199
+ label?: string;
159
200
  }): number;
160
201
  /**
161
202
  * Price one response's tokens offline and add the cost to the total.
@@ -166,6 +207,21 @@ declare class BudgetGuard {
166
207
  */
167
208
  record(model: string, promptTokens: number, completionTokens: number, options?: {
168
209
  price?: ManualPrice;
210
+ label?: string;
211
+ }): number;
212
+ /**
213
+ * Accrue a non-LLM cost (a paid tool/API call) against the same ceiling.
214
+ *
215
+ * Tools with direct dollar costs — search APIs, scrapers, sandboxes — spend the
216
+ * same budget the LLM calls do; `recordTool` folds them into `spentUsd` (so
217
+ * `check()` / `reserve()` see them) and appends a `kind: "tool"`
218
+ * {@link SpendEvent} to {@link BudgetGuard.spendLog}. The caller supplies the
219
+ * cost: tools have no token usage to price. Deliberately does NOT update the
220
+ * next-call estimate — that predicts the next *LLM* call, and a tool's price
221
+ * would skew it. Returns `costUsd`.
222
+ */
223
+ recordTool(tool: string, costUsd: number, options?: {
224
+ label?: string;
169
225
  }): number;
170
226
  /**
171
227
  * Drop an in-flight reservation without recording spend (e.g. the call failed
@@ -174,6 +230,24 @@ declare class BudgetGuard {
174
230
  release(reserved: number): void;
175
231
  /** USD left before the ceiling, net of in-flight reservations (never negative). */
176
232
  get remainingUsd(): number;
233
+ /**
234
+ * The per-call spend ledger, oldest first — one {@link SpendEvent} per priced
235
+ * `record()` / `settle()` / `recordTool()`. Returns a snapshot copy: mutating
236
+ * it cannot corrupt the ledger.
237
+ */
238
+ get spendLog(): SpendEvent[];
239
+ /**
240
+ * The spend ledger as JSONL — one event per line, newline-terminated.
241
+ *
242
+ * The schema is stable and language-independent (snake_case keys, fixed order;
243
+ * optional fields omitted when absent), identical to the Python package's
244
+ * `export_log()`, so heterogeneous agents produce logs you can concatenate and
245
+ * analyse as one stream. (The *schema* is the contract, not the bytes: the two
246
+ * runtimes may render the same float differently, e.g. JS `0.0000025` vs
247
+ * Python `2.5e-06`.) Empty ledger yields `""`.
248
+ */
249
+ exportLog(): string;
250
+ private appendEvent;
177
251
  /**
178
252
  * Context-aware spend advisory for this budget — see {@link BudgetAdvisory}.
179
253
  *
@@ -289,4 +363,4 @@ interface BudgetGuardMiddleware {
289
363
  */
290
364
  declare function budgetGuardMiddleware(guard: BudgetGuard): BudgetGuardMiddleware;
291
365
 
292
- export { type BudgetAdvisory, BudgetExceeded, BudgetGuard, type BudgetGuardMiddleware, type BudgetGuardOptions, FloeGuardError, type ManualPrice, type PricedModel, UnpriceableModelError, budgetGuardMiddleware, priceTokens, pricing, resolvePrice };
366
+ export { type BudgetAdvisory, BudgetExceeded, BudgetGuard, type BudgetGuardMiddleware, type BudgetGuardOptions, FloeGuardError, type ManualPrice, type PricedModel, type SpendEvent, UnpriceableModelError, budgetGuardMiddleware, priceTokens, pricing, resolvePrice };