---
name: letlms
description: "Operate a LetLMS learning portal through its MCP server: build and edit courses, sections and lessons (ebooks, videos, interactive games, simulations, quizzes, AI role-play tutors), manage members and groups, and report on learner progress. Use whenever LetLMS MCP tools are available or the user asks about their LetLMS learning portal."
---

# Operating a LetLMS learning portal

LetLMS is an AI-native Learning Management System. Each customer has their own
**learning portal** on its own domain, with its own MCP server at
`https://<portal-domain>/mcp`. In this guide `<portal>` means the origin of the
portal whose MCP server you are connected to (e.g. `https://acme.letlms.app`).

This file has the topics for building and editing courses. Read the others
with the MCP server's `guide` tool when a task needs them (list below). If the
MCP handshake carries instructions specific to the portal, those override the
general guidance here.

---

## How to work on a LetLMS portal

LetLMS is an AI-native LMS. Each customer has a **learning portal** (also
called a *school*) on its own domain; you act on exactly one portal.

| Concept | What it is |
| --- | --- |
| **Course** | Title, description, thumbnail, slug, release (`draft` / `published`) and audience (`public` / `unlisted`). |
| **Section** | An ordered chapter of a course. |
| **Lesson** | One item a learner consumes, ordered within its section, with a `type`, a status (`draft` / `published`) and a versioned body. |
| **Member** | A user of the portal: `admin` or `student`. Groups enrol their members in the group's courses. |

Lesson types: `ebook` (written lesson, HTML), `video` (HTML with video embeds),
`game` (scored HTML/CSS/JS game), `interactive` (simulation or interactive
explanation, HTML/CSS/JS), `assessment` (quiz or form, JSON questions),
`role_play` (an AI tutor that runs a scenario and grades the learner).

## The sequence

1. **Read before you write.** `course_get` for the outline before changing a
   course; `lesson_get` before changing a lesson. Creating blindly makes
   duplicates.
2. **Structure first, in one call.** Create, rename, reorder or move sections
   and lessons with one `outline_apply` — list them in the order you want.
   It returns the new ids (`idMap`).
3. **Can you create and run files on your machine** (Claude Code, Codex,
   Cursor, any agent with a workspace)? Then build every game and interactive
   lesson there first, test it in a real browser, and only upload what works —
   topic `local_dev`. This is where you can show what you are capable of.
4. **Then the bodies.** Build every game and interactive lesson as described
   in `craft`, then follow the lesson type's section of this guide
   (`game`, `interactive`, `ebook`, `assessment`, `role_play`, `video`),
   then `lesson_write` each body. The lessons `outline_apply` created are
   empty: fill them with `lesson_write({ lessonId, body })` (no
   `baseVersion` for a lesson's first body) — creating them again by section
   and type is refused as a duplicate. For HTML lessons that share a look, read
   `engines` first. Sub-agents: at most three — topic `local_dev`.
5. **Small changes are edits.** Wording, a fixed bug, one more question or a
   setting: `lesson_edit` with the `version` you read as `baseVersion` —
   several ops in one call. Don't resend a whole lesson for a small change.
6. **Report back in plain language.** Say what changed, by title.

Building a whole new course? `template_search` first — cloning a close
template (`course_clone`) and adapting it is faster than starting from zero.

**Course size.** If the creator gives a structure (sections, lesson count or
list), build exactly that. Otherwise plan a complete course the way a teacher
would: list the topics a learner needs to go from beginner to the course's
goal, then give each topic its own section with **3–6 focused lessons**
(typically 4–8 sections, 15–30 lessons). Mix types: `ebook` / `video` to
explain, `interactive` or `game` to practise, an `assessment` to check each
section, a `role_play` where conversation fits. One idea per lesson — split a
topic into several lessons rather than packing it into one. Building many
lessons is the job; don't trim the outline to save effort.

## Hard rules

- **Never show ids to the user** (course, section, lesson, asset, user…). Refer
  to things by title; ids are for tool arguments.
- **Only change what the user asked for.** Don't "improve" a course you were
  asked a question about.
- **Writes that replace long text need the version you read.** Send it as
  `baseVersion`; a mismatch is `stale_version` with the current state — read
  again and redo your change on top of it, never blindly.
- **Learner-facing fields are content only.** Titles, descriptions, lesson
  bodies, questions and page copy are shown to learners as-is: no notes to the
  course creator, no remarks about the request.
- **Destructive actions need the user's go-ahead** (deletes, refunds, removing
  members). `dryRun` shows what a change would do without saving it.
