feat(input): expand Araso Han/Eng contractions, acronyms, typo recovery, and fast cursor-tail replacement
This commit is contained in:
parent
51bf664302
commit
f403111256
80 changed files with 1449 additions and 458 deletions
|
|
@ -249,16 +249,12 @@ async function initInputIntelligence(): Promise<void> {
|
|||
typo.on('corrected', () => {
|
||||
if (suggestion.isPresentationActive) suggestion.dismiss('stale')
|
||||
})
|
||||
// 제안이 켜져 있을 때도 한영 전환(Araso 방식 영→한·한→영·혼합어)은 기본 기능으로 즉시 고치고,
|
||||
// 일반 철자·모델 오타는 제안 창에 "지운 글자 → 고친 글자" 로 함께 내놓는다.
|
||||
// 인플레이스 자동 교정(handleTypingContext)은 타이핑과 절대 경합하지 않도록
|
||||
// 0.1ms 결정적 한영·영문오타 엔진(layoutOnly: true, 커서 직전 어절만 교체)만 즉시 실행하고,
|
||||
// 문장 단위 로컬 LLM(Gemma) 오타 교정은 키보드를 건드리지 않는 제안 팝업(propose)에서만 제시한다.
|
||||
suggestion.setTypoProposer({ propose: (context, signal, options) => typo.propose(context, signal, options) })
|
||||
telemetry.on('typed-context', (context) => {
|
||||
if (suggestion.isEnabled()) {
|
||||
const layoutVerdict = typo.handleTypingContext(context, { layoutOnly: true })
|
||||
if (layoutVerdict === 'pass') suggestion.handleTypingContext(context)
|
||||
return
|
||||
}
|
||||
const verdict = typo.handleTypingContext(context)
|
||||
const verdict = typo.handleTypingContext(context, { layoutOnly: true, trailingWordOnly: true })
|
||||
if (verdict === 'pass') suggestion.handleTypingContext(context)
|
||||
})
|
||||
telemetry.on('state-changed', (state) =>
|
||||
|
|
|
|||
|
|
@ -571,9 +571,23 @@ export class SuggestionService extends EventEmitter {
|
|||
this.emit('state-changed', this.getState())
|
||||
}
|
||||
|
||||
/** 설정에서 명시적으로 제안을 켤 때만 모델을 짧게 준비한다. */
|
||||
warmUp(options: { silent?: boolean } = {}): Promise<void> {
|
||||
if (!this.isEnabled()) return Promise.resolve()
|
||||
private _isModelWarmNeeded(allowForTypo = false): boolean {
|
||||
if (this.isEnabled()) return true
|
||||
return (
|
||||
allowForTypo &&
|
||||
configGet('typoAutoCorrectEnabled') !== false &&
|
||||
configGet('typoAutoCorrectUseModel') !== false
|
||||
)
|
||||
}
|
||||
|
||||
/** 타이핑 중 오타·한영 교정 모델(Gemma)과 제안 모델을 백그라운드에서 미리 데운다. */
|
||||
ensureWarmForTyping(context: TypingContext): void {
|
||||
this._keepWarm(context, Date.now())
|
||||
}
|
||||
|
||||
/** 설정에서 명시적으로 제안을 켤 때 또는 백그라운드 오타 교정 워밍업 시 모델을 짧게 준비한다. */
|
||||
warmUp(options: { silent?: boolean; allowForTypo?: boolean } = {}): Promise<void> {
|
||||
if (!this._isModelWarmNeeded(options.allowForTypo === true)) return Promise.resolve()
|
||||
if (this._warmUpPromise) return this._warmUpPromise
|
||||
|
||||
const abort = new AbortController()
|
||||
|
|
@ -582,7 +596,7 @@ export class SuggestionService extends EventEmitter {
|
|||
// 열려 실제로 제안을 기다릴 때(_showWarming)만 한다.
|
||||
if (!options.silent) this._warmingUp = true
|
||||
this.emit('state-changed', this.getState())
|
||||
const warmUp = this._warmUpUntilReady(abort)
|
||||
const warmUp = this._warmUpUntilReady(abort, options.allowForTypo === true)
|
||||
this._warmUpPromise = warmUp
|
||||
void warmUp.finally(() => {
|
||||
if (this._warmUpPromise === warmUp) this._warmUpPromise = null
|
||||
|
|
@ -591,10 +605,10 @@ export class SuggestionService extends EventEmitter {
|
|||
return warmUp
|
||||
}
|
||||
|
||||
private async _warmUpUntilReady(abort: AbortController): Promise<void> {
|
||||
private async _warmUpUntilReady(abort: AbortController, allowForTypo = false): Promise<void> {
|
||||
try {
|
||||
for (let attempt = 0; attempt <= 15; attempt += 1) {
|
||||
if (abort.signal.aborted || !this.isEnabled()) return
|
||||
if (abort.signal.aborted || !this._isModelWarmNeeded(allowForTypo)) return
|
||||
if (!getLocalLLMService().isAvailable()) {
|
||||
if (attempt === 15) return
|
||||
await this._waitForWarmUpRetry(abort.signal)
|
||||
|
|
@ -861,14 +875,14 @@ export class SuggestionService extends EventEmitter {
|
|||
* - 따뜻하지만 유지 시간이 얼마 안 남았으면 1토큰 요청으로 연장한다.
|
||||
*/
|
||||
private _keepWarm(context: TypingContext, now: number): void {
|
||||
if (!this.isEnabled() || !context.typedRecently || !context.isEditable || context.isPassword) return
|
||||
if (!this._isModelWarmNeeded(true) || !context.typedRecently || !context.isEditable || context.isPassword) return
|
||||
if (this._warmUpPromise || this._inFlight || this._filling) return
|
||||
const model = this.resolveModel()
|
||||
if (!model || !getLocalLLMService().isAvailable()) return
|
||||
if (!this._warmth.isWarm(model, now)) {
|
||||
if (this._warmth.isBackingOff(model, now, WARM_UP_FAILURE_BACKOFF_MS)) return
|
||||
logger.info(`타이핑 감지 — 식은 제안 모델을 미리 올린다 (model=${model})`)
|
||||
void this.warmUp({ silent: true })
|
||||
void this.warmUp({ silent: true, allowForTypo: true })
|
||||
return
|
||||
}
|
||||
if (this._warmth.warmUntil - now > KEEP_WARM_REFRESH_MS) return
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ import {
|
|||
type TypoCorrection,
|
||||
type TypoReplacementPlan
|
||||
} from '@d3ro/core/typo-correction'
|
||||
import { isAppExcluded, isTerminalApp, shouldLearnFromApp } from '@d3ro/core/input-intelligence'
|
||||
import { isAppExcluded, isTerminalApp } from '@d3ro/core/input-intelligence'
|
||||
import { analyzeWritingContext } from '@d3ro/core/writing-context'
|
||||
import { configGet, configSet } from './ConfigService'
|
||||
import { getLogger } from './LoggerService'
|
||||
|
|
@ -56,13 +56,21 @@ const VOCABULARY_TTL_MS = 60_000
|
|||
/** 제안용 모델 검사 응답 제한 — 제안 첫 후보가 그만큼 늦어진다. */
|
||||
const PROPOSAL_CHECK_TIMEOUT_MS = 1500
|
||||
/** 모델 검사 최소 구간 길이 (글자) */
|
||||
const MODEL_CHECK_MIN_CHARS = 6
|
||||
const MODEL_CHECK_MIN_CHARS = 3
|
||||
/** 공백·문장부호로 단어가 끝난 직후 한영 전환(Araso) 최소 유휴 시간 (ms) */
|
||||
const LAYOUT_BOUNDARY_MIN_IDLE_MS = 25
|
||||
/** 공백·문장부호로 끝난 어절에 수상한 자모·한영 오타가 있을 때 모델 검사를 시작할 최소 유휴 시간 (ms) */
|
||||
const SUSPICIOUS_BOUNDARY_MIN_IDLE_MS = 350
|
||||
/** Vim 명령줄(:wq 등)에서 공백 없이 엔터를 치기 전 한영 전환 최소 유휴 시간 (ms) */
|
||||
const LAYOUT_VIM_CMD_MIN_IDLE_MS = 135
|
||||
/** 공백 없이 단어 끝에서 멈췄을 때 한영 전환(Araso) 최소 유휴 시간 (ms) — 단어 입력 도중(some->sometime) 끼어들지 않게 함 */
|
||||
const LAYOUT_TRAILING_MIN_IDLE_MS = 650
|
||||
/** 타이핑 도중(짧은 유휴) 인플레이스 교정이 지울 수 있는 커서 앞 최대 글자 수 — 문장 전체 재작성 방지 */
|
||||
const MAX_FAST_DELETE_CHARS = 22
|
||||
/** 모델·자모 잡음 인플레이스 교정이 지울 수 있는 커서 앞 최대 글자 수 — 방금 친 마지막 어절만 교정 */
|
||||
const MAX_MODEL_DELETE_CHARS = 18
|
||||
/** 멈춘 뒤에도 인플레이스 교정이 한 번에 지울 수 있는 최대 글자 수 */
|
||||
const MAX_INPLACE_DELETE_CHARS = 32
|
||||
|
||||
/** 'typed-context' 에 대한 판단 — 제안 서비스로 그대로 넘길지(pass), 미룰지. */
|
||||
export type TypoVerdict = 'pass' | 'correcting' | 'checking'
|
||||
|
|
@ -116,8 +124,9 @@ const REVERT_LENGTH_TOLERANCE = 12
|
|||
export class TypoCorrectionService extends EventEmitter {
|
||||
private _applying = false
|
||||
private _check: { abort: AbortController; prefix: string; context: TypingContext } | null = null
|
||||
/** 마지막으로 결정적·모델 검사를 마친 구간 — 같은 구간을 되풀이해 묻지 않는다. */
|
||||
/** 마지막으로 결정적·모델 검사를 마친 구간(교정 전·후 모두 포함) — 같은 구간을 되풀이해 묻거나 연쇄 재교정하지 않는다. */
|
||||
private _lastCheckedRegion = ''
|
||||
private _lastPostRegion = ''
|
||||
private _lastApplied: AppliedCorrection | null = null
|
||||
private _vocabulary: { at: number; latin: Map<string, number>; known: Set<string> } | null = null
|
||||
|
||||
|
|
@ -154,7 +163,10 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
* `layoutOnly`: 한영 전환(Araso 방식 영→한·한→영·혼합어 자동 변환)만 즉시 교정하고,
|
||||
* 일반 철자·모델 오타는 제안 오버레이(`propose()`)에 맡긴다.
|
||||
*/
|
||||
handleTypingContext(context: TypingContext, options: { layoutOnly?: boolean } = {}): TypoVerdict {
|
||||
handleTypingContext(
|
||||
context: TypingContext,
|
||||
options: { layoutOnly?: boolean; trailingWordOnly?: boolean } = {}
|
||||
): TypoVerdict {
|
||||
this._watchRevert(context)
|
||||
if (this._applying) return 'correcting'
|
||||
|
||||
|
|
@ -170,6 +182,11 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
if (!this._eligible(context, { allowComposing: true })) return 'pass'
|
||||
|
||||
const prefix = context.prefix
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
if (region !== this._lastCheckedRegion && region !== this._lastPostRegion) {
|
||||
this._lastCheckedRegion = ''
|
||||
this._lastPostRegion = ''
|
||||
}
|
||||
const hasTrailingBoundary = /[ \t.,!?;:]$/u.test(prefix)
|
||||
const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':')
|
||||
const minLayoutIdle = hasTrailingBoundary
|
||||
|
|
@ -179,36 +196,79 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
: LAYOUT_TRAILING_MIN_IDLE_MS
|
||||
if (context.idleMs < minLayoutIdle) return 'pass'
|
||||
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
if (!region.trim() || region === this._lastCheckedRegion) return 'pass'
|
||||
if (!region.trim() || this._isRegionChecked(region)) return 'pass'
|
||||
|
||||
// Chromium/Discord 등은 영문 입력·공백 뒤에도 comp=true 를 유지하고, 한글 자판에서 ㅎ샤ㅗㅕㅠ에 를 치고
|
||||
// 멈췄을 때도 마지막 음절이 조합 중이다. 한영 전환(layoutOnly)은 조합 여부와 짧은 유휴에서도 즉시 허용하고,
|
||||
// 일반 철자·모델 검사는 터미널·개발 도구가 아니고 조합이 없으며 TYPO_MIN_IDLE_MS 이상 멈췄을 때만 실행한다.
|
||||
const isTerminalOrDev =
|
||||
context.terminalMode === true ||
|
||||
isTerminalApp(context.appName) ||
|
||||
!shouldLearnFromApp(context.appName)
|
||||
// Chromium/Discord/Electron 등은 한글 입력·공백 뒤에도 comp=true 를 유지한다.
|
||||
// 1단계(한영 전환 layoutOnly)는 단어 경계(25ms)와 어절 끝 유휴(650ms)에서 즉시 실행하고,
|
||||
// 2단계(철자 사전 + Gemma 배경 오타·한영 보정)는 터미널이 아니면서 유휴 조건을 충족했을 때 실행한다.
|
||||
const isTerminal = context.terminalMode === true || isTerminalApp(context.appName)
|
||||
const suspicious = hasSuspiciousTypo(region)
|
||||
const minFullCheckIdle =
|
||||
hasTrailingBoundary && suspicious
|
||||
? SUSPICIOUS_BOUNDARY_MIN_IDLE_MS
|
||||
: context.isComposing && !hasTrailingBoundary
|
||||
? Math.ceil(TYPO_MIN_IDLE_MS * 1.15)
|
||||
: TYPO_MIN_IDLE_MS
|
||||
const fullCheckEligible =
|
||||
options.layoutOnly !== true &&
|
||||
!isTerminalOrDev &&
|
||||
!context.isComposing &&
|
||||
context.idleMs >= TYPO_MIN_IDLE_MS
|
||||
!isTerminal &&
|
||||
context.idleMs >= minFullCheckIdle
|
||||
|
||||
const ignoredWords = configGet('typoIgnoredWords') ?? []
|
||||
const vocabulary = this._loadVocabulary()
|
||||
const keyAtDecision = this._deps.lastKeyAt()
|
||||
|
||||
const corrections = detectTypos(prefix, {
|
||||
const maxDeterministicSpan =
|
||||
options.trailingWordOnly === true || context.idleMs < TYPO_MIN_IDLE_MS
|
||||
? MAX_FAST_DELETE_CHARS
|
||||
: MAX_INPLACE_DELETE_CHARS
|
||||
const allCorrections = detectTypos(prefix, {
|
||||
includeTrailingToken: true,
|
||||
ignoredWords,
|
||||
vocabulary: vocabulary.latin,
|
||||
layoutOnly: !fullCheckEligible,
|
||||
terminalMode: context.terminalMode === true || isTerminalApp(context.appName)
|
||||
terminalMode: isTerminal
|
||||
})
|
||||
const baseCorrections: TypoCorrection[] = []
|
||||
if (options.trailingWordOnly !== true) {
|
||||
for (const c of allCorrections) {
|
||||
if (prefix.length - c.start <= maxDeterministicSpan) {
|
||||
baseCorrections.push(c)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// trailingWordOnly: 커서 끝에서 가까운 연속 교정 사슬만 남긴다 (예: "ㅑ ㅊ무'ㅅ " → "I can't ",
|
||||
// 반면 문장 앞쪽의 이미 지나간 긴 문장은 건드리지 않는다).
|
||||
for (let i = allCorrections.length - 1; i >= 0; i -= 1) {
|
||||
const c = allCorrections[i]
|
||||
if (prefix.length - c.start > maxDeterministicSpan) break
|
||||
if (baseCorrections.length === 0) {
|
||||
const tailAfter = prefix.slice(c.end)
|
||||
const nonSpaceTailLen = tailAfter.replace(/[ \t.,!?;:]/gu, '').length
|
||||
if (nonSpaceTailLen > 2) break
|
||||
baseCorrections.unshift(c)
|
||||
} else {
|
||||
const nextCorr = baseCorrections[0]
|
||||
const between = prefix.slice(c.end, nextCorr.start)
|
||||
if (/^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2) {
|
||||
baseCorrections.unshift(c)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const loneJamoRemovals =
|
||||
!isTerminal && options.trailingWordOnly !== true && (fullCheckEligible || baseCorrections.length > 0)
|
||||
? detectJamoNoise(prefix, { ignoredWords }).filter(
|
||||
(c) => c.to === '' && /[ \t]$/u.test(c.from) && prefix.length - c.start <= maxDeterministicSpan
|
||||
)
|
||||
: []
|
||||
const corrections =
|
||||
loneJamoRemovals.length > 0 ? mergeTypoCorrections(baseCorrections, loneJamoRemovals) : baseCorrections
|
||||
const plan = planTypoReplacement(prefix, corrections)
|
||||
if (plan) {
|
||||
this._lastCheckedRegion = region
|
||||
if (plan && plan.deleteCount <= maxDeterministicSpan) {
|
||||
this._markRegionChecked(region)
|
||||
void this._apply(plan, context, keyAtDecision)
|
||||
return 'correcting'
|
||||
}
|
||||
|
|
@ -216,13 +276,25 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
return 'pass'
|
||||
}
|
||||
|
||||
const worthModel = this._worthModelCheck(region)
|
||||
const model = configGet('typoAutoCorrectUseModel') !== false ? this._deps.warmModel() : null
|
||||
if (!model || !this._worthModelCheck(region)) {
|
||||
this._lastCheckedRegion = region
|
||||
if (!model || !worthModel) {
|
||||
const tailJamo = detectJamoNoise(prefix, { ignoredWords }).filter(
|
||||
(c) => prefix.length - c.start <= MAX_MODEL_DELETE_CHARS
|
||||
)
|
||||
const jamoPlan = planTypoReplacement(prefix, tailJamo)
|
||||
if (jamoPlan && jamoPlan.deleteCount <= MAX_MODEL_DELETE_CHARS) {
|
||||
this._markRegionChecked(region)
|
||||
void this._apply(jamoPlan, context, keyAtDecision)
|
||||
return 'correcting'
|
||||
}
|
||||
if (!worthModel || configGet('typoAutoCorrectUseModel') === false) {
|
||||
this._markRegionChecked(region)
|
||||
}
|
||||
return 'pass'
|
||||
}
|
||||
|
||||
this._lastCheckedRegion = region
|
||||
this._markRegionChecked(region)
|
||||
const abort = new AbortController()
|
||||
this._check = { abort, prefix, context }
|
||||
void this._runModelCheck(model, context, abort, keyAtDecision, ignoredWords, vocabulary.known)
|
||||
|
|
@ -313,10 +385,17 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
return true
|
||||
}
|
||||
|
||||
/** 모델에 물어볼 만한 구간인가 — 끝난 단어가 2개 이상인 글. */
|
||||
/** 모델에 물어볼 만한 구간인가 — 2어절 이상이거나 수상한 1어절(낱자·비상용 음절·미등록 영타) 또는 공백으로 끝난 4자 이상 어절. */
|
||||
private _worthModelCheck(region: string): boolean {
|
||||
if (region.replace(/\s+/gu, '').length < MODEL_CHECK_MIN_CHARS) return false
|
||||
return tokenizeWords(region).length >= 2
|
||||
const compact = region.replace(/\s+/gu, '')
|
||||
if (compact.length < MODEL_CHECK_MIN_CHARS) return false
|
||||
const words = tokenizeWords(region)
|
||||
if (words.length >= 2) return compact.length >= 4
|
||||
if (words.length === 1) {
|
||||
if (hasSuspiciousTypo(region)) return true
|
||||
return compact.length >= 4 && /[ \t.,!?;:]$/u.test(region)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private _loadVocabulary(): { latin: Map<string, number>; known: Set<string> } {
|
||||
|
|
@ -352,10 +431,15 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
let corrected = false
|
||||
try {
|
||||
const prefix = context.prefix
|
||||
const corrections = await this._askModel(model, prefix, abort.signal, ignoredWords, knownWords)
|
||||
const fromModel = await this._askModel(model, prefix, abort.signal, ignoredWords, knownWords)
|
||||
if (abort.signal.aborted || this._check?.abort !== abort) return
|
||||
const plan = planTypoReplacement(prefix, corrections)
|
||||
if (!plan) return
|
||||
// 인플레이스 모델 교정은 커서 바로 앞 어절(MAX_MODEL_DELETE_CHARS 이내)만 고친다.
|
||||
// 문장 앞쪽 단어를 고치려고 50~70자를 통째로 백스페이스하면 사용자의 다음 타이핑과 정면 충돌한다.
|
||||
const tailCorrections = mergeTypoCorrections(fromModel, detectJamoNoise(prefix, { ignoredWords })).filter(
|
||||
(c) => prefix.length - c.start <= MAX_MODEL_DELETE_CHARS
|
||||
)
|
||||
const plan = planTypoReplacement(prefix, tailCorrections)
|
||||
if (!plan || plan.deleteCount > MAX_MODEL_DELETE_CHARS) return
|
||||
// 검사하는 사이 사용자가 더 쳤으면 접두가 달라져 위에서 취소됐다. 여기서 한 번 더 키를 본다.
|
||||
this._check = null
|
||||
corrected = await this._apply(plan, context, keyAtDecision)
|
||||
|
|
@ -405,16 +489,33 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
|
||||
// ── 적용 ───────────────────────────────────────────────
|
||||
|
||||
private _isRegionChecked(region: string): boolean {
|
||||
return region === this._lastCheckedRegion || (this._lastPostRegion !== '' && region === this._lastPostRegion)
|
||||
}
|
||||
|
||||
private _markRegionChecked(region: string, postRegion?: string): void {
|
||||
this._lastCheckedRegion = region
|
||||
if (postRegion !== undefined) {
|
||||
this._lastPostRegion = postRegion
|
||||
}
|
||||
}
|
||||
|
||||
private _unmarkRegionChecked(region: string): void {
|
||||
if (this._lastCheckedRegion === region) this._lastCheckedRegion = ''
|
||||
if (this._lastPostRegion === region) this._lastPostRegion = ''
|
||||
}
|
||||
|
||||
private async _apply(plan: TypoReplacementPlan, context: TypingContext, keyAtDecision: number): Promise<boolean> {
|
||||
const preRegion = context.prefix.slice(typoRegionStart(context.prefix))
|
||||
if (this._deps.lastKeyAt() !== keyAtDecision) {
|
||||
this._lastCheckedRegion = ''
|
||||
this._unmarkRegionChecked(preRegion)
|
||||
logger.debug('오타 교정 취소: 판단 뒤 키 입력이 있었다')
|
||||
return false
|
||||
}
|
||||
if (context.windowHandle != null) {
|
||||
const current = this._deps.foregroundHandle()
|
||||
if (current !== null && current !== context.windowHandle) {
|
||||
this._lastCheckedRegion = ''
|
||||
this._unmarkRegionChecked(preRegion)
|
||||
logger.debug('오타 교정 취소: 포커스가 다른 창으로 옮겨 갔다')
|
||||
return false
|
||||
}
|
||||
|
|
@ -434,15 +535,19 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
: await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText)
|
||||
if (!ok) {
|
||||
cancelInsert()
|
||||
this._lastCheckedRegion = ''
|
||||
this._unmarkRegionChecked(preRegion)
|
||||
logger.warn('오타 교정 삽입 실패')
|
||||
return false
|
||||
}
|
||||
const postPrefix =
|
||||
context.prefix.slice(0, Math.max(0, context.prefix.length - plan.deleteCount)) + plan.insertText
|
||||
const postRegion = postPrefix.slice(typoRegionStart(postPrefix))
|
||||
this._markRegionChecked(preRegion, postRegion)
|
||||
this._lastApplied = {
|
||||
corrections: plan.corrections,
|
||||
completedAt: Date.now(),
|
||||
tailLength: plan.insertText.length,
|
||||
prefixLength: context.prefix.length - plan.deleteCount + plan.insertText.length,
|
||||
prefixLength: postPrefix.length,
|
||||
prefixBefore: context.prefix.slice(0, Math.max(0, context.prefix.length - plan.deleteCount)),
|
||||
windowHandle: context.windowHandle ?? null
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
type WritingRegister
|
||||
} from '@d3ro/core/writing-context'
|
||||
import { containsEmoji } from '@d3ro/core/input-intelligence'
|
||||
import { buildModelTypoHints } from '@d3ro/core/typo-correction'
|
||||
|
||||
const logger = getLogger('llm-prompts')
|
||||
|
||||
|
|
@ -455,14 +456,15 @@ export { SUGGESTION_SYSTEM_PROMPT, SUGGESTION_CONTINUE_SYSTEM_PROMPT }
|
|||
* 띄어쓰기·문체·단어 선택은 고치지 않는다. 호출자는 core `validateModelCorrections` 로
|
||||
* 결과를 다시 거른다(모델 출력은 신뢰하지 않는다).
|
||||
*/
|
||||
const TYPO_CHECK_SYSTEM_PROMPT = `사용자가 입력창에 방금 친 문장에서 오타만 찾습니다.
|
||||
const TYPO_CHECK_SYSTEM_PROMPT = `사용자가 입력창에 방금 친 문장에서 오타와 한영 자판 오타를 찾습니다.
|
||||
|
||||
규칙:
|
||||
- 잘못 누른 글자, 빠지거나 겹친 글자, 자모가 뒤바뀐 글자, 틀린 맞춤법 철자처럼 명백한 오타만 고르세요.
|
||||
- 한영키가 잘못 눌린 채 입력된 영단어·한글 단어(예: ㅗ디ㅐ => hello, ㅡㅁ가둥 => markdown, 네갸ㅜㅎ에서 => spring에서, dkssudgktpd => 안녕하세요)도 [한영 자판 변환 참고]와 문맥을 보고 바르게 고치세요.
|
||||
- 띄어쓰기, 문장부호, 말투, 단어 선택, 어순은 고치지 마세요.
|
||||
- 고유명사, 약어, 신조어, 외래어, 일부러 쓴 줄임말·구어체(ㅋㅋ, 넘, 젤 등)는 그대로 두세요.
|
||||
- 확실하지 않으면 고치지 마세요.
|
||||
- 오타마다 한 줄에 "틀린단어 => 고친단어" 형식으로 출력하세요. 단어는 문장에 나온 어절 그대로 쓰세요.
|
||||
- 오타마다 한 줄에 "틀린단어 => 고친단어" 형식으로 출력하세요. 왼쪽에는 [검사할 문장]에 나온 어절 원문을 그대로 쓰세요.
|
||||
- 오타가 없으면 "없음" 한 단어만 출력하세요. 다른 설명은 쓰지 마세요.`
|
||||
|
||||
export function buildTypoCheckPrompt(input: { sentence: string; previous?: string | null }): {
|
||||
|
|
@ -471,8 +473,13 @@ export function buildTypoCheckPrompt(input: { sentence: string; previous?: strin
|
|||
} {
|
||||
const sections: string[] = []
|
||||
const previous = input.previous?.replace(/\s+/gu, ' ').trim()
|
||||
const sentence = input.sentence.replace(/\s+/gu, ' ').trim()
|
||||
if (previous) sections.push('[앞 문맥]', previous.slice(-200), '')
|
||||
sections.push('[검사할 문장]', input.sentence.replace(/\s+/gu, ' ').trim())
|
||||
sections.push('[검사할 문장]', sentence)
|
||||
const layoutHints = buildModelTypoHints(sentence)
|
||||
if (layoutHints.length > 0) {
|
||||
sections.push('', '[한영 자판 변환 참고]', ...layoutHints)
|
||||
}
|
||||
return {
|
||||
systemPrompt: `${SUGGESTION_NO_THINK_PREFIX}\n${TYPO_CHECK_SYSTEM_PROMPT}`,
|
||||
text: sections.join('\n')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue