File size: 8,390 Bytes
d160eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// The small text protocol between the model and the app.
//
// Frejya's raw reply looks like this:
//
//   <mood>curious</mood>
//   first chat bubble
//
//   second chat bubble with $math$
//   <remember>They are preparing for a linear algebra exam on 3 December.</remember>
//
// 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 = ['<mood>', '</mood>', '<remember>', '</remember>'];
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(/<mood>\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(/<remember>([\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. "<rem".
      const lt = t.lastIndexOf('<');
      if (lt >= 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 };
}