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
+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;