The Learn APIBy ForeverLearning

Build with Learn · Recipe

A tutor for my class

About 10 minutes with a coding assistant.

Before you start

  • An account and a key. Sign in to the developer console, add Learn to your workspace, and create a server key in My APIs.
  • Node 24 or later. The code uses no packages.
  • Your environment. Put your key in FOREVERLEARNING_API_KEY and your API host in FOREVERLEARNING_BASE_URL (production: https://developers-api.foreverlearning.ai/v1; to test on staging: https://developers-api-staging.foreverlearning.ai/v1). Choose your own CLASS_CODE for your students, a different TEACHER_CODE for yourself, and a long random LEARNER_ID_SECRET. There are no defaults: the server will not start until all three are set, because a known code would let anyone join your class or read every student's work on your instructor page.
  • Your students. This recipe is for adult learners in a class you run yourself. A class at a school, college or university, or any class of children, is set up under an agreement first.
  • Start from an empty folder. The finished app is class in learn-tutor-starter.

Each turn that succeeds costs 5¢, and the tutor's opening is a turn. A turn that fails costs nothing. Preparing a session is free.

Option A: hand it to your coding assistant

Open an empty folder in your coding assistant, with your key and host in the environment it runs commands in, and paste the prompt. Change the tutor's name, course and assignment to your own. The assistant needs to read web pages and run commands. Before we publish a prompt, we run it three times in each of two coding assistants, from an empty folder, against the release you use. Coding assistants are your tools; they are not part of the Learn API.

Paste this
Goal: a tutor for my class. Students sign in with the class code and chat with a tutor that carries the name I chose for it and knows my course and assignment. They get hints while they work and feedback when they submit work, and I can see what each student worked on.

Read first: https://developers.foreverlearning.ai/docs/learn/ (the Learn integration guide), and the Learn OpenAPI contract, the Learn JSON schema and the runnable TypeScript example linked there. Use only what they describe.

Start from: an empty folder.

Build, in TypeScript on Node 24 or later:
1. A settings file, class.json, with the tutor's name ("Maple"), a welcome line, two colors, the course ("Algebra 1 (adult education)") and the assignment ("Solve linear equations in one variable. Show each step."). The pages use the name, the welcome and the colors.
2. A sign-in page: the class code (from CLASS_CODE) and the student's own short sign-in, not their full name. The server turns the sign-in into a pseudonymous learner id with a keyed hash (the secret in LEARNER_ID_SECRET).
3. One Learn session per student, prepared with the tutor's name as the setup's display_name, and a homework task whose subject is the course and whose assignment is the assignment, for an adult learner (grade_band "adult"). When a student's session is new, ask Learn for its generated opening and show it.
4. A chat with two buttons: "Ask" sends the message as a Guided turn; "Submit my work" sends it as a Feedback turn. Show both parts of each reply (the conversation part and the display part, in Markdown), under the tutor's name, then the safety status and the receipt (the request id, the turns billed and the charge).
5. Keep each student's conversation on the server (a JSON file is fine). When a student signs in again, from any browser, show it and carry on in the same session.
6. An instructor page at /teacher, behind TEACHER_CODE, listing each student's sign-in, what they asked and submitted, and the safety level of the replies they got, so I can follow up with a student who may need support.
7. Treat a turn as done only when Learn's final done event confirms it. Then append its receipt (request id, session id, learner id, posture, safety level, billable units, charge) as one JSON line to receipts.jsonl.
8. A package.json whose `npm start` serves it at http://localhost:$PORT (default 3000), and a README that says how to set it up for a class.

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; it can be empty when your key has one assignment. 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.
- Send Learn only the pseudonymous learner id: never a student's name, sign-in or email.
- The replies are the tutor's teaching. Show them under the tutor's name, never as the instructor's own words.
- No default codes: never ship a default class code, instructor code or learner-id secret. If CLASS_CODE, TEACHER_CODE or LEARNER_ID_SECRET is not set, or the instructor code is the same as the class code, the server refuses to start and says which to set. The instructor page sends its code in a request header or a POST body, never in the address (no code in a URL), so it stays out of logs and browser history.
- Make sure the pages work in an ordinary browser, not only from command-line requests: a browser's form posts and fetch calls carry its own headers.
- Stop only the processes you started; never stop processes by name.
- Each message is a real turn, at 5¢ per turn that succeeds, and the opening is a turn too. Test with three or four turns, no more. Test as one student, signing in once and keeping the same cookie: a test key admits only a limited number of new learners a day.

Done when:
- a student signs in with the class code, sees the tutor's name and its opening, asks for the answer and gets a hint
- "Submit my work" sends a Feedback turn and the feedback shows
- /teacher, given the instructor code, lists the student, what they asked and submitted, and the safety levels
- the server refuses to start while CLASS_CODE, TEACHER_CODE or LEARNER_ID_SECRET is unset
- signing in again in a new browser shows the conversation and carries on
- receipts.jsonl has one line for each confirmed turn

Paste into your coding assistant.

Option B: by hand

The guide sections this recipe uses: Prepare without generating, Choose a posture for each request and Send a turn and validate its result. The tutor's name: Name the tutor.

What your app does, and what Learn does:

Your appLearn
The tutor's name, look, welcome, course and assignmentThe teaching, in the tutor's name
The class sign-in, and the learner id (a keyed hash of each student's sign-in)One session per student, saved
Which kind of help on each turn: guided for a question, feedback for submitted workHints that leave the step to the student; feedback that checks the work, never a grade
Each student's conversation, and your instructor pageThe safety status and the receipt on every turn

Three calls do the work:

  1. POST /v1/quest/sessions prepares each student's session, once, with display_name (your tutor's name) and the task: {"kind": "homework", "subject": "<your course>", "assignment": "<your assignment>"}, for an adult learner ("grade_band": "adult"). It is free.
  2. POST /v1/chat with "quest": {"operation": "opening"} and an empty prompt asks for the tutor's opening, in its own name.
  3. POST /v1/chat for each message, with "posture": "guided" for Ask and "posture": "feedback" for Submit my work. Leaving posture out means Guided every time, so send it on every turn.

Create these files in an empty folder, then run npm start and open http://localhost:3000.

File: package.json

{
  "name": "learn-class-tutor",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "description": "Build with Learn recipe: a tutor for my class.",
  "engines": { "node": ">=24" },
  "scripts": {
    "start": "node --env-file-if-exists=.env server.ts"
  }
}

File: .env.example

# Copy this file to .env and fill in your own values. Never commit .env.
# Your Learn server key, from My APIs in your developer workspace. It stays on your server.
FOREVERLEARNING_API_KEY=
# The API host, ending in /v1.
FOREVERLEARNING_BASE_URL=https://developers-api.foreverlearning.ai/v1
# To test on staging instead:
# FOREVERLEARNING_BASE_URL=https://developers-api-staging.foreverlearning.ai/v1
# Optional: your Learn assignment id, from My APIs. Leave empty if your key has one assignment.
FOREVERLEARNING_ASSIGNMENT_ID=
# Choose your own: the code you give your class, and a different code for your instructor page.
# The server will not start until both are set.
CLASS_CODE=
TEACHER_CODE=
# A long random string (16 characters or more). Learner ids are a keyed hash of each student's
# sign-in, so Learn never sees it. The server will not start without it.
LEARNER_ID_SECRET=
# The port for your local server.
PORT=3000

File: class.json

{
  "tutor_name": "Maple",
  "welcome": "Bring the problem you're on and what you've tried. Ask when you're stuck; submit your work when you want it checked.",
  "course": "Algebra 1 (adult education)",
  "assignment": "Solve linear equations in one variable. Show each step.",
  "colors": { "accent": "#2d6a4f", "background": "#f3f6f1" }
}

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;
  posture?: Posture;
  // 'opening' asks Learn to greet the learner, with an empty prompt. It is a turn like any other.
  operation?: 'turn' | 'opening';
}

