diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d8fd11..96f3966 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a ## Unreleased +### Contracts + +- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`, + `capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs. + ### Docs - The roadmap (`docs/ROADMAP-v3.md`) and the Hub protocol (`docs/hub-protocol.md`) move here from diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 7ff8f07..b1beca1 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -7,6 +7,20 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed + +- **AI use is shown in tokens, not rand** (for 2.3.0; needs Hub 2.0.1 for the token figures). Site + settings → AI shows the percentage used, the input and output tokens used this month and an + estimated allowance in tokens; the per-person, per-helper and per-day tables show tokens instead + of cost. The 80% email names tokens instead of rand. The rand amounts the Hub sends are dropped + on arrival, so they never reach a browser. With a Hub before 2.0.1 only the percentage shows. +- **API (v2):** `GET /api/v2/ai/status` (and the `status` in every AI reply and in `/ai/usage`) no + longer has `capCents` / `usedCents`; it has `usedInputTokens`, `usedOutputTokens`, + `capInputTokens`, `capOutputTokens` (null from an older Hub). `/ai/usage` rows have + `inputTokens` / `outputTokens` instead of `chargedCents`. +- `AiCall` keeps each call's tokens (migration `20261117120000_ai_tokens`). Calls from before it + show 0 tokens. + ## [2.1.1] - 2026-11-03 ### Fixed diff --git a/apps/events/backend/prisma/migrations/20261117120000_ai_tokens/migration.sql b/apps/events/backend/prisma/migrations/20261117120000_ai_tokens/migration.sql new file mode 100644 index 0000000..5b35726 --- /dev/null +++ b/apps/events/backend/prisma/migrations/20261117120000_ai_tokens/migration.sql @@ -0,0 +1,3 @@ +-- 2.3.0: tokens per AI call, which is what the site shows (the rand amount is the Hub's business). +ALTER TABLE "AiCall" ADD COLUMN "inputTokens" INTEGER NOT NULL DEFAULT 0; +ALTER TABLE "AiCall" ADD COLUMN "outputTokens" INTEGER NOT NULL DEFAULT 0; diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma index 5629659..de2d008 100644 --- a/apps/events/backend/prisma/schema.prisma +++ b/apps/events/backend/prisma/schema.prisma @@ -2341,8 +2341,12 @@ model AiCall { helper String // ok, refused, incomplete, failed, cap_reached, unavailable outcome String - // What the church was charged, in cents (fractions of a cent). + // What the church was charged, in cents (fractions of a cent). Kept for the record; the site + // shows tokens (2.3.0), and only the Hub shows rand. chargedCents Float @default(0) + // Tokens the call used (2.3.0): input counts cached prompt tokens. 0 when the call failed. + inputTokens Int @default(0) + outputTokens Int @default(0) createdAt DateTime @default(now()) user User? @relation(fields: [userId], references: [id], onDelete: SetNull) diff --git a/apps/events/backend/src/ai/index.ts b/apps/events/backend/src/ai/index.ts index ecfec21..7b1f5e7 100644 --- a/apps/events/backend/src/ai/index.ts +++ b/apps/events/backend/src/ai/index.ts @@ -1,7 +1,8 @@ /** * AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through - * the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap in rand, - * calls Claude and meters the call. This module: + * the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap, calls + * Claude and meters the call. The site shows that use as tokens and a percentage (2.3.0); the cap's + * rand amount stays on the Hub. This module: * - works out what the AI buttons do (`aiStatus`): hidden, working, or disabled until the * allowance renews — from the licence token first, then the Hub (cached for a minute); * - runs one helper call (`runHelper`), with this site's own switches per helper and an optional @@ -32,8 +33,16 @@ const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(en export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const; export type HelperName = (typeof HELPERS)[number]; -/** What the Hub says (§3b). Cents are charged rand, with fractions. */ -export type HubAiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string | null }; +/** + * What the Hub says (§3b), as the site keeps it. The Hub also sends the allowance in rand + * (`capCents`, `usedCents`); the site drops those (2.3.0): people see tokens and a percentage, + * and only the Hub shows rand. The token fields are null from a Hub before 2.0.1. + */ +export type HubAiStatus = { + enabled: boolean; capReached: boolean; usedPercent: number; renewsOn: string | null; + usedInputTokens: number | null; usedOutputTokens: number | null; + capInputTokens: number | null; capOutputTokens: number | null; +}; /** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */ export type AiStatus = HubAiStatus & { available: boolean; helpers: Record }; @@ -44,7 +53,28 @@ const STATUS_TTL_MS = 60 * 1000; const CALL_TIMEOUT_MS = 90 * 1000; const KEEP_CALLS_DAYS = 400; -const OFF: HubAiStatus = { enabled: false, capReached: false, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null }; +const OFF: HubAiStatus = { enabled: false, capReached: false, usedPercent: 0, renewsOn: null, usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null }; + +const tokens = (n: unknown): number | null => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.round(n) : null); + +/** The Hub's status without its rand amounts. */ +function fromHub(v: Record): HubAiStatus { + return { + enabled: v.enabled === true, + capReached: v.capReached === true, + usedPercent: typeof v.usedPercent === 'number' ? v.usedPercent : 0, + renewsOn: typeof v.renewsOn === 'string' ? v.renewsOn : null, + usedInputTokens: tokens(v.usedInputTokens), usedOutputTokens: tokens(v.usedOutputTokens), + capInputTokens: tokens(v.capInputTokens), capOutputTokens: tokens(v.capOutputTokens), + }; +} + +/** "1.2M", "450K", "800": tokens for people. */ +export function tokenText(n: number): string { + if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, '')}M`; + if (n >= 1e3) return `${Math.round(n / 1e3)}K`; + return String(n); +} // ─── This site's settings ───────────────────────────────────────────────────── @@ -78,8 +108,8 @@ let cached: { at: number; value: HubAiStatus; available: boolean } | null = null /** Keep what the Hub just said (every AI reply and error carries it). */ function remember(value: unknown, available = true): void { - const v = value as Partial | null; - if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: { ...OFF, ...v } as HubAiStatus, available }; + const v = value as Record | null; + if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: fromHub(v), available }; } export function clearAiStatusCache(): void { @@ -185,7 +215,10 @@ async function warnAt80(status: HubAiStatus): Promise { if (!email.isSmtpConfigured()) return; const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } }); const when = renewsText(status.renewsOn); - const text = `This site has used ${status.usedPercent}% of this month's AI allowance (R${(status.usedCents / 100).toFixed(2)} of R${(status.capCents / 100).toFixed(2)}). The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`; + const used = status.usedInputTokens != null && status.usedOutputTokens != null + ? ` (${tokenText(status.usedInputTokens)} input and ${tokenText(status.usedOutputTokens)} output tokens)` + : ''; + const text = `This site has used ${status.usedPercent}% of this month's AI allowance${used}. The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`; for (const a of admins) { await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`

