diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ba29fe..a524ddf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,25 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.6.0] - 2026-10-30 + +### Added + +- **AI for Cross Events 2.0** (protocol §3b) — sites call AI through the Hub, which holds the Claude + API key, checks each licence's monthly cap and meters every call. `POST /api/installs/ai/status` + tells a site whether to show its AI buttons (hidden at a R0 cap, disabled once the month's + allowance is used up); `POST /api/installs/ai/complete` runs one helper call (Claude Haiku 5.5, + instructions prompt-cached, optional JSON schema). Both are signed like the heartbeat. +- **Metering in rand:** real cost from the tokens, the model's price and an exchange rate set in the + Hub; charged = real × (1 + markup). The cap counts charged rand. The worst case of each call is + held against the cap in a locked transaction before Claude is called, so calls at the same moment + can't push a month over; failed calls cost nothing, refused or cut-off answers cost what they used. + Only the install, helper, tokens, cost and time are kept — never prompt or response text. +- **Settings → AI:** Claude API key (encrypted), model, prices, exchange rate, default markup, + **Test the saved key**, and every site's use per month (real cost, charged, profit). +- **Licences:** an AI markup override next to the AI cap. **Install page:** this month's AI use + against the cap, use by helper, and six months of real cost, charged and profit. + ## [1.5.0] - 2026-10-28 ### Added diff --git a/README.md b/README.md index bbfaad6..74b3aa4 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,17 @@ and `HUB_PUBLIC_KEY` (the public key shown in Hub → Settings) in Cross Events' - **Notices** (Notices page) are banners on churches' sites for their admins and supervisors, emails to them, or both — e.g. planned maintenance. +## AI (Cross Events 2.0) + +Sites call AI through the Hub (protocol §3b), so the Claude API key never leaves this server. +Set it up in **Settings → AI**: the key, the model (Claude Haiku 5.5), its prices, the exchange rate +and the default markup — AI stays off for every site until the key and exchange rate are saved; +**Test the saved key** checks them. Each licence has a monthly **AI cap** in rand (0 = off) and an +optional markup override, on the customer's page. The cap counts what the church is charged +(real cost plus markup); the Hub checks the worst case before every call, so a month can't run over. +Use per site (real cost, charged, profit) is on Settings → AI and on each install's page. No prompt +or response text is stored. + ## The licence signing key Licences are tokens signed with an Ed25519 key. **The private key exists only on the Hub server**; diff --git a/backend/package-lock.json b/backend/package-lock.json index 62aa01b..3afa1cb 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,14 +1,15 @@ { "name": "events-hub-backend", - "version": "1.5.0", + "version": "1.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "1.5.0", + "version": "1.6.0", "hasInstallScript": true, "dependencies": { + "@anthropic-ai/sdk": "^1.3.0", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", @@ -28,6 +29,28 @@ "node": ">=20" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-1.3.0.tgz", + "integrity": "sha512-k7z9BlLLPxfZH+ov7dS6EnaN/wiZeV8YNT1LZfrpAHIy7oY7pHr4UzirF9f2OlHtFEnRBOX+AZQ91Y5fK+TPTw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.4.1", + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -494,6 +517,15 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -1198,6 +1230,15 @@ "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/@parcel/watcher": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", @@ -1918,6 +1959,12 @@ "@sinonjs/commons": "^3.0.1" } }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -4052,6 +4099,12 @@ "fast-decode-uri-component": "^1.0.1" } }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, "node_modules/fast-uri": { "version": "3.1.9", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", @@ -5331,6 +5384,19 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -6894,6 +6960,16 @@ "node": ">=10" } }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -7145,6 +7221,12 @@ "node": ">=0.6" } }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", diff --git a/backend/package.json b/backend/package.json index 3941d91..5806d12 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "1.5.0", + "version": "1.6.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", @@ -18,6 +18,7 @@ "generate-keys": "node scripts/generate-keys.js" }, "dependencies": { + "@anthropic-ai/sdk": "^1.3.0", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", diff --git a/backend/prisma/migrations/20261030070818_ai_usage/migration.sql b/backend/prisma/migrations/20261030070818_ai_usage/migration.sql new file mode 100644 index 0000000..15cd5b2 --- /dev/null +++ b/backend/prisma/migrations/20261030070818_ai_usage/migration.sql @@ -0,0 +1,35 @@ +-- CreateEnum +CREATE TYPE "AiUsageStatus" AS ENUM ('reserved', 'done', 'failed'); + +-- AlterTable +ALTER TABLE "Licence" ADD COLUMN "aiMarkupPercent" INTEGER; + +-- CreateTable +CREATE TABLE "AiUsage" ( + "id" TEXT NOT NULL, + "installId" TEXT NOT NULL, + "helper" TEXT NOT NULL, + "model" TEXT NOT NULL, + "month" TEXT NOT NULL, + "status" "AiUsageStatus" NOT NULL DEFAULT 'reserved', + "inputTokens" INTEGER NOT NULL DEFAULT 0, + "outputTokens" INTEGER NOT NULL DEFAULT 0, + "cacheReadTokens" INTEGER NOT NULL DEFAULT 0, + "cacheWriteTokens" INTEGER NOT NULL DEFAULT 0, + "realMillicents" INTEGER NOT NULL DEFAULT 0, + "chargedMillicents" INTEGER NOT NULL DEFAULT 0, + "markupPercent" INTEGER NOT NULL, + "usdZar" DOUBLE PRECISION NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "AiUsage_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "AiUsage_installId_month_idx" ON "AiUsage"("installId", "month"); + +-- CreateIndex +CREATE INDEX "AiUsage_month_idx" ON "AiUsage"("month"); + +-- AddForeignKey +ALTER TABLE "AiUsage" ADD CONSTRAINT "AiUsage_installId_fkey" FOREIGN KEY ("installId") REFERENCES "Install"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 9f9cb20..2518a14 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -55,8 +55,10 @@ model Licence { // Null = no end date. expiresAt DateTime? graceDays Int @default(14) - // Cross Events 2.0: monthly AI spend cap (in cents, rand). 0 = AI off. + // Cross Events 2.0: monthly AI spend cap (in cents, rand), counted in charged rand. 0 = AI off. aiMonthlyCapCents Int @default(0) + // Markup on the real AI cost, in %. Null = the Hub default (Settings → AI). + aiMarkupPercent Int? notes String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -90,10 +92,45 @@ model Install { releasedAt DateTime? heartbeats Heartbeat[] events InstallEvent[] + aiUsage AiUsage[] @@index([lastHeartbeatAt]) } +enum AiUsageStatus { + // The worst case is held against the cap while the call runs. + reserved + done + failed +} + +// One AI call from an install (Cross Events 2.0). No prompt or response text is kept — only what's +// needed to meter it. Amounts are in millicents (1/1000 of a cent, rand): a call costs a few cents. +model AiUsage { + id String @id @default(uuid()) + installId String + install Install @relation(fields: [installId], references: [id], onDelete: Cascade) + helper String + model String + // The billing month, YYYY-MM in South African time. + month String + status AiUsageStatus @default(reserved) + inputTokens Int @default(0) + outputTokens Int @default(0) + cacheReadTokens Int @default(0) + cacheWriteTokens Int @default(0) + // What Claude cost (real) and what the church is charged (real × (1 + markup)). + realMillicents Int @default(0) + chargedMillicents Int @default(0) + markupPercent Int + // Rand per US dollar used for this call. + usdZar Float + createdAt DateTime @default(now()) + + @@index([installId, month]) + @@index([month]) +} + // Every heartbeat for 30 days, then one per install per day. model Heartbeat { id String @id @default(uuid()) diff --git a/backend/src/app.js b/backend/src/app.js index e0a31b8..e86c77e 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -8,8 +8,9 @@ app.disable('x-powered-by'); // Installs call the Hub server-to-server; only the dashboard needs CORS. app.use(cors({ origin: (process.env.FRONTEND_URL || 'http://localhost:3200').replace(/\/$/, '') })); -// Keep the exact bytes: heartbeat signatures are over the raw body. -app.use(express.json({ limit: '200kb', verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } })); +// Keep the exact bytes: heartbeat signatures are over the raw body. 300 KB fits the largest AI +// request the Hub accepts (utils/ai.js MAX_INPUT_TOKENS). +app.use(express.json({ limit: '300kb', verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } })); app.get('/api/health', (req, res) => res.json({ ok: true })); app.use('/api', require('./routes/installApi')); diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 525f211..ad0e38f 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -13,6 +13,7 @@ const { smtpConfigured, testSmtp } = require('../utils/mail'); const { VERSION_RE, sortReleases, syncLatestVersion } = require('../utils/releases'); const { emailNotice } = require('../utils/notices'); const { parseRepoUrl, syncReleases } = require('../utils/releaseSync'); +const ai = require('../utils/ai'); const router = express.Router(); router.use(protect); @@ -134,6 +135,14 @@ function licenceData(body, { partial = false } = {}) { if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.'); data.aiMonthlyCapCents = n; } + if (body?.aiMarkupPercent !== undefined) { + if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null; + else { + const n = parseInt(body.aiMarkupPercent, 10); + if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.'); + data.aiMarkupPercent = n; + } + } if (body?.status !== undefined) { if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.'); data.status = body.status; @@ -203,7 +212,8 @@ router.get('/installs/:id', wrap(async (req, res) => { // What the install would be told right now, for checking. licence = { ...install.licence, tokenPreview: licenceToken.buildPayload(install.licence, install, install.customer.name) }; } - res.json({ ...safe, licence, summary: summary(install, settings), heartbeats }); + const [aiStatus, aiMonths, aiHelpers] = await Promise.all([ai.statusFor(install), ai.usageByMonth(install.id), ai.usageByHelper(install.id)]); + res.json({ ...safe, licence, summary: summary(install, settings), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers } }); })); router.put('/installs/:id', wrap(async (req, res) => { @@ -386,14 +396,27 @@ function checkSmtp(values) { // What the audit log records: never the password, only that it changed. function auditValues(values) { - const { smtp_pass, smtp_pass_clear, release_repo_token, release_repo_token_clear, ...rest } = values; + const { smtp_pass, smtp_pass_clear, release_repo_token, release_repo_token_clear, ai_api_key, ai_api_key_clear, ...rest } = values; if (smtp_pass_clear) rest.smtp_pass = '(removed)'; else if (smtp_pass) rest.smtp_pass = '(changed)'; if (release_repo_token_clear) rest.release_repo_token = '(removed)'; else if (release_repo_token) rest.release_repo_token = '(changed)'; + if (ai_api_key_clear) rest.ai_api_key = '(removed)'; + else if (ai_api_key) rest.ai_api_key = '(changed)'; return rest; } +function checkAi(values) { + for (const [key, label] of [['ai_input_usd_per_mtok', 'Input price'], ['ai_output_usd_per_mtok', 'Output price'], ['ai_usd_zar', 'Exchange rate']]) { + if (values[key] != null && values[key] !== '' && !(parseFloat(values[key]) >= 0)) throw bad(`${label} is a number.`); + } + if (values.ai_markup_percent != null && values.ai_markup_percent !== '') { + const n = Number(values.ai_markup_percent); + if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The default markup is a whole number of % (0–500).'); + } + if (values.ai_model != null && !/^[a-z0-9][a-z0-9.-]{2,60}$/.test(String(values.ai_model).trim())) throw bad('The model looks like claude-haiku-5-5.'); +} + router.put('/settings', wrap(async (req, res) => { // The latest version follows the Releases page; the sync writes its own status. // eslint-disable-next-line no-unused-vars @@ -401,6 +424,8 @@ router.put('/settings', wrap(async (req, res) => { if (values.release_repo_url && !parseRepoUrl(values.release_repo_url)) throw bad('The repository address looks like https://git.example.com/owner/repo.'); if (values.release_notes_path != null && !String(values.release_notes_path).trim()) values.release_notes_path = 'WHATS-NEW.md'; checkSmtp(values); + checkAi(values); + if (values.ai_model != null) values.ai_model = String(values.ai_model).trim(); const settings = await setSettings(values); await audit(req, 'settings_updated', null, auditValues(values)); res.json({ settings, smtp: await smtpConfigured() }); @@ -422,5 +447,27 @@ router.post('/settings/smtp-test', smtpTestLimiter, wrap(async (req, res) => { res.json({ to }); })); +// ─── AI ─────────────────────────────────────────────────────────────────────── + +// A tiny call with the saved key and model, to check they work. Not metered to any install. +router.post('/settings/ai-test', smtpTestLimiter, wrap(async (req, res) => { + try { + const result = await ai.testCall(await getSettings()); + await audit(req, 'ai_test_ok', null, { model: result.model }); + res.json(result); + } catch (e) { + await audit(req, 'ai_test_failed', null, { error: String(e.message).slice(0, 300) }); + throw bad(e.message, e.status || 502); + } +})); + +// Every install's AI use in a month (YYYY-MM, default this month): real cost, charged, profit. +router.get('/ai-usage', wrap(async (req, res) => { + const month = /^\d{4}-\d{2}$/.test(String(req.query.month || '')) ? String(req.query.month) : ai.monthOf(); + const installs = await ai.usageForMonth(month); + const sum = key => Math.round(installs.reduce((n, i) => n + i[key], 0) * 100) / 100; + res.json({ month, installs, totals: { calls: installs.reduce((n, i) => n + i.calls, 0), realCents: sum('realCents'), chargedCents: sum('chargedCents'), profitCents: sum('profitCents') } }); +})); + module.exports = router; module.exports.summary = summary; diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index b649048..4e840b4 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -16,6 +16,7 @@ const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/upd const { sendMail } = require('../utils/mail'); const { releasesForInstall } = require('../utils/releases'); const { noticesForInstall } = require('../utils/notices'); +const ai = require('../utils/ai'); const router = express.Router(); @@ -24,6 +25,8 @@ const HEARTBEAT_MINUTES = 15; const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } }); const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } }); const updateRequestLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } }); +// AI is limited by money (the cap); this only stops a runaway loop. +const aiLimiter = rateLimit({ windowMs: 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many AI requests — wait a minute.', code: 'RATE_LIMITED' } }); const fail = (res, status, code, message) => res.status(status).json({ code, message }); @@ -246,5 +249,33 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req, } }); +// ─── AI (Cross Events 2.0, §3b) ─────────────────────────────────────────────── + +// What the install's AI buttons should do: hidden, working, or disabled until the allowance renews. +router.post('/installs/ai/status', aiLimiter, async (req, res) => { + try { + const install = await signedInstall(req, res); + if (!install) return; + res.json(await ai.statusFor(install)); + } catch (e) { + console.error('[ai/status]', e); + fail(res, 500, 'SERVER_ERROR', 'The Hub could not check the AI allowance.'); + } +}); + +// One helper call: the Hub adds the key, checks the cap, calls Claude and meters the call. +router.post('/installs/ai/complete', aiLimiter, async (req, res) => { + let install; + try { + install = await signedInstall(req, res); + if (!install) return; + res.json(await ai.complete(install, req.body)); + } catch (e) { + if (e.status && e.code) return res.status(e.status).json({ code: e.code, message: e.message, ...(e.aiStatus ? { status: e.aiStatus } : {}) }); + console.error('[ai/complete]', e); + fail(res, 500, 'SERVER_ERROR', 'The Hub could not run this AI request.'); + } +}); + module.exports = router; module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS; diff --git a/backend/src/utils/ai.js b/backend/src/utils/ai.js new file mode 100644 index 0000000..c9595a8 --- /dev/null +++ b/backend/src/utils/ai.js @@ -0,0 +1,345 @@ +/** + * The AI proxy for Cross Events 2.0 (docs/hub-protocol.md §3b). Installs never hold the Claude API + * key: they send one helper call here, the Hub checks the licence's monthly cap, calls Claude and + * meters the call in rand. + * + * Money is counted in millicents (1/1000 of a cent, rand). The cap is counted in *charged* rand + * (real cost × (1 + markup)), so the real spend can never be more than cap ÷ (1 + markup). + * Before each call the worst case (the estimated prompt plus max_tokens, at the markup) is held + * against the cap inside a transaction with a per-install lock, so several people clicking at once + * can't push a month over. When the call returns, the hold becomes the real amount. + * + * No prompt or response text is stored — only the install, helper, tokens, cost and time. + */ + +const Anthropic = require('@anthropic-ai/sdk'); +const prisma = require('../config/db'); +const { getSettings, aiApiKey } = require('./settings'); + +// South African time (UTC+2, no daylight saving): the month the cap belongs to. +const SAST_MS = 2 * 60 * 60 * 1000; +// Cache writes cost 1.25× the input price, cache reads 0.1×. +const CACHE_WRITE = 1.25; +const CACHE_READ = 0.1; +// Prompts are priced higher from 100K tokens, so the Hub refuses anything close to it. +const MAX_INPUT_TOKENS = 90000; +const MAX_OUTPUT_TOKENS = 8000; +// A hold whose call never finished (the process stopped) stops counting after this long. +const STALE_HOLD_MS = 15 * 60 * 1000; +// The smallest call worth allowing: below this much room left, the cap counts as reached. +const SMALLEST_CALL = { inputTokens: 2000, outputTokens: 1000 }; +const HELPER_RE = /^[a-z][a-z0-9_]{1,39}$/; +const EFFORTS = ['low', 'medium', 'high']; + +const fail = (status, code, message) => Object.assign(new Error(message), { status, code }); + +/** The billing month of a moment, "YYYY-MM" in South African time. */ +function monthOf(date = new Date()) { + return new Date(date.getTime() + SAST_MS).toISOString().slice(0, 7); +} + +/** The day the allowance renews: the 1st of the next month ("YYYY-MM-DD"). */ +function renewsOn(date = new Date()) { + const [y, m] = monthOf(date).split('-').map(Number); + return m === 12 ? `${y + 1}-01-01` : `${y}-${String(m + 1).padStart(2, '0')}-01`; +} + +/** + * Prices for a call, or null when the Hub's AI isn't set up (no key or no exchange rate). + * `licence.aiMarkupPercent` overrides the Hub's default markup. + */ +function pricing(settings, licence, hasKey) { + const inUsd = parseFloat(settings.ai_input_usd_per_mtok); + const outUsd = parseFloat(settings.ai_output_usd_per_mtok); + const usdZar = parseFloat(settings.ai_usd_zar); + const markup = licence?.aiMarkupPercent ?? parseInt(settings.ai_markup_percent, 10); + if (!hasKey || !settings.ai_model || !(inUsd >= 0) || !(outUsd > 0) || !(usdZar > 0) || !(markup >= 0)) return null; + return { model: settings.ai_model, inUsd, outUsd, usdZar, markup }; +} + +/** Real and charged cost of some usage, in millicents (rounded up). */ +function costOf(usage, price) { + const usd = ((usage.inputTokens || 0) * price.inUsd + + (usage.cacheWriteTokens || 0) * price.inUsd * CACHE_WRITE + + (usage.cacheReadTokens || 0) * price.inUsd * CACHE_READ + + (usage.outputTokens || 0) * price.outUsd) / 1e6; + const real = usd * price.usdZar * 100 * 1000; + return { real: Math.ceil(real), charged: Math.ceil(real * (1 + price.markup / 100)) }; +} + +/** + * A safe over-estimate of the prompt's tokens without asking the API: about 2.5 characters a token + * (English prose is nearer 4; JSON and numbers less), plus room for the request's framing. + */ +function estimateInputTokens(...parts) { + const chars = parts.reduce((n, p) => n + (p == null ? 0 : typeof p === 'string' ? p.length : JSON.stringify(p).length), 0); + return Math.ceil(chars / 2.5) + 100; +} + +/** The most a call can cost: every prompt token written to the cache, and every output token used. */ +function worstCase(inputTokens, maxTokens, price) { + return costOf({ cacheWriteTokens: inputTokens, outputTokens: maxTokens }, price).charged; +} + +/** Whether a licence may use AI at all right now (apart from the cap). */ +function licenceAllows(licence, now = new Date()) { + if (!licence || licence.status !== 'active') return false; + if (!licence.expiresAt) return true; + return now.getTime() < new Date(licence.expiresAt).getTime() + licence.graceDays * 86400000; +} + +/** + * What the install's AI buttons should do (protocol §3b): + * - enabled false → hidden (cap R0, licence not active, or the Hub's AI not set up); + * - capReached → shown but disabled until `renewsOn` or until the cap is raised. + */ +function statusOf({ licence, price, chargedMillicents, now = new Date() }) { + const capCents = licence?.aiMonthlyCapCents || 0; + const usedCents = Math.ceil(chargedMillicents / 1000); + const base = { capCents, usedCents, renewsOn: renewsOn(now), usedPercent: capCents ? Math.min(100, Math.round((usedCents / capCents) * 100)) : 0 }; + if (!price || capCents <= 0 || !licenceAllows(licence, now)) return { enabled: false, capReached: false, ...base }; + const room = capCents * 1000 - chargedMillicents; + return { enabled: true, capReached: room < worstCase(SMALLEST_CALL.inputTokens, SMALLEST_CALL.outputTokens, price), ...base }; +} + +/** Check and clean what an install sends to /installs/ai/complete. */ +function cleanRequest(body) { + const helper = String(body?.helper || ''); + if (!HELPER_RE.test(helper)) throw fail(400, 'BAD_REQUEST', 'helper must be a short lower-case name like draft_event.'); + if (typeof body.system !== 'string' || !body.system.trim() || body.system.length > 20000) throw fail(400, 'BAD_REQUEST', 'system must be text (at most 20 000 characters).'); + if (typeof body.input !== 'string' || !body.input.trim()) throw fail(400, 'BAD_REQUEST', 'input must be text.'); + const maxTokens = Number(body.maxTokens); + if (!Number.isInteger(maxTokens) || maxTokens < 1 || maxTokens > MAX_OUTPUT_TOKENS) throw fail(400, 'BAD_REQUEST', `maxTokens must be 1–${MAX_OUTPUT_TOKENS}.`); + const effort = body.effort == null ? 'low' : String(body.effort); + if (!EFFORTS.includes(effort)) throw fail(400, 'BAD_REQUEST', `effort must be one of ${EFFORTS.join(', ')}.`); + let schema = null; + if (body.schema != null) { + if (typeof body.schema !== 'object' || Array.isArray(body.schema) || JSON.stringify(body.schema).length > 20000) throw fail(400, 'BAD_REQUEST', 'schema must be a JSON schema object.'); + schema = body.schema; + } + const inputTokens = estimateInputTokens(body.system, body.input, schema); + if (inputTokens > MAX_INPUT_TOKENS) throw fail(413, 'AI_INPUT_TOO_LARGE', 'This is too much to send in one go.'); + return { helper, system: body.system, input: body.input, schema, maxTokens, effort, inputTokens }; +} + +// ─── Database ───────────────────────────────────────────────────────────────── + +/** Charged so far this month (millicents): finished calls, and holds for calls still running. */ +async function chargedThisMonth(db, installId, month, now = new Date()) { + const rows = await db.aiUsage.aggregate({ + where: { + installId, month, + OR: [{ status: { in: ['done', 'failed'] } }, { status: 'reserved', createdAt: { gt: new Date(now.getTime() - STALE_HOLD_MS) } }], + }, + _sum: { chargedMillicents: true }, + }); + return rows._sum.chargedMillicents || 0; +} + +async function setup(install) { + const [settings, key, licence] = await Promise.all([ + getSettings(), + aiApiKey(), + install.licenceId ? prisma.licence.findUnique({ where: { id: install.licenceId } }) : null, + ]); + return { settings, key, licence, price: pricing(settings, licence, !!key) }; +} + +/** Status for one install (§3b). */ +async function statusFor(install, now = new Date()) { + const { licence, price } = await setup(install); + return statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now }); +} + +/** + * Hold the worst case against the cap, or refuse. One transaction with a lock per install, so two + * calls at once can't both take the last of the allowance. + */ +async function reserve({ install, licence, price, helper, worst, now }) { + const month = monthOf(now); + return prisma.$transaction(async tx => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.id}`}))`; + const charged = await chargedThisMonth(tx, install.id, month, now); + if (charged + worst > licence.aiMonthlyCapCents * 1000) return null; + return tx.aiUsage.create({ + data: { installId: install.id, helper, model: price.model, month, status: 'reserved', chargedMillicents: worst, markupPercent: price.markup, usdZar: price.usdZar }, + }); + }); +} + +// ─── Claude ─────────────────────────────────────────────────────────────────── + +let client = null; +let clientKey = null; +function claude(key) { + if (!client || clientKey !== key) { + client = new Anthropic({ apiKey: key, maxRetries: 1, timeout: 60 * 1000 }); + clientKey = key; + } + return client; +} + +/** One request to Claude. Returns the raw message (with usage). */ +function callClaude(key, model, req) { + return claude(key).messages.create({ + model, + max_tokens: req.maxTokens, + // The helper's fixed instructions are cached, so repeat calls cost less. + system: [{ type: 'text', text: req.system, cache_control: { type: 'ephemeral' } }], + messages: [{ role: 'user', content: req.input }], + output_config: { effort: req.effort, ...(req.schema ? { format: { type: 'json_schema', schema: req.schema } } : {}) }, + }); +} + +const usageOf = message => ({ + inputTokens: message?.usage?.input_tokens || 0, + outputTokens: message?.usage?.output_tokens || 0, + cacheReadTokens: message?.usage?.cache_read_input_tokens || 0, + cacheWriteTokens: message?.usage?.cache_creation_input_tokens || 0, +}); + +/** Claude's errors as the Hub's (§3b): the install shows "AI is unavailable" for all of them. */ +function claudeError(e) { + if (e instanceof Anthropic.RateLimitError) return fail(503, 'AI_BUSY', 'The AI service is busy. Try again in a minute.'); + if (e instanceof Anthropic.AuthenticationError || e instanceof Anthropic.PermissionDeniedError) { + console.error('[ai] the Claude API key was refused:', e.message); + return fail(503, 'AI_UNAVAILABLE', 'AI is unavailable right now.'); + } + if (e instanceof Anthropic.BadRequestError) { + console.error('[ai] Claude refused the request:', e.message); + return fail(502, 'AI_FAILED', 'The AI service could not handle this request.'); + } + if (e instanceof Anthropic.APIError) { + console.error('[ai] Claude error', e.status, e.message); + return fail(503, 'AI_UNAVAILABLE', 'AI is unavailable right now.'); + } + console.error('[ai]', e); + return fail(503, 'AI_UNAVAILABLE', 'AI is unavailable right now.'); +} + +/** + * Run one helper call for an install: check, hold, call, meter. Resolves to the reply (§3b) or + * throws an error with `status` and `code`. Every reply and error carries the new status, so the + * install's buttons disable straight after the call that used up the allowance. + */ +async function complete(install, body, now = new Date()) { + const req = cleanRequest(body); + const { key, licence, price } = await setup(install); + const status = async () => statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now }); + + if (!price) throw Object.assign(fail(503, 'AI_NOT_CONFIGURED', 'AI is not available.'), { aiStatus: await status() }); + if (!licence || licence.aiMonthlyCapCents <= 0) throw Object.assign(fail(403, 'AI_OFF', 'AI is not part of this licence.'), { aiStatus: await status() }); + if (!licenceAllows(licence, now)) throw Object.assign(fail(403, 'LICENCE_INACTIVE', 'AI needs an active licence.'), { aiStatus: await status() }); + + const worst = worstCase(req.inputTokens, req.maxTokens, price); + const hold = await reserve({ install, licence, price, helper: req.helper, worst, now }); + if (!hold) throw Object.assign(fail(402, 'AI_CAP_REACHED', "This month's AI allowance is used up."), { aiStatus: await status() }); + + let message; + try { + message = await callClaude(key, price.model, req); + } catch (e) { + await prisma.aiUsage.update({ where: { id: hold.id }, data: { status: 'failed', chargedMillicents: 0 } }); + throw Object.assign(claudeError(e), { aiStatus: await status() }); + } + + // Tokens used are paid for whatever the outcome. + const usage = usageOf(message); + const cost = costOf(usage, price); + const text = (message.content || []).filter(b => b.type === 'text').map(b => b.text).join(''); + let output = text; + let problem = null; + if (message.stop_reason === 'refusal') problem = fail(422, 'AI_REFUSED', 'The AI declined to help with this.'); + else if (message.stop_reason === 'max_tokens') problem = fail(502, 'AI_INCOMPLETE', 'The answer was too long and got cut off.'); + else if (req.schema) { + try { output = JSON.parse(text); } catch { problem = fail(502, 'AI_FAILED', 'The AI gave an answer in the wrong shape.'); } + } + await prisma.aiUsage.update({ + where: { id: hold.id }, + data: { status: problem ? 'failed' : 'done', ...usage, realMillicents: cost.real, chargedMillicents: cost.charged }, + }); + if (problem) throw Object.assign(problem, { aiStatus: await status() }); + + return { + output, + usage: { inputTokens: usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens, outputTokens: usage.outputTokens }, + chargedCents: cost.charged / 1000, + status: await status(), + }; +} + +/** A tiny call to check the key and model from the Settings page (not metered to any install). */ +async function testCall(settings) { + const key = await aiApiKey(); + if (!key) throw fail(400, 'AI_NOT_CONFIGURED', 'Save the Claude API key first.'); + try { + const message = await callClaude(key, settings.ai_model, { maxTokens: 50, effort: 'low', system: 'Reply with the single word OK.', input: 'Are you there?' }); + return { model: message.model, reply: (message.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim().slice(0, 100) }; + } catch (e) { + throw fail(502, 'AI_FAILED', e instanceof Anthropic.APIError ? `Claude answered ${e.status}: ${e.message}` : e.message); + } +} + +// ─── Usage views (admin) ────────────────────────────────────────────────────── + +const toCents = m => Math.round(m / 10) / 100; + +/** Totals per month for one install (newest first): real cost, charged and profit in cents. */ +async function usageByMonth(installId, months = 6) { + const rows = await prisma.aiUsage.groupBy({ + by: ['month'], + where: { installId, status: { in: ['done', 'failed'] } }, + _sum: { realMillicents: true, chargedMillicents: true, inputTokens: true, outputTokens: true, cacheReadTokens: true, cacheWriteTokens: true }, + _count: { _all: true }, + orderBy: { month: 'desc' }, + take: months, + }); + return rows.map(r => ({ + month: r.month, + calls: r._count._all, + inputTokens: (r._sum.inputTokens || 0) + (r._sum.cacheReadTokens || 0) + (r._sum.cacheWriteTokens || 0), + outputTokens: r._sum.outputTokens || 0, + realCents: toCents(r._sum.realMillicents || 0), + chargedCents: toCents(r._sum.chargedMillicents || 0), + profitCents: toCents((r._sum.chargedMillicents || 0) - (r._sum.realMillicents || 0)), + })); +} + +/** This month's use per helper for one install. */ +async function usageByHelper(installId, month = monthOf()) { + const rows = await prisma.aiUsage.groupBy({ + by: ['helper'], + where: { installId, month, status: { in: ['done', 'failed'] } }, + _sum: { chargedMillicents: true }, + _count: { _all: true }, + }); + return rows.map(r => ({ helper: r.helper, calls: r._count._all, chargedCents: toCents(r._sum.chargedMillicents || 0) })).sort((a, b) => b.chargedCents - a.chargedCents); +} + +/** Every install's use in a month, for the Settings → AI overview. */ +async function usageForMonth(month = monthOf()) { + const rows = await prisma.aiUsage.groupBy({ + by: ['installId'], + where: { month, status: { in: ['done', 'failed'] } }, + _sum: { realMillicents: true, chargedMillicents: true }, + _count: { _all: true }, + }); + const installs = await prisma.install.findMany({ where: { id: { in: rows.map(r => r.installId) } }, select: { id: true, name: true, url: true, licence: { select: { aiMonthlyCapCents: true } } } }); + const byId = new Map(installs.map(i => [i.id, i])); + return rows.map(r => { + const i = byId.get(r.installId); + return { + installId: r.installId, name: i?.name || '?', url: i?.url || '', capCents: i?.licence?.aiMonthlyCapCents || 0, + calls: r._count._all, + realCents: toCents(r._sum.realMillicents || 0), + chargedCents: toCents(r._sum.chargedMillicents || 0), + profitCents: toCents((r._sum.chargedMillicents || 0) - (r._sum.realMillicents || 0)), + }; + }).sort((a, b) => b.chargedCents - a.chargedCents); +} + +module.exports = { + MAX_INPUT_TOKENS, MAX_OUTPUT_TOKENS, SMALLEST_CALL, + monthOf, renewsOn, pricing, costOf, estimateInputTokens, worstCase, licenceAllows, statusOf, cleanRequest, + statusFor, complete, testCall, usageByMonth, usageByHelper, usageForMonth, +}; diff --git a/backend/src/utils/settings.js b/backend/src/utils/settings.js index c964962..be24019 100644 --- a/backend/src/utils/settings.js +++ b/backend/src/utils/settings.js @@ -24,10 +24,20 @@ const DEFAULTS = { // Written by the sync, not the Settings page. release_synced_at: '', release_sync_error: '', + // AI for Cross Events 2.0 (utils/ai.js). Off until a key and the exchange rate are set. + ai_api_key: '', + ai_model: 'claude-haiku-5-5', + // US dollars per million tokens, for prompts under 100K tokens (the Hub refuses bigger ones). + ai_input_usd_per_mtok: '0.10', + ai_output_usd_per_mtok: '0.50', + // Rand per US dollar. + ai_usd_zar: '', + // Default markup on the real cost, in %; a licence can override it. + ai_markup_percent: '40', }; // Stored encrypted and never sent to the browser: only "is one saved" (_set). -const SECRETS = ['smtp_pass', 'release_repo_token']; +const SECRETS = ['smtp_pass', 'release_repo_token', 'ai_api_key']; async function rawSettings() { const rows = await prisma.setting.findMany(); @@ -105,4 +115,10 @@ async function releaseRepoToken() { return release_repo_token ? decrypt(release_repo_token) : ''; } -module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv, releaseRepoToken }; +/** The saved Claude API key, decrypted ('' when none). */ +async function aiApiKey() { + const { ai_api_key } = await rawSettings(); + return ai_api_key ? decrypt(ai_api_key) : ''; +} + +module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv, releaseRepoToken, aiApiKey }; diff --git a/backend/tests/ai.test.js b/backend/tests/ai.test.js new file mode 100644 index 0000000..c04a25e --- /dev/null +++ b/backend/tests/ai.test.js @@ -0,0 +1,182 @@ +// The AI proxy (utils/ai.js): pricing, the cap and the hold, with an in-memory database and a +// mocked Claude. + +const mockRows = []; +const mockState = { licence: null }; +const mockDb = { + licence: { findUnique: jest.fn(async () => mockState.licence) }, + aiUsage: { + aggregate: jest.fn(async ({ where }) => { + const cutoff = where.OR[1].createdAt.gt; + const sum = mockRows + .filter(r => r.installId === where.installId && r.month === where.month) + .filter(r => r.status !== 'reserved' || r.createdAt > cutoff) + .reduce((n, r) => n + r.chargedMillicents, 0); + return { _sum: { chargedMillicents: sum } }; + }), + create: jest.fn(async ({ data }) => { const row = { id: `u${mockRows.length + 1}`, createdAt: new Date(), ...data }; mockRows.push(row); return row; }), + update: jest.fn(async ({ where, data }) => Object.assign(mockRows.find(r => r.id === where.id), data)), + }, + $executeRaw: jest.fn(async () => 0), + $transaction: jest.fn(async fn => fn(mockDb)), +}; +jest.mock('../src/config/db', () => mockDb); + +const mockSettings = { + ai_model: 'claude-haiku-5-5', ai_input_usd_per_mtok: '0.10', ai_output_usd_per_mtok: '0.50', ai_usd_zar: '20', ai_markup_percent: '40', +}; +jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => mockSettings), aiApiKey: jest.fn(async () => 'sk-test') })); + +const mockCreate = jest.fn(); +jest.mock('@anthropic-ai/sdk', () => { + const actual = jest.requireActual('@anthropic-ai/sdk'); + function Anthropic() { return { messages: { create: mockCreate } }; } + for (const k of ['APIError', 'RateLimitError', 'AuthenticationError', 'PermissionDeniedError', 'BadRequestError']) Anthropic[k] = actual[k]; + return Anthropic; +}); + +const ai = require('../src/utils/ai'); + +const install = { id: 'inst_1', licenceId: 'lic_1' }; +const price = { model: 'claude-haiku-5-5', inUsd: 0.1, outUsd: 0.5, usdZar: 20, markup: 40 }; +const body = { protocolVersion: 1, helper: 'draft_message', system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 1000 }; +const reply = (usage, extra = {}) => ({ model: 'claude-haiku-5-5', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Hi all!' }], usage, ...extra }); + +beforeEach(() => { + mockRows.length = 0; + mockState.licence = { id: 'lic_1', status: 'active', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 5000, aiMarkupPercent: null }; + mockCreate.mockReset(); +}); + +describe('months', () => { + test('the month is South African time', () => { + expect(ai.monthOf(new Date('2026-10-31T21:59:00Z'))).toBe('2026-10'); + expect(ai.monthOf(new Date('2026-10-31T22:00:00Z'))).toBe('2026-11'); + }); + test('renews on the 1st of the next month, across the year end', () => { + expect(ai.renewsOn(new Date('2026-11-15T10:00:00Z'))).toBe('2026-12-01'); + expect(ai.renewsOn(new Date('2026-12-31T23:00:00Z'))).toBe('2027-02-01'); + }); +}); + +describe('pricing', () => { + test('off without a key or an exchange rate; the licence markup wins', () => { + expect(ai.pricing(mockSettings, mockState.licence, false)).toBeNull(); + expect(ai.pricing({ ...mockSettings, ai_usd_zar: '' }, mockState.licence, true)).toBeNull(); + expect(ai.pricing(mockSettings, mockState.licence, true)).toEqual(price); + expect(ai.pricing(mockSettings, { aiMarkupPercent: 0 }, true).markup).toBe(0); + }); + + test('cost in millicents: input, cache writes at 1.25×, reads at 0.1×, output; markup on top', () => { + // 1M input tokens at $0.10 × R20 = R2 = 200 000 millicents. + expect(ai.costOf({ inputTokens: 1e6 }, price)).toEqual({ real: 200000, charged: 280000 }); + expect(ai.costOf({ cacheWriteTokens: 1e6 }, price).real).toBe(250000); + expect(ai.costOf({ cacheReadTokens: 1e6 }, price).real).toBe(20000); + expect(ai.costOf({ outputTokens: 1e6 }, price).real).toBe(1000000); + // A typical call is a fraction of a cent, rounded up. + expect(ai.costOf({ inputTokens: 3000, outputTokens: 500 }, price)).toEqual({ real: 1100, charged: 1540 }); + }); + + test('the worst case is never less than any real outcome', () => { + const est = ai.estimateInputTokens(body.system, body.input); + const worst = ai.worstCase(est, 1000, price); + expect(worst).toBeGreaterThanOrEqual(ai.costOf({ inputTokens: est, outputTokens: 1000 }, price).charged); + expect(worst).toBeGreaterThanOrEqual(ai.costOf({ cacheReadTokens: est, outputTokens: 1000 }, price).charged); + }); +}); + +describe('status', () => { + const now = new Date('2026-11-10T10:00:00Z'); + test('hidden for cap R0, an inactive licence or no Hub set-up', () => { + expect(ai.statusOf({ licence: { ...mockState.licence, aiMonthlyCapCents: 0 }, price, chargedMillicents: 0, now }).enabled).toBe(false); + expect(ai.statusOf({ licence: { ...mockState.licence, status: 'suspended' }, price, chargedMillicents: 0, now }).enabled).toBe(false); + expect(ai.statusOf({ licence: mockState.licence, price: null, chargedMillicents: 0, now }).enabled).toBe(false); + }); + test('an expired licence still has AI during its grace days', () => { + const expired = { ...mockState.licence, expiresAt: new Date('2026-11-01T00:00:00Z') }; + expect(ai.licenceAllows(expired, now)).toBe(true); + expect(ai.licenceAllows(expired, new Date('2026-11-16T00:00:00Z'))).toBe(false); + }); + test('cap reached once there is no room for the smallest call', () => { + const s = ai.statusOf({ licence: mockState.licence, price, chargedMillicents: 1000 * 1000, now }); + expect(s).toMatchObject({ enabled: true, capReached: false, capCents: 5000, usedCents: 1000, usedPercent: 20, renewsOn: '2026-12-01' }); + expect(ai.statusOf({ licence: mockState.licence, price, chargedMillicents: 5000 * 1000 - 100, now }).capReached).toBe(true); + }); +}); + +describe('requests', () => { + test('checks the helper, sizes and effort', () => { + expect(() => ai.cleanRequest({ ...body, helper: 'Draft Event' })).toThrow(/helper/); + expect(() => ai.cleanRequest({ ...body, maxTokens: 9000 })).toThrow(/maxTokens/); + expect(() => ai.cleanRequest({ ...body, effort: 'max' })).toThrow(/effort/); + expect(() => ai.cleanRequest({ ...body, schema: [] })).toThrow(/schema/); + expect(() => ai.cleanRequest({ ...body, input: 'x'.repeat(240000) })).toThrow(expect.objectContaining({ code: 'AI_INPUT_TOO_LARGE' })); + expect(ai.cleanRequest(body)).toMatchObject({ helper: 'draft_message', effort: 'low', schema: null }); + }); +}); + +describe('complete', () => { + test('calls Claude with the key, caches the instructions, meters the real use', async () => { + mockCreate.mockResolvedValue(reply({ input_tokens: 40, output_tokens: 200, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 })); + const r = await ai.complete(install, body); + expect(r.output).toBe('Hi all!'); + expect(mockCreate.mock.calls[0][0]).toMatchObject({ + model: 'claude-haiku-5-5', max_tokens: 1000, + system: [{ type: 'text', text: body.system, cache_control: { type: 'ephemeral' } }], + output_config: { effort: 'low' }, + }); + expect(mockRows).toHaveLength(1); + expect(mockRows[0]).toMatchObject({ status: 'done', helper: 'draft_message', inputTokens: 40, outputTokens: 200, markupPercent: 40 }); + expect(mockRows[0].chargedMillicents).toBe(ai.costOf({ inputTokens: 40, outputTokens: 200 }, price).charged); + expect(r.status).toMatchObject({ enabled: true, capReached: false }); + }); + + test('a schema asks for JSON and the reply is parsed', async () => { + mockCreate.mockResolvedValue(reply({ input_tokens: 40, output_tokens: 20 }, { content: [{ type: 'text', text: '{"title":"Camp"}' }] })); + const schema = { type: 'object', properties: { title: { type: 'string' } }, required: ['title'], additionalProperties: false }; + const r = await ai.complete(install, { ...body, schema }); + expect(r.output).toEqual({ title: 'Camp' }); + expect(mockCreate.mock.calls[0][0].output_config.format).toEqual({ type: 'json_schema', schema }); + }); + + test('refused before calling Claude when the worst case would pass the cap', async () => { + mockState.licence.aiMonthlyCapCents = 1; + await expect(ai.complete(install, body)).rejects.toMatchObject({ status: 402, code: 'AI_CAP_REACHED', aiStatus: expect.objectContaining({ capReached: true }) }); + expect(mockCreate).not.toHaveBeenCalled(); + expect(mockRows).toHaveLength(0); + }); + + test('a running call holds its worst case, so a second one at once is refused', async () => { + const big = { ...body, maxTokens: 8000 }; + const worst = ai.worstCase(ai.estimateInputTokens(big.system, big.input, null), 8000, price); + // Room for one worst case, not two. + mockState.licence.aiMonthlyCapCents = Math.floor((worst * 1.5) / 1000); + expect(mockState.licence.aiMonthlyCapCents * 1000).toBeGreaterThan(worst); + let finish; + mockCreate.mockReturnValue(new Promise(r => { finish = r; })); + const first = ai.complete(install, big); + while (!mockCreate.mock.calls.length) await new Promise(r => setImmediate(r)); + await expect(ai.complete(install, big)).rejects.toMatchObject({ code: 'AI_CAP_REACHED' }); + finish(reply({ input_tokens: 40, output_tokens: 10 })); + await expect(first).resolves.toMatchObject({ output: 'Hi all!' }); + }); + + test('a failed call costs nothing; a refusal still pays for its tokens', async () => { + mockCreate.mockRejectedValueOnce(new Error('network down')); + await expect(ai.complete(install, body)).rejects.toMatchObject({ status: 503, code: 'AI_UNAVAILABLE' }); + expect(mockRows[0]).toMatchObject({ status: 'failed', chargedMillicents: 0 }); + + mockCreate.mockResolvedValueOnce(reply({ input_tokens: 40, output_tokens: 5 }, { stop_reason: 'refusal' })); + await expect(ai.complete(install, body)).rejects.toMatchObject({ status: 422, code: 'AI_REFUSED' }); + expect(mockRows[1].status).toBe('failed'); + expect(mockRows[1].chargedMillicents).toBeGreaterThan(0); + }); + + test('AI off on the licence, or a suspended licence', async () => { + mockState.licence.aiMonthlyCapCents = 0; + await expect(ai.complete(install, body)).rejects.toMatchObject({ status: 403, code: 'AI_OFF' }); + mockState.licence = { ...mockState.licence, aiMonthlyCapCents: 5000, status: 'suspended' }; + await expect(ai.complete(install, body)).rejects.toMatchObject({ status: 403, code: 'LICENCE_INACTIVE' }); + expect(mockCreate).not.toHaveBeenCalled(); + }); +}); diff --git a/docs/hub-protocol.md b/docs/hub-protocol.md index d4f143c..342c101 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -178,6 +178,65 @@ X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) history. Rate-limited with update requests. A Hub older than 1.4.0 answers `404 NOT_FOUND`. - **"Not now"** (no reminders until the next version) stays on the install; the Hub isn't told. +## 3b. AI (Cross Events 2.0, Hub 1.6.0) + +Installs never hold the Claude API key. Each AI helper call goes through the Hub, which adds the +key, checks the licence's monthly cap, calls Claude and meters the call. Both requests are signed +exactly like the heartbeat. The install keeps its prompts; the Hub stores **no prompt or response +text** — only the install, helper name, tokens, cost and time. + +### Status + +``` +POST /api/installs/ai/status +X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) +{ "protocolVersion": 1 } +→ 200 { "enabled": true, "capReached": false, "capCents": 5000, "usedCents": 812.4, + "usedPercent": 16, "renewsOn": "2026-12-01" } +``` + +- **`enabled: false`** — hide the AI buttons everywhere: the licence's cap is R0, the licence isn't + active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up. +- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it + renews on 1 December"). Reached means there isn't room left for even a small call. +- Amounts are cents (rand) as **charged** to the church, with fractions (a call costs a fraction of a + cent). The month is South African time; `renewsOn` is the 1st of the next month. + +### A helper call + +``` +POST /api/installs/ai/complete +X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) +{ + "protocolVersion": 1, + "helper": "draft_event", // lower-case name, for usage reports + "system": "…", // the helper's fixed instructions (cached by Claude) + "input": "…", // this request's text + "schema": { … }, // optional JSON schema: the reply is JSON in that shape + "maxTokens": 2000, // 1–8000 + "effort": "low" // optional: low (default) | medium | high +} +→ 200 { "output": "…" | { … }, // text, or the parsed JSON when a schema was given + "usage": { "inputTokens": 1840, "outputTokens": 420 }, + "chargedCents": 0.31, + "status": { …as above… } } +``` + +- **Errors** are `{ code, message, status }` — `status` is the new AI status, so buttons can disable + straight after the call that used up the allowance: + - `402 AI_CAP_REACHED` — this call could pass the cap (checked before calling Claude). + - `403 AI_OFF` (cap R0) · `403 LICENCE_INACTIVE` · `503 AI_NOT_CONFIGURED` (Hub not set up). + - `422 AI_REFUSED` — Claude declined. `502 AI_INCOMPLETE` — the answer hit `maxTokens`. + `502 AI_FAILED` — not usable (e.g. JSON in the wrong shape). These still cost what was used. + - `503 AI_BUSY` / `503 AI_UNAVAILABLE` — Claude unreachable or rate-limited; nothing is charged. + - `400 BAD_REQUEST`, `413 AI_INPUT_TOO_LARGE` (about 90 000 tokens), and the §3 errors. +- **Metering:** real cost = tokens × the model's price × the exchange rate set in the Hub; charged = + real × (1 + markup). The cap counts charged rand. Before calling Claude the Hub holds the worst + case (an over-estimate of the prompt, plus `maxTokens`) against the cap in one transaction per + install, so calls at the same moment can't pass it; afterwards the hold becomes the real amount. +- Rate-limited to 60 a minute per IP (against runaway loops; money is limited by the cap). +- A Hub older than 1.6.0 answers `404 NOT_FOUND`: the install treats that as "AI off". + ## 4. Licence token `hel1..` — `payload` is base64url JSON, `signature` is the base64url @@ -195,7 +254,7 @@ Ed25519 signature of the ASCII string `hel1.`. "graceDays": 14, "issuedAt": "2026-10-24T08:15:00.000Z", "validUntil": "2026-11-23T08:15:00.000Z", // issuedAt + 30 days - "limits": { "aiMonthlyCapCents": 0 } + "limits": { "aiMonthlyCapCents": 0 } // the AI cap (§3b); 0 = AI off } ``` @@ -221,8 +280,3 @@ grace starts). Blocking the Hub can't keep a suspended licence active for more t fields to a heartbeat or a token doesn't need a new version — both sides ignore fields they don't know. - The Hub accepts protocol `N` and `N-1`; anything else is `400 UNSUPPORTED_PROTOCOL`. - -## 6. Later (not in v1) - -- **AI proxy** (Cross Events 2.0): `POST /api/ai/complete`, signed like the heartbeat; the Hub holds - the Claude API key, meters each call in rand and enforces `limits.aiMonthlyCapCents`. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f1c29fb..8e457d0 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "1.5.0", + "version": "1.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "1.5.0", + "version": "1.6.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index 1fc6f0c..f2ccb86 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "1.5.0", + "version": "1.6.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/customers/[id]/page.tsx b/frontend/src/app/(hub)/customers/[id]/page.tsx index e1c0cc9..f34e50e 100644 --- a/frontend/src/app/(hub)/customers/[id]/page.tsx +++ b/frontend/src/app/(hub)/customers/[id]/page.tsx @@ -19,6 +19,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: expiresAt: dateInput(licence.expiresAt), graceDays: String(licence.graceDays), aiRand: String(licence.aiMonthlyCapCents / 100), + aiMarkup: licence.aiMarkupPercent == null ? "" : String(licence.aiMarkupPercent), notes: licence.notes || "", }); const [busy, setBusy] = useState(false); @@ -35,6 +36,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null, graceDays: form.graceDays, aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100), + aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup, notes: form.notes, }, }); @@ -65,7 +67,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: ? <>Used by {licence.install.url} · last heartbeat {ago(licence.install.lastHeartbeatAt)} : "Not used yet — enter this key in the church's Cross Events setup (or Site settings → Licence)."} -
+
setForm({ ...form, aiRand: e.target.value })} /> -

