cloud-ai: the Cloud's own mind reads every mind's OpenAI-direct spend by day (#1)
jonas, 2026-11-28 16:52 UTC · cd0b1dd9f1570c9372bad735070ed4e3be473333 · parent 662bdf0
7 files changed
- M internal-packages/cloud-ai/README.md
- M internal-packages/cloud-ai/src/ai-target.ts
- M internal-packages/cloud-ai/src/connect.ts
- M internal-packages/cloud-ai/src/ledger.ts
- A internal-packages/cloud-ai/src/usage-by-mind.test.ts
- M internal-packages/cloud-ai/src/usage.ts
- M internal-packages/cloud-ai/src/worker.ts
M internal-packages/cloud-ai/README.md
@@ -15,6 +15,12 @@ 3. **Unified per-customer spend reporting (`await itx.iterateCloud.usage()`):** Combines Cloudflare GraphQL `aiGatewayRequestsAdaptiveGroups` (`aiGateway`) with `CloudUsageLedger` (`openAi`: `byCategory.voice` + `byCategory.transcription` + `byModel`) into a single USD and token/audio-second report per `mindId`. +4. **Every mind's OpenAI-direct spend, for the Cloud's own mind alone (`await itx.iterateCloud.openAiUsageByMind({ since, until, minds? })`):** + Voice and transcription cost by UTC day, mind, kind and model (`byDay`), with a sum for each mind (`byMind`). The window is at most 31 days. It holds no AI Gateway spend: Cloudflare's analytics answer that by mind. + - **Who may call:** the mind whose proven id is the Worker's `MIND_ID` and that wrote from `MIND_HOSTNAME`. Every other mind is refused, a house account too. A Worker with no `MIND_ID` refuses everyone. + - **Which minds it reads:** `CloudUsageLedger` has one shard for each mind, and a Worker cannot list its Durable Objects. So one more shard, `index:minds`, lists the minds that have a ledger. A mind's shard tells it of itself on a write and on the mind's own `usage()`. A ledger from before 28 Nov 2026 is in the list from its mind's next use; until then, name the mind's id in `minds`. + - **An open live session** counts on the UTC day that it began, to now and at most to OpenAI's hour. + ## Connecting an Enrolled Mind ```ts
M internal-packages/cloud-ai/src/ai-target.ts
@@ -2,6 +2,7 @@ import type { ItxWebSearchAnswer } from "iterate/api"; import { codedError } from "iterate/lib"; import { httpFailureKind } from "iterate/platform-retry"; +import { isMindId } from "iterate/signed"; import { z } from "zod"; import type { AuthenticatedMind } from "./auth.ts"; import { createInMemoryOpenAiUsageStore, type OpenAiUsageStore } from "./ledger.ts"; @@ -10,6 +11,9 @@ emptyGatewaySpendReport, type GatewaySpendReport, type IterateCloudUsageReport, + type OpenAiUsageByMindInput, + type OpenAiUsageByMindReport, + openAiUsageByMindReport, queryGatewaySpend, resolveUsageWindow, type UsageWindowInput, @@ -37,6 +41,9 @@ fetcher?: (request: Request) => Promise<Response>; }; openAiUsageStore?: OpenAiUsageStore; + /** THE CLOUD'S OWN MIND (`MIND_ID` and `MIND_HOSTNAME` of the Worker): the one mind that reads + * every mind's spend (`IterateCloudApi.openAiUsageByMind`). With no id, no mind does. */ + ownMind?: { id?: string; hostname?: string }; }; /** Builds the AI Gateway `metadata` object for an authenticated mind. Cloudflare AI Gateway keeps @@ -168,6 +175,34 @@ }), ]); return combineCloudUsageReports(this.#caller, aiGateway, openAi); + } + + /** EVERY MIND'S OPENAI-DIRECT SPEND BY UTC DAY (voice and transcription on the Cloud's own + * OpenAI key), FOR THE CLOUD'S OWN MIND ALONE: its id is `ownMind.id`, proven by the caller's + * signed statement, and it wrote from `ownMind.hostname`. Any other mind is refused, a house + * account too: `usage()` answers a mind its own spend. The window is `usage()`'s, at most 31 + * days. `minds` names ids to read beside the minds that the ledger lists. */ + async openAiUsageByMind(input?: OpenAiUsageByMindInput): Promise<OpenAiUsageByMindReport> { + const own = this.#deps.ownMind; + const isOwnMind = + Boolean(own?.id) && + this.#caller.mindId === own?.id && + (!own.hostname || this.#caller.mindSlug === own.hostname); + if (!isOwnMind) { + throw codedError("INVALID_INPUT", "only iterate Cloud's own mind reads every mind's usage"); + } + const given = input?.minds ?? []; + if (!Array.isArray(given) || given.length > 200 || !given.every((id) => isMindId(id))) { + throw codedError("INVALID_INPUT", "`minds` must be at most 200 mind ids"); + } + const resolved = resolveUsageWindow(input); + const store = this.#deps.openAiUsageStore || createInMemoryOpenAiUsageStore(); + const byDay = await store.queryUsageByDay({ + sinceMs: resolved.sinceMs, + untilMs: resolved.untilMs, + mindIds: given, + }); + return openAiUsageByMindReport(resolved, byDay); } get ai(): CloudAiTarget {
M internal-packages/cloud-ai/src/connect.ts
@@ -1,7 +1,13 @@ import type { ItxWebSearchAnswer, RewriteRuleConfigured, SecretProxy } from "iterate/api"; import type { StreamEventInput } from "iterate/stream/processor"; import type { CloudGatewayRunOptions } from "./ai-target.ts"; -import type { GatewaySpendReport, IterateCloudUsageReport, UsageWindowInput } from "./usage.ts"; +import type { + GatewaySpendReport, + IterateCloudUsageReport, + OpenAiUsageByMindInput, + OpenAiUsageByMindReport, + UsageWindowInput, +} from "./usage.ts"; export interface IterateCloudAiClient { run(model: string, inputs: Record<string, unknown>, options?: AiOptions): Promise<unknown>; @@ -32,6 +38,9 @@ /** Unified per-mind usage & USD spend across BOTH Cloudflare AI Gateway AND Iterate Cloud's * lent OpenAI API key for realtime voice & transcription. */ usage(window?: UsageWindowInput): Promise<IterateCloudUsageReport>; + /** Every mind's OpenAI-direct spend (voice, transcription) by UTC day. The Cloud answers it to + * its own mind alone and refuses every other mind. */ + openAiUsageByMind(input?: OpenAiUsageByMindInput): Promise<OpenAiUsageByMindReport>; readonly ai: IterateCloudAiClient; }
M internal-packages/cloud-ai/src/ledger.ts
@@ -69,6 +69,28 @@ byModel: OpenAiDirectModelRow[]; }; +/** One UTC day of one mind's OpenAI-direct spend, for one kind and model. */ +export type OpenAiDayRow = { + /** The UTC day, `YYYY-MM-DD`. */ + day: string; + mindId: string; + mindSlug: string; + kind: OpenAiDirectKind; + model: string; + requests: number; + costUsd: number; + audioSeconds: number; + tokensIn: number; + tokensOut: number; +}; + +/** The most minds that one read of every mind's ledger asks (a Worker's subrequest limit bounds it). */ +export const MAX_LEDGER_MINDS = 500; + +/** The name of the ledger's one shard that lists the minds with a ledger. A mind's shard is named + * by its id (64 hex characters), so no mind has this name. */ +const LEDGER_INDEX_NAME = "index:minds"; + export type OpenWebRtcSessionInput = { sessionId: string; mindId: string; @@ -97,6 +119,15 @@ untilMs: number; nowMs?: number; }): Promise<OpenAiDirectSpendReport>; + /** EVERY MIND'S SPEND BY UTC DAY: the minds that the ledger lists, and `mindIds` beside them (a + * mind whose last use is older than the list). Only the Cloud's own mind is answered this + * (`IterateCloudApi.openAiUsageByMind`). */ + queryUsageByDay(input: { + sinceMs: number; + untilMs: number; + nowMs?: number; + mindIds?: string[]; + }): Promise<OpenAiDayRow[]>; } export function roundUsd(usd: number): number { @@ -348,6 +379,84 @@ }; } +const dayOf = (ms: number) => new Date(ms).toISOString().slice(0, 10); + +/** The rows of `[sinceMs, untilMs)` by UTC day, mind, kind and model. A row is on the day that it + * began. A live session that nobody closed counts on its start day too, to `nowMs` and at most + * to OpenAI's hour, as `aggregateUsageRows` prices it; unlike there, one that began before + * `sinceMs` is on no day of the window. */ +function dayRowsOf(input: { + sinceMs: number; + untilMs: number; + nowMs: number; + events: Iterable<StoredUsageRow>; + sessions: Iterable<StoredLiveSession>; +}): OpenAiDayRow[] { + const rows = new Map<string, OpenAiDayRow>(); + const add = ( + atMs: number, + row: Omit<OpenAiDayRow, "day" | "tokensIn" | "tokensOut"> & { + tokensIn?: number; + tokensOut?: number; + }, + ) => { + if (atMs < input.sinceMs || atMs >= input.untilMs) return; + const day = dayOf(atMs); + const key = `${day}:${row.mindId}:${row.kind}:${row.model}`; + const kept = rows.get(key); + if (!kept) { + rows.set(key, { day, ...row, tokensIn: row.tokensIn ?? 0, tokensOut: row.tokensOut ?? 0 }); + return; + } + kept.requests += row.requests; + kept.costUsd = roundUsd(kept.costUsd + row.costUsd); + kept.audioSeconds = Math.round((kept.audioSeconds + row.audioSeconds) * 1000) / 1000; + kept.tokensIn += row.tokensIn ?? 0; + kept.tokensOut += row.tokensOut ?? 0; + // the newest name that the mind wrote from + kept.mindSlug = row.mindSlug || kept.mindSlug; + }; + + for (const event of input.events) { + add(event.createdAtMs, { + mindId: event.mindId, + mindSlug: event.mindSlug, + kind: event.kind, + model: event.model, + requests: event.requests, + costUsd: event.costUsd, + audioSeconds: event.audioSeconds, + tokensIn: event.tokensIn, + tokensOut: event.tokensOut, + }); + } + for (const session of input.sessions) { + if (session.endedAtMs !== null) continue; + const endMs = Math.min(input.nowMs, session.startedAtMs + MAX_LIVE_SESSION_SECONDS * 1000); + const seconds = Math.max(0, (endMs - session.startedAtMs) / 1000); + add(session.startedAtMs, { + mindId: session.mindId, + mindSlug: session.mindSlug, + kind: "voice", + model: session.model, + requests: 1, + costUsd: costOfLiveVoiceSeconds(seconds), + audioSeconds: seconds, + }); + } + return sortDayRows([...rows.values()]); +} + +function sortDayRows(rows: OpenAiDayRow[]): OpenAiDayRow[] { + return rows.sort( + (left, right) => + left.day.localeCompare(right.day) || + left.mindId.localeCompare(right.mindId) || + left.kind.localeCompare(right.kind) || + left.model.localeCompare(right.model), + ); +} + /** In-memory `OpenAiUsageStore` used by unit tests and single-isolate local dev when no * `USAGE_LEDGER` Durable Object binding is configured. */ export function createInMemoryOpenAiUsageStore(): OpenAiUsageStore { @@ -444,13 +553,34 @@ }), ); }, + + // one map holds every mind's rows, so `mindIds` adds nothing here + queryUsageByDay({ sinceMs, untilMs, nowMs = Date.now() }) { + return Promise.resolve( + dayRowsOf({ + sinceMs, + untilMs, + nowMs, + events: events.values(), + sessions: sessions.values(), + }), + ); + }, }; } +type LedgerEnv = { USAGE_LEDGER?: DurableObjectNamespace<CloudUsageLedger> }; + /** SQLite-backed Durable Object storing per-mind OpenAI voice & transcription usage, sharded by - * `mindId` (`USAGE_LEDGER.idFromName(mindId)`) so each mind's ledger is physically isolated. */ -export class CloudUsageLedger extends DurableObject { + * `mindId` (`USAGE_LEDGER.idFromName(mindId)`) so each mind's ledger is physically isolated. + * + * ONE MORE SHARD, `LEDGER_INDEX_NAME`, LISTS THE MINDS THAT HAVE A LEDGER (`ledger_minds`), for + * the read of every mind (`queryUsageByDay` of the store). A mind's shard tells it of itself + * (`#announce`) once each time that it wakes, on a write and on the mind's own read. So a ledger + * that was written before the list existed is in it from its mind's next use. */ +export class CloudUsageLedger extends DurableObject<LedgerEnv> { #initialized = false; + #announced = false; #ensureSchema(): SqlStorage { // `DurableObject.ctx` in Workers provides `storage.sql` on SQLite-backed classes. @@ -482,14 +612,67 @@ ended_at_ms INTEGER, settled_cost_usd REAL ); + CREATE TABLE IF NOT EXISTS ledger_minds ( + mind_id TEXT PRIMARY KEY, + mind_slug TEXT NOT NULL, + first_seen_ms INTEGER NOT NULL, + last_seen_ms INTEGER NOT NULL + ); `); this.#initialized = true; } return sql; } + /** Tell the list of minds that this mind has a ledger. It holds up no write: a failure is + * logged, and the next call tries again. */ + #announce(mind: { mindId: string; mindSlug: string }): void { + const namespace = this.env?.USAGE_LEDGER; + if (this.#announced || !namespace) return; + this.#announced = true; + const told = namespace + .get(namespace.idFromName(LEDGER_INDEX_NAME)) + .registerMind(mind) + .catch((error: unknown) => { + this.#announced = false; + console.error({ + event: "cloud-ai.ledger-announce-failed", + mindId: mind.mindId, + error: String((error as Error)?.message ?? error).slice(0, 200), + }); + }); + (this.ctx as DurableObjectState).waitUntil(told as Promise<unknown>); + } + + /** On the list's shard alone: note a mind that has a ledger. */ + registerMind(mind: { mindId: string; mindSlug: string }): void { + const sql = this.#ensureSchema(); + const now = Date.now(); + sql.exec( + `INSERT INTO ledger_minds (mind_id, mind_slug, first_seen_ms, last_seen_ms) + VALUES (?, ?, ?, ?) + ON CONFLICT (mind_id) DO UPDATE SET mind_slug = excluded.mind_slug, last_seen_ms = excluded.last_seen_ms`, + mind.mindId, + mind.mindSlug, + now, + now, + ); + } + + /** On the list's shard alone: the minds that have a ledger, the newest use first. */ + listMinds(): { mindId: string; mindSlug: string }[] { + const sql = this.#ensureSchema(); + return [ + ...sql.exec<{ mind_id: string; mind_slug: string }>( + "SELECT mind_id, mind_slug FROM ledger_minds ORDER BY last_seen_ms DESC LIMIT ?", + MAX_LEDGER_MINDS, + ), + ].map((row) => ({ mindId: row.mind_id, mindSlug: row.mind_slug })); + } + recordUsage(entry: OpenAiUsageEventInput): void { const sql = this.#ensureSchema(); + this.#announce(entry); const id = entry.id || crypto.randomUUID(); sql.exec( `INSERT OR IGNORE INTO openai_usage_events ( @@ -514,6 +697,7 @@ openWebRtcSession(input: OpenWebRtcSessionInput): void { const sql = this.#ensureSchema(); + this.#announce(input); sql.exec( `INSERT OR REPLACE INTO openai_live_sessions ( session_id, mind_id, mind_slug, model, started_at_ms, ended_at_ms, settled_cost_usd @@ -584,16 +768,9 @@ return { status: "closed", audioSeconds, costUsd }; } - queryUsage(input: { - mindId: string; - mindSlug: string; - sinceMs: number; - untilMs: number; - nowMs?: number; - }): OpenAiDirectSpendReport { - const sql = this.#ensureSchema(); - const eventRows = [ - ...sql.exec<{ + #eventsOf(where: string, ...bindings: (string | number)[]): StoredUsageRow[] { + return [ + ...this.#ensureSchema().exec<{ id: string; mind_id: string; mind_slug: string; @@ -607,12 +784,7 @@ tokens_in: number; tokens_out: number; client_secret_grant: number; - }>( - "SELECT * FROM openai_usage_events WHERE mind_id = ? AND created_at_ms >= ? AND created_at_ms < ?", - input.mindId, - input.sinceMs, - input.untilMs, - ), + }>(`SELECT * FROM openai_usage_events WHERE ${where}`, ...bindings), ].map((row): StoredUsageRow => ({ id: row.id, mindId: row.mind_id, @@ -628,9 +800,11 @@ tokensOut: row.tokens_out, isClientSecretGrant: row.client_secret_grant === 1, })); + } - const openSessions = [ - ...sql.exec<{ + #openSessionsOf(where: string, ...bindings: (string | number)[]): StoredLiveSession[] { + return [ + ...this.#ensureSchema().exec<{ session_id: string; mind_id: string; mind_slug: string; @@ -638,10 +812,7 @@ started_at_ms: number; ended_at_ms: number | null; settled_cost_usd: number | null; - }>( - "SELECT * FROM openai_live_sessions WHERE mind_id = ? AND ended_at_ms IS NULL", - input.mindId, - ), + }>(`SELECT * FROM openai_live_sessions WHERE ended_at_ms IS NULL AND ${where}`, ...bindings), ].map((row): StoredLiveSession => ({ sessionId: row.session_id, mindId: row.mind_id, @@ -651,17 +822,50 @@ endedAtMs: row.ended_at_ms, settledCostUsd: row.settled_cost_usd, })); + } + queryUsage(input: { + mindId: string; + mindSlug: string; + sinceMs: number; + untilMs: number; + nowMs?: number; + }): OpenAiDirectSpendReport { + this.#announce(input); return aggregateUsageRows({ mindId: input.mindId, mindSlug: input.mindSlug, sinceMs: input.sinceMs, untilMs: input.untilMs, nowMs: input.nowMs ?? Date.now(), - events: eventRows, - sessions: openSessions, + events: this.#eventsOf( + "mind_id = ? AND created_at_ms >= ? AND created_at_ms < ?", + input.mindId, + input.sinceMs, + input.untilMs, + ), + sessions: this.#openSessionsOf("mind_id = ?", input.mindId), }); } + + /** This shard's rows by UTC day (`dayRowsOf`): one mind's, because a shard holds one mind. */ + queryUsageByDay(input: { sinceMs: number; untilMs: number; nowMs?: number }): OpenAiDayRow[] { + return dayRowsOf({ + sinceMs: input.sinceMs, + untilMs: input.untilMs, + nowMs: input.nowMs ?? Date.now(), + events: this.#eventsOf( + "created_at_ms >= ? AND created_at_ms < ?", + input.sinceMs, + input.untilMs, + ), + sessions: this.#openSessionsOf( + "started_at_ms >= ? AND started_at_ms < ?", + input.sinceMs, + input.untilMs, + ), + }); + } } /** Wraps a `DurableObjectNamespace<CloudUsageLedger>` as an `OpenAiUsageStore`, sharding each @@ -682,6 +886,24 @@ }, async queryUsage(input) { return await stubFor(input.mindId).queryUsage(input); + }, + async queryUsageByDay({ sinceMs, untilMs, nowMs, mindIds = [] }) { + const listed = await stubFor(LEDGER_INDEX_NAME).listMinds(); + const ids = [...new Set([...listed.map((mind) => mind.mindId), ...mindIds])].slice( + 0, + MAX_LEDGER_MINDS, + ); + const rows: OpenAiDayRow[] = []; + // 25 shards at a time: a Worker holds 6 connections open, and the rest wait in line + for (let at = 0; at < ids.length; at += 25) { + const answers = await Promise.all( + ids + .slice(at, at + 25) + .map((mindId) => stubFor(mindId).queryUsageByDay({ sinceMs, untilMs, nowMs })), + ); + for (const answer of answers) rows.push(...answer); + } + return sortDayRows(rows); }, }; }
A internal-packages/cloud-ai/src/usage-by-mind.test.ts
@@ -0,0 +1,336 @@ +import { MessageChannel } from "node:worker_threads"; +import { DatabaseSync } from "node:sqlite"; +import { newMessagePortRpcSession } from "capnweb"; +import { expect, test } from "vitest"; +import { type CloudAiDeps, IterateCloudApi } from "./ai-target.ts"; +import type { IterateCloudClientApi } from "./connect.ts"; +import { + CloudUsageLedger, + createInMemoryOpenAiUsageStore, + durableObjectUsageStore, + type OpenAiUsageStore, +} from "./ledger.ts"; + +const CLOUD_MIND = { id: "c".repeat(64), hostname: "iterate.iterate.com" }; +const MIND_A = { mindId: "a".repeat(64), mindSlug: "iterate.acme.example" }; +const MIND_B = { mindId: "b".repeat(64), mindSlug: "iterate.blifto.example" }; +const WINDOW = { since: "2026-11-20T00:00:00.000Z", until: "2026-11-23T00:00:00.000Z" }; +const at = (iso: string) => Date.parse(iso); + +function clientOf( + caller: { mindId: string; mindSlug: string }, + deps: Partial<CloudAiDeps> & { openAiUsageStore: OpenAiUsageStore }, +) { + const { port1, port2 } = new MessageChannel(); + newMessagePortRpcSession( + port1 as unknown as MessagePort, + new IterateCloudApi( + { ...caller, expiresAtMs: Date.now() + 60_000 }, + { ai: {} as Ai, gatewayId: "iterate-cloud", ...deps }, + ), + ); + const client = newMessagePortRpcSession<IterateCloudClientApi>(port2 as unknown as MessagePort); + return { + client, + [Symbol.dispose]() { + port1.close(); + port2.close(); + }, + }; +} + +async function fill(store: OpenAiUsageStore) { + await store.recordUsage({ + ...MIND_A, + id: "a1", + createdAtMs: at("2026-11-20T10:00:00.000Z"), + kind: "transcription", + route: "POST /v1/audio/transcriptions", + model: "whisper-1", + costUsd: 0.006, + audioSeconds: 60, + }); + await store.recordUsage({ + ...MIND_A, + id: "a2", + createdAtMs: at("2026-11-20T23:59:59.999Z"), + kind: "transcription", + route: "POST /v1/audio/transcriptions", + model: "whisper-1", + costUsd: 0.012, + audioSeconds: 120, + }); + await store.recordUsage({ + ...MIND_A, + id: "a3", + createdAtMs: at("2026-11-21T00:00:00.000Z"), + kind: "voice", + route: "GET /v1/realtime", + model: "gpt-realtime", + costUsd: 0.5, + audioSeconds: 30, + tokensIn: 100, + tokensOut: 50, + }); + // outside the window, on each side + await store.recordUsage({ + ...MIND_A, + id: "a4", + createdAtMs: at("2026-11-19T23:59:59.999Z"), + kind: "voice", + route: "GET /v1/realtime", + model: "gpt-realtime", + costUsd: 9, + }); + await store.recordUsage({ + ...MIND_B, + id: "b1", + createdAtMs: at("2026-11-23T00:00:00.000Z"), + kind: "voice", + route: "GET /v1/realtime", + model: "gpt-realtime", + costUsd: 9, + }); + // a live session of 30 seconds that was closed, and one that nobody closed + await store.openWebRtcSession({ + ...MIND_B, + sessionId: "closed", + model: "gpt-live-1", + startedAtMs: at("2026-11-21T08:00:00.000Z"), + }); + await store.closeWebRtcSession({ + sessionId: "closed", + mindId: MIND_B.mindId, + endedAtMs: at("2026-11-21T08:00:30.000Z"), + }); + await store.openWebRtcSession({ + ...MIND_B, + sessionId: "open", + model: "gpt-live-1", + startedAtMs: at("2026-11-22T23:59:00.000Z"), + }); +} + +const EXPECTED_DAYS = [ + { + day: "2026-11-20", + ...MIND_A, + kind: "transcription", + model: "whisper-1", + requests: 2, + costUsd: 0.018, + audioSeconds: 180, + tokensIn: 0, + tokensOut: 0, + }, + { + day: "2026-11-21", + ...MIND_A, + kind: "voice", + model: "gpt-realtime", + requests: 1, + costUsd: 0.5, + audioSeconds: 30, + tokensIn: 100, + tokensOut: 50, + }, + { + day: "2026-11-21", + ...MIND_B, + kind: "voice", + model: "gpt-live-1", + requests: 1, + costUsd: 0.025, + audioSeconds: 30, + tokensIn: 0, + tokensOut: 0, + }, + // the open session: an hour at most, on the day that it began + { + day: "2026-11-22", + ...MIND_B, + kind: "voice", + model: "gpt-live-1", + requests: 1, + costUsd: 3, + audioSeconds: 3600, + tokensIn: 0, + tokensOut: 0, + }, +]; + +test("the Cloud's own mind reads every mind's OpenAI-direct spend by UTC day", async () => { + const store = createInMemoryOpenAiUsageStore(); + await fill(store); + using own = clientOf( + { mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname }, + { openAiUsageStore: store, ownMind: CLOUD_MIND }, + ); + + const report = await own.client.openAiUsageByMind(WINDOW); + expect(report.byDay).toEqual(EXPECTED_DAYS); + expect(report).toMatchObject({ + since: WINDOW.since, + until: WINDOW.until, + totalRequests: 5, + totalCostUsd: 3.543, + totalAudioSeconds: 3840, + byMind: [ + { ...MIND_B, requests: 2, costUsd: 3.025, audioSeconds: 3630 }, + { ...MIND_A, requests: 3, costUsd: 0.518, audioSeconds: 210 }, + ], + }); +}); + +test("any other mind is refused every mind's spend, and so is everyone when the Cloud names no own mind", async () => { + const store = createInMemoryOpenAiUsageStore(); + await fill(store); + const refusal = "only iterate Cloud's own mind reads every mind's usage"; + + using customer = clientOf(MIND_A, { openAiUsageStore: store, ownMind: CLOUD_MIND }); + await expect(customer.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal); + + // the own mind's id from another hostname + using elsewhere = clientOf( + { mindId: CLOUD_MIND.id, mindSlug: "iterate.other.example" }, + { openAiUsageStore: store, ownMind: CLOUD_MIND }, + ); + await expect(elsewhere.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal); + + // a Worker with no MIND_ID: a hostname alone names nobody + using unnamed = clientOf( + { mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname }, + { openAiUsageStore: store, ownMind: { hostname: CLOUD_MIND.hostname } }, + ); + await expect(unnamed.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal); + using bare = clientOf( + { mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname }, + { openAiUsageStore: store }, + ); + await expect(bare.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal); + + using own = clientOf( + { mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname }, + { openAiUsageStore: store, ownMind: CLOUD_MIND }, + ); + await expect(own.client.openAiUsageByMind({ ...WINDOW, minds: ["not-an-id"] })).rejects.toThrow( + "`minds` must be at most 200 mind ids", + ); + await expect( + own.client.openAiUsageByMind({ since: "2026-10-01T00:00:00.000Z", until: WINDOW.until }), + ).rejects.toThrow("at most 31 days"); +}); + +/** The ledger's Durable Objects on Node's SQLite: each name is one object with a database of its + * own, as `idFromName` gives each mind a shard. `listed: false` builds a shard with no binding + * to the namespace, as a ledger that was written before the list of minds existed. */ +function ledgerNamespace() { + const shards = new Map<string, CloudUsageLedger>(); + const held: Promise<unknown>[] = []; + const unlisted = new Set<string>(); + const namespace = { + idFromName: (name: string) => name, + get(name: string) { + let shard = shards.get(name); + if (!shard) { + const db = new DatabaseSync(":memory:"); + const sql = { + exec(query: string, ...bindings: (string | number | null)[]) { + if (bindings.length === 0 && query.trim().split(";").filter((s) => s.trim()).length > 1) { + db.exec(query); + return []; + } + return db.prepare(query).all(...bindings); + }, + }; + const ctx = { storage: { sql }, waitUntil: (promise: Promise<unknown>) => held.push(promise) }; + const Ledger = CloudUsageLedger as unknown as new ( + ctx: unknown, + env: unknown, + ) => CloudUsageLedger; + shard = new Ledger(ctx, unlisted.has(name) ? {} : { USAGE_LEDGER: namespace }); + shards.set(name, shard); + } + const target = shard as unknown as Record<string, (...args: unknown[]) => unknown>; + // a stub's call answers a promise + return new Proxy( + {}, + { get: (_, method: string) => async (...args: unknown[]) => target[method]!(...args) }, + ); + }, + }; + return { + namespace: namespace as unknown as DurableObjectNamespace<CloudUsageLedger>, + names: () => [...shards.keys()].sort(), + unlisted, + settle: async () => { + while (held.length) await held.pop(); + }, + }; +} + +test("the Durable Object ledger lists its minds and answers every shard's days", async () => { + const ledger = ledgerNamespace(); + const store = durableObjectUsageStore(ledger.namespace); + await fill(store); + await ledger.settle(); + expect(ledger.names()).toEqual([MIND_A.mindId, MIND_B.mindId, "index:minds"]); + + const nowMs = at("2026-11-25T00:00:00.000Z"); + const window = { sinceMs: at(WINDOW.since), untilMs: at(WINDOW.until), nowMs }; + expect(await store.queryUsageByDay(window)).toEqual(EXPECTED_DAYS); + + // an open session costs what has run of it + const early = await store.queryUsageByDay({ ...window, nowMs: at("2026-11-22T23:59:30.000Z") }); + expect(early.at(-1)).toMatchObject({ day: "2026-11-22", costUsd: 0.025, audioSeconds: 30 }); + + // a mind's own read is unchanged by the list + expect(await store.queryUsage({ ...MIND_A, ...window })).toMatchObject({ + totalRequests: 3, + totalCostUsd: 0.518, + }); +}); + +test("a ledger from before the list is read when its mind is named, and is listed from its mind's next use", async () => { + const ledger = ledgerNamespace(); + const old = { mindId: "d".repeat(64), mindSlug: "iterate.old.example" }; + ledger.unlisted.add(old.mindId); + const store = durableObjectUsageStore(ledger.namespace); + await store.recordUsage({ + ...old, + id: "d1", + createdAtMs: at("2026-11-20T10:00:00.000Z"), + kind: "transcription", + route: "POST /v1/audio/transcriptions", + model: "whisper-1", + costUsd: 0.006, + audioSeconds: 60, + }); + await ledger.settle(); + const window = { sinceMs: at(WINDOW.since), untilMs: at(WINDOW.until) }; + expect(await store.queryUsageByDay(window)).toEqual([]); + expect(await store.queryUsageByDay({ ...window, mindIds: [old.mindId] })).toMatchObject([ + { day: "2026-11-20", ...old, requests: 1, costUsd: 0.006 }, + ]); + + // the Cloud's own mind names it through the call + using own = clientOf( + { mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname }, + { openAiUsageStore: store, ownMind: CLOUD_MIND }, + ); + expect(await own.client.openAiUsageByMind({ ...WINDOW, minds: [old.mindId] })).toMatchObject({ + totalCostUsd: 0.006, + byMind: [{ ...old, requests: 1 }], + }); +}); + +test("a shard tells the list of its mind on the mind's own read", async () => { + const ledger = ledgerNamespace(); + const store = durableObjectUsageStore(ledger.namespace); + const window = { sinceMs: at(WINDOW.since), untilMs: at(WINDOW.until) }; + await store.queryUsage({ ...MIND_A, ...window }); + await store.queryUsage({ ...MIND_A, ...window }); + await ledger.settle(); + const index = ledger.namespace.get(ledger.namespace.idFromName("index:minds")); + expect(await index.listMinds()).toEqual([MIND_A]); +});
M internal-packages/cloud-ai/src/usage.ts
@@ -1,6 +1,6 @@ import { codedError } from "iterate/lib"; import { z } from "zod"; -import { type OpenAiDirectSpendReport, roundUsd } from "./ledger.ts"; +import { type OpenAiDayRow, type OpenAiDirectSpendReport, roundUsd } from "./ledger.ts"; const DEFAULT_WINDOW_MS = 24 * 60 * 60_000; const MAX_WINDOW_MS = 31 * 24 * 60 * 60_000; @@ -98,6 +98,70 @@ aiGateway: GatewaySpendReport; openAi: OpenAiDirectSpendReport; }; + +export type OpenAiUsageByMindInput = UsageWindowInput & { + /** Mind ids to read beside the minds that the ledger lists (a mind whose last use is older than + * the list). At most 200. */ + minds?: string[]; +}; + +export type OpenAiMindSpendSummary = { + mindId: string; + mindSlug: string; + requests: number; + costUsd: number; + audioSeconds: number; +}; + +/** EVERY MIND'S OPENAI-DIRECT SPEND (voice and transcription on the Cloud's own OpenAI key), by + * UTC day. It holds no AI Gateway spend: Cloudflare's analytics answer that by mind. */ +export type OpenAiUsageByMindReport = { + since: string; + until: string; + totalRequests: number; + totalCostUsd: number; + totalAudioSeconds: number; + /** One entry for each mind with spend in the window, the highest cost first. */ + byMind: OpenAiMindSpendSummary[]; + /** One row for each UTC day, mind, kind and model, the oldest day first. */ + byDay: OpenAiDayRow[]; +}; + +export function openAiUsageByMindReport( + window: { since: string; until: string }, + byDay: OpenAiDayRow[], +): OpenAiUsageByMindReport { + const minds = new Map<string, OpenAiMindSpendSummary>(); + for (const row of byDay) { + const mind = minds.get(row.mindId); + if (!mind) { + minds.set(row.mindId, { + mindId: row.mindId, + mindSlug: row.mindSlug, + requests: row.requests, + costUsd: row.costUsd, + audioSeconds: row.audioSeconds, + }); + continue; + } + mind.requests += row.requests; + mind.costUsd = roundUsd(mind.costUsd + row.costUsd); + mind.audioSeconds = Math.round((mind.audioSeconds + row.audioSeconds) * 1000) / 1000; + // the rows are oldest first: the newest name that the mind wrote from + mind.mindSlug = row.mindSlug || mind.mindSlug; + } + const byMind = [...minds.values()].sort((left, right) => right.costUsd - left.costUsd); + return { + since: window.since, + until: window.until, + totalRequests: byMind.reduce((sum, mind) => sum + mind.requests, 0), + totalCostUsd: roundUsd(byMind.reduce((sum, mind) => sum + mind.costUsd, 0)), + totalAudioSeconds: + Math.round(byMind.reduce((sum, mind) => sum + mind.audioSeconds, 0) * 1000) / 1000, + byMind, + byDay, + }; +} export type QueryGatewaySpendInput = UsageWindowInput & { accountId: string;
M internal-packages/cloud-ai/src/worker.ts
@@ -131,6 +131,7 @@ cloudOrigin: url.origin, analytics, openAiUsageStore: usageStore, + ownMind: { id: env.MIND_ID, hostname: env.MIND_HOSTNAME }, }), ); },