- Lists page with `cursor` → `nextCursor` (null on the last page).
- `idempotencyKey` (any string you choose) makes a create safe to retry: the
  same key returns the first result instead of creating a second copy.

## Errors

A failed call returns `{ error: { code, message, hint, retryable, details } }`.
Follow the `hint` — it usually names the guide topic or the read to do first.
`retryable: false` means repeating the same call will fail again. Common codes:
`not_found`, `invalid_input`, `conflict` (e.g. a folder that isn't empty or already exists), `stale_version`, `insufficient_scope` (ask the
user to reconnect with that permission), `plan_limit_reached` (the plan's course or seat limit — tell the user to
upgrade). An HTTP 402 / `payment_required` means the portal has no active
plan or is out of AI credits: tell the user to upgrade or wait for the next
period rather than retrying.

---

## Build and test locally first

If you can write files and run commands where you work, build the
course's interactive material as a small local project before touching the
portal. Real files let you write proper, reusable code (an engine, a component
kit, a shared theme), open it in a browser, play it end to end and fix it —
then the portal gets finished, tested work instead of a first draft.

**1. Lay out the project** (one folder per course):

```
<course-slug>/
  shared/course-theme.css     colours, type, layout, buttons, feedback states
  shared/lesson-kit.js        helpers several lessons use (window.LessonKit)
  engines/<name>.js           larger reusable pieces: a quiz runner, a simulation core
  lessons/<lesson>.html       one file per game / interactive lesson
  dev/lms-stub.js             local stand-in for the LMS SDK (never uploaded)
```

Write the shared files once and build every lesson on them; a lesson keeps only
its own layout and logic inline.

**2. Stand in for the SDK while testing.** On the portal the lesson loads
`/js_sdk.js`; locally load `../dev/lms-stub.js` instead, with the same API
(it keeps state in this browser only, which is fine for testing and nowhere
else):

```js
// dev/lms-stub.js — LOCAL TESTING ONLY. Never upload it.
(() => {
  const KEY = "lms-stub:" + location.pathname;
  const fresh = () => ({ data: null, location: "", interactions: [] });
  let saved = JSON.parse(localStorage.getItem(KEY) || "null");
  let s = saved || fresh(), resume = !!saved;
  const keep = () => localStorage.setItem(KEY, JSON.stringify(s));
  window.LMS = {
    async init() { return true; },
    isResume: () => resume,
    load: () => s.data, save: (o) => { s.data = o; keep(); },
    setLocation: (l) => { s.location = l; keep(); }, getLocation: () => s.location,
    setProgress: (p) => { s.progress = p; keep(); },
    setScore: (score, max) => { s.score = { score, max }; keep(); },
    // Like the real SDK: one entry per id, newest values win.
    recordInteraction: (i) => {
      const at = s.interactions.findIndex((x) => x.id === i.id);
      if (at === -1) s.interactions.push(i);
      else s.interactions[at] = { ...s.interactions[at], ...i };
      keep();
    },
    getInteractions: () => s.interactions,
    async complete(r) { s.completed = r ?? true; keep(); console.log("LMS.complete", r); },
    reset: () => { localStorage.removeItem(KEY); s = fresh(); resume = false; },
    onExternalChange() {},
  };
})();
```