0 = off. Used from 2.0.

+

0 = off (no AI buttons). Counted in charged rand.

+
+
+ + setForm({ ...form, aiMarkup: e.target.value })} /> +

Blank uses the default (Settings → AI).

diff --git a/frontend/src/app/(hub)/installs/[id]/page.tsx b/frontend/src/app/(hub)/installs/[id]/page.tsx index 114fbd6..29ae619 100644 --- a/frontend/src/app/(hub)/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/installs/[id]/page.tsx @@ -5,9 +5,9 @@ import Link from "next/link"; import { useParams } from "next/navigation"; import { ArrowLeft } from "lucide-react"; import { api, errorText } from "@/lib/api"; -import { ago, bytes, fmtDate, rand } from "@/lib/format"; +import { ago, bytes, fmtDate, rand, randFine } from "@/lib/format"; import { usePaged } from "@/lib/paging"; -import type { Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types"; +import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types"; import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui"; type Detail = { @@ -20,6 +20,7 @@ type Detail = { summary: InstallSummary; events: InstallEvent[]; heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[]; + ai: { status: AiStatus; months: AiMonth[]; helpers: AiHelperUse[] }; }; const NO_EVENTS: InstallEvent[] = []; @@ -114,7 +115,8 @@ export default function InstallPage() { } /> - + + Change the licence → ) :

No licence (released).

} @@ -135,6 +137,38 @@ export default function InstallPage() { {msg &&
} +
+

AI

+ {!d.ai.status.enabled && d.ai.months.length === 0 ? ( +

Off for this site{d.licence?.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.

+ ) : ( + <> + + + {d.ai.helpers.length > 0 && `${h.helper.replace(/_/g, " ")}: ${h.calls} (${randFine(h.chargedCents)})`).join(" · ")} />} + {d.ai.months.length > 0 && ( +
+ + + + {d.ai.months.map(m => ( + + + + + + + + + ))} + +
MonthUsesTokens in / outReal costChargedProfit
{m.month}{m.calls}{m.inputTokens.toLocaleString("en-ZA")} / {m.outputTokens.toLocaleString("en-ZA")}{randFine(m.realCents)}{randFine(m.chargedCents)}{randFine(m.profitCents)}
+
+ )} + + )} +
+

