d3ro-voice/packages/core/src/suggestion-text.ts

454 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// packages/core — 제안 텍스트 정본 (후보 정제 · 접두 정규화).
//
// 두 종류의 입력을 분리해 다룬다 (ISP):
// 1) 신뢰할 수 없는 모델 출력 — 번호/불릿/따옴표/지시문 되풀이를 걷어내야 한다
// (`stripModelArtifacts` → `normalizeSuggestionText`).
// 2) 사용자가 학습시킨 로컬 기억 문구 — 사용자 자신의 글이므로 내용을 건드리지 않고
// 공백과 길이만 정규화한다 (`normalizeSuggestionText`).
// 두 입력이 한 정제 함수를 공유하던 시절, 모델 대응 규칙이 사용자의 "3 pm …" 같은
// 문장 앞 숫자를 지웠다 — 이 분리가 그 회귀를 구조적으로 막는다.
//
// 순수 함수만 둔다 — Electron/Node 의존 금지. input-intelligence.ts 를 import 하지 않는다
// (input-intelligence 가 이 모듈을 다시 export 하므로 순환이 생긴다).
/**
* 프롬프트에 넣을 컨텍스트 길이 상한.
*
* 길이가 곧 로컬 추론 지연이므로 짧게 유지한다.
*/
export const SUGGESTION_CONTEXT_MAX_CHARS = 400
/** 후보 문자열 길이 상한. */
export const SUGGESTION_MAX_OUTPUT_CHARS = 160
/** 문장 종결 부호. */
export const SENTENCE_TERMINATORS = /[.!?。!?…]/
/** 마지막 문장 종결 여부 — 참이면 직전 문장이 끝난 것이므로 제안을 지운다. */
export function endsSentence(text: string): boolean {
const trimmed = text.replace(/\s+$/u, '')
if (!trimmed) return false
const last = trimmed[trimmed.length - 1]
return SENTENCE_TERMINATORS.test(last) || last === '\n'
}
// ============================================================
// 접두 정규화
// ============================================================
/**
* 요청 접두 정규화 — 뒤쪽 공백만 걷어낸다 (길이는 자르지 않는다).
*
* 진행 중 요청의 연속 확장 판정(decideSuggestionRefresh)은 전체 접두로 비교해야 한다 —
* 400자 창으로 자르면 한 글자만 쳐도 창이 밀려 "연속 확장" 이 깨진다.
*/
export function normalizeRequestPrefix(prefix: string): string {
return prefix.replace(/\s+$/u, '')
}
/**
* 세션 접두 정규화 — 뒤쪽 공백을 걷어내고 마지막 SUGGESTION_CONTEXT_MAX_CHARS 자만 남긴다.
*
* 세션은 이 창으로 만든 후보이므로, 표시 중인 세션의 유효성 비교는 양쪽 모두 이 함수로
* 맞춰야 한다. 한쪽만 자르면 400자를 넘는 입력창에서 텍스트가 그대로여도 매 스냅샷마다
* 세션이 stale 로 닫힌다.
*/
export function normalizeSessionPrefix(prefix: string): string {
return normalizeRequestPrefix(prefix).slice(-SUGGESTION_CONTEXT_MAX_CHARS)
}
// ============================================================
// 후보 정제
// ============================================================
/**
* 목록 표지: 불릿(-, *, •)이거나, 1~3자리 번호 뒤에 목록 구두점(. ) ])이 붙은 것.
*
* 숫자만으로는 목록 표지로 보지 않는다 — "3 pm in the lobby", "10 minutes later",
* "2026 roadmap" 의 숫자는 문장 내용이다.
*/
const LIST_MARKER_PATTERN = /^(?:[-*•]+[.)\]]?|\d{1,3}[.)\]])\s+/u
const WRAPPING_QUOTES_PATTERN = /^["'“”‘’`]+|["'“”‘’`]+$/gu
/** 모델이 지시문·섹션 헤더를 되풀이한 경우 (llm-prompts 지시문 누출 차단) */
const INSTRUCTION_ECHO_PATTERN =
/^(?:(?:suggestion|completion|candidate|output|answer|다음 문장|입력)\s*[::]|\[(?:이어 쓰기 지시|지금 쓰는 문장|직전 문장|앞 문맥|현재 앱|글의 첫머리|글에 나온 사실)\])|(?:검색어입니다\.?|검색어 키워드 몇 개로만|짧게 이어 쓰세요|나머지 부분만 쓰세요|새 문장 하나를 쓰세요|바로 뒤부터 이어 쓰세요|겹치지 않는 다른 문장을 쓰세요)/iu
const TEMPLATE_ECHO_PATTERN = /^\{\{.*\}\}$/u
/**
* 모델 출력 한 줄에서 모델 특유의 부산물을 걷어낸다.
*
* 번호/불릿/따옴표를 지우고, 지시문 되풀이·템플릿 누출은 버린다(null).
* 길이 제한은 하지 않는다 — normalizeSuggestionText 가 맡는다.
*/
export function stripModelArtifacts(line: string): string | null {
let text = line.trim()
if (!text) return null
text = text.replace(LIST_MARKER_PATTERN, '')
text = text.replace(WRAPPING_QUOTES_PATTERN, '')
text = text.replace(/\s+/gu, ' ').trim()
if (INSTRUCTION_ECHO_PATTERN.test(text)) return null
if (TEMPLATE_ECHO_PATTERN.test(text)) return null
return text
}
/**
* 후보 텍스트 정규화 — 공백을 한 칸으로 모으고 길이를 제한한다.
*
* 내용은 바꾸지 않는다 (사용자 자신의 문구에 안전). 2자 미만이면 null.
*/
export function normalizeSuggestionText(
text: string,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string | null {
let normalized = text.replace(/\s+/gu, ' ').trim()
if (normalized.length < 2) return null
if (normalized.length > maxChars) {
normalized = normalized.slice(0, maxChars)
const lastSpace = normalized.lastIndexOf(' ')
if (lastSpace > maxChars * 0.6) normalized = normalized.slice(0, lastSpace)
normalized = normalized.trim()
}
return normalized.length >= 2 ? normalized : null
}
/** 모델 출력 한 줄 정제: 번호/불릿/따옴표/지시문 제거 + 길이 제한. */
export function sanitizeSuggestionLine(line: string, maxChars = SUGGESTION_MAX_OUTPUT_CHARS): string | null {
const stripped = stripModelArtifacts(line)
return stripped === null ? null : normalizeSuggestionText(stripped, maxChars)
}
const WORD_BOUNDARY_AFTER = /^[\s.,!?;:。、,!?…"'”’)\]]/u
/**
* 후보 머리가 접두(지금 문장) 꼬리를 되풀이하면 그 부분을 걷어낸다.
*
* 되풀이로 보는 조건: 접두의 지금 문장 안에서 어절 경계부터 시작하는 꼬리(2자 이상)가 후보의
* 머리와 같고, 후보 쪽에서도 그 뒤가 어절 경계다. "회의실" + "실에서" 같은 우연한 글자 겹침은
* 어절 경계 조건에 걸려 그대로 둔다. 되풀이 말고 남는 것이 없으면 '' 를 돌려준다.
*/
export function stripRestatedPrefix(candidate: string, prefix: string): string {
const sentenceStart = Math.max(
...['.', '!', '?', '。', '!', '?', '…', '\n'].map((mark) => prefix.lastIndexOf(mark) + 1)
)
const sentence = prefix.slice(sentenceStart).replace(/\s+/gu, ' ').trim()
if (sentence.length < 2) return candidate
const lowerCandidate = candidate.toLowerCase()
const lowerSentence = sentence.toLowerCase()
for (let start = 0; start <= lowerSentence.length - 2; start += 1) {
if (start > 0 && lowerSentence[start - 1] !== ' ') continue
const tail = lowerSentence.slice(start)
if (!lowerCandidate.startsWith(tail)) continue
const rest = candidate.slice(tail.length)
if (rest.length > 0 && !WORD_BOUNDARY_AFTER.test(rest)) continue
return rest.trim()
}
return candidate
}
/**
* 모델 출력에서 후보 목록을 뽑아 정제한다.
*
* gemma 계열 소형 모델은 번호/따옴표/머리말을 붙이기 쉬우므로 여기서 걷어낸다.
* 접두를 그대로 되풀이하는 후보는 버린다 (ghost text 로 쓸 수 없음).
*/
export function parseSuggestionCandidates(
raw: string,
prefix: string,
maxCandidates = 3,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string[] {
if (!raw) return []
const normalizedPrefix = normalizeRequestPrefix(prefix)
const out: string[] = []
for (const line of raw.split(/\r?\n/u)) {
const sanitized = sanitizeSuggestionLine(line, maxChars)
if (!sanitized) continue
// 지금 문장의 앞부분을 다시 쓰고 이어 간 후보는 되풀이한 부분만 걷어낸다 — 그대로 넣으면
// "CI는 CI는 통과했고…" 처럼 같은 말이 두 번 들어간다(실측). 되풀이뿐이면 버린다.
const cleaned = stripRestatedPrefix(sanitized, normalizedPrefix)
if (!cleaned || cleaned.length < 2) continue
if (out.some((existing) => existing.toLowerCase() === cleaned.toLowerCase())) continue
out.push(cleaned)
if (out.length >= maxCandidates) break
}
return out
}
// ============================================================
// 로컬 기억 후보
// ============================================================
export interface LocalSuggestionHints {
continuationHints: readonly string[]
relatedHints: readonly string[]
phraseHints: readonly string[]
}
function suffixPrefixOverlap(prefix: string, candidate: string): number {
const normalizedPrefix = prefix.toLowerCase()
const normalizedCandidate = candidate.toLowerCase()
const maximum = Math.min(normalizedPrefix.length, normalizedCandidate.length)
for (let length = maximum; length >= 2; length -= 1) {
if (normalizedPrefix.slice(-length) === normalizedCandidate.slice(0, length)) return length
}
return 0
}
/** 로컬 기억 후보 하나 — 삽입할 텍스트와, 접두에 붙여 써야 하는지(단어 중간에서 이어짐). */
export interface LocalSuggestionCandidate {
text: string
/**
* true 면 접두의 단어 중간에서 이어지는 나머지다(예: "Thank yo" + "u for the update") —
* 수락할 때 구분 공백을 넣지 않는다. joinSuggestion 의 joint 'attach' 에 해당한다.
*/
attachToPrefix: boolean
}
/**
* 로컬 기억만으로 삽입 가능한 다음 문자열을 만든다.
*
* 힌트는 사용자 자신이 쓴 글이다 — 모델 출력용 정제(목록 표지·따옴표 제거)를 거치지
* 않고 공백·길이만 정규화한다. 모델 실패를 성공처럼 숨기지 않고, 호출부가
* provenance.mode 로 출처를 명시한다.
*/
export function buildLocalSuggestionCandidates(
prefix: string,
hints: LocalSuggestionHints,
limit = 3,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string[] {
return buildLocalSuggestionCandidateEntries(prefix, hints, limit, maxChars).map((entry) => entry.text)
}
export interface LocalSuggestionBuildOptions {
/**
* 사용자가 친 원문이 공백으로 끝났는가(단어를 끝냈는가). 생략하면 prefix 인자의 뒤 공백으로 판단한다.
* true 면 접두 꼬리와 문구 머리가 단어 중간에서 겹치는 후보를 버린다.
*/
wordFinished?: boolean
}
/**
* buildLocalSuggestionCandidates 와 같은 후보를, 접두와의 이음새 정보와 함께 돌려준다.
*
* 문구 겹침(접두 꼬리 = 문구 머리)으로 잘라 낸 나머지가 공백으로 시작하지 않으면 단어
* 중간에서 이어지는 것이다 — 정규화(trim)가 그 정보를 지우기 전에 여기서 기록한다.
*/
export function buildLocalSuggestionCandidateEntries(
prefix: string,
hints: LocalSuggestionHints,
limit = 3,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS,
options: LocalSuggestionBuildOptions = {}
): LocalSuggestionCandidate[] {
// 커서 앞 원문이 공백으로 끝나면 단어가 끝났다 — 단어 중간 이어 쓰기(attach)는 조각이 된다
// ("내일 회의 " + "록 공유드립니다"). 호출자가 뒤 공백을 걷어낸 접두를 넘기면 명시적으로 알린다.
const wordFinished = options.wordFinished ?? /\s$/u.test(prefix)
const safeLimit = Math.max(0, Math.floor(limit))
const safeMaxChars = Math.max(0, Math.floor(maxChars))
if (safeLimit === 0 || safeMaxChars < 2) return []
const normalizedPrefix = normalizeRequestPrefix(prefix)
const normalizedPrefixLower = normalizedPrefix.toLowerCase()
const acceptsWholePhrase = endsSentence(normalizedPrefix)
const out: LocalSuggestionCandidate[] = []
const append = (candidate: string | null, attachToPrefix = false): void => {
if (candidate === null || candidate.length === 0) return
if (candidate.toLowerCase() === normalizedPrefixLower) return
if (out.some((existing) => existing.text.toLowerCase() === candidate.toLowerCase())) return
out.push({ text: candidate, attachToPrefix })
}
for (const raw of hints.continuationHints) {
if (out.length >= safeLimit) break
const candidate = normalizeSuggestionText(raw, safeMaxChars)
if (candidate === null) continue
if (normalizedPrefixLower && candidate.toLowerCase().startsWith(normalizedPrefixLower)) continue
append(candidate)
}
for (const source of [hints.relatedHints, hints.phraseHints]) {
for (const raw of source) {
if (out.length >= safeLimit) break
const candidate = normalizeSuggestionText(raw, safeMaxChars)
if (candidate === null) continue
const overlap = suffixPrefixOverlap(normalizedPrefix, candidate)
if (overlap >= 2) {
const remainder = candidate.slice(overlap)
const midWord = !/^\s/u.test(remainder)
if (midWord && wordFinished) continue
append(normalizeSuggestionText(remainder, safeMaxChars), midWord)
} else if (acceptsWholePhrase) {
append(candidate)
}
}
}
return out
}
// ============================================================
// 수락 시 이음새
// ============================================================
/**
* 후보가 접두와 어떻게 이어지는가.
* - separate: 새 단어/문장이다 — 띄어 쓰는 문자 체계면 공백 하나로 떼어 쓴다.
* - attach: 접두의 단어 중간에서 이어지는 나머지다 — 그대로 붙인다.
*/
export type SuggestionJoint = 'separate' | 'attach'
/** 이 문자 뒤에는 떼어 쓰지 않는다 (여는 괄호·따옴표, 경로·멘션·해시 기호). */
const NO_SPACE_AFTER = /[([{<“‘«‹「『【〔〈《([{/\\@#_-]/u
/** 이 문자로 시작하는 후보는 앞 글자에 붙는다 (닫는 괄호·구두점). */
const NO_SPACE_BEFORE = /[.,;:!?)\]}>…%’”»›」』】〕〉》、。,.!?:;)]}]/u
/** 단어 사이를 띄어 쓰지 않는 문자 체계 + CJK 구두점·전각 기호. */
const UNSPACED_JOIN_SCRIPT =
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}\u3000-\u303f\uff00-\uffef]/u
function lastCodePoint(text: string): string {
const chars = Array.from(text)
return chars[chars.length - 1] ?? ''
}
function firstCodePoint(text: string): string {
return Array.from(text)[0] ?? ''
}
/**
* 수락한 후보를 커서 위치에 넣을 문자열로 만든다 (필요하면 앞에 공백 하나).
*
* 후보는 정제 과정에서 앞 공백이 모두 사라진다. 사용자는 대개 마지막 글자(단어 끝이나
* 마침표) 바로 뒤에서 멈추므로, 그대로 붙이면 "report.Let me…", "회의에서논의한…" 처럼
* 들러붙는다. 다음 경우에만 공백을 넣는다:
* - 커서 앞 원문(rawPrefix)이 비어 있지 않고 공백으로 끝나지 않는다.
* - 후보가 접두의 단어 중간에서 이어지는 나머지(joint 'attach')가 아니다.
* - 앞 글자가 여는 괄호/따옴표·경로 기호가 아니고, 후보가 닫는 구두점으로 시작하지 않는다.
* - 이음새 양쪽 어느 쪽도 띄어 쓰지 않는 문자 체계(중·일·태 등, CJK 구두점)가 아니다.
*/
/**
* 후보를 첫 어절과 나머지로 나눈다 (단어 단위 수락). 어절 뒤 문장부호는 그 어절에 붙인다.
* 나머지가 없으면 rest 는 빈 문자열 — 호출자는 통째로 수락한다.
*/
export function splitFirstWord(candidate: string): { word: string; rest: string } {
const text = candidate.replace(/^\s+/u, '')
const match = /^\S+/u.exec(text)
if (!match) return { word: text, rest: '' }
return { word: match[0], rest: text.slice(match[0].length).replace(/^\s+/u, '') }
}
export function joinSuggestion(rawPrefix: string, candidate: string, joint: SuggestionJoint = 'separate'): string {
if (!candidate) return candidate
// 단어 중간 이어 쓰기는 공백 없이 붙인다. 원문이 이미 공백으로 끝났으면 이어 붙일 단어가 없다
// — separate 규칙으로 간다(공백 뒤라 결과는 후보 그대로).
if (joint === 'attach' && !/\s$/u.test(rawPrefix)) return candidate
const before = lastCodePoint(rawPrefix)
const after = firstCodePoint(candidate)
if (!before || !after) return candidate
if (/\s/u.test(before) || /\s/u.test(after)) return candidate
if (NO_SPACE_AFTER.test(before) || NO_SPACE_BEFORE.test(after)) return candidate
if (UNSPACED_JOIN_SCRIPT.test(before) || UNSPACED_JOIN_SCRIPT.test(after)) return candidate
return ` ${candidate}`
}
// ============================================================
// 이어 쓰기(prefill) 출력 정제
// ============================================================
export interface ContinuationOptions {
/** 지금 문장 마저 쓰기인가, 다음 문장인가 */
mode: 'complete-sentence' | 'next-sentence'
/** 모델 차례 앞에 미리 넣은 사용자 글 (모델은 이 바로 뒤부터 쓴다) */
prefill: string
/** 이미 쓴 문장들 — 모델이 같은 문장을 되풀이하면 버린다 */
writtenSentences?: readonly string[]
/**
* 사용자가 친 원문이 공백으로 끝났는가(단어를 끝냈는가). prefill 은 끝 공백을 빼고 보낸다 —
* 끝 공백 하나만 남은 토큰 상태는 모델 분포를 흔들어 엉뚱한 말을 만든다(실측). 그 대신 모델이
* 끝난 단어에 글자를 붙여 쓰면(공백 없이 시작) 버린다.
*/
wordFinished?: boolean
/** 사용자가 이모지를 쓰는가 — 아니면 모델이 붙인 이모지를 지운다 */
allowEmoji?: boolean
maxChars?: number
}
export interface ExtractedContinuation {
text: string
joint: SuggestionJoint
}
const EMOJI_PATTERN = /\p{Extended_Pictographic}|[\u{1F3FB}-\u{1F3FF}]|\u200d|\ufe0f/gu
const LEADING_LIST_MARKER = /^(?:[-*•]|\d{1,3}[.)])\s+/u
/** 텍스트에 이모지가 있는가 (사용자 습관 판별). */
export function containsEmoji(text: string): boolean {
return /\p{Extended_Pictographic}/u.test(text)
}
/** 원형 템플릿 응답에 섞일 수 있는 특수 토큰·마크다운 강조. */
const SPECIAL_TOKEN_PATTERN = /<\|?\/?(?:turn|start_of_turn|end_of_turn|eos|bos|im_start|im_end|channel|message)\|?>|<(?:turn|end_of_turn|eos)\|>/gu
const MARKDOWN_EMPHASIS_PATTERN = /\*\*|__/gu
/** 첫 문장의 끝 — 종결 부호(+닫는 따옴표/괄호) 뒤가 공백이거나 끝. "3.5", "v1.2" 의 점은 아니다. */
const FIRST_SENTENCE_END = /[.!?。!?…]+["'”’)\]]*(?=\s|$)/u
function comparable(text: string): string {
return text.replace(/[\s.!?。!?…,"'“”‘’]+/gu, '').toLowerCase()
}
/**
* prefill 한 응답(모델이 사용자 글 바로 뒤부터 쓴 텍스트)에서 삽입할 이어 쓰기를 뽑는다.
*
* 응답 원문은 사용자 글과 이음새까지 그대로 이어진다 — 첫 글자가 공백이면 새 단어이고, 아니면
* 단어 중간("회의실" + "에서")이다. 그 정보를 joint 로 보존한 뒤 첫 줄·첫 문장만 남긴다.
* 사용자 글이 이어지는 것이므로 목록 표지·따옴표는 지우지 않는다(사용자가 목록을 쓰는 중일 수 있다).
*/
export function extractContinuation(raw: string, options: ContinuationOptions): ExtractedContinuation | null {
const maxChars = options.maxChars ?? SUGGESTION_MAX_OUTPUT_CHARS
let text = raw.replace(SPECIAL_TOKEN_PATTERN, '').replace(MARKDOWN_EMPHASIS_PATTERN, '')
if (options.mode === 'complete-sentence') {
// 줄바꿈부터 시작하면 모델은 지금 문장이 이미 끝났다고 본 것이다 — 이어 쓸 것이 없다.
if (/^[ \t]*\n/u.test(text)) return null
} else {
text = text.replace(/^\s*\n/u, ' ')
}
const startsNewWord = /^\s/u.test(text)
if (!options.allowEmoji) text = text.replace(EMOJI_PATTERN, '')
// 끝난 단어 뒤에 모델이 글자를 붙였다("회의실 " + "에서") — 그대로 넣으면 띄어 쓴 조사가 된다.
if (options.wordFinished && !startsNewWord && /^[\p{L}\p{N}]/u.test(text)) return null
text = text.replace(/^\s+/u, '').split(/\r?\n/u)[0] ?? ''
// 목록 줄이 아닌데 "- " 로 시작하면 힌트 목록 형식을 베낀 것이다.
const prefillLastLine = options.prefill.split('\n').pop() ?? ''
const onListLine = LEADING_LIST_MARKER.test(prefillLastLine.trim()) || /\n$/u.test(options.prefill)
if (!onListLine) text = text.replace(LEADING_LIST_MARKER, '')
// 모델이 지금 문장을 처음부터 다시 쓴 경우 — 이미 쓴 부분을 걷어낸다.
const prefill = options.prefill.replace(/\s+/gu, ' ').trim()
if (options.mode === 'complete-sentence' && prefill.length >= 4) {
const normalized = text.replace(/\s+/gu, ' ')
if (normalized.startsWith(prefill)) text = normalized.slice(prefill.length).replace(/^\s+/u, '')
}
const end = FIRST_SENTENCE_END.exec(text)
if (end) text = text.slice(0, end.index + end[0].length)
if (INSTRUCTION_ECHO_PATTERN.test(text) || TEMPLATE_ECHO_PATTERN.test(text)) return null
const normalized = normalizeSuggestionText(text, maxChars)
// 마저 쓰기에서는 마침표 하나("뵙겠습니다" + ".")도 정당한 나머지다 — 글자 수 하한을 따로 둔다.
const result = normalized ?? (options.mode === 'complete-sentence' && text.trim().length > 0 ? text.trim() : null)
if (!result || !/[\p{L}\p{N}]/u.test(result)) return null
// 이미 쓴 문장 되풀이
const key = comparable(result)
if (key.length >= 6 && (options.writtenSentences ?? []).some((sentence) => comparable(sentence) === key)) return null
const joint: SuggestionJoint =
options.mode === 'complete-sentence' && !startsNewWord && !options.wordFinished && !/\s$/u.test(options.prefill)
? 'attach'
: 'separate'
return { text: result, joint }
}