// 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,
    posture: input.posture ?? 'guided',
    quest: { operation: input.operation ?? 'turn', requested_support: 'auto', team_dialog: false },
  };
  const response = await fetch(base + '/chat', {
    method: 'POST',
    headers: headers(learnerId, randomUUID()),
    body: JSON.stringify(body),
  });
  if (!response.ok || !response.body) throw await failure(response);

  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 '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);

  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

// A tutor for my class. Students sign in with the class code; the tutor carries your name
// for it, your course and your assignment. Questions get Guided help; submitted work gets
// Feedback. Your instructor page shows what each student worked on. Node 24+, no packages.
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFile, writeFile, appendFile, mkdir } from 'node:fs/promises';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { join } from 'node:path';
import { createSession, sendTurn, isConfigured, LearnError, type Posture } from './learn.ts';

const PORT = Number(process.env.PORT ?? 3000);
const HERE = import.meta.dirname;
const PUBLIC = join(HERE, 'public');
const DATA = join(HERE, 'data');
const STORE = join(DATA, 'class-store.json');
const RECEIPTS = join(HERE, 'receipts.jsonl');
const CLASS_CODE = (process.env.CLASS_CODE ?? '').trim();
const TEACHER_CODE = (process.env.TEACHER_CODE ?? '').trim();
const SECRET = process.env.LEARNER_ID_SECRET ?? '';
// No default codes, ever. With a missing or example code, anyone could join your class or open
// your instructor page and read every student's work, so the server will not start.
const EXAMPLES = new Set(['demo-class', 'demo-teacher', 'class-code', 'teacher-code', 'change-me', 'change-this-secret']);
const unset: string[] = [];
if (!CLASS_CODE || EXAMPLES.has(CLASS_CODE.toLowerCase())) unset.push('CLASS_CODE (the code your students enter)');
if (!TEACHER_CODE || EXAMPLES.has(TEACHER_CODE.toLowerCase()) || TEACHER_CODE === CLASS_CODE) unset.push('TEACHER_CODE (the code for your instructor page, different from the class code)');
if (SECRET.length < 16 || EXAMPLES.has(SECRET.toLowerCase())) unset.push('LEARNER_ID_SECRET (a long random string, 16 characters or more)');
if (unset.length) {
  console.error('Not starting. Choose your own ' + unset.join('; ') + '. Set ' + (unset.length > 1 ? 'them' : 'it') + ' in .env (see .env.example).');
  process.exit(1);
}