History

{d.events.length === 0 ?

Nothing yet.

: ( diff --git a/frontend/src/app/(hub)/settings/page.tsx b/frontend/src/app/(hub)/settings/page.tsx index e88f80f..b184e39 100644 --- a/frontend/src/app/(hub)/settings/page.tsx +++ b/frontend/src/app/(hub)/settings/page.tsx @@ -3,8 +3,9 @@ import React, { useEffect, useMemo, useState } from "react"; import Link from "next/link"; import { api, errorText, setToken } from "@/lib/api"; -import { fmtDate } from "@/lib/format"; +import { fmtDate, rand, randFine } from "@/lib/format"; import { matches, usePaged } from "@/lib/paging"; +import type { AiInstallUse } from "@/lib/types"; import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui"; type Settings = Record; @@ -20,14 +21,113 @@ const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [ { key: "licence_expiry_warning_days", label: "Warn about licence expiry (days before)", hint: "Default 14.", type: "number" }, ]; -type Tab = "alerts" | "email" | "security" | "audit"; +type Tab = "alerts" | "email" | "ai" | "security" | "audit"; const TABS: { key: Tab; label: string }[] = [ { key: "alerts", label: "Alerts" }, { key: "email", label: "Email" }, + { key: "ai", label: "AI" }, { key: "security", label: "Login and security" }, { key: "audit", label: "Audit log" }, ]; +type AiUsage = { month: string; installs: AiInstallUse[]; totals: { calls: number; realCents: number; chargedCents: number; profitCents: number } }; + +const AI_FIELDS: { key: string; label: string; hint: string; type?: string }[] = [ + { key: "ai_model", label: "Model", hint: "claude-haiku-5-5 — the cheapest current model." }, + { key: "ai_input_usd_per_mtok", label: "Input price (US$ per million tokens)", hint: "Haiku 5.5: 0.10 (prompts under 100K tokens).", type: "number" }, + { key: "ai_output_usd_per_mtok", label: "Output price (US$ per million tokens)", hint: "Haiku 5.5: 0.50.", type: "number" }, + { key: "ai_usd_zar", label: "Exchange rate (rand per US$)", hint: "AI stays off until this is set. Each call is charged at the rate in force when it ran.", type: "number" }, + { key: "ai_markup_percent", label: "Default markup (%)", hint: "Added to the real cost; covers small overruns and is the profit. A licence can override it.", type: "number" }, +]; + +/** Settings → AI: the Claude key and prices, and what each install used this month. */ +function AiTab({ settings, onSaved, setMsg }: { settings: Settings; onSaved: (s: Settings) => void; setMsg: (m: Msg) => void }) { + const [form, setForm] = useState(() => Object.fromEntries(AI_FIELDS.map(f => [f.key, settings[f.key] ?? ""]))); + const [key, setKey] = useState({ value: "", clear: false }); + const [testing, setTesting] = useState(false); + const [month, setMonth] = useState(""); + const [usage, setUsage] = useState(null); + + useEffect(() => { + api(`/api/admin/ai-usage${month ? `?month=${month}` : ""}`).then(setUsage).catch(e => setMsg({ type: "err", text: errorText(e) })); + }, [month, setMsg]); + + const save = async (e: React.FormEvent) => { + e.preventDefault(); + try { + const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PUT", body: { settings: { ...form, ai_api_key: key.value, ai_api_key_clear: key.clear } } }); + onSaved(r.settings); + setKey({ value: "", clear: false }); + setMsg({ type: "ok", text: "AI settings saved." }); + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + }; + + const test = async () => { + setTesting(true); + setMsg(null); + try { + const r = await api<{ model: string; reply: string }>("/api/admin/settings/ai-test", { method: "POST" }); + setMsg({ type: "ok", text: `Claude answered (${r.model}): “${r.reply}”. Uses the saved key and model.` }); + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + setTesting(false); + }; + + return ( +
+
+

Sites call AI through the Hub, which adds this key, checks each licence's monthly cap and meters every call. Churches only ever see the charged amount in rand.

+ {!settings.ai_api_key_set &&

No Claude API key saved, so AI is off for every site.

} +
+ + setKey({ ...key, value: e.target.value })} /> + {settings.ai_api_key_set && ( + + )} +

Stored encrypted; never sent to the browser or to sites.

+
+ {AI_FIELDS.map(f => ( +
+ + setForm({ ...form, [f.key]: e.target.value })} /> +

{f.hint}

+
+ ))} +
+ + +
+
+ +
+
+