${text}

`) }) .catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message)); @@ -210,9 +243,13 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR let outcome = 'ok'; let chargedCents = 0; + let inputTokens = 0; + let outputTokens = 0; try { const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS }); chargedCents = Number(reply.chargedCents) || 0; + inputTokens = tokens(reply.usage?.inputTokens) ?? 0; + outputTokens = tokens(reply.usage?.outputTokens) ?? 0; remember(reply.status); await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message)); return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } }; @@ -223,7 +260,7 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false); throw mapped.error; } finally { - await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message)); + await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents, inputTokens, outputTokens } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message)); await pruneOldCalls(); } } @@ -234,27 +271,30 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR export async function usageThisMonth(now = new Date()) { const sast = new Date(now.getTime() + 2 * 3600 * 1000); const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000); - const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, chargedCents: true, createdAt: true } }); - const add = (m: Map, key: string, cents: number) => { - const v = m.get(key) || { uses: 0, chargedCents: 0 }; + const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, inputTokens: true, outputTokens: true, createdAt: true } }); + type Use = { uses: number; inputTokens: number; outputTokens: number }; + const add = (m: Map, key: string, c: { inputTokens: number; outputTokens: number }) => { + const v = m.get(key) || { uses: 0, inputTokens: 0, outputTokens: 0 }; v.uses++; - v.chargedCents += cents; + v.inputTokens += c.inputTokens; + v.outputTokens += c.outputTokens; m.set(key, v); }; - const byPerson = new Map(); - const byHelper = new Map(); - const byDay = new Map(); + const byPerson = new Map(); + const byHelper = new Map(); + const byDay = new Map(); for (const c of calls) { if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue; - add(byPerson, c.userId || '', c.chargedCents); - add(byHelper, c.helper, c.chargedCents); - add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c.chargedCents); + add(byPerson, c.userId || '', c); + add(byHelper, c.helper, c); + add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c); } const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } }); const names = new Map(people.map(p => [p.id, p.name])); + const most = (a: Use, b: Use) => (b.inputTokens + b.outputTokens) - (a.inputTokens + a.outputTokens) || b.uses - a.uses; return { - people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort((a, b) => b.chargedCents - a.chargedCents), - helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort((a, b) => b.chargedCents - a.chargedCents), + people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort(most), + helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort(most), days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)), }; } diff --git a/apps/events/backend/src/v2/resources/ai.ts b/apps/events/backend/src/v2/resources/ai.ts index ddb8559..e0ca2c4 100644 --- a/apps/events/backend/src/v2/resources/ai.ts +++ b/apps/events/backend/src/v2/resources/ai.ts @@ -21,9 +21,11 @@ const status = z.object({ enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'), capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'), available: z.boolean().describe('false: the Hub couldn\'t be reached just now'), - capCents: z.number().describe('The monthly allowance, in cents'), - usedCents: z.number().describe('Used this month, in cents (fractions of a cent)'), - usedPercent: z.number(), + usedPercent: z.number().describe('How much of this month\'s allowance is used (0–100)'), + usedInputTokens: z.number().int().nullable().describe('Input tokens used this month by all the church\'s products (null from a Hub before 2.0.1)'), + usedOutputTokens: z.number().int().nullable().describe('Output tokens used this month'), + capInputTokens: z.number().int().nullable().describe('About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)'), + capOutputTokens: z.number().int().nullable().describe('About how many output tokens the allowance holds, if half of it went on output'), renewsOn: z.string().nullable().describe('YYYY-MM-DD'), helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'), }); @@ -33,7 +35,7 @@ const settings = z.object({ dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'), }); -const use = z.object({ uses: z.number().int(), chargedCents: z.number() }); +const use = z.object({ uses: z.number().int(), inputTokens: z.number().int(), outputTokens: z.number().int() }); export const getAiStatus = defineRoute({ method: 'get', diff --git a/apps/events/backend/tests/ai.test.ts b/apps/events/backend/tests/ai.test.ts index 8bbdabc..f6e8f40 100644 --- a/apps/events/backend/tests/ai.test.ts +++ b/apps/events/backend/tests/ai.test.ts @@ -28,9 +28,12 @@ const mockMail = jest.fn(async (_m: unknown) => undefined); jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true })); jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) })); -import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, _internal } from '../src/ai'; +import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, tokenText, _internal } from '../src/ai'; -const hubStatus = (over = {}) => ({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', ...over }); +const hubStatus = (over = {}) => ({ + enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', + usedInputTokens: 40000, usedOutputTokens: 9000, capInputTokens: 1785000, capOutputTokens: 357000, ...over, +}); const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 }; beforeEach(() => { @@ -55,7 +58,7 @@ describe('status', () => { test('asks the Hub and caches its answer for a minute', async () => { mockPost.mockResolvedValue(hubStatus()); - expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedCents: 100, helpers: { draft_event: true } }); + expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedInputTokens: 40000, capOutputTokens: 357000, helpers: { draft_event: true } }); await aiStatus(); expect(mockPost).toHaveBeenCalledTimes(1); expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 }); @@ -68,16 +71,32 @@ describe('status', () => { mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502)); expect(await aiStatus()).toMatchObject({ enabled: true, available: false }); }); + + test('the Hub\'s rand amounts never leave the site (2.3.0); a Hub before 2.0.1 sends no tokens', async () => { + mockPost.mockResolvedValueOnce(hubStatus()); + const s = await aiStatus() as unknown as Record; + expect(s).not.toHaveProperty('capCents'); + expect(s).not.toHaveProperty('usedCents'); + clearAiStatusCache(); + mockPost.mockResolvedValueOnce({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01' }); + expect(await aiStatus()).toMatchObject({ usedPercent: 2, usedInputTokens: null, capInputTokens: null }); + }); + + test('tokens for people', () => { + expect(['800', '45K', '1.2M', '2M', '12M']).toEqual([800, 45000, 1200000, 2000000, 12300000].map(tokenText)); + }); }); describe('running a helper', () => { test('sends the request to the Hub, logs the call, returns the answer', async () => { - mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'Hi all!', chargedCents: 0.31, status: hubStatus({ usedCents: 100.31 }) }); + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ + output: 'Hi all!', usage: { inputTokens: 1840, outputTokens: 420 }, chargedCents: 0.31, status: hubStatus({ usedInputTokens: 41840, usedOutputTokens: 9420 }), + }); const r = await runHelper('draft_message', 'u1', req); expect(r.output).toBe('Hi all!'); - expect(r.status.usedCents).toBe(100.31); + expect(r.status).toMatchObject({ usedInputTokens: 41840, usedOutputTokens: 9420 }); expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 }); - expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31 }]); + expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31, inputTokens: 1840, outputTokens: 420 }]); }); test('a helper switched off, or the cap reached, never reaches the Hub', async () => { @@ -102,7 +121,7 @@ describe('running a helper', () => { .mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) })); await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') }); expect((await aiStatus()).capReached).toBe(true); - expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0 }); + expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0, inputTokens: 0, outputTokens: 0 }); }); test('admins are emailed once a month at 80%', async () => { @@ -112,6 +131,9 @@ describe('running a helper', () => { await runHelper('draft_message', 'u1', req); expect(mockMail).toHaveBeenCalledTimes(1); expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]); + const text = (mockMail.mock.calls[0] as unknown as [{ text: string }])[0].text; + expect(text).toContain('40K input and 9K output tokens'); + expect(text).not.toMatch(/R\d/); }); }); diff --git a/apps/events/backend/tests/aiHelpers.test.ts b/apps/events/backend/tests/aiHelpers.test.ts index d1b8fd4..277e1e0 100644 --- a/apps/events/backend/tests/aiHelpers.test.ts +++ b/apps/events/backend/tests/aiHelpers.test.ts @@ -9,7 +9,7 @@ import { draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer, } from '../src/ai/helpers'; -const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} }; +const status = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: {} }; const now = new Date('2026-10-30T08:00:00Z'); beforeEach(() => mockRun.mockReset()); diff --git a/apps/events/backend/tests/v2.test.ts b/apps/events/backend/tests/v2.test.ts index c86c49d..cc46b7a 100644 --- a/apps/events/backend/tests/v2.test.ts +++ b/apps/events/backend/tests/v2.test.ts @@ -683,7 +683,7 @@ describe('money (v1 handlers behind v2 routes)', () => { }); describe('AI helpers (2.0)', () => { - const st = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } }; + const st = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } }; test('supervisors only', async () => { signedIn = { id: 's1', role: 'staff' }; diff --git a/apps/events/frontend/src/components/admin/AiTab.tsx b/apps/events/frontend/src/components/admin/AiTab.tsx index e018da0..d2a83df 100644 --- a/apps/events/frontend/src/components/admin/AiTab.tsx +++ b/apps/events/frontend/src/components/admin/AiTab.tsx @@ -4,7 +4,7 @@ import React, { useEffect, useState } from "react"; import { Sparkles } from "lucide-react"; import { useAuth } from "@/hooks/useAuth"; import { apiV2, type V2Result } from "@/lib/apiV2"; -import { loadAiStatus, renewsText } from "@/lib/ai"; +import { loadAiStatus, renewsText, tokenText } from "@/lib/ai"; import { errorMessage } from "@/lib/utils"; type Usage = V2Result<"/ai/usage", "get">["data"]; @@ -18,8 +18,8 @@ const HELPERS: { key: Helper; label: string; where: string }[] = [ { key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" }, ]; -// Fractions of a cent add up: show R0.0123 below a rand. -const money = (cents: number) => (cents > 0 && cents < 100 ? `R${(cents / 100).toFixed(4)}` : `R${(cents / 100).toFixed(2)}`); +/** "12K in · 3K out" for a row of use. */ +const inOut = (u: { inputTokens: number; outputTokens: number }) => `${tokenText(u.inputTokens)} in · ${tokenText(u.outputTokens)} out`; /** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */ export function AiTab({ active }: { active: boolean }) { @@ -53,7 +53,10 @@ export function AiTab({ active }: { active: boolean }) { if (!usage) return msg ?

{msg.text}

:

Loading…

; const s = usage.status; - const maxDay = Math.max(0.0001, ...usage.days.map(d => d.chargedCents)); + const dayTokens = (d: { inputTokens: number; outputTokens: number }) => d.inputTokens + d.outputTokens; + const maxDay = Math.max(1, ...usage.days.map(dayTokens)); + const hasTokens = s.usedInputTokens != null && s.usedOutputTokens != null; + const hasCap = s.capInputTokens != null && s.capOutputTokens != null && s.capInputTokens > 0; return (
@@ -72,14 +75,23 @@ export function AiTab({ active }: { active: boolean }) {
This month - {money(s.usedCents)} of {money(s.capCents)} · renews on {renewsText(s.renewsOn)} + {s.usedPercent}% used · renews on {renewsText(s.renewsOn)}
+ {hasTokens && ( +

+ {tokenText(s.usedInputTokens!)} input and {tokenText(s.usedOutputTokens!)} output tokens used + {hasCap && <> of about {tokenText(s.capInputTokens!)} input and {tokenText(s.capOutputTokens!)} output} +

+ )}
= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
{s.capReached &&

The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.

} {!s.available &&

The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.

} -

Admins get an email when 80% is used.

+

+ Admins get an email when 80% is used. + {hasCap && " The allowance in tokens is an estimate: it's what you'd get if half went on input (what's sent) and half on output (the answers). Repeated instructions are cached and cost less, so most sites get more input than this."} +

)} @@ -114,8 +126,8 @@ export function AiTab({ active }: { active: boolean }) {

By person this month

{usage.people.length === 0 ?

Nobody has used AI yet this month.

: ( - - {usage.people.map(p => )} + + {usage.people.map(p => )}
PersonUsesCost
{p.name}{p.uses}{money(p.chargedCents)}
PersonUsesTokens
{p.name}{p.uses}{inOut(p)}
)}
@@ -123,16 +135,16 @@ export function AiTab({ active }: { active: boolean }) {

By helper this month

{usage.helpers.length === 0 ?

—

: ( - - {usage.helpers.map(h => )} + + {usage.helpers.map(h => )}
HelperUsesCost
{HELPERS.find(x => x.key === h.helper)?.label || h.helper}{h.uses}{money(h.chargedCents)}
HelperUsesTokens
{HELPERS.find(x => x.key === h.helper)?.label || h.helper}{h.uses}{inOut(h)}
)}
{usage.days.length > 0 && (

Per day

-
- {usage.days.map(d =>
)} +
+ {usage.days.map(d =>
)}
)} diff --git a/apps/events/frontend/src/lib/ai.ts b/apps/events/frontend/src/lib/ai.ts index 04d977d..dd26728 100644 --- a/apps/events/frontend/src/lib/ai.ts +++ b/apps/events/frontend/src/lib/ai.ts @@ -3,7 +3,7 @@ import type { V2Result } from "@/lib/apiV2"; /** * AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly - * allowance in rand per licence. One status per page load is shared by every AI button + * allowance per licence, shown here as tokens and a percentage (2.3.0). One status per page load is shared by every AI button * (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the * call that used up the allowance. */ @@ -12,7 +12,8 @@ export type AiStatus = V2Result<"/ai/status", "get">["data"]; export type AiHelper = keyof AiStatus["helpers"]; const OFF: AiStatus = { - enabled: false, capReached: false, available: true, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null, + enabled: false, capReached: false, available: true, usedPercent: 0, renewsOn: null, + usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null, helpers: { draft_event: false, summarise_report: false, draft_message: false, summarise_feedback: false, improve_text: false }, }; @@ -46,6 +47,13 @@ export function currentAiStatus(): AiStatus | null { return current; } +/** "800", "45K", "1.2M": token counts for people (the allowance is shown in tokens, never rand). */ +export function tokenText(n: number): string { + if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, "")}M`; + if (n >= 1e3) return `${Math.round(n / 1e3)}K`; + return String(n); +} + /** "1 December" from "2026-12-01". */ export function renewsText(renewsOn: string | null): string { if (!renewsOn) return "next month"; diff --git a/apps/events/frontend/src/lib/api-v2/openapi.json b/apps/events/frontend/src/lib/api-v2/openapi.json index f6bf0bf..5ee91d2 100644 --- a/apps/events/frontend/src/lib/api-v2/openapi.json +++ b/apps/events/frontend/src/lib/api-v2/openapi.json @@ -67449,16 +67449,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -67501,9 +67546,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], @@ -67581,16 +67628,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -67633,9 +67725,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], @@ -67695,8 +67789,15 @@ "minimum": -9007199254740991, "maximum": 9007199254740991 }, - "chargedCents": { - "type": "number" + "inputTokens": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "outputTokens": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, "userId": { "type": [ @@ -67710,7 +67811,8 @@ }, "required": [ "uses", - "chargedCents", + "inputTokens", + "outputTokens", "userId", "name" ], @@ -67727,8 +67829,15 @@ "minimum": -9007199254740991, "maximum": 9007199254740991 }, - "chargedCents": { - "type": "number" + "inputTokens": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "outputTokens": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, "helper": { "type": "string" @@ -67736,7 +67845,8 @@ }, "required": [ "uses", - "chargedCents", + "inputTokens", + "outputTokens", "helper" ], "additionalProperties": false @@ -67752,8 +67862,15 @@ "minimum": -9007199254740991, "maximum": 9007199254740991 }, - "chargedCents": { - "type": "number" + "inputTokens": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "outputTokens": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, "day": { "type": "string" @@ -67761,7 +67878,8 @@ }, "required": [ "uses", - "chargedCents", + "inputTokens", + "outputTokens", "day" ], "additionalProperties": false @@ -68184,16 +68302,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -68236,9 +68399,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], @@ -68479,16 +68644,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -68531,9 +68741,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], @@ -68677,16 +68889,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -68729,9 +68986,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], @@ -68916,16 +69175,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -68968,9 +69272,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], @@ -69122,16 +69428,61 @@ "type": "boolean", "description": "false: the Hub couldn't be reached just now" }, - "capCents": { - "type": "number", - "description": "The monthly allowance, in cents" - }, - "usedCents": { - "type": "number", - "description": "Used this month, in cents (fractions of a cent)" - }, "usedPercent": { - "type": "number" + "type": "number", + "description": "How much of this month's allowance is used (0–100)" + }, + "usedInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Input tokens used this month by all the church's products (null from a Hub before 2.0.1)" + }, + "usedOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "Output tokens used this month" + }, + "capInputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)" + }, + "capOutputTokens": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "About how many output tokens the allowance holds, if half of it went on output" }, "renewsOn": { "description": "YYYY-MM-DD", @@ -69174,9 +69525,11 @@ "enabled", "capReached", "available", - "capCents", - "usedCents", "usedPercent", + "usedInputTokens", + "usedOutputTokens", + "capInputTokens", + "capOutputTokens", "renewsOn", "helpers" ], diff --git a/apps/events/frontend/src/lib/api-v2/schema.d.ts b/apps/events/frontend/src/lib/api-v2/schema.d.ts index 6dfa514..444e855 100644 --- a/apps/events/frontend/src/lib/api-v2/schema.d.ts +++ b/apps/events/frontend/src/lib/api-v2/schema.d.ts @@ -37676,11 +37676,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ @@ -37739,11 +37744,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ @@ -37768,18 +37778,21 @@ export interface operations { }; people: { uses: number; - chargedCents: number; + inputTokens: number; + outputTokens: number; userId: string | null; name: string; }[]; helpers: { uses: number; - chargedCents: number; + inputTokens: number; + outputTokens: number; helper: string; }[]; days: { uses: number; - chargedCents: number; + inputTokens: number; + outputTokens: number; day: string; }[]; }; @@ -37945,11 +37958,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ @@ -38041,11 +38059,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ @@ -38127,11 +38150,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ @@ -38220,11 +38248,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ @@ -38313,11 +38346,16 @@ export interface operations { capReached: boolean; /** @description false: the Hub couldn't be reached just now */ available: boolean; - /** @description The monthly allowance, in cents */ - capCents: number; - /** @description Used this month, in cents (fractions of a cent) */ - usedCents: number; + /** @description How much of this month's allowance is used (0–100) */ usedPercent: number; + /** @description Input tokens used this month by all the church's products (null from a Hub before 2.0.1) */ + usedInputTokens: number | null; + /** @description Output tokens used this month */ + usedOutputTokens: number | null; + /** @description About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less) */ + capInputTokens: number | null; + /** @description About how many output tokens the allowance holds, if half of it went on output */ + capOutputTokens: number | null; /** @description YYYY-MM-DD */ renewsOn: string | null; /** @description Each helper switched on or off in Site settings → AI */ diff --git a/docs/hub-protocol.md b/docs/hub-protocol.md index 0891724..5674075 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -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 diff --git a/packages/contracts/schemas/hub-ai-complete-response.json b/packages/contracts/schemas/hub-ai-complete-response.json index b421071..c2c2d0a 100644 --- a/packages/contracts/schemas/hub-ai-complete-response.json +++ b/packages/contracts/schemas/hub-ai-complete-response.json @@ -65,6 +65,26 @@ "type": "string", "format": "date", "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + }, + "usedInputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "usedOutputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "capInputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "capOutputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 } }, "required": [ diff --git a/packages/contracts/schemas/hub-ai-status.json b/packages/contracts/schemas/hub-ai-status.json index 4e05a65..ad94408 100644 --- a/packages/contracts/schemas/hub-ai-status.json +++ b/packages/contracts/schemas/hub-ai-status.json @@ -25,6 +25,26 @@ "type": "string", "format": "date", "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + }, + "usedInputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "usedOutputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "capInputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "capOutputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 } }, "required": [ diff --git a/packages/contracts/src/hub.ts b/packages/contracts/src/hub.ts index dac298e..75fc751 100644 --- a/packages/contracts/src/hub.ts +++ b/packages/contracts/src/hub.ts @@ -269,6 +269,12 @@ export const aiStatusSchema = z.object({ usedCents: z.number().nonnegative(), usedPercent: z.number().nonnegative(), renewsOn: dateSchema, + // Hub 2.0.1: tokens, which is what churches see (the cents are for the Hub and older installs). + // The allowance is approximate: half the cap priced as input, half as output. + usedInputTokens: count.optional(), + usedOutputTokens: count.optional(), + capInputTokens: count.optional(), + capOutputTokens: count.optional(), }); export type AiStatus = z.infer;