@takk/treasury - v1.0.0 - Apache-2.0

The CFO of your agent swarm.

Massive Intelligence (IM) orchestration burns model spend you cannot see coming, and a closed orchestrator prices at the pool ceiling with cost you cannot predict. Treasury is the deterministic, zero-dependency cost-governance layer: it approves or vetoes model spend before it happens and optimizes the prompt-prefix cache, self-hosted and offline, on your own infrastructure.

59tests passing
97.7%coverage
0runtime deps
16price profiles
What it is

One library, every dollar under control.

In a few words

Treasury is the cost-governance layer for a Massive Intelligence (IM) agent swarm. You set a USD budget and describe the arrangement of model calls you plan to run, and it forecasts the cost before anything happens, then approves or vetoes the spend against a hard ceiling. Your code is two lines: createTreasury({ budget }), then t.authorize(f.totalMicros).

Technically

Forecasting is exact arithmetic over the token estimates you supply, no tokenizer and no network, and returns a total in integer micro-USD with a confidence band. Budgets are enforced per request, per task, and per day with pre-flight authorization and depletion events. Prefix-cache break-even is planned across 16 provider price profiles with 9 explicit cache-kill rules, and a cheapest-first cascade reports expected, best, and worst-case cost. The core is node-free and network-free.

Before and after

The same swarm, two very different invoices.

Take a real production scene: a Massive Intelligence (IM) swarm making many model calls per task, where the spend is unpredictable, the cache is guesswork, and a closed orchestrator prices at the pool ceiling.

Ungoverned spend or a closed orchestrator

Cost you discover on the invoice, in a box you cannot see into

  1. Blind You dispatch model calls with no forecast, and the bill is a surprise after the fact.
  2. Closed A closed orchestrator is a black box; you cannot see what a step will cost before it runs.
  3. Cost Pricing sits at the ceiling of the pool, and unpredictable cost is its first criticism.
  4. Cache Prefix-cache writes are guesswork, and an unprofitable write quietly loses you money.
  5. Sovereignty A vendor sits in the middle of every call, and the EU and EEA may be blocked.
  6. Lock-in The routing, the prices, and the keys all belong to someone else.
  7. Result No pre-flight control, no cache math, and no ceiling you can trust.
With Treasury

Every dollar approved before it is spent, deterministic and offline

  1. Forecast Exact arithmetic over your token estimates gives a total plus a confidence band.
  2. Authorize A hard per-request, per-task, and per-day USD ceiling approves or vetoes each spend.
  3. Deplete Depletion events fire as a budget drains, so nothing runs past the line silently.
  4. Cache Break-even planning across 16 profiles never recommends an unprofitable cache write.
  5. Cascade A cheapest-first route reports expected, best, and worst-case cost up front.
  6. Sovereignty It runs on your infrastructure, self-hosted and offline, the EU included.
  7. Money is integer micro-USD, so every number is exact and every run is deterministic.

Deterministic cost governance is the layer between an ungoverned swarm and an opaque closed orchestrator; it keeps the forecast, the budget, and the cache math in your hands, on your infrastructure, with every spend decision made before the money leaves.

Install

Five minutes from install to your first auditable run.

1. Add the package

pnpm add @takk/treasury
npm install @takk/treasury
yarn add @takk/treasury
bun add @takk/treasury

2. Zero required dependencies

The core has no runtime dependencies and is node-free and network-free. Every @takk sibling is an optional peer; install only what you govern alongside.

# nothing else is required to start experimenting
              # optional: install a peer you govern alongside, for example
              pnpm add @takk/caduceus @takk/coryphaeus

3. Authorize a spend in a few lines

import { createTreasury } from '@takk/treasury';

              // A hard per-day USD ceiling. Money is tracked as integer micro-USD.
              const t = createTreasury({ budget: { perDay: 5 } });

              // Forecast the arrangement of model calls before anything runs. Exact
              // arithmetic over the token estimates you supply, no tokenizer, no network.
              const f = t.forecast({
              steps: [{ model: 'gpt-5-mini', usage: { inputTokens: 4000, outputTokens: 800 } }],
              });

              if (t.authorize(f.totalMicros).allowed) {
              // run: the spend fits the budget and was approved before it happened
              }

