Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(tutor): back the session ledger with Postgres before falling back to KV
nirholas6505050bcb16
diff --git a/agents/tutor/src/session.js b/agents/tutor/src/session.jsindex 648e2f5e8..637410f60 100644--- a/agents/tutor/src/session.js+++ b/agents/tutor/src/session.js@@ -1,18 +1,32 @@-// Pay-As-You-Learn Tutor — session ledger.+// Pay-As-You-Learn Tutor: session ledger.//// Each tutoring session keeps a running tab: every answered question appends an// itemized charge, and "end session" produces an itemized invoice with a-// SHA-256 attestation over the entries. State lives in Upstash/Vercel KV (REST)-// with a 7-day TTL so a learner can resume a session after closing the tab.+// SHA-256 attestation over the entries.//-// Storage is best-effort: when no KV is configured the tutor still works as a-// stateless per-question service — each answer simply reports its own charge-// and the session total reflects only the current request.+// Storage tiers, in order of preference:+// 1. Postgres `tutor_sessions` (DATABASE_URL). This is the platform's real+// store and the tier production runs on; the table is created lazily.+// 2. Upstash/Vercel KV REST (UPSTASH_REDIS_REST_URL/TOKEN), for a deployment+// that has KV but no database.+// 3. Process-local memory, for local dev with neither configured. Resume then+// works within one server process and nowhere else.+//+// Records expire 7 days after the last write, so a learner can close the tab+// and resume the same session later.+//+// Reads propagate a storage fault to the caller: reporting "$0, no questions"+// because the store is down would tell a learner who owes money that they owe+// nothing. Writes on the paid path are best-effort, because losing a ledger row+// must never cost the learner the answer they already paid for.import { createHash } from 'crypto';+import { sql } from '../../../api/_lib/db.js';+import { databaseConfigured } from '../../../api/_lib/env.js';const SESSION_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 daysconst MAX_ENTRIES = 500; // hard cap so a session object can't grow unbounded+const PRUNE_INTERVAL_MS = 60 * 60 * 1000; // at most one expired-row sweep per hour per processfunction kvCredentials() {const url =@@ -26,59 +40,167 @@ function kvCredentials() {return { url, token };}-export function kvAvailable() {+/** Which backend this process will use: 'db', 'kv', or 'memory'. */+export function sessionBackend() {+ if (databaseConfigured()) return 'db';const { url, token } = kvCredentials();- return Boolean(url && token);+ return url && token ? 'kv' : 'memory';+}++// ── Postgres tier ─────────────────────────────────────────────────────────────++let schemaReady = null;++function ensureSchema() {+ if (schemaReady) return schemaReady;+ schemaReady = (async () => {+ await sql`+ create table if not exists tutor_sessions (+ session_id text primary key,+ status text not null default 'open',+ total_atomics bigint not null default 0,+ session jsonb not null,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ expires_at timestamptz not null+ )+ `;+ await sql`create index if not exists tutor_sessions_expires_idx on tutor_sessions (expires_at)`;+ return true;+ })();+ // A failed CREATE (outage, permissions) must not poison every later call with+ // the same rejected promise; drop it so the next request retries.+ schemaReady.catch(() => {+ schemaReady = null;+ });+ return schemaReady;+}++let lastPruneAt = 0;++function prunePostgres() {+ const now = Date.now();+ if (now - lastPruneAt < PRUNE_INTERVAL_MS) return;+ lastPruneAt = now;+ sql`delete from tutor_sessions where expires_at < now()`.catch((err) => {+ console.warn('[tutor] expired-session sweep failed:', err?.message || err);+ });+}++async function dbRead(sessionId) {+ await ensureSchema();+ const rows = await sql`+ select session from tutor_sessions+ where session_id = ${sessionId} and expires_at > now()+ `;+ const raw = rows?.[0]?.session;+ if (!raw) return null;+ return typeof raw === 'string' ? JSON.parse(raw) : raw;+}++async function dbWrite(session) {+ await ensureSchema();+ await sql`+ insert into tutor_sessions (session_id, status, total_atomics, session, created_at, updated_at, expires_at)+ values (+ ${session.sessionId},+ ${session.status},+ ${session.totalAtomics},+ ${JSON.stringify(session)}::jsonb,+ ${session.createdAt}::timestamptz,+ now(),+ now() + ${`${SESSION_TTL_SECONDS} seconds`}::interval+ )+ on conflict (session_id) do update set+ status = excluded.status,+ total_atomics = excluded.total_atomics,+ session = excluded.session,+ updated_at = now(),+ expires_at = excluded.expires_at+ `;+ prunePostgres();}-async function kvGet(key) {+// ── KV tier ───────────────────────────────────────────────────────────────────++function sessionKey(sessionId) {+ return `tutor:session:v1:${sessionId}`;+}++async function kvRead(sessionId) {const { url, token } = kvCredentials();- if (!url || !token) return null;- try {- const r = await fetch(`${url}/get/${encodeURIComponent(key)}`, {- headers: { authorization: `Bearer ${token}` },- });- const d = await r.json();- return d.result ? JSON.parse(d.result) : null;- } catch {- return null;- }+ const r = await fetch(`${url}/get/${encodeURIComponent(sessionKey(sessionId))}`, {+ headers: { authorization: `Bearer ${token}` },+ });+ if (!r.ok) throw new Error(`kv get failed with ${r.status}`);+ const d = await r.json();+ return d.result ? JSON.parse(d.result) : null;}-async function kvSet(key, value, ttlSeconds) {+async function kvWrite(session) {const { url, token } = kvCredentials();- if (!url || !token) return;- try {- // Upstash REST: the raw request body IS the stored value; TTL goes in the- // query string. A JSON envelope body would be stored verbatim and corrupt- // every subsequent read.- await fetch(`${url}/set/${encodeURIComponent(key)}?EX=${ttlSeconds}`, {- method: 'POST',- headers: { authorization: `Bearer ${token}` },- body: JSON.stringify(value),- });- } catch {- // Non-fatal — session simply won't persist.+ // Upstash REST: the raw request body IS the stored value; TTL goes in the+ // query string. A JSON envelope body would be stored verbatim and corrupt+ // every subsequent read.+ const key = encodeURIComponent(sessionKey(session.sessionId));+ const r = await fetch(`${url}/set/${key}?EX=${SESSION_TTL_SECONDS}`, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}` },+ body: JSON.stringify(session),+ });+ if (!r.ok) throw new Error(`kv set failed with ${r.status}`);+}++// ── Memory tier ───────────────────────────────────────────────────────────────++const memory = new Map();++function memoryRead(sessionId) {+ const rec = memory.get(sessionId);+ if (!rec) return null;+ if (rec.expiresAt <= Date.now()) {+ memory.delete(sessionId);+ return null;}+ return JSON.parse(JSON.stringify(rec.session));}-function sessionKey(sessionId) {- return `tutor:session:v1:${sessionId}`;+function memoryWrite(session) {+ memory.set(session.sessionId, {+ session: JSON.parse(JSON.stringify(session)),+ expiresAt: Date.now() + SESSION_TTL_SECONDS * 1000,+ });+}++// ── Backend dispatch ──────────────────────────────────────────────────────────++/** Read the stored session, or null when this id has no tab. Throws on a store fault. */+async function readSession(sessionId) {+ const backend = sessionBackend();+ const stored =+ backend === 'db' ? await dbRead(sessionId) : backend === 'kv' ? await kvRead(sessionId) : memoryRead(sessionId);+ // A record written by a foreign writer (or an older shape) lacks the session+ // fields; treat it as absent rather than crashing the charge path.+ if (!stored || !Array.isArray(stored.entries)) return null;+ if (!Number.isFinite(stored.totalAtomics)) stored.totalAtomics = 0;+ if (!stored.status) stored.status = 'open';+ return stored;+}++async function writeSession(session) {+ const backend = sessionBackend();+ if (backend === 'db') return dbWrite(session);+ if (backend === 'kv') return kvWrite(session);+ return memoryWrite(session);}function emptySession(sessionId) {return { sessionId, createdAt: new Date().toISOString(), entries: [], totalAtomics: 0, status: 'open' };}-/** Load a session, or a fresh empty one when absent/unstored. */+/** Load a session, or a fresh empty one when this id has no tab yet. */export async function loadSession(sessionId) {- const existing = await kvGet(sessionKey(sessionId));- // Records written by the old envelope-body kvSet (or any foreign value under- // our key) lack the session shape — treat them as absent rather than crashing- // the charge path on `entries.push`.- if (!existing || !Array.isArray(existing.entries)) return emptySession(sessionId);- if (!Number.isFinite(existing.totalAtomics)) existing.totalAtomics = 0;- return existing;+ return (await readSession(sessionId)) || emptySession(sessionId);}/**@@ -86,11 +208,20 @@ export async function loadSession(sessionId) {* Returns the updated session.*/export async function appendCharge(sessionId, entry) {- const session = await loadSession(sessionId);+ let session;+ try {+ session = await loadSession(sessionId);+ } catch (err) {+ // The learner has already paid for this answer: a ledger outage costs them+ // the running total, never the explanation itself.+ console.warn('[tutor] session ledger read failed, charging a fresh tab:', err?.message || err);+ session = emptySession(sessionId);+ }if (session.status === 'closed') {- const err = new Error('session is closed — start a new session');+ const err = new Error('session is closed, start a new session');err.status = 409;err.code = 'session_closed';+ err.expose = true;throw err;}session.entries.push({@@ -105,7 +236,11 @@ export async function appendCharge(sessionId, entry) {session.entries = session.entries.slice(-MAX_ENTRIES);}session.totalAtomics = session.entries.reduce((sum, e) => sum + (e.costAtomics || 0), 0);- await kvSet(sessionKey(sessionId), session, SESSION_TTL_SECONDS);+ try {+ await writeSession(session);+ } catch (err) {+ console.warn('[tutor] session ledger write failed:', err?.message || err);+ }return session;}@@ -114,13 +249,7 @@ export function atomicsToUsd(atomics) {return (Number(atomics) / 1_000_000).toFixed(6);}-/**- * Close a session and produce an itemized, attested invoice.- * Idempotent: closing an already-closed session returns the same invoice.- */-export async function closeSession(sessionId) {- const session = await loadSession(sessionId);-+function buildInvoice(session) {const lineItems = session.entries.map((e, i) => ({n: i + 1,question: e.question,@@ -134,11 +263,11 @@ export async function closeSession(sessionId) {const attestation ='sha256:' +createHash('sha256')- .update(JSON.stringify({ sessionId, lineItems, totalAtomics: session.totalAtomics }))+ .update(JSON.stringify({ sessionId: session.sessionId, lineItems, totalAtomics: session.totalAtomics })).digest('hex');- const invoice = {- sessionId,+ return {+ sessionId: session.sessionId,createdAt: session.createdAt,closedAt: new Date().toISOString(),questionCount: lineItems.length,@@ -147,9 +276,27 @@ export async function closeSession(sessionId) {totalUsd: atomicsToUsd(session.totalAtomics),attestation,};+}- session.status = 'closed';- session.invoice = invoice;- await kvSet(sessionKey(sessionId), session, SESSION_TTL_SECONDS);+/**+ * Close a session and produce an itemized, attested invoice.+ * Idempotent: closing an already-closed session returns the stored invoice+ * verbatim, closedAt included.+ */+export async function closeSession(sessionId) {+ const stored = await readSession(sessionId);+ if (stored?.status === 'closed' && stored.invoice) return stored.invoice;++ const session = stored || emptySession(sessionId);+ const invoice = buildInvoice(session);++ // Never persist a close for an id that has no tab. Writing a `closed` record+ // for an unused id would make it permanently unusable (appendCharge rejects a+ // closed session) for whoever actually holds it.+ if (stored) {+ session.status = 'closed';+ session.invoice = invoice;+ await writeSession(session);+ }return invoice;}diff --git a/api/tutor/session.js b/api/tutor/session.jsindex aa018ff0f..11abd31f2 100644--- a/api/tutor/session.js+++ b/api/tutor/session.js@@ -1,15 +1,27 @@-// Tutor session ledger — FREE, read-only / close operations (no x402 charge).+// Tutor session ledger: FREE, read-only / close operations (no x402 charge).//-// GET /api/tutor/session?sessionId=<id> → current itemized tab (for resume)-// POST /api/tutor/session { sessionId, action: "end" } → close + signed invoice+// GET /api/tutor/session?sessionId=<id> -> current itemized tab (for resume)+// POST /api/tutor/session { sessionId, action: "end" } -> close + signed invoice//// Answering questions is the paid action (POST /api/x402/tutor, $0.01 each).// Viewing the running tab and closing the session are free: a learner must// never be charged to see what they owe or to end the session.+//+// The sessionId is the capability: it is minted client-side as a UUID and is+// the only thing that addresses a tab, so there is no account to authenticate+// against here. A store fault surfaces as a 5xx rather than an empty tab, so a+// learner is never shown "$0, no questions" for a session they are being+// billed for.import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';import { loadSession, closeSession, atomicsToUsd } from '../../agents/tutor/src/session.js';+const MAX_SESSION_ID = 100;++function cleanSessionId(value) {+ return typeof value === 'string' ? value.trim().slice(0, MAX_SESSION_ID) : '';+}+function itemize(session) {return {sessionId: session.sessionId,@@ -36,15 +48,18 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET', 'POST'])) return;if (req.method === 'GET') {- const sessionId = new URL(req.url, 'http://x').searchParams.get('sessionId');+ const sessionId = cleanSessionId(new URL(req.url, 'http://x').searchParams.get('sessionId'));if (!sessionId) return error(res, 400, 'missing_session', 'sessionId query param required');- const session = await loadSession(sessionId.slice(0, 100));+ // An id with no stored tab is not an error: the /tutor page resumes by+ // asking for its locally-minted id on every load, and a fresh id+ // legitimately has nothing behind it yet.+ const session = await loadSession(sessionId);return json(res, 200, itemize(session));}- // POST — close the session and return the signed invoice.- const body = await readJson(req).catch(() => ({}));- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim().slice(0, 100) : '';+ // POST: close the session and return the signed invoice.+ const body = await readJson(req);+ const sessionId = cleanSessionId(body?.sessionId);if (!sessionId) return error(res, 400, 'missing_session', 'sessionId is required');if (body?.action && body.action !== 'end') {return error(res, 400, 'bad_action', 'only action "end" is supported');