// The small text protocol between the model and the app. // // Frejya's raw reply looks like this: // // curious // first chat bubble // // second chat bubble with $math$ // They are preparing for a linear algebra exam on 3 December. // // This module strips the tags, splits the text into bubbles and pulls the math // out so that Markdown cannot mangle it. Pure string functions (unit-tested in Node). import { MOODS, LIMITS } from './config.js'; const TAGS = ['', '', '', '']; export const MATH_OPEN = ''; export const MATH_CLOSE = ''; /** Splits text into code and non-code segments (fenced blocks and inline code spans). */ export function splitCode(src) { const out = []; const push = (type, value) => { if (!value) return; const last = out[out.length - 1]; if (last && last.type === type) last.value += value; else out.push({ type, value }); }; // Pass 1: fenced blocks, line by line. const lines = src.split('\n'); const chunks = []; let fence = null; let buf = []; const flush = (type) => { if (buf.length) chunks.push({ type, value: buf.join('\n') }); buf = []; }; for (const line of lines) { const m = line.match(/^ {0,3}(`{3,}|~{3,})/); if (fence) { buf.push(line); if (m && m[1][0] === fence[0] && m[1].length >= fence.length && line.trim() === m[1]) { flush('code'); fence = null; } } else if (m) { flush('text'); fence = m[1]; buf.push(line); } else { buf.push(line); } } flush(fence ? 'code' : 'text'); // Pass 2: inline code spans inside the text chunks. chunks.forEach((chunk, idx) => { const sep = idx < chunks.length - 1 ? '\n' : ''; if (chunk.type === 'code') { push('code', chunk.value + sep); return; } const s = chunk.value; let i = 0; let textStart = 0; while (i < s.length) { if (s[i] !== '`') { i += 1; continue; } let n = 0; while (s[i + n] === '`') n += 1; const run = '`'.repeat(n); let j = i + n; let close = -1; while (j < s.length) { const k = s.indexOf(run, j); if (k < 0) break; let len = n; while (s[k + len] === '`') len += 1; if (len === n && s[k - 1] !== '`') { close = k; break; } j = k + len; } if (close < 0) { i += n; continue; } push('text', s.slice(textStart, i)); push('code', s.slice(i, close + n)); i = close + n; textStart = i; } push('text', s.slice(textStart) + sep); }); return out; } /** * Parses Frejya's raw reply. * @param {string} raw text received so far * @param {{final?: boolean}} [opts] final=false while streaming: half-received tags stay hidden * @returns {{mood: string|null, text: string, memories: string[]}} */ export function parseReply(raw, { final = false } = {}) { let mood = null; const memories = []; const segs = splitCode(raw || ''); const kept = []; let cut = false; for (let idx = 0; idx < segs.length && !cut; idx += 1) { const seg = segs[idx]; if (seg.type === 'code') { kept.push(seg.value); continue; } let t = seg.value; t = t.replace(/\s*([a-zA-Z_-]*)\s*<\/mood>[ \t]*\n?/gi, (_, name) => { const m = name.toLowerCase(); if (!mood && MOODS.includes(m)) mood = m; return ''; }); t = t.replace(/([\s\S]*?)<\/remember>[ \t]*\n?/gi, (_, fact) => { const clean = fact.replace(/\s+/g, ' ').trim(); if (clean) memories.push(clean.slice(0, LIMITS.memoryMaxChars)); return ''; }); // A tag that opened but has not closed (still streaming, or the reply was cut off). const open = t.search(/<(?:mood|remember)>/i); if (open >= 0) { t = t.slice(0, open); cut = true; } else if (!final && idx === segs.length - 1) { // The first characters of a tag that is still arriving, e.g. "= 0 && t.length - lt < 11) { const tail = t.slice(lt).toLowerCase(); if (TAGS.some((tag) => tag.startsWith(tail))) t = t.slice(0, lt); } } kept.push(t); } const text = kept.join('').replace(/\n{3,}/g, '\n\n').replace(/^\s*\n/, '').trimEnd(); return { mood, text, memories }; } const LIST_ITEM = /^ {0,3}(?:[-*+]|\d{1,3}[.)]) /; /** Splits display text into chat bubbles: one per paragraph, code block, list or equation. */ export function splitBubbles(text) { const blocks = []; let cur = []; let fence = null; let mathOpen = false; const flush = () => { if (cur.some((l) => l.trim())) blocks.push(cur.join('\n')); cur = []; }; for (const line of (text || '').split('\n')) { const m = line.match(/^ {0,3}(`{3,}|~{3,})/); if (fence) { cur.push(line); if (m && m[1][0] === fence[0] && m[1].length >= fence.length && line.trim() === m[1]) { fence = null; flush(); } continue; } if (m) { flush(); fence = m[1]; cur.push(line); continue; } const dollars = (line.match(/\$\$/g) || []).length; if (mathOpen) { cur.push(line); if (dollars % 2 === 1) mathOpen = false; continue; } if (dollars % 2 === 1) { mathOpen = true; cur.push(line); continue; } if (line.trim() === '') flush(); else cur.push(line); } flush(); // Keep things together that only make sense together. const merged = []; for (const block of blocks) { const prev = merged[merged.length - 1]; const first = block.split('\n')[0]; const prevIsList = prev !== undefined && LIST_ITEM.test(prev.split('\n')[0]); const prevIsHeading = prev !== undefined && /^ {0,3}#{1,6} /.test(prev) && !prev.includes('\n'); if (prevIsHeading || (prevIsList && (LIST_ITEM.test(first) || /^(?: {2,}|\t)/.test(first)))) { merged[merged.length - 1] = `${prev}\n\n${block}`; } else { merged.push(block); } } return merged; } function isSpace(ch) { return ch === undefined || /\s/.test(ch); } function replaceMathInText(s, items) { let out = ''; let i = 0; const add = (tex, display) => { items.push({ tex: tex.trim(), display }); out += `${MATH_OPEN}${items.length - 1}${MATH_CLOSE}`; }; while (i < s.length) { const ch = s[i]; const next = s[i + 1]; if (ch === '\\' && next === '$') { out += '\\$'; i += 2; continue; } if (ch === '\\' && (next === '[' || next === '(')) { const close = next === '[' ? '\\]' : '\\)'; const end = s.indexOf(close, i + 2); if (end > 0 && s.slice(i + 2, end).trim()) { add(s.slice(i + 2, end), next === '['); i = end + 2; continue; } out += ch; i += 1; continue; } if (ch === '$' && next === '$') { const end = s.indexOf('$$', i + 2); if (end > 0 && s.slice(i + 2, end).trim()) { add(s.slice(i + 2, end), true); i = end + 2; continue; } out += '$$'; i += 2; continue; } if (ch === '$' && !isSpace(next)) { // Inline math: closes at a "$" that is not escaped, not preceded by a space // and not followed by a digit (so "$5 and $10" stays plain text). let j = i + 1; let end = -1; while (j < s.length && j - i < 1500) { if (s[j] === '\n' && s[j + 1] === '\n') break; if (s[j] === '\\') { j += 2; continue; } if (s[j] === '$') { if (!isSpace(s[j - 1]) && !/\d/.test(s[j + 1] || '')) end = j; break; } j += 1; } if (end > 0) { add(s.slice(i + 1, end), false); i = end + 1; continue; } } out += ch; i += 1; } return out; } /** * Replaces TeX math ($...$, $$...$$, \(...\), \[...\]) outside code with * placeholders, so Markdown rendering cannot damage it. * @returns {{text: string, items: {tex: string, display: boolean}[]}} */ export function extractMath(src) { const items = []; const text = splitCode(src || '') .map((seg) => (seg.type === 'code' ? seg.value : replaceMathInText(seg.value, items))) .join(''); return { text, items }; }