iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / cloud-ai / README.mdmain at aacbc74

# `@iterate-com/cloud-ai`

Iterate Cloud AI Gateway lending over Cap'n Web (`itx.iterateCloud.ai`), authenticated OpenAI Responses WebSockets (`/ai-ws/openai/responses`), and OpenAI Realtime Voice & Transcription lending (`/secrets/openai` `SecretProxy` -> `/capnweb/api.openai.com/...`) with unified per-customer spend reporting (`itx.iterateCloud.usage()`) and zero changes to `core/`.

## Architecture

1. **Mind X connects `itx.iterateCloud`** via [`connectIterateCloud`](./src/connect.ts):
   - Sets `/secrets/iterate-cloud` as a `SecretProxy` (`proxy: { mind: "iterate.iterate.com", url: "https://cloud.iterate.com/capnweb" }`).
   - Sets `/secrets/openai` as a `SecretProxy` (`urls: ["https://api.openai.com"]`, when no owner key is already stored) so `packages/voice`, `call/outbound.ts` (`POST /v1/live/sessions`, `POST /v1/live/sessions/:id/hangup`, `POST /v1/realtime/client_secrets`), `POST /v1/audio/transcriptions`, and `GET /v1/realtime` WebSockets work out of the box with zero `core/` changes.
   - Configures `itx.iterateCloud` -> `connectToCapnweb("wss://cloud.iterate.com/api/cloud-ai", ...)` (and optionally `itx.ai` -> `itx.iterateCloud.ai`).
2. **Three transports, one credential (`ML-DSA-65` `iterate-auth-statement` via `SecretProxy`):**
   - **Cap'n Web (`itx.iterateCloud.usage()`, `itx.iterateCloud.ai.run` / `gateway().run` / `websearch` / `models`):** Multi-provider (`openai/*`, `anthropic/*`, `google/*`, `@cf/*`), streaming raw `Response` SSE bodies over Cap'n Web.
   - **OpenAI Responses WebSocket (`/ai-ws/openai/responses`):** Warm WebSocket through Cloudflare AI Gateway Unified Billing with server-injected `cf-aig-authorization`, unforgeable `cf-aig-metadata` (`mindId`, `mindSlug`, `streamPath`), and `cf-aig-collect-log-payload: "false"`.
   - **OpenAI Realtime Voice & Transcription (`/capnweb/api.openai.com/...` / `/openai-voice/...`):** Proxied with Iterate Cloud's `OPENAI_API_KEY`, refusing `store: true` and recording per-mind voice & transcription usage into a SQLite Durable Object (`CloudUsageLedger`, sharded per `mindId`).
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
import { connectIterateCloud } from "@iterate-com/cloud-ai/connect";
import type { IterateContextApiWith } from "iterate/api";

const { responsesWebSocketUrl, secretPath, openAiSecret } = await connectIterateCloud(itx, {
  cloudOrigin: "https://cloud.iterate.com",
  cloudMind: "iterate.iterate.com",
  replaceItxAi: true,
});

const cloudItx = itx as IterateContextApiWith<"iterateCloud">;
const answer = await cloudItx.iterateCloud.ai.run("openai/gpt-5.4-mini", {
  input: "Hello from an enrolled mind!",
});
const usage = await cloudItx.iterateCloud.usage();
// usage.totalCostUsd = usage.aiGateway.totalCostUsd + usage.openAi.totalCostUsd
```