The last lesson’s route streamed the partner’s reply, but every request stood alone, and any message reached the model using the club’s key. Now you’ll give each practice session its own history on the server, refuse bad requests, and keep each request’s estimate under its budget with trimHistory(). Start with where the history lives now, a question the script never had to answer.
Keep One History per Session
A server handles requests from many members at once, so it needs one history per session, not the single array in partner.js. The page can’t send the history either. Anyone can call the route, so a caller could send assistant turns the partner never wrote, or thousands of turns billed to the club.
So the server keeps the histories, and the page sends only the message and a session ID, a string that names one practice session. The ID doesn’t prove who’s sending: anyone with Mei’s ID could use her session, so a real feature would need IDs the server issues and checks.
A Map stores values by key: new Map() creates one, .set(key, value) stores a value, .has(key) checks for a key, and .get(key) returns its value. Here, the keys are session IDs. Update the top of server.js:
server.js
import { readFile } from "node:fs/promises";
import express from "express";
import { streamAnswer } from "./model/index.js";
import {
estimate, trimHistory, recordTurn,
} from "./history.js";
const PORT = 3000;
const BUDGET = 1000;
const MAX_LENGTH = 500;
const prompt = await readFile("prompts/partner.md", "utf8");
const fixed = estimate(prompt);
const sessions = new Map();
const app = express();
The history.js import, BUDGET, and fixed come from trim-session.js. The budget still limits an estimate, so a request can go a little over budget. The map is a toy store: restarting the server clears it, and nothing expires sessions or limits their number. A production feature would use a database and add both safeguards.
If you’re still unsure why the server keeps the history, this button opens a mentor chat with the question ready: