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:
@@ -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,
|
||||
};
|
||||
Reference in New Issue
Block a user