The repository
A start folder and the finish.
Open the kit04-remember-the-learner in learn-tutor-starter
Build with Learn · Step 4
About 10 minutes with a coding assistant.
What you'll build. The tutor picks up where the learner left off. The learner finishes a session; Learn saves its summary and what it learned about them; next time your app shows "Last time" and carries on.
FOREVERLEARNING_API_KEY and your API host in FOREVERLEARNING_BASE_URL.03-photos-of-work. The finished step is 04-remember-the-learner.Ending a session is a turn (5¢ when it succeeds). The saved reads are free.
Open a copy of 03-photos-of-work in your coding assistant, with your key and host in the environment it runs commands in, and paste the prompt. Before we publish a prompt, we run it three times in each of two coding assistants against the release you use. Coding assistants are your tools; they are not part of the Learn API.
Goal: the tutor picks up where the learner left off. The learner finishes a session, and next time the app shows what Learn saved about last time and carries on.
Read first: https://developers.foreverlearning.ai/docs/learn/ (the Learn integration guide, especially "Read committed learning records" and "Starting a new session while one is open"), and the Learn OpenAPI contract and the runnable TypeScript example linked there. Use only what they describe.
Start from: the app in this folder, a copy of the 03-photos-of-work folder of learn-tutor-starter. Keep how it works and add to it.
Build:
1. Keep each learner's record on the server (a JSON file under data/ is fine): their open session, and the sessions that ended. Keep the learner id in the browser's cookie as before, so the same browser is the same learner next time.
2. A "Finish for today" button that ends the open session through Learn's end-session route, shows the closeout reply with its safety status and receipt, and moves the session to the learner's ended sessions.
3. When the page opens and the learner has an ended session, a "Last time" panel with that session's saved summary and the concepts in the learner's profile, grouped by name, from Learn's free saved reads. Empty evidence stays empty.
4. The learner's next message starts a new session and carries on.
Rules:
- Keep the API key on the server, in the FOREVERLEARNING_API_KEY environment variable. Read the API host from FOREVERLEARNING_BASE_URL. If FOREVERLEARNING_ASSIGNMENT_ID is set, send it as X-Assignment-Id. Never send the key to the browser, print it or write it into a file.
- Render each reply's Markdown (headings, lists, bold, code) and its math. Learn writes math between \( and \) inline and between \[ and \] for display math, which often spans several lines. Use a math library, loaded the way your page loads its other code, so the learner never sees raw notation.
- Use a pseudonymous learner id, never a name or an email. Make a new random id for each new browser; never reuse a fixed test id.
- Keep your own record of each learner's sessions, so you know which session is open and which ended.
- Each message is a real turn, at 5¢ per turn that succeeds, and ending a session is a turn too. Test with three turns: a question, the finish, and one question in the next session. Test as one learner, keeping the same cookie for all your test messages: a test key admits only a limited number of new learners a day.
Done when:
- you ran `npm start`, asked a question, pressed "Finish for today", and the closeout reply showed
- reopening the page shows "Last time" with the saved summary
- the next question starts a new session and gets a reply
- receipts.jsonl has one line for each confirmed turn, the closeout includedPaste into your coding assistant.
The guide sections this step uses: Read committed learning records and A new session while one is open.
POST /v1/sessions/{id}/end with {"operation_id": "<uuid>"} and the same value as the Idempotency-Key. The reply comes back like a turn's and ends with session_ended. Learn saves the summary.GET /v1/quest/sessions/{id}/summary (the saved summary) and GET /v1/quest/learners/{user_id}/profile (observed signals). Free. The profile can list the same concept once for each request that observed it, so group the signals by concept. Empty evidence stays empty; these are observations, not grades.Keep your own record of each learner's sessions, so you know which one is open and which ended. GET /v1/quest/sessions lists a learner's saved sessions too (an empty list for a new learner). If a learner already has an open session (for example after your server restarts and forgets it), preparing a new one makes Learn close the earlier session first: that closeout is billed as its own request, and the first reply takes about ten seconds longer, about 19 seconds (A new session while one is open).
Starting from 03-photos-of-work, replace these files. Then run npm start and open http://localhost:3000.
File: learn.ts
// A small Learn API client for your server. The key is read from the environment
// and never leaves this process. Guide: https://developers.foreverlearning.ai/docs/learn/
import { randomUUID } from 'node:crypto';
const API_VERSION = '2026-12-01';
export type Posture = 'guided' | 'feedback' | 'explain';
export interface SafetyStatus {
level: 'unknown' | 'clear' | 'watch' | 'warning' | 'critical';
evaluated: boolean;
response_action: 'none' | 'support' | 'escalate';
source: string;
}
export interface Receipt {
request_id: string;
session_id: string;
posture: string;
turn_index: number;
billable_units: number;
charge_micro_usd: number;
settlement: string;
safety_level: string;
}
export interface TurnResult {
request_id: string;
session_id: string;
reply: string;
display: string;
safety: SafetyStatus;
receipt: Receipt;
}
export class LearnError extends Error {
status: number;
code: string;
requestId: string;
constructor(status: number, code: string, message: string, requestId = '') {
super(message);
this.status = status;
this.code = code;
this.requestId = requestId;
}
}
function settings() {
const key = process.env.FOREVERLEARNING_API_KEY ?? '';
const base = (process.env.FOREVERLEARNING_BASE_URL ?? 'https://developers-api.foreverlearning.ai/v1').replace(/\/+$/, '');
const assignment = process.env.FOREVERLEARNING_ASSIGNMENT_ID ?? '';
return { key, base, assignment };
}
export function isConfigured(): boolean {
return settings().key.length > 0;
}
function headers(learnerId: string, idempotencyKey?: string): Record<string, string> {
const { key, assignment } = settings();
const h: Record<string, string> = {
Authorization: 'Bearer ' + key,
'X-User-Id': learnerId,
'FL-API-Version': API_VERSION,
};
if (assignment) h['X-Assignment-Id'] = assignment;
if (idempotencyKey) {
h['Idempotency-Key'] = idempotencyKey;
h['Content-Type'] = 'application/json';
}
return h;
}
async function failure(response: Response): Promise<LearnError> {
let code = 'HTTP_' + response.status;
let message = 'Learn returned HTTP ' + response.status + '.';
let requestId = response.headers.get('x-request-id') ?? '';
try {
const body = await response.json() as { code?: string; message?: string; request_id?: string };
if (body.code) code = body.code;
if (body.message) message = body.message;
if (body.request_id) requestId = body.request_id;
} catch { /* keep the HTTP status */ }
return new LearnError(response.status, code, message, requestId);
}
// Prepare a session. No reply is generated and nothing is charged.
export async function createSession(learnerId: string, setup: Record<string, unknown>): Promise<string> {
const { base } = settings();
const response = await fetch(base + '/quest/sessions', {
method: 'POST',
headers: headers(learnerId, randomUUID()),
body: JSON.stringify({ setup }),
});
if (!response.ok) throw await failure(response);
const session = await response.json() as { session_id?: string };
if (!session.session_id) throw new LearnError(502, 'NO_SESSION', 'Learn did not return a session id.');
return session.session_id;
}
export interface TurnInput {
sessionId: string;
prompt: string;
// Send the posture on every turn: leaving it out means Guided, except in a Diagnostic
// session, where null leaves it out so the session stays Diagnostic.
posture?: Posture | null;
// 'opening' asks Learn to greet the learner, with an empty prompt. It is a turn like any other.
operation?: 'turn' | 'opening';
// Up to four uploaded files (photos of the learner's work) for this turn.
attachmentIds?: string[];
}
// Upload one file of the learner's work. Free: no reply is generated. The returned id is
// private to this learner and session, and goes with a turn in quest.attachment_ids.
export async function uploadAttachment(learnerId: string, sessionId: string, mediaType: string, base64: string, filename: string): Promise<string> {
const { base } = settings();
const response = await fetch(base + '/quest/attachments', {
method: 'POST',
headers: headers(learnerId, randomUUID()),
body: JSON.stringify({ session_id: sessionId, media_type: mediaType, data: base64, filename }),
});
if (!response.ok) throw await failure(response);
const upload = await response.json() as { attachment_id?: string };
if (!upload.attachment_id) throw new LearnError(502, 'NO_ATTACHMENT', 'Learn did not return an attachment id.');
return upload.attachment_id;
}
// Send one learner turn and pass on the reply when it arrives. onText receives each part of the
// reply: the "conversation" part (what the tutor says) and the
// "display" part (the hint or working to show, in Markdown). The result is returned
// only after Learn's final "done" event confirms the turn, with its safety status
// and receipt.
export async function sendTurn(
learnerId: string,
input: TurnInput,
onText: (part: 'conversation' | 'display', text: string) => void,
): Promise<TurnResult> {
const { base } = settings();
const body = {
session_id: input.sessionId,
prompt: input.operation === 'opening' ? '' : input.prompt,
...(input.posture === null ? {} : { posture: input.posture ?? 'guided' }),
quest: {
operation: input.operation ?? 'turn', requested_support: 'auto', team_dialog: false,
...(input.attachmentIds?.length ? { attachment_ids: input.attachmentIds } : {}),
},
};
const response = await fetch(base + '/chat', {
method: 'POST',
headers: headers(learnerId, randomUUID()),
body: JSON.stringify(body),
});
return readTurn(response, input.sessionId, onText, false);
}
// End a session when the learner finishes. Learn writes and saves the session's summary
// and what it learned about the learner; the closeout is a turn like any other.
export async function endSession(
learnerId: string,
sessionId: string,
onText: (part: 'conversation' | 'display', text: string) => void,
): Promise<TurnResult> {
const { base } = settings();
const operation = randomUUID(); // the same value is the operation id and the Idempotency-Key
const response = await fetch(base + '/sessions/' + encodeURIComponent(sessionId) + '/end', {
method: 'POST',
headers: headers(learnerId, operation),
body: JSON.stringify({ operation_id: operation }),
});
return readTurn(response, sessionId, onText, true);
}
// Free saved reads: a session's summary and state, and the learner's profile.
export async function getSaved(learnerId: string, path: string): Promise<Record<string, any>> {
const { base } = settings();
const response = await fetch(base + path, { headers: headers(learnerId) });
if (!response.ok) throw await failure(response);
return await response.json() as Record<string, any>;
}
async function readTurn(
response: Response,
expectedSession: string,
onText: (part: 'conversation' | 'display', text: string) => void,
requireEnd: boolean,
): Promise<TurnResult> {
if (!response.ok || !response.body) throw await failure(response);
const input = { sessionId: expectedSession };
let ended = false;
let requestId = '';
let sessionId = '';
let reply = '';
let display = '';
let safety: SafetyStatus | undefined;
let questReceipt: Record<string, unknown> | undefined;
let commercial: Record<string, any> | undefined;
const handle = (event: Record<string, any>) => {
switch (event.type) {
case 'metadata':
requestId = event.request_id;
sessionId = event.sessionId;
break;
case 'content':
if (event.part === 'conversation') {
reply += event.text;
onText('conversation', event.text);
} else if (event.part === 'display') {
display += event.text;
onText('display', event.text);
}
break;
case 'safety_status':
safety = event as SafetyStatus;
break;
case 'quest_receipt':
questReceipt = event.receipt;
break;
case 'done':
commercial = event.commercial;
break;
case 'session_ended':
ended = event.sessionId === sessionId;
break;
case 'error':
throw new LearnError(502, event.code ?? 'STREAM_ERROR', event.message ?? 'The turn did not complete.', event.request_id ?? requestId);
default:
break; // Unknown future events are ignored, never treated as success.
}
};
const decoder = new TextDecoder();
const reader = response.body.getReader();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }).replaceAll('\r\n', '\n');
let end: number;
while ((end = buffer.indexOf('\n\n')) >= 0) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const data = frame.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');
if (data) handle(JSON.parse(data));
}
}
// A reply is committed only when the final event arrived with the same identity.
if (!commercial || commercial.request_id !== requestId || !safety || !questReceipt) {
throw new LearnError(502, 'INCOMPLETE', 'The turn was not confirmed. Look it up with GET /v1/requests/' + requestId + ', as the same learner (X-User-Id), before sending again.', requestId);
}
if (sessionId !== input.sessionId) throw new LearnError(502, 'SESSION_MISMATCH', 'The reply belongs to a different session.', requestId);
if (requireEnd && !ended) throw new LearnError(502, 'NOT_ENDED', 'The closeout was not confirmed. Look it up with GET /v1/requests/' + requestId + ', as the same learner (X-User-Id).', requestId);
return {
request_id: requestId,
session_id: sessionId,
reply,
display,
safety,
receipt: {
request_id: requestId,
session_id: sessionId,
posture: String(questReceipt.posture),
turn_index: Number(questReceipt.turn_index),
billable_units: Number(commercial.billable_units),
charge_micro_usd: Number(commercial.charge?.amount_micro_usd ?? 0),
settlement: String(commercial.settlement),
safety_level: safety.level,
},
};
}
File: server.ts
// Remember the learner: the learner finishes a session, Learn saves its summary and what it
// learned about them, and next time the app shows "last time" and the tutor picks up.
// Builds on steps 2 and 3. Node 24+, no packages. Start it with: npm start
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFile, writeFile, appendFile, mkdir } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { join, dirname } from 'node:path';
import { createSession, sendTurn, endSession, getSaved, uploadAttachment, isConfigured, LearnError } from './learn.ts';
const PORT = Number(process.env.PORT ?? 3000);
const PUBLIC = join(import.meta.dirname, 'public');
const RECEIPTS = join(import.meta.dirname, 'receipts.jsonl');
// Each learner's record, kept on disk so the tutor can pick up next time: the open session
// and the sessions that ended. A real app keeps this in its database.
interface LearnerRecord { current?: { id: string; diagnostic: boolean }; past: { id: string; ended_at: string }[] }
const STORE = join(import.meta.dirname, 'data', 'learners.json');
let records: Record<string, LearnerRecord> = {};
try { records = JSON.parse(await readFile(STORE, 'utf8')); } catch { /* first run */ }
async function saveRecords() {
await mkdir(dirname(STORE), { recursive: true });
await writeFile(STORE, JSON.stringify(records, null, 2));
}
const sessions = {
get: (learner: string) => records[learner]?.current,
set: (learner: string, session: { id: string; diagnostic: boolean }) => {
(records[learner] ??= { past: [] }).current = session;
void saveRecords();
},
};
// The task for teaching sessions (Guided, Feedback, Explain): practice, so all three fit.
const SETUP = { task: { kind: 'practice', subject: 'Algebra' }, team_dialog: false };
// A Diagnostic session: the posture and the learner's finished work are set when it is prepared.
function diagnosticSetup(finishedWork: string) {
return {
task: { kind: 'practice', subject: 'Algebra', assignment: 'A finished practice quiz.' },
posture: 'diagnostic',
// The finished work can only be given here, when the session is prepared.
assessment: {
schema_version: 'fl.quest.assessment-input.v1',
goal: 'Find what the learner understands from their finished practice quiz.',
sources: [{ id: 'quiz', origin: 'submitted_work', text: finishedWork, attachment_id: null, locator: 'finished quiz', availability: 'available' }],
items: [], targets: [], original_result: '', limitations: [],
},
team_dialog: false,
};
}
const FILES: Record<string, string> = {
'/': 'index.html',
'/app.js': 'app.js',
'/style.css': 'style.css',
};
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', js: 'text/javascript; charset=utf-8', css: 'text/css; charset=utf-8' };
// A pseudonymous learner id kept in a cookie: never a name or an email.
function learnerId(request: IncomingMessage, response: ServerResponse): string {
const match = /(?:^|;\s*)learner=([A-Za-z0-9_-]{1,128})/.exec(request.headers.cookie ?? '');
if (match) return match[1];
const id = 'learner-' + randomUUID();
response.setHeader('Set-Cookie', 'learner=' + id + '; Path=/; HttpOnly; SameSite=Strict; Max-Age=31536000');
return id;
}
async function readJson(request: IncomingMessage, limit = 20000): Promise<Record<string, unknown>> {
let raw = '';
for await (const chunk of request) {
raw += chunk;
if (raw.length > limit) throw new Error('Message too long');
}
return JSON.parse(raw || '{}');
}
// What the learner sees when a request fails: your app's own short words. Learn's own message is
// for you, in the server log with the request id; never show it to the learner.
function forLearner(e: LearnError): string {
if (e.code === 'DEVELOPER_POLICY_BLOCKED') return "I can't help with that message. Try asking another way.";
if (e.status === 429) return 'The tutor is busy right now. Try again in a moment.';
return "That didn't go through. Try again in a moment.";
}
function send(response: ServerResponse, event: string, data: unknown) {
response.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
}
// The learner's teaching session (Guided, Feedback, Explain), prepared the first time.
async function teachingSession(learner: string) {
let session = sessions.get(learner);
if (!session || session.diagnostic) {
session = { id: await createSession(learner, SETUP), diagnostic: false };
sessions.set(learner, session);
}
return session;
}
const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];
// A photo of the learner's work: uploaded to Learn before the turn that uses it. Free.
async function upload(request: IncomingMessage, response: ServerResponse) {
const learner = learnerId(request, response);
const { media_type, data, filename } = await readJson(request, 12_000_000);
if (typeof media_type !== 'string' || !IMAGE_TYPES.includes(media_type) || typeof data !== 'string' || !data || data.length > 11_184_812) {
response.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Attach a PNG, JPEG or WebP photo up to 8 MiB.' }));
return;
}
try {
const session = await teachingSession(learner);
const id = await uploadAttachment(learner, session.id, media_type, data, typeof filename === 'string' ? filename.slice(0, 120) : 'work');
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ attachment_id: id }));
} catch (error) {
const e = error instanceof LearnError ? error : new LearnError(500, 'SERVER_ERROR', (error as Error).message);
console.error('Upload failed:', e.status, e.code, e.message, e.requestId ? 'request ' + e.requestId : '');
response.writeHead(e.status >= 400 && e.status < 600 ? e.status : 502, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: forLearner(e), code: e.code }));
}
}
// Last time: the summary Learn saved when the learner's last session ended, and what Learn
// has observed about them. Free saved reads; empty evidence stays empty.
async function me(request: IncomingMessage, response: ServerResponse) {
const learner = learnerId(request, response);
const record = records[learner];
const last = record?.past.at(-1);
let summary: string | null = null, remembered: string[] = [];
try {
if (last) {
summary = (await getSaved(learner, '/quest/sessions/' + last.id + '/summary')).text ?? null;
const profile = await getSaved(learner, '/quest/learners/' + learner + '/profile');
// The profile can list a concept once for each request that observed it: group by name.
remembered = [...new Set((profile.observed_signals ?? []).map((s: { concept: string }) => s.concept).filter(Boolean))].slice(0, 6);
}
} catch (error) {
console.error('Saved read failed:', (error as LearnError).code ?? error);
}
response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
.end(JSON.stringify({ last: last ? { ended_at: last.ended_at, summary } : null, remembered, open: Boolean(record?.current) }));
}
// Finish for today: end the open session. Learn writes and saves its summary (a turn).
async function finish(request: IncomingMessage, response: ServerResponse) {
const learner = learnerId(request, response);
const session = records[learner]?.current;
if (!session) {
response.writeHead(409, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'There is no open session to finish.' }));
return;
}
response.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store' });
try {
const result = await endSession(learner, session.id, (part, text) => send(response, 'text', { part, text }));
records[learner].past.push({ id: session.id, ended_at: new Date().toISOString() });
delete records[learner].current;
await saveRecords();
await appendFile(RECEIPTS, JSON.stringify({ at: new Date().toISOString(), learner_id: learner, operation: 'closeout', ...result.receipt }) + '\n');
send(response, 'done', { safety: result.safety, receipt: result.receipt, ended: true });
} catch (error) {
const e = error instanceof LearnError ? error : new LearnError(500, 'SERVER_ERROR', (error as Error).message);
console.error('Closeout failed:', e.status, e.code, e.message, e.requestId ? 'request ' + e.requestId : '');
send(response, 'failed', { status: e.status, code: e.code, message: forLearner(e), request_id: e.requestId });
}
response.end();
}
const KINDS = ['guided', 'feedback', 'explain', 'diagnostic'] as const;
type Kind = typeof KINDS[number];
async function turn(request: IncomingMessage, response: ServerResponse) {
const learner = learnerId(request, response);
const { message, kind, attachment_ids } = await readJson(request);
const attachmentIds = Array.isArray(attachment_ids) ? attachment_ids.filter((a): a is string => typeof a === 'string').slice(0, 4) : [];
if (typeof message !== 'string' || !message.trim() || !KINDS.includes(kind as Kind)) {
response.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Choose a kind of help and type a message first.' }));
return;
}
response.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store' });
try {
// Guided, Feedback and Explain share one session: the posture goes with each turn.
// Diagnostic is chosen when the session is prepared, with the finished work, so it gets a
// session of its own; later Diagnostic messages are the learner's answers, sent with no posture.
// Starting either kind of session closes the learner's other open one (its closeout is a turn).
const diagnostic = kind === 'diagnostic';
let session = sessions.get(learner);
let opening = false;
if (!session || session.diagnostic !== diagnostic) {
// Diagnostic: the learner's finished quiz goes into the session's setup, then the session opens.
const setup = diagnostic ? diagnosticSetup(message.trim()) : SETUP;
session = { id: await createSession(learner, setup), diagnostic };
opening = diagnostic;
sessions.set(learner, session);
}
const posture = diagnostic ? null : kind as 'guided' | 'feedback' | 'explain';
// Photos go with teaching turns; they belong to the session they were uploaded to.
const result = await sendTurn(learner, { sessionId: session.id, prompt: opening ? '' : message.trim(), posture, operation: opening ? 'opening' : 'turn', attachmentIds: diagnostic ? [] : attachmentIds }, (part, text) => send(response, 'text', { part, text }));
// Keep the receipt: one line per confirmed turn.
await appendFile(RECEIPTS, JSON.stringify({ at: new Date().toISOString(), learner_id: learner, ...result.receipt }) + '\n');
send(response, 'done', { safety: result.safety, receipt: result.receipt });
} catch (error) {
const e = error instanceof LearnError ? error : new LearnError(500, 'SERVER_ERROR', (error as Error).message);
console.error('Learn turn failed:', e.status, e.code, e.message, e.requestId ? 'request ' + e.requestId : '');
send(response, 'failed', { status: e.status, code: e.code, message: forLearner(e), request_id: e.requestId });
}
response.end();
}
const server = createServer(async (request, response) => {
response.setHeader('X-Content-Type-Options', 'nosniff');
try {
if (request.method === 'POST' && request.url === '/api/turn') return await turn(request, response);
if (request.method === 'POST' && request.url === '/api/upload') return await upload(request, response);
if (request.method === 'GET' && request.url === '/api/me') return await me(request, response);
if (request.method === 'POST' && request.url === '/api/finish') return await finish(request, response);
const file = request.method === 'GET' ? FILES[(request.url ?? '/').split('?')[0]] : undefined;
if (!file) {
response.writeHead(404).end('Not found');
return;
}
learnerId(request, response);
const body = await readFile(join(PUBLIC, file));
response.writeHead(200, { 'Content-Type': TYPES[file.split('.').pop()!], 'Cache-Control': 'no-store' }).end(body);
} catch (error) {
if (!response.headersSent) response.writeHead(500).end('Server error');
console.error(error);
}
});
if (!isConfigured()) console.warn('FOREVERLEARNING_API_KEY is not set. Copy .env.example to .env and add your key.');
server.listen(PORT, '127.0.0.1', () => console.log('Your tutor is running at http://localhost:' + PORT));
File: public/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Remember the learner</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js" integrity="sha384-7zkQWkzuo3B5mTepMUcHkMB5jZaolc2xDwL6VFqjFALcbeS9Ggm/Yr2r3Dy4lfFg" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" integrity="sha384-43gviWU0YVjaDtb/GhzOouOXtZMP/7XUzwPTstBeZFe/+rCMvRwr4yROQP43s0Xk" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<main class="chat">
<header>
<h1>Your tutor</h1>
<p>Pick up where you left off. Finish for today when you're done, and next time starts from there.</p>
</header>
<section id="last-time" class="last-time" hidden>
<h2>Last time</h2>
<div id="last-summary"></div>
<ul id="remembered"></ul>
</section>
<ol id="messages" aria-live="polite"></ol>
<form id="composer">
<fieldset class="kinds">
<legend class="visually-hidden">Kind of help</legend>
<label><input type="radio" name="kind" value="guided" checked> <span><strong>Guided</strong> I'm working on it</span></label>
<label><input type="radio" name="kind" value="feedback"> <span><strong>Feedback</strong> Check my work</span></label>
<label><input type="radio" name="kind" value="explain"> <span><strong>Explain</strong> A worked example I don't follow</span></label>
<label><input type="radio" name="kind" value="diagnostic"> <span><strong>Diagnostic</strong> I finished a quiz</span></label>
</fieldset>
<div class="attach">
<label class="attach-button">Attach a photo of your work <input id="photos" type="file" accept="image/png,image/jpeg,image/webp" multiple></label>
<ul id="thumbs"></ul>
</div>
<label for="message" class="visually-hidden">Your message</label>
<textarea id="message" name="message" rows="2" placeholder="Type your question" required></textarea>
<div class="actions">
<button type="submit">Send</button>
<button type="button" id="finish" class="secondary">Finish for today</button>
</div>
</form>
</main>
<script src="/app.js" type="module"></script>
</body>
</html>
File: public/app.js
// The chat page. It talks only to your own server (/api/turn, /api/upload, /api/finish and /api/me), never to Learn directly.
const messages = document.querySelector('#messages');
const form = document.querySelector('#composer');
const input = document.querySelector('#message');
const button = form.querySelector('button[type="submit"], button:not([type])');
const photos = document.querySelector('#photos');
const thumbs = document.querySelector('#thumbs');
let attached = []; // { id, url } for each uploaded photo, up to four
// Upload each chosen photo to your server, which uploads it to Learn. Free: no reply is made.
photos.addEventListener('change', async () => {
for (const file of [...photos.files].slice(0, 4 - attached.length)) {
const item = document.createElement('li');
const img = document.createElement('img');
img.src = URL.createObjectURL(file);
img.alt = 'Your photo: ' + file.name;
item.append(img);
thumbs.append(item);
item.classList.add('uploading');
const data = await new Promise((resolve) => { const r = new FileReader(); r.onload = () => resolve(String(r.result).split(',')[1]); r.readAsDataURL(file); });
const response = await fetch('/api/upload', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ media_type: file.type, data, filename: file.name }) });
const body = await response.json();
item.classList.remove('uploading');
if (response.ok) attached.push({ id: body.attachment_id, url: img.src });
else { item.classList.add('failed'); item.title = body.error; }
}
photos.value = '';
});
// A small, safe Markdown renderer for the reply's display part:
// paragraphs, lists, `code`, **bold** and *italic*. Everything is escaped first.
function escape(text) {
return text.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
}
function inline(text) {
return escape(text)
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>');
}
function markdown(text) {
// Keep each display-math block (\[ ... \], often over several lines) together in one
// paragraph, so the math library finds both delimiters.
const blocks = [];
text = text.replace(/\\\[[\s\S]*?\\\]/g, (block) => '\u0000' + (blocks.push(block) - 1) + '\u0000');
const html = [];
let list = null;
for (const line of text.split('\n')) {
const heading = /^\s*#{1,6}\s+(.*)$/.exec(line);
if (heading) {
if (list) { html.push('</' + list + '>'); list = null; }
html.push('<p class="heading"><strong>' + inline(heading[1]) + '</strong></p>');
continue;
}
const item = /^\s*(?:[-*]|(\d+)[.)])\s+(.*)$/.exec(line);
if (item) {
const kind = item[1] ? 'ol' : 'ul';
if (list !== kind) { if (list) html.push('</' + list + '>'); html.push('<' + kind + '>'); list = kind; }
html.push('<li>' + inline(item[2]) + '</li>');
continue;
}
if (list) { html.push('</' + list + '>'); list = null; }
if (line.trim()) html.push('<p>' + inline(line) + '</p>');
}
if (list) html.push('</' + list + '>');
return html.join('').replace(/\u0000(\d+)\u0000/g, (_, i) => escape(blocks[Number(i)]));
}
// Math in a reply (\( \) inline, \[ \] on its own line), rendered by KaTeX's auto-render,
// loaded in index.html. Without it the learner would see the raw notation.
function typeset(element) {
window.renderMathInElement?.(element, {
delimiters: [{ left: '\\(', right: '\\)', display: false }, { left: '\\[', right: '\\]', display: true }],
throwOnError: false,
});
}
function add(role, text) {
const item = document.createElement('li');
item.className = 'message ' + role;
const bubble = document.createElement('div');
bubble.className = 'bubble';
if (text) bubble.textContent = text;
item.append(bubble);
messages.append(item);
item.scrollIntoView({ block: 'end' });
return item;
}
function chip(label, value, kind) {
const span = document.createElement('span');
span.className = 'chip ' + (kind ?? '');
span.textContent = label + ': ' + value;
return span;
}
function dollars(micro) {
return '$' + (micro / 1e6).toFixed(2);
}
// Read the server's events: the reply's "text" parts, then "done" or "failed".
async function* events(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) return;
buffer += decoder.decode(value, { stream: true });
let end;
while ((end = buffer.indexOf('\n\n')) >= 0) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = /^event: (.*)$/m.exec(frame)?.[1];
const data = /^data: (.*)$/m.exec(frame)?.[1];
if (event && data) yield { event, data: JSON.parse(data) };
}
}
}
form.addEventListener('submit', async (submit) => {
submit.preventDefault();
const text = input.value.trim();
if (!text) return;
// The kind of help goes with every message. Diagnostic starts a session of its own.
const kind = form.querySelector('input[name="kind"]:checked').value;
const learnerItem = add('learner', text);
learnerItem.querySelector('.bubble').dataset.kind = kind;
// The photos go with this message, then the tray clears.
const sent = attached;
attached = [];
thumbs.replaceChildren();
for (const p of sent) { const img = document.createElement('img'); img.src = p.url; img.alt = 'Your photo'; img.className = 'sent-photo'; learnerItem.append(img); }
input.value = '';
button.disabled = true;
const item = add('tutor', '');
const bubble = item.querySelector('.bubble');
const said = document.createElement('p');
const board = document.createElement('div');
board.className = 'board';
bubble.append(said, board);
bubble.classList.add('waiting');
let conversation = '';
let display = '';
try {
const response = await fetch('/api/turn', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text, kind, attachment_ids: sent.map((p) => p.id) }),
});
for await (const { event, data } of events(response)) {
if (event === 'text' && data.part === 'conversation') {
conversation += data.text;
said.innerHTML = inline(conversation);
typeset(said);
} else if (event === 'text' && data.part === 'display') {
display += data.text;
board.innerHTML = markdown(display);
typeset(board);
} else if (event === 'done') {
const meta = document.createElement('div');
meta.className = 'meta';
meta.append(
chip('Kind', data.receipt.posture),
chip('Safety', data.safety.level, 'safety-' + data.safety.level),
chip('Receipt', data.receipt.billable_units + ' turn · ' + dollars(data.receipt.charge_micro_usd) + ' · ' + data.receipt.settlement),
chip('Request', data.receipt.request_id.slice(0, 12) + '…'),
);
item.append(meta);
} else if (event === 'failed') {
// Your app's own words (from the server); Learn's error text stays in the server log.
said.textContent = data.message;
item.classList.add('error');
}
item.scrollIntoView({ block: 'end' });
}
} catch {
said.textContent = 'The connection dropped. Try again.';
item.classList.add('error');
} finally {
bubble.classList.remove('waiting');
button.disabled = false;
input.focus();
}
});
input.addEventListener('keydown', (key) => {
if (key.key === 'Enter' && !key.shiftKey) {
key.preventDefault();
form.requestSubmit();
}
});
// Last time: what Learn saved when the learner's last session ended.
async function lastTime() {
const me = await (await fetch('/api/me')).json();
const card = document.querySelector('#last-time');
card.hidden = !me.last;
if (!me.last) return;
// The summary is Learn's text too: render its Markdown and math like a reply.
const summary = document.querySelector('#last-summary');
if (me.last.summary) { summary.innerHTML = markdown(me.last.summary); typeset(summary); }
else summary.textContent = 'Your last session ended; its summary is not available yet.';
const list = document.querySelector('#remembered');
list.replaceChildren(...me.remembered.map((concept) => { const li = document.createElement('li'); li.textContent = concept; return li; }));
}
// Finish for today: Learn ends the session and saves its summary. The closeout is a turn.
document.querySelector('#finish').addEventListener('click', async () => {
const finish = document.querySelector('#finish');
finish.disabled = true;
button.disabled = true;
const item = add('tutor', '');
const bubble = item.querySelector('.bubble');
bubble.classList.add('waiting');
let conversation = '', display = '';
try {
const response = await fetch('/api/finish', { method: 'POST' });
if (!response.ok) throw new Error((await response.json().catch(() => ({}))).error ?? 'HTTP ' + response.status);
for await (const { event, data } of events(response)) {
if (event === 'text' && data.part === 'conversation') conversation += data.text;
else if (event === 'text' && data.part === 'display') display += data.text;
else if (event === 'done') {
const meta = document.createElement('div');
meta.className = 'meta';
meta.append(chip('Session', 'finished'), chip('Safety', data.safety.level, 'safety-' + data.safety.level),
chip('Receipt', data.receipt.billable_units + ' turn · ' + dollars(data.receipt.charge_micro_usd) + ' · ' + data.receipt.settlement),
chip('Request', data.receipt.request_id.slice(0, 12) + '…'));
item.append(meta);
} else if (event === 'failed') conversation = 'Finishing did not go through (' + data.code + ').';
bubble.innerHTML = '<p>' + inline(conversation) + '</p>' + (display ? '<div class="board">' + markdown(display) + '</div>' : '');
typeset(bubble);
}
await lastTime();
} catch (error) {
bubble.textContent = error.message;
} finally {
bubble.classList.remove('waiting');
finish.disabled = false;
button.disabled = false;
}
});
lastTime();
File: public/style.css
:root {
--bg: #f6f5f1;
--panel: #ffffff;
--ink: #1d1d1f;
--muted: #5d5d66;
--accent: #1f5f8b;
--learner: #e6eef5;
--line: #dedbd2;
--clear: #2f7d4f;
--watch: #9a6b00;
--warning: #b3471d;
--critical: #a1122b;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
color: var(--ink);
background: var(--bg);
}
* { box-sizing: border-box; }
body { margin: 0; }
.chat { max-width: 720px; margin: 0 auto; min-height: 100vh; display: flex; flex-direction: column; padding: 24px 16px; }
header h1 { margin: 0 0 4px; font-size: 1.5rem; }
header p { margin: 0 0 16px; color: var(--muted); }
#messages { list-style: none; margin: 0; padding: 0; flex: 1; display: flex; flex-direction: column; gap: 12px; }
.message { display: flex; flex-direction: column; max-width: 85%; }
.message.learner { align-self: flex-end; }
.bubble { margin: 0; padding: 10px 14px; border-radius: 14px; line-height: 1.45; background: var(--panel); border: 1px solid var(--line); }
.bubble p { margin: 0 0 6px; white-space: pre-wrap; }
.bubble p:last-child { margin-bottom: 0; }
.board { border-left: 3px solid var(--accent); padding-left: 10px; margin-top: 4px; }
.board:empty { display: none; }
.board ul, .board ol { margin: 4px 0; padding-left: 20px; }
code { font-family: ui-monospace, Consolas, monospace; background: #f0efe9; padding: 0 4px; border-radius: 4px; }
.learner .bubble { background: var(--learner); border-color: transparent; }
.bubble.waiting::after { content: "Thinking…"; color: var(--muted); font-size: 0.9rem; }
.error .bubble { border-color: var(--warning); }
.meta { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
.chip { font-size: 0.78rem; padding: 2px 8px; border-radius: 999px; background: #ecebe6; color: var(--muted); }
.chip.safety-clear { background: #e3f1e8; color: var(--clear); }
.chip.safety-watch { background: #f6edd6; color: var(--watch); }
.chip.safety-warning { background: #f8e3da; color: var(--warning); }
.chip.safety-critical, .chip.safety-unknown { background: #f7dde2; color: var(--critical); }
#composer { display: flex; gap: 8px; margin-top: 16px; }
#composer textarea { flex: 1; font: inherit; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; resize: vertical; }
#composer button { font: inherit; padding: 0 18px; border: 0; border-radius: 10px; background: var(--accent); color: #fff; cursor: pointer; }
#composer button:disabled { opacity: 0.5; cursor: default; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
.kinds { display: flex; flex-wrap: wrap; gap: 6px; border: 0; padding: 0; margin: 0 0 8px; width: 100%; }
.kinds label { flex: 1 1 150px; display: flex; gap: 6px; align-items: flex-start; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); cursor: pointer; font-size: 0.88rem; }
.kinds label:has(input:checked) { border-color: var(--accent); background: #eaf1f7; }
.kinds strong { display: block; }
#composer { flex-wrap: wrap; }
.bubble[data-kind]::before { content: attr(data-kind); display: block; font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); }
.attach { width: 100%; display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.attach-button { font-size: 0.88rem; color: var(--accent); border: 1px dashed var(--accent); border-radius: 10px; padding: 6px 10px; cursor: pointer; }
.attach-button input { position: absolute; width: 1px; height: 1px; opacity: 0; }
#thumbs { list-style: none; display: flex; gap: 6px; margin: 0; padding: 0; }
#thumbs img { width: 56px; height: 44px; object-fit: cover; border-radius: 6px; border: 1px solid var(--line); }
#thumbs .uploading img { opacity: 0.4; }
#thumbs .failed img { outline: 2px solid var(--warning); }
.sent-photo { max-width: 220px; border-radius: 8px; border: 1px solid var(--line); margin-top: 4px; align-self: flex-end; }
.last-time { background: var(--panel); border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: 12px; padding: 12px 16px; margin-bottom: 14px; }
.last-time h2 { margin: 0 0 6px; font-size: 1rem; }
.last-time p { margin: 0 0 6px; }
.last-time ul { margin: 0; padding-left: 18px; color: var(--muted); font-size: 0.9rem; }
.actions { display: flex; flex-direction: column; gap: 6px; }
.actions button { font: inherit; padding: 8px 16px; border: 0; border-radius: 10px; background: var(--accent); color: #fff; cursor: pointer; }
.actions button.secondary { background: #fff; color: var(--accent); border: 1px solid var(--accent); }
.actions button:disabled { opacity: 0.5; }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }
Run npm start and open http://localhost:3000.
A real saved summary, captured November 23, 2026, word for word:
Next starting point: apply the outside factor to both terms inside the brackets.
The reply arrives complete and checked. Nothing unchecked is ever shown. Every reply is written fresh, so yours will use different words.
receipts.jsonl has a line for each turn, the closeout included. data/learners.json holds your app's own record: each learner's open session and the sessions that ended.
The saved summary, state and profile are observations from the sessions, not grades or diagnoses. Empty evidence stays empty.
The reply arrives complete and checked, about 10 to 20 seconds after the request, with nothing sent before it. Set your client and proxy timeouts to allow for that. Nothing unchecked is ever shown.
Learn's replies use Markdown (headings, lists, bold, code) and can contain math, usually written between \( and \) inline and between \[ and \] for display math, which often spans several lines. The guide asks you to render each part "using safe text, Markdown, math and code rendering" (Send a turn and validate its result): render the Markdown, and the math with a math library such as KaTeX, so the learner never sees raw notation. The sample pages load KaTeX from a public CDN and call its auto-render on each reply. A product can serve the same files itself from the npm package, so the learner's browser does not fetch them from a third party.
| What you see | What it means | Fix |
|---|---|---|
The summary is unavailable | The session has not been ended, or its closeout did not complete. | End it with /end, and count it finished only after session_ended. |
429 DEVELOPER_NEW_USER_LIMIT: "Daily limit for new end users reached. End users already admitted are not affected; new end users can start after 00:00 UTC" | Your key or workspace has admitted its daily number of new learners. | Learners already admitted keep working. New ones can start after the Retry-After time (also in retry_after_seconds). When testing, keep the same learner id between test messages. |
402 DEVELOPER_BALANCE_EXHAUSTED when preparing a session | Your workspace has less than ten turns' worth left (50¢). | Add funds to your workspace, then prepare the session again. |
403 DEVELOPER_POLICY_BLOCKED | The safety screening refused the learner's message before it reached the tutor. | Show your own short message, such as "I can't help with that message. Try asking another way.", and let the learner continue. Never show the refusal's own text; log it with the request id for yourself. |
429, for example DEVELOPER_CAPACITY_LIMIT | Your workspace reached its allowance or rate limit, and the turn was refused. | Respect the Retry-After header if it is there. A refused turn is a confirmed failure, so you may send a new request for it, with a new Idempotency-Key (Recover the original operation). |
A turn that stops before done (a dropped connection, or an answer still in progress) is not confirmed. Send the same body again with the same Idempotency-Key, or look it up with GET /v1/requests/<request_id>, using the same key, assignment and learner X-User-Id as the original. A turn that committed replays its saved reply at no new charge. 409 REQUEST_IN_PROGRESS means it is still running: check again shortly. 409 REQUEST_FAILED means it failed and was not charged: send it again with a new Idempotency-Key (Recover the original operation). A request refused outright (a 400, 403 or 429 before it was admitted) leaves nothing to look up, and the look-up answers 401: fix the cause and send it again with a new Idempotency-Key.
A start folder and the finish.
Open the kit04-remember-the-learner in learn-tutor-starter
One click to start.
DownloadThe same steps, by hand.
04-remember-the-learnerYour first tutor in ten minutes.
Start building