Developer production · Server APIs
The Learn APIBy ForeverLearning

Build with Learn · Step 2

The four kinds of help

About 10 minutes with a coding assistant.

What you'll build. One tutor, four kinds of help: three on any turn, and Diagnostic for a session. The learner chooses on each message: Guided while the learner works on a problem, Feedback to check finished work, Explain for a worked example they don't follow, and Diagnostic for a quiz they finished. Guided and Explain leave the answer with the learner. Feedback checks finished work line by line and corrects it. Diagnostic reports what the learner understands, and does not teach.

Before you start

  • An account and a key, as in step 1, with your key in FOREVERLEARNING_API_KEY and your API host in FOREVERLEARNING_BASE_URL.
  • Start from step 1's checkpoint, 01-first-tutor. The finished step is 02-four-kinds-of-help.

Each turn that succeeds costs 5¢. A turn that fails costs nothing.

Option A: hand it to your coding assistant

Open a copy of 01-first-tutor 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.

Paste this
Goal: one tutor, four kinds of help. On each message the learner chooses: Guided while working on a problem, Feedback to check finished work, Explain for a worked example they don't follow, or Diagnostic for a quiz they finished.

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: the app in this folder, a copy of the 01-first-tutor folder of learn-tutor-starter. Keep how it works and add to it.

