AI status: tokens used and an estimated allowance in tokens, for churches (2.0.1)
Churches see their AI use as input/output tokens; rand stays on the Hub. The status also carries usedInputTokens/usedOutputTokens and capInputTokens/capOutputTokens (half the cap priced as input, half as output). Cents unchanged for older installs. Protocol §3b updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+40
-11
@@ -95,15 +95,38 @@ function licenceAllows(licence, now = new Date()) {
|
||||
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.3.0; newer ones show only tokens and the percentage.
|
||||
*/
|
||||
function statusOf({ licence, price, chargedMillicents, now = new Date() }) {
|
||||
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 };
|
||||
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 };
|
||||
@@ -132,18 +155,24 @@ function cleanRequest(body) {
|
||||
// ─── Database ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Charged so far this month (millicents) over the church's installs (Hub 2.0: the cap is the
|
||||
* church's): finished calls, and holds for calls still running.
|
||||
* 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 chargedThisMonth(db, installIds, month, now = new Date()) {
|
||||
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 },
|
||||
_sum: { chargedMillicents: true, inputTokens: true, outputTokens: true, cacheReadTokens: true, cacheWriteTokens: true },
|
||||
});
|
||||
return rows._sum.chargedMillicents || 0;
|
||||
const sum = rows._sum || {};
|
||||
return {
|
||||
chargedMillicents: sum.chargedMillicents || 0,
|
||||
inputTokens: (sum.inputTokens || 0) + (sum.cacheReadTokens || 0) + (sum.cacheWriteTokens || 0),
|
||||
outputTokens: sum.outputTokens || 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,7 +195,7 @@ async function setup(install) {
|
||||
/** 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, chargedMillicents: await chargedThisMonth(prisma, installIds, monthOf(now), now), now });
|
||||
return statusOf({ licence, price, used: await usedThisMonth(prisma, installIds, monthOf(now), now), now });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -177,7 +206,7 @@ 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 chargedThisMonth(tx, installIds, month, now);
|
||||
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 },
|
||||
@@ -243,7 +272,7 @@ function claudeError(e) {
|
||||
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, chargedMillicents: await chargedThisMonth(prisma, installIds, monthOf(now), now), now });
|
||||
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() });
|
||||
@@ -359,6 +388,6 @@ async function usageForMonth(month = monthOf()) {
|
||||
|
||||
module.exports = {
|
||||
MAX_INPUT_TOKENS, MAX_OUTPUT_TOKENS, SMALLEST_CALL,
|
||||
monthOf, renewsOn, pricing, costOf, estimateInputTokens, worstCase, licenceAllows, statusOf, cleanRequest,
|
||||
monthOf, renewsOn, pricing, costOf, estimateInputTokens, worstCase, licenceAllows, allowanceTokens, statusOf, cleanRequest,
|
||||
statusFor, complete, testCall, usageByMonth, usageByHelper, usageForMonth,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user