4. Expose it as a tool a non-human entity can call

import { createForecastTool } from '@takk/treasury/mcp';

              // A framework-agnostic descriptor (name, description, JSON Schema, handler) that
              // matches what MCP servers and tool-calling APIs expect. Its name is 'treasury_forecast'.
              const tool = createForecastTool(t);
              const result = await tool.handler({
              steps: [{ model: 'claude-sonnet-4', usage: { inputTokens: 8000, outputTokens: 1200 } }],
              });
              // the host fixes the budget and prices; the caller only asks what it will cost
Features

Nine capabilities, every one tied to a measurable outcome.

Hard USD budgets

Per-request, per-task, and per-day ceilings with pre-flight authorization. Every spend is approved or vetoed before it happens, and depletion events fire as a budget drains toward the line.

Cost is a number you set up front, instead of a surprise discovered on the invoice.

Pre-flight forecasting

Forecast the cost of an arrangement of model calls before any spend, exact arithmetic over the token estimates you provide, with no tokenizer and no network, and a confidence band around the total.

Know what a run will cost before it runs, instead of measuring the damage afterward.

Prefix-cache break-even

Plan the prompt-prefix cache across 16 provider price profiles with 9 explicit cache-kill rules. It is guaranteed never to recommend a cache write that would not pay for itself.

Cache when it saves money and skip when it does not, instead of guessing at every write.

Cheapest-first cascade

Route an escalating cascade that tries the cheapest capable model first, and reports the expected, best, and worst-case cost of the whole route up front.

Spend the least a task needs, with the full cost envelope known before you commit.

Deterministic money

Money is tracked as integer micro-USD, so there is no floating-point drift. The same inputs always produce the same forecast, authorization, and cache decision, on every runtime.

Reproduce any cost decision exactly, instead of chasing rounding differences across runs.

Overridable reference prices

Ships with provider reference prices as of 2026-07-01, never fetched over the network. Override any of them via withPrices to match your negotiated rates or a new model.

Govern against your real prices, instead of a stale table you cannot correct.

Self-hosted and offline

The core is node-free and network-free and runs entirely on your infrastructure. No vendor sits in the middle of a cost decision, and the EU and EEA are not blocked.

Govern spend where a closed, region-locked orchestrator cannot follow you.

Runs everywhere

Dual ESM and CJS, TypeScript strict, with a node-free core that runs on Node, edge runtimes such as Cloudflare Workers, Vercel Edge, Deno, and Bun, and the browser.

Put the cost gate wherever the spend happens, instead of only on a single server.

SLSA provenance

Every published version signed with npm publish --provenance through GitHub Actions OIDC. Lockfile committed, zero runtime dependencies, node-free core.

Verify in one command that the tarball you installed was built from the source commit you trust.

Model

Four cost decisions, no black box.

Treasury answers four questions about the spend of a Massive Intelligence (IM) swarm, each deterministic and inspectable, each exact arithmetic in integer micro-USD; the only knobs are your budget and your prices.

Decision What it is When you reach for it
budget Hard per-request, per-task, and per-day USD ceilings, authorized before spend with depletion events. You need a spend that cannot exceed a line, whatever the swarm does.
forecast Exact arithmetic over the token estimates you supply, a total plus a confidence band, no network. You want to know what an arrangement of model calls will cost before it runs.
prefixcache Break-even planning across 16 price profiles with 9 cache-kill rules; never recommends an unprofitable write. You reuse a long prompt prefix and need the cache to actually pay for itself.
cascade Cheapest capable model first, escalating on demand, with expected, best, and worst-case cost reported. You want the least a task needs, with the full cost envelope known up front.

The forecast is exact arithmetic over the token estimates you provide, with no tokenizer and no network; prices are reference data as of 2026-07-01, overridable via withPrices and never fetched over the network.

Entry points

Ten subpaths, import only what you need.

Entry point Subpath export Runtime Use it when
Toolkit barrel @takk/treasury node-free You want the facade, budgets, forecasting, prefix-cache, cascade, prices, and the MCP tool.
Budget and forecast @takk/treasury/budget, /forecast node-free You want the hard USD ceilings, or the pre-flight cost forecast, on their own.
Cache, cascade, prices @takk/treasury/prefixcache, /cascade, /pricing node-free You want break-even planning, cheapest-first routing, or the reference price profiles.
MCP, edge, node @takk/treasury/mcp, /edge, /node edge or Node You want the tool for an MCP server, the edge build, or the Node file loaders.
CLI