Build:
1. On the chat page, a choice of four kinds of help, labeled Guided, Feedback, Explain and Diagnostic, sent with each message.
2. Guided, Feedback and Explain share the learner's one teaching session (task kind "practice"). Send the chosen posture on every turn: leaving it out means Guided.
3. Diagnostic is chosen when a session is prepared. When the learner sends a Diagnostic message (their finished quiz), prepare a new session for them with the setup's posture "diagnostic" and the quiz as the finished work in the setup's assessment, then ask Learn for the session's opening and show it. The learner's next Diagnostic messages are their answers, sent as ordinary turns with no posture. Choosing Guided, Feedback or Explain after it starts a new teaching session. Starting a session closes the learner's open one first: that closeout is billed on its own, and the reply takes about ten seconds longer, about 19 seconds.
4. Under each reply, show which kind of help it was (the posture in the turn's receipt), with the safety status and the receipt as before. Keep receipts.jsonl as before, with the posture on each line.

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.
- Each message is a real turn, at 5¢ per turn that succeeds. Test each kind once, no more. 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` and sent one message of each kind through your route, and each got a reply
- each reply shows its kind, its safety status and its receipt
- receipts.jsonl has a line for each turn, with its posture

Paste into your coding assistant.

Option B: by hand

The guide section this step uses: Choose a posture for each request. Diagnostic: Run a Diagnostic session.

KindForHow you ask for it
Guidedworking on a problem"posture": "guided" on the turn
Feedbackchecking finished work"posture": "feedback" on the turn
Explaina worked example they don't follow"posture": "explain" on the turn
Diagnostica quiz they finishedprepare a new session with "posture": "diagnostic" and the finished work in setup.assessment, open it, then send the learner's answers with no posture
  • Guided, Feedback and Explain share one session and change on any turn. Leaving posture out means Guided every time, even after Feedback or Explain, so send it on every turn.
  • Diagnostic is chosen when the session is prepared, and holds for the whole session. The finished work can only be given then, in setup.assessment (fl.quest.assessment-input.v1). Every field is required: schema_version, goal, sources (the work, as a submitted_work source), items and targets (which may be empty lists), original_result and limitations; see Run a Diagnostic session. The starter's code sends them all. Then ask for the session's opening: an empty prompt with "operation": "opening".
  • The examples here are mathematical. A Diagnostic session is billed like any other: the opening, each answer and the end, 5¢ each; preparing it and reading its report are free.
  • A learner has one open session at a time. Starting a Diagnostic session closes their teaching session first, and starting a teaching session after it closes the Diagnostic one. Each closeout is billed on its own, and that reply takes about ten seconds longer, about 19 seconds (A new session while one is open).

Starting from 01-first-tutor, 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';
}

// 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 },
  };
  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

// The four kinds of help: Guided, Feedback and Explain on any turn, and Diagnostic for a
// finished quiz. A small server that keeps the Learn key and a chat page that
// shows the reply. Node 24+, no packages. Start it with: npm start
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFile, appendFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { createSession, sendTurn, 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');

// One Learn session per learner. A real app keeps this in its database.
const sessions = new Map<string, { id: string; diagnostic: boolean }>();

// 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): 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 || '{}');
}

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

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 } = await readJson(request);
  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';
    const result = await sendTurn(learner, { sessionId: session.id, prompt: opening ? '' : message.trim(), posture, operation: opening ? 'opening' : 'turn' }, (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);
    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>Four kinds of help</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>Four kinds of help</h1>
      <p>Choose the help you want for each message. Guided and Explain leave the answer with you. Feedback checks your finished work line by line and corrects it. Diagnostic reports what you understand.</p>
    </header>
    <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>
      <label for="message" class="visually-hidden">Your message</label>
      <textarea id="message" name="message" rows="2" placeholder="Type your question" required></textarea>
      <button type="submit">Send</button>
    </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), never to Learn directly.
const messages = document.querySelector('#messages');
const form = document.querySelector('#composer');
const input = document.querySelector('#message');
const button = form.querySelector('button');

// 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) => ({ '&': '&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>');
}
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;
  add('learner', text).querySelector('.bubble').dataset.kind = kind;
  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 }),
    });
    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();
  }
});

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); }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }

Check it works

Run npm start, open http://localhost:3000, and send one message of each kind.

ChooseSend, for exampleWhat the reply does
GuidedI'm working on 2(x - 4) = 10. Where do I start?One move toward the next step: a question or a hint. Never the answer.
FeedbackHere is my work: 2(x - 4) = 10, 2x - 4 = 10, 2x = 14, x = 7. Is it right?Checks the work line by line: what holds, the first line that does not and why. Never a grade.
ExplainMy book's solution says: 2(x - 4) = 10, so x - 4 = 5, so x = 9. Why can you divide both sides by 2 first?Explains the part of the worked solution you don't follow, then asks one question to check.
Diagnosticyour finished quiz, question by questionPrepares a Diagnostic session with your quiz as the finished work and opens it: a few neutral questions about your work, without marking answers right or wrong.

Guided. A real reply, captured November 23, 2026, word for word:

You have a specific equation to work with, and you’re asking for the first move. Start by noticing what is being done to the parentheses.

In 2(x - 4) = 10, what operation is happening to (x - 4)? What could you do to both sides to undo that operation?

Feedback. A real reply, captured November 23, 2026, word for word:

You applied distribution, isolated the variable term, and divided to reach a value. I’ll check each line in order and trace the first change that affects the rest.

Your starting equation 2(x - 4) = 10 holds as written. Your next line, 2x - 4 = 10, does not hold: this is a distribution error because the 2 must multiply both terms inside the parentheses, giving 2x - 8 = 10. Then 2x = 14 carries that earlier value; adding 8 to both sides gives 2x = 18. Finally, x = 7 carries that value; dividing by 2 gives x = 9. Practice: when a number is outside parentheses, check that it reaches every term inside. As a separate check, substitute the resulting value into the original equation and compare both sides.

Explain. A real reply, captured November 23, 2026, word for word:

The point you’re asking about is why dividing by the outside 2 can happen before handling the parentheses.

An equation stays balanced when you perform the same reversible operation on both sides. Here, the entire left side is 2(x - 4), so dividing by 2 cancels the multiplication by 2:

2(x - 4) ÷ 2 = 10 ÷ 2

That leaves x - 4 = 5. The parentheses stay together because the 2 was multiplying the whole group. Analogy: if two identical bundles weigh 10 units, one bundle weighs 5 units. What operation would undo the - 4 next?

Diagnostic. A real reply, captured November 23, 2026, word for word:

I'm Learn. This assessment will examine the reasoning in your finished quiz without changing or teaching the solutions. For the first question, how did you get from \(3x + 5 = 20\) to \(3x = 15\)?

Explain your reasoning in your own words, starting with the first problem.

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

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

Under each reply

  • Kind: the posture in the turn's receipt (guided, feedback, explain; a Diagnostic session's receipt carries its own).
  • Safety: clear for ordinary work.
  • Receipt: 1 turn · $0.05 · settled and the request id.

receipts.jsonl gets one line per turn, with its posture. Switching to Diagnostic closes the learner's teaching session first; that closeout is a separate charged request in your Usage.

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
Every reply's kind is guidedThe turn was sent without posture.Send the chosen posture on every turn.
A reply takes about ten seconds longer, about 19 seconds, and Usage shows an extra charged requestStarting a session closed the learner's open one, and its closeout ran first (A new session while one is open).Expected when switching to or from Diagnostic. End a session yourself when the learner finishes (step 4) to choose when that happens.
400 DIAGNOSTIC_SESSION_REQUIREDA Diagnostic turn was sent on a session that was not prepared for Diagnostic. Nothing was charged.Prepare a new session with "posture": "diagnostic" and the finished work in setup.assessment, then open it.
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).

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

02-four-kinds-of-help in learn-tutor-starter

Next

Your first tutor in ten minutes.

Start building