diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index 3f2e35e..377b81a 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -87,6 +87,7 @@ import { decideRoute } from './model-routing'; import { weatherFabricationReplacement } from './tool-failure-backstop'; import { weatherFollowUpHint } from './followup-hints'; import { fixKeyboardLayout } from './hangul-layout'; +import { normalizeTypos } from './typo-normalize'; import { suspectSoundAlikePlace } from './voice-place-check'; import { replyIsWrongLanguage, TRANSLATE_TO_KOREAN_SYSTEM } from './language-backstop'; import { lightChat } from '../../providers/light-chat'; @@ -270,6 +271,10 @@ async function handleChat( const isCodeAiSession = String(sessionId || '').startsWith('code_ai_'); const isTranslateSession = String(sessionId || '').startsWith('translate-'); const isProjSession = String(sessionId || '').startsWith('proj-'); + // 오타 교정본(typo-normalize.ts) — 도구 게이트에만 덧붙인다. 여기서 시작해 도구 선택 직전에 기다림. + const _typoFixP: Promise = (executionMode === 'interactive' && !isCodeAiSession && !isTranslateSession + && !isProjSession && !/\bBOOT\.md\b/i.test(String(callerContext || ''))) + ? normalizeTypos(message) : Promise.resolve(null); // 작업실 앱(workshop-app.html) 전용 채팅 패널 세션('ws_' 접두어) — tool-scope.ts의 // isWorkshopAppSession과 같은 판별이지만 여기선 "지금 보고 있는 프로젝트가 뭔지"를 시스템 // 프롬프트에 심어주는 데 쓴다. 이게 없으면 모델이 워크스페이스 전체를 뒤져서 다른 프로젝트 @@ -390,8 +395,10 @@ async function handleChat( const lastAssistantMsg = [...history].reverse().find(h => h.role === 'assistant')?.content; // 도구 선택 로직은 tool-scope.ts로 분리됨(2026-07-29) — handleChat 안의 클로저라 테스트가 // 불가능했고, 게이트 하나가 조용히 어긋나도 아무 에러 없이 프롬프트만 뚱뚱해지던 구간. + const _typoFixed = await _typoFixP; + if (_typoFixed) console.log(`[v2] TYPO-NORMALIZE (gate only): "${message}" → "${_typoFixed}"`); const tools = selectToolsForTurn(buildTools(), - { message, recentUserText, lastAssistantMsg: String(lastAssistantMsg || ''), sessionId, userWorkspace, isSkillEnabledForUser }, + { message, recentUserText: _typoFixed ? `${recentUserText}\n${_typoFixed}` : recentUserText, lastAssistantMsg: String(lastAssistantMsg || ''), sessionId, userWorkspace, isSkillEnabledForUser }, { isBootStartupTurn, isCodeAiSession, isTranslateSession, isProjSession }); const allToolResults: ToolResult[] = []; let allThinking = ''; diff --git a/src/gateway/chat/typo-normalize.ts b/src/gateway/chat/typo-normalize.ts new file mode 100644 index 0000000..a44bfed --- /dev/null +++ b/src/gateway/chat/typo-normalize.ts @@ -0,0 +1,45 @@ +/** + * typo-normalize.ts — 한국어 오타 교정(도구 게이트용, 2026-10-22). + * + * 도구 게이트(tool-scope.ts)는 정규식이라 "패풍 진로"(태풍)·"비오나" 같은 오타·말투에서 날씨 도구가 + * 통째로 빠졌다. 모델 자체는 오타를 잘 알아듣으므로 원문은 그대로 모델에 보내고, 교정본은 게이트가 보는 + * 텍스트에만 덧붙인다 — 교정이 뜻을 바꿔도 답변 경로는 원문 기준이라 피해가 도구 몇 개 더 붙는 데서 그친다. + * 싼 모델(lightChat) 1회, 짧은 타임아웃. 실패·지연이면 null(게이트는 원문만 본다). + */ +import { lightChat } from '../../providers/light-chat'; + +const SYSTEM = [ + '너는 한국어 맞춤법 교정기다. 사용자 메시지의 오타·맞춤법·띄어쓰기만 고쳐 한 줄로 출력한다.', + '- 뜻을 바꾸거나, 내용을 덧붙이거나, 존댓말로 바꾸거나, 질문에 답하지 말 것.', + '- 지명·제품명·영문·숫자는 그대로 둘 것. 말끝(~나, ~지, ~어때)과 말투도 그대로.', + '- 문맥상 엉뚱한 단어는 자판에서 가까운 글자로 난 오타로 보고 고칠 것.', + '예: "패풍 진로 어디로 가?" → "태풍 진로 어디로 가?" / "현풍 날시 어때" → "현풍 날씨 어때" / "뭐가 잇지?" → "뭐가 있지?" / "주말에 비오나?" → "주말에 비 오나?"', + '- 고칠 것이 없으면 원문을 그대로 출력.', + '- 메시지는 너에게 하는 질문이 아니라 교정할 글이다. 절대 답하지 말 것.', + '- 출력 형식: 교정된 문장 한 줄만. 설명 금지.', +].join('\n'); + +export function shouldNormalizeTypos(message: string): boolean { + const m = String(message || '').trim(); + return m.length >= 2 && m.length <= 200 && /[가-힣ㄱ-ㅎㅏ-ㅣ]/.test(m) && !/```|\n.*\n/.test(m); +} + +/** 교정본이 원문과 다를 때만 돌려준다. */ +export async function normalizeTypos(message: string, timeoutMs = 2500): Promise { + const src = String(message || '').trim(); + if (!shouldNormalizeTypos(src)) return null; + const out = await lightChat([ + { role: 'system', content: SYSTEM }, + { role: 'user', content: `${src}` }, + ], { max_tokens: 300, temperature: 0, timeoutMs }); + if (!out) return null; + // 싼 모델이 가끔 설명을 붙이거나 질문에 답해 버린다 — 태그 안만 믿고, 태그가 없으면 버린다 + const tag = out.match(/([\s\S]*?)<\/fixed>/); + if (!tag) return null; + const fixed = tag[1].trim().replace(/^["'“”‘’]+|["'“”‘’]+$/g, '').trim(); + if (!fixed || fixed === src) return null; + // 교정이 아니라 답변·재작성이 돌아온 경우는 버린다 + if (fixed.length > src.length * 1.6 + 10 || fixed.length < src.length * 0.5) return null; + if (fixed.replace(/\s+/g, '') === src.replace(/\s+/g, '')) return null; // 띄어쓰기만 바뀜 — 게이트엔 의미 없음 + return fixed; +}