394 lines
20 KiB
JavaScript
394 lines
20 KiB
JavaScript
/**
|
||
* 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');
|
||
const { findModel } = require('./aiModels');
|
||
|
||
// 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; reads are priced per model (utils/aiModels.js), 0.1×
|
||
// the input price for a model the Hub doesn't know.
|
||
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).
|
||
* Blank prices use the built-in ones for the model (utils/aiModels.js); cache reads always do,
|
||
* falling back to 0.1× the input price for a model the Hub doesn't know.
|
||
* `allowance.aiMarkupPercent` (the church's, Hub 2.0) overrides the Hub's default markup.
|
||
*/
|
||
function pricing(settings, licence, hasKey) {
|
||
const known = findModel(settings.ai_model);
|
||
const price = (value, builtIn) => (value != null && String(value).trim() !== '' ? parseFloat(value) : builtIn ?? NaN);
|
||
const inUsd = price(settings.ai_input_usd_per_mtok, known?.inputUsd);
|
||
const outUsd = price(settings.ai_output_usd_per_mtok, known?.outputUsd);
|
||
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;
|
||
const cacheReadUsd = known && known.inputUsd === inUsd ? known.cacheReadUsd : inUsd * CACHE_READ;
|
||
return { model: settings.ai_model, inUsd, outUsd, cacheReadUsd, 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.cacheReadUsd ?? 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;
|
||
}
|
||
|
||
/**
|
||
* The cap as tokens, for churches (Hub 2.0.1: churches see tokens, only the Hub sees rand). Half
|
||
* the cap is priced as input and half as output, at the current model price, exchange rate and
|
||
* markup, rounded down to a thousand. An approximation: cached prompts cost less, so a church
|
||
* usually gets more input than this.
|
||
*/
|
||
function allowanceTokens(capCents, price) {
|
||
if (!price || !(capCents > 0)) return { capInputTokens: 0, capOutputTokens: 0 };
|
||
const half = (capCents * 1000) / 2;
|
||
const tokens = usd => {
|
||
if (!(usd > 0)) return 0;
|
||
const perMillion = costOf({ inputTokens: 1e6 }, { ...price, inUsd: usd }).charged;
|
||
return Math.floor(((half / perMillion) * 1e6) / 1000) * 1000;
|
||
};
|
||
return { capInputTokens: tokens(price.inUsd), capOutputTokens: tokens(price.outUsd) };
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
* `used` is this month's use from usedThisMonth. The cents stay for installs older than Events
|
||
* 2.2.0; newer ones show only tokens and the percentage.
|
||
*/
|
||
function statusOf({ licence, price, used, now = new Date() }) {
|
||
const chargedMillicents = used?.chargedMillicents || 0;
|
||
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,
|
||
usedInputTokens: used?.inputTokens || 0, usedOutputTokens: used?.outputTokens || 0, ...allowanceTokens(capCents, price),
|
||
};
|
||
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 ─────────────────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Used so far this month over the church's installs (Hub 2.0: the cap is the church's): charged
|
||
* millicents of finished calls and of holds for calls still running, and the tokens of finished
|
||
* calls (input counts cache reads and writes, as the reply to a call does).
|
||
*/
|
||
async function usedThisMonth(db, installIds, month, now = new Date()) {
|
||
const rows = await db.aiUsage.aggregate({
|
||
where: {
|
||
installId: { in: installIds }, month,
|
||
OR: [{ status: { in: ['done', 'failed'] } }, { status: 'reserved', createdAt: { gt: new Date(now.getTime() - STALE_HOLD_MS) } }],
|
||
},
|
||
_sum: { chargedMillicents: true, inputTokens: true, outputTokens: true, cacheReadTokens: true, cacheWriteTokens: true },
|
||
});
|
||
const sum = rows._sum || {};
|
||
return {
|
||
chargedMillicents: sum.chargedMillicents || 0,
|
||
inputTokens: (sum.inputTokens || 0) + (sum.cacheReadTokens || 0) + (sum.cacheWriteTokens || 0),
|
||
outputTokens: sum.outputTokens || 0,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* What a call is checked against: the install's licence (active, not expired) with the church's
|
||
* cap and markup (Hub 2.0), and the church's installs whose use counts towards the cap.
|
||
*/
|
||
async function setup(install) {
|
||
const [settings, key, licence, customer, installs] = await Promise.all([
|
||
getSettings(),
|
||
aiApiKey(),
|
||
install.licenceId ? prisma.licence.findUnique({ where: { id: install.licenceId } }) : null,
|
||
install.customerId ? prisma.customer.findUnique({ where: { id: install.customerId }, select: { aiMonthlyCapCents: true, aiMarkupPercent: true } }) : null,
|
||
install.customerId ? prisma.install.findMany({ where: { customerId: install.customerId }, select: { id: true } }) : [],
|
||
]);
|
||
const allowance = licence ? { ...licence, aiMonthlyCapCents: customer?.aiMonthlyCapCents || 0, aiMarkupPercent: customer?.aiMarkupPercent ?? null } : null;
|
||
const installIds = [...new Set([install.id, ...installs.map(i => i.id)])];
|
||
return { settings, key, licence: allowance, installIds, price: pricing(settings, allowance, !!key) };
|
||
}
|
||
|
||
/** Status for one install (§3b): the church's allowance, used by all its installs. */
|
||
async function statusFor(install, now = new Date()) {
|
||
const { licence, installIds, price } = await setup(install);
|
||
return statusOf({ licence, price, used: await usedThisMonth(prisma, installIds, monthOf(now), now), now });
|
||
}
|
||
|
||
/**
|
||
* Hold the worst case against the cap, or refuse. One transaction with a lock per church (its
|
||
* installs share the cap), so two calls at once can't both take the last of the allowance.
|
||
*/
|
||
async function reserve({ install, installIds, 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.customerId || install.id}`}))`;
|
||
const charged = (await usedThisMonth(tx, installIds, month, now)).chargedMillicents;
|
||
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, installIds, price } = await setup(install);
|
||
const status = async () => statusOf({ licence, price, used: await usedThisMonth(prisma, installIds, 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 church\'s plan.'), { 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, installIds, 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 (with its product and the church's cap). */
|
||
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, product: true, customer: { select: { id: true, name: true, 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 || '', product: i?.product || 'events',
|
||
customer: i?.customer ? { id: i.customer.id, name: i.customer.name } : null, capCents: i?.customer?.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, allowanceTokens, statusOf, cleanRequest,
|
||
statusFor, complete, testCall, usageByMonth, usageByHelper, usageForMonth,
|
||
};
|