Developer production · Server APIs
The Learn APIBy ForeverLearning

Build with Learn · Step 5

Show the safety status

About 10 minutes with a coding assistant.

What you'll build. Your app acts on each turn's safety status: a quiet check-in, a support message, or a help card with crisis lines, always under Learn's reply. It keeps a record of every turn that is not clear, for the people who oversee your app.

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.
  • Cost. Testing this step takes about two turns, 10¢. When the safety check on a learner's message flags self-harm, that turn is free.
  • Start from step 4's checkpoint, 04-remember-the-learner. The finished step is 05-safety-status.

Option A: hand it to your coding assistant

Open a copy of 04-remember-the-learner 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: the app acts on each turn's safety status, from a quiet check-in to a help card with crisis lines, always under Learn's reply, and keeps a record for the people who oversee it.

Read first: https://developers.foreverlearning.ai/docs/learn/ (the Learn integration guide, especially "Send a turn and validate its result" and "Read the safety status on every turn"), 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 04-remember-the-learner folder of learn-tutor-starter. Keep how it works and add to it.

Build:
1. Read each turn's safety status (its response action and its level) and show it under the reply, as before.
2. Show Learn's reply at once, as Learn wrote it. Under it (or beside it), add the app's own response for any turn that is not clear: for a response action of support, a short message that it is fine to stop the work and that talking with someone they trust can help (a quiet check-in at watch, more prominent at warning); at critical, or a response action of escalate, a help card that says to reach out to someone now, with the US crisis line (call or text 988, the Suicide & Crisis Lifeline) and a line for learners outside the US to call their local emergency number. Never cover, hide or delay the reply, and never make the learner press anything to see it. Treat unknown as not checked, never as clear.
3. Record every turn that is not clear (time, learner id, level, response action, request id, session id) as a JSON line in data/safety-events.jsonl, and for critical or escalate, also log a clear escalation line on the server.
4. When a turn fails, show the learner your app's own short message (for a message the safety screening refuses, 403 DEVELOPER_POLICY_BLOCKED: "I can't help with that message. Try asking another way."), and keep Learn's own error text in your server log, never on the page.
5. Everything else as before.

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.
- Learn's reply stays as Learn wrote it, visible at once; your app adds its own response under it, never over it.
- Never tell the learner that a person has been told or will check in. The escalation line only logs; say so in a comment where a builder would connect it to a real person.
- Each message is a real turn, at 5¢ per turn that succeeds. Test with two turns: one ordinary question, and one from a learner who sounds worn down and hopeless about their work. 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 an ordinary question shows a clear status with no extra message
- a learner who sounds hopeless gets a status that is not clear, Learn's reply shows at once, and your app's response shows under it, with nothing over the page
- data/safety-events.jsonl has a line for that turn

Paste into your coding assistant.

Option B: by hand

The guide sections this step uses: Read the safety status on every turn and Your product's part in a crisis.

Every turn's events include one safety_status: response_action (none or support on this release; the contract also defines escalate, which you handle as you handle critical), level (clear, watch, warning, critical, or unknown), evaluated and source. Learn has already replied with care. Your application owns consent, oversight and escalation:

Response action and levelWhat the sample app adds, under the reply
none, clearnothing
support, watcha quiet check-in: it's fine to take a break; talk with someone you trust
support, warninga support message: it's fine to stop the work; talking with someone you trust can help
support, critical (or escalate)a help card: please reach out to someone now, with the US crisis line (988) and the local emergency number elsewhere; an escalation line in the server log
none, unknown"This turn couldn't be checked": never treated as clear

Show Learn's reply at once, as Learn wrote it: never hide it, delay it or replace it, and never put anything over it (Your product's part in a crisis). Your app's response goes under the reply or beside it. 988 is the US line. Learn is not told where a learner is, so show your own local resources for the other countries you serve, Canada included. Adapt the words and the help to your learners and your region.

Reaching a person. The sample's escalation line only logs. Connecting it to a real person is your next step: your own on-call, email or messaging, or the optional safety webhook. In the console you can opt in to signed safety events sent to your own server, at a public HTTPS endpoint on port 443 with no credentials, query strings or redirects. Store the signing secret the console shows once, and verify each event's X-FL-Signature header before you act on it. Each event carries the safety status and opaque identifiers, never conversation text or the learner's id, and its delivery never holds back the reply. Only once your app really notifies someone may it tell a learner that a person has been told.

A message the screening refuses. 403 DEVELOPER_POLICY_BLOCKED means the safety screening stopped the learner's message before it reached the tutor. Show your own short message, for example "I can't help with that message. Try asking another way.", and let the learner continue. Never show the refusal's own text. The sample does the same for every failed turn: the learner sees the app's words, and Learn's message goes to the server log.

Free turns. When the safety check on a learner's message flags self-harm, that turn is free. It is answered even when your balance has run out. The rule follows the check on the message, not the level in the reply, so read the charge from done, not from the level.

Starting from 04-remember-the-learner, replace these files. Then run npm start and open http://localhost:3000.

File: server.ts

// Show the safety status: every turn carries Learn's safety status, and your app acts on it,
// from a quiet check-in to a help card under the reply, and keeps a record for the people who
// oversee it.
// Builds on steps 2 to 4. 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. (Your own record also
// means you never depend on listing a new learner's sessions.)
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();
}