**Sub-agents: at most three.** Build lessons yourself, one after another, by
default. If your client can run sub-agents at the same time (Claude Code's
Agent tool, Codex sub-agents, …), you may hand part of the work to **at most
three** of them (two is usually enough) — each one re-reads the shared files and its instructions on
every step, so more of them cost far more and save little:

1. Build, test and upload the shared files yourself first (theme, kit,
   engines; step 4), so every lesson can link their URLs.
2. Split the interactive lessons and games into two or three groups and
   start one sub-agent per group, **in the same turn**. Before that, save
   what they all need in the project once — `dev/lesson-rules.md` (topics
   `craft` and `game` / `interactive`, as text) and `dev/shared-api.md`
   (each shared file's URL and its classes / functions with one-line
   signatures). Then each sub-agent's brief is short: the project folder,
   "read `dev/lesson-rules.md` and `dev/shared-api.md`", and for each of
   its lessons the file to write (`lessons/<lesson>.html`), the
   `lessonId`, the `courseId` and a few lines of brief (what the learner
   should be able to do, the scenario). It builds, tests (step 3), uploads
   and sets each lesson body (step 4) if it has the LetLMS tools — otherwise
   it reports back and you upload. It never changes a shared file; it
   reports what it needs.
3. Meanwhile write the ebooks, quizzes and role-plays yourself
   (`lesson_write`), then apply any reported shared-file changes
   (overwrite in place, so every lesson gets them).

**Keep sub-agents cheap.** Every sub-agent pays again for everything it is
given and everything it reads, on every step it takes — a brief stuffed
with files and guide text, or a sub-agent that reads whole engines and
looks at dozens of screenshots, can cost more than the lessons themselves.

- Pass **paths and summaries, never contents**: no pasted source files, no
  pasted guide text, no whole conversation history. Point to the files in
  the project instead.
- Tell it to read a shared file only for the part it needs (`grep` /
  `sed -n` for one function), not the whole file, and never twice.
- Change files with small edits; don't rewrite a whole lesson to fix a line.
- Test with one scripted browser run that prints only failures; take a
  screenshot only to check a layout, and look at as few as possible.
- Don't have it load the LetLMS skill or call read tools it doesn't need —
  it only needs `media_put({ localFile: true })` and `lesson_write`.
- Ask for a **short reply**: the lessons it finished, anything it couldn't
  do, and shared-file changes it needs — no code, logs or summaries of the
  lesson.

**3. Test it like a learner** — open each lesson in a browser (a headless
browser such as Playwright, or a local static server):

- play it from start to finish; no console errors;
- if the creator asked for resume: reload part-way — it must offer to continue
  at the right place, with the score intact (that reload is what another device
  looks like);
- a game must call `LMS.complete({ score, maxScore })` with integers at the end;
- check a 375 px wide screen as well as a desktop one;
- unit-test engine logic with a quick script where it is non-trivial.

**4. Upload what works — the files themselves, never their text.** Pasting a
finished file into a tool call makes you write it out a second time, which is
most of the time a course takes. `media_put({ localFile: true, … })` returns a one-time URL and a
`curl` command; run it with your local file and its JSON reply is the stored
file. Run several uploads in one shell command.

- Shared files and engines first:
  `media_put({ localFile: true, scope: "course-library", courseId, path: "shared/course-theme.css" })`
  → run the command (and the same for each `.js`). Each reply has the
  file's `url`.
