v4.3.29: 프롬프트가 스키마에 없는 도구를 지목하던 누출 차단 + 날씨 소스 라우팅

스키마 게이팅이 도구 실행을 전혀 막지 못하고 있었음. executeTool()은 이름으로
레지스트리를 조회할 뿐 스키마 포함 여부를 검사하지 않으므로, 프롬프트가 도구
이름을 알려주면 모델이 그대로 호출하고 그대로 실행됨.

실제 관측(2026-07-29): papa는 meteorologist 스킬이 꺼져 있어 tool-scope가 모든
weather_* 스키마를 정상적으로 제외했는데도(런타임 계측으로 weatherTools=(none)
확인), weather_kma가 매 날씨 턴마다 2회씩 실행되고 있었음. 모델이 파라미터
문서 없이 이름만 보고 호출한 것 — 날씨 도구 라우팅이 설명 문구를 두 번 고쳐도
계속 불안정했던 원인이 이것이었음.

누출 지점 3곳을 모두 실제 도구 목록 기반으로 전환:
- handle-chat 사전 리마인더: 하드코딩 "weather_kma/weather_search" → 보유한
  도구만 나열
- handle-chat AUTO-RECOVER toolHint: 동일
- personality-context [TOOLS] 블록: 키워드로만 켜지고 보유 여부를 안 봐서
  날씨 단어 하나에 9개 도구 사용법이 통째로 주입되던 것이 최대 누출원.
  카테고리→도구 매핑을 두고 하나라도 보유한 경우에만 블록 포함(호출자가
  목록을 안 주면 기존 동작 유지)
- system-prompt 날씨 라우팅 문장도 보유 도구에 따라 조건부 생성

배포 후 확인: 스킬이 꺼진 상태에서 날씨 질문 시 weather_* 호출이 완전히
사라지고 web_search로 폴백 — 의도한 동작.

함께 반영한 날씨 소스 우선순위(스킬이 켜졌을 때 적용):
한국은 weather_kma 우선(관측 기반, 강수확률 포함), 3일 초과·UV·시간별은
weather_openmeteo, 해외는 openmeteo, weather_search는 폴백. 구미 실측 비교에서
세 소스가 강수확률 20% vs 0%, 최고기온 34.0 vs 36.5로 갈렸음.

전체 121개 테스트 통과.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-07-29 17:54:59 +09:00
1 parent a1c653655f
commit 5f99dab941
4 files changed
+87 -11

No files matched your search