// Your app's part in safety. Learn evaluates every turn and replies with care; what happens
// next in your product is yours: what the learner sees, and who on your side is told.
// Every turn that is not clear is recorded here for the people who oversee your app.
const SAFETY_LOG = join(import.meta.dirname, 'data', 'safety-events.jsonl');
async function recordSafety(learner: string, safety: { level: string; response_action: string; evaluated: boolean }, requestId: string, sessionId: string) {
  if (safety.level === 'clear' && safety.response_action === 'none') return;
  await mkdir(dirname(SAFETY_LOG), { recursive: true });
  await appendFile(SAFETY_LOG, JSON.stringify({ at: new Date().toISOString(), learner_id: learner, level: safety.level, response_action: safety.response_action, evaluated: safety.evaluated, request_id: requestId, session_id: sessionId }) + '\n');
  if (safety.response_action === 'escalate' || safety.level === 'critical') {
    // This only logs. To reach a person, connect it to your own on-call, email or messaging, or opt
    // in to the safety webhook in the console. Until a person is really told, never tell the
    // learner that someone has been.
    console.warn('SAFETY ESCALATION (logged only): learner ' + learner + ', request ' + requestId + ' (level ' + safety.level + ')');
  }
}

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');
    await recordSafety(learner, result.safety, result.request_id, result.session_id);
    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>Safety status</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) => ({ '&': '&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;
  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);
        react(item, data.safety);
      } 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();

// Your app's response to each turn's safety status, added under Learn's reply. The reply is shown
// at once, as Learn wrote it: nothing here hides, delays or covers it, and the learner never has to
// press anything to see it. Adapt the words and the help to your learners: 988 is the US line, and
// Learn is not told where a learner is, so show your own local resources for the other countries
// you serve, Canada included.
function react(item, safety) {
  const { level, response_action: action } = safety;
  if (level === 'clear' && action === 'none') return;
  const note = document.createElement('div');
  note.className = 'safety-note safety-note-' + level;
  note.setAttribute('role', 'status');
  if (level === 'critical' || action === 'escalate') {
    // The most serious level: help to reach right away, under the reply.
    note.classList.add('safety-help');
    note.innerHTML = '<strong>Please reach out to someone now.</strong> '
      + 'If you are in danger or thinking about hurting yourself, call or text <strong>988</strong> (the Suicide &amp; Crisis Lifeline, in the US), or call 911. '
      + 'Outside the US, call your local emergency number or crisis line. Talk with someone you trust right away.';
  } else if (level === 'unknown') {
    // Unknown is not an all-clear: the turn was not evaluated. Keep the support path in view.
    note.textContent = "This turn couldn't be checked for safety. If something is wrong, talk with someone you trust.";
  } else if (level === 'warning') {
    note.innerHTML = "<strong>You don't have to carry this alone.</strong> It's fine to stop the work for now. Talking with someone you trust can help.";
  } else {
    // watch (on this release, with support): a quiet check-in, the support path within reach.
    note.textContent = "It's fine to take a break. If something else is on your mind, you can say so here, or talk with someone you trust.";
  }
  item.append(note);
}

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; }
.safety-note { margin-top: 6px; padding: 8px 12px; border-radius: 10px; font-size: 0.92rem; line-height: 1.4; }
.safety-note-watch { background: #f6f1e2; color: #5b4500; }
.safety-note-warning { background: #fbe9e1; color: #6d2a10; border: 1px solid #e7b9a5; }
.safety-note-critical { background: #fbe1e6; color: #6e0f22; border: 1px solid #e3a3b1; }
.safety-note-unknown { background: #eeeef2; color: #3d3d4a; }
.safety-note.safety-help { border: 2px solid #8a1230; background: #fdecef; color: #4a0a1a; }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }

Check it works

Run npm start and open http://localhost:3000.

  1. Ask an ordinary question, for example "I'm stuck on 5x + 2 = 17. Where do I start?" Under the reply: Safety: clear, and nothing else from your app.
  2. Write as a learner who sounds worn down, for example "I failed my test again. Honestly I don't see the point of trying anymore, I'm so tired of everything." Learn's reply shows at once, with care, and its safety status is not clear. Under the reply, your app adds its own response for that level. Nothing covers the page, and you never have to press anything to see the reply.

A real reply, with safety status watch and response action support, captured November 23, 2026, word for word:

Failing again sounds exhausting, and “I don’t see the point anymore” makes me want to check on you before we return to the test.

How are you doing right now? You can answer in a few words. If you feel able, tell me whether you’re safe at this moment and whether you’re alone.

The reply arrives complete and checked. Nothing unchecked is ever shown. Every reply is written fresh, so yours will use different words.

  1. Open data/safety-events.jsonl. It has a line for that turn: the time, the learner id, the level, the response action, the request id and the session id. A critical level or an escalate action also logs an escalation line on the server. It only logs: until you connect it to a person (your on-call, email or messaging, or the safety webhook), your app never tells a learner that someone has been told.
Response action and levelWhat the sample app adds, under the reply
none, clearnothing
support, watcha quiet check-in: it's fine to take a break; talk with someone you trust
support, warninga support message: it's fine to stop the work; talking with someone you trust can help
support, critical (or escalate)a help card: please reach out to someone now, with the US crisis line (988) and the local emergency number elsewhere; an escalation line in the server log
none, unknown"This turn couldn't be checked": never treated as clear

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
unknown shown as all clearThe app checks only for warning and critical.Treat anything but clear with action none as needing your response.
No escalation reaches a personThe escalation hook only logs.Connect it to your on-call, email or messaging, or opt in to the safety webhook. Until it notifies a person, never tell a learner that someone has been told.
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 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.
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

05-safety-status in learn-tutor-starter

Next

Your first tutor in ten minutes.

Start building