// Your tutor: name, welcome, course, assignment and colors. Edit class.json.
const settings = JSON.parse(await readFile(join(HERE, 'class.json'), 'utf8'));

interface Message { role: 'student' | 'tutor'; kind: 'opening' | 'ask' | 'submit'; text: string; display?: string; safety?: string; request_id?: string; at: string }
interface Student { handle: string; session_id?: string; messages: Message[] }
type Store = { students: Record<string, Student> };

// Your app's own record of each student. Learn sees only the pseudonymous learner id.
let store: Store = { students: {} };
try { store = JSON.parse(await readFile(STORE, 'utf8')); } catch { /* first run */ }
async function save() {
  await mkdir(DATA, { recursive: true });
  await writeFile(STORE, JSON.stringify(store, null, 2));
}

const sign = (value: string) => createHmac('sha256', SECRET).update(value).digest('hex');
// A pseudonymous learner id: a keyed hash of the student's sign-in, never a name or an email.
const learnerIdFor = (handle: string) => 'learner-' + sign('student:' + handle.trim().toLowerCase()).slice(0, 32);

function same(a: string, b: string) {
  const x = Buffer.from(a), y = Buffer.from(b);
  return x.length === y.length && timingSafeEqual(x, y);
}

function signedIn(request: IncomingMessage): string | null {
  const match = /(?:^|;\s*)student=(learner-[0-9a-f]{32})\.([0-9a-f]{64})/.exec(request.headers.cookie ?? '');
  return match && same(match[2], sign(match[1])) && store.students[match[1]] ? match[1] : null;
}

async function readJson(request: IncomingMessage): Promise<Record<string, unknown>> {
  let raw = '';
  for await (const chunk of request) {
    raw += chunk;
    if (raw.length > 20000) throw new Error('Message too long');
  }
  return JSON.parse(raw || '{}');
}

function json(response: ServerResponse, status: number, body: unknown) {
  response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(JSON.stringify(body));
}

function send(response: ServerResponse, event: string, data: unknown) {
  response.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
}

async function signIn(request: IncomingMessage, response: ServerResponse) {
  const { class_code, handle } = await readJson(request);
  if (typeof class_code !== 'string' || !same(class_code.trim(), CLASS_CODE)) return json(response, 403, { error: 'That class code is not right.' });
  if (typeof handle !== 'string' || !/^[A-Za-z0-9 ._-]{2,40}$/.test(handle.trim())) return json(response, 400, { error: 'Use 2 to 40 letters, numbers, spaces, dots, dashes or underscores.' });
  const learner = learnerIdFor(handle);
  store.students[learner] ??= { handle: handle.trim(), messages: [] };
  await save();
  response.setHeader('Set-Cookie', 'student=' + learner + '.' + sign(learner) + '; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000');
  json(response, 200, { ok: true });
}