Use by site

+ setMonth(e.target.value)} /> + {usage && {usage.totals.calls} uses · real {randFine(usage.totals.realCents)} · charged {randFine(usage.totals.chargedCents)} · profit {randFine(usage.totals.profitCents)}} +
+ {!usage ? : usage.installs.length === 0 ?

No AI use in {usage.month}.

: ( +
+ + + + {usage.installs.map(i => ( + + + + + + + + + ))} + +
SiteCapUsesReal costChargedProfit
{i.name}{i.capCents ? rand(i.capCents) : "off"}{i.calls}{randFine(i.realCents)}{randFine(i.chargedCents)}{randFine(i.profitCents)}
+
+ )} +
+
+ ); +} + export default function SettingsPage() { const [tab, setTab] = useState("alerts"); const [settings, setSettings] = useState(null); @@ -164,6 +264,8 @@ export default function SettingsPage() { )} + {tab === "ai" && } + {tab === "security" && (
diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index 0d11f5c..b737cde 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -23,3 +23,6 @@ export function bytes(n: number | null | undefined) { } export const rand = (cents: number) => `R${(cents / 100).toFixed(2)}`; + +/** AI amounts are fractions of a cent per call: show R0.0042 rather than R0.00. */ +export const randFine = (cents: number) => (cents !== 0 && Math.abs(cents) < 100 ? `R${(cents / 100).toFixed(4)}` : rand(cents)); diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index 9e0db40..11927e5 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -23,6 +23,7 @@ export type Licence = { expiresAt: string | null; graceDays: number; aiMonthlyCapCents: number; + aiMarkupPercent: number | null; notes: string | null; createdAt: string; install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null; @@ -65,7 +66,13 @@ export type Stats = { export type InstallEvent = { id: string; type: string; level: Problem["level"]; message: string; createdAt: string; resolvedAt: string | null; install?: { id: string; name: string; url: string } }; -export type Release = { id: string; version: string; notes: string; urgent: boolean; releasedAt: string; installs: number }; +// AI (Cross Events 2.0). Amounts are in cents (rand), with fractions. +export type AiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string }; +export type AiMonth = { month: string; calls: number; inputTokens: number; outputTokens: number; realCents: number; chargedCents: number; profitCents: number }; +export type AiHelperUse = { helper: string; calls: number; chargedCents: number }; +export type AiInstallUse = { installId: string; name: string; url: string; capCents: number; calls: number; realCents: number; chargedCents: number; profitCents: number }; + +export type Release ={ id: string; version: string; notes: string; urgent: boolean; releasedAt: string; installs: number }; export type NoticeLevel = "info" | "maintenance" | "warning"; export type Notice = {