Merge branch 'feat/ai-model-picker'

This commit is contained in:
2026-10-30 17:21:30 +02:00
12 changed files with 131 additions and 26 deletions
+13
View File
@@ -5,6 +5,19 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [1.6.1] - 2026-10-30
### Changed
- **Claude Sonnet 5.5 is the default AI model** (was Haiku 5.5), after a trial of all five helpers
on both: Haiku made factual mistakes in a report summary, over-counted feedback themes and
misspelt words in messages. A Hub that already saved its AI settings keeps its model until it's
changed on Settings → AI.
- **Settings → AI has a model list** — Sonnet 5.5, Haiku 5.5 and Opus 5.5 with their list prices,
or another model ID typed in. Choosing one fills in its prices (still editable, with a note and
"Use the list price" when they differ). Blank prices use the built-in ones.
- Cache reads are metered at each model's own price (Opus 5.5 reads at half the usual rate).
## [1.6.0] - 2026-10-30
### Added
+4 -2
View File
@@ -52,8 +52,10 @@ and `HUB_PUBLIC_KEY` (the public key shown in Hub → Settings) in Cross Events'
## AI (Cross Events 2.0)
Sites call AI through the Hub (protocol §3b), so the Claude API key never leaves this server.
Set it up in **Settings → AI**: the key, the model (Claude Haiku 5.5), its prices, the exchange rate
and the default markup — AI stays off for every site until the key and exchange rate are saved;
Set it up in **Settings → AI**: the key, the model (Claude Sonnet 5.5 by default; choosing one from the
list fills in its prices, kept in `backend/src/utils/aiModels.js` — update that list in a release when
Anthropic's prices change), the exchange rate and the default markup — AI stays off for every site
until the key and exchange rate are saved;
**Test the saved key** checks them. Each licence has a monthly **AI cap** in rand (0 = off) and an
optional markup override, on the customer's page. The cap counts what the church is charged
(real cost plus markup); the Hub checks the worst case before every call, so a month can't run over.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "1.6.0",
"version": "1.6.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "1.6.0",
"version": "1.6.1",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "1.6.0",
"version": "1.6.1",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+2 -1
View File
@@ -14,6 +14,7 @@ const { VERSION_RE, sortReleases, syncLatestVersion } = require('../utils/releas
const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases } = require('../utils/releaseSync');
const ai = require('../utils/ai');
const { AI_MODELS } = require('../utils/aiModels');
const router = express.Router();
router.use(protect);
@@ -384,7 +385,7 @@ router.delete('/notices/:id', wrap(async (req, res) => {
// ─── Settings ─────────────────────────────────────────────────────────────────
router.get('/settings', wrap(async (req, res) => {
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured() });
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS });
}));
const SMTP_FIELDS = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_pass_clear', 'smtp_from'];
+12 -5
View File
@@ -15,10 +15,12 @@
const Anthropic = require('@anthropic-ai/sdk');
const prisma = require('../config/db');
const { getSettings, aiApiKey } = require('./settings');
const { findModel } = require('./aiModels');
// South African time (UTC+2, no daylight saving): the month the cap belongs to.
const SAST_MS = 2 * 60 * 60 * 1000;
// Cache writes cost 1.25× the input price, cache reads 0.1×.
// Cache writes cost 1.25× the input price; reads are priced per model (utils/aiModels.js), 0.1×
// the input price for a model the Hub doesn't know.
const CACHE_WRITE = 1.25;
const CACHE_READ = 0.1;
// Prompts are priced higher from 100K tokens, so the Hub refuses anything close to it.
@@ -46,22 +48,27 @@ function renewsOn(date = new Date()) {
/**
* Prices for a call, or null when the Hub's AI isn't set up (no key or no exchange rate).
* Blank prices use the built-in ones for the model (utils/aiModels.js); cache reads always do,
* falling back to 0.1× the input price for a model the Hub doesn't know.
* `licence.aiMarkupPercent` overrides the Hub's default markup.
*/
function pricing(settings, licence, hasKey) {
const inUsd = parseFloat(settings.ai_input_usd_per_mtok);
const outUsd = parseFloat(settings.ai_output_usd_per_mtok);
const known = findModel(settings.ai_model);
const price = (value, builtIn) => (value != null && String(value).trim() !== '' ? parseFloat(value) : builtIn ?? NaN);
const inUsd = price(settings.ai_input_usd_per_mtok, known?.inputUsd);
const outUsd = price(settings.ai_output_usd_per_mtok, known?.outputUsd);
const usdZar = parseFloat(settings.ai_usd_zar);
const markup = licence?.aiMarkupPercent ?? parseInt(settings.ai_markup_percent, 10);
if (!hasKey || !settings.ai_model || !(inUsd >= 0) || !(outUsd > 0) || !(usdZar > 0) || !(markup >= 0)) return null;
return { model: settings.ai_model, inUsd, outUsd, usdZar, markup };
const cacheReadUsd = known && known.inputUsd === inUsd ? known.cacheReadUsd : inUsd * CACHE_READ;
return { model: settings.ai_model, inUsd, outUsd, cacheReadUsd, usdZar, markup };
}
/** Real and charged cost of some usage, in millicents (rounded up). */
function costOf(usage, price) {
const usd = ((usage.inputTokens || 0) * price.inUsd
+ (usage.cacheWriteTokens || 0) * price.inUsd * CACHE_WRITE
+ (usage.cacheReadTokens || 0) * price.inUsd * CACHE_READ
+ (usage.cacheReadTokens || 0) * (price.cacheReadUsd ?? price.inUsd * CACHE_READ)
+ (usage.outputTokens || 0) * price.outUsd) / 1e6;
const real = usd * price.usdZar * 100 * 1000;
return { real: Math.ceil(real), charged: Math.ceil(real * (1 + price.markup / 100)) };
+21
View File
@@ -0,0 +1,21 @@
/**
* The Claude models Settings → AI offers, with Anthropic's list prices in US dollars per million
* tokens (prompts under 100K tokens — the Hub refuses anything near that). Anthropic's API doesn't
* publish prices, so they're kept here: choosing a model fills in its prices, which stay editable
* in case Anthropic changes them before a Hub release does.
*
* Prices as of October 2026. Cache writes (5-minute) cost 1.25× the input price for every model;
* cache reads vary, so each model gives its own.
*/
const AI_MODELS = [
{ id: 'claude-sonnet-5-5', label: 'Claude Sonnet 5.5', inputUsd: 2, outputUsd: 10, cacheReadUsd: 0.2, note: 'The default. Chosen after the October 2026 trial: right on report figures, feedback counts and message spelling.' },
{ id: 'claude-haiku-5-5', label: 'Claude Haiku 5.5', inputUsd: 0.1, outputUsd: 0.5, cacheReadUsd: 0.01, note: 'About 15× cheaper; made some factual and spelling mistakes in the trial.' },
{ id: 'claude-opus-5-5', label: 'Claude Opus 5.5', inputUsd: 4, outputUsd: 20, cacheReadUsd: 0.2, note: 'The most capable of the three, at twice Sonnet\'s price.' },
];
const DEFAULT_AI_MODEL = AI_MODELS[0];
const findModel = id => AI_MODELS.find(m => m.id === id) || null;
module.exports = { AI_MODELS, DEFAULT_AI_MODEL, findModel };
+6 -3
View File
@@ -1,5 +1,6 @@
const prisma = require('../config/db');
const { encrypt, decrypt } = require('./crypto');
const { DEFAULT_AI_MODEL } = require('./aiModels');
// Hub settings Joshua edits on the Settings page, with their defaults.
const DEFAULTS = {
@@ -26,10 +27,12 @@ const DEFAULTS = {
release_sync_error: '',
// AI for Cross Events 2.0 (utils/ai.js). Off until a key and the exchange rate are set.
ai_api_key: '',
ai_model: 'claude-haiku-5-5',
// One of utils/aiModels.js, or another model ID typed in.
ai_model: DEFAULT_AI_MODEL.id,
// US dollars per million tokens, for prompts under 100K tokens (the Hub refuses bigger ones).
ai_input_usd_per_mtok: '0.10',
ai_output_usd_per_mtok: '0.50',
// Filled in from utils/aiModels.js when a model is chosen; blank means the built-in price.
ai_input_usd_per_mtok: String(DEFAULT_AI_MODEL.inputUsd),
ai_output_usd_per_mtok: String(DEFAULT_AI_MODEL.outputUsd),
// Rand per US dollar.
ai_usd_zar: '',
// Default markup on the real cost, in %; a licence can override it.
+22 -1
View File
@@ -38,7 +38,7 @@ jest.mock('@anthropic-ai/sdk', () => {
const ai = require('../src/utils/ai');
const install = { id: 'inst_1', licenceId: 'lic_1' };
const price = { model: 'claude-haiku-5-5', inUsd: 0.1, outUsd: 0.5, usdZar: 20, markup: 40 };
const price = { model: 'claude-haiku-5-5', inUsd: 0.1, outUsd: 0.5, cacheReadUsd: 0.01, usdZar: 20, markup: 40 };
const body = { protocolVersion: 1, helper: 'draft_message', system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 1000 };
const reply = (usage, extra = {}) => ({ model: 'claude-haiku-5-5', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Hi all!' }], usage, ...extra });
@@ -67,6 +67,27 @@ describe('pricing', () => {
expect(ai.pricing(mockSettings, { aiMarkupPercent: 0 }, true).markup).toBe(0);
});
test('Sonnet 5.5 is the default model, at its list prices', () => {
const { DEFAULTS } = jest.requireActual('../src/utils/settings');
expect(DEFAULTS).toMatchObject({ ai_model: 'claude-sonnet-5-5', ai_input_usd_per_mtok: '2', ai_output_usd_per_mtok: '10' });
});
test('blank prices use the built-in list; cache reads are priced per model', () => {
const sonnet = ai.pricing({ ...mockSettings, ai_model: 'claude-sonnet-5-5', ai_input_usd_per_mtok: '', ai_output_usd_per_mtok: '' }, mockState.licence, true);
expect(sonnet).toMatchObject({ inUsd: 2, outUsd: 10, cacheReadUsd: 0.2 });
// Opus 5.5 reads its cache at 0.05× the input price.
expect(ai.pricing({ ...mockSettings, ai_model: 'claude-opus-5-5', ai_input_usd_per_mtok: '4', ai_output_usd_per_mtok: '20' }, mockState.licence, true).cacheReadUsd).toBe(0.2);
});
test('a model the Hub doesn\'t know needs its prices; cache reads at 0.1× of an edited price', () => {
expect(ai.pricing({ ...mockSettings, ai_model: 'claude-new-model', ai_input_usd_per_mtok: '', ai_output_usd_per_mtok: '' }, mockState.licence, true)).toBeNull();
const other = ai.pricing({ ...mockSettings, ai_model: 'claude-new-model', ai_input_usd_per_mtok: '3', ai_output_usd_per_mtok: '15' }, mockState.licence, true);
expect(other.inUsd).toBe(3);
expect(other.cacheReadUsd).toBeCloseTo(0.3);
// Sonnet with a changed input price: its listed cache price no longer applies.
expect(ai.pricing({ ...mockSettings, ai_model: 'claude-sonnet-5-5', ai_input_usd_per_mtok: '2.5', ai_output_usd_per_mtok: '10' }, mockState.licence, true).cacheReadUsd).toBe(0.25);
});
test('cost in millicents: input, cache writes at 1.25×, reads at 0.1×, output; markup on top', () => {
// 1M input tokens at $0.10 × R20 = R2 = 200 000 millicents.
expect(ai.costOf({ inputTokens: 1e6 }, price)).toEqual({ real: 200000, charged: 280000 });
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "1.6.0",
"version": "1.6.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "1.6.0",
"version": "1.6.1",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "1.6.0",
"version": "1.6.1",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+45 -8
View File
@@ -32,17 +32,29 @@ const TABS: { key: Tab; label: string }[] = [
type AiUsage = { month: string; installs: AiInstallUse[]; totals: { calls: number; realCents: number; chargedCents: number; profitCents: number } };
type AiModel = { id: string; label: string; inputUsd: number; outputUsd: number; cacheReadUsd: number; note: string };
const AI_KEYS = ["ai_model", "ai_input_usd_per_mtok", "ai_output_usd_per_mtok", "ai_usd_zar", "ai_markup_percent"];
const OTHER = "__other";
const AI_FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "ai_model", label: "Model", hint: "claude-haiku-5-5 — the cheapest current model." },
{ key: "ai_input_usd_per_mtok", label: "Input price (US$ per million tokens)", hint: "Haiku 5.5: 0.10 (prompts under 100K tokens).", type: "number" },
{ key: "ai_output_usd_per_mtok", label: "Output price (US$ per million tokens)", hint: "Haiku 5.5: 0.50.", type: "number" },
{ key: "ai_usd_zar", label: "Exchange rate (rand per US$)", hint: "AI stays off until this is set. Each call is charged at the rate in force when it ran.", type: "number" },
{ key: "ai_markup_percent", label: "Default markup (%)", hint: "Added to the real cost; covers small overruns and is the profit. A licence can override it.", type: "number" },
];
/** Settings → AI: the Claude key and prices, and what each install used this month. */
function AiTab({ settings, onSaved, setMsg }: { settings: Settings; onSaved: (s: Settings) => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState(() => Object.fromEntries(AI_FIELDS.map(f => [f.key, settings[f.key] ?? ""])));
/** Settings → AI: the Claude key, model and prices, and what each install used this month. */
function AiTab({ settings, models, onSaved, setMsg }: { settings: Settings; models: AiModel[]; onSaved: (s: Settings) => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState(() => Object.fromEntries(AI_KEYS.map(k => [k, settings[k] ?? ""])));
const known = models.find(m => m.id === form.ai_model);
const [other, setOther] = useState(() => !!form.ai_model && !known);
// Choosing a model fills in its list prices; they stay editable.
const chooseModel = (value: string) => {
if (value === OTHER) { setOther(true); setForm({ ...form, ai_model: "" }); return; }
const m = models.find(x => x.id === value);
setOther(false);
setForm({ ...form, ai_model: value, ...(m ? { ai_input_usd_per_mtok: String(m.inputUsd), ai_output_usd_per_mtok: String(m.outputUsd) } : {}) });
};
const pricesDiffer = !!known && (parseFloat(form.ai_input_usd_per_mtok) !== known.inputUsd || parseFloat(form.ai_output_usd_per_mtok) !== known.outputUsd);
const [key, setKey] = useState({ value: "", clear: false });
const [testing, setTesting] = useState(false);
const [month, setMonth] = useState("");
@@ -85,6 +97,30 @@ function AiTab({ settings, onSaved, setMsg }: { settings: Settings; onSaved: (s:
)}
<p className="mt-1 text-xs text-slate-500">Stored encrypted; never sent to the browser or to sites.</p>
</div>
<div>
<label className="label" htmlFor="ai_model">Model</label>
<select id="ai_model" className="input" value={other ? OTHER : form.ai_model} onChange={e => chooseModel(e.target.value)}>
{models.map(m => <option key={m.id} value={m.id}>{m.label} — ${m.inputUsd} / ${m.outputUsd} per million tokens</option>)}
<option value={OTHER}>Another model (type its ID)</option>
</select>
{other ? (
<input id="ai_model_other" aria-label="Model ID" className="input mt-2" placeholder="claude-…" value={form.ai_model} onChange={e => setForm({ ...form, ai_model: e.target.value })} />
) : known && <p className="mt-1 text-xs text-slate-500">{known.note}</p>}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="ai_input_usd_per_mtok">Input price (US$ per million tokens)</label>
<input id="ai_input_usd_per_mtok" className="input" type="number" step="any" min={0} value={form.ai_input_usd_per_mtok} onChange={e => setForm({ ...form, ai_input_usd_per_mtok: e.target.value })} />
</div>
<div>
<label className="label" htmlFor="ai_output_usd_per_mtok">Output price (US$ per million tokens)</label>
<input id="ai_output_usd_per_mtok" className="input" type="number" step="any" min={0} value={form.ai_output_usd_per_mtok} onChange={e => setForm({ ...form, ai_output_usd_per_mtok: e.target.value })} />
</div>
</div>
<p className="-mt-1 text-xs text-slate-500">
{other ? "Enter the model's prices from Anthropic's pricing page." : "Filled in from Anthropic's list prices when you choose a model. Change them only if Anthropic's prices change."}
{pricesDiffer && <> These differ from the list price (${known!.inputUsd} / ${known!.outputUsd}). <button type="button" className="text-indigo-700 hover:underline" onClick={() => chooseModel(known!.id)}>Use the list price</button></>}
</p>
{AI_FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
@@ -133,6 +169,7 @@ export default function SettingsPage() {
const [settings, setSettings] = useState<Settings | null>(null);
const [publicKey, setPublicKey] = useState("");
const [smtp, setSmtp] = useState(false);
const [aiModels, setAiModels] = useState<AiModel[]>([]);
const [audit, setAudit] = useState<AuditRow[]>([]);
const [auditQuery, setAuditQuery] = useState("");
const [pw, setPw] = useState({ currentPassword: "", newPassword: "" });
@@ -142,7 +179,7 @@ export default function SettingsPage() {
const [testing, setTesting] = useState(false);
useEffect(() => {
api<{ settings: Settings; publicKey: string; smtp: boolean }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ settings: Settings; publicKey: string; smtp: boolean; aiModels: AiModel[] }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); setAiModels(r.aiModels || []); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<AuditRow[]>("/api/admin/audit").then(setAudit).catch(() => {});
// Open the tab named in the address (#email), so a reload or a link lands in the same place.
const fromHash = window.location.hash.slice(1);
@@ -264,7 +301,7 @@ export default function SettingsPage() {
</form>
)}
{tab === "ai" && <AiTab settings={settings} onSaved={setSettings} setMsg={setMsg} />}
{tab === "ai" && <AiTab settings={settings} models={aiModels} onSaved={setSettings} setMsg={setMsg} />}
{tab === "security" && (
<div className="max-w-2xl space-y-6">