// One turn: an opening, a question (Guided) or submitted work (Feedback).
async function turn(request: IncomingMessage, response: ServerResponse, learner: string) {
  const { message, kind } = await readJson(request);
  if (kind !== 'opening' && kind !== 'ask' && kind !== 'submit') return json(response, 400, { error: 'Unknown kind.' });
  const text = typeof message === 'string' ? message.trim() : '';
  if (kind !== 'opening' && !text) return json(response, 400, { error: 'Type a message first.' });
  const student = store.students[learner];
  if (kind === 'opening' && student.messages.length) return json(response, 409, { error: 'This session already started.' });
  const posture: Posture = kind === 'submit' ? 'feedback' : 'guided';
  response.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store' });
  try {
    if (!student.session_id) {
      // The app sets the tutor's name, the course and the assignment. Learn does the teaching.
      student.session_id = await createSession(learner, {
        display_name: settings.tutor_name,
        task: { kind: 'homework', subject: settings.course, assignment: settings.assignment },
        learner: { grade_band: 'adult' },
        team_dialog: false,
      });
      await save();
    }
    const result = await sendTurn(learner, { sessionId: student.session_id, prompt: text, posture, operation: kind === 'opening' ? 'opening' : 'turn' }, (part, piece) => send(response, 'text', { part, text: piece }));
    const at = new Date().toISOString();
    if (kind !== 'opening') student.messages.push({ role: 'student', kind, text, at });
    student.messages.push({ role: 'tutor', kind, text: result.reply, display: result.display, safety: result.safety.level, request_id: result.request_id, at });
    await save();
    await appendFile(RECEIPTS, JSON.stringify({ at, 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: e.message, request_id: e.requestId });
  }
  response.end();
}

// The instructor code arrives in the request body, never in the address, so it stays out of
// server logs and browser history.
async function teacher(request: IncomingMessage, response: ServerResponse) {
  const { code } = await readJson(request);
  if (typeof code !== 'string' || !same(code.trim(), TEACHER_CODE)) return json(response, 403, { error: 'That instructor code is not right.' });
  const students = Object.values(store.students).map((s) => ({
    handle: s.handle,
    started: s.messages[0]?.at ?? null,
    questions: s.messages.filter((m) => m.role === 'student' && m.kind === 'ask').length,
    submissions: s.messages.filter((m) => m.role === 'student' && m.kind === 'submit').length,
    safety: [...new Set(s.messages.map((m) => m.safety).filter(Boolean))],
    worked_on: s.messages.filter((m) => m.role === 'student').map((m) => ({ kind: m.kind, text: m.text, at: m.at })),
  }));
  json(response, 200, { course: settings.course, assignment: settings.assignment, tutor_name: settings.tutor_name, students });
}

const FILES: Record<string, string> = { '/': 'index.html', '/teacher': 'teacher.html', '/app.js': 'app.js', '/teacher.js': 'teacher.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' };

const server = createServer(async (request, response) => {
  response.setHeader('X-Content-Type-Options', 'nosniff');
  try {
    const path = (request.url ?? '/').split('?')[0];
    if (request.method === 'POST' && path === '/api/sign-in') return await signIn(request, response);
    if (request.method === 'POST' && path === '/api/sign-out') {
      response.setHeader('Set-Cookie', 'student=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0');
      return json(response, 200, { ok: true });
    }
    if (request.method === 'POST' && path === '/api/teacher') return await teacher(request, response);
    if (request.method === 'GET' && path === '/api/me') {
      const learner = signedIn(request);
      const student = learner ? store.students[learner] : null;
      const { tutor_name, welcome, course, colors } = settings;
      return json(response, 200, { tutor: { name: tutor_name, welcome, course, colors }, signed_in: Boolean(student), handle: student?.handle ?? null, messages: student?.messages ?? [] });
    }
    if (request.method === 'POST' && path === '/api/turn') {
      const learner = signedIn(request);
      if (!learner) return json(response, 401, { error: 'Sign in first.' });
      return await turn(request, response, learner);
    }
    const file = request.method === 'GET' ? FILES[path] : undefined;
    if (!file) return void response.writeHead(404).end('Not found');
    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(settings.tutor_name + ' is running at http://localhost:' + PORT + ' (instructor page: /teacher)'));

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>Class tutor</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 id="tutor-name">Class tutor</h1>
      <p id="course"></p>
    </header>
    <form id="sign-in" hidden>
      <p id="welcome"></p>
      <label>Class code <input id="class-code" name="class_code" autocomplete="off" required></label>
      <label>Your sign-in (not your full name) <input id="handle" name="handle" autocomplete="username" required></label>
      <button type="submit">Sign in</button>
      <p id="sign-in-error" class="error-text" role="alert"></p>
    </form>
    <section id="chat" hidden>
      <p class="signed-in">Signed in as <strong id="who"></strong> · <button type="button" id="sign-out" class="link">Sign out</button></p>
      <ol id="messages" aria-live="polite"></ol>
      <form id="composer">
        <label for="message" class="visually-hidden">Your message</label>
        <textarea id="message" name="message" rows="3" placeholder="Ask a question, or paste your work and submit it" required></textarea>
        <div class="actions">
          <button type="submit" id="ask">Ask</button>
          <button type="button" id="submit-work" class="secondary">Submit my work</button>
        </div>
      </form>
    </section>
  </main>
  <script src="/app.js" type="module"></script>
</body>
</html>

File: public/app.js

// The class page: sign in, then chat with your tutor. It talks only to your own server.
const $ = (selector) => document.querySelector(selector);
const messages = $('#messages');
const input = $('#message');
const buttons = [$('#ask'), $('#submit-work')];

function escape(text) {
  return text.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
function inline(text) {
  return escape(text)
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>');
}
// Safe Markdown for the display part: paragraphs, lists, code, bold, italic.
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)]));
}

let tutorName = 'Tutor';

function bubble(role, label) {
  const item = document.createElement('li');
  item.className = 'message ' + (role === 'tutor' ? 'tutor' : 'learner');
  const who = document.createElement('span');
  who.className = 'who';
  who.textContent = role === 'tutor' ? tutorName : label;
  const body = document.createElement('div');
  body.className = 'bubble';
  item.append(who, body);
  messages.append(item);
  item.scrollIntoView({ block: 'end' });
  return { item, body };
}

function tutorReply(body, conversation, display) {
  body.innerHTML = '<p>' + inline(conversation) + '</p>' + (display ? '<div class="board">' + markdown(display) + '</div>' : '');
  typeset(body);
}
// 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 chips(item, safety, receipt) {
  const meta = document.createElement('div');
  meta.className = 'meta';
  const add = (text, kind) => { const s = document.createElement('span'); s.className = 'chip ' + (kind ?? ''); s.textContent = text; meta.append(s); };
  add('Safety: ' + safety, 'safety-' + safety);
  if (receipt) {
    add('Receipt: ' + receipt.billable_units + ' turn · $' + (receipt.charge_micro_usd / 1e6).toFixed(2) + ' · ' + receipt.settlement);
    add('Request: ' + receipt.request_id.slice(0, 12) + '…');
  }
  item.append(meta);
}

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) };
    }
  }
}

async function turn(kind, message) {
  buttons.forEach((b) => { b.disabled = true; });
  if (kind !== 'opening') bubble('student', kind === 'submit' ? 'You submitted' : 'You').body.textContent = message;
  const { item, body } = bubble('tutor');
  body.classList.add('waiting');
  let conversation = '', display = '';
  try {
    const response = await fetch('/api/turn', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind, message }) });
    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') chips(item, data.safety.level, data.receipt);
      else if (event === 'failed') { conversation = 'That did not go through (' + data.code + '). Try again in a moment.'; display = ''; }
      tutorReply(body, conversation, display);
    }
  } catch (error) {
    body.textContent = 'That did not go through. ' + error.message;
  } finally {
    body.classList.remove('waiting');
    buttons.forEach((b) => { b.disabled = false; });
    input.focus();
  }
}