+8 -3
View File
@@ -849,7 +849,7 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
// time and could only ever report a temperature range and a sky word, so answers came
// out as one bare sentence with no precipitation chance at all. The "not web_search"
// part is still worth keeping; the "always" part was steering to the weakest option.
description: 'Current weather or 5-day min/max forecast for any city/coordinates (OpenWeather). Returns temperature range and sky condition only — NO precipitation chance, humidity or wind. For a forecast the user will act on ("비 와?", "우산 챙겨야 해?", tomorrow/this week), prefer weather_openmeteo, which adds precipitation probability and hourly detail. Never use web_search for weather.',
description: 'FALLBACK ONLY — do not pick this first. OpenWeather: current conditions or 5-day min/max for any city/coordinates, but it returns temperature and a sky word ONLY (no precipitation chance, humidity or wind), so it cannot answer "비 와?" / "우산 챙겨야 해?". Correct order is weather_kma for Korea, weather_openmeteo everywhere else (it handles Korean city names for foreign cities too — "파리", "도쿄" all resolve). Use this one only after one of those actually failed. Never use web_search for weather.',
parameters: {
type: 'object', required: ['location'],
properties: {
@@ -878,7 +878,7 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
type: 'function',
function: {
name: 'weather_openmeteo',
description: 'PREFERRED forecast tool. Detailed weather via Open-Meteo (free, no key) — includes precipitation probability, hourly detail, UV index, ECMWF/GFS models, up to 16 days. Use this for any "will it rain / what is tomorrow like / this week" question; weather_search only carries temperature and a sky word, which is not enough to answer those.',
description: 'Preferred forecast tool OUTSIDE Korea, and inside Korea whenever the range exceeds weather_kma\'s 3 days or the question needs UV / hourly detail. Open-Meteo (free, no key): precipitation probability, hourly breakdown, UV index, ECMWF/GFS models, up to 16 days. For a Korean location within 3 days call weather_kma first — it is observation-backed and its numbers differ materially (verified 2026-07-29: 20% vs 0% rain, highs 1.5-2.5°C apart for the same day). Never use web_search for weather.',
parameters: {
type: 'object', required: ['location'],
properties: {
@@ -893,7 +893,12 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
type: 'function',
function: {
name: 'weather_kma',
description: '기상청 공식 API로 한국 날씨 조회. 초단기실황(현재)과 단기예보(3일). 한국 내 위치에 가장 정확. data.go.kr API 키 필요.',
// 2026-07-29: promoted to first choice for Korea. Head-to-head on 구미 the three sources
// disagreed in ways that matter — KMA gave 20% rain where Open-Meteo said 0%, and KMA's
// highs ran 1.5-2.5°C cooler (34.0 vs 36.5 for the same day), which matches its far
// denser domestic observation network. "current" is a real measurement, not a model
// estimate like the other two.
description: '한국 위치라면 이 도구를 먼저 쓸 것 (기상청 공식 API). type="current"는 관측 실황(기온·습도·풍향·풍속·강수형태) — 추정치가 아닌 실측값이라 국내에서 가장 신뢰도 높음. type="forecast"는 3일 단기예보(강수확률 포함). 한국 도시명을 그대로 넣으면 된다. 3일을 넘는 예보나 UV·시간별 상세가 필요하면 weather_openmeteo로 보완할 것. 해외 지역에는 사용 불가.',
parameters: {
type: 'object', required: ['location'],
properties: {
+24 -6
View File
@@ -122,7 +122,7 @@ export interface HandleChatDeps {
getModelProfileExtraPrompt: (modelName: string) => string;
extractLikelyUrl: (message: string) => string | null;
evaluateBrowserSnapshotQuality: (snapshot: string, snapshotElements: number, goal: string) => any;
buildPersonalityContext: (sessionId: string, workspacePath: string, messageText: string, executionMode: string, historyLength: number, recentContextText?: string) => Promise<string>;
buildPersonalityContext: (sessionId: string, workspacePath: string, messageText: string, executionMode: string, historyLength: number, recentContextText?: string, availableToolNames?: readonly string[]) => Promise<string>;
broadcastWS: (data: object) => void;
codeAiLocalSessions: Set<string>;
CONFIG_DIR_PATH: string;
@@ -606,7 +606,7 @@ async function handleChat(
}
const lastAssistantMsg = [...history].reverse().find(h => h.role === 'assistant')?.content;
const personalityCtx = await buildPersonalityContext(sessionId, workspacePath, message, executionMode || 'interactive', history.length, String(lastAssistantMsg || '').slice(-500));
const personalityCtx = await buildPersonalityContext(sessionId, workspacePath, message, executionMode || 'interactive', history.length, String(lastAssistantMsg || '').slice(-500), tools.map((t: any) => String(t?.function?.name || '')));
// Inject active browser session state so LLM knows to reuse it instead of re-opening
const browserInfo = getBrowserSessionInfo(sessionId);
@@ -685,9 +685,23 @@ async function handleChat(
// something and grabbed the nearest available anchor).
const newsRequest = isNewsRequest(message);
messages.push({ role: 'assistant', content: 'Got it — checking now.' });
const _has = (n: string) => tools.some((t: any) => String(t?.function?.name || '') === n);
const _weatherHint = ['weather_kma', 'weather_openmeteo', 'weather_search'].filter(_has).join(' / ');
const _availableGroundingHint = [
newsRequest && _has('news_search') ? 'news_search for news' : '',
_has('web_search') ? 'web_search for general lookups' : '',
_weatherHint ? `${_weatherHint} for weather/forecast` : '',
].filter(Boolean).join(', ') || 'whichever tool above fits';
// Only ever name tools this turn actually has. Naming one that was filtered out of the
// schema does not merely waste words: executeTool() resolves by NAME against the registry
// and never checks schema membership, so the model happily calls a tool it was never given
// — without its parameter documentation, guessing arguments. Verified 2026-07-29: papa has
// the meteorologist skill OFF, so tool-scope correctly withheld every weather_* schema, yet
// weather_kma still ran twice per weather turn purely because this reminder named it. That
// also explains why weather routing behaved erratically: the model was calling blind.
messages.push({
role: 'user',
content: `Reminder: this needs live/current data. Call a tool first (${newsRequest ? 'news_search for news' : 'web_search for news'}, weather_kma/weather_search for weather/forecast, etc.) before writing anything. Do NOT answer from memory or training data.${newsRequest ? ' If this message names a specific topic, pass it as news_search\'s query param; otherwise (a bare "뉴스"/"news" request) call news_search several times across different categories (e.g. "top", "business", "technology", "world", "sports") rather than a single bare no-category call — a lone bare call tends to return only 4-5 stories clustered around 1-2 dominant topics; spanning categories like this builds a well-rounded ~8-10 item digest. Do NOT default to unrelated topics from earlier in this conversation unless the user explicitly asks for updates on them.' : ''}`,
content: `Reminder: this needs live/current data. Call a tool first (${_availableGroundingHint}) before writing anything. Do NOT answer from memory or training data.${newsRequest ? ' If this message names a specific topic, pass it as news_search\'s query param; otherwise (a bare "뉴스"/"news" request) call news_search several times across different categories (e.g. "top", "business", "technology", "world", "sports") rather than a single bare no-category call — a lone bare call tends to return only 4-5 stories clustered around 1-2 dominant topics; spanning categories like this builds a well-rounded ~8-10 item digest. Do NOT default to unrelated topics from earlier in this conversation unless the user explicitly asks for updates on them.' : ''}`,
});
} else if (isFactualInfoRequest(message)) {
messages.push({ role: 'assistant', content: 'Got it — let me verify that first.' });
@@ -1573,9 +1587,13 @@ async function handleChat(
} else {
const isWeatherRequest = /(날씨|기온|예보|미세먼지|황사)/.test(message) || /\b(weather|forecast)\b/i.test(message);
const newsRequest = isNewsRequest(message);
const toolHint = isWeatherRequest
? 'the weather tool (weather_kma / weather_search, etc. — NOT web_search)'
: newsRequest
// Same rule as the pre-emptive reminder above: name only tools this turn actually
// holds, because executeTool() dispatches by name and would run a withheld tool blind.
const _avail = (n: string) => tools.some((t: any) => String(t?.function?.name || '') === n);
const _weatherAvail = ['weather_kma', 'weather_openmeteo', 'weather_search'].filter(_avail);
const toolHint = isWeatherRequest && _weatherAvail.length
? `the weather tool (${_weatherAvail.join(' / ')} — NOT web_search)`
: newsRequest && _avail('news_search')
? 'the news_search tool (NOT web_search)'
: 'the web_search tool';
const scopeHint = newsRequest
+37 -1
View File
@@ -276,6 +276,7 @@ return async function buildPersonalityContext(
executionMode: string,
historyLength: number,
recentContextText: string = '',
availableToolNames: readonly string[] = [],
): Promise<string> {
// Per-request file cache — prevents reading USER.md/SOUL.md twice
@@ -330,6 +331,41 @@ return async function buildPersonalityContext(
const cats = detectToolCategories(`${recentContextText}\n${messageText}`, sessionId);
// Build tool blocks for detected categories
// A [TOOLS] block documents tools by name. Until 2026-07-29 the blocks were selected purely
// from message keywords, with no check that the turn actually holds those tools — so a single
// weather word injected the full 9-tool weather reference, and the model dutifully called
// weather_search even for a user whose meteorologist skill was switched OFF and whose schema
// therefore contained no weather tool at all. executeTool() resolves by name against the
// registry without checking schema membership, so those calls ran: the tool executed with no
// parameter documentation behind it, which is also why its behaviour looked erratic.
// Keep a block only when at least one tool it describes is really on offer.
const CATEGORY_TOOLS: Record<string, string[]> = {
weather: ['weather_search', 'weather_openmeteo', 'weather_kma', 'weather_airpollution', 'weather_airkorea', 'weather_nasa_power', 'weather_era5', 'weather_cds', 'weather_cmip6'],
ollama_web: ['ollama_web_search', 'ollama_web_fetch'],
email: ['email_list', 'email_read', 'email_send', 'email_search', 'email_delete'],
kakao: ['kakao_send_message'],
pdf: ['pdf_read', 'pdf_extract_images'],
image_ocr: ['image_read'],
sqlite: ['sqlite_query'],
pptx: ['create_presentation', 'edit_presentation'],
pubmed: ['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext'],
scholar: ['openalex_search', 'semantic_search'],
files: ['coder_read_file', 'coder_write_file', 'coder_list_files'],
shell: ['shell', 'run_command'],
schedule: ['schedule_job'],
browser: ['browser_open', 'browser_snapshot'],
desktop: ['desktop_screenshot', 'desktop_click'],
photo: ['search_images'],
python: ['python_eval'],
};
const _availSet = new Set(availableToolNames);
// Empty list = caller did not tell us; fall back to the old permissive behaviour rather than
// silently stripping every block.
const categoryIsAvailable = (cat: string): boolean => {
if (_availSet.size === 0) return true;
const needed = CATEGORY_TOOLS[cat];
return !needed || needed.some(n => _availSet.has(n));
};
const toolBlockParts: string[] = [];
for (const cat of cats) {
if (cat === 'email') {
@@ -339,7 +375,7 @@ return async function buildPersonalityContext(
continue;
}
}
if (TOOL_BLOCKS[cat]) toolBlockParts.push(TOOL_BLOCKS[cat]);
if (TOOL_BLOCKS[cat] && categoryIsAvailable(cat)) toolBlockParts.push(TOOL_BLOCKS[cat]);
}
// Build memory snippets — pass fileCache so USER.md/SOUL.md are not re-read
+18 -1
View File
@@ -58,6 +58,7 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
const skillsCtx = input.skillsCtx || '';
const tools = input.toolNames.map(n => ({ function: { name: n } }));
const executionModeSystemBlock = (() => {
if (executionMode === 'background_task') {
return [
@@ -89,6 +90,22 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
const toolNames = new Set(tools.map((t: any) => String(t?.function?.name || '')));
const hasToolPrefix = (p: string) => tools.some((t: any) => String(t?.function?.name || '').startsWith(p));
const hasBrowserTools = hasToolPrefix('browser_');
// Weather-source routing, but only when the turn actually holds weather tools. Naming a
// withheld tool here is not harmless: executeTool() dispatches by name against the registry
// without checking schema membership, so the model will call it anyway — blind, with no
// parameter documentation. That is exactly how weather_kma kept running for a user whose
// meteorologist skill was switched off (found 2026-07-29), and why its routing looked erratic.
const weatherRoutingBlock = (() => {
const has = (n: string) => toolNames.has(n);
const kma = has('weather_kma');
const meteo = has('weather_openmeteo');
if (!kma && !meteo) return '';
if (kma && meteo) {
return 'Pick the source by location: for anywhere in Korea call weather_kma first (observation-backed, includes precipitation chance), and add weather_openmeteo only when you need more than 3 days out or UV/hourly detail; outside Korea use weather_openmeteo. If the tool you called did not return precipitation chance, do NOT invent one and do NOT quietly skip it — call one that provides it. ';
}
if (kma) return 'Use weather_kma (Korea only, observation-backed, includes precipitation chance). If it cannot cover the location or range, say so rather than estimating. ';
return 'Use weather_openmeteo — it carries precipitation probability and hourly detail. If it did not return a precipitation chance, do NOT invent one. ';
})();
const browserRuleBlock = hasBrowserTools
? '\nBROWSER RULE: NEVER call browser_open, browser_snapshot, browser_click, browser_fill, browser_scroll, or any browser_* tool unless the user EXPLICITLY asks to use the browser (e.g. "브라우저로 열어줘", "Chrome으로 봐줘", "사이트 직접 들어가봐"). "열어줘" or "보여줘" alone is NOT a browser request — answer from knowledge, use web_fetch/web_search, or output the relevant URL/embed. Pasting a URL or asking a question is also NOT a browser request.'
: '';
@@ -124,5 +141,5 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know. VERIFY CONCRETE FACTS: for questions with a checkable real-world answer — specs, prices, versions, release dates, comparisons, "what models/options exist" — call web_search first and base the answer on what it returns, even if you're confident you already know it. Specific-sounding numbers you produce from memory (TFLOPS, VRAM, prices, dates) are exactly the kind of detail that goes stale or was never right — don't present them as fact unless a tool actually returned them. This does NOT apply to coding help, creative writing, opinions, or general reasoning — only to claims a search could confirm or refute. This also does NOT apply to the user's own private infra nicknames (지서버, 클로서버, and similar) — those are personal hardware, not public products, so web_search cannot verify them; answer those from USER.md/SOUL.md/[RECALLED_FACTS] context instead.
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day. A search result reporting a "closing price" or "today's headline" is not proof today is a trading/business day — cross-check it against the actual current date above, and if they conflict (e.g. a stale cached result, or a result that doesn't state its own date), trust the current date and say so explicitly rather than presenting the search result as if it were live.${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}
CHEMISTRY NOTATION: NEVER draw molecular structures as ASCII art (H/C/#/=/\\/| characters arranged to look like a diagram) — it always renders as garbled, misaligned text. Instead: for a formula or reaction, use LaTeX inside $...$ (e.g. $\\ce{C4H10}$, $\\ce{2H2 + O2 -> 2H2O}$ — mhchem extension is loaded). For an actual 2D structure with real bond lines (rings, branches), output a \`\`\`smiles\`\`\` code block containing the SMILES string (e.g. \`\`\`smiles\\nc1ccccc1\\n\`\`\` for benzene, \`\`\`smiles\\nCC(=O)Oc1ccccc1C(=O)O\\n\`\`\` for aspirin) — the client automatically renders it as a proper 2D diagram with bond lines.${codeOutputRuleBlock}${packageInstallRuleBlock}
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. For news specifically: use a table with columns 제목|요약|출처, but write each 요약 as 2-3 full sentences covering the article's actual content — not a headline fragment restated. Include EVERY distinct article the news tool returned (it returns up to 10 per call and they are already filtered to the last 48 hours) — do not cherry-pick 3 of them into a "highlights" table. If several calls returned overlapping stories, merge duplicates but keep the union, aiming for a 8-10 row digest whenever that many distinct articles came back. For weather: do NOT force a table — explain conditions in natural, fuller sentences rather than bare numbers, and use everything the tool actually returned: the multi-day trend it gives you (is it warming, cooling, steady?), precipitation chance, and anything notable. If the tool you called did not return precipitation chance, do NOT invent one and do NOT quietly skip it — call weather_openmeteo, which provides it. Never pad a weather answer with figures no tool gave you.${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph. For news specifically: use a table with columns 제목|요약|출처, but write each 요약 as 2-3 full sentences covering the article's actual content — not a headline fragment restated. Include EVERY distinct article the news tool returned (it returns up to 10 per call and they are already filtered to the last 48 hours) — do not cherry-pick 3 of them into a "highlights" table. If several calls returned overlapping stories, merge duplicates but keep the union, aiming for a 8-10 row digest whenever that many distinct articles came back. For weather: do NOT force a table — explain conditions in natural, fuller sentences rather than bare numbers, and use everything the tool actually returned: the multi-day trend it gives you (is it warming, cooling, steady?), precipitation chance, and anything notable. ${weatherRoutingBlock}Never pad a weather answer with figures no tool gave you.${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
}