Merge branch 'feat/ai-tokens'

This commit is contained in:
2026-11-17 11:27:32 +02:00
5 changed files with 84 additions and 24 deletions
+14
View File
@@ -5,6 +5,20 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
- **AI use in tokens for churches** (planned as 2.0.1): the AI status (`/api/installs/ai/status`, and
the `status` in every AI reply) also carries `usedInputTokens` / `usedOutputTokens` (this month,
all the church's installs) and `capInputTokens` / `capOutputTokens`, an estimate of the allowance
(half the cap priced as input and half as output, at the current model price, exchange rate and
markup). Cross Events 2.3.0 shows only these and the percentage; rand stays on the Hub. The cents
fields are unchanged, so older installs keep working (protocol §3b).
### Changed
- **Default AI markup is 15%** (was 40%). Only applies where Settings → AI has no markup saved; a
saved value, and a customer's own markup, are kept.
## [2.0.0] - 2026-11-05
**Cross Code Hub**: every product a church has — Cross Events, Accounts, Church Website, Church App —
+40 -11
View File
@@ -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,
};
+1 -1
View File
@@ -39,7 +39,7 @@ const DEFAULTS = {
// Rand per US dollar.
ai_usd_zar: '',
// Default markup on the real cost, in %; a licence can override it.
ai_markup_percent: '40',
ai_markup_percent: '15',
// Billing (1.7.0, utils/billing/). Drafts are made billing_draft_days before an invoice's date
// and emailed to alert_email for approval; approved invoices go out on their date at
// billing_send_hour (South African time).
+17 -9
View File
@@ -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);
});
});
+12 -3
View File
@@ -205,15 +205,24 @@ POST /api/installs/ai/status
X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
{ "protocolVersion": 1 }
→ 200 { "enabled": true, "capReached": false, "capCents": 5000, "usedCents": 812.4,
"usedPercent": 16, "renewsOn": "2026-12-01" }
"usedPercent": 16, "renewsOn": "2026-12-01",
"usedInputTokens": 412000, "usedOutputTokens": 61000, // Hub 2.0.1+
"capInputTokens": 3571000, "capOutputTokens": 714000 } // Hub 2.0.1+
```
- **`enabled: false`** — hide the AI buttons everywhere: the licence's cap is R0, the licence isn't
active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up.
- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it
renews on 1 December"). Reached means there isn't room left for even a small call.
- Amounts are cents (rand) as **charged** to the church, with fractions (a call costs a fraction of a
cent). The month is South African time; `renewsOn` is the 1st of the next month.
- **Churches see tokens, never rand** (Hub 2.0.1, Cross Events 2.3.0). `usedInputTokens` /
`usedOutputTokens` are this month's tokens over all the church's installs (input counts cached
prompt tokens). `capInputTokens` / `capOutputTokens` are an **estimate** of the allowance: what half
the cap buys as input and half as output, at the current model price, exchange rate and markup,
rounded down to a thousand. `usedPercent` is exact (it's worked out in rand). Installs show the
tokens and the percentage, and don't pass the cents on.
- `capCents` / `usedCents` are cents (rand) as **charged** to the church, with fractions (a call costs
a fraction of a cent), for the Hub and for installs before Cross Events 2.3.0. The month is South
African time; `renewsOn` is the 1st of the next month.
### A helper call