@takk/treasury
v1.0.0
Published
Cost governance for Massive Intelligence (IM) agent orchestration: hard per-request, per-task, and per-day USD budgets with depletion events, pre-flight cost forecasting, prefix-cache break-even planning across sixteen provider profiles, and cheapest-firs
Downloads
110
Maintainers
Readme
Treasury
The deterministic, zero-dependency cost-governance layer for Massive Intelligence (IM) agent orchestration, self-hosted and offline, on your own infrastructure. Treasury forecasts the price of an arrangement before it runs, enforces hard USD budgets per request, per task, and per day, plans prefix-cache break-even across sixteen provider profiles, and routes a cheapest-first cascade, all with exact integer-cent arithmetic and no network calls.
Treasury is the cost and finance satellite of the @takk8is open multi-agent ecosystem, delivered as a zero-runtime-dependency NPM library that runs in your process, not someone else's. Composing several frontier models as a coordinated team raises the ceiling, but stacking model calls is where the bill runs away, and unpredictable cost is the loudest complaint against closed orchestration endpoints. Treasury is the CFO of the swarm: it approves or vetoes spend before it happens and optimizes the cache. A cost request is forecast, checked against the budgets you declared, and either authorized or rejected with a typed depletion event, all before a single provider call goes out. You always see the price first.
Core promise: zero required runtime dependencies, a two-line facade over the whole toolkit, hard per-request, per-task, and per-day USD budgets with pre-flight authorization and depletion events, exact-arithmetic cost forecasting with a confidence band and a per-model breakdown, prefix-cache break-even planning across sixteen provider profiles with nine explicit cache-kill rules and a guarantee that Treasury never recommends an unprofitable cache write, cheapest-first cascade routing with expected, best, and worst-case cost, deterministic money as integer micro-USD so sums never drift, a node-free and network-free core that runs in Node, edge runtimes, and the browser, ESM plus CJS dual distribution, and an MCP tool adapter that exposes forecasting, budgeting, and caching to any tool-calling host.
Why Treasury
Governing the cost of a fleet of black-box models is a control problem, not a routing problem. You want a hard, predictable ceiling on spend and an honest forecast of what an arrangement will cost, without handing your finances to a vendor in the middle of every call. The reflexive answer, a closed orchestrator, fails on exactly this axis: it is priced at the ceiling of the pool it orchestrates, its cost is unpredictable, it is a black box with no self-hosting, and it may be unavailable in your region. Treasury uses the correct primitive: a deterministic accounting layer that prices an arrangement up front, enforces budgets you set, and optimizes caching, over a pool you own, on infrastructure you control.
What sets it apart from a closed orchestration endpoint:
- Predictable, not surprising. Treasury forecasts the exact dollar cost of an arrangement before any model is called, with a per-model breakdown and a confidence band, so cost is a decision you make up front, not a line on an invoice.
- Controllable, not open-ended. Hard per-request, per-task, and per-day USD budgets with pre-flight authorization and a typed depletion event when a scope is exhausted. Nothing that would breach a budget is ever authorized.
- Transparent per step. Every forecast returns the total, the confidence band, the per-model breakdown, and the token totals. The bill is itemized, not hidden behind one opaque endpoint.
- Self-hosted and EU-friendly. Treasury runs in your process, on your infrastructure. No regional block, no vendor in the middle, no telemetry. Sovereignty is the default.
- Deterministic by construction. Money is integer micro-USD, so sums never drift, and the same inputs always produce the same forecast. There is no tokenizer and no network call in the core; the forecast is exact arithmetic over the token estimates you provide.
- Cache-aware. Prefix-cache break-even planning across sixteen provider profiles, with nine explicit cache-kill rules and a guarantee that Treasury never recommends an unprofitable cache write.
- Cost-aware routing. A cheapest-first cascade plan with expected, best, and worst-case cost and budget truncation, using the accept probabilities you provide.
Treasury is Briefing 6 of the @takk8is open multi-agent ecosystem, the cost and finance satellite. It runs standalone; its optional conceptual peers are @takk/caduceus (transport budgets) and @takk/coryphaeus (the orchestrator whose spend Treasury governs).
Install
pnpm add @takk/treasury
# or: npm install @takk/treasury
# or: yarn add @takk/treasury
# or: bun add @takk/treasuryThe core has zero required runtime dependencies. Every @takk sibling is optional; Treasury runs on its own.
Quickstart
import { createTreasury, formatUsd } from "@takk/treasury";
// 1. Declare your budgets. Any scope you omit is uncapped.
const treasury = createTreasury({
budget: { perDay: 5 },
onDepleted: (e) => console.warn("over budget", e.scope),
});
// 2. Forecast the arrangement before you run it. Exact arithmetic over the token estimates you provide.
const f = treasury.forecast({
steps: [{ model: "gpt-5-mini", usage: { inputTokens: 4000, outputTokens: 800 } }],
});
console.log(formatUsd(f.totalMicros)); // the priced arrangement, before any model call
// 3. Authorize, run, then record what actually happened.
if (treasury.authorize(f.totalMicros).allowed) {
// run the step, then:
treasury.record({ inputTokens: 4000, outputTokens: 820 }, "gpt-5-mini");
}forecast prices the arrangement with no network call and no tokenizer; the number is exact arithmetic over the token estimates you pass. authorize checks that total against every budget scope you declared and refuses anything that would breach one. record charges the real usage back and fires onDepleted when a scope is exhausted. Prices are reference data as of 2026-07-01, fully overridable, and Treasury never fetches prices over the network.
Forecast an arrangement
import { createTreasury } from "@takk/treasury";
const treasury = createTreasury({ budget: { perTask: 0.25 } });
const forecast = treasury.forecast({
steps: [
{ model: "gpt-5-mini", usage: { inputTokens: 4000, outputTokens: 800 } },
{ model: "claude-sonnet-4.5", usage: { inputTokens: 12000, outputTokens: 1500 } },
{ model: "claude-opus-4.8", usage: { inputTokens: 8000, outputTokens: 2000 } },
],
});
forecast.totalMicros; // the total in integer micro-USD, exact and drift-free
forecast.lowMicros; // the low end of the confidence band
forecast.highMicros; // the high end of the confidence band
forecast.perModel; // a Map of the cost attributed to each model
forecast.tokens; // input, output, and any cached token totalsThe forecast is exact arithmetic over the token estimates you provide. A three-model arrangement like the one above forecasts about $0.0591. There is no tokenizer and no network call: if your token estimates are right, the price is right. Optional cachedInputTokens and cacheWriteTokens per step feed the prefix-cache accounting.
Prefix-cache break-even
import { evaluateCache } from "@takk/treasury/prefixcache";
const plan = evaluateCache({
model: "claude-opus-4.8",
prefixTokens: 8000,
expectedReuses: 20,
});
plan.shouldCache; // true only when caching is profitable
plan.breakEvenReuses; // the reuse count where a cache write pays for itself
plan.netMicros; // the net saving across the expected reusesTreasury plans prefix-cache break-even across sixteen provider profiles, with nine explicit cache-kill rules. It never recommends an unprofitable cache write. An 8000-token Claude Opus prefix breaks even at 2 reuses and nets about $0.67 across 20 reuses. A provider with no read discount, such as mistral-large-2, never caches, because there is no arithmetic under which the write pays for itself. Use shouldCache(...) for the boolean and breakEvenReuses(...) for the threshold directly.
Cheapest-first cascade
import { planCascade } from "@takk/treasury/cascade";
const plan = planCascade({
ladder: [
{ model: "gpt-5-mini", usage: { inputTokens: 4000, outputTokens: 400 }, acceptProbability: 0.6 },
{ model: "claude-sonnet-4.5", usage: { inputTokens: 4000, outputTokens: 600 }, acceptProbability: 0.8 },
{ model: "claude-opus-4.8", usage: { inputTokens: 4000, outputTokens: 800 } },
],
});
plan.expectedMicros; // expected cost, weighted by the accept probabilities you provide
plan.bestMicros; // the cheapest rung answers
plan.worstMicros; // every rung is exhaustedplanCascade prices a cheapest-first ladder: it tries the cheapest rung, escalates only when a rung is not accepted, and reports the expected, best, and worst-case cost. The expected cost uses the accept probabilities you provide; Treasury does not estimate them for you. A budget truncates the ladder so no rung that would breach a ceiling is ever included in the plan.
Budgets and depletion
import { createTreasury } from "@takk/treasury";
const treasury = createTreasury({
budget: { perRequest: 0.05, perTask: 0.5, perDay: 5 },
onDepleted: (event) => {
event.scope; // "perRequest" | "perTask" | "perDay", the ceiling that was hit
},
});
const decision = treasury.authorize(forecastTotalMicros);
decision.allowed; // false when the spend would breach any declared scopeBudgets are hard ceilings enforced before dispatch, not after the fact. authorize checks a forecast total against every scope you declared and refuses anything that would breach one; record charges real usage and fires onDepleted the moment a scope is exhausted. Any scope you omit is uncapped. Because money is integer micro-USD, the running totals never drift.
Prices are reference data, and yours to override
import { createTreasury } from "@takk/treasury";
import { isPriceTableStale, priceTableAgeDays } from "@takk/treasury/pricing";
const now = new Date();
isPriceTableStale(now); // true once the bundled table is past its freshness window
priceTableAgeDays(now); // how many days old the bundled table is
// Bring your own prices; Treasury never fetches them over the network.
// withPrices(overrides) returns a new table merged over the bundled one.
const treasury = createTreasury({ budget: { perDay: 5 }, table: withPrices(myOverrides) });The bundled price table is reference data as of 2026-07-01. Treasury never fetches prices over the network, in 1.0 or ever, so the number you see is the number you shipped. Check staleness with isPriceTableStale(now) and priceTableAgeDays(now), then refresh or pass your own table with withPrices. Overriding prices is the intended path; the bundle is a convenience, not a source of truth.
Entry points
Ten subpath exports plus a CLI, each importable on its own. The core is node-free and network-free; only node touches a Node built-in.
| Import | What it gives you |
|---|---|
| @takk/treasury | The full toolkit barrel, re-exporting pricing, budget, forecast, prefix cache, cascade, and the facade. |
| @takk/treasury/pricing | The reference price table, estimateCost, withPrices, isPriceTableStale, and priceTableAgeDays. |
| @takk/treasury/budget | Per-request, per-task, and per-day budget tracking with pre-flight authorization and depletion events. |
| @takk/treasury/forecast | forecast(...), exact arithmetic over your token estimates, with a confidence band and a per-model breakdown. |
| @takk/treasury/prefixcache | evaluateCache, shouldCache, and breakEvenReuses across sixteen provider profiles with nine cache-kill rules. |
| @takk/treasury/cascade | planCascade(...), cheapest-first routing with expected, best, and worst-case cost and budget truncation. |
| @takk/treasury/treasury | The facade: createTreasury and Treasury, tying budgets, forecasting, and recording together. |
| @takk/treasury/mcp | createTreasuryTools, exposing treasury_forecast, treasury_budget, and treasury_cache tools plus a treasury://pricing resource. |
| @takk/treasury/edge | The node-free, network-free core, re-exported for edge runtimes and the browser. |
| @takk/treasury/node | readJsonFile and writeJsonFile, the only node:fs surface in the package. |
A tool for a non-human entity
The MCP adapter exposes Treasury as framework-agnostic tools a non-human entity can call to price, budget, and cache-plan its own spend. The descriptor shape, a name, a description, a JSON Schema, and a handler, matches what MCP servers and tool-calling APIs expect, and input arriving from a model is parsed defensively.
import { createTreasuryTools } from "@takk/treasury/mcp";
// Register with your MCP server or tool-calling API.
// Tools: treasury_forecast, treasury_budget, treasury_cache. Resource: treasury://pricing.
const { tools, resource } = createTreasuryTools();
const forecastTool = tools.find((t) => t.name === "treasury_forecast");
const priced = forecastTool.handler({
steps: [{ model: "gpt-5-mini", inputTokens: 4000, outputTokens: 800 }],
});This is the loop a non-human entity (NHE) closes over its own budget: it prices a plan, checks it against the ceiling it was given, and plans its cache, all before spending a cent. The treasury://pricing resource exposes the current reference table for inspection.
CLI
Treasury ships a command-line tool that runs the real accounting core. Because it makes no network calls, every subcommand is deterministic and offline.
# Forecast a saved plan file, exact arithmetic over its token estimates.
npx @takk/treasury forecast plan.json
# Simulate a plan against hard budgets, per request, per task, or per day.
npx @takk/treasury simulate plan.json --per-day 5
# Combine budget scopes.
npx @takk/treasury simulate plan.json --per-request 0.05 --per-task 0.5 --per-day 5
# Look up a model's price, list every priced model, or evaluate a cache plan.
npx @takk/treasury price claude-opus-4.8
npx @takk/treasury models
npx @takk/treasury cache --model claude-opus-4.8 --prefix 8000 --reuses 20
# Plan a cheapest-first cascade from a ladder file.
npx @takk/treasury plan ladder.jsonExit codes are explicit and stable: 0 success, 2 usage error, 10 file not found, 20 invalid input, 30 budget exceeded. See examples/ for runnable demos that exercise the built artifact end to end.
How it works, in one paragraph
A cost request carries the steps of a planned arrangement, each a model and its estimated token usage. Treasury prices every step against the reference price table (or the table you injected), sums the result in integer micro-USD so nothing drifts, and returns a forecast with a total, a confidence band, a per-model breakdown, and the token totals. That total is checked against the per-request, per-task, and per-day budgets you declared: authorize refuses anything that would breach a scope, and record charges real usage back and fires onDepleted when a scope is exhausted. The prefix-cache planner evaluates a candidate cache write across sixteen provider profiles under nine cache-kill rules and returns a break-even reuse count, never recommending an unprofitable write. The cascade planner prices a cheapest-first ladder and reports expected, best, and worst-case cost using the accept probabilities you supply, truncating the ladder to fit a budget. There is no tokenizer, no network call, and no hidden state: the forecast is exact arithmetic over the token estimates you provide, which is what keeps Treasury deterministic, node-free, network-free, and testable with no network.
Honest framing
Treasury does not pretend to know more than it does, and it is worth stating plainly what it is and is not:
- The forecast is exact arithmetic, not a prediction. There is no tokenizer and no network call. Treasury prices the token estimates you provide; if those estimates are wrong, the price is wrong. The exactness is in the arithmetic, not in guessing your token counts for you.
- The cascade expected cost uses your accept probabilities. Treasury weights the ladder by the accept probabilities you pass in. It does not learn or estimate them, and there is no learned routing in 1.0.
- Prices are reference data, not a live feed. The bundled table is a snapshot as of 2026-07-01. Treasury never fetches prices over the network. Check staleness with
isPriceTableStale(now)/priceTableAgeDays(now)and refresh or override withwithPrices. - No dashboards, no analytics, no telemetry. Treasury is a library. It ships no UI and makes no outbound calls.
Positioning
The closed orchestrator this ecosystem answers, Sakana Fugu, is priced at the ceiling of the pool it orchestrates. Its cost is unpredictable, which is the single most common criticism levelled at it. It is a black box with no self-hosting, and it is blocked in the EU and EEA. Treasury inverts every one of those properties.
| Property | A closed orchestrator (Fugu) | Treasury | |---|---|---| | Cost | Unpredictable, the top complaint | Forecast up front, exact arithmetic | | Pricing | At the ceiling of the pool | The reference table, or your own | | Transparency | Opaque, one endpoint | Itemized per step and per model | | Hosting | Vendor-only, no self-hosting | Self-hosted, in your process | | Region | Blocked in the EU and EEA | EU-friendly, no regional block | | Determinism | Whatever the box decides | Integer micro-USD, sums never drift |
Quality
- 60 tests across 11 suites, all passing under Vitest on Node 20, 22, and 24.
- Coverage: statements 97.7%, branches 91.48%, functions 93.82%.
- Benchmark on Apple silicon:
estimateCostabout 114,000,000 ops/s,forecast(3 steps) about 7,300,000 ops/s,evaluateCache(9 rules) about 17,900,000 ops/s,planCascade(3 rungs) about 5,200,000 ops/s. - Lint clean under Biome.
- Typecheck clean under TypeScript in maximum strict mode (
exactOptionalPropertyTypes,useUnknownInCatchVariables,noUncheckedIndexedAccess,noPropertyAccessFromIndexSignature). publintclean and@arethetypeswrong/cligreen across all ten subpaths.size-limitunder budget on every bundle (brotli root bundle 5.99 kB).- SLSA provenance attested on every release.
- Zero required runtime dependencies; a node-free and network-free core that runs in Node, edge runtimes, and the browser; dual ESM plus CJS; TypeScript-first.
See SPEC.md for the formal specification, public surface, and stability promise.
FAQ
How is this different from a closed multi-agent endpoint? A closed endpoint prices at the ceiling of its pool, hides what each step cost, cannot be self-hosted, and may be unavailable in your region. Treasury runs in your process over your pool, forecasts the exact dollar cost before any call, enforces hard per-request, per-task, and per-day budgets, and itemizes the bill per step and per model. Cost is predictable, controllable, and yours.
Does Treasury call any model or fetch any prices? No. The core is accounting logic with no network surface. It never calls a model and never fetches prices; you provide the token estimates and, if you like, your own price table. That is what keeps the package deterministic, dependency-free, and testable with no network.
Is the forecast a real prediction of what I will be charged? It is exact arithmetic over the token estimates you provide, priced against the price table in effect. There is no tokenizer, so Treasury does not count your tokens for you; if your estimates match reality, the forecast matches the invoice. The exactness is in the math, not in guessing your token counts.
How does it control cost?
Every forecast total is checked against the per-request, per-task, and per-day budgets you declared. authorize refuses anything that would breach a scope before it is dispatched, and record fires a typed depletion event the moment a scope is exhausted. A cascade plan further prices a cheapest-first ladder and truncates it to fit a budget.
Can a non-human entity drive it?
Yes. The MCP adapter exposes treasury_forecast, treasury_budget, and treasury_cache as framework-agnostic tools with JSON Schemas and handlers, plus a treasury://pricing resource, ready to register with an MCP server or any tool-calling API.
Does this work in Cloudflare Workers, Vercel Edge, Bun, and Deno?
Yes. The core is node-free and network-free. Import @takk/treasury or @takk/treasury/edge anywhere. Only @takk/treasury/node, which is just readJsonFile and writeJsonFile, requires Node.
Contributing
See .github/CONTRIBUTING.md for the contributor guide. Substantive proposals open a GitHub Issue first; trivial fixes can go straight to a PR. All commits require DCO sign-off (git commit -s). Non-trivial contributions are governed by the Contributor License Agreement.
Community and support
- Issues and feature requests. Open a GitHub issue at
davccavalcante/treasury/issues. Include the package version, a minimal reproduction, expected versus actual behavior, and where relevant theforecast()orauthorize()output. - Security disclosures. Do not open public issues for vulnerabilities. Follow the responsible-disclosure flow in
SECURITY.md, contact[email protected](or[email protected]) with the[SECURITY]prefix. - Code of Conduct. This project follows the Contributor Covenant 2.1. Participation in any Treasury space implies agreement.
- Contributions. All non-trivial contributions go through the Contributor License Agreement. Tests, lint, typecheck, and build must be green before review (
pnpm verify).
Author
Created by David C Cavalcante, [email protected] (preferred), [email protected] (Takk relay), linkedin.com/in/hellodav, x.com/davccavalcante, takk.ag.
Treasury is part of a broader family of NPM packages targeting Massive Intelligence (IM) native infrastructure for 2026-2030, built at Takk Innovate Studio. Predictable, self-hosted cost governance is foundational infrastructure for that era, the finance plane that lets a fleet of non-human entities spend without surrendering control of the budget.
Related research by the author
The philosophy behind Treasury, governing the cost of many intelligences as one predictable, inspectable ledger, echoes the author's research frameworks:
- MAIC (Massive Artificial Intelligence Consciousness), a systemic intelligence framework designed to coordinate, supervise, and govern large-scale Massive Intelligence ecosystems, providing global context awareness, alignment, and orchestration across multiple models, agents, and decision layers.
- HIM (Hybrid Entity Intelligence Model), a hybrid intelligence layer that integrates Massive Intelligence systems with human-defined logic, rules, heuristics, and strategic intent, interpreting objectives and structuring decision-making before and after model execution.
- NHE (Noumenal Higher-order Entity), a non-human cognitive entity with a defined functional identity and operational agency within a Massive Intelligence ecosystem, operating through coordinated intelligence layers while maintaining a non-anthropomorphic identity.
These frameworks are published independently of Treasury and are separate works:
- Research papers: The Soul of the Machine, Beyond Consciousness in LLMs, The Cave of Silence.
- PhilPapers profile: David Cortes Cavalcante.
- Hugging Face: TeleologyHI.
- GitHub: davccavalcante, Takk8IS.
Sponsors
Join the journey as the family continues to ship Massive Intelligence (IM) native infrastructure. Your support is the cornerstone of this work.
- Sponsor on GitHub: github.com/sponsors/davccavalcante
- USDT (TRC-20):
TS1vuhMAhFpbd7y68cu5ZtP9PsXVmZWmeh
Privacy
Treasury runs entirely inside your own process and infrastructure. It makes no outbound calls to the author, collects no telemetry, and ships no analytics. It never fetches prices over the network, and it never calls a model. See PRIVACY.md for the full data-handling notice, including how the optional file loaders read a plan and a ladder from disk.
License
Licensed under the Apache License 2.0. See LICENSE for the full text and NOTICE for attribution and third-party component licenses. You may use, modify, and distribute the code under the terms of that license, including its patent grant and attribution requirements.
