WIP Hub 1.6.0: AI proxy for Cross Events 2.0

Signed /installs/ai/status and /installs/ai/complete (protocol 3b):
the Hub holds the Claude key, holds each call's worst case against the
licence's monthly cap in a locked transaction, calls Claude Haiku 5.5
and meters real cost and charged amount (markup) in rand. Settings ->
AI, licence markup override, AI use on the install page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 09:16:04 +02:00
co-authored by Claude Opus 5.5
parent 0f4d1c360a
commit 49f62aeb75
20 changed files with 1041 additions and 27 deletions
+84 -2
View File
@@ -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",
+2 -1
View File
@@ -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",
@@ -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;
+38 -1
View File
@@ -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())
+3 -2
View File
@@ -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'));
+49 -2
View File
@@ -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;
+31
View File
@@ -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;
+345
View File
@@ -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,
};
+18 -2
View File
@@ -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" (<key>_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 };
+182
View File
@@ -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();
});
});