okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
2.3 KiB44 linesraw
1/**
2 * Quoting a turn or a passage into the next message (#4785). The message that goes out carries the quote in one fixed, visible form, so the
3 * model knows what is being answered and the transcript can show the quote apart from the reply:
4 *
5 *   Quoting:
6 *   「the first passage」
7 *   「the second passage」
8 *   → Reply: what the person wrote
9 */
10export const MAX_QUOTES = 8;
11export const MAX_QUOTE_CHARS = 4000;
12
13export interface Quote { id: string; text: string; messageId: string; role: 'user' | 'assistant' }
14
15/** The quote as it is carried: trimmed, bounded, and with the corner brackets of the form turned into other brackets so a quote cannot end itself early. */
16export function cleanQuote(text: string): string {
17  const flat = String(text ?? '').replace(/\r\n?/g, '\n').replace(/\n{3,}/g, '\n\n').trim().replace(/「/g, '『').replace(/」/g, '』');
18  return flat.length > MAX_QUOTE_CHARS ? `${flat.slice(0, MAX_QUOTE_CHARS - 1).trimEnd()}…` : flat;
19}
20
21export function composeQuoted(quotes: readonly string[], reply: string): string {
22  const list = quotes.map(cleanQuote).filter(Boolean).slice(0, MAX_QUOTES);
23  if (!list.length) return reply;
24  return `Quoting:\n${list.map(q => `「${q}」`).join('\n')}\n→ Reply: ${reply}`;
25}
26
27/** The quotes and the reply of a message made by composeQuoted, or null when the message is not one. */
28export function parseQuoted(content: string): { quotes: string[]; reply: string } | null {
29  const text = String(content ?? '');
30  if (!text.startsWith('Quoting:\n「')) return null;
31  const marker = text.indexOf('」\n→ Reply: ');
32  if (marker < 0) return null;
33  const head = text.slice('Quoting:\n'.length, marker + 1);
34  const quotes = [...head.matchAll(/「([^」]*)」/g)].map(m => m[1]);
35  if (!quotes.length) return null;
36  return { quotes, reply: text.slice(marker + '」\n→ Reply: '.length) };
37}
38
39/** Adds a quote to a list: an empty one, a repeat and anything past the limit are left out. */
40export function addToQuotes(list: readonly Quote[], quote: Omit<Quote, 'id'> & { id?: string }): Quote[] {
41  const text = cleanQuote(quote.text);
42  if (!text || list.length >= MAX_QUOTES || list.some(q => q.text === text && q.messageId === quote.messageId)) return [...list];
43  return [...list, { id: quote.id ?? `q_${Math.random().toString(36).slice(2, 9)}`, text, messageId: quote.messageId, role: quote.role }];
44}