import { DIAGRAM_FENCE_INFO, FENCE_CLOSE, FENCE_OPEN, isBoxDiagram } from '../prompts/visualPresentation.js'; /** * Lets a live answer be corrected for text-drawn diagrams without ever * retracting shown text. Text streams as it arrives, except a fenced block * that could be a prose drawing (no info string, `text`, `plaintext`): that is * held from its opening line until it closes. Not a box → released at once. * A box → the visible answer stops right before it; the loop keeps the shown * part and asks the model to continue from there with a real diagram. Fences * with a language are code and stream straight through. */ export class LiveDiagramGate { #scanned = 0; #fence?: { start: number; body: number; marker: string; candidate: boolean }; #hit?: number; #released = false; /** Start of the held box, once one was found (and not released). */ get hit(): number | undefined { return this.#released ? undefined : this.#hit; } /** Give up on correcting (tool round, no turns left): show everything. */ release(): void { this.#released = true; } /** How much of `text` may be shown now; `final` once the model has finished. */ releasable(text: string, final = false): number { if (this.#released) return text.length; if (this.#hit !== undefined) return this.#hit; for (let newline = text.indexOf('\n', this.#scanned); newline >= 0; newline = text.indexOf('\n', this.#scanned)) { const start = this.#scanned; const line = text.slice(start, newline).replace(/\r$/, ''); this.#scanned = newline + 1; if (!this.#fence) { const open = FENCE_OPEN.exec(line); if (open) this.#fence = { start, body: this.#scanned, marker: open[1]!, candidate: DIAGRAM_FENCE_INFO.test(open[2]!) }; continue; } const close = FENCE_CLOSE.exec(line); if (!close || close[1]![0] !== this.#fence.marker[0] || close[1]!.length < this.#fence.marker.length) continue; if (this.#fence.candidate && isBoxDiagram(text.slice(this.#fence.body, start))) { this.#hit = this.#fence.start; return this.#hit; } this.#fence = undefined; } if (final) { // The model ended inside a fence: judge what it wrote, then show the rest. if (this.#fence?.candidate && isBoxDiagram(text.slice(this.#fence.body))) this.#hit = this.#fence.start; return this.#hit ?? text.length; } if (this.#fence?.candidate) return this.#fence.start; // A partial line outside any fence may still turn into a fence opener // (list items indent fences by up to 3 spaces). if (!this.#fence && /^ {0,3}[`~]/.test(text.slice(this.#scanned))) return this.#scanned; return text.length; } }