Local task cost quick start
Track what each agent task costs — locally.
Measurement stands alone. Routing and anonymized outcome contribution are separate, optional steps — the @hokusai/costs package never calls Hokusai and never reads HOKUSAI_API_KEY.
Give it usage events (or Claude Code / Codex session files you name explicitly) and it returns a typed report with per-task, per-model, per-harness breakdowns. Charges and token-equivalent estimates stay labeled separately. Missing values stay null, never $0.
Install
The version is pinned exactly so your output matches the pricing revision in the examples below.
npm install @hokusai/costs@0.8.0Already using @hokusai/core?
@hokusai/costs@0.8.0 requires exactly @hokusai/core@0.8.0. Align your direct core dependency and any SDK adapters in the same change; all SDK packages use fixed versioning. The task-cost contract first shipped in core 0.5.0; that historical minimum is no reason to downgrade a newer install.
npm install @hokusai/core@0.8.0 @hokusai/costs@0.8.0See the versioning policy, release notes, and harness measurement guide.
Two-line quick start
Pass a harness that your code already emits usage events from — measureTask subscribes for the run and returns a typed cost report alongside your run’s result.
import { measureTask } from "@hokusai/costs"
const { result, cost } = await measureTask({ events: harness }, () => harness.run(task))Supported emitters: an on/off or addListener/removeListener EventEmitter, an EventTarget, or a sync/async iterable. The default event name is "usage".
When you need usage events
Automatic capture works only from usage events you pass, or from Claude Code / Codex session files you name explicitly. With neither available, call recordUsage yourself. If nothing was captured, the report returns coverage.status: "unavailable", totalUsd: null, and a no_usage_captured diagnostic. Hokusai never guesses.
Record manually
Use createTaskCostTracker when your harness owns the loop. Each recordUsage call takes a model id, a usage object (the fromAnthropicUsage / fromOpenAIUsage helpers map provider payloads), an optional provider-reported charge, and an optional stable event id so retries dedupe.
import {
createTaskCostTracker,
fromAnthropicUsage,
fromOpenAIUsage,
} from "@hokusai/costs"
const tracker = createTaskCostTracker({
taskId: "task-local-demo",
harness: "native",
})
// A known model with a provider-reported charge.
tracker.recordUsage({
model: "claude-sonnet-5",
usage: fromAnthropicUsage({ input_tokens: 4000, output_tokens: 900 }),
providerCostUsd: 0.0135,
costBasis: "per_token_api",
})
// A known model priced locally from the built-in table (an estimate).
tracker.recordUsage({
model: "gpt-5",
usage: fromOpenAIUsage({ prompt_tokens: 2000, completion_tokens: 300 }),
})
// An unknown model: cost stays null, never 0.
tracker.recordUsage({
model: "some-internal-model",
usage: { inputTokens: 1000, outputTokens: 200 },
})
const report = tracker.summary()
if (report.totalUsd !== null) throw new Error("unknown model must null the total")
if (!(report.estimatedUsd > 0)) throw new Error("expected a priced lower bound")
if (report.coverage.unknownModels[0] !== "some-internal-model") {
throw new Error("expected the unknown model to be called out")
}
Claude Code and Codex session files
If the agent is running inside Claude Code or Codex, name the session files explicitly: a non-empty list of session ids, the paths (or roots) to look in, and an inclusive time window. Session-file capture is Node-only; file paths and prompt text never enter the report (counts and model ids only).
Claude Code
const CLAUDE_CODE_SESSION_ID = "your-claude-code-session-id"
const CLAUDE_CODE_SESSION_PATH = "/absolute/path/to/your-claude-code-session.jsonl"
import { measureTask } from "@hokusai/costs"
const { cost } = await measureTask(
{
taskId: "task-claude-code-demo",
sessionFiles: {
harness: "claude-code",
sessionIds: [CLAUDE_CODE_SESSION_ID],
paths: [CLAUDE_CODE_SESSION_PATH],
window: {
startedAt: "2026-01-01T00:00:00Z",
endedAt: "2026-01-01T01:00:00Z",
},
},
},
() => "task-ran",
)
if (cost.source.sessionFileCount !== 1) {
throw new Error("expected one session file")
}
Codex
const CODEX_SESSION_ID = "your-codex-session-id"
const CODEX_SESSION_ROOT = "/absolute/path/to/your/codex/sessions"
import { measureTask } from "@hokusai/costs"
const { cost } = await measureTask(
{
taskId: "task-codex-demo",
sessionFiles: {
harness: "codex",
sessionIds: [CODEX_SESSION_ID],
roots: [CODEX_SESSION_ROOT],
window: {
startedAt: "2026-01-01T00:00:00Z",
endedAt: "2026-01-01T01:00:00Z",
},
},
},
() => "task-ran",
)
// coverage.status is "complete" | "partial" | "unavailable" | "known_zero".
// With no matching session files it is "unavailable" and totalUsd is null —
// Hokusai never guesses.
if (cost.coverage.status === "unavailable" && cost.totalUsd !== null) {
throw new Error("unavailable coverage must not carry a total")
}
Query your local ledger
Pass a ledger to measureTask or the tracker, and accepted records are persisted (the tracker needs an explicit await tracker.flush(); measureTask flushes for you). Ledger files are opened with 0600 permissions. Query by task, time window, or any combination of model, harness, backend, and source.
import { mkdtempSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import {
createTaskCostTracker,
fromAnthropicUsage,
fromOpenAIUsage,
} from "@hokusai/costs"
import {
createNodeFileLedgerStorage,
defaultLedgerHash,
openTaskCostLedger,
} from "@hokusai/costs/ledger/node"
const dir = mkdtempSync(join(tmpdir(), "hokusai-costs-ledger-"))
const ledger = await openTaskCostLedger({
storage: createNodeFileLedgerStorage({ path: join(dir, "task-cost.v1.jsonl") }),
hashFn: defaultLedgerHash,
})
const tracker = createTaskCostTracker({
taskId: "task-ledger-demo",
harness: "claude-code",
ledger,
})
tracker.recordUsage({
model: "claude-sonnet-5",
usage: fromAnthropicUsage({
input_tokens: 10000,
output_tokens: 2000,
cache_read_input_tokens: 1000,
}),
providerCostUsd: 0.045,
costBasis: "per_token_api",
})
tracker.recordUsage({
model: "gpt-5",
harness: "native",
usage: fromOpenAIUsage({ prompt_tokens: 4000, completion_tokens: 500 }),
})
tracker.recordUsage({
model: "some-internal-model",
usage: { inputTokens: 500, outputTokens: 100 },
})
await tracker.flush()
const summary = ledger.summarizeTask("task-ledger-demo")
const q = ledger.query({
taskId: "task-ledger-demo",
groupBy: ["model", "backend", "source"],
})
// `summary.byModel`, `byHarness`, `byBackend`, `bySource` ride alongside
// the raw `q.groups` so hosts can pick the shape that matches their UI.
console.log(JSON.stringify({ summary, groups: q.groups }, null, 2))
Sample output
What the ledger query above returns when the three recordUsage calls run against the released package. Amounts shown here are converted from the ledger’s integer meteredMicros / tokenEquivalentMicros into USD for display.
| Task | Model | Backend | Source | Basis | Amount (USD) |
|---|---|---|---|---|---|
| task-ledger-demo | claude-sonnet-5 | anthropic | provider_reported | charge | $0.0450 |
| task-ledger-demo | gpt-5 | openai | local_estimate | estimate | ≈ $0.0100 |
| task-ledger-demo | some-internal-model | unknown | none | missing | — |
Charges, estimates, and missing values
- Charge. A provider-reported amount in USD. Shown in the report as
actualUsdand in the ledger asmeteredMicros. - Token-equivalent estimate. Priced locally from a dated built-in table (or your own overrides) and reported as
estimatedUsd. API-equivalent resource cost supports comparison across subscriptions, discounts, and subsidies. Preserve token evidence and price provenance regardless of how execution is funded; no payment classification is needed. - Missing. An unknown model, an unreported counter, or an unpriceable usage shape stays
null, never$0.totalUsdisnullunless every captured event resolved; the priced subtotal is a lower bound andcoverage.unknownModelsnames what was unpriceable.
totalUsd resolves each event by preferring a provider-reported charge over its token-derived estimate. It can therefore include both sources; keep source, pricing, and coverage alongside every amount. Partial actualUsd and estimatedUsd subtotals are labeled lower bounds. Unsupported pricing dimensions remain unpriced.
What stays local
Kept
- Token counts and USD amounts.
- Model ids, harness names, and other enum values.
- Timestamps and task / session / turn / event ids you supply.
Never kept
- Prompts and transcript text.
- File paths, directory names, and git branches.
- Credentials, account ids, and user identifiers.
Behavior: no network calls, HOKUSAI_API_KEY is not read, and nothing is written to disk unless you open a ledger. Ledger files live at the path you give and are created with mode 0600.
Optional: share with Hokusai
Measure and inspect locally without an API key or network call. Routing and contribution are optional. If you opt in, your harness makes a separate, explicit network submission of an anonymized outcome row. Pass the whole measured report as cost to retain tokens, coverage, and pricing provenance, including partial evidence. Server repricing and trust determine cost-label eligibility; a scalar alone guarantees neither training eligibility nor rewards. Supply a budget and completion outcome and keep the executed model and route linkage. Missing totals stay null, never 0. Your harness runs the recommended model and records any deviation.
This optional example also uses the published router package at the same version. Configure its API key only when choosing routing.
npm install @hokusai/router@0.8.0import { measureTask } from "@hokusai/costs"
import { route } from "@hokusai/router"
// Supply your own event-emitting harness; it executes the selected model.
declare const harness: {
on(event: string, listener: (...args: any[]) => void): unknown
off(event: string, listener: (...args: any[]) => void): unknown
run(task: string, model: string): Promise<{ ok: boolean }>
}
declare const task: string
// Routing is a separate network action and needs a Hokusai API key.
const decision = await route({
task,
availableModels: ["claude-sonnet-4-6", "gpt-5"],
maxCostUsd: 1,
})
const executedModel = decision.model
const { result, cost } = await measureTask({ events: harness }, () =>
harness.run(task, executedModel),
)
console.log(result, cost.totalUsd, cost.coverage.status) // Inspect locally first.
// Separate, explicit network submission. Retain partial token/coverage evidence.
// The server decides eligibility; a scalar amount alone is no guarantee.
if (process.env.HOKUSAI_OUTCOME_OPT_IN === "true") {
await route.reportOutcome({
correlationId: decision.correlationId,
model: executedModel,
status: result.ok ? "succeeded" : "failed",
cost,
})
}
// Report before starting the next route with this single-flight helper.
Usage mappers and exports
Use fromAnthropicUsage for Anthropic Messages usage and fromOpenAIUsage for OpenAI API usage. OpenAI input includes cached reads; the mapper separates them once. Reasoning is informational within output and must not be billed twice. Missing counters stay null.
In the verified 0.8.0 release, fromCodexUsage and @hokusai/core/token-prices are unavailable. The Codex session-file example above is supported; do not map Codex CLI payloads with fromOpenAIUsage. Upcoming fromCodexUsage normalizes inclusive input and cached reads/writes once, clamps underflow with an optional count-only codex_cache_exceeds_input diagnostic, preserves missing or malformed counters as null, and keeps reasoning within output. Difference cumulative counters before mapping.
The upcoming generated hokusai_token_prices/v1 artifact is intended as the shared SDK/server rate source, with explicit unpriced dimensions, per-row source/date and version/hash provenance. It is not an export in this pin, and no live server rollout is claimed. Follow the SDK release notes before adopting new exports; retain historical snapshots when updating rates.
Missing an export?
Run npm ls @hokusai/core @hokusai/costs and compare installed versions, available exports, and your lockfile with the selected release. A missing aggregateTaskCost usually means core before 0.5.0 or a stale install. Align direct core, costs, and adapters, update the lockfile with your package manager, then reinstall with npm ci or pnpm install --frozen-lockfile. Reinstalling 0.8.0 cannot add unpublished exports. Hosts supporting older SDKs may use lazy loading or feature detection; surface unavailable measurement instead of silently dropping usage.