A command-line tool that runs the real cost engine.

The treasury binary runs the compiled engine. forecast prices an arrangement of model calls; simulate runs a plan against a budget and returns a spend verdict; price and models read the reference prices; cache plans prefix-cache break-even; plan lays out a cheapest-first cascade. Everything is deterministic and offline.

Forecast the cost of an arrangement

# price the arrangement of model calls, no spend
              npx @takk/treasury forecast plan.json

Simulate a plan against a budget

# run the plan against a hard per-day USD ceiling and get a verdict
              npx @takk/treasury simulate plan.json --per-day 5
              npx @takk/treasury cache plan.json
          

Read prices, inspect version and help

npx @takk/treasury models
              npx @takk/treasury --version

              # exit codes: 0 ok, 2 usage, 10 file not found, 20 invalid input, 30 budget exceeded
Forecast and transparency

Know the cost, and read every number.

Forecast the spend of an arrangement before anything runs, then authorize it against a hard budget. Because every decision is explicit, forecast returns the total, the per-step cost, and a confidence band, and authorize returns whether the spend is allowed and how much budget remains, so cost is never a black box. Both are node-free, network-free, and need no external service.

import { createTreasury } from '@takk/treasury';

              const t = createTreasury({ budget: { perDay: 5 } });

              // Forecast the arrangement, then authorize the spend before it happens.
              const f = t.forecast({
              steps: [{ model: 'gpt-5-mini', usage: { inputTokens: 4000, outputTokens: 800 } }],
              });

              const decision = t.authorize(f.totalMicros); // { allowed: true, remainingMicros: 4994720, ... }

Every forecast is explicit

const f = t.forecast({
              steps: [{ model: 'gpt-5-mini', usage: { inputTokens: 4000, outputTokens: 800 } }],
              });
              // {
              //   totalMicros: 5280,                              // exact cost, integer micro-USD
              //   totalUsd: 0.00528,                              // the same total in USD
              //   confidence: { lowMicros: 5016, highMicros: 5544 },
              //   steps: [ { model: 'gpt-5-mini', costMicros: 5280, ... } ],
              //   assumptions: { pricesAsOf: '2026-07-01', network: 'none' }
              // }

The forecast carries the exact total in integer micro-USD, the per-step cost, and a confidence band, so you can see what a run will cost and why. It is exact arithmetic over the token estimates you supply, with no tokenizer and no network, the cost gate for a non-human entity spending against a budget it does not own.

Compare

Treasury vs the alternatives.

The other approaches solve part of the problem. The contrast clarifies where Treasury sits.

Capability Treasury Sakana Fugu Provider dashboard Usage SDK Hand-rolled
Distribution npm library hosted orchestrator hosted console npm library your repo
Cost predictable pre-flight forecast unpredictable after the fact reported after varies
Hard budget ceiling authorized before spend pool ceiling alerts, not gates no manual
Prefix-cache break-even yes hidden no no no
Transparent per step every number black box totals only per call varies
Self-hosted, EU-friendly your infra blocked in EU vendor-hosted yes yes
Deterministic, offline integer micro-USD no no network varies
Zero deps, node-free yes n/a n/a deps varies
License Apache-2.0 proprietary proprietary mixed your call

The honest summary: a closed orchestrator is fine when you do not need to see or cap the spend, and a provider dashboard is fine for reading totals after the fact. Pick Treasury when you want the cost of a Massive Intelligence (IM) swarm forecast and authorized before it happens, the cache math done for you, and every number visible, all in one deterministic, node-free TypeScript library you embed in production.

The engine, honestly

What the cost engine assumes, and how it stays honest.

Treasury is deterministic cost governance over the token estimates you supply, and that has boundaries. They are documented, and where reality bends them, there is an explicit choice rather than a silent fudge.

