okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1306424be
main
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 { 17const flat = String ( text ?? '' ). replace ( / \r\n? / g , '\n' ). replace ( / \n{3,} / g , '\n\n' ). trim (). replace ( / 「 / g , '『' ). replace ( / 」 / g , '』' ); 18return 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 { 22const list = quotes . map ( cleanQuote ). filter ( Boolean ). slice ( 0 , MAX_QUOTES ); 23if ( ! list . length ) return reply ; 24return `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 { 29const text = String ( content ?? '' ); 30if ( ! text . startsWith ( 'Quoting:\n「' )) return null ; 31const marker = text . indexOf ( '」\n→ Reply: ' ); 32if ( marker < 0 ) return null ; 33const head = text . slice ( 'Quoting:\n' . length , marker + 1 ); 34const quotes = [ ...head . matchAll ( / 「([^」]*)」 / g )]. map ( m => m [ 1 ]); 35if ( ! quotes . length ) return null ; 36return { 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 [] { 41const text = cleanQuote ( quote . text ); 42if ( ! text || list . length >= MAX_QUOTES || list . some ( q => q . text === text && q . messageId === quote . messageId )) return [ ...list ]; 43return [ ...list , { id :quote . id ?? `q_ ${ Math . random (). toString ( 36 ). slice ( 2 , 9 )} ` , text, messageId :quote . messageId , role :quote . role }]; 44}