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,
|
||||
};
|
||||
|
||||
@@ -12,11 +12,11 @@ const mockDb = {
|
||||
aiUsage: {
|
||||
aggregate: jest.fn(async ({ where }) => {
|
||||
const cutoff = where.OR[1].createdAt.gt;
|
||||
const sum = mockRows
|
||||
const rows = mockRows
|
||||
.filter(r => where.installId.in.includes(r.installId) && r.month === where.month)
|
||||
.filter(r => r.status !== 'reserved' || r.createdAt > cutoff)
|
||||
.reduce((n, r) => n + r.chargedMillicents, 0);
|
||||
return { _sum: { chargedMillicents: sum } };
|
||||
.filter(r => r.status !== 'reserved' || r.createdAt > cutoff);
|
||||
const sum = k => rows.reduce((n, r) => n + (r[k] || 0), 0);
|
||||
return { _sum: { chargedMillicents: sum('chargedMillicents'), inputTokens: sum('inputTokens'), outputTokens: sum('outputTokens'), cacheReadTokens: sum('cacheReadTokens'), cacheWriteTokens: sum('cacheWriteTokens') } };
|
||||
}),
|
||||
create: jest.fn(async ({ data }) => { const row = { id: `u${mockRows.length + 1}`, createdAt: new Date(), ...data }; mockRows.push(row); return row; }),
|
||||
update: jest.fn(async ({ where, data }) => Object.assign(mockRows.find(r => r.id === where.id), data)),
|
||||
@@ -114,9 +114,17 @@ describe('pricing', () => {
|
||||
describe('status', () => {
|
||||
const now = new Date('2026-11-10T10:00:00Z');
|
||||
test('hidden for cap R0, an inactive licence or no Hub set-up', () => {
|
||||
expect(ai.statusOf({ licence: { ...mockState.licence, aiMonthlyCapCents: 0 }, price, chargedMillicents: 0, now }).enabled).toBe(false);
|
||||
expect(ai.statusOf({ licence: { ...mockState.licence, status: 'suspended' }, price, chargedMillicents: 0, now }).enabled).toBe(false);
|
||||
expect(ai.statusOf({ licence: mockState.licence, price: null, chargedMillicents: 0, now }).enabled).toBe(false);
|
||||
expect(ai.statusOf({ licence: { ...mockState.licence, aiMonthlyCapCents: 0 }, price, used: null, now }).enabled).toBe(false);
|
||||
expect(ai.statusOf({ licence: { ...mockState.licence, status: 'suspended' }, price, used: null, now }).enabled).toBe(false);
|
||||
expect(ai.statusOf({ licence: mockState.licence, price: null, used: null, now }).enabled).toBe(false);
|
||||
});
|
||||
test('the allowance as tokens: half the cap priced as input, half as output (Hub 2.0.1)', () => {
|
||||
// R50 at Haiku's $0.10 / $0.50, R20 to the dollar, 40% markup: R25 buys 8.93M input or 1.79M output.
|
||||
expect(ai.allowanceTokens(5000, price)).toEqual({ capInputTokens: 8928000, capOutputTokens: 1785000 });
|
||||
expect(ai.allowanceTokens(0, price)).toEqual({ capInputTokens: 0, capOutputTokens: 0 });
|
||||
expect(ai.allowanceTokens(5000, null)).toEqual({ capInputTokens: 0, capOutputTokens: 0 });
|
||||
const s = ai.statusOf({ licence: mockState.licence, price, used: { chargedMillicents: 0, inputTokens: 1840, outputTokens: 420 }, now });
|
||||
expect(s).toMatchObject({ usedInputTokens: 1840, usedOutputTokens: 420, capInputTokens: 8928000, capOutputTokens: 1785000 });
|
||||
});
|
||||
test('an expired licence still has AI during its grace days', () => {
|
||||
const expired = { ...mockState.licence, expiresAt: new Date('2026-11-01T00:00:00Z') };
|
||||
@@ -124,9 +132,9 @@ describe('status', () => {
|
||||
expect(ai.licenceAllows(expired, new Date('2026-11-16T00:00:00Z'))).toBe(false);
|
||||
});
|
||||
test('cap reached once there is no room for the smallest call', () => {
|
||||
const s = ai.statusOf({ licence: mockState.licence, price, chargedMillicents: 1000 * 1000, now });
|
||||
const s = ai.statusOf({ licence: mockState.licence, price, used: { chargedMillicents: 1000 * 1000 }, now });
|
||||
expect(s).toMatchObject({ enabled: true, capReached: false, capCents: 5000, usedCents: 1000, usedPercent: 20, renewsOn: '2026-12-01' });
|
||||
expect(ai.statusOf({ licence: mockState.licence, price, chargedMillicents: 5000 * 1000 - 100, now }).capReached).toBe(true);
|
||||
expect(ai.statusOf({ licence: mockState.licence, price, used: { chargedMillicents: 5000 * 1000 - 100 }, now }).capReached).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user