/** * 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, calls * Claude and meters the call. The site shows that use as tokens and a percentage (2.2.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 * daily limit per person, and logs it in `AiCall` (no prompt or answer text); * - emails the site admins once a month when 80% of the allowance is used. * The helpers themselves (prompts, schemas, what they send) are in ./helpers.ts. */ import { ApiError } from '../v2/errors'; import { prisma } from '../v2/legacy'; /* eslint-disable @typescript-eslint/no-explicit-any -- the JS Hub client and helpers aren't typed */ const hub = require('../hub/client') as { PROTOCOL_VERSION: number; signedPost(path: string, body: object, opts?: { timeoutMs?: number }): Promise; HubError: new (...args: any[]) => Error & { code: string; statusCode: number; data: any }; }; const { licenceStatus } = require('../hub/licence') as { licenceStatus(): Promise<{ connected: boolean; claims: { limits?: { aiMonthlyCapCents?: number } } | null; state: string; readOnly: boolean }>; }; const email = require('../utils/email') as { sendMail(m: { to: string; subject: string; html: string; text: string }): Promise; emailWrapper(body: string): string; isSmtpConfigured(): boolean; }; const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; 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), as the site keeps it. The Hub also sends the allowance in rand * (`capCents`, `usedCents`); the site drops those (2.2.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 }; export type AiSettings = { helpers: Record; dailyLimitPerPerson: number }; const SETTINGS_KEY = 'ai_settings'; const WARNED_KEY = 'ai_warned_month'; const STATUS_TTL_MS = 60 * 1000; const CALL_TIMEOUT_MS = 90 * 1000; const KEEP_CALLS_DAYS = 400; 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 ───────────────────────────────────────────────────── export const DEFAULT_SETTINGS: AiSettings = { helpers: Object.fromEntries(HELPERS.map(h => [h, true])) as Record, dailyLimitPerPerson: 0 }; export async function getAiSettings(): Promise { const row = await prisma.appSetting.findUnique({ where: { key: SETTINGS_KEY } }); let saved: Partial = {}; try { saved = row ? JSON.parse(row.value) : {}; } catch { /* keep the defaults */ } return { helpers: { ...DEFAULT_SETTINGS.helpers, ...Object.fromEntries(HELPERS.filter(h => typeof saved.helpers?.[h] === 'boolean').map(h => [h, saved.helpers![h]])) }, dailyLimitPerPerson: Number.isInteger(saved.dailyLimitPerPerson) && saved.dailyLimitPerPerson! >= 0 ? saved.dailyLimitPerPerson! : 0, }; } export async function saveAiSettings(next: { helpers?: Partial>; dailyLimitPerPerson?: number }, actor: { id: string; role: string }, ip?: string): Promise { const current = await getAiSettings(); const changed = Object.fromEntries(HELPERS.filter(h => typeof next.helpers?.[h] === 'boolean').map(h => [h, next.helpers![h]])); const value: AiSettings = { helpers: { ...current.helpers, ...changed }, dailyLimitPerPerson: next.dailyLimitPerPerson ?? current.dailyLimitPerPerson, }; await prisma.appSetting.upsert({ where: { key: SETTINGS_KEY }, update: { value: JSON.stringify(value) }, create: { key: SETTINGS_KEY, value: JSON.stringify(value) } }); await logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'ai_settings_changed', targetType: 'setting', targetId: SETTINGS_KEY, metadata: value, ip }); return value; } // ─── Status ─────────────────────────────────────────────────────────────────── 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 Record | null; if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: fromHub(v), available }; } export function clearAiStatusCache(): void { cached = null; } /** * The cap from the licence token (refreshed by every heartbeat): no Hub call is needed to know AI * is off, which is most sites. */ async function licenceCap(): Promise { const l = await licenceStatus(); if (!l.connected || !l.claims || l.readOnly) return 0; return Number(l.claims.limits?.aiMonthlyCapCents) || 0; } async function hubStatus(fresh = false): Promise<{ value: HubAiStatus; available: boolean }> { if (!fresh && cached && Date.now() - cached.at < STATUS_TTL_MS) return cached; try { remember(await hub.signedPost('/api/installs/ai/status', { protocolVersion: hub.PROTOCOL_VERSION })); } catch (e) { const err = e as { code?: string; statusCode?: number }; // A Hub before 1.6.0 has no AI; a released install has no licence: both mean off. if (err.statusCode === 404) cached = { at: Date.now(), value: OFF, available: true }; else { console.warn('[ai] could not ask the Hub for the AI status:', (e as Error).message); // Unreachable: keep showing the buttons (they say AI is unavailable when pressed). cached = { at: Date.now(), value: { ...(cached?.value || OFF), enabled: true }, available: false }; } } return cached!; } export async function aiStatus({ fresh = false } = {}): Promise { const settings = await getAiSettings(); if ((await licenceCap()) <= 0) return { ...OFF, available: true, helpers: settings.helpers }; const { value, available } = await hubStatus(fresh); return { ...value, available, helpers: settings.helpers }; } // ─── Running a helper ───────────────────────────────────────────────────────── export type HelperRequest = { /** The helper's fixed instructions (the Hub has Claude cache them). */ system: string; /** This request's text. Never names, contact details, medical or children's information. */ input: string; /** A JSON schema: the answer comes back as JSON in this shape. */ schema?: object; maxTokens: number; effort?: 'low' | 'medium' | 'high'; }; const failure = (code: 'FORBIDDEN' | 'RATE_LIMITED' | 'UNAVAILABLE', reason: string, message: string) => Object.assign(new ApiError(code, message), { reason }); function renewsText(renewsOn: string | null): string { if (!renewsOn) return 'next month'; return new Date(`${renewsOn}T12:00:00Z`).toLocaleDateString('en-ZA', { day: 'numeric', month: 'long', timeZone: 'Africa/Johannesburg' }); } /** The Hub's errors (§3b) as v2 errors, and what to log. */ function fromHubError(e: { code?: string; statusCode?: number; message: string; data?: any }): { error: ApiError; outcome: string } { remember(e.data?.status); switch (e.code) { case 'AI_CAP_REACHED': return { outcome: 'cap_reached', error: failure('FORBIDDEN', 'AI_CAP_REACHED', `This month's AI allowance is used up — it renews on ${renewsText(e.data?.status?.renewsOn ?? null)}.`) }; case 'AI_OFF': case 'LICENCE_INACTIVE': case 'AI_NOT_CONFIGURED': return { outcome: 'unavailable', error: failure('FORBIDDEN', 'AI_OFF', 'AI helpers are not available on this site.') }; case 'AI_REFUSED': return { outcome: 'refused', error: failure('UNAVAILABLE', 'AI_REFUSED', "The AI couldn't help with this one. Try wording it differently.") }; case 'AI_INCOMPLETE': return { outcome: 'incomplete', error: failure('UNAVAILABLE', 'AI_INCOMPLETE', 'The answer was too long and got cut off. Try asking for less.') }; case 'AI_INPUT_TOO_LARGE': return { outcome: 'failed', error: failure('UNAVAILABLE', 'AI_INPUT_TOO_LARGE', 'There is too much here to send in one go.') }; case 'AI_FAILED': return { outcome: 'failed', error: failure('UNAVAILABLE', 'AI_FAILED', "The AI's answer couldn't be used. Try again.") }; default: return { outcome: 'unavailable', error: failure('UNAVAILABLE', 'AI_UNAVAILABLE', 'AI is unavailable right now. Try again in a few minutes.') }; } } /** Starts of today in South African time, for the per-person daily limit. */ function startOfToday(now = new Date()): Date { const sast = new Date(now.getTime() + 2 * 3600 * 1000); return new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), sast.getUTCDate()) - 2 * 3600 * 1000); } let prunedOn = ''; /** Calls older than about 13 months go (once a day, on the first call). */ async function pruneOldCalls(now = new Date()): Promise { const today = now.toISOString().slice(0, 10); if (prunedOn === today) return; prunedOn = today; await prisma.aiCall.deleteMany({ where: { createdAt: { lt: new Date(now.getTime() - KEEP_CALLS_DAYS * 86400000) } } }).catch(() => {}); } /** At 80% of the allowance, the site's admins get one email a month. */ async function warnAt80(status: HubAiStatus): Promise { if (!status.enabled || status.usedPercent < 80 || !status.renewsOn) return; const row = await prisma.appSetting.findUnique({ where: { key: WARNED_KEY } }); if (row?.value === status.renewsOn) return; await prisma.appSetting.upsert({ where: { key: WARNED_KEY }, update: { value: status.renewsOn }, create: { key: WARNED_KEY, value: status.renewsOn } }); if (!email.isSmtpConfigured()) return; const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } }); const when = renewsText(status.renewsOn); 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)); } } /** * Run one helper call for a person. Resolves to the answer (text, or JSON when a schema was * given) and the new status; throws an ApiError with a `reason` (AI_OFF, AI_HELPER_OFF, * AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE…). */ export async function runHelper(helper: HelperName, userId: string, req: HelperRequest): Promise<{ output: unknown; status: AiStatus }> { const status = await aiStatus(); if (!status.enabled) throw failure('FORBIDDEN', 'AI_OFF', 'AI helpers are not available on this site.'); if (!status.helpers[helper]) throw failure('FORBIDDEN', 'AI_HELPER_OFF', 'This AI helper is switched off in Site settings → AI.'); if (status.capReached) throw failure('FORBIDDEN', 'AI_CAP_REACHED', `This month's AI allowance is used up — it renews on ${renewsText(status.renewsOn)}.`); const { dailyLimitPerPerson } = await getAiSettings(); if (dailyLimitPerPerson > 0) { const today = await prisma.aiCall.count({ where: { userId, createdAt: { gte: startOfToday() }, outcome: { in: ['ok', 'refused', 'incomplete'] } } }); if (today >= dailyLimitPerPerson) throw failure('RATE_LIMITED', 'AI_DAILY_LIMIT', `You've used the AI helpers ${dailyLimitPerPerson} times today, the most this site allows. Try again tomorrow.`); } 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 } }; } catch (e) { if (e instanceof ApiError) throw e; const mapped = fromHubError(e as Error & { code?: string; data?: any }); outcome = mapped.outcome; 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, inputTokens, outputTokens } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message)); await pruneOldCalls(); } } // ─── Usage (Site settings → AI) ─────────────────────────────────────────────── /** This month's use on this site: per person, per helper and per day (South African time). */ 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, 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.inputTokens += c.inputTokens; v.outputTokens += c.outputTokens; m.set(key, v); }; 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); 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(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)), }; } // For tests. export const _internal = { fromHubError, startOfToday, renewsText };