diff --git a/src/gateway/chat/handle-chat.ts b/src/gateway/chat/handle-chat.ts index e893364..eab0f0e 100644 --- a/src/gateway/chat/handle-chat.ts +++ b/src/gateway/chat/handle-chat.ts @@ -96,7 +96,7 @@ import { lightChat } from '../../providers/light-chat'; import { replyLooksEmpty, appendDroppedSearchImages, appendGeneratedChartImages } from './reply-content'; import { evaluateSearchBudget } from './search-budget'; import { adaptNudgesForClaude, isClaudeModel } from './claude-nudge-adapt'; -import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceWorkshopSaveRetry, shouldForceWorkshopFileRetry, shouldForceUnverifiedSpecRetry, unverifiedSpecPrompt, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions'; +import { decideAutoRecover, shouldForceMessagingRetry as decideMessagingRetry, shouldForceWorkshopSaveRetry, shouldForceWorkshopFileRetry, shouldForceUnverifiedSpecRetry, unverifiedSpecPrompt, shouldForceSearchOfferRetry, searchOfferPrompt, shouldForceEmptyGroundingRetry as decideEmptyGroundingRetry, GROUNDING_TOOL_PATTERN } from './retry-decisions'; import { logToolSkip } from './tool-skip-log'; import { checkNumericGrounding } from './numeric-grounding'; import { decideSearchAbandonmentRetry } from './search-abandonment'; @@ -481,6 +481,8 @@ async function handleChat( // 확인 도구 없이 규격·호환을 사실처럼 단정한 작업실 답을 한 번 되묻는다(2026-09-30 duck 서보 사건). let unverifiedSpecForcedRetries = 0; const MAX_UNVERIFIED_SPEC_FORCED_RETRIES = 1; + let searchOfferForcedRetries = 0; + const MAX_SEARCH_OFFER_FORCED_RETRIES = 1; let emptyGroundingForcedRetries = 0; const MAX_EMPTY_GROUNDING_FORCED_RETRIES = 1; let numericGroundingForcedRetries = 0; @@ -2125,6 +2127,19 @@ async function handleChat( continue; } + // SEARCH-OFFER POST-CHECK (2026-11-22). "원하시면 검색해 보겠습니다"로 끝내고 검색은 안 한 답 — + // 사용자가 "검색"을 따로 쳐야 했다. 허락을 구하지 말고 바로 검색하게 한 번 되돌린다. + if (shouldForceSearchOfferRetry({ candidateText, toolResults: allToolResults }) + && searchOfferForcedRetries < MAX_SEARCH_OFFER_FORCED_RETRIES) { + searchOfferForcedRetries++; + console.log(`[v2] SEARCH-OFFER POST-CHECK (${searchOfferForcedRetries}/${MAX_SEARCH_OFFER_FORCED_RETRIES}): answer offers to search instead of searching. Re-prompting...`); + sendSSE('info', { message: 'Re-prompting model: search now instead of asking...' }); + messages.push({ role: 'assistant', content: candidateText }); + messages.push({ role: 'user', content: searchOfferPrompt() }); + lastRoundWasGuardReprompt = true; + continue; + } + const groundingResultsThisTurn = allToolResults.filter((r) => GROUNDING_TOOL_PATTERN.test(String(r?.name || '')), ); diff --git a/src/gateway/chat/retry-decisions.ts b/src/gateway/chat/retry-decisions.ts index 54e7b85..9827418 100644 --- a/src/gateway/chat/retry-decisions.ts +++ b/src/gateway/chat/retry-decisions.ts @@ -311,6 +311,31 @@ export function unverifiedSpecPrompt(): string { + 'If the user gave a link, open it (web_fetch / browser) before saying what the product is — never identify a product from the URL text alone; if it cannot be opened, say so. Never say you "found" or "searched" something unless a search tool actually ran this turn, and never give a model name or a spec number (weight, size, torque, voltage) that no tool result shows — if you recall one from memory, label it "from memory, unverified". Never write that a part "is designed for", "fits", or "is compatible with" something unless a tool result in this turn shows it. If your earlier answer was wrong, say so.'; } +// SEARCH-OFFER (2026-11-22). 메인채팅이 "원하시면 그 방향으로 검색해 보겠습니다"로 답을 끝내서 사용자가 +// "검색"이라고 따로 쳐야 했다. 검색은 허락받을 일이 아니다 — 답 끝(마지막 문장)이 검색 제안/의사 확인이고 +// 이번 턴에 검색·조회 도구가 하나도 안 돌았으면 한 번 되돌려 바로 검색하게 한다. +// 도구가 이미 돈 턴은 건드리지 않는다(루프 방지) — 판정은 "이번 턴 검색 도구 호출 여부"뿐이다. +export interface SearchOfferInput { + candidateText: string; + toolResults: readonly { name?: string }[]; +} + +const SEARCH_OFFER_TAIL = /(검색|조사|찾아)\s*(해\s*)?(드릴까요|볼까요|드리겠습니다|보겠습니다|볼게요|드릴게요)|(원하시면|필요하시면|괜찮으시면|말씀해\s*주시면)[^.\n?]{0,40}(검색|찾아|조사)|(계속|이어서)\s*(검색|찾아|조사)[^.\n]{0,12}(까요|ㄹ까요)/; +const SEARCH_RAN = /^(web_search|web_fetch|news_search|ollama_web|place_search|openalex_search|pubmed_)/i; + +export function shouldForceSearchOfferRetry(input: SearchOfferInput): boolean { + const text = String(input.candidateText || '').replace(/\*+/g, '').trim(); + if (!text || text.length > 1500) return false; + // 마지막 두 문장 안에 있을 때만 — 본문 중간의 "검색해 보니" 같은 서술은 거른다. + const tail = text.split(/(?<=[.!?。])\s+|\n+/).filter(Boolean).slice(-2).join(' '); + if (!SEARCH_OFFER_TAIL.test(tail)) return false; + return !input.toolResults.some(r => SEARCH_RAN.test(String(r?.name || ''))); +} + +export function searchOfferPrompt(): string { + return 'Your answer ends by offering to search ("검색해 볼까요 / 원하시면 검색해 보겠습니다") instead of searching. Never ask permission to search — the user already asked the question. Run web_search NOW with a specific query for what is missing, then answer from the results (cite sources, and say plainly what the results did not show). If no search is actually needed, rewrite the answer without any offer to search.'; +} + export interface EmptyGroundingInput { message: string; /** Tool results this turn; only grounding tools are considered. */ diff --git a/tests/retry-decisions.test.ts b/tests/retry-decisions.test.ts index 5f955f9..4884362 100644 --- a/tests/retry-decisions.test.ts +++ b/tests/retry-decisions.test.ts @@ -516,3 +516,20 @@ describe('decideAutoRecover — Haiku 전환 후 오발동(2026-10-22)', () => { assert.equal(d.shouldRetry, true); }); }); + +import { shouldForceSearchOfferRetry } from '../src/gateway/chat/retry-decisions'; + +describe('shouldForceSearchOfferRetry', () => { + test('검색 제안으로 끝나고 검색 안 했으면 되돌린다', () => { + assert.equal(shouldForceSearchOfferRetry({ candidateText: '확인하지 못했습니다.\n\n원하시면 그 방향으로 검색해 보겠습니다.', toolResults: [] }), true); + assert.equal(shouldForceSearchOfferRetry({ candidateText: '배혜지 기상캐스터에 대한 정보를 찾아드릴까요?', toolResults: [] }), true); + assert.equal(shouldForceSearchOfferRetry({ candidateText: '국가별 비율이 필요하시면 검색해 보겠습니다.', toolResults: [] }), true); + }); + test('이번 턴에 검색이 돌았으면 건드리지 않는다', () => { + assert.equal(shouldForceSearchOfferRetry({ candidateText: '결과입니다. 더 필요하시면 검색해 드릴까요?', toolResults: [{ name: 'web_search' }] }), false); + }); + test('본문 중간의 검색 서술·일반 답은 통과', () => { + assert.equal(shouldForceSearchOfferRetry({ candidateText: '검색해 보니 A입니다. 그래서 B입니다. 이상입니다.', toolResults: [] }), false); + assert.equal(shouldForceSearchOfferRetry({ candidateText: '770억 ÷ 1,050억 ≈ 73%입니다.', toolResults: [] }), false); + }); +});