Joel Stevick

Production RAG, line by line · index.ts, createApp's fetch, route() and ask()'s two renderings · stage 5 of 6

Worker router

demo/src/index.ts is the Worker's entry point. It calls createApp with a function that builds the model clients from the Worker's bindings (properties of env for D1, Workers AI, Vectorize and the other resources declared in wrangler.toml) on each request. app.ts declares the bindings the runtime injects (Env), each demo account's allowance (LIMITS), the account's row the routes read (Demo) and the options that configure the ask (Options). Every request enters createApp's fetch, which calls route(). route() checks method and path in a fixed order: first the site's own /internal calls, then the MCP server and OAuth paths, then the visitor's routes, which look up the visitor's demo account by the X-Demo-Key header. A demo account is one visitor's row in the demos table, one per verified email address; it owns their files, chunks, Vectorize namespace (named by its id) and questions, and the code calls it a demo. X-Demo-Key carries the account's access key, which the browser keeps in the demo cookie; the table stores only the key's SHA-256 hash. POST /api/files goes to upload(), where Ingestion begins. POST /api/ask goes to ask(), which runs ASK 1 and 2 and then creates answering(), an async generator. ask() renders the generator's events either as one JSON body or as server-sent events through a TransformStream. Every function downstream receives env and models as arguments, so the tests run the same code with scripted models.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/app.ts280 / 280 lines on this page explainedlines 1-40,58-70,260-264,462-469,505-534,538-547,558-681,1064-1113 of 1124; the rest are on other stage pages
demo/src/index.ts16 / 16 lines on this page explainedevery line of the file
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo/src/index.ts The deployed Worker's entry point (main in wrangler.toml), all 16 lines.

Module scope

module scope · lines 1–8View on GitHub

The licence, the header comment and the imports.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under the MIT licence. Licence scanners read the SPDX line.

// The deployed demo Worker: Claude on Joel's key, bge-m3 through Workers AI, and// the demo's own Vectorize index. The routes are in app.ts.

What this file is Never runs

WhatThe comment says this is the deployed Worker: Claude on the owner's API key, bge-m3 on Workers AI, and the demo app's own Vectorize index. The routes are in app.ts.

WhyThis file holds only the connections to real services. Everything testable is in app.ts, which never imports a concrete model client.

import { createApp } from './app'import { claudeFor, claudeStreamFor, embedFor, vectorsFor } from './models'

Imports Module load

WhatcreateApp from app.ts, and the four client factories from models.ts: claudeFor, claudeStreamFor, embedFor and vectorsFor.

WhyNo other file in demo/src imports the factories, so the test suite can give createApp scripted models (tests/support/scripted.ts). The one test that runs the real clients stubs fetch, so no test calls a paid API.

default export

module scope · lines 9–16View on GitHub

The Worker object: the result of createApp, given a function from bindings to model clients.

Calls createApp(): fetch claudeFor() Model clients claudeStreamFor() Model clients embedFor() Model clients vectorsFor() Model clients

// Each request gets its models built from the Worker's bindings and secrets.export default createApp((env) => ({

The Worker's default export Module load

WhatAt module load, createApp is called once with an arrow function, which becomes its modelsFor parameter, and with no Options, so options is {} and widening is on. createApp returns { fetch, scheduled }, and the module exports that object as default.

WhyThis is the ES module Worker format: the runtime calls the default export's fetch for each request and its scheduled for each cron trigger. The arrow function does not run at module load, because the runtime passes env only to the handlers. The models are therefore built inside each handler.

  claude: claudeFor(env.ANTHROPIC_API_KEY),  stream: claudeStreamFor(env.ANTHROPIC_API_KEY),  embed: embedFor(env.AI),  vectors: vectorsFor(env.VECTORS),}))

The four clients, from bindings Query time

WhatThe arrow function runs on every request, whatever the route, and in the daily scheduled job. claude and stream use the ANTHROPIC_API_KEY secret, embed wraps the AI binding (bge-m3), and vectors wraps the VECTORS binding.

WhyEach factory degrades instead of failing. Without its binding, embedFor or vectorsFor returns undefined, and the demo app searches by keywords alone. Without the key, claude rejects on every call and stream throws on its first read, and their callers take their fallbacks. Building the clients only creates closures over the bindings, so doing it per request costs nothing.

embedding model: @cf/baai/bge-m3 (EMBEDDING_MODEL, models.ts)

