AI-native design editor. Open-source Figma alternative.
feat(cloud): add a reference AI relay that meters Cloud-signed requests (#1357)
Danila Poyarkov7adb2821d578
diff --git a/bun.lock b/bun.lockindex 5751b0bda..264077a11 100644--- a/bun.lock+++ b/bun.lock@@ -213,6 +213,7 @@"@better-auth/passkey": "1.7.7","@better-auth/utils": "0.4.2","@hono/node-server": "^1.19.17",+ "@internationalized/date": "^3.12.3","@noble/hashes": "^2.4.0","@open-pencil/feedback": "workspace:*","@open-pencil/scene-graph": "workspace:*",diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex b7e6f7e6e..d5582ff31 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -24,6 +24,15 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo- Decoders must consume exactly the frame's bytes and copy payloads out, since socket buffers are pooled (`src/contract/relay.ts`, `tests/contract/relay.test.ts`).- Send frames through `relayServerMessages` and `relayClientMessages`, which split anything past `RELAY_FRAGMENT_BYTES` into fragments, and read sockets through the matching assemblers; never send an encoded frame whole (`tests/server/collaboration/relay/hub.test.ts`).+## AI relay++- The reference AI service in `src/ai-relay/` is runtime-neutral like `src/server`; runtimes own listening and keys (`src/runtime/node/ai-relay/server.ts`).+- It speaks only the contract in `src/contract/ai.ts` (`tests/contract/ai.test.ts`).+- It trusts nothing about a request beyond a token that verifies against Cloud's keys (`tests/integration/ai-relay/app.test.ts`).+- It forwards only the chat completion fields in `FORWARDED_FIELDS`, so routing fields cannot reach models outside the catalog (`tests/integration/ai-relay/app.test.ts`).+- The relay's tables are `ai_relay_*` with their own migration history, so it can share Cloud's database (`src/ai-relay/db/migrate.ts`).+- Neither the relay nor Cloud reads the other's tables (`src/ai-relay/db/schema.ts`).+## Portal- The portal's pages live in the app (`cloud.html`, `src/views/cloud/`, `src/components/cloud-portal/`); this package owns only their paths (`src/contract/portal.ts`) and serving them beside the editor (`src/runtime/site/server.ts`). Links the server sends to people point at `publicURL`, its editor and portal alike (`src/contract/links.ts`, `src/admin/enrollment/email.ts`).@@ -36,6 +45,6 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo## Tests-- Unit tests mirror `src` under `tests/{client,contract,runtime,server}`; integration tests mirror `src` under `tests/integration` and run on PGlite through `tests/helpers/database.ts`; `tests/e2e` holds Docker Compose runners that `test` never starts.+- Unit tests mirror `src` under `tests/{ai-relay,client,contract,runtime,server}`; integration tests mirror `src` under `tests/integration` and run on PGlite through `tests/helpers/database.ts`; `tests/e2e` holds Docker Compose runners that `test` never starts.- Tests import source through `#cloud/*` and helpers through `#cloud-tests/*`, and read responses with `responseJSON` from `tests/helpers/response.ts`.- `bun run test:cloud` type-checks the package and runs unit and integration suites.diff --git a/packages/cloud/deploy/.env.example b/packages/cloud/deploy/.env.exampleindex d4364a0b4..6f29aad27 100644--- a/packages/cloud/deploy/.env.example+++ b/packages/cloud/deploy/.env.example@@ -17,6 +17,12 @@ S3_SECRET_ACCESS_KEY=openpencil-development-secret# S3_SESSION_TOKEN=# OPENPENCIL_CLOUD_SMTP_USER=# OPENPENCIL_CLOUD_SMTP_PASSWORD=+# OPENPENCIL_CLOUD_AI_SIGNING_KEY=+# OPENPENCIL_CLOUD_SERVICE_TOKEN=++# The AI relay (`node dist-standalone/ai-relay.mjs`) reads its own TOML file and upstream key.+# OPENPENCIL_AI_RELAY_CONFIG=./openpencil-ai-relay.toml+# OPENPENCIL_AI_RELAY_UPSTREAM_KEY=# Compose infrastructure settings, not Cloud application configuration.POSTGRES_PASSWORD=openpencil-development-passworddiff --git a/packages/cloud/deploy/openpencil-ai-relay.example.toml b/packages/cloud/deploy/openpencil-ai-relay.example.tomlnew file mode 100644index 000000000..e0cb50e14--- /dev/null+++ b/packages/cloud/deploy/openpencil-ai-relay.example.toml@@ -0,0 +1,38 @@+# The OpenPencil AI relay: a minimal AI service for a self-hosted Cloud. It accepts tokens your Cloud+# signs, forwards chat completions to one OpenAI-compatible upstream with one key, and holds each+# workspace to the monthly credit allowance its Cloud entitlements grant. Point Cloud's `[ai]`+# endpoint at it. Run it with `OPENPENCIL_AI_RELAY_CONFIG=<this file>`.+schema_version = 1++[relay]+# The Cloud whose tokens are accepted; its public keys are read from /.well-known/jwks.json.+cloud_url = "http://localhost:8787"+# Browser editors calling the relay. The desktop editor is not subject to CORS.+allowed_origins = ["http://localhost:5173"]+# Model requests one workspace may have in flight at once.+max_concurrent_requests = 4+# The largest model request accepted, in bytes; vision requests carry their images inline.+max_request_bytes = 16777216++# Defaults to DATABASE_URL. The relay can share Cloud's database; its tables and migration history+# are its own.+[database]++[upstream]+base_url = "https://openrouter.ai/api/v1"+# The key defaults to OPENPENCIL_AI_RELAY_UPSTREAM_KEY.++# 1,000 credits are worth what your plan says they are; the relay only counts them. A request costs+# its input and output tokens at these rates, rounded up.+[catalog]+default_model = "anthropic/claude-sonnet-5-5"++[[catalog.models]]+id = "anthropic/claude-sonnet-5-5"+label = "Claude Sonnet 5.5"+credits_per_million_input_tokens = 3000+credits_per_million_output_tokens = 15000+context_tokens = 1000000+reasoning = true+vision = true+tools = truediff --git a/packages/cloud/package.json b/packages/cloud/package.jsonindex d5933bbad..fa6af6efd 100644--- a/packages/cloud/package.json+++ b/packages/cloud/package.json@@ -55,9 +55,10 @@"build:standalone": "bunx tsdown --config tsdown.standalone.config.ts","start": "node dist-standalone/server.mjs","dev": "bun --watch src/runtime/node/main.ts",+ "ai-relay": "bun src/runtime/node/ai-relay/main.ts","check": "bun run typecheck && bun run test && bun run build","test": "bun run test:unit && bun run test:integration",- "test:unit": "bun test tests/client tests/contract tests/runtime tests/server",+ "test:unit": "bun test tests/ai-relay tests/client tests/contract tests/runtime tests/server","test:integration": "bun test --max-concurrency 8 tests/integration","test:e2e": "bun tests/e2e/run.ts","test:e2e:garage": "bun tests/e2e/garage.ts",@@ -75,6 +76,7 @@"@better-auth/passkey": "1.7.7","@better-auth/utils": "0.4.2","@hono/node-server": "^1.19.17",+ "@internationalized/date": "^3.12.3","@noble/hashes": "^2.4.0","@open-pencil/feedback": "workspace:*","@open-pencil/scene-graph": "workspace:*",diff --git a/packages/cloud/src/ai-relay/app.ts b/packages/cloud/src/ai-relay/app.tsnew file mode 100644index 000000000..ccf529ebd--- /dev/null+++ b/packages/cloud/src/ai-relay/app.ts@@ -0,0 +1,240 @@+import {+ AI_ERROR_STATUS,+ aiTokenClaimsSchema,+ CLOUD_AI_API_PATHS,+ CLOUD_AI_TOKEN_AUDIENCE,+ parseAIUsageQuery,+ type AIErrorCode,+ type AITokenClaims+} from '#cloud/contract'+import { validatedQuery } from '#cloud/server/validation'+import { pick } from 'es-toolkit'+import { Hono, type Context } from 'hono'+import { bodyLimit } from 'hono/body-limit'+import { cors } from 'hono/cors'+import { jwtVerify, type JWTVerifyGetKey } from 'jose'+import type { Kysely } from 'kysely'+import * as v from 'valibot'++import type { AIRelayConfig } from './config'+import type { AIRelayDatabase } from './db'+import { creditsFor, meteredUsage } from './metering'+import { AIUsageCursorError, createAIUsageStore } from './usage'++export type AIRelayServices = {+ config: AIRelayConfig+ database: Kysely<AIRelayDatabase>+ /** Resolves Cloud's signing keys, normally `createRemoteJWKSet` on Cloud's JWKS. */+ keys: JWTVerifyGetKey+ /** Reaches the upstream model API. */+ fetch?: (input: string, init: RequestInit) => Promise<Response>+ now?: () => Date+ /**+ * Keeps metering alive after the answer is returned, as Workers' `waitUntil` does. Node runs the+ * promise to completion on its own.+ */+ waitUntil?: (promise: Promise<unknown>) => void+ onBackgroundError?: (error: unknown) => void+ upstreamTimeoutMs?: number+}++type AIRelayEnvironment = { Variables: { claims: AITokenClaims } }++const chatRequestSchema = v.looseObject({+ model: v.pipe(v.string(), v.minLength(1)),+ stream: v.optional(v.boolean())+})+const chatRequestBodySchema = v.pipe(v.string(), v.parseJson(), chatRequestSchema)++/**+ * The chat completion fields sent upstream. Routing and extension fields, such as OpenRouter's+ * `models` fallbacks, `provider`, and `plugins`, are dropped, so the relay's key runs only the+ * catalog model it charges for.+ */+const FORWARDED_FIELDS = [+ 'model',+ 'messages',+ 'stream',+ 'max_tokens',+ 'max_completion_tokens',+ 'temperature',+ 'top_p',+ 'frequency_penalty',+ 'presence_penalty',+ 'stop',+ 'seed',+ 'tools',+ 'tool_choice',+ 'parallel_tool_calls',+ 'response_format',+ 'reasoning_effort',+ 'reasoning'+] as const++/** How long an upstream answer may take in all, streamed or not, so a stalled one cannot hold a request slot forever. */+const DEFAULT_UPSTREAM_TIMEOUT_MS = 10 * 60_000++function aiError(context: Context, code: AIErrorCode) {+ return context.json({ error: { code } }, AI_ERROR_STATUS[code])+}++/** Counts each workspace's model requests in flight, within one process. */+function concurrencyLimiter(maximum: number) {+ const inFlight = new Map<string, number>()+ return {+ acquire(workspaceId: string): (() => void) | null {+ const count = inFlight.get(workspaceId) ?? 0+ if (count >= maximum) return null+ inFlight.set(workspaceId, count + 1)+ let released = false+ return () => {+ if (released) return+ released = true+ const remaining = (inFlight.get(workspaceId) ?? 1) - 1+ if (remaining > 0) inFlight.set(workspaceId, remaining)+ else inFlight.delete(workspaceId)+ }+ }+ }+}++/**+ * The reference AI service: it verifies Cloud-signed tokens, proxies chat completions to one+ * OpenAI-compatible upstream with one key, and holds each workspace to its monthly allowance.+ * A request is admitted while the workspace has credits left and charged once its usage is known,+ * so concurrent requests can overdraw the allowance by what they cost.+ */+export function createAIRelayApp(services: AIRelayServices) {+ const { config } = services+ const upstreamFetch = services.fetch ?? ((input, init) => fetch(input, init))+ const now = services.now ?? (() => new Date())+ const usage = createAIUsageStore(services.database)+ const models = new Map(config.catalog.models.map((model) => [model.id, model]))+ const limiter = concurrencyLimiter(config.maximumConcurrentRequests)+ const allowedOrigins = new Set(config.allowedOrigins)+ const reportBackgroundError =+ services.onBackgroundError ??+ ((error: unknown) => console.error('[AI relay] Metering failed:', error))++ const requireToken = async (context: Context<AIRelayEnvironment>, next: () => Promise<void>) => {+ const header = context.req.header('Authorization')+ const token = header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined+ if (!token) return aiError(context, 'unauthorized')+ try {+ const { payload } = await jwtVerify(token, services.keys, {+ issuer: config.cloudURL,+ audience: CLOUD_AI_TOKEN_AUDIENCE,+ algorithms: ['ES256']+ })+ context.set('claims', v.parse(aiTokenClaimsSchema, payload))+ } catch {+ return aiError(context, 'unauthorized')+ }+ return next()+ }++ return new Hono<AIRelayEnvironment>()+ .use(+ '*',+ cors({+ origin: (origin) => (allowedOrigins.has(origin) ? origin : null),+ allowMethods: ['GET', 'POST', 'OPTIONS'],+ allowHeaders: ['Content-Type', 'Authorization'],+ maxAge: 600+ })+ )+ .use(`${CLOUD_AI_API_PATHS.base}/*`, requireToken)+ .get(CLOUD_AI_API_PATHS.catalog, (context) => context.json(config.catalog))+ .get(CLOUD_AI_API_PATHS.wallet, async (context) => {+ const claims = context.get('claims')+ return context.json(+ await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())+ )+ })+ .get(CLOUD_AI_API_PATHS.usage, validatedQuery(parseAIUsageQuery), async (context) => {+ try {+ return context.json(+ await usage.page(context.get('claims').workspaceId, context.req.valid('query').cursor)+ )+ } catch (error) {+ if (error instanceof AIUsageCursorError) {+ return context.json({ error: { code: 'invalid_request' as const } }, 400)+ }+ throw error+ }+ })+ .post(+ CLOUD_AI_API_PATHS.chatCompletions,+ // Counted as it streams in, so a body without Content-Length is bounded too.+ bodyLimit({+ maxSize: config.maximumRequestBytes,+ onError: (context) => context.json({ error: { code: 'invalid_request' as const } }, 413)+ }),+ async (context) => {+ const claims = context.get('claims')+ const parsed = v.safeParse(chatRequestBodySchema, await context.req.text())+ if (!parsed.success)+ return context.json({ error: { code: 'invalid_request' as const } }, 400)+ const request = pick(parsed.output, FORWARDED_FIELDS)+ const model = models.get(request.model)+ if (!model) return aiError(context, 'model_not_allowed')+ const wallet = await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())+ if (wallet.balance === 0) return aiError(context, 'insufficient_credits')+ const release = limiter.acquire(claims.workspaceId)+ if (!release) return aiError(context, 'rate_limited')++ const streamed = request.stream === true+ let upstream: Response+ try {+ upstream = await upstreamFetch(`${config.upstreamURL}/chat/completions`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${config.upstreamKey}`+ },+ body: JSON.stringify(+ streamed ? { ...request, stream_options: { include_usage: true } } : request+ ),+ // Aborting also errors a stream in progress, so metering ends and frees the slot.+ signal: AbortSignal.timeout(services.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS)+ })+ } catch (error) {+ release()+ throw error+ }+ const headers = new Headers()+ const contentType = upstream.headers.get('Content-Type')+ if (contentType) headers.set('Content-Type', contentType)+ if (streamed) headers.set('Cache-Control', 'no-cache')+ if (!upstream.ok || !upstream.body) {+ release()+ return new Response(upstream.body, { status: upstream.status, headers })+ }++ // The metering branch reads to the end even if the editor disconnects, so the request is+ // still charged for what the upstream generated.+ const [answer, metered] = upstream.body.tee()+ const settle = async () => {+ const tokens = await meteredUsage(metered, streamed)+ // An upstream that reports no usage leaves the request uncharged, so operators hear of it.+ if (!tokens)+ throw new Error(`The upstream reported no usage for ${model.id}; not charged`)+ await usage.record({+ id: crypto.randomUUID(),+ workspaceId: claims.workspaceId,+ userId: claims.sub,+ modelId: model.id,+ inputTokens: tokens.inputTokens,+ outputTokens: tokens.outputTokens,+ credits: creditsFor(model, tokens),+ createdAt: now()+ })+ }+ const settled = settle().catch(reportBackgroundError).finally(release)+ services.waitUntil?.(settled)+ return new Response(answer, { status: upstream.status, headers })+ }+ )+}++export type AIRelayApp = ReturnType<typeof createAIRelayApp>diff --git a/packages/cloud/src/ai-relay/config.ts b/packages/cloud/src/ai-relay/config.tsnew file mode 100644index 000000000..aef9db167--- /dev/null+++ b/packages/cloud/src/ai-relay/config.ts@@ -0,0 +1,120 @@+import { aiCatalogSchema, type AICatalog } from '#cloud/contract'+import { httpURLSchema } from '#cloud/server/config/schema'+import { parse as parseTOML } from 'smol-toml'+import * as v from 'valibot'++export type AIRelayEnvironment = Readonly<Record<string, string | undefined>>++export type AIRelayConfig = {+ /** The Cloud whose tokens the relay accepts: their issuer, and where its keys are published. */+ cloudURL: string+ /** Browser origins allowed to call the relay; the desktop editor is not subject to CORS. */+ allowedOrigins: string[]+ /** Model requests a workspace may have in flight at once. */+ maximumConcurrentRequests: number+ /** The largest model request body accepted, in bytes. */+ maximumRequestBytes: number+ databaseURL: string+ /** An OpenAI-compatible API base URL, such as `https://openrouter.ai/api/v1`. */+ upstreamURL: string+ upstreamKey: string+ catalog: AICatalog+}++export class AIRelayConfigError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'AIRelayConfigError'+ }+}++const DEFAULT_SECRET_NAMES = {+ databaseURL: 'DATABASE_URL',+ upstreamKey: 'OPENPENCIL_AI_RELAY_UPSTREAM_KEY'+} as const++const textSchema = v.pipe(v.string(), v.trim(), v.minLength(1))+const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0))+const secretReferenceSchema = v.object({ from_env: textSchema })+const defaultReference = (name: string) => v.optional(secretReferenceSchema, { from_env: name })++const modelSchema = v.object({+ id: textSchema,+ label: textSchema,+ credits_per_million_input_tokens: creditsSchema,+ credits_per_million_output_tokens: creditsSchema,+ context_tokens: v.pipe(v.number(), v.integer(), v.minValue(1)),+ reasoning: v.optional(v.boolean(), false),+ vision: v.optional(v.boolean(), false),+ tools: v.optional(v.boolean(), true)+})++const aiRelayConfigSchema = v.object({+ schema_version: v.literal(1),+ relay: v.object({+ cloud_url: httpURLSchema,+ allowed_origins: v.optional(v.array(httpURLSchema), []),+ max_concurrent_requests: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1)), 4),+ // Room for the images a vision request carries inline.+ max_request_bytes: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1)), 16 * 1024 * 1024)+ }),+ database: v.optional(v.object({ url: defaultReference(DEFAULT_SECRET_NAMES.databaseURL) }), {+ url: { from_env: DEFAULT_SECRET_NAMES.databaseURL }+ }),+ upstream: v.object({+ base_url: httpURLSchema,+ api_key: defaultReference(DEFAULT_SECRET_NAMES.upstreamKey)+ }),+ catalog: v.object({+ default_model: textSchema,+ models: v.pipe(v.array(modelSchema), v.minLength(1))+ })+})++export type AIRelayConfigInput = v.InferInput<typeof aiRelayConfigSchema>++function requiredSecret(environment: AIRelayEnvironment, name: string): string {+ const value = environment[name]+ if (!value) throw new AIRelayConfigError(`Required secret binding is unavailable: ${name}`)+ return value+}++function catalogFrom(input: v.InferOutput<typeof aiRelayConfigSchema>['catalog']): AICatalog {+ const ids = new Set<string>()+ for (const model of input.models) {+ if (ids.has(model.id)) throw new AIRelayConfigError(`Model ${model.id} is listed twice`)+ ids.add(model.id)+ }+ if (!ids.has(input.default_model)) {+ throw new AIRelayConfigError(`Default model ${input.default_model} is not in the catalog`)+ }+ return v.parse(aiCatalogSchema, {+ defaultModelID: input.default_model,+ models: input.models.map((model) => ({+ id: model.id,+ label: model.label,+ creditsPerMillionInputTokens: model.credits_per_million_input_tokens,+ creditsPerMillionOutputTokens: model.credits_per_million_output_tokens,+ contextTokens: model.context_tokens,+ capabilities: { reasoning: model.reasoning, vision: model.vision, tools: model.tools }+ }))+ })+}++export function parseAIRelayConfig(input: unknown, environment: AIRelayEnvironment): AIRelayConfig {+ const config = v.parse(aiRelayConfigSchema, input)+ return {+ cloudURL: new URL(config.relay.cloud_url).origin,+ allowedOrigins: config.relay.allowed_origins.map((origin) => new URL(origin).origin),+ maximumConcurrentRequests: config.relay.max_concurrent_requests,+ maximumRequestBytes: config.relay.max_request_bytes,+ databaseURL: requiredSecret(environment, config.database.url.from_env),+ upstreamURL: config.upstream.base_url.replace(/\/+$/, ''),+ upstreamKey: requiredSecret(environment, config.upstream.api_key.from_env),+ catalog: catalogFrom(config.catalog)+ }+}++export function parseAIRelayTOML(source: string, environment: AIRelayEnvironment): AIRelayConfig {+ return parseAIRelayConfig(parseTOML(source), environment)+}diff --git a/packages/cloud/src/ai-relay/db/index.ts b/packages/cloud/src/ai-relay/db/index.tsnew file mode 100644index 000000000..91da1d910--- /dev/null+++ b/packages/cloud/src/ai-relay/db/index.ts@@ -0,0 +1,10 @@+import { CamelCasePlugin, Kysely, type Dialect } from 'kysely'++import type { AIRelayDatabase } from './schema'++export { migrateAIRelayDatabase } from './migrate'+export type { AIRelayDatabase, AIRelayUsage, NewAIRelayUsage } from './schema'++export function createAIRelayDatabase(dialect: Dialect): Kysely<AIRelayDatabase> {+ return new Kysely<AIRelayDatabase>({ dialect, plugins: [new CamelCasePlugin()] })+}diff --git a/packages/cloud/src/ai-relay/db/migrate.ts b/packages/cloud/src/ai-relay/db/migrate.tsnew file mode 100644index 000000000..c0f5fe312--- /dev/null+++ b/packages/cloud/src/ai-relay/db/migrate.ts@@ -0,0 +1,32 @@+import { migrateToLatest } from '#cloud/server/db/migrate'+import type { Kysely } from 'kysely'+import { Migrator, type Migration, type MigrationProvider } from 'kysely/migration'++import * as usage from './migrations/001_usage'+import type { AIRelayDatabase } from './schema'++const migrations: Record<string, Migration> = {+ '001_usage': usage+}++class AIRelayMigrationProvider implements MigrationProvider {+ async getMigrations(): Promise<Record<string, Migration>> {+ return migrations+ }+}++/**+ * The relay keeps its own migration history, so it can share a PostgreSQL database with Cloud+ * without either one seeing the other's migrations as unknown.+ */+export async function migrateAIRelayDatabase(database: Kysely<AIRelayDatabase>): Promise<void> {+ await migrateToLatest(+ new Migrator({+ db: database,+ provider: new AIRelayMigrationProvider(),+ migrationTableName: 'ai_relay_migration',+ migrationLockTableName: 'ai_relay_migration_lock'+ }),+ 'OpenPencil AI relay database migration failed'+ )+}diff --git a/packages/cloud/src/ai-relay/db/migrations/001_usage.ts b/packages/cloud/src/ai-relay/db/migrations/001_usage.tsnew file mode 100644index 000000000..cb457d93d--- /dev/null+++ b/packages/cloud/src/ai-relay/db/migrations/001_usage.ts@@ -0,0 +1,26 @@+import { addCurrentTimestampColumns } from '#cloud/server/db/migrations/helpers'+import type { Kysely } from 'kysely'++/** One row per settled model request; a workspace's monthly spend is the sum of its rows. */+export async function up(database: Kysely<unknown>): Promise<void> {+ await database.schema+ .createTable('ai_relay_usage')+ .addColumn('id', 'uuid', (column) => column.primaryKey())+ .addColumn('workspace_id', 'uuid', (column) => column.notNull())+ .addColumn('user_id', 'text', (column) => column.notNull())+ .addColumn('model_id', 'text', (column) => column.notNull())+ .addColumn('input_tokens', 'integer', (column) => column.notNull())+ .addColumn('output_tokens', 'integer', (column) => column.notNull())+ .addColumn('credits', 'integer', (column) => column.notNull())+ .execute()+ await addCurrentTimestampColumns(database, 'ai_relay_usage', ['created_at'])+ await database.schema+ .createIndex('ai_relay_usage_workspace_created_idx')+ .on('ai_relay_usage')+ .columns(['workspace_id', 'created_at desc', 'id desc'])+ .execute()+}++export async function down(database: Kysely<unknown>): Promise<void> {+ await database.schema.dropTable('ai_relay_usage').ifExists().execute()+}diff --git a/packages/cloud/src/ai-relay/db/schema.ts b/packages/cloud/src/ai-relay/db/schema.tsnew file mode 100644index 000000000..cc6300b82--- /dev/null+++ b/packages/cloud/src/ai-relay/db/schema.ts@@ -0,0 +1,20 @@+import type { TimestampColumn } from '#cloud/server/db/tables'+import type { Insertable, Selectable } from 'kysely'++export interface AIRelayUsageTable {+ id: string+ workspaceId: string+ userId: string+ modelId: string+ inputTokens: number+ outputTokens: number+ credits: number+ createdAt: TimestampColumn+}++export interface AIRelayDatabase {+ aiRelayUsage: AIRelayUsageTable+}++export type AIRelayUsage = Selectable<AIRelayUsageTable>+export type NewAIRelayUsage = Insertable<AIRelayUsageTable>diff --git a/packages/cloud/src/ai-relay/index.ts b/packages/cloud/src/ai-relay/index.tsnew file mode 100644index 000000000..241b6e624--- /dev/null+++ b/packages/cloud/src/ai-relay/index.ts@@ -0,0 +1,18 @@+export { createAIRelayApp, type AIRelayApp, type AIRelayServices } from './app'+export {+ AIRelayConfigError,+ parseAIRelayConfig,+ parseAIRelayTOML,+ type AIRelayConfig,+ type AIRelayConfigInput,+ type AIRelayEnvironment+} from './config'+export {+ createAIRelayDatabase,+ migrateAIRelayDatabase,+ type AIRelayDatabase,+ type AIRelayUsage,+ type NewAIRelayUsage+} from './db'+export { creditsFor, meteredUsage, type TokenUsage } from './metering'+export { createAIUsageStore, usagePeriod, type AIUsageStore } from './usage'diff --git a/packages/cloud/src/ai-relay/metering.ts b/packages/cloud/src/ai-relay/metering.tsnew file mode 100644index 000000000..c8a8875e1--- /dev/null+++ b/packages/cloud/src/ai-relay/metering.ts@@ -0,0 +1,68 @@+import type { AIModel } from '#cloud/contract'+import * as v from 'valibot'++export type TokenUsage = { inputTokens: number; outputTokens: number }++const tokensSchema = v.pipe(v.number(), v.integer(), v.minValue(0))+const usageSchema = v.object({+ usage: v.object({ prompt_tokens: tokensSchema, completion_tokens: tokensSchema })+})++const usageBodySchema = v.pipe(v.string(), v.parseJson(), usageSchema)++function usageOf(text: string): TokenUsage | null {+ const parsed = v.safeParse(usageBodySchema, text)+ if (!parsed.success) return null+ return {+ inputTokens: parsed.output.usage.prompt_tokens,+ outputTokens: parsed.output.usage.completion_tokens+ }+}++/** Credits a request costs, rounded up so a request is never free. */+export function creditsFor(model: AIModel, usage: TokenUsage): number {+ return Math.ceil(+ (usage.inputTokens * model.creditsPerMillionInputTokens ++ usage.outputTokens * model.creditsPerMillionOutputTokens) /+ 1_000_000+ )+}++/**+ * Reads the token usage of a chat completion: the `usage` of a JSON answer, or of the last stream+ * event that carries one, which upstreams send when asked with `stream_options.include_usage`.+ */+export async function meteredUsage(+ body: ReadableStream<Uint8Array>,+ streamed: boolean+): Promise<TokenUsage | null> {+ const reader = body.getReader()+ const decoder = new TextDecoder()+ const chunks = async function* () {+ for (let next = await reader.read(); !next.done; next = await reader.read()) {+ yield decoder.decode(next.value, { stream: true })+ }+ yield decoder.decode()+ }+ if (!streamed) {+ let text = ''+ for await (const chunk of chunks()) text += chunk+ return usageOf(text)+ }+ let usage: TokenUsage | null = null+ let pending = ''+ const read = (line: string) => {+ if (!line.startsWith('data:')) return+ const data = line.slice('data:'.length).trim()+ if (data === '[DONE]') return+ usage = usageOf(data) ?? usage+ }+ for await (const chunk of chunks()) {+ pending += chunk+ const parts = pending.split(/\r?\n/)+ pending = parts.pop() ?? ''+ for (const line of parts) read(line)+ }+ read(pending)+ return usage+}diff --git a/packages/cloud/src/ai-relay/usage.ts b/packages/cloud/src/ai-relay/usage.tsnew file mode 100644index 000000000..fe9d759b0--- /dev/null+++ b/packages/cloud/src/ai-relay/usage.ts@@ -0,0 +1,115 @@+import type { AIUsagePage, AIWallet } from '#cloud/contract'+import { fromDate, startOfMonth, toCalendarDate } from '@internationalized/date'+import type { Kysely } from 'kysely'+import * as v from 'valibot'++import type { AIRelayDatabase, NewAIRelayUsage } from './db'++const USAGE_PAGE_SIZE = 50++/** The UTC calendar month a moment falls in, as its first instant and the next month's. */+export function usagePeriod(now: Date): { start: Date; end: Date } {+ const month = startOfMonth(toCalendarDate(fromDate(now, 'UTC')))+ return { start: month.toDate('UTC'), end: month.add({ months: 1 }).toDate('UTC') }+}++/** A page boundary: the last entry's creation time in milliseconds and its ID. */+const cursorSchema = v.pipe(+ v.string(),+ v.regex(/^\d+\.[0-9a-f-]{36}$/),+ v.transform((value) => {+ const [milliseconds = '', id = ''] = value.split('.')+ return { createdAt: new Date(Number(milliseconds)), id }+ }),+ v.check(+ ({ createdAt, id }) =>+ !Number.isNaN(createdAt.getTime()) && v.is(v.pipe(v.string(), v.uuid()), id)+ )+)++function encodeCursor(createdAt: Date, id: string): string {+ return `${createdAt.getTime()}.${id}`+}++export class AIUsageCursorError extends Error {+ constructor() {+ super('Invalid usage cursor')+ this.name = 'AIUsageCursorError'+ }+}++export function createAIUsageStore(database: Kysely<AIRelayDatabase>) {+ async function spent(workspaceId: string, now: Date): Promise<number> {+ const { start, end } = usagePeriod(now)+ const row = await database+ .selectFrom('aiRelayUsage')+ .select((query) => query.fn.sum<string | number | null>('credits').as('credits'))+ .where('workspaceId', '=', workspaceId)+ .where('createdAt', '>=', start)+ .where('createdAt', '<', end)+ .executeTakeFirst()+ return Number(row?.credits ?? 0)+ }++ return {+ async record(usage: NewAIRelayUsage): Promise<void> {+ await database.insertInto('aiRelayUsage').values(usage).execute()+ },++ /**+ * The workspace's single allowance bucket for the current month. A `null` allowance means+ * Cloud set none, and the relay does not limit spend.+ */+ async wallet(workspaceId: string, allowance: number | null, now: Date): Promise<AIWallet> {+ if (allowance === null) return { balance: null, buckets: [] }+ const remaining = Math.max(0, allowance - (await spent(workspaceId, now)))+ return {+ balance: remaining,+ buckets: [{ kind: 'allowance', remaining, expiresAt: usagePeriod(now).end.toISOString() }]+ }+ },++ /** Newest first, across every member of the workspace. */+ async page(workspaceId: string, cursor: string | undefined): Promise<AIUsagePage> {+ let after: { createdAt: Date; id: string } | undefined+ if (cursor !== undefined) {+ const parsed = v.safeParse(cursorSchema, cursor)+ if (!parsed.success) throw new AIUsageCursorError()+ after = parsed.output+ }+ let query = database+ .selectFrom('aiRelayUsage')+ .select(['id', 'createdAt', 'modelId', 'userId', 'credits'])+ .where('workspaceId', '=', workspaceId)+ if (after) {+ const { createdAt, id } = after+ query = query.where((row) =>+ row.or([+ row('createdAt', '<', createdAt),+ row.and([row('createdAt', '=', createdAt), row('id', '<', id)])+ ])+ )+ }+ const rows = await query+ .orderBy('createdAt', 'desc')+ .orderBy('id', 'desc')+ .limit(USAGE_PAGE_SIZE + 1)+ .execute()+ const entries = rows.slice(0, USAGE_PAGE_SIZE)+ const last = entries.at(-1)+ return {+ entries: entries.map((row) => ({+ id: row.id,+ createdAt: row.createdAt.toISOString(),+ kind: 'model',+ modelID: row.modelId,+ userId: row.userId,+ credits: row.credits+ })),+ next: rows.length > USAGE_PAGE_SIZE && last ? encodeCursor(last.createdAt, last.id) : null+ }+ }+ }+}++export type AIUsageStore = ReturnType<typeof createAIUsageStore>diff --git a/packages/cloud/src/contract/ai.ts b/packages/cloud/src/contract/ai.tsindex 83a3784fa..aec607a2f 100644--- a/packages/cloud/src/contract/ai.ts+++ b/packages/cloud/src/contract/ai.ts@@ -12,6 +12,18 @@ export const CLOUD_AI_TOKEN_AUDIENCE = 'openpencil-ai' as const/** Where Cloud publishes the public keys an AI service verifies its tokens with. */export const CLOUD_AI_JWKS_PATH = '/.well-known/jwks.json' as const+/**+ * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat+ * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.+ */+export const CLOUD_AI_API_PATHS = {+ base: '/v1',+ chatCompletions: '/v1/chat/completions',+ catalog: '/v1/catalog',+ wallet: '/v1/wallet',+ usage: '/v1/usage'+} as const+const urlSchema = v.pipe(v.string(), v.url())const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0))@@ -75,7 +87,8 @@ export const aiCreditBucketSchema = v.object({export type AICreditBucket = v.InferOutput<typeof aiCreditBucketSchema>export const aiWalletSchema = v.object({- balance: creditsSchema,+ /** Credits left to spend; `null` when the service sets no limit. */+ balance: v.nullable(creditsSchema),/** Spent first to last. */buckets: v.array(aiCreditBucketSchema)})@@ -91,6 +104,15 @@ export const aiUsageEntrySchema = v.object({})export type AIUsageEntry = v.InferOutput<typeof aiUsageEntrySchema>+export const aiUsageQuerySchema = v.object({+ cursor: v.optional(v.pipe(v.string(), v.minLength(1)))+})+export type AIUsageQuery = v.InferOutput<typeof aiUsageQuerySchema>++export function parseAIUsageQuery(input: unknown): AIUsageQuery {+ return v.parse(aiUsageQuerySchema, input)+}+export const aiUsagePageSchema = v.object({entries: v.array(aiUsageEntrySchema),next: v.nullable(v.string())diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.tsindex 19760bba9..c185d70aa 100644--- a/packages/cloud/src/contract/index.ts+++ b/packages/cloud/src/contract/index.ts@@ -10,13 +10,16 @@ export {aiTokenSchema,aiUsageEntrySchema,aiUsagePageSchema,+ aiUsageQuerySchema,aiWalletSchema,+ CLOUD_AI_API_PATHS,CLOUD_AI_CONTRACT_VERSION,CLOUD_AI_JWKS_PATH,CLOUD_AI_TOKEN_AUDIENCE,cloudAIDiscoverySchema,cloudBillingDiscoverySchema,createAITokenSchema,+ parseAIUsageQuery,parseCreateAIToken,type AICatalog,type AICreditBucket,@@ -27,6 +30,7 @@ export {type AITokenClaims,type AIUsageEntry,type AIUsagePage,+ type AIUsageQuery,type AIWallet,type CloudAIDiscovery,type CloudBillingDiscovery,diff --git a/packages/cloud/src/runtime/node/ai-relay/main.ts b/packages/cloud/src/runtime/node/ai-relay/main.tsnew file mode 100644index 000000000..db98c9ec6--- /dev/null+++ b/packages/cloud/src/runtime/node/ai-relay/main.ts@@ -0,0 +1,19 @@+import { startNodeAIRelay } from './server'++const relay = await startNodeAIRelay()+console.log(`OpenPencil AI relay listening on ${relay.url}`)++let stopping: Promise<void> | undefined++function shutdown() {+ stopping ??= relay.stop().then(+ () => process.exit(0),+ (error: unknown) => {+ console.error('[AI relay] Shutdown failed:', error)+ process.exit(1)+ }+ )+}++process.on('SIGINT', shutdown)+process.on('SIGTERM', shutdown)diff --git a/packages/cloud/src/runtime/node/ai-relay/server.ts b/packages/cloud/src/runtime/node/ai-relay/server.tsnew file mode 100644index 000000000..6a9634993--- /dev/null+++ b/packages/cloud/src/runtime/node/ai-relay/server.ts@@ -0,0 +1,63 @@+import { readFile } from 'node:fs/promises'++import {+ AIRelayConfigError,+ createAIRelayApp,+ createAIRelayDatabase,+ migrateAIRelayDatabase,+ parseAIRelayTOML,+ type AIRelayEnvironment+} from '#cloud/ai-relay'+import { CLOUD_AI_JWKS_PATH } from '#cloud/contract'+import { createRemoteJWKSet } from 'jose'+import { PostgresDialect } from 'kysely'+import { Pool } from 'pg'++import { listen } from '../listen'++export type NodeAIRelayOptions = {+ environment?: AIRelayEnvironment+ port?: number+}++export async function startNodeAIRelay(options: NodeAIRelayOptions = {}) {+ const environment = options.environment ?? process.env+ const path = environment.OPENPENCIL_AI_RELAY_CONFIG+ if (!path) {+ throw new AIRelayConfigError('OPENPENCIL_AI_RELAY_CONFIG must name a relay TOML file')+ }+ const config = parseAIRelayTOML(await readFile(path, 'utf8'), environment)+ const database = createAIRelayDatabase(+ new PostgresDialect({ pool: new Pool({ connectionString: config.databaseURL }) })+ )+ try {+ await migrateAIRelayDatabase(database)+ } catch (error) {+ await database.destroy()+ throw error+ }+ // Metering outlives its answer; shutdown waits for it so no request goes uncharged.+ const metering = new Set<Promise<unknown>>()+ const app = createAIRelayApp({+ config,+ database,+ keys: createRemoteJWKSet(new URL(CLOUD_AI_JWKS_PATH, config.cloudURL)),+ waitUntil: (promise) => {+ metering.add(promise)+ void promise.finally(() => metering.delete(promise))+ }+ })+ const server = await listen(+ async (request) => app.fetch(request),+ options.port ?? Number(environment.PORT ?? 8788),+ environment.HOST ?? '0.0.0.0'+ )+ return {+ url: server.url,+ async stop() {+ await server.close()+ await Promise.allSettled(metering)+ await database.destroy()+ }+ }+}diff --git a/packages/cloud/src/runtime/node/index.ts b/packages/cloud/src/runtime/node/index.tsindex 624b0f185..fc4263fc8 100644--- a/packages/cloud/src/runtime/node/index.ts+++ b/packages/cloud/src/runtime/node/index.ts@@ -1,3 +1,4 @@+export { startNodeAIRelay, type NodeAIRelayOptions } from './ai-relay/server'export { createMigratedNodeCloudDatabase } from './bootstrap'export { createNodeCloudApplication, type NodeCloudApplicationOptions } from './application'export { loadNodeCloudServerConfig } from './config'diff --git a/packages/cloud/src/runtime/node/listen.ts b/packages/cloud/src/runtime/node/listen.tsnew file mode 100644index 000000000..aea8bb28e--- /dev/null+++ b/packages/cloud/src/runtime/node/listen.ts@@ -0,0 +1,35 @@+import { createServer } from 'node:http'++import { getRequestListener } from '@hono/node-server'++/** Serves a fetch handler over Node HTTP and resolves once the port is bound. */+export async function listen(+ fetch: (request: Request) => Promise<Response>,+ port: number,+ hostname: string+) {+ const listener = getRequestListener(fetch)+ const server = createServer((request, response) => {+ void listener(request, response)+ })+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(port, hostname, () => {+ server.off('error', reject)+ resolve()+ })+ })+ const address = server.address()+ const boundPort = typeof address === 'object' && address ? address.port : port+ return {+ url: new URL(`http://localhost:${boundPort}`),+ http: server,+ close: () =>+ new Promise<void>((done, fail) => {+ server.close((error) => {+ if (error) fail(error)+ else done()+ })+ })+ }+}diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.tsindex 2c333b82a..55d087f52 100644--- a/packages/cloud/src/runtime/node/server.ts+++ b/packages/cloud/src/runtime/node/server.ts@@ -1,5 +1,3 @@-import { createServer } from 'node:http'-import { defaultRelayURL } from '#cloud/contract'import { createS3ObjectStore } from '#cloud/runtime/s3/objects'import { createCloudServer } from '#cloud/runtime/site/server'@@ -16,10 +14,10 @@ import {startCleanupWorker,startTransactionalEmailWorker} from '#cloud/server'-import { getRequestListener } from '@hono/node-server'import { createMigratedNodeCloudDatabase } from './bootstrap'import { createNodeTransactionalEmailRuntime } from './email/runtime'+import { listen } from './listen'import { attachCollaborationRelay } from './relay'import { nodeSiteFiles } from './site'@@ -112,34 +110,3 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})}}}--async function listen(- fetch: (request: Request) => Promise<Response>,- port: number,- hostname: string-) {- const listener = getRequestListener(fetch)- const server = createServer((request, response) => {- void listener(request, response)- })- await new Promise<void>((resolve, reject) => {- server.once('error', reject)- server.listen(port, hostname, () => {- server.off('error', reject)- resolve()- })- })- const address = server.address()- const boundPort = typeof address === 'object' && address ? address.port : port- return {- url: new URL(`http://localhost:${boundPort}`),- http: server,- close: () =>- new Promise<void>((done, fail) => {- server.close((error) => {- if (error) fail(error)- else done()- })- })- }-}diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.tsindex 51fc2e3d8..925479cef 100644--- a/packages/cloud/src/server/config/schema.ts+++ b/packages/cloud/src/server/config/schema.ts@@ -11,7 +11,7 @@ import {CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM} from './limits'-const httpURLSchema = v.pipe(+export const httpURLSchema = v.pipe(v.string(),v.url(),v.check((value) => {diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.tsindex 434c5285f..59df1bde3 100644--- a/packages/cloud/src/server/db/migrate.ts+++ b/packages/cloud/src/server/db/migrate.ts@@ -143,14 +143,8 @@ async function migrateAuthSchema(.execute()}-export async function migrateCloudDatabase(- database: Kysely<CloudDatabase>,- authMigration?: CloudAuthMigration-): Promise<void> {- const migrator = new Migrator({- db: database,- provider: new CloudMigrationProvider()- })+/** Runs a migrator to its latest migration, failing with every error it reports. */+export async function migrateToLatest(migrator: Migrator, failure: string): Promise<void> {const result = await migrator.migrateToLatest()const failed = result.results?.find((migration) => migration.status === 'Error')if (result.error || failed) {@@ -158,8 +152,18 @@ export async function migrateCloudDatabase([result.error, failed ? new Error(`Migration failed: ${failed.migrationName}`) : null].filter((error): error is Error => error instanceof Error),- 'OpenPencil Cloud database migration failed'+ failure)}+}++export async function migrateCloudDatabase(+ database: Kysely<CloudDatabase>,+ authMigration?: CloudAuthMigration+): Promise<void> {+ await migrateToLatest(+ new Migrator({ db: database, provider: new CloudMigrationProvider() }),+ 'OpenPencil Cloud database migration failed'+ )if (authMigration) await migrateAuthSchema(database, authMigration)}diff --git a/packages/cloud/tests/ai-relay/config.test.ts b/packages/cloud/tests/ai-relay/config.test.tsnew file mode 100644index 000000000..e33053406--- /dev/null+++ b/packages/cloud/tests/ai-relay/config.test.ts@@ -0,0 +1,79 @@+import { describe, expect, test } from 'bun:test'+import { readFile } from 'node:fs/promises'++import { cloudDeployPath } from '#cloud-tests/helpers/paths'+import { AIRelayConfigError, parseAIRelayTOML } from '#cloud/ai-relay'++const environment = {+ DATABASE_URL: 'postgresql://relay:secret@database/relay',+ OPENPENCIL_AI_RELAY_UPSTREAM_KEY: 'upstream-key'+}++const source = `schema_version = 1++[relay]+cloud_url = "https://cloud.example.com/some/path"+allowed_origins = ["https://app.example.com/"]++[upstream]+base_url = "https://openrouter.ai/api/v1/"++[catalog]+default_model = "anthropic/claude-sonnet-5-5"++[[catalog.models]]+id = "anthropic/claude-sonnet-5-5"+label = "Claude Sonnet 5.5"+credits_per_million_input_tokens = 3000+credits_per_million_output_tokens = 15000+context_tokens = 1000000+reasoning = true+vision = true+`++describe('AI relay configuration', () => {+ test('reads the catalog, resolves secrets, and normalizes URLs', () => {+ const config = parseAIRelayTOML(source, environment)+ expect(config).toMatchObject({+ cloudURL: 'https://cloud.example.com',+ allowedOrigins: ['https://app.example.com'],+ maximumConcurrentRequests: 4,+ maximumRequestBytes: 16 * 1024 * 1024,+ databaseURL: environment.DATABASE_URL,+ upstreamURL: 'https://openrouter.ai/api/v1',+ upstreamKey: 'upstream-key'+ })+ expect(config.catalog).toEqual({+ defaultModelID: 'anthropic/claude-sonnet-5-5',+ models: [+ {+ id: 'anthropic/claude-sonnet-5-5',+ label: 'Claude Sonnet 5.5',+ creditsPerMillionInputTokens: 3000,+ creditsPerMillionOutputTokens: 15000,+ contextTokens: 1_000_000,+ capabilities: { reasoning: true, vision: true, tools: true }+ }+ ]+ })+ })++ test('the example file parses', async () => {+ const example = await readFile(cloudDeployPath('openpencil-ai-relay.example.toml'), 'utf8')+ expect(parseAIRelayTOML(example, environment).catalog.models).not.toBeEmpty()+ })++ test('requires the upstream key and a default model from the catalog', () => {+ expect(() => parseAIRelayTOML(source, { DATABASE_URL: environment.DATABASE_URL })).toThrow(+ 'OPENPENCIL_AI_RELAY_UPSTREAM_KEY'+ )+ expect(() =>+ parseAIRelayTOML(+ source.replace('default_model = "anthropic', 'default_model = "openai'),+ environment+ )+ ).toThrow(AIRelayConfigError)+ const duplicated = `${source}\n${source.slice(source.indexOf('[[catalog.models]]'))}`+ expect(() => parseAIRelayTOML(duplicated, environment)).toThrow('listed twice')+ })+})diff --git a/packages/cloud/tests/ai-relay/metering.test.ts b/packages/cloud/tests/ai-relay/metering.test.tsnew file mode 100644index 000000000..d9cb3c60c--- /dev/null+++ b/packages/cloud/tests/ai-relay/metering.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from 'bun:test'++import { creditsFor, meteredUsage } from '#cloud/ai-relay'+import type { AIModel } from '#cloud/contract'++const model: AIModel = {+ id: 'model',+ label: 'Model',+ creditsPerMillionInputTokens: 3000,+ creditsPerMillionOutputTokens: 15000,+ contextTokens: 200_000,+ capabilities: { reasoning: false, vision: false, tools: true }+}++function stream(...chunks: string[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder()+ return new ReadableStream({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(encoder.encode(chunk))+ controller.close()+ }+ })+}++describe('AI relay metering', () => {+ test('charges per million tokens and rounds up', () => {+ expect(creditsFor(model, { inputTokens: 1_000_000, outputTokens: 0 })).toBe(3000)+ expect(creditsFor(model, { inputTokens: 1000, outputTokens: 1000 })).toBe(18)+ expect(creditsFor(model, { inputTokens: 1, outputTokens: 0 })).toBe(1)+ expect(creditsFor(model, { inputTokens: 0, outputTokens: 0 })).toBe(0)+ })++ test('reads usage from a JSON answer', async () => {+ const body = JSON.stringify({+ choices: [],+ usage: { prompt_tokens: 12, completion_tokens: 34 }+ })+ expect(await meteredUsage(stream(body), false)).toEqual({ inputTokens: 12, outputTokens: 34 })+ expect(await meteredUsage(stream('{"choices":[]}'), false)).toBeNull()+ })++ test('reads usage from the last event that carries it, across chunk boundaries', async () => {+ const usage = await meteredUsage(+ stream(+ 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n: keep-alive\n\nda',+ 'ta: {"choices":[],"usage":{"prompt_tokens":5,"completion_tokens":7}}\r\n\r\n',+ 'data: [DONE]\n\n'+ ),+ true+ )+ expect(usage).toEqual({ inputTokens: 5, outputTokens: 7 })+ expect(await meteredUsage(stream('data: {"choices":[]}\n\ndata: [DONE]'), true)).toBeNull()+ })+})diff --git a/packages/cloud/tests/integration/ai-relay/app.test.ts b/packages/cloud/tests/integration/ai-relay/app.test.tsnew file mode 100644index 000000000..d86ca3bf3--- /dev/null+++ b/packages/cloud/tests/integration/ai-relay/app.test.ts@@ -0,0 +1,434 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { responseJSON } from '#cloud-tests/helpers/response'+import {+ createAIRelayApp,+ createAIRelayDatabase,+ migrateAIRelayDatabase,+ parseAIRelayConfig,+ type AIRelayConfigInput+} from '#cloud/ai-relay'+import {+ aiCatalogSchema,+ aiErrorSchema,+ aiUsagePageSchema,+ aiWalletSchema,+ CLOUD_AI_API_PATHS,+ CLOUD_AI_TOKEN_AUDIENCE+} from '#cloud/contract'+import { PGlite } from '@electric-sql/pglite'+import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT } from 'jose'+import { PGliteDialect } from 'kysely-pglite-dialect'+import * as v from 'valibot'++const CLOUD = 'https://cloud.example.com'+const APP = 'https://app.example.com'+const MODEL = 'anthropic/claude-sonnet-5-5'+const NOW = new Date('2026-10-21T12:00:00Z')++const configInput: AIRelayConfigInput = {+ schema_version: 1,+ relay: { cloud_url: CLOUD, allowed_origins: [APP], max_concurrent_requests: 1 },+ upstream: { base_url: 'https://upstream.example.com/api/v1' },+ catalog: {+ default_model: MODEL,+ models: [+ {+ id: MODEL,+ label: 'Claude Sonnet 5.5',+ credits_per_million_input_tokens: 3000,+ credits_per_million_output_tokens: 15000,+ context_tokens: 1_000_000+ }+ ]+ }+}++type UpstreamCall = {+ url: string+ authorization: string | null+ body: { [key: string]: unknown }+ signal: AbortSignal | null | undefined+}++const closers: (() => Promise<void>)[] = []+afterEach(async () => {+ for (const close of closers.splice(0)) await close()+})++function streamOf(...events: unknown[]): string {+ return events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n'+}++async function relay(+ upstream: (call: UpstreamCall) => Response = () => Response.json({}),+ options: { upstreamTimeoutMs?: number; maxRequestBytes?: number } = {}+) {+ const pglite = await PGlite.create({ dataDir: 'memory://' })+ const database = createAIRelayDatabase(new PGliteDialect(pglite))+ closers.push(() => database.destroy())+ await migrateAIRelayDatabase(database)++ const { privateKey, publicKey } = await generateKeyPair('ES256')+ const keys = createLocalJWKSet({ keys: [{ ...(await exportJWK(publicKey)), kid: 'cloud' }] })+ const calls: UpstreamCall[] = []+ const settled: Promise<unknown>[] = []+ const backgroundErrors: unknown[] = []+ const app = createAIRelayApp({+ config: parseAIRelayConfig(+ {+ ...configInput,+ relay: { ...configInput.relay, max_request_bytes: options.maxRequestBytes }+ },+ {+ DATABASE_URL: 'postgresql://unused',+ OPENPENCIL_AI_RELAY_UPSTREAM_KEY: 'upstream-key'+ }+ ),+ database,+ keys,+ now: () => NOW,+ upstreamTimeoutMs: options.upstreamTimeoutMs,+ waitUntil: (promise) => settled.push(promise),+ onBackgroundError: (error) => backgroundErrors.push(error),+ fetch: async (input, init) => {+ const call = {+ url: input,+ authorization: new Headers(init.headers).get('Authorization'),+ body: v.parse(v.pipe(v.string(), v.parseJson(), v.looseObject({})), init.body),+ signal: init.signal+ }+ calls.push(call)+ return upstream(call)+ }+ })++ const workspaceId = crypto.randomUUID()+ async function token(+ claims: { monthlyCreditAllowance?: number | null; workspaceId?: string } = {},+ options: { issuer?: string; signingKey?: CryptoKey } = {}+ ) {+ return new SignJWT({+ workspaceId: claims.workspaceId ?? workspaceId,+ monthlyCreditAllowance:+ claims.monthlyCreditAllowance === undefined ? 1000 : claims.monthlyCreditAllowance+ })+ .setProtectedHeader({ alg: 'ES256', kid: 'cloud' })+ .setIssuer(options.issuer ?? CLOUD)+ .setAudience(CLOUD_AI_TOKEN_AUDIENCE)+ .setSubject('user-1')+ .setIssuedAt()+ .setExpirationTime('10m')+ .sign(options.signingKey ?? privateKey)+ }+ const request = async (path: string, bearer: string, init: RequestInit = {}) =>+ app.request(path, {+ ...init,+ headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' }+ })+ const complete = async (bearer: string, body: Record<string, unknown>) =>+ request(CLOUD_AI_API_PATHS.chatCompletions, bearer, {+ method: 'POST',+ body: JSON.stringify(body)+ })+ return { app, calls, settled, backgroundErrors, token, request, complete, workspaceId }+}++describe('AI relay', () => {+ test('refuses requests without a token Cloud signed for this service', async () => {+ const context = await relay()+ const { privateKey: otherKey } = await generateKeyPair('ES256')+ const refused = [+ await context.app.request(CLOUD_AI_API_PATHS.catalog),+ await context.request(CLOUD_AI_API_PATHS.catalog, 'not-a-token'),+ await context.request(+ CLOUD_AI_API_PATHS.catalog,+ await context.token({}, { issuer: 'https://other.example.com' })+ ),+ await context.request(+ CLOUD_AI_API_PATHS.catalog,+ await context.token({}, { signingKey: otherKey })+ )+ ]+ for (const response of refused) {+ expect(response.status).toBe(401)+ expect((await responseJSON(response, aiErrorSchema)).error.code).toBe('unauthorized')+ }+ const catalog = await context.request(CLOUD_AI_API_PATHS.catalog, await context.token())+ expect((await responseJSON(catalog, aiCatalogSchema)).defaultModelID).toBe(MODEL)+ })++ test('proxies a completion with the upstream key and charges its usage', async () => {+ const context = await relay(() =>+ Response.json({+ choices: [{ message: { role: 'assistant', content: 'Hi' } }],+ usage: { prompt_tokens: 100_000, completion_tokens: 10_000 }+ })+ )+ const bearer = await context.token()+ const response = await context.complete(bearer, {+ model: MODEL,+ messages: [{ role: 'user', content: 'Hello' }]+ })+ expect(response.status).toBe(200)+ expect(context.calls).toEqual([+ {+ url: 'https://upstream.example.com/api/v1/chat/completions',+ authorization: 'Bearer upstream-key',+ body: { model: MODEL, messages: [{ role: 'user', content: 'Hello' }] },+ signal: expect.any(AbortSignal)+ }+ ])+ expect(await response.json()).toMatchObject({ choices: [{ message: { content: 'Hi' } }] })+ await Promise.all(context.settled)++ // 100k input tokens at 3,000 and 10k output tokens at 15,000 credits per million.+ const wallet = await responseJSON(+ await context.request(CLOUD_AI_API_PATHS.wallet, bearer),+ aiWalletSchema+ )+ expect(wallet).toEqual({+ balance: 550,+ buckets: [{ kind: 'allowance', remaining: 550, expiresAt: '2026-11-01T00:00:00.000Z' }]+ })+ const usage = await responseJSON(+ await context.request(CLOUD_AI_API_PATHS.usage, bearer),+ aiUsagePageSchema+ )+ expect(usage.entries).toMatchObject([+ { kind: 'model', modelID: MODEL, userId: 'user-1', credits: 450 }+ ])+ expect(usage.next).toBeNull()+ })++ test('reports a completion the upstream gives no usage for, which goes uncharged', async () => {+ const context = await relay(() =>+ Response.json({ choices: [{ message: { role: 'assistant', content: 'Hi' } }] })+ )+ const bearer = await context.token()+ const response = await context.complete(bearer, { model: MODEL, messages: [] })+ expect(response.status).toBe(200)+ await response.text()+ await Promise.all(context.settled)++ expect(context.backgroundErrors).toHaveLength(1)+ const usage = await responseJSON(+ await context.request(CLOUD_AI_API_PATHS.usage, bearer),+ aiUsagePageSchema+ )+ expect(usage.entries).toEqual([])+ })++ test('asks a streamed completion for usage and charges it after the stream ends', async () => {+ const context = await relay(+ () =>+ new Response(+ streamOf(+ { choices: [{ delta: { content: 'Hi' } }] },+ { choices: [], usage: { prompt_tokens: 1000, completion_tokens: 1000 } }+ ),+ { headers: { 'Content-Type': 'text/event-stream' } }+ )+ )+ const bearer = await context.token()+ const response = await context.complete(bearer, {+ model: MODEL,+ stream: true,+ stream_options: { keep: true },+ messages: []+ })+ expect(response.headers.get('Content-Type')).toBe('text/event-stream')+ expect(context.calls[0]?.body.stream_options).toEqual({ include_usage: true })+ expect(await response.text()).toContain('"content":"Hi"')+ await Promise.all(context.settled)+ const wallet = await responseJSON(+ await context.request(CLOUD_AI_API_PATHS.wallet, bearer),+ aiWalletSchema+ )+ expect(wallet.balance).toBe(1000 - 18)+ })++ test('refuses models outside the catalog and workspaces with no credits left', async () => {+ const context = await relay(() =>+ Response.json({ choices: [], usage: { prompt_tokens: 1_000_000, completion_tokens: 0 } })+ )+ const notAllowed = await context.complete(await context.token(), { model: 'other/model' })+ expect(notAllowed.status).toBe(403)+ expect((await responseJSON(notAllowed, aiErrorSchema)).error.code).toBe('model_not_allowed')++ // The first request is admitted with credits left and overdraws the allowance.+ const bearer = await context.token()+ expect((await context.complete(bearer, { model: MODEL })).status).toBe(200)+ await Promise.all(context.settled)+ const exhausted = await context.complete(bearer, { model: MODEL })+ expect(exhausted.status).toBe(402)+ expect((await responseJSON(exhausted, aiErrorSchema)).error.code).toBe('insufficient_credits')+ expect(context.calls).toHaveLength(1)++ // Another workspace, and one without an allowance, are unaffected.+ const other = await context.token({ workspaceId: crypto.randomUUID() })+ expect((await context.complete(other, { model: MODEL })).status).toBe(200)+ const unlimited = await context.token({ monthlyCreditAllowance: null })+ const wallet = await responseJSON(+ await context.request(CLOUD_AI_API_PATHS.wallet, unlimited),+ aiWalletSchema+ )+ expect(wallet).toEqual({ balance: null, buckets: [] })+ expect((await context.complete(unlimited, { model: MODEL })).status).toBe(200)+ })++ test('limits a workspace to its concurrent requests until metering settles', async () => {+ let finish: (() => void) | undefined+ const context = await relay(+ () =>+ new Response(+ new ReadableStream({+ start(controller) {+ finish = () => {+ controller.enqueue(new TextEncoder().encode('{"choices":[]}'))+ controller.close()+ }+ }+ })+ )+ )+ const bearer = await context.token()+ const first = await context.complete(bearer, { model: MODEL })+ expect(first.status).toBe(200)+ const second = await context.complete(bearer, { model: MODEL })+ expect(second.status).toBe(429)+ expect((await responseJSON(second, aiErrorSchema)).error.code).toBe('rate_limited')+ finish?.()+ await first.text()+ await Promise.all(context.settled)+ expect((await context.complete(bearer, { model: MODEL })).status).toBe(200)+ })++ test('passes upstream failures through and frees the request slot', async () => {+ const context = await relay(() =>+ Response.json({ error: { message: 'Upstream is down' } }, { status: 503 })+ )+ const bearer = await context.token()+ for (let attempt = 0; attempt < 2; attempt++) {+ const response = await context.complete(bearer, { model: MODEL })+ expect(response.status).toBe(503)+ expect(await response.json()).toEqual({ error: { message: 'Upstream is down' } })+ }+ expect((await context.complete(bearer, { messages: [] })).status).toBe(400)+ })++ test('answers browsers only from allowed origins', async () => {+ const context = await relay()+ const preflight = (origin: string) =>+ context.app.request(CLOUD_AI_API_PATHS.chatCompletions, {+ method: 'OPTIONS',+ headers: {+ Origin: origin,+ 'Access-Control-Request-Method': 'POST',+ 'Access-Control-Request-Headers': 'authorization,content-type'+ }+ })+ const allowed = await preflight(APP)+ expect(allowed.headers.get('Access-Control-Allow-Origin')).toBe(APP)+ expect(allowed.headers.get('Access-Control-Allow-Headers')).toContain('Authorization')+ expect(+ (await preflight('https://evil.example.com')).headers.get('Access-Control-Allow-Origin')+ ).toBeNull()+ })++ test('pages usage newest first and rejects a malformed cursor', async () => {+ const context = await relay(() =>+ Response.json({ choices: [], usage: { prompt_tokens: 1, completion_tokens: 0 } })+ )+ const bearer = await context.token({ monthlyCreditAllowance: null })+ for (let index = 0; index < 51; index++) {+ await context.complete(bearer, { model: MODEL })+ await Promise.all(context.settled.splice(0))+ }+ const first = await responseJSON(+ await context.request(CLOUD_AI_API_PATHS.usage, bearer),+ aiUsagePageSchema+ )+ expect(first.entries).toHaveLength(50)+ expect(first.next).not.toBeNull()+ const second = await responseJSON(+ await context.request(+ `${CLOUD_AI_API_PATHS.usage}?cursor=${encodeURIComponent(first.next ?? '')}`,+ bearer+ ),+ aiUsagePageSchema+ )+ expect(second.entries).toHaveLength(1)+ expect(second.next).toBeNull()+ const seen = new Set([...first.entries, ...second.entries].map((entry) => entry.id))+ expect(seen.size).toBe(51)+ for (const cursor of ['12.not-an-id', `99999999999999999.${crypto.randomUUID()}`]) {+ expect(+ (await context.request(`${CLOUD_AI_API_PATHS.usage}?cursor=${cursor}`, bearer)).status+ ).toBe(400)+ }+ })++ test('forwards only chat completion fields, so routing fields cannot reach other models', async () => {+ const context = await relay(() => Response.json({ choices: [] }))+ await context.complete(await context.token(), {+ model: MODEL,+ messages: [{ role: 'user', content: 'Hi' }],+ tools: [],+ temperature: 0.2,+ models: ['other/expensive-model'],+ provider: { order: ['other'] },+ plugins: [{ id: 'web' }],+ route: 'fallback',+ user: 'someone'+ })+ expect(context.calls[0]?.body).toEqual({+ model: MODEL,+ messages: [{ role: 'user', content: 'Hi' }],+ tools: [],+ temperature: 0.2+ })+ })++ test('refuses a body past the size limit, even without Content-Length, before the upstream', async () => {+ const context = await relay(undefined, { maxRequestBytes: 1024 })+ const bearer = await context.token()+ const oversized = new TextEncoder().encode(+ JSON.stringify({ model: MODEL, messages: [{ role: 'user', content: 'x'.repeat(4096) }] })+ )+ const response = await context.request(CLOUD_AI_API_PATHS.chatCompletions, bearer, {+ method: 'POST',+ body: new ReadableStream({+ start(controller) {+ controller.enqueue(oversized)+ controller.close()+ }+ })+ })+ expect(response.status).toBe(413)+ expect(context.calls).toHaveLength(0)+ expect((await context.complete(bearer, { model: MODEL, messages: [] })).status).not.toBe(413)+ })++ test('gives up on a stalled upstream and frees its request slot', async () => {+ const context = await relay(+ ({ signal }) =>+ new Response(+ new ReadableStream({+ start(controller) {+ signal?.addEventListener('abort', () => controller.error(signal.reason))+ }+ })+ ),+ { upstreamTimeoutMs: 50 }+ )+ const bearer = await context.token()+ const stalled = await context.complete(bearer, { model: MODEL })+ expect(stalled.status).toBe(200)+ expect(context.calls[0]?.signal).toBeInstanceOf(AbortSignal)+ await Promise.all(context.settled)+ await stalled.text().catch(() => undefined)+ expect(context.backgroundErrors).toHaveLength(1)+ expect((await context.complete(bearer, { model: MODEL })).status).toBe(200)+ })+})diff --git a/packages/cloud/tsdown.standalone.config.ts b/packages/cloud/tsdown.standalone.config.tsindex 89edb5029..bd4bf71c6 100644--- a/packages/cloud/tsdown.standalone.config.ts+++ b/packages/cloud/tsdown.standalone.config.ts@@ -3,7 +3,10 @@ import { fileURLToPath } from 'node:url'import { defineConfig } from 'tsdown'export default defineConfig({- entry: { server: './src/runtime/node/main.ts' },+ entry: {+ server: './src/runtime/node/main.ts',+ 'ai-relay': './src/runtime/node/ai-relay/main.ts'+ },platform: 'node',format: ['esm'],dts: false,diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 614c9ab6b..ecd3b25ef 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -288,6 +288,18 @@ share, including the service's catalog, wallet, and error codes, is `src/contracown version so a service can change without a Cloud release. A `[billing]` table only advertiseswhere people manage their plan.+A service answers below its endpoint at the paths in `CLOUD_AI_API_PATHS`: model requests follow+the OpenAI chat completions API, so editors reach it with an OpenAI-compatible client, and the+catalog, wallet, and usage pages are the contract's own. The reference service is the AI relay in+`src/ai-relay`, run by `src/runtime/node/ai-relay`: it verifies tokens against Cloud's keys,+forwards completions to one upstream with one key, and keeps one usage row per settled request, so a+workspace's monthly spend is the sum of its rows. It reads usage from the upstream's answer, asking+streams for it with `stream_options.include_usage`, and keeps reading after the editor disconnects+so a request is still charged. It admits a request while credits remain and charges it afterwards,+so in-flight requests can overdraw an allowance; the official service reserves credits instead. It forwards only+chat completion fields, so a router's fallback or provider fields cannot run a model outside the+catalog on its key. An upstream answer has ten minutes in all, streamed or not, before the relay ends it.+Services that decide entitlements, such as billing, write them through the internal API rather thanthe database: `setWorkspaceEntitlements` in `src/server/internal`, which runtimes expose over HTTPwith a bearer token (`[internal_api]`) or a private transport of their own. Every write carries andiff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.mdindex bea27018f..e70dfb304 100644--- a/packages/docs/reference/self-hosting-cloud.md+++ b/packages/docs/reference/self-hosting-cloud.md@@ -88,6 +88,17 @@ Each runs from a repository checkout with the same `OPENPENCIL_CLOUD_CONFIG` and| `bun --filter @open-pencil/cloud entitlements` | Inspect or set a workspace's entitlements || `bun --filter @open-pencil/cloud admin` | Approve enrollment and grant deployment admin |+## AI++Cloud does not run models itself. It advertises an AI service and signs short-lived tokens that let workspace members use it, and the service holds each workspace to the credit allowance its entitlements grant. The repository's AI relay is a minimal service for this: it forwards chat completions to one OpenAI-compatible upstream, such as OpenRouter, with your key.++1. Create a P-256 signing key, `openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256`, and pass the PEM in `OPENPENCIL_CLOUD_AI_SIGNING_KEY`. Cloud refuses to start with a key it cannot sign with.+2. Add `[ai] endpoint` to the Cloud TOML with the relay's address, and enable `[entitlements.ai]`, optionally with a `monthly_credit_allowance`; without one, the relay does not limit spend. With entitlements from the database, set them per workspace with the `entitlements` command instead.+3. Copy [`openpencil-ai-relay.example.toml`](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/openpencil-ai-relay.example.toml), set `relay.cloud_url` to Cloud's `public_url`, `allowed_origins` to the browser editors, and list the models with their credit prices.+4. Start it with `OPENPENCIL_AI_RELAY_CONFIG`, `OPENPENCIL_AI_RELAY_UPSTREAM_KEY`, and `DATABASE_URL` set: `node --env-file=.env dist-standalone/ai-relay.mjs`. It listens on `PORT` (default `8788`) and can share Cloud's database, keeping its own tables and migration history.++The relay charges a request once the upstream reports its usage, and admits one while the workspace has credits left, so requests already in flight can overdraw the month's allowance by what they cost; `relay.max_concurrent_requests` bounds them. A workspace's allowance renews at the start of each UTC month. It refuses a model request larger than `relay.max_request_bytes` (16 MiB by default) before reading it all. Choose an upstream that reports token usage: a request it reports none for is logged as an error and not charged.+Set `email.transport = "smtp"` with an `[email.smtp]` table, `"cloudflare"` on Cloudflare Workers to send through Cloudflare Email Service from an address on a domain onboarded to it (the Worker needs the `send_email` binding named `EMAIL`, and sending to addresses you haven't verified needs Workers Paid), or `"none"` to send nothing; invitations still work through their links. Messages go through an encrypted outbox in PostgreSQL, tuned under `[workers.email]`. Delivery records that the SMTP server accepted a message, not that it reached the inbox.