The site calls AI through the Hub (protocol 3b, Hub 1.6.0): src/ai works out whether the AI buttons show (licence token first, then the Hub, cached a minute), runs a helper call with per-helper switches and a per-person daily limit, logs AiCall rows, and emails admins at 80%. v2 /ai/status, /ai/usage, /ai/settings; useAiStatus, AiButton, AiTab. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
264 lines
15 KiB
TypeScript
264 lines
15 KiB
TypeScript
/**
|
|
* 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:
|
|
* - 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<any>;
|
|
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<unknown>;
|
|
emailWrapper(body: string): string;
|
|
isSmtpConfigured(): boolean;
|
|
};
|
|
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<unknown> };
|
|
|
|
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 buttons need: the Hub's answer, whether it could be reached, and this site's switches. */
|
|
export type AiStatus = HubAiStatus & { available: boolean; helpers: Record<HelperName, boolean> };
|
|
|
|
export type AiSettings = { helpers: Record<HelperName, boolean>; 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, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null };
|
|
|
|
// ─── This site's settings ─────────────────────────────────────────────────────
|
|
|
|
export const DEFAULT_SETTINGS: AiSettings = { helpers: Object.fromEntries(HELPERS.map(h => [h, true])) as Record<HelperName, boolean>, dailyLimitPerPerson: 0 };
|
|
|
|
export async function getAiSettings(): Promise<AiSettings> {
|
|
const row = await prisma.appSetting.findUnique({ where: { key: SETTINGS_KEY } });
|
|
let saved: Partial<AiSettings> = {};
|
|
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<Record<HelperName, boolean | undefined>>; dailyLimitPerPerson?: number }, actor: { id: string; role: string }, ip?: string): Promise<AiSettings> {
|
|
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 Partial<HubAiStatus> | null;
|
|
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: { ...OFF, ...v } as HubAiStatus, 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<number> {
|
|
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<AiStatus> {
|
|
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<void> {
|
|
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<void> {
|
|
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 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.`;
|
|
for (const a of admins) {
|
|
await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`<p>${text}</p>`) })
|
|
.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;
|
|
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;
|
|
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 } }).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, chargedCents: true, createdAt: true } });
|
|
const add = (m: Map<string, { uses: number; chargedCents: number }>, key: string, cents: number) => {
|
|
const v = m.get(key) || { uses: 0, chargedCents: 0 };
|
|
v.uses++;
|
|
v.chargedCents += cents;
|
|
m.set(key, v);
|
|
};
|
|
const byPerson = new Map<string, { uses: number; chargedCents: number }>();
|
|
const byHelper = new Map<string, { uses: number; chargedCents: number }>();
|
|
const byDay = new Map<string, { uses: number; chargedCents: number }>();
|
|
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);
|
|
}
|
|
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]));
|
|
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),
|
|
days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)),
|
|
};
|
|
}
|
|
|
|
// For tests.
|
|
export const _internal = { fromHubError, startOfToday, renewsText };
|