demo/src/app.ts The demo Worker: its header comment, imports, Env, LIMITS and the Demo type (the account's row); upload()'s doc comment and signature; Options and AskEvent; ask() without ASK 1 and 2, which have their own stages; strip(); the start of answering(); and route() with createApp's fetch handler.

Module scope

module scope · lines 1–26View on GitHub

The licence, the header comment and the imports.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under the MIT licence. Licence scanners read the SPDX line.

/** * The demo chatbot's routes. Reached only through the site's Pages Functions * (the DEMO service binding): `/api/*` from functions/api/demo/[[path]].ts, * which forwards the visitor's cookie as X-Demo-Key; the MCP server, its OAuth * endpoints, the discovery documents and the document store (MCP_PATHS in oauth.ts) * from functions/_lib/demo-mcp.ts; and `/internal/*` (creating, finding and opening * demos, and the admin reads), which the site's own functions call, outside this * repository, and which no proxy in it forwards to. *

Who calls the Worker Never runs

WhatThe routes are reached only through the site's DEMO service binding. functions/api/demo/[[path]].ts forwards /api/*, with the access key from the visitor's demo cookie as X-Demo-Key. functions/_lib/demo-mcp.ts forwards the MCP server, its OAuth endpoints, the discovery documents and the document store (MCP_PATHS in oauth.ts). The site's own functions call /internal/* (creating, finding and opening demo accounts, and the admin reads), and no Pages Function in this repository forwards to those routes.

WhyThe Worker has no public URL (workers_dev = false and preview_urls = false in wrangler.toml), so only the site can call the /internal routes, and they need no key. The site functions that call them (sign-up and the admin pages) belong to joelstevick.com and are not in this repository.

 * Every question is recorded in `questions`. When the site sends X-Demo-Keep: 1 (the visitor * may be recorded), the question outlives the 10-day purge and each uploaded page's text is * archived in `archived_pages`; both are deleted after 25 months. */

What is recorded, and for how long Never runs

WhatEvery question is recorded in questions. When X-Demo-Keep is 1, the question outlives the 10-day idle purge and each uploaded page's text is archived in archived_pages; both are deleted after 25 months.

WhyThe comment states the retention policy in one place. IDLE_DAYS, KEEP_MONTHS, purge() and expire() implement it.

import { checkUnits, uncited, units, type Counts, type RawUnit, type UnitKind } from './check'import { chunkPage } from './chunks'import { ANSWER_CHUNKS, answer, rerank, type Models } from './models'import { fuseKeywordAndVector, type Chunk } from './retrieval'import { widen } from './widen'

The pipeline's modules Module load

WhatThe citation check (check.ts), the page chunker (chunks.ts), the model client interface with rerank and answer (models.ts), keyword search and fusion (retrieval.ts), and neighbour widening (widen.ts). Names marked type are erased at compile time.

Whyapp.ts does the input and output (D1, Vectorize, HTTP). check.ts, chunks.ts, retrieval.ts and widen.ts are pure functions of plain data. rerank and answer in models.ts call Claude only through the Models client passed to them, so the tests run them with scripted models.

import { oauthRoute, grantsRoute, revokeGrants, appsOf, MCP_PATHS } from './oauth'import { forgetHits } from './mcp'import { dailyHealth, healthRoute } from './health'

MCP, OAuth and health Module load

WhatThe OAuth and MCP routes and the grant helpers (oauth.ts; a grant is the access a visitor approved for one connected app), forgetHits, which deletes old MCP rate counters (mcp.ts), and the daily health job and its route (health.ts).

Whyoauth.ts, mcp.ts and health.ts each import from app.ts, which makes an import cycle. ES modules resolve it because every use of an imported binding is inside a function that runs after all the modules have loaded.

Env

interface · lines 27–37View on GitHub

The bindings and secrets the Workers runtime passes to every handler.

export interface Env {  DB: D1Database  MAILER?: Fetcher  AI?: Ai  VECTORS?: VectorizeIndex  ANTHROPIC_API_KEY?: string

The bindings Type only

WhatDB is the D1 database and is required. MAILER (a service binding to the mailer Worker), AI (Workers AI), VECTORS (the Vectorize index) and ANTHROPIC_API_KEY (a Worker secret) are optional.

Whywrangler.toml declares each binding, and the runtime injects them into env. Because every binding except DB is optional, the tests and a partial deployment can run. Without AI or VECTORS the demo app uses keyword search alone, without MAILER no first-upload email is sent, and without the key every Claude call fails into its fallback.

  /** '0' turns the daily canary off (demo/src/health.ts); anything else, or unset, leaves it on. */  CANARY_ENABLED?: string  /** Where the OAuth library keeps the MCP server's clients, grants and tokens (demo/src/oauth.ts). */  OAUTH_KV?: KVNamespace}

The canary switch and the OAuth store Type only

WhatCANARY_ENABLED set to '0' turns the daily canary off. OAUTH_KV is the KV namespace (a Cloudflare key-value store) where the OAuth library stores the MCP server's clients, grants and tokens.

WhyWithout OAUTH_KV the MCP routes answer 503, the page's Connected apps reports the feature as unavailable, and purge has no grants to revoke. The rest of the demo app works as before.

LIMITS

constant · lines 38–40View on GitHub

One demo account's allowance.

/** One demo's allowance: questions asked, PDFs, pages, and characters of text across all its files. */export const LIMITS = { asks: 10, files: 5, pages: 300, chars: 500_000 }

10 questions, 5 PDFs, 300 pages, 500,000 characters Module load

Whatasks caps the questions per demo account. files, pages and chars cap the total of all of an account's uploads.

WhyThe upload check (INGEST 3) enforces files, pages and chars in one conditional UPDATE, and the reservation (ASK 2) enforces asks. The caps bound model spend and keep keyword search cheap, because BM25 scores every chunk on every question. session() also returns LIMITS in the page's state, but only the Worker enforces them.

asks: 10files: 5pages: 300chars: 500_000

Demo

interface · lines 58–70View on GitHub

The columns of a demo account's row the routes read.

/** The columns of a demo's row the routes read: its id, what it has used, and who it is for. */export interface Demo {  id: string  asks_used: number  files: number  pages: number  chars: number  company: string | null  contact: string | null  cleared_at: string | null}

The account's row Type only

Whatid (also the Vectorize namespace); asks_used, files, pages and chars (usage against LIMITS); company and contact (for the first-upload email and the X-Demo-Email header); and cleared_at (set when the idle purge deleted the account's documents).

WhysignedIn selects exactly these columns and never key_hash or card_fingerprint, so the object passed to every route carries no secret. signedIn runs at the start of every visitor request, so the counts are a snapshot from the start of the request. The routes that change the counts check the limits again in SQL instead of against this object.

upload(): doc comment and signature

segment · lines 260–264View on GitHub

What upload() is for, and what it is given.

Called by route(): the visitor's routes canaryDemo() The canary

/** * Stores one PDF's extracted text: its file row, its chunks in D1 and their vectors in Vectorize. * The PDF itself never arrives; the browser reads it and sends only each page's text. */

What upload() stores Never runs

WhatThe doc comment says that one PDF's extracted text becomes a file row, chunks in D1 and their vectors in Vectorize. The PDF itself never reaches the Worker, only each page's text.

Whyupload() writes the file row first (INGEST 2), then claims room in the account's limits (INGEST 3), stores the chunks (5) and writes the vectors (6). When INGEST 3 finds no room, the file row is deleted. When storing the chunks fails, everything this upload wrote is deleted and its room given back. When embedding or indexing fails at INGEST 6, the error is only logged, and the file stays searchable by keyword.

export async function upload(request: Request, env: Env, models: Models, demo: Demo): Promise<Response> {

Signature Ingestion

Whatupload takes the forwarded request, the Worker's bindings (env), the model clients (models) and the demo account's row the router found, and returns a Response.

WhyThe router passes in a demo account it has already authenticated, so upload never reads the key. index.ts builds models from env on each request, so a missing AI or VECTORS binding appears here as models.embed or models.vectors being undefined. upload is exported so that health.ts can call it directly for the daily canary's upload.

Options

interface · lines 462–469View on GitHub

The options that configure the ask.

/** How the ask is assembled. `widen: false` turns widening off; it is on by default. */export interface Options {  widen?: boolean  /** The models are scripted (the tests and the canary's tests). */  scripted?: boolean}

Options: widen and scripted Type only

Whatwiden: false turns off neighbour widening at ASK 5; widening is on when the field is unset. scripted marks the models as scripted.

WhycreateApp receives Options once and passes them to every route that asks a question (the page's /api/ask and the MCP server) and to the daily health job. The tests can therefore run the same pipeline with and without widening (demo/tests/demo.test.ts). The tests set scripted (demo/tests/health.test.ts), but no code in demo/src reads it.

AskEvent

type · lines 505–534View on GitHub

Every event the ask can yield: the contract between the pipeline and both renderings.

/** * What the ask says as it goes. The ask is written once, as an async * generator of these events (`answering` below), and rendered two ways from that one sequence: * *   - as server-sent events, when the page asks with `Accept: text/event-stream`: each event is *     written to the response the moment it is yielded, so the first checked sentence reaches the *     browser while the model is still writing the rest; *   - as one JSON body, for every other caller (the eval harness, the daily canary, a plain *     POST): the same events are drained to their end and the last one becomes the body. *

One pipeline, two renderings Never runs

WhatThe doc comment states the design. The ask is written once, as an async generator of these events, and rendered either as server-sent events (when the request's Accept contains text/event-stream) or as one JSON body built from the last event.

WhyStreaming lets the first checked sentence reach the browser while the model is still writing. The JSON rendering keeps the route's original response for callers that read it whole: the eval harness (evals/run.mjs), the daily canary (health.ts) and any plain POST. When the page reloads, its earlier answers come from session(), which reads the questions table and never calls ask().

 * The events, in the order they can occur: *   stage     the ask has moved on: retrieving the passages, reranking them, or writing the answer; *   unit      one checked sentence (or a list's lead-in, or one list item), released to the page, *             with the ids of the passages it cites; *   stopped   a later unit failed its check (or the model failed partway): what was shown stays, *             and nothing more will come; *   done      the whole answer, as the JSON body has always carried it, plus the timings; *   fallback  nothing was shown: the "couldn't find that" line, with the check's reason; *   error     the model failed before anything was shown (the question is given back), or the ask threw. * Exactly one of done, fallback or error ends every ask. */

The events, in the order they can occur Never runs

WhatThe comment lists the events: stage (retrieving, reranking, writing); unit (one checked sentence, lead-in or list item, with the passage ids it cites); stopped (a later unit failed); and the three terminal events, done, fallback and error.

WhyThe comment ends with an invariant: exactly one of done, fallback or error ends every ask. Because of it, the page treats a stream that closes without one of them as cut off (demo.html line 492). The error line names both ways an ask can fail before an answer. In the first, the answer model fails inside the generator, and the generator gives the question back. In the second, an exception escapes the generator, and the pump sends it as the last event (line 623) without giving the question back.

export type AskEvent =  | { type: 'stage'; stage: 'retrieving' | 'reranking' | 'writing' }  | { type: 'unit'; kind: UnitKind; text: string; sources: string[] }  | { type: 'stopped'; reason: 'empty' | 'uncited' | 'ungrounded' | 'overlong' | 'trouble' }

The stage, unit and stopped events Type only

WhatA discriminated union on type. unit carries kind (lead, sentence or item; UnitKind from check.ts), the text with its citation markers removed, and sources, the cited chunk ids. stopped carries the check's reason, or trouble when the model failed partway.

WhyThe type field becomes the SSE event name, and the other fields become the data JSON (strip() removes type). TypeScript narrows on event.type in both renderings, so a misspelt field is a compile error.

stopped reasons: empty, uncited, ungrounded, overlong, trouble

  | { type: 'done'; answer: string; items?: string[]; sources: unknown[]; found: true; left: number; first_ms: number | null; ms: number }  | { type: 'fallback'; answer: string; found: false; refused?: string; left: number }  | { type: 'error'; error: string; left: number }

The done, fallback and error events Type only

Whatdone carries the whole answer (answer, optional items, sources, found: true, left) plus first_ms and ms. fallback carries the "couldn't find that" line, found: false, an optional refused reason and left. error carries the message and left.

Whydone and fallback carry the fields the JSON body always had, so the JSON rendering builds its body from the last event with strip(). It adds stopped to a done, and sources: [] and first_ms: null to a fallback. found has a literal type, true or false, which distinguishes the two. first_ms, the time to the first released unit, is the latency that streaming exists to reduce.

ask(): ASK 1–2, then JSON or server-sent events

segment · lines 538–639View on GitHub

Parses the body, runs ASK 1 and 2, creates the answering generator, and renders its events as JSON or as server-sent events.

Called by route(): the visitor's routes build(): TOOL 2 ask_documents runCanary() The canaryCalls answering(): the generator's contract, timer and record() strip() about() Shared helpers json() Shared helpers randomKey() Shared helpers

/** * Answers one question from the demo's documents: reserve one of its questions, retrieve, rerank, * widen, then stream the answer, checking each sentence or list item in code as it completes and * releasing it only when it passes; record the outcome. Validation and the limit answer in JSON * before anything is streamed. */

What ask() does Never runs

WhatThe doc comment lists the steps: reserve, retrieve, rerank, widen, then stream the answer, checking each sentence or list item in code and releasing it only when it passes, and record the outcome. Validation and the limit answer in JSON before anything is streamed.

WhyThe last sentence is the contract the page relies on. Every refusal is a JSON body with its own status, and only an accepted question can produce a stream.

export async function ask(request: Request, env: Env, models: Models, demo: Demo, options: Options, ctx?: ExecutionContext): Promise<Response> {

Signature Query time

WhatTakes the request, the bindings (env), the model clients, the signed-in demo account's row, the Options (widen, scripted) and an optional ExecutionContext, and returns a Response.

Whyctx is optional for two reasons. The router's fetch takes an optional ctx, and the tests call createApp's fetch without one. The canary also calls ask() in process without one (health.ts 235). The MCP tool ask_documents passes its own (mcp.ts 321). ask() uses only ctx.waitUntil, for the stream's pump.

  // The page's request body; a body that is not JSON reads as empty.  const body = (await request.json().catch(() => ({}))) as { question?: unknown }

Parse the body Query time

Whatrequest.json() is awaited, and a body that is not JSON is caught and read as {}. question is typed unknown.

WhyA body that is not JSON, or JSON without a string question, becomes an empty question and gets ASK 1's 400. The exception is a body of the literal null: it parses, then reading body.question throws a TypeError, and createApp answers 500.

  // The question's id is drawn now, before the row exists, because a streamed response sends its  // headers (X-Question-Id among them) before the answer is known; the row is inserted at the end  // under this same id.  const id = randomKey(12)

The question's id, drawn early Query time

WhatrandomKey(12) returns 12 random bytes from crypto.getRandomValues as unpadded URL-safe base64, 16 characters. The value becomes the primary key of the questions row inserted at the end of the ask.

WhyA streamed response sends its headers, X-Question-Id among them, before the answer exists, so the id cannot come from the insert. The site's Pages Function uses the header to record the ask's event without waiting for the body.

12 random bytes → 16 base64url characters

  // Calling an async generator function runs none of its body: `events` is a handle on the ask,  // and the ask only proceeds as something iterates it (`for await` below). Both renderings  // iterate the same object, so there is one pipeline, never two.  const events = answering(request, env, models, demo, options, question, LIMITS.asks - reserved.asks_used, id)

Create the generator Query time

Whatanswering() is called with the question, the questions left after this one (LIMITS.asks minus reserved.asks_used) and the id. Calling an async generator function runs none of its body; it returns an AsyncGenerator object.

WhyWhichever rendering iterates this one object drives the whole pipeline, so the ask has a single implementation. At this point there has been no retrieval, no model call and no questions row. The only D1 write so far is ASK 2's reservation.

  if (!(request.headers.get('Accept') ?? '').includes('text/event-stream')) {    // JSON: the same events, drained to the end, and the last one shaped into the body the    // route has always answered with (`answer`, `items`, `sources`, `found`, `left`, `refused`),    // plus `first_ms` and, when the answer stopped partway, `stopped` with its reason. A `unit`    // event is skipped here: the body carries the whole answer at the end.

No event stream asked for: JSON Query time

WhatIf the Accept header does not contain text/event-stream, the ask is answered as one JSON body: answer, items, sources, found, left and refused, plus first_ms, ms and, when the answer stopped partway, stopped.

WhyThe eval harness (call() in evals/run.mjs, which sends no Accept header) and the canary score whole answers, so they need the final body, not the frames. This branch skips unit events because done repeats the whole answer.

    let result: Record<string, unknown> = {}    let status = 200    let stopped: string | null = null    let recorded = false

The body being built Query time

Whatresult starts as {}, status as 200, stopped as null and recorded as false.

WhyThe loop that follows fills each of them from the events. result stays {} only if the generator ends without a terminal event, which its invariant rules out.

    // Each event fills in the body; the last outcome wins.    for await (const event of events) {      if (event.type === 'stopped') stopped = event.reason      else if (event.type === 'done') result = { ...strip(event), ...(stopped === null ? {} : { stopped }) }      else if (event.type === 'fallback') result = { ...strip(event), sources: [], first_ms: null }      else if (event.type === 'error') (result = strip(event)), (status = 503)      else if (event.type === 'recorded') recorded = event.ok    }

Drain the generator Query time

Whatfor await pulls every event. stopped keeps its reason. done becomes the body, with stopped added if one came. fallback becomes the body with sources: [] and first_ms: null. error becomes the body with status 503. The recorded sentinel says whether the row was written.

WhyDraining runs the whole pipeline, the questions insert included, before the response is built. fallback gets sources and first_ms so that a client can read both fields from either kind of body. 503 marks a failure of the answer model, after which the question was given back. This loop does not catch an exception thrown by the generator. On a request through the router, the exception propagates to createApp's fetch handler, which returns a 500 JSON body.

    // X-Question-Id names the row to the site only when the row was written, as before.    return json(status, result, about(demo, recorded ? id : undefined))  }

Return the JSON Query time

Whatjson(status, result, about(demo, …)) returns the body with X-Demo-Id, X-Demo-Email when the contact has an address, and X-Question-Id only when the row was recorded.

WhyThe site records an ask event only when X-Question-Id is present. In the JSON rendering, a question whose row failed to insert is therefore not reported as asked. A stream always carries X-Question-Id, so its event is recorded whether or not the insert succeeds. The site's Pages Function deletes these headers before the response reaches the browser.

  // Server-sent events. The response is the readable side of a TransformStream, returned at once  // with the headers; the writable side is fed by `pump`, which iterates the generator and writes  // each event as `event: <type>\ndata: <json>\n\n`, the text/event-stream framing the page's  // reader (demo.html, `events`) parses (evals/trace.ts reads Anthropic's). Nothing is buffered:  // each write reaches the browser as soon as the Worker has made it.  const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()  const writer = writable.getWriter()  const encoder = new TextEncoder()

Server-sent events through a TransformStream Query time

WhatAn identity TransformStream of bytes. Its readable side becomes the Response body, and one writer writes to its writable side. A TextEncoder encodes each frame as UTF-8.

WhyA Worker can return a Response whose body is still being written. Returning the readable side sends the headers immediately, and each later write to the writable side goes to the client when it is made. The comment mentions evals/trace.ts because it parses the same text/event-stream framing. That parser reads the Anthropic Messages API stream inside the eval harness Worker, never this route's events.

The same idea, shown in the episode's own code: Wrapping the generator in a stream that becomes the response body From Streaming for RAG engineers, Ep 1: Async Generators: Streaming, Step by Step
  const pump = (async () => {    // `open` is whether the browser is still reading. Once a write fails (the visitor closed the    // tab, or the connection dropped) nothing more is written, but the generator is still run to    // its end below, so the ask is checked and recorded exactly as if they had stayed.    let open = true

Start the pump; open tracks the client Query time

Whatpump is an async arrow function that is called immediately (an IIFE), and its promise is kept. open records whether the client is still reading.

WhyThe IIFE starts the for await loop at once, and the loop runs answering() up to its first yield (the retrieving stage event) before ask() returns. From then on the pipeline runs concurrently with the response being sent. When the client disconnects, the writes stop, but the generator still runs to its end, so the question is checked and recorded exactly as if the client had stayed.

    // Writes one event in the text/event-stream format.    const send = async (type: string, data: Record<string, unknown>) => {      try {        await writer.write(encoder.encode(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`))      } catch {        // The visitor has gone: the rest of the ask still runs, so it is recorded.        open = false      }    }

One frame per event Query time

Whatsend writes one frame in the text/event-stream format: an event: line, a data: line and a blank line. A failed write sets open to false instead of throwing.

WhyJSON.stringify escapes newlines inside strings, so each event's data always fits on one data: line, which the page's parser assumes. A write fails when the client has disconnected, and catching the error keeps the pipeline running. The write is awaited, so a client that reads slowly holds the generator at its yield and events do not queue up in memory.

frame: event: <type>\ndata: <json>\n\n

    try {      // The `recorded` sentinel is for the JSON rendering only; the browser never sees it.      for await (const event of events) if (event.type !== 'recorded' && open) await send(event.type, strip(event))

Iterate and send Query time

Whatfor await pulls each event from the generator and, while open is true, sends it with strip(event) as its data. The recorded sentinel is never sent.

WhyThe recorded sentinel only tells the JSON rendering whether to set X-Question-Id, and the stream has already sent that header. After open becomes false, the loop still pulls every event, which drives the generator to its insert.

    } catch (error) {      // An exception out of the generator (D1 down, a bug) is what `createApp` turns into a 500      // for a JSON request; here the status went out long ago, so it is said as the last event.      console.error('demo: the request failed', error)      if (open) await send('error', { error: 'Something went wrong. Please try again in a minute.', left: LIMITS.asks - reserved.asks_used })    }

An exception becomes the last event Query time

WhatIf the generator throws (D1 unavailable, a bug), the error is logged and, if the client is still reading, sent as an error event with a generic message and left.

WhyThe 200 status went out with the headers, so the failure cannot become a 500. An error event is the only way to tell the page, which shows its message. left here is the count after this question, because this path does not give the question back, unlike a model failure inside the generator. The page does not update its count from an error event.

    // Closing the writer ends the stream, which is how the page knows the ask is over.    if (open) await writer.close().catch(() => {})  })()

Close the stream Query time

WhatIf the client is still reading, the writer is closed (a rejection is ignored), and the IIFE ends.

WhyClosing the writable side ends the response body. The page's reader.read() then resolves with done: true (demo.html 404, 415), which tells the page the body has ended.

  // The pump outlives the `return` below. `waitUntil` tells the Workers runtime to keep the  // request alive until it settles, so the insert at the end of the ask is never cut off when  // the visitor leaves early; the tests call the app with no ctx (`wrangler dev` passes one), and  // there the promise simply runs.  ctx?.waitUntil(pump)

Keep the pump alive with waitUntil Query time

Whatctx.waitUntil(pump) registers the pump's promise with the Workers runtime. Without a ctx (the tests call createApp's fetch without one, and route() passes undefined to ask()), the promise runs on its own. The MCP tool ask_documents (mcp.ts 321), the one in-process caller that asks for a stream, passes its own ctx. The canary asks for JSON and never reaches this line.

WhyWithout waitUntil, the runtime may stop the request's work once the client disconnects, which could cut off the questions insert at the end of the ask. With it, the invocation stays alive until the pump settles. As the comment says, only the tests call the app without a ctx; wrangler dev passes a real ExecutionContext.

  // The X-Demo-* headers go out with the stream's headers, so the proxy can record its event  // before the body has ended; `no-store` keeps any cache from holding a stream.  return new Response(readable, { status: 200, headers: { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', ...about(demo, id) } })}

Return the stream at once Query time

WhatReturns a 200 Response over the readable side, with Content-Type: text/event-stream; charset=utf-8, Cache-Control: no-store and the X-Demo-* headers, X-Question-Id included.

WhyReturning now lets the headers go out while the pipeline runs. no-store stops any cache from storing the stream. The page and the MCP tool read the Content-Type to tell a stream from a JSON refusal.

Content-Type: text/event-stream; charset=utf-8Cache-Control: no-store

strip()

function · lines 640–645View on GitHub

An event's fields without its type.

Called by ask(): ASK 1–2, then JSON or server-sent events

/** An event's fields without its type, as the body or the event's data carries them. */function strip(event: { type: string }): Record<string, unknown> {  const { type: _type, ...rest } = event  return rest}

Drop the discriminant Query time

WhatObject rest destructuring copies every field except type into a new object.

WhyIn the stream the type is already on the event: line, so the data carries only the other fields. The JSON body never had a type field. Both renderings use this one function, so an event's data and the JSON body have the same shape.

answering(): the generator's contract, timer and record()

segment · lines 646–681View on GitHub

The generator's doc comment, its signature, the timer, and record(), which every outcome calls.

Called by ask(): ASK 1–2, then JSON or server-sent events answering(): ASK 6–7 Answer and check answering(): ASK 8 Answer with sources answering(): Between ASK 4 and 5 Whole documents and the empty poolCalls keeps() Consent and the archive via() Consent and the archive

/** * The ask after its question is reserved, as an async generator: every `AskEvent` in order, * ending in exactly one of done, fallback or error, then a `recorded` sentinel saying whether the * row was written (the JSON rendering uses it for X-Question-Id). * * Why a generator. The ask has to do two things at once: run the pipeline (retrieve, rerank, * read the model's stream, check each sentence, record the row) and tell the caller what has * happened so far, at the moment it happens. An async generator does both in one plain * sequence of steps: `await` where the pipeline waits on a service, `yield` where it has * something to say. The consumer (`ask` above) pulls the next event with `for await`; between * pulls the generator is suspended at its last `yield`, so a slow reader slows the ask rather * than piling up events. Nothing here knows whether it is being rendered as a stream or as JSON. * * The stages read in order, as the old `ask` did: ASK 3-4 retrieval, ASK 5 rerank and widen, * ASK 6-7 the answer written and checked a unit at a time, ASK 8 the answer with its sources. */

Why an async generator Never runs

WhatThe doc comment says the generator yields every AskEvent in order, exactly one terminal event, and then a recorded sentinel. It explains why the ask is a generator, which can await where the pipeline waits on a service and yield where it has something to report, in one sequence of statements.

WhyThe generator is pull-based. Between pulls it is suspended at its last yield, so the consumer sets the pace and events never accumulate in memory. The generator does not know whether its events are rendered as a stream or as JSON, so the same pipeline runs for every caller and every test.

The same idea, shown in the episode's own code: A server-side async generator that yields the model's stream From Streaming for RAG engineers, Ep 1: Async Generators: Streaming, Step by Step
async function* answering(  request: Request, env: Env, models: Models, demo: Demo, options: Options, question: string, left: number, id: string,): AsyncGenerator<AskEvent | { type: 'recorded'; ok: boolean }> {

Signature Query time

WhatTakes ask()'s request, env, models, the account's row (demo) and options (not ctx), plus the validated question, the questions left and the row id. It yields an AskEvent or {type: 'recorded', ok}.

WhyThe recorded sentinel is deliberately outside the AskEvent union. It is internal bookkeeping and never part of the protocol the page reads.

  // `started` times the whole ask for the record, and the first shown unit for `first_ms`.  const started = Date.now()

Start the clock Query time

Whatstarted is set to Date.now() when the generator first runs, which is when the consumer first pulls.

WhyIt times the whole ask (questions.ms) and the time to the first released unit (first_ms). In a Worker, Date.now() advances only across I/O, which is where all of this time is spent.

  // Every outcome is recorded with the id drawn above; a failure to record never costs the visitor the answer.  const record = async (row: { answer: string | null; sources?: unknown[]; checked?: boolean; fallback: string | null; first_ms?: number | null }) => {    try {      await env.DB.prepare('INSERT INTO questions (id, demo_id, question, answer, sources, checked, fallback, ms, first_ms, keep, via) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')        // `via` is 'mcp' or 'canary' for a question the MCP server or the canary asked (X-Demo-Via, which the page's proxy never forwards).        .bind(id, demo.id, question, row.answer, JSON.stringify(row.sources ?? []), row.checked ? 1 : 0, row.fallback, Date.now() - started, row.first_ms ?? null, keeps(request) ? 1 : 0, via(request)).run()      return true    } catch (error) {      console.error('demo ask: the question could not be recorded', error)      return false    }  }

record(): one row per question Query time

WhatInserts the questions row under the id drawn in ask(): the account's id, the question, the answer (or null), the sources as JSON, checked (1 or 0), the fallback reason, ms, first_ms, keep (whether X-Demo-Keep is 1) and via ('mcp', 'canary', or NULL for the page). It returns true, or logs an error and returns false.

WhyEvery outcome calls it once: no passages found, the model's failure, the fallback and the answer. A failed insert never costs the visitor the answer; its result goes into the recorded sentinel. keep decides whether the row survives the idle purge (IDLE_DAYS, 10 days). via comes from X-Demo-Via, a header that only in-process callers set ('mcp' from the MCP server, 'canary' from the canary). The site's Pages Function builds new headers and never forwards X-Demo-Via.

table: questions11 columns

route(): the site's calls and MCP

segment · lines 1064–1083View on GitHub

The routes that need no visitor key.

Called by createApp(): fetchCalls adminDemo() Consent and the archive adminDemos() Consent and the archive createDemo() Demo accounts and sessions golden() Consent and the archive healthRoute() Daily health oauthRoute(): RESOURCE Token validation and limits openDemo() Demo accounts and sessions whichDemos() Demo accounts and sessions

/** Sends each request to its handler: the site's own calls, the MCP server, then a visitor's routes. */async function route(request: Request, env: Env, models: Models, options: Options, ctx?: ExecutionContext): Promise<Response> {

Signature Query time

WhatTakes the request, the bindings, the model clients built for this request, the Options given to createApp, and the optional ExecutionContext.

Whyctx is optional because the tests call fetch without one. route() passes it to the routes that use waitUntil to keep work running after the response: the ask and the MCP server.

  // The path decides the route.  const url = new URL(request.url)  const { pathname } = url

Parse the URL Query time

WhatThe request URL is parsed once. pathname selects the route, and url is passed to the routes that read query parameters.

Whyroute() ignores the host and dispatches on path and method only. The /api/demo/* Pages Function calls the Worker with a placeholder host (https://demo/api/...). The MCP and OAuth paths arrive with the site's own URL. oauthRoute uses that URL's origin when it is the site's (or a local http://localhost run), and otherwise uses the fixed SITE origin.

  // The site's own calls first: creating and opening demos, and the /admin reads. The proxy never  // forwards /internal paths, so these need no key.  if (pathname === '/internal/demos' && request.method === 'POST') return createDemo(request, env)

Create a demo account Site request

WhatPOST /internal/demos goes to createDemo, before any key is checked.

Whyjoelstevick.com's sign-up code, which is not in this repository, calls it to create a visitor's demo account or give it a new access key. It needs no key because the Worker has no public URL and the /api/demo/* Pages Function forwards only four /api routes, so only the site can reach /internal.

  if (request.method === 'GET' && pathname === '/internal/admin/demos') return adminDemos(url, env)  if (request.method === 'GET' && pathname.startsWith('/internal/admin/demos/')) return adminDemo(decodeURIComponent(pathname.slice('/internal/admin/demos/'.length)), env)  if (request.method === 'GET' && pathname === '/internal/admin/golden') return golden(url, env)  if (request.method === 'GET' && pathname === '/internal/admin/health') return healthRoute(env)

The /admin reads Site request

WhatGET /internal/admin/demos lists demos. /internal/admin/demos/<id> opens one, with the id URL-decoded from the path. /internal/admin/golden exports kept questions as JSONL. /internal/admin/health returns the pipeline's daily health.

WhyThe site does the access control for these routes: their callers are joelstevick.com's admin routes, which are not in this repository. A malformed percent-escape in the id makes decodeURIComponent throw a URIError, and fetch's catch turns it into a 500.

  if (pathname === '/internal/demos/which' && request.method === 'POST') return whichDemos(request, env)  if (pathname === '/internal/demos/open' && request.method === 'POST') return openDemo(request, env)

Which engagements have demo accounts, and reopen one Site request

WhatPOST /internal/demos/which goes to whichDemos, which returns the engagement ids that have a live demo account, and POST /internal/demos/open goes to openDemo, which gives an engagement's newest live demo account a new access key.

WhyBoth are lookups by engagement id that only the site calls, so they come before the key check with the other /internal routes.

  // The MCP server and its OAuth endpoints (README.md, "The MCP server"): the site forwards these with its own URL.  if (MCP_PATHS.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`))) return oauthRoute(request, env, models, options, ctx)

The MCP server and OAuth MCP request

WhatA path equal to, or under, any MCP_PATHS prefix goes to oauthRoute with the models, options and ctx. The prefixes are /mcp/demo, /oauth, the two /.well-known/ OAuth discovery documents and /api/docs-store, the document store.

WhyThese callers carry an OAuth bearer token or are partway through authorization, and they have no demo cookie, so they are routed before the key check. Matching prefix + '/' instead of a bare prefix stops a path such as /oauthx from matching /oauth.

MCP_PATHS: /mcp/demo, /oauth, /.well-known/oauth-protected-resource, /.well-known/oauth-authorization-server, /api/docs-store

route(): the visitor's routes

segment · lines 1084–1100View on GitHub

Finds the visitor's demo account by the access key's hash and calls the route's handler.

Calls ask(): ASK 1–2, then JSON or server-sent events upload(): doc comment and signature grantsRoute() Listing and disconnecting apps json() Shared helpers remove() Removing a file session() Demo accounts and sessions signedIn() Shared helpers

  // Everything below is a visitor's route: the key the proxy forwards must name a live demo.  const demo = await signedIn(request, env)

The key's hash finds the account Query time

WhatsignedIn returns null at once, without a query, when no X-Demo-Key was sent. Otherwise it hashes the key with SHA-256 (hex) and runs SELECT id, asks_used, files, pages, chars, company, contact, cleared_at FROM demos WHERE key_hash = ? AND purged_at IS NULL.

WhyNothing in the request names an account id. Possession of the key is the only credential, and the table stores only its hash. key_hash is UNIQUE, so one indexed lookup finds at most one account. INGEST 3 checks the limits against the row's current values inside its UPDATE, because a concurrent upload may already have made this copy stale.

table: demosfilter: key_hash = sha256(key) AND purged_at IS NULL

  if (demo === null) {    // `expired` tells the page that a key it has is no longer good (re-keyed, or its demo purged by the old rule), as against no key at all.    return json(401, { error: 'signed out', expired: (request.headers.get('X-Demo-Key') ?? '') !== '' })  }

Signed out, or expired Query time

WhatWithout a live demo account the route answers 401 { error: 'signed out', expired }, where expired is true only when a key was sent.

WhyA key that matches no live demo account was replaced by a newer sign-in (createDemo and openDemo give an account a new key), belongs to an account purged under the old rule, or never existed. The page shows this case differently from having no key at all.

  // The visitor's own routes: the page's state, adding and removing files, asking, and connected apps.  if (pathname === '/api/session' && request.method === 'GET') return session(demo, env)  if (pathname === '/api/files' && request.method === 'POST') return upload(request, env, models, demo)  if (pathname === '/api/files' && request.method === 'DELETE') return remove(request, env, models, demo)  if (pathname === '/api/ask' && request.method === 'POST') return ask(request, env, models, demo, options, ctx)  if (pathname === '/api/grants' && (request.method === 'GET' || request.method === 'DELETE')) return grantsRoute(request, env, demo)

Dispatch on path and method Query time

WhatGET /api/session, POST /api/files (upload), DELETE /api/files (remove), POST /api/ask, and GET or DELETE /api/grants each go to their handler with the account's row.

WhyEvery handler from here on receives an authenticated demo account and scopes every read and write to demo.id: the D1 rows, and for /api/grants the grants in the OAuth store. An exception thrown in a handler such as upload() reaches createApp's fetch, which logs it and answers 500.

  // Any other path or method.  return json(404, { error: 'not found' })}

Anything else Query time

WhatAny other path or method answers 404 { error: 'not found' }.

WhyThe Pages Function's allow-list (ROUTES) already limits the paths to four. This line also refuses a wrong method, such as GET /api/files.

createApp(): fetch

segment · lines 1101–1113View on GitHub

createApp and the Worker object's request handler.

Called by default export app Traced demo app and /eval routes createApp(): scheduled The scheduled handler default.fetch() Traced demo app and /eval routesCalls route(): the site's calls and MCP json() Shared helpers

/** The Worker: `fetch` serves the routes, `scheduled` runs the daily health, purge, expiry and MCP counter cleanup. */export function createApp(modelsFor: (env: Env) => Models, options: Options = {}) {

createApp: builds the Worker object Module load

WhatTakes modelsFor, a function from the bindings to the model clients, and Options (default {}), and returns the Worker object.

Whyindex.ts calls it once at module load with the real clients, and the tests call it with scripted ones. The doc comment lists what scheduled runs: the daily health job, the purge, the expiry, and forgetHits, which deletes the MCP server's rate-limit counters (mcp_hits) older than two days.

  return {    async fetch(request: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {      try {        // `modelsFor(env)` on every request: `env` exists only inside a handler, never at module load.        return await route(request, env, modelsFor(env), options, ctx)

Models per request, then route Query time

Whatfetch calls modelsFor(env) and passes the result to route() with the request, env, options and ctx, and awaits the response inside a try.

Whyenv exists only as an argument to a handler, so the clients cannot be built at module load. The await is needed, because returning the promise without awaiting it would let a rejection escape the catch.

      } catch (error) {        console.error('demo: the request failed', error)        return json(500, { error: 'Something went wrong. Please try again in a minute.' })      }    },

One catch for every route Query time

WhatAny exception from any route (D1, a binding, a malformed escape in a path) is logged and answered with 500 and a generic message asking the visitor to try again.

WhyThe visitor gets a JSON error the page can show instead of the runtime's error page, and no stack trace or internal detail is exposed. The routes catch their expected failures themselves (vector outages, model errors); this catch receives only the unexpected ones.

status: 500