async function load() {
  const me = await (await fetch('/api/me')).json();
  tutorName = me.tutor.name;
  document.title = me.tutor.name;
  $('#tutor-name').textContent = me.tutor.name;
  $('#course').textContent = me.tutor.course;
  $('#welcome').textContent = me.tutor.welcome;
  document.documentElement.style.setProperty('--accent', me.tutor.colors.accent);
  document.documentElement.style.setProperty('--bg', me.tutor.colors.background);
  $('#sign-in').hidden = me.signed_in;
  $('#chat').hidden = !me.signed_in;
  if (!me.signed_in) return;
  $('#who').textContent = me.handle;
  messages.replaceChildren();
  // Pick up where the student left off: the app keeps each student's conversation.
  for (const m of me.messages) {
    if (m.role === 'student') bubble('student', m.kind === 'submit' ? 'You submitted' : 'You').body.textContent = m.text;
    else { const { item, body } = bubble('tutor'); tutorReply(body, m.text, m.display); chips(item, m.safety); }
  }
  if (!me.messages.length) await turn('opening', '');
}

$('#sign-in').addEventListener('submit', async (event) => {
  event.preventDefault();
  const response = await fetch('/api/sign-in', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ class_code: $('#class-code').value, handle: $('#handle').value }) });
  if (!response.ok) { $('#sign-in-error').textContent = (await response.json()).error; return; }
  await load();
});

$('#sign-out').addEventListener('click', async () => {
  await fetch('/api/sign-out', { method: 'POST' });
  await load();
});

$('#composer').addEventListener('submit', (event) => {
  event.preventDefault();
  const text = input.value.trim();
  if (!text) return;
  input.value = '';
  turn('ask', text);
});

$('#submit-work').addEventListener('click', () => {
  const text = input.value.trim();
  if (!text) { input.focus(); return; }
  input.value = '';
  turn('submit', text);
});

input.addEventListener('keydown', (key) => {
  if (key.key === 'Enter' && !key.shiftKey) { key.preventDefault(); $('#composer').requestSubmit(); }
});

await load();

File: public/teacher.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Instructor page</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>Instructor page</h1>
      <p id="course"></p>
    </header>
    <form id="teacher-sign-in">
      <label>Instructor code <input id="teacher-code" type="password" required></label>
      <button type="submit">Show my class</button>
      <p id="teacher-error" class="error-text" role="alert"></p>
    </form>
    <section id="students"></section>
  </main>
  <script src="/teacher.js" type="module"></script>
</body>
</html>

File: public/teacher.js

// The instructor page: what each student worked on, from your app's own record.
const form = document.querySelector('#teacher-sign-in');
const list = document.querySelector('#students');
const error = document.querySelector('#teacher-error');

function show(data) {
  document.querySelector('#course').textContent = data.course + ' · ' + data.assignment + ' · Tutor: ' + data.tutor_name;
  list.replaceChildren();
  if (!data.students.length) list.textContent = 'No students have signed in yet.';
  for (const s of data.students) {
    const card = document.createElement('article');
    card.className = 'student';
    const h = document.createElement('h2');
    h.textContent = s.handle;
    const p = document.createElement('p');
    p.className = 'meta-line';
    p.textContent = s.questions + ' questions · ' + s.submissions + ' submissions · safety: ' + (s.safety.join(', ') || 'none yet');
    const ol = document.createElement('ol');
    for (const w of s.worked_on) {
      const li = document.createElement('li');
      li.textContent = (w.kind === 'submit' ? 'Submitted: ' : 'Asked: ') + w.text;
      ol.append(li);
    }
    card.append(h, p, ol);
    list.append(card);
  }
}

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const code = document.querySelector('#teacher-code').value;
  // The code goes in the request body, never in the address.
  const response = await fetch('/api/teacher', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) });
  const data = await response.json();
  if (!response.ok) { error.textContent = data.error; return; }
  error.textContent = '';
  form.hidden = true;
  show(data);
});

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); }
.who { font-size: 0.78rem; color: var(--muted); margin: 0 4px 3px; }
.message.learner .who { text-align: right; }
.tutor .bubble { border-color: var(--accent); }
.board { border-left-color: var(--accent); }
.waiting::after { content: "Thinking…"; color: var(--muted); font-size: 0.9rem; }
header h1 { color: var(--accent); }
#sign-in, #teacher-sign-in { display: flex; flex-direction: column; gap: 12px; max-width: 420px; }
#sign-in label, #teacher-sign-in label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; }
#sign-in input, #teacher-sign-in input { font: inherit; font-weight: 400; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; }
#sign-in button, #teacher-sign-in button, .actions button { font: inherit; padding: 8px 16px; border: 0; border-radius: 10px; background: var(--accent); color: #fff; cursor: pointer; }
.actions { display: flex; flex-direction: column; gap: 6px; }
.actions button.secondary { background: #fff; color: var(--accent); border: 1px solid var(--accent); }
.actions button:disabled { opacity: 0.5; }
.signed-in { color: var(--muted); font-size: 0.9rem; }
button.link { background: none; border: 0; color: var(--accent); cursor: pointer; font: inherit; padding: 0; text-decoration: underline; }
.error-text { color: var(--warning); min-height: 1em; }
.student { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 12px 16px; margin-bottom: 12px; }
.student h2 { margin: 0 0 4px; font-size: 1.1rem; }
.meta-line { color: var(--muted); margin: 0 0 8px; font-size: 0.9rem; }
[hidden] { display: none !important; }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }

Check it works

Start the app, open it, and sign in with the class code you set in CLASS_CODE and a short sign-in. (Without CLASS_CODE, TEACHER_CODE and LEARNER_ID_SECRET the server does not start: it says which to set.)

Your tutor, in your name and look

The page carries your tutor's name, your course and your colors. A new student's first screen is the tutor's own opening, which introduces it by the name you chose. Learn writes the opening; your app sets the name with display_name.

A real opening, captured November 23, 2026, word for word:

I am Maple. Welcome. We’ll keep the algebra work yours while making each step clearer.

Start with the first equation you need to solve, and show the step you would try first.

A question gets a hint

Type a question and press Ask. For example:

Can you just give me the answer to 4x - 7 = 21?

After about 10 to 20 seconds: a sentence that keeps the step the student's, then a hint toward the next move. Never the answer.

A real reply to that question, captured November 23, 2026, word for word:

You want the finished value, but let’s keep the solving step yours. Start by undoing the subtraction on the left.

What number should you add to both sides to remove the −7?

Submitted work gets feedback

Type the work and press Submit my work. For example:

4x - 7 = 21 4x = 14 x = 3.5

Learn checks it the way a good teacher marks a paper: the steps that hold, the first step that does not hold and why, and what to practice. It is feedback, never a grade.

Real feedback on that work, captured November 23, 2026, word for word:

You carried the equation through two algebra steps and isolated the variable; the first rearrangement changes the value that the last step uses.

The starting equation, 4x - 7 = 21, holds as written. The line 4x = 14 does not hold: this is an inverse-operation error, because removing −7 requires adding 7 to both sides, giving 4x = 28. The line x = 3.5 carries that earlier value; dividing the corrected equation by 4 gives x = 7. Practice: when undoing a subtraction, use addition on both sides, then divide by the coefficient.

The reply arrives complete and checked. Nothing unchecked is ever shown.

Every reply is written fresh, so yours will use different words.

The safety status and the receipt

Under every reply: Safety: clear for ordinary work, and the receipt, 1 turn · $0.05 · settled with the request id. The opening is a turn too. receipts.jsonl gets one line per confirmed turn, with the posture (guided for Ask, feedback for Submit my work).

Your instructor page

Open /teacher and enter the instructor code you set in TEACHER_CODE. The page sends it in the request body, never in the address. Each student's sign-in is listed, with what they asked and what they submitted. The page also shows each student's safety levels, so you can follow up with a student who may need support.

The conversation picks up

Sign out, or open another browser, and sign in with the same sign-in. The conversation is there, and the next question carries on in the same session.

What stays on your server

The key, and who the student is. Learn gets a keyed hash of the student's sign-in (learner-…), never a name, a sign-in or an email.

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.

If something goes wrong

What you seeWhat it meansFix
The opening says "I am Learn."The session was prepared without display_name, or before you set it.Set display_name in the setup. A session's setup never changes, so a student with an older session keeps its name until that session ends.
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 sessionYour workspace has less than ten turns' worth left (50¢).Add funds to your workspace, then prepare the session again.
403 DEVELOPER_POLICY_BLOCKEDThe 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_LIMITYour 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).
Feedback asks for the work instead of checking itA bare final answer was submitted.Feedback checks work it can see: submit the steps, not just the answer.

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.

The kit.

The repository

A start folder and the finish.

Open the kit

class in learn-tutor-starter

Next

  • The finished app: class
  • The steps it builds on: Your first tutor in ten minutes (step 1) and The four kinds of help (step 2)
  • Next: Embed Learn in your app, Learn inside the product you already have

Your first tutor in ten minutes.

Start building