Assumption or property What it means How Treasury handles it
Estimates in, exact out The forecast prices the token estimates you provide; it does not count tokens for you. Given those estimates the arithmetic is exact, with no tokenizer and no network, and a confidence band brackets the total.
Reference prices Prices are reference data as of 2026-07-01, not a live feed. They are never fetched over the network and are overridable via withPrices to match your real rates or a new model.
Integer micro-USD All money is tracked as integer micro-USD, not floating-point dollars. The same inputs always produce the same result, with no rounding drift across runtimes or runs.
Budget is a hard ceiling The ceiling is enforced before a breaching spend is authorized. authorize returns allowed: false before the call, and depletion events fire as a budget drains, rather than reporting an overrun after.
Cache never loses money Prefix-cache planning weighs the write cost against reuse across 16 price profiles. With 9 explicit cache-kill rules it is guaranteed never to recommend an unprofitable cache write.
Cascade cost envelope A cascade may escalate, so its cost is a range, not a single number. It reports the expected, best, and worst-case cost of the whole route up front, so the ceiling is known.
Governance, not calling Treasury decides whether spend is allowed; it never makes the model call. Your code makes the call after authorize approves it, so provider keys and traffic never touch Treasury.
Node-free core The core does not depend on the Node standard library. It runs on Node, edge runtimes, and the browser; only the file loaders in /node need Node.
Quality and validation

The receipts behind v1.0.0.

Tests & coverage

60 tests passing under Vitest 4 across 11 suites on the Node 20, 22, and 24 matrix, with 97.7% statements, 91.48% branches, and 93.82% functions covered. Runnable examples exercise the built artifact end to end. Run pnpm test on a fresh clone to reproduce.

Type safety

TypeScript 6 in maximum strict mode (exactOptionalPropertyTypes, useUnknownInCatchVariables, noUncheckedIndexedAccess, noImplicitOverride, noImplicitReturns). Zero errors under tsc --noEmit.

Lint & types-correctness

Biome 2.5 clean across src and tests. publint clean and @arethetypeswrong/cli green across all subpaths. Dual ESM + CJS with separate .d.ts and .d.cts per subpath.

Behavior, verified

The forecast prices a known arrangement to the exact micro-USD, the budget guard vetoes a spend before it breaches the ceiling, the cascade escalates only when the cheaper tier cannot carry the task, and the cache planner refuses an unprofitable write. Every invariant is a test.

Distribution smoke

A smoke test exercises the compiled ESM and CJS artifacts and spawns the compiled CLI as a single Node process, run on the Node 20, 22, and 24 matrix. The root bundle is 5.99 kB brotlied.

Supply chain

Committed pnpm lockfile, zero runtime dependencies, node-free core, and SLSA provenance attestation on every published version. Verify with npm view @takk/treasury@1.0.0 --json | jq .dist.attestations.

Roadmap

What is shipped, what is next, what is later.

Now (1.0)

Shipped in v1.0.0

  • Hard per-request, per-task, and per-day USD budgets
  • Pre-flight authorization and depletion events
  • Exact cost forecast with a confidence band
  • Prefix-cache break-even across 16 price profiles
  • Cheapest-first cascade with best and worst-case cost
  • MCP tool, CLI with forecast, simulate, price, models, cache, plan
  • Dual ESM + CJS, node-free core, SLSA provenance
Next

Planned next

  • More provider price profiles and model families
  • Rolling and monthly budget windows
  • Per-team and per-tenant budget hierarchies
  • Optional live price refresh, opt-in and cached
  • A recorded spend ledger for reconciliation
Later

On the horizon

  • Deeper integration with the transport satellite (Caduceus)
  • Cost governance across the orchestrator (Coryphaeus)
  • A shared price and profile registry
  • Hosted spend dashboards for the swarm
FAQ

Common questions.

Is Treasury production-ready at 1.0.0?

Yes. 60 tests pass under Vitest 4 across 11 suites with 97.7% statement coverage; TypeScript 6 maximum strict mode is clean; Biome 2.5 lint is clean; publint and @arethetypeswrong/cli are clean across all subpaths. The suite and the distribution smoke test are run on the Node 20, 22, and 24 matrix. Every published release carries SLSA provenance produced by GitHub Actions.

Is the forecast accurate?

The forecast is exact arithmetic over the token estimates you supply, with no tokenizer and no network, so given those estimates the cost is exact to the micro-USD. It does not count tokens for you; you provide the usage estimate, and Treasury prices it and brackets the total with a confidence band. If your estimates are good, the forecast is good.