- In each local lesson file, replace the local links with those exact URLs,
  write the SDK tag `<script src="/js_sdk.js"></script>` where
  `dev/lms-stub.js` was, and use `CONTENT_ID_PLACEHOLDER` as the content id
  (small edits, e.g. with `sed` — don't rewrite the file).
- Upload each lesson file the same way (`path: "lessons/<lesson>.html"`),
  then set it as the lesson body with
  `lesson_write({ lessonId, body: { ref: { libraryPath: "lessons/<lesson>.html" } } })`.
- Images, audio, video and PDFs you made or were given: `localFile: true` too.
- Keep the local folder as the source of truth. To change something later,
  edit and retest locally, then upload again: a shared file in place with
  `media_put({ localFile: true, assetId, baseVersion })` (same URL, so every lesson gets
  it); a lesson as a new library file and `lesson_write` with `ref` and the
  lesson's `baseVersion` — or `lesson_edit` for a small change.

Without a local workspace (a chat-only client), write the files straight to the
course library and lessons the same way — the structure and the shared files
still apply.

---

## Building a game or interactive lesson

A game or interactive lesson is a front-end application. Approach it the way
you would any serious web project you were shipping: plan it, structure the
code, design the interface, test it in a browser. The LetLMS part is small — an
adapter that maps your app's state to a few SDK calls — and it comes last.

### 1. Plan before you code

Write yourself a short spec first (it is for you, not the learner):

- **The skill.** What should the learner be able to *do* afterwards? Phrase it
  as an action on the real tool or problem ("write a SUM over a range", "resolve
  a merge conflict"), not as a fact to recall.
- **The model.** What does the app have to simulate for the learner to do that
  action for real? A spreadsheet needs cells, references and a formula
  evaluator; a git lesson needs a repository with commits and branches; a
  pricing lesson needs a market that reacts. This model is the heart of the app.
- **The design.** Decide the lesson's shape yourself from the skill and the
  creator's request — a single screen, a free-play sandbox, a sequence of
  tasks, a game session. There is no required number of steps or rounds.
  Whatever the shape, give each task a realistic scenario (a sales table, a
  budget, a team's repo), the check that decides it is done, a hint, and the
  mistakes you expect and what to say about each.
- **The game loop** (for a game): what the learner produces, how they score,
  how it ends.

### 2. Structure the code like an app

Separate concerns even inside one HTML file, and put anything reusable in its
own file in the course library (topic `engines`):

- **engine** — the domain model and its rules (parse and evaluate a formula, run
  a command against the repo, step the simulation). Pure functions over plain
  data, no DOM. Several lessons and the game can then share it.
- **state** — one plain object holding everything that changes (where the
  learner is, their work, score, attempts). Everything else derives from it.
- **render** — draws the state; re-run it after every change.
- **input** — clicks, typing and keyboard handling that turn into state updates.
- **checks** — functions that inspect the learner's work and return
  pass / fail plus a specific explanation.
- **progress adapter** — the only code that talks to `LMS`: on boot
  `await LMS.init()`; as the learner moves on `LMS.setLocation()` and
  `LMS.setProgress()` where the lesson has a sense of position; `LMS.recordInteraction()` for every answer;
  `LMS.complete()` at the end (topic `sdk`). Only if the creator asked for
  resume: restore `state` from `LMS.load()` when `LMS.isResume()` and
  `LMS.save(state)` after each change — because all progress lives in
  `state`, resume is then just "load state, render".

### 3. What good looks like

- **The learner performs the skill on a working model**, not on a form that
  describes it: they type the formula into the grid and it computes, they run
  the command and the repo changes. Dropdowns and "choose, then Apply" panels
  replace the skill with a description of it — avoid them as the main
  interaction.
- **It behaves like the real thing**: the keyboard conventions, selection and
  editing, error states and the visual language of the tool being taught.
- **Feedback is diagnostic**: checks look at *how* the learner solved the task
  (referenced the cells rather than typing the number; used the right function
  or an absolute reference) and the message names the actual mistake and how to
  fix it.
- **Games are built on the same engine, and designed as games**:
  - *Core loop*: the learner produces real answers on the working model
    under pressure (a clock, lives, a target).
  - *Variety*: challenges come in several formats that each exercise a different
    facet of the same skill. Producing the answer is the backbone; mix in
    formats such as predicting what something will do, finding and fixing a
    broken one, or choosing between near-miss alternatives that each hide a
    classic mistake.
  - *Rewarded mastery*: scoring rewards fluency as well as correctness, for
    example streaks or combos, a speed bonus, and partial credit after a
    retry, and the HUD makes these rewards visible as they happen.
  - *Replay value*: the engine generates data so a replay is a new game.
  - *End screen*: a score breakdown, a review of every miss with the
    correct answer and why (from the attempt log kept in `state`), and a
    replay.
- **Designed, not defaulted**: a deliberate layout and type scale, a palette
  from the course's shared theme, states for hover / focus / correct / wrong,
  motion where it clarifies, and a layout that works from 375 px up.
- **Polish over length**: a working model, real feedback and a clean design
  matter more than how long the lesson is.

### 4. Verify before you save

Use a browser if you have one (topic `local_dev`): play it through, trigger
each expected mistake and read its explanation, finish and see the end screen
and `LMS.complete` — and, if the creator asked for resume, reload half-way and
confirm it resumes in the same place with the same work. Fix what you find,
then upload.

---

## Ebook lessons

An ebook is written material. Send its body as `body.html_or_data`: plain
semantic HTML equivalent to Markdown — headings, paragraphs, lists, tables,
links, `<code>`/`<pre>`, images (`<img src>` with a real URL).

- No `<style>`, inline styles, `<script>` or external stylesheets — the
  learner's reader styles the lesson.
- Diagrams and flowcharts are Mermaid inside a `<mermaid>` tag:

```html
<mermaid width="500" height="500">
flowchart TD
A["Start"] --> B{"Is valid?"}
B -- "Yes" --> C["Yes path"]
B -- "No" --> D["No path"]
</mermaid>
```

- A video: `<video data-lexical-url="VIDEO_URL"></video>`, only for a URL you
  were given (never base64).
- Reading progress is tracked by the platform — no SDK.
- To add or fix a paragraph later, use `lesson_edit` (`replace`, or `text` for
  wording) rather than rewriting the lesson.

---

## Game lessons

A game is a front-end application — plan, structure and test it as one
(topic `craft`: architecture, the quality bar, verification). This section
adds what is specific to games. It is a complete, self-contained,
mobile-responsive HTML document in `body.html_or_data` — or, built as a
local file, uploaded with `media_put({ localFile: true })` and set with
`body.ref: { libraryPath }` (topic `local_dev`). It runs in a sealed sandbox (no access to the page around
it, no cookies; browser storage only lasts for the visit).

**Enforced by the server:** a game must call `await LMS.init(...)` when it
loads and `await LMS.complete({ score, maxScore })` (integers) when it ends —
that is how it is marked complete and its score reaches the course. A game
without them is refused. The server adds `<script src="/js_sdk.js"></script>`
if you leave it out, and replaces `CONTENT_ID_PLACEHOLDER` with the lesson id.

Structure every game as: clear instructions → a start button → gameplay → a
visible replay option → the final score shown against the maximum. A replay
is a new run in your own `state`; don't call
`LMS.reset()` for it — that also marks the lesson incomplete and clears its
score, so it is only for a deliberate "erase my progress".

- Styling: Tailwind is available with
  `<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>`,
  or link the course's shared stylesheet (topic `engines`).
- Never keep progress in `localStorage` / `sessionStorage`: it does not follow
  the learner to another device.

**Cross-device resume is opt-in.** Save and restore the learner's progress
(`LMS.save` / `LMS.load` / `LMS.isResume`, restoring the bookmark from
`LMS.getLocation`, `LMS.onExternalChange`) **only when the course creator
asks for it** — "let learners continue where they left off", "resume on another
device", "save their progress". Otherwise leave it out: the lesson starts
fresh each time it is opened. Not sure? Leave it out and mention in your reply
that it can be added. When asked, add save/restore as in topic `sdk` and offer to
continue when `LMS.isResume()` is true.

```html
<script src="/js_sdk.js"></script>
<script>
  async function boot() {
    await LMS.init({ contentId: 'CONTENT_ID_PLACEHOLDER' });
    render();
  }
  // at the end of a game:
  // await LMS.complete({ score, maxScore });
  boot();
</script>
```

---

## Interactive lessons (simulations)

An interactive lesson (`type: "interactive"`) is a front-end application —
plan, structure and test it as one (topic `craft`). It is a practical
HTML/CSS/JS app — a simulation, a lab, a stepper, an explorable explanation —
in `body.html_or_data` (a local file: `media_put({ localFile: true })` + `body.ref: { libraryPath }`).
Use it when the user asks for a simulation or
interactive content; use `game` when they ask for a game.

- Complete, self-contained and mobile-responsive. Same sandbox as games.
- It is marked complete when the learner opens it, so the SDK is optional:
  - **Report progress** when the lesson has a sense of position or questions:
    `await LMS.init()`, `LMS.setLocation()` as the learner moves on,
    `LMS.setProgress(fraction)` as they advance, and
    `await LMS.complete()` at the end (topic `sdk`).
  - **Skip it** for a single-screen explainer or a visualisation the learner
    only looks at.
- The server adds the SDK script and the lesson id for you, and warns when a
  lesson saves progress without ever restoring it.
- Share styles and helpers with the course's other lessons (topic `engines`).

**Cross-device resume is opt-in.** Save and restore the learner's progress
(`LMS.save` / `LMS.load` / `LMS.isResume`, restoring the bookmark from
`LMS.getLocation`, `LMS.onExternalChange`) **only when the course creator
asks for it** — "let learners continue where they left off", "resume on another
device", "save their progress". Otherwise leave it out: the lesson starts
fresh each time it is opened. Not sure? Leave it out and mention in your reply
that it can be added. When asked, also `LMS.save({...})` answers and simulation
state and restore them on load (topic `sdk`).

---

## Assessment lessons (quizzes and forms)

An assessment's body is `body.assessment: { questions, config }`, graded on
the server. Learners' in-progress answers are saved automatically.

Each question: `{ type, title, description?, required?, score?, settings }`.
Types: `single_choice`, `multiple_choice`, `yes_no`, `dropdown` (use
`settings.choices: [{ id, value, isCorrect }]`), `match_following`
(`settings.matchPairs: [{ id, left, right }]`), `short_text`, `long_text`,
`number` (`settings.correctAnswer` when it is graded), `file_upload`
(`settings.acceptTypes`), `thank_you`. `settings.answerExplanation` (HTML)
is shown after answering. Ids are generated when you leave them out.

`config`: `isQuizMode` (true = graded quiz with a score; false = a form) and
`thankYouConfig: { title, message, buttonText?, showScore?, showConfetti?, minScore? }`.

To change an existing assessment, `lesson_get` it (`view: "outline"` lists the
questions with their ids) and send `lesson_edit` ops — several in one call:

```json
{ "lessonId": "…", "baseVersion": 3, "ops": [
  { "question": { "add": { "questions": [ { "type": "single_choice", "title": "…", "settings": { "choices": [ … ] } } ] } } },
  { "question": { "update": { "id": "q-id", "question": { "title": "Better wording" } } } },
  { "question": { "remove": { "id": "other-id" } } },
  { "config": { "isQuizMode": true } }
] }
```

`add.index` inserts at a position (0 = first; default: the end). An update
only changes the fields you send.

---

## Role-play lessons (AI tutors)

A role-play is an AI tutor that plays a part, runs a scenario, asks
activity questions and grades the learner. Send
`body.rolePlay: { instructions, initialMessage }`:

- `instructions` — the tutor's system prompt. Start with "You are a [role], an
  AI tutor that helps learners with [topic]." Describe its personality, how it
  teaches, how it asks questions and how it assesses, specific to the topic.
  End by telling it to ask at least 2 assessment questions and score the
  learner.
- `initialMessage` — the tutor's first line, in character, warm and specific
  (e.g. "Hi! I'm Ms. Parker, your science teacher. Today we're exploring how
  plants make their own food. Ready?").

At run time the platform records each answer and the final grade, and resumes
an unfinished activity on any device — you don't implement any of that. To
change one sentence of the instructions use `lesson_edit` `replace`.

---

## Video lessons

A video lesson is HTML like an ebook (topic `ebook`) built around one or
more videos: `<video data-lexical-url="VIDEO_URL"></video>`, with notes,
key points or a summary as normal HTML around it.

- From just a URL: `lesson_write` with `type: "video"` and
  `body.ref: { url }` creates the lesson with that video embedded; add notes
  later with `lesson_edit`.
- A video file the user gives you: upload it with `media_put` — `localFile: true` (a file
  on your machine) or `sourceUrl` and use the returned URL.
- Only embed URLs you were given or uploaded. Never base64 video.

---

## The lesson SDK (progress and resume)

HTML lessons talk to LetLMS through `/js_sdk.js`, which exposes `LMS`. State
is stored on the server against the signed-in learner. The lesson can't reach
the page around it or any other API.

**Always (games):** `LMS.init` on load and `LMS.complete` at the end, so the
lesson is marked complete and scored. `setLocation`, `setProgress` and
`recordInteraction` feed the course reports — use them where the lesson has
a sense of position or questions.

```html
<script src="/js_sdk.js"></script>
<script>
  async function boot() {
    await LMS.init({ contentId: 'CONTENT_ID_PLACEHOLDER' });
    render();
  }
  // at the end of a game:
  // await LMS.complete({ score, maxScore });
  boot();
</script>
```

**Cross-device resume is opt-in.** Save and restore the learner's progress
(`LMS.save` / `LMS.load` / `LMS.isResume`, restoring the bookmark from
`LMS.getLocation`, `LMS.onExternalChange`) **only when the course creator
asks for it** — "let learners continue where they left off", "resume on another
device", "save their progress". Otherwise leave it out: the lesson starts
fresh each time it is opened. Not sure? Leave it out and mention in your reply
that it can be added. With it, a learner can stop on a laptop and continue on a
phone. **Never use localStorage / sessionStorage for progress** — it does not follow
the learner to another device.

```html
<script src="/js_sdk.js"></script>
<script>
  let state = { /* your own default state */ };

  async function boot() {
    await LMS.init({ contentId: 'CONTENT_ID_PLACEHOLDER' });
    if (LMS.isResume()) {
      state = LMS.load() || state;   // whatever you last passed to LMS.save()
      goTo(LMS.getLocation());       // your own bookmark string
    }
    render();
  }
  boot();
</script>
```

Use the literal `CONTENT_ID_PLACEHOLDER`; the server puts the real id in.

| Call | Purpose |
| --- | --- |
| `await LMS.init({ contentId })` | Open the session. Await it once, first. |
| `LMS.isResume()` | True if the learner has been here before. |
| `LMS.load()` | The object you last passed to `save()`, or null. |
| `LMS.save(obj)` | Persist your state (debounced — call it freely; no need to await). |
| `LMS.setLocation(str)` / `LMS.getLocation()` | Bookmark of where the learner is; reports group learners by it. |
| `LMS.setProgress(0..1)` | Fraction complete. |
| `LMS.setScore(score, maxScore)` | Record a score without finishing. |
| `LMS.recordInteraction({ id, type, learnerResponse, correctResponse, result })` | Log one answer. Stored **per id**: recording the same id again updates that entry (newest values win), so a retry under the same id erases the miss. Use one id per attempt (`q3-try2`) when every attempt matters. |
| `LMS.getInteractions()` | Past answers. |
| `await LMS.complete({ score, maxScore })` | Mark finished (score optional outside games). |
| `LMS.reset()` | Erase saved state, completion and score (a deliberate "start over", not a replay). |
| `LMS.onExternalChange(fn)` | Another device moved ahead: inside `fn` re-read `LMS.load()` / `LMS.getLocation()` and re-render (don't parse `fn`'s argument). |

**Keep your own record of attempts.** Anything the app shows the learner later
(misses on an end screen, a review of wrong answers, streaks) belongs in your
`state` (saved with `LMS.save(state)` when the lesson resumes); don't
rebuild it from `LMS.getInteractions()`, which holds the latest entry per id,
for reporting.

**When resuming, save the position to resume at.** Once a question is answered, the saved
location must already point to the next one and the saved score must include
that answer — otherwise a resumed learner answers it twice. Save whenever
meaningful state changes (an answer, a level, a section read).

SCORM 1.2 (`window.API`) and 2004 (`window.API_1484_11`) shims are backed by
the same store for ported content; prefer `LMS` for new lessons.

---

## Course library: shared styles and engines

Lessons of a course share one look and one set of helpers, kept in the
course's **library** (build and test them locally first if you can — topic
`local_dev`) (private files only that course's lessons can load). Build
every game and interactive lesson this way, even the first one — later lessons
reuse it, which keeps the course consistent and every lesson shorter.

1. `media_get({ scope: "course-library", courseId })` — see what the course
   already has. Open a file with `media_get({ assetId })` to read its classes
   and functions.
2. No shared stylesheet yet? Save one first:
   `media_put({ scope: "course-library", courseId, path: "course-theme.css", text })`
   — or, if you wrote it as a local file, `localFile: true` with the same
   `path` and run its `curl` command (never paste a local file's text) — colour variables, typography, layout, cards, buttons, a score panel,
   correct / wrong states. Add `lesson-kit.js` (exposing `window.LessonKit`)
   when helpers fit more than one lesson: shuffling, scoring, feedback. A
   larger reusable piece (a quiz runner, a simulation core) is an **engine**:
   `engines/<name>.js`.
3. Link them in each lesson with the exact returned `url`, after the SDK:
   `<link rel="stylesheet" href="URL">`, `<script src="URL"></script>`. Keep only
   that lesson's own layout and logic inline.
4. A lesson needs something the shared files lack? Add it to the shared file —
   `media_get` it, then `media_put({ assetId, text, baseVersion })` (a local
   copy: `media_put({ localFile: true, assetId, baseVersion })`); the URL stays the same, so every lesson gets the new version. Keep what other
   lessons use.

Write every URL out in full (one assembled in script at run time won't load),
and reference each file by its own URL — relative imports between library
files don't resolve. Library files work only inside the course's lessons, not
on the sales page. Each lesson still makes its own `LMS.init` /
`LMS.complete` calls. A library HTML file can also be a lesson body:
`lesson_write` with `body.ref: { libraryPath }`.

---

## More topics — read with `guide({ topic })` when the task needs them

- `sales_page` — The public course page: variables, theme and the HTML rules.
- `analytics` — Answering 'how are learners doing' questions with analytics_query.
- `media` — Uploading, organising and deleting files.

---

## Tools

Each tool's description and arguments come with the tool itself;
`guide({ topic: "index" })` has the full catalogue.

- **Docs:** `load_skill`, `guide`
- **Course authoring:** `course_list`, `course_get`, `course_save`, `course_delete`, `outline_apply`, `lesson_get`, `lesson_write`, `lesson_edit`, `lesson_delete`, `sales_page_get`, `sales_page_write`
- **Media and course library:** `media_get`, `media_put`, `media_delete`
- **Templates and cloning:** `template_search`, `course_clone`
- **Analytics:** `analytics_query`
- **Members, enrolments and groups:** `member_list`, `member_invite`, `member_remove`, `enrollment_add`, `group_list`, `group_save`, `group_delete`, `group_add_members`, `group_add_courses`
- **Portal settings:** `portal_get`, `portal_update`
