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