WIP 2.0.0: the five AI helpers' API
src/ai/helpers.ts: instructions, schemas and inputs for draft event, summarise report (people-free reports only), draft message, summarise feedback (no names, access-logged) and improve text. Contact details are swapped for placeholders before sending and restored after; every helper gets today's date; weekday clashes and break-even over capacity are checked in code. v2 routes /ai/draft-event and friends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* The five AI helpers (roadmap §15): each one's instructions, the shape of its answer, and what it
|
||||
* sends. Run through `runHelper` (./index.ts), which goes via the Hub.
|
||||
*
|
||||
* What leaves the site (POPIA): only what a helper needs, and never names, contact details,
|
||||
* medical or children's information.
|
||||
* - Email addresses, phone numbers and ID numbers in any free text are swapped for placeholders
|
||||
* like [[CONTACT1]] before sending, and put back in the answer (`protect` / `restore`).
|
||||
* - Reports: only those without people in them (REPORTS_WITHOUT_PEOPLE).
|
||||
* - Feedback: ratings, choice counts and comments, never who answered.
|
||||
*
|
||||
* Lessons from the October 2026 trial, built in: every helper is told today's date, and the checks
|
||||
* that matter most (a weekday that doesn't match its date, an event that loses money when full)
|
||||
* are worked out here in code as well, not left to the model.
|
||||
*/
|
||||
|
||||
import { ApiError } from '../v2/errors';
|
||||
import { runHelper, type AiStatus } from './index';
|
||||
|
||||
// ─── Dates ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const SAST_MS = 2 * 3600 * 1000;
|
||||
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
|
||||
/** "Today is Friday 30 October 2026." in South African time. */
|
||||
export function todayLine(now = new Date()): string {
|
||||
const d = new Date(now.getTime() + SAST_MS);
|
||||
return `Today is ${WEEKDAYS[d.getUTCDay()]} ${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}.`;
|
||||
}
|
||||
|
||||
// ─── Keeping contact details on the site ──────────────────────────────────────
|
||||
|
||||
const CONTACT_RE = [
|
||||
/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, // email
|
||||
/(?:\+27|\b0)(?:[\s-]?\d){9}\b/g, // South African phone numbers
|
||||
/\b\d{13}\b/g, // South African ID numbers
|
||||
];
|
||||
|
||||
export type Protected = { text: string; found: Map<string, string> };
|
||||
|
||||
/** Swap contact details for [[CONTACTn]], so they never leave the site. */
|
||||
export function protect(text: string, found: Map<string, string> = new Map()): Protected {
|
||||
let out = text;
|
||||
for (const re of CONTACT_RE) {
|
||||
out = out.replace(re, match => {
|
||||
for (const [k, v] of found) if (v === match) return k;
|
||||
const key = `[[CONTACT${found.size + 1}]]`;
|
||||
found.set(key, match);
|
||||
return key;
|
||||
});
|
||||
}
|
||||
return { text: out, found };
|
||||
}
|
||||
|
||||
/** Put the contact details back into an answer (strings anywhere inside it). */
|
||||
export function restore<T>(value: T, found: Map<string, string>): T {
|
||||
if (!found.size) return value;
|
||||
const fix = (s: string) => s.replace(/\[\[CONTACT\d+\]\]/g, k => found.get(k) ?? k);
|
||||
const walk = (v: unknown): unknown => (typeof v === 'string' ? fix(v) : Array.isArray(v) ? v.map(walk) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)])) : v);
|
||||
return walk(value) as T;
|
||||
}
|
||||
|
||||
const KEEP_PLACEHOLDERS = 'Text like [[CONTACT1]] stands for a contact detail the site keeps private: copy it exactly where it belongs and never change it.';
|
||||
|
||||
// ─── Schemas ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const str = { type: 'string' };
|
||||
const num = { type: 'number' };
|
||||
const int = { type: 'integer' };
|
||||
const bool = { type: 'boolean' };
|
||||
const list = (items: object) => ({ type: 'array', items });
|
||||
const obj = (properties: Record<string, object>, descriptions: Record<string, string> = {}) => ({
|
||||
type: 'object', additionalProperties: false, required: Object.keys(properties),
|
||||
properties: Object.fromEntries(Object.entries(properties).map(([k, v]) => [k, descriptions[k] ? { ...v, description: descriptions[k] } : v])),
|
||||
});
|
||||
|
||||
// ─── 1. Draft an event ────────────────────────────────────────────────────────
|
||||
|
||||
export type EventDraftAnswer = {
|
||||
title: string; summary: string; description: string;
|
||||
startDate: string; startTime: string; endDate: string; endTime: string;
|
||||
location: string; capacity: number; needsParentalConsent: boolean; ageGroup: string;
|
||||
ticketOptions: { name: string; priceRand: number; description: string; earlyBirdPriceRand: number; earlyBirdUntil: string }[];
|
||||
sessions: { date: string; startTime: string; endTime: string; label: string }[];
|
||||
costs: { item: string; basis: string; amountRand: number }[];
|
||||
checks: string[];
|
||||
};
|
||||
|
||||
const EVENT_SCHEMA = obj({
|
||||
title: str, summary: str, description: str,
|
||||
startDate: str, startTime: str, endDate: str, endTime: str,
|
||||
location: str, capacity: int, needsParentalConsent: bool, ageGroup: str,
|
||||
ticketOptions: list(obj({ name: str, priceRand: num, description: str, earlyBirdPriceRand: num, earlyBirdUntil: str }, { earlyBirdPriceRand: '0 when there is none', earlyBirdUntil: 'YYYY-MM-DD, or empty' })),
|
||||
sessions: list(obj({ date: str, startTime: str, endTime: str, label: str })),
|
||||
costs: list(obj({ item: str, basis: str, amountRand: num }, { basis: 'How it is worked out, e.g. "R180 × 60 people × 2 nights"', amountRand: 'Total for this line at full capacity' })),
|
||||
checks: list(str),
|
||||
}, {
|
||||
summary: 'One sentence for the event card',
|
||||
description: 'The public event page: 2–4 short paragraphs, plain text',
|
||||
startDate: 'YYYY-MM-DD', endDate: 'YYYY-MM-DD', startTime: 'HH:MM, 24-hour, or empty', endTime: 'HH:MM, 24-hour, or empty',
|
||||
capacity: 'Places in total; 0 when not given',
|
||||
sessions: 'Only for an event that meets on several separate dates people attend, like a weekly course: one row per date. Empty for a single event, even one over a weekend.',
|
||||
checks: 'Things to look at before publishing: missing details, contradictions, money that does not add up. Empty if none.',
|
||||
});
|
||||
|
||||
const EVENT_SYSTEM = (now: Date) => [
|
||||
'You help a church events team set up an event in Cross Events, an event registration system. From the organiser\'s notes, fill in the event form.',
|
||||
todayLine(now),
|
||||
'- Title: short and clear. Description: for the public event page, warm and clear, 2–4 short paragraphs, plain text (no markdown): who it is for, what happens, what is included, what to bring if known.',
|
||||
'- South African rand; 24-hour times. Dates as YYYY-MM-DD: the next time that date comes round after today, unless the notes give a year.',
|
||||
'- If a weekday in the notes does not match its date, keep the date and say so in "checks".',
|
||||
'- Ticket options: the prices the notes give, with any early-bird price and its last day. One option when only one price is given.',
|
||||
'- Leave anything the notes do not give empty (or 0) rather than guess, including times.',
|
||||
'- Costs: one line per cost the notes give, worked out at full capacity, showing how. Never invent costs.',
|
||||
'- Never invent names, phone numbers, email addresses or links.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
|
||||
/** Weekdays written next to dates in the notes ("Fri 14 March") that don't match the year used. */
|
||||
export function weekdayClashes(notes: string, year: number): string[] {
|
||||
const out: string[] = [];
|
||||
const re = /\b(mon|tue|wed|thu|fri|sat|sun)[a-z]*\.?,?\s+(\d{1,2})(?:st|nd|rd|th)?\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*/gi;
|
||||
for (const m of notes.matchAll(re)) {
|
||||
const day = Number(m[2]);
|
||||
const month = MONTHS.findIndex(x => x.toLowerCase().startsWith(m[3].toLowerCase()));
|
||||
const actual = new Date(Date.UTC(year, month, day)).getUTCDay();
|
||||
const said = WEEKDAYS.findIndex(w => w.toLowerCase().startsWith(m[1].toLowerCase()));
|
||||
if (actual !== said) out.push(`The notes say ${WEEKDAYS[said]} ${day} ${MONTHS[month]}, but ${day} ${MONTHS[month]} ${year} is a ${WEEKDAYS[actual]}. Check the dates.`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** R34 800 — plain spaces between thousands, as the AI writes them (en-ZA uses a no-break space). */
|
||||
const rands = (n: number) => `R${Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}`;
|
||||
|
||||
/** Money and date checks worked out in code, whatever the model said. */
|
||||
export function eventWarnings(notes: string, a: EventDraftAnswer): string[] {
|
||||
const out: string[] = [];
|
||||
const year = Number(a.startDate.slice(0, 4));
|
||||
if (year > 2000) out.push(...weekdayClashes(notes, year));
|
||||
if (a.startDate && a.endDate && `${a.endDate}T${a.endTime || '23:59'}` < `${a.startDate}T${a.startTime || '00:00'}`) out.push('The end is before the start.');
|
||||
const costs = a.costs.reduce((s, c) => s + (Number(c.amountRand) || 0), 0);
|
||||
const main = a.ticketOptions[0];
|
||||
if (costs > 0 && main?.priceRand > 0) {
|
||||
const breakEven = Math.ceil(costs / main.priceRand);
|
||||
if (a.capacity > 0 && breakEven > a.capacity) {
|
||||
const full = a.capacity * main.priceRand;
|
||||
const early = main.earlyBirdPriceRand > 0 ? a.capacity * main.earlyBirdPriceRand : null;
|
||||
out.push(`The costs in the notes come to ${rands(costs)}, which needs ${breakEven} places at ${rands(main.priceRand)} — more than the ${a.capacity} available. Even full, the event takes ${rands(full)}${early ? ` (${rands(early)} if everyone books early)` : ''}, ${rands(costs - full)} short.`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function draftEvent(userId: string, notes: string, now = new Date()): Promise<{ draft: EventDraftAnswer; warnings: string[]; totalCostRand: number; breakEvenPlaces: number | null; status: AiStatus }> {
|
||||
const p = protect(notes);
|
||||
const { output, status } = await runHelper('draft_event', userId, { system: EVENT_SYSTEM(now), input: p.text, schema: EVENT_SCHEMA, maxTokens: 4000, effort: 'low' });
|
||||
const draft = restore(output as EventDraftAnswer, p.found);
|
||||
const totalCostRand = draft.costs.reduce((s, c) => s + (Number(c.amountRand) || 0), 0);
|
||||
const price = draft.ticketOptions[0]?.priceRand || 0;
|
||||
return { draft, warnings: eventWarnings(notes, draft), totalCostRand, breakEvenPlaces: totalCostRand > 0 && price > 0 ? Math.ceil(totalCostRand / price) : null, status };
|
||||
}
|
||||
|
||||
// ─── 2. Summarise a report ────────────────────────────────────────────────────
|
||||
|
||||
/** Reports with no people in them: only these can be summarised (keys from ReportCatalog). */
|
||||
export const REPORTS_WITHOUT_PEOPLE = ['seriesComparison', 'regTypes', 'usage', 'revenue', 'regStatus', 'donations', 'funnel', 'discounts', 'cashup', 'financeReport', 'profitReport'] as const;
|
||||
const MAX_ROWS = 400;
|
||||
|
||||
export type ReportInput = {
|
||||
reportKey: string;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
stats?: { label: string; value: string | number }[];
|
||||
columns: string[];
|
||||
rows: (string | number)[][];
|
||||
};
|
||||
|
||||
export type ReportSummary = { headline: string; insights: { title: string; detail: string }[]; watchOut: string[] };
|
||||
|
||||
const REPORT_SCHEMA = obj({ headline: str, insights: list(obj({ title: str, detail: str })), watchOut: list(str) }, { watchOut: 'Things that need someone to act; empty if none' });
|
||||
|
||||
const REPORT_SYSTEM = (now: Date) => [
|
||||
'You summarise a report for the leaders of a church that uses Cross Events, an event registration system. They are busy volunteers and staff, not analysts.',
|
||||
todayLine(now),
|
||||
'- A one-sentence headline, then 3–5 insights: trends, changes against earlier periods, outliers, and anything that needs action.',
|
||||
'- Use the report\'s numbers; work out percentages and differences where they help, and get them right. Never invent figures or causes; when you suggest a cause, say it is only a possibility.',
|
||||
'- Mind the dates against today: an event that has already happened can\'t still be promoted or paid for before it starts.',
|
||||
'- Plain, friendly South African English. Amounts in rand like R18 900.',
|
||||
].join('\n');
|
||||
|
||||
/** The report as compact text: stats, then the table as pipe-separated rows. */
|
||||
export function reportText(r: ReportInput): string {
|
||||
const lines = [`Report: ${r.title}`];
|
||||
if (r.subtitle) lines.push(r.subtitle);
|
||||
for (const s of r.stats || []) lines.push(`${s.label}: ${s.value}`);
|
||||
lines.push(`Columns: ${r.columns.join(' | ')}`);
|
||||
for (const row of r.rows.slice(0, MAX_ROWS)) lines.push(row.map(c => String(c ?? '').replace(/\s+/g, ' ')).join(' | '));
|
||||
if (r.rows.length > MAX_ROWS) lines.push(`(${r.rows.length - MAX_ROWS} more rows not shown)`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export async function summariseReport(userId: string, report: ReportInput, now = new Date()): Promise<{ summary: ReportSummary; status: AiStatus }> {
|
||||
if (!(REPORTS_WITHOUT_PEOPLE as readonly string[]).includes(report.reportKey)) {
|
||||
throw Object.assign(new ApiError('FORBIDDEN', 'This report lists people, so it can\'t be sent to the AI. Summaries work on totals-only reports.'), { reason: 'AI_REPORT_HAS_PEOPLE' });
|
||||
}
|
||||
const p = protect(reportText(report));
|
||||
const { output, status } = await runHelper('summarise_report', userId, { system: REPORT_SYSTEM(now), input: p.text, schema: REPORT_SCHEMA, maxTokens: 2000, effort: 'low' });
|
||||
return { summary: restore(output as ReportSummary, p.found), status };
|
||||
}
|
||||
|
||||
// ─── 3. Draft a message ───────────────────────────────────────────────────────
|
||||
|
||||
export type MessageAnswer = { subject: string; body: string };
|
||||
|
||||
const MESSAGE_SCHEMA = obj({ subject: str, body: str }, { subject: 'Empty for WhatsApp' });
|
||||
|
||||
const MESSAGE_SYSTEM = (channel: 'email' | 'whatsapp', now: Date) => [
|
||||
'You write messages from a church events team to people registered for an event, from the organiser\'s short note.',
|
||||
todayLine(now),
|
||||
channel === 'whatsapp'
|
||||
? '- WhatsApp: plain text, at most 3 short sentences, at most one emoji. "subject" is empty.'
|
||||
: '- Email: a clear subject, then the body in short plain-text paragraphs, the most important thing first. Start with "Hi {{name}}," and end with "The events team".',
|
||||
'- Use {{name}} for the person\'s first name. {{event.title}}, {{event.start}} and {{event.link}} are filled in for each event, if useful.',
|
||||
'- Use only the facts in the note and the event details; never invent times, places, prices, links or contact details, or add advice the note doesn\'t give.',
|
||||
'- Spell carefully: this goes to everyone registered.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
|
||||
export type EventFacts = { title: string; start: string; location: string | null };
|
||||
|
||||
export async function draftMessage(userId: string, input: { channel: 'email' | 'whatsapp'; note: string; event?: EventFacts | null }, now = new Date()): Promise<{ message: MessageAnswer; status: AiStatus }> {
|
||||
const p = protect(input.note);
|
||||
const facts = input.event ? `\n\nEvent: ${input.event.title}, ${input.event.start}${input.event.location ? `, at ${input.event.location}` : ''}` : '';
|
||||
const { output, status } = await runHelper('draft_message', userId, {
|
||||
system: MESSAGE_SYSTEM(input.channel, now), input: `Note: ${p.text}${facts}`, schema: MESSAGE_SCHEMA, maxTokens: input.channel === 'whatsapp' ? 600 : 1500, effort: 'low',
|
||||
});
|
||||
const message = restore(output as MessageAnswer, p.found);
|
||||
return { message: input.channel === 'whatsapp' ? { subject: '', body: message.body } : message, status };
|
||||
}
|
||||
|
||||
// ─── 4. Summarise feedback ────────────────────────────────────────────────────
|
||||
|
||||
export type FeedbackQuestion = { label: string; type: string; answered: number; average?: number | null; counts?: { label: string; value: number }[]; texts?: string[] };
|
||||
export type FeedbackSummary = { overall: string; liked: { theme: string; mentions: number }[]; improve: { theme: string; mentions: number }[]; quotes: string[]; nextTime: string[] };
|
||||
|
||||
const FEEDBACK_SCHEMA = obj({
|
||||
overall: str, liked: list(obj({ theme: str, mentions: int })), improve: list(obj({ theme: str, mentions: int })), quotes: list(str), nextTime: list(str),
|
||||
}, { liked: 'Most-mentioned first', improve: 'Most-mentioned first', quotes: 'Up to 3 short comments, copied exactly' });
|
||||
|
||||
const FEEDBACK_SYSTEM = [
|
||||
'You summarise the feedback people gave after a church event, for the team that ran it.',
|
||||
'- "overall": two sentences on how it went, using the ratings.',
|
||||
'- "liked" and "improve": the main themes, most-mentioned first, each with how many comments raised it. Count carefully: a comment counts once per theme.',
|
||||
'- "quotes": up to 3 short comments that capture the feedback well, copied exactly.',
|
||||
'- "nextTime": 2–4 concrete suggestions for next time, based only on the feedback.',
|
||||
'- The comments are anonymous; never guess who wrote one.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
const MAX_COMMENTS = 400;
|
||||
const MAX_COMMENT = 600;
|
||||
|
||||
/** The feedback as text: each question with its average or counts, and the comments numbered. */
|
||||
export function feedbackText(event: { title: string }, responses: number, invited: number, questions: FeedbackQuestion[]): string {
|
||||
const lines = [`Event: ${event.title}`, `Responses: ${responses}${invited ? ` of ${invited} asked` : ''}`];
|
||||
let n = 0;
|
||||
for (const q of questions) {
|
||||
if (q.average != null) lines.push(`${q.label} — average ${q.average} (${q.answered} answers)`);
|
||||
else if (q.counts) lines.push(`${q.label} — ${q.counts.map(c => `${c.label}: ${c.value}`).join(', ')}`);
|
||||
else if (q.texts?.length) {
|
||||
lines.push(`${q.label} — comments:`);
|
||||
for (const t of q.texts) {
|
||||
if (n++ >= MAX_COMMENTS) break;
|
||||
lines.push(`${n}. ${t.replace(/\s+/g, ' ').slice(0, MAX_COMMENT)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export async function summariseFeedback(userId: string, input: { event: { title: string }; responses: number; invited: number; questions: FeedbackQuestion[] }): Promise<{ summary: FeedbackSummary; status: AiStatus }> {
|
||||
const p = protect(feedbackText(input.event, input.responses, input.invited, input.questions));
|
||||
const { output, status } = await runHelper('summarise_feedback', userId, { system: FEEDBACK_SYSTEM, input: p.text, schema: FEEDBACK_SCHEMA, maxTokens: 2000, effort: 'low' });
|
||||
return { summary: restore(output as FeedbackSummary, p.found), status };
|
||||
}
|
||||
|
||||
// ─── 5. Improve this text ─────────────────────────────────────────────────────
|
||||
|
||||
export const IMPROVE_MODES = { improve: 'Make it clear and friendly', shorter: 'Make it shorter', fix: 'Only fix spelling and grammar' } as const;
|
||||
export type ImproveMode = keyof typeof IMPROVE_MODES;
|
||||
export type ImproveAnswer = { text: string; changes: string[] };
|
||||
|
||||
const IMPROVE_SCHEMA = obj({ text: str, changes: list(str) }, { changes: 'A short list of what changed and why' });
|
||||
|
||||
const IMPROVE_SYSTEM = (mode: ImproveMode, where: string) => [
|
||||
`You improve text a church events team wrote for ${where}.`,
|
||||
mode === 'fix'
|
||||
? '- Only fix spelling, grammar and punctuation. Change nothing else.'
|
||||
: mode === 'shorter'
|
||||
? '- Make it noticeably shorter and easier to scan, fixing spelling and grammar too.'
|
||||
: '- Fix spelling, grammar and punctuation, and make it clear and friendly, about the same length or shorter.',
|
||||
'- Keep every fact (times, dates, prices, places, ages) exactly; add none.',
|
||||
'- Plain text, no markdown. Keep the writer\'s warmth, and any humour that works in public. Keep placeholders like {{name}} exactly.',
|
||||
KEEP_PLACEHOLDERS,
|
||||
].join('\n');
|
||||
|
||||
const WHERE = { description: 'an event page', banner: 'a short banner across the top of the website', message: 'a message to people registered for an event' } as const;
|
||||
export type ImproveWhere = keyof typeof WHERE;
|
||||
|
||||
export async function improveText(userId: string, input: { text: string; mode: ImproveMode; where: ImproveWhere }): Promise<{ result: ImproveAnswer; status: AiStatus }> {
|
||||
const p = protect(input.text);
|
||||
const { output, status } = await runHelper('improve_text', userId, { system: IMPROVE_SYSTEM(input.mode, WHERE[input.where]), input: p.text, schema: IMPROVE_SCHEMA, maxTokens: Math.min(8000, 600 + Math.ceil(input.text.length / 2)), effort: 'low' });
|
||||
return { result: restore(output as ImproveAnswer, p.found), status };
|
||||
}
|
||||
Reference in New Issue
Block a user