Where do the prices come from?

They are reference data as of 2026-07-01, bundled with the package and never fetched over the network, so the engine stays deterministic and offline. Override any of them via withPrices to match your negotiated rates, a new model, or a provider Treasury does not ship a profile for. Sixteen provider price profiles are included out of the box.

Does Treasury call any model or network itself?

No. Treasury decides whether spend is allowed; it never makes the model call. The core is node-free and network-free: the forecast is local arithmetic and the prices are bundled data. Your code makes the provider call after authorize approves it, so provider keys and traffic never touch Treasury.

Does this work in Cloudflare Workers, Vercel Edge, Bun, or Deno?

Yes. The core is node-free and network-free. Import @takk/treasury or @takk/treasury/edge on any of those runtimes and the browser. Only @takk/treasury/node, the JSON file loaders, requires the Node standard library.

How does Treasury handle my data?

Treasury holds the budget you configure, the step estimates you pass to a forecast, and the prices it ships or you override, nothing else. It makes no outbound network calls at all; there are no model calls to make. With the file loaders, only the plan or price files you point it at are read from disk, and no provider credentials are ever held by Treasury.

What exactly does authorize decide?

Given a forecast total in micro-USD, authorize checks it against your per-request, per-task, and per-day ceilings and returns whether the spend is allowed and how much budget remains. It is a pre-flight gate: it runs before the call, so a spend that would breach a ceiling comes back allowed: false and never happens. Depletion events fire as a budget drains toward the line.

How is this different from Sakana Fugu?

Fugu is a closed orchestrator: it prices at the pool ceiling, its cost is unpredictable, which is its first criticism, it is a black box, cannot be self-hosted, and is blocked in the EU. Treasury is the opposite on every axis: cost is forecast and predictable, capped by a hard budget, transparent per step, self-hosted on your infrastructure, and EU-friendly.

Which providers and models does it price?

It ships 16 provider price profiles covering the major families from OpenAI, Anthropic, and Google, among others. Any model it does not ship a profile for you add with withPrices. Because pricing is just data, extending it to a new provider or a negotiated rate is a one-line override.

Where does the state live?

In-process memory by default: the budget windows and their spend, plus the prices in effect. For disk-backed input, load a plan or a price table from JSON with @takk/treasury/node. For an edge runtime, keep the running spend in your own KV store between invocations and rehydrate the budget from it.

How does it keep the prefix cache profitable?

The prefix-cache planner weighs the one-time write cost against the savings from reuse, across 16 price profiles and with 9 explicit cache-kill rules. It is guaranteed never to recommend a cache write that would not pay for itself, so you cache when it saves money and skip when it does not, instead of guessing at every write.

How do I verify a published version's provenance?

Every release is published with npm publish --provenance. Check the attestations with npm view @takk/treasury@<version> --json | jq .dist.attestations. The attestation links the tarball you installed to the GitHub Actions workflow that built it from a specific source commit.

What is the policy on breaking changes?

Strict SemVer 2.0.0, starting from 1.0.0. The binding stability surface is documented in SPEC.md section 5. Major bumps require a deprecation cycle; security fixes follow the disclosure flow in SECURITY.md.

Author

Built and maintained by David C Cavalcante.

David C Cavalcante

Founder, Takk Innovate Studio

Product Engineer, ML Engineer, LLM Engineer, LLM Architect, Massive Intelligence (IM) Researcher. Builder of the @takk family of NPM packages for Massive Intelligence (IM) native infrastructure.

Treasury is part of a planned family of NPM libraries targeting Massive Intelligence (IM) native infrastructure for 2026 to 2030, the cost and finance satellite of the @takk8is open multi-agent ecosystem. Adjacent research by the author covers systemic intelligence frameworks (MAIC, HIM, NHE) published independently of this codebase, with research notes on PhilPapers and PhilArchive linked from the repository README.

If Treasury kept the spend of a Massive Intelligence (IM) swarm under control for you this quarter, the most useful thing you can do is open a GitHub issue when you find an edge case the test suite missed. The runbook for releases, the threat model, and the contributor agreement all live in the repository.