v4.3.37: 날씨 지도 블랙스크린·스트리밍 레이스 수정, 태풍 예상진로(KMA/NHC) 지도 추가

- Windy iframe이 실제 로딩보다 훨씬 먼저 스피너를 걷어 몇 초간 완전 블랙스크린으로
  보이던 문제 수정 (반투명 오버레이 + 고정 타이머)
- 스트리밍 중 Windy URL이 아직 다 도착 안 한 상태에서 잘린 좌표로 지도를
  이동시키고 잠가버리던 레이스 컨디션 수정
- Windy는 태풍 예상 진로(향후 경로)를 그리지 않는다는 걸 명확히 하고, 실제로
  경로를 그리는 기상청 태풍 페이지 + NOAA/NHC 페이지를 지도에 임베드하는 기능 추가
  (nhc_active_storms 신규 도구로 이름→공식 forecast-track URL 조회, 대양/슬롯
  번호를 모델이 추측하지 않도록 함)
- 채팅창에 원문 도구호출(web_search{...} 등)이 그대로 노출되던 누출 수정 —
  기존 정리 로직은 메시지 전체/끝부분만 잡아서 중간에 낀 누출은 못 걸렀음
- Windy/NHC URL 정규식이 마크다운 괄호·별표까지 삼켜 URL을 깨뜨리던 과매칭 버그 수정
- 모델이 NHC URL의 슬롯 번호를 잘못 베끼는 경우에 대비해, 도구가 찾은 검증된
  URL을 직접 스트림에 실어보내 지도가 항상 정확한 폭풍을 가리키도록 함

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5 committed 2026-07-30 13:02:56 +09:00
1 parent 52a42e26f0
commit b61fcd1889
8 files changed
+371 -66

No files matched your search

+4
View File
@@ -161,3 +161,7 @@ tests/.golden-progress.log
.DS_Store
Thumbs.db
desktop.ini
# Valetudo 로봇청소기 (2호기 설치용 보관)
valetudo-helper-miioota
voicepack_ko/
+15 -2
View File
@@ -979,16 +979,29 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
type: 'function',
function: {
name: 'weather_map_screenshot',
description: 'Capture a real screenshot of a rendered Windy weather map (radar, satellite, wind, precipitation, etc.) so you can actually SEE it before describing it. Call this with the exact embed.windy.com URL you just generated — do not guess what the map shows from the URL parameters alone.',
description: 'Capture a real screenshot of a rendered weather map — the Windy embed (radar, satellite, wind, precipitation, etc.), the KMA typhoon forecast-track page, or an NHC forecast-track page (URL from nhc_active_storms) — so you can actually SEE it before describing it. Call this with the exact URL you just generated — do not guess what the map shows from the URL parameters alone.',
parameters: {
type: 'object', required: ['url'],
properties: {
url: { type: 'string', description: 'The exact https://embed.windy.com/embed2.html?... URL to capture (must match the one shown to the user)' },
url: { type: 'string', description: 'The exact https://embed.windy.com/embed2.html?... URL, the KMA typhoon track URL, or an https://www.nhc.noaa.gov/graphics_XXN.shtml URL from nhc_active_storms (must match the one shown to the user)' },
wait_ms: { type: 'number', description: 'Milliseconds to wait for map tiles to finish loading before capturing (default 4000, max 8000)' },
},
},
},
},
{
type: 'function',
function: {
name: 'nhc_active_storms',
description: 'Look up NOAA/NHC active tropical cyclones outside Korea\'s warning area (Atlantic, Eastern Pacific, Central Pacific hurricanes/storms) and get the official forecast-track-cone page URL for a specific storm by name. Use this before showing a non-Korean storm\'s forecast track — never guess the graphics_XXN.shtml URL yourself, the basin/slot number in it isn\'t derivable from the name.',
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: 'Storm name to look up, e.g. "Genevieve" (case-insensitive substring match). Omit to list all currently active storms across all basins.' },
},
},
},
},
{
type: 'function',
function: {
+8
View File
@@ -1398,6 +1398,14 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals
const imgMatch = _resultText.match(/!\[[^\]]*\]\(\/api\/files\/satellite-images\/[^)]+\)/);
if (imgMatch) sendSSE?.('token', { text: `\n${imgMatch[0]}\n` });
}
// nhc_active_storms: observed the model retyping the forecast-track URL with a
// wrong basin/slot digit (e.g. graphics_ep2.shtml → graphics_ep5.shtml) instead of
// copying it verbatim — silently pointing at an unrelated or dissipated storm. When
// exactly one storm matched, the tool exposes its own verified URL via tr.data.url;
// push that directly so the map is right regardless of what the model's prose says.
if (name === 'nhc_active_storms' && tr.success && typeof tr.data?.url === 'string') {
sendSSE?.('token', { text: `\n${tr.data.url}\n` });
}
return { name, args, result: _resultText, error: !tr.success, ...(_hasImageMd ? { isImage: true } : {}), ...(tr.data !== undefined ? { data: tr.data } : {}) };
}
}
+1
View File
@@ -182,6 +182,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
// model there has already generated the embed.windy.com URL to capture) — unlike the
// other weather tools, not offered via the meteorologist skill in general chat.
if (name === 'weather_map_screenshot' && !isWeatherAppSession) return false;
if (name === 'nhc_active_storms' && !isWeatherAppSession) return false;
if (ollamaWebToolNames.has(name) && !hasOllamaWebKeyword) return false;
if (legalToolNames.has(name) && !isLawyerAppSession && !(lawyerEnabled && hasLegalKeyword)) return false;
if ((name === 'excel_read' || name === 'excel_write') && !isAccountantAppSession && !hasExcelKeyword) return false;
+75
View File
@@ -243,6 +243,69 @@ function parseOrphanTrailingToolJson(content: string, tools: any[] | undefined):
return null;
}
/**
* Strip a leaked raw tool-call invocation (e.g. literal `web_search{"query":"..."}` typed
* as text) from ANYWHERE in the content, even with substantial real prose both before and
* after it. parseEmbeddedToolCalls/parseOrphanTrailingToolJson above only fire when the
* whole message (or its very end) is essentially just the call — they intentionally bail
* out the moment there's real surrounding prose, so a model that leaks a malformed call
* mid-response and then keeps writing a normal answer around it slips past both. This is
* safe to run unconditionally because — unlike those two, which match any lowercase
* identifier — it only touches a span whose identifier is an EXACT registered tool name,
* so it can't mistake a code sample or JSON example in a legitimate answer for a leak.
*/
function stripEmbeddedToolCallLeaks(content: string, tools: any[] | undefined): string {
if (!Array.isArray(tools) || !tools.length || !content.includes('{')) return content;
const toolNames = new Set(tools.map((t: any) => t?.function?.name).filter(Boolean));
if (!toolNames.size) return content;
const nameRe = /\b([a-z][a-z0-9_]*)\{/g;
let out = '';
let pos = 0;
let m: RegExpExecArray | null;
let changed = false;
while ((m = nameRe.exec(content)) !== null) {
const matchIndex = m.index, matchLen = m[0].length, toolName = m[1];
if (matchIndex < pos) continue; // inside a span already consumed
if (!toolNames.has(toolName)) continue;
const jsonStart = matchIndex + matchLen - 1;
let depth = 0, inStr = false, escaped = false, i = jsonStart;
for (; i < content.length; i++) {
const ch = content[i];
if (escaped) { escaped = false; continue; }
if (ch === '\\' && inStr) { escaped = true; continue; }
if (ch === '"') { inStr = !inStr; continue; }
if (inStr) continue;
if (ch === '{') depth++;
else if (ch === '}') { depth--; if (depth === 0) break; }
}
if (depth !== 0 || i >= content.length) continue; // unterminated — leave as-is
const jsonStr = content.slice(jsonStart, i + 1);
let args: any;
try { args = JSON.parse(jsonStr); } catch { continue; }
if (typeof args !== 'object' || Array.isArray(args) || args === null) continue;
const tool = tools.find((t: any) => t?.function?.name === toolName);
const params = tool?.function?.parameters;
const props = params?.properties ? Object.keys(params.properties) : [];
const required = Array.isArray(params?.required) ? params.required : [];
const keys = Object.keys(args);
if (!required.every((r: string) => keys.includes(r))) continue;
if (!keys.every((k) => props.includes(k))) continue;
// Genuine leak — excise the "name{...}" span entirely.
out += content.slice(pos, matchIndex);
pos = i + 1;
changed = true;
}
if (!changed) return content;
out += content.slice(pos);
return out.replace(/[ \t]{2,}/g, ' ').trim();
}
/** Repair malformed JSON: close truncated brackets, strip trailing garbage. */
function repairJson(input: string): string {
let s = input.trim();
@@ -442,6 +505,12 @@ export class OllamaAdapter implements LLMProvider {
}
}
}
// Catches a leaked call sitting in the MIDDLE of otherwise-normal prose (the two
// checks above only fire when the whole message, or its tail, is basically just
// the call — a model that leaks one and then keeps writing past it slips through).
if (message.content) {
message.content = stripEmbeddedToolCallLeaks(String(message.content), options?.tools);
}
// If we got no content and no tool_calls, try the next think candidate.
// Some models (e.g. glm-5.1:cloud) default to thinking-only mode when the
@@ -626,6 +695,12 @@ export class OllamaAdapter implements LLMProvider {
}
}
}
// Catches a leaked call sitting in the MIDDLE of otherwise-normal prose (the two
// checks above only fire when the whole message, or its tail, is basically just
// the call — a model that leaks one and then keeps writing past it slips through).
if (message.content) {
message.content = stripEmbeddedToolCallLeaks(String(message.content), options?.tools);
}
// If we got no content and no tool_calls, try the next think candidate.
// Some models (e.g. glm-5.1:cloud) default to thinking-only mode when the
+2 -1
View File
@@ -21,7 +21,7 @@ import { imageGenerateTool, videoGenerateTool, imageStyleTransformTool } from '.
import { audioTranscribeTool } from './audio-transcribe.js';
import { pythonEvalTool } from './python.js';
import { sqliteTool } from './sqlite.js';
import { weatherSearchTool, weatherAirPollutionTool, weatherOpenMeteoTool, weatherKmaTool, weatherAirKoreaTool, weatherNasaPowerTool, weatherEra5Tool, weatherCdsTool, weatherCmip6Tool, weatherMapScreenshotTool } from './weather.js';
import { weatherSearchTool, weatherAirPollutionTool, weatherOpenMeteoTool, weatherKmaTool, weatherAirKoreaTool, weatherNasaPowerTool, weatherEra5Tool, weatherCdsTool, weatherCmip6Tool, weatherMapScreenshotTool, nhcActiveStormsTool } from './weather.js';
import { eonetEventsTool, satelliteSnapshotTool } from './satellite.js';
import { newsSearchTool } from './news.js';
import { emailListTool, emailReadTool, emailSendTool, emailSearchTool, emailDeleteTool } from './email.js';
@@ -224,6 +224,7 @@ class ToolRegistry {
this.registerSafe(weatherCdsTool);
this.registerSafe(weatherCmip6Tool);
this.registerSafe(weatherMapScreenshotTool);
this.registerSafe(nhcActiveStormsTool);
// NASA EONET (natural event tracker) + Worldview Snapshots (satellite imagery) — both public, no API key
this.registerSafe(eonetEventsTool);
this.registerSafe(satelliteSnapshotTool);
+152 -47
View File
@@ -3,6 +3,7 @@ import { getConfig } from '../config/config.js';
import { getVault } from '../security/vault.js';
import { getPaths, getWorkspacePath } from '../config/paths.js';
import { buildImageMarkdown } from './image.js';
import { splitOpenMeteoVariables, formatOpenMeteoReport } from './weather-openmeteo-format.js';
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
@@ -176,29 +177,40 @@ function parseExplicitCountry(name: string): { city: string; countryCode?: strin
return { city: name };
}
async function geocodeCity(name: string): Promise<{ lat: number; lon: number; displayName: string } | null> {
export async function geocodeCity(name: string): Promise<{ lat: number; lon: number; displayName: string } | null> {
const key = name.trim().toLowerCase();
if (KR_CITY_COORDS[key]) {
const [lat, lon] = KR_CITY_COORDS[key];
return { lat, lon, displayName: name };
}
const { city, countryCode } = parseExplicitCountry(name);
try {
const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=10&language=ko&format=json`;
const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
if (!res.ok) return null;
const data: any = await res.json();
const results: any[] = data.results || [];
if (!results.length) return null;
// Prefer an explicit country match; otherwise fall back to the most populous
// candidate rather than index 0 (Open-Meteo often ranks a small US namesake
// above the internationally-known city for a bare query like "Rome").
let r = countryCode ? results.find((x: any) => String(x.country_code || '').toUpperCase() === countryCode) : undefined;
if (!r) r = results.reduce((best: any, cur: any) => (cur.population || 0) > (best.population || 0) ? cur : best, results[0]);
return { lat: r.latitude, lon: r.longitude, displayName: `${r.name}${r.country ? ', ' + r.country : ''}` };
} catch {
return null;
const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=10&language=ko&format=json`;
// Open-Meteo geocoding throws a transient network/5xx blip now and then that
// clears on an immediate retry. Observed 2026-07-29: a single Madrid call in
// the middle of a 6-city burst returned "위치를 찾을 수 없습니다" while every
// surrounding call and 20/20 direct retries succeeded — a one-off blip, not a
// real miss. Without a retry that blip hardens into a permanent "city not
// found" in the answer. Retry only on transient causes (throw / non-ok); a
// 200 with no results is a genuine "not found" and returns immediately.
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
if (!res.ok) throw new Error(`geocoding HTTP ${res.status}`);
const data: any = await res.json();
const results: any[] = data.results || [];
if (!results.length) return null; // API answered "not found" — retrying won't change it
// Prefer an explicit country match; otherwise fall back to the most populous
// candidate rather than index 0 (Open-Meteo often ranks a small US namesake
// above the internationally-known city for a bare query like "Rome").
let r = countryCode ? results.find((x: any) => String(x.country_code || '').toUpperCase() === countryCode) : undefined;
if (!r) r = results.reduce((best: any, cur: any) => (cur.population || 0) > (best.population || 0) ? cur : best, results[0]);
return { lat: r.latitude, lon: r.longitude, displayName: `${r.name}${r.country ? ', ' + r.country : ''}` };
} catch (err: any) {
if (attempt >= 3) break;
await new Promise(r => setTimeout(r, 300 * attempt)); // 300ms, 600ms
}
}
return null;
}
function parseCoords(location: string): [number, number] | null {
@@ -556,18 +568,20 @@ const WMO_CODES: Record<number, string> = {
export const weatherOpenMeteoTool = {
name: 'weather_openmeteo',
description: 'Get detailed hourly weather forecast using Open-Meteo API (free, no API key). Powered by ECMWF, GFS, and other NWP models. Supports temperature, precipitation, wind, UV index, soil temp, and more for up to 16 days.',
description: 'Get weather forecast using Open-Meteo API (free, no API key). Powered by ECMWF, GFS, and other NWP models. Times are returned in the LOCATION\'s local timezone. For "today\'s high/low" use daily variables (temperature_2m_max, temperature_2m_min, precipitation_sum, …) — the hourly series is a rolling window from now and spans two calendar days, so its maximum is NOT the daily high. Hourly variables (temperature_2m, precipitation, wind_speed_10m, uv_index, weather_code, …) are for intra-day detail. Up to 16 days.',
schema: {
location: 'City name (Korean or English) or "lat,lon" coordinates',
hours: 'Number of hours to forecast (default: 24, max: 384)',
variables: 'Comma-separated Open-Meteo hourly variables (default: temperature_2m,precipitation,wind_speed_10m,wind_direction_10m,relative_humidity_2m,uv_index,weather_code)',
hours: 'Hours of hourly forecast (default: 24, max: 384)',
days: 'Days of daily forecast when daily variables are requested (default: 3, max: 16)',
variables: 'Comma-separated Open-Meteo variables. Daily ones (temperature_2m_max/min, precipitation_sum, sunrise, …) are routed to the daily block automatically; everything else is treated as hourly. Default: temperature_2m,precipitation,wind_speed_10m,wind_direction_10m,relative_humidity_2m,uv_index,weather_code',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name or "lat,lon"' },
hours: { type: 'number', description: 'Hours ahead (1–384, default 24)' },
variables: { type: 'string', description: 'Comma-separated hourly variable names' },
days: { type: 'number', description: 'Days ahead for daily variables (1–16, default 3)' },
variables: { type: 'string', description: 'Comma-separated variable names (daily and hourly may be mixed)' },
},
required: ['location'],
additionalProperties: false,
@@ -577,7 +591,12 @@ export const weatherOpenMeteoTool = {
if (!location) return { success: false, error: 'location is required' };
const hours = Math.min(Math.max(1, Math.round(Number(args?.hours) || 24)), 384);
const days = Math.min(Math.max(1, Math.round(Number(args?.days) || 3)), 16);
const vars = String(args?.variables || 'temperature_2m,precipitation,wind_speed_10m,wind_direction_10m,relative_humidity_2m,uv_index,weather_code');
// Daily-only names used to be posted to `hourly=`, which Open-Meteo accepts — it returns
// an hourly series under a daily name, so `temperature_2m_max` produced numbers that were
// not maxima at all. Route them before the request instead.
const { hourly: hourlyVars, daily: dailyVars } = splitOpenMeteoVariables(vars);
try {
let lat: number, lon: number, displayName: string;
@@ -594,34 +613,41 @@ export const weatherOpenMeteoTool = {
const params = new URLSearchParams({
latitude: String(lat),
longitude: String(lon),
hourly: vars,
forecast_hours: String(hours),
timezone: 'Asia/Seoul',
// 'auto' resolves the timezone from the coordinates. This was hardcoded to
// Asia/Seoul, which stamped every foreign forecast with Korean day boundaries and
// made "today's high" unanswerable for anywhere outside KST.
timezone: 'auto',
wind_speed_unit: 'ms',
});
if (hourlyVars.length) {
params.set('hourly', hourlyVars.join(','));
params.set('forecast_hours', String(hours));
}
if (dailyVars.length) {
params.set('daily', dailyVars.join(','));
params.set('forecast_days', String(days));
}
const res = await fetch(`https://api.open-meteo.com/v1/forecast?${params}`, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) throw new Error(`Open-Meteo API error ${res.status}`);
const data: any = await res.json();
const times: string[] = data.hourly?.time || [];
const varKeys = vars.split(',').map(v => v.trim());
const units = data.hourly_units || {};
const SHOW = Math.min(hours, 48);
const headerCols = ['시각', ...varKeys.map(k => k.replace('_', ' '))];
const rows = times.slice(0, SHOW).map((t, i) => {
const vals = varKeys.map(k => {
const v = data.hourly?.[k]?.[i];
if (v == null) return '-';
const text = formatOpenMeteoReport({
displayName,
timezone: data.timezone || 'auto',
utcOffsetSeconds: Number(data.utc_offset_seconds) || 0,
hours,
hourlyVars,
dailyVars,
hourlyBlock: data.hourly,
dailyBlock: data.daily,
hourlyUnits: data.hourly_units || {},
dailyUnits: data.daily_units || {},
renderValue: (k, v) => {
if (k === 'weather_code') return WMO_CODES[v as number] ?? String(v);
if (k === 'wind_direction_10m') return `${windDirectionKo(v)}(${v}°)`;
if (k === 'wind_direction_10m' || k === 'wind_direction_10m_dominant') return `${windDirectionKo(v)}(${v}°)`;
return String(v);
});
return [t.replace('T', ' '), ...vals].join('\t');
},
});
const unitLine = `단위: ${varKeys.map(k => `${k}=${units[k] || '-'}`).join(', ')}`;
const text = [`Open-Meteo 예보: ${displayName} (${hours}시간)`, unitLine, '', headerCols.join('\t'), ...rows].join('\n');
return { success: true, stdout: text, data: { location: displayName, lat, lon, raw: data } };
} catch (err: any) {
return { success: false, error: err.message };
@@ -1517,17 +1543,27 @@ async function getMapBrowser(): Promise<any> {
return _mapBrowser;
}
// KMA's typhoon page is the only place that actually plots a forecast track (the
// cone-of-uncertainty + path line) — Windy's embed never does. Allowlisted by exact
// path (not just hostname) since weather.go.kr hosts far more than this one page.
const KMA_TYPHOON_TRACK_URL = 'https://www.weather.go.kr/w/typhoon/ko/weather/typhoon_02.jsp';
// NOAA/NHC's equivalent for storms outside KMA's warning area. The URL is basin+slot
// specific (graphics_ep2.shtml, graphics_at1.shtml, ...) so it can't be a single fixed
// string like KMA's — nhc_active_storms resolves the right one, this just validates the
// shape stays within nhc.noaa.gov's own graphics pages (no arbitrary path/host).
const NHC_TRACK_URL_RE = /^https:\/\/www\.nhc\.noaa\.gov\/graphics_[a-z]+\d\.shtml(?:\?.*)?$/;
export const weatherMapScreenshotTool = {
name: 'weather_map_screenshot',
description: 'Capture a real screenshot of a rendered Windy weather map (radar, satellite, wind, precipitation, etc.) so you can actually SEE it before describing it. Call this with the exact embed.windy.com URL you just generated — do not guess what the map shows from the URL parameters alone.',
description: 'Capture a real screenshot of a rendered weather map — the Windy embed (radar, satellite, wind, precipitation, etc.), the KMA typhoon forecast-track page, or an NHC forecast-track page (from nhc_active_storms) — so you can actually SEE it before describing it. Call this with the exact URL you just generated — do not guess what the map shows from the URL parameters alone.',
schema: {
url: 'The exact https://embed.windy.com/embed2.html?... URL to capture (must match the one shown to the user)',
url: `The exact https://embed.windy.com/embed2.html?... URL, the literal ${KMA_TYPHOON_TRACK_URL} for KMA, or an https://www.nhc.noaa.gov/graphics_XXN.shtml URL from nhc_active_storms`,
wait_ms: 'Milliseconds to wait for map tiles to finish loading before capturing (default 4000, max 8000)',
},
jsonSchema: {
type: 'object',
properties: {
url: { type: 'string', description: 'The exact embed.windy.com URL to capture' },
url: { type: 'string', description: 'The exact embed.windy.com, KMA typhoon track, or NHC graphics_XXN.shtml URL to capture' },
wait_ms: { type: 'number', description: 'Wait time in ms for tiles to load (default 4000, max 8000)' },
},
required: ['url'],
@@ -1539,8 +1575,10 @@ export const weatherMapScreenshotTool = {
let parsed: URL;
try { parsed = new URL(urlStr); } catch { return { success: false, error: 'Invalid URL' }; }
if (parsed.hostname !== 'embed.windy.com') {
return { success: false, error: 'Only embed.windy.com URLs can be captured' };
const isKmaTrack = urlStr === KMA_TYPHOON_TRACK_URL;
const isNhcTrack = NHC_TRACK_URL_RE.test(urlStr);
if (parsed.hostname !== 'embed.windy.com' && !isKmaTrack && !isNhcTrack) {
return { success: false, error: `Only embed.windy.com, ${KMA_TYPHOON_TRACK_URL}, or nhc.noaa.gov graphics_XXN.shtml URLs can be captured` };
}
const waitMs = Math.min(Math.max(Number(args?.wait_ms) || 4000, 1000), 8000);
@@ -1566,11 +1604,14 @@ export const weatherMapScreenshotTool = {
const filePath = path.join(outDir, `windy-${Date.now()}.jpg`);
fs.writeFileSync(filePath, buf);
const overlay = parsed.searchParams.get('overlay') || 'map';
const zoom = parsed.searchParams.get('zoom') || '?';
const label = isKmaTrack
? 'KMA 태풍 예상진로 페이지 캡처 완료'
: isNhcTrack
? 'NHC 허리케인 예상진로 페이지 캡처 완료'
: `Windy 지도 캡처 완료 (overlay=${parsed.searchParams.get('overlay') || 'map'}, zoom=${parsed.searchParams.get('zoom') || '?'})`;
return {
success: true,
stdout: `Windy 지도 캡처 완료 (overlay=${overlay}, zoom=${zoom}):\n\n${buildImageMarkdown(filePath, workspacePath)}\n\n위 이미지에 실제로 보이는 내용만 근거로 설명하세요. 보이지 않는 세부사항을 추측하지 마세요.`,
stdout: `${label}:\n\n${buildImageMarkdown(filePath, workspacePath)}\n\n위 이미지에 실제로 보이는 내용만 근거로 설명하세요. 보이지 않는 세부사항을 추측하지 마세요.`,
};
} catch (err: any) {
return { success: false, error: `지도 캡처 실패: ${err.message}` };
@@ -1579,3 +1620,67 @@ export const weatherMapScreenshotTool = {
}
},
};
// ── nhc_active_storms (NOAA/NHC forecast-track lookup for non-Korean storms) ──────
// KMA's typhoon page (KMA_TYPHOON_TRACK_URL above) only ever shows storms in KMA's own
// warning area — a hurricane near Mexico never appears there. NHC's forecast-cone page
// URL is basin+slot specific (e.g. graphics_ep2.shtml = 2nd Eastern Pacific storm this
// season) and that slot number isn't guessable from a storm's name alone. NHC publishes
// a small official JSON feed of all currently active storms with their basin/slot and
// the exact forecast-graphics URL already resolved — this tool just looks a name up in it,
// so the model never has to guess or scrape for the right graphics_XXN.shtml URL.
export const nhcActiveStormsTool = {
name: 'nhc_active_storms',
description: 'Look up NOAA/NHC (National Hurricane Center) active tropical cyclones outside Korea\'s warning area (Atlantic, Eastern Pacific, Central Pacific hurricanes/storms) and get the official forecast-track-cone page URL for a specific storm by name. Use this before showing a non-Korean storm\'s forecast track — do not guess the graphics_XXN.shtml URL yourself.',
schema: {
name: 'Storm name to look up (e.g. "Genevieve"), case-insensitive substring match. Omit to list all currently active storms across all basins.',
},
jsonSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Storm name to look up, e.g. "Genevieve". Omit to list all active storms.' },
},
required: [],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
try {
const res = await fetch('https://www.nhc.noaa.gov/CurrentStorms.json', { signal: AbortSignal.timeout(15_000) });
if (!res.ok) return { success: false, error: `NHC 조회 실패: HTTP ${res.status}` };
const data: any = await res.json();
const all = Array.isArray(data?.activeStorms) ? data.activeStorms : [];
const nameFilter = String(args?.name || '').trim().toLowerCase();
const matches = nameFilter ? all.filter((s: any) => String(s?.name || '').toLowerCase().includes(nameFilter)) : all;
if (all.length === 0) {
return { success: true, stdout: '현재 NHC(대서양·동태평양·중태평양) 관할 구역에 활성화된 열대저기압이 없습니다.' };
}
if (nameFilter && matches.length === 0) {
const names = all.map((s: any) => s.name).join(', ');
return { success: true, stdout: `"${args.name}"이라는 이름의 활성 태풍/허리케인을 NHC 목록에서 찾지 못했습니다. 현재 NHC 활성 목록: ${names}. 이름을 다시 확인하거나, 이미 소멸했을 가능성을 검토하세요.` };
}
const lines = matches.map((s: any) => {
const track = s?.forecastGraphics?.url || '(예보 그래픽 URL 없음 — 열대저압부 단계라 아직 진로 원뿔이 없을 수 있음)';
return [
`이름: ${s.name} (${s.classification || '?'}, basin/slot ${s.binNumber || '?'})`,
`위치: ${s.latitude ?? '?'}, ${s.longitude ?? '?'}`,
`세력: 최대풍속 ${s.intensity ?? '?'}kt, 중심기압 ${s.pressure ?? '?'}hPa`,
`이동: 방위각 ${s.movementDir ?? '?'}°, 시속 ${s.movementSpeed ?? '?'}kt`,
`마지막 업데이트: ${s.lastUpdate || '?'}`,
`예상진로 페이지 URL: ${track}`,
].join('\n');
});
// Models have been observed retyping this URL with a wrong digit (e.g. ep2 → ep5)
// instead of copying it verbatim, which silently points at an unrelated/dissipated
// storm. When exactly one match has a real graphics URL, expose it as structured
// data so the caller can push the tool's own (guaranteed-correct) URL directly
// instead of trusting the model's prose to reproduce it — same reasoning as the
// satellite_snapshot auto-push in execute-tool.ts.
const singleUrl = matches.length === 1 ? matches[0]?.forecastGraphics?.url : undefined;
return { success: true, stdout: lines.join('\n---\n'), ...(singleUrl ? { data: { url: singleUrl } } : {}) };
} catch (err: any) {
return { success: false, error: `NHC 조회 실패: ${err.message}` };
}
},
};
+114 -16
View File
@@ -106,7 +106,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;fon
.wt-photo-goto-map{position:absolute;left:12px;bottom:12px;background:rgba(0,0,0,.55);border:none;border-radius:8px;padding:7px 12px;color:#e5e7eb;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;backdrop-filter:blur(4px);}
.wt-photo-goto-map:hover{background:rgba(255,255,255,.18);}
.wt-map-frame{width:100%;height:100%;border:none;display:block;}
.wt-map-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:12px;background:var(--bg);pointer-events:none;transition:opacity .3s;}
.wt-map-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:12px;background:color-mix(in srgb,var(--bg) 85%,transparent);pointer-events:none;transition:opacity .3s;}
.wt-map-loading.hidden{opacity:0;}
/* ── Resize ── */
@@ -269,11 +269,12 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;fon
<button class="wt-ov" data-ov="pressure" onclick="setOverlay('pressure')">📊 기압</button>
<button class="wt-ov" data-ov="snowcover" onclick="setOverlay('snowcover')">❄️ 적설</button>
<button class="wt-ov" data-ov="waves" onclick="setOverlay('waves')">🌊 파고</button>
<button class="wt-ov" data-ov="kma-track" onclick="setOverlay('kma-track')" title="기상청 태풍 예상진로(원뿔형 확률반경) — Windy엔 없는 실제 진로도">🧭 예상진로</button>
</div>
</div>
<div class="wt-map-area" id="wt-map-area">
<div class="wt-map-loading" id="map-loading">🌍 Windy 지도 로딩 중...</div>
<iframe class="wt-map-frame" id="windy-frame" src="about:blank" allow="geolocation" onload="document.getElementById('map-loading').classList.add('hidden')"></iframe>
<iframe class="wt-map-frame" id="windy-frame" src="about:blank" allow="geolocation"></iframe>
</div>
<div class="wt-map-area" id="wt-photo-area" style="display:none;align-items:center;justify-content:center;background:#0a0e14">
<img id="wt-photo-img" src="" alt="" draggable="false" style="max-width:100%;max-height:100%;object-fit:contain;transform-origin:center center;transition:transform .08s linear;user-select:none">
@@ -405,7 +406,7 @@ async function ensureChatContextForLoc(){
addMsg('system',l?`📍 '${escHtml(l.name)}' 위치 컨텍스트입니다. 이 대화는 이 위치에서만 이어집니다.`:'🌍 전체 컨텍스트입니다. (선택된 위치 없음)');
}
const SKILL_CONTENT="---\nname: Meteorologist\ndescription: 날씨 분석·기후 해설·기상 현상 설명·예보 해석을 제공하는 기상 전문가 어시스턴트. 기상청 공식 데이터와 세계 기상 자료를 바탕으로 정확하고 쉬운 설명 제공.\nemoji: \"🌤️\"\nversion: 1.3.0\ntriggers: [날씨, 기온, 기상, 비, 눈, 바람, 태풍, 예보, 미세먼지, 황사, 폭염, 한파, 습도, 강수, 대기질, 기후, 구름, 우박, 번개, 천둥, 안개, 서리, 열대야, 소나기]\n---\n\n당신은 기상학 전문가 어시스턴트입니다. 기상청 공식 데이터와 세계 기상 자료를 바탕으로 날씨 예보 해석, 기상 현상 설명, 기후 분석, 자연재해 경보 해설을 제공하세요.\n\n**언어**: 사용자가 한국어로 말하면 반드시 한국어로만 답변. 기상 용어는 한국어 먼저, 영어 괄호 병기. (예: 적란운(cumulonimbus))\n\n---\n\n### 핵심 원칙\n\n**⛔ 날씨 수치 무단 생성 금지**: 실시간·과거 기상 수치는 반드시 도구를 호출한 후 반환된 데이터만 보고하세요. 도구 없이 날씨를 서술하면 오보입니다.\n\n**⛔ 이전 대화 수치 재사용 금지**: 같은 지역·날짜라도 새 질문마다 도구를 새로 호출하세요.\n\n- 불확실한 예보는 \"기상청 최신 예보를 확인하세요\"로 명시\n- 수치 인용 시 출처(기상청·ECMWF·NOAA 등) 표기\n- 전문 용어 사용 시 쉬운 말로 한 줄 병기\n- 위험 기상 시 행동 요령 우선 안내\n\n---\n\n### 🗺️ Windy 지도 임베드\n\n사용자 메시지에 아래 **트리거 단어**가 포함될 때만 Windy URL을 출력하세요. 그 외에는 절대 출력하지 마세요.\n\n**트리거 단어**: 기상도, 위성사진, 위성영상, 레이더, 강수레이더, 바람지도, 풍향지도, 기압도, 일기도, 구름사진, 구름영상, 적설지도, 파고지도, 태풍, 태풍위치, 태풍경로, 허리케인, 사이클론\n\n**⛔ 후속 \"이동/이동해줘/옮겨줘/그쪽으로\" 요청도 트리거로 취급**: 직전 대화에서 이미 지도(Windy URL)를 출력한 적이 있고, 사용자가 \"위치로 이동\", \"거기로 옮겨줘\", \"그 사진 위치로\", \"이동하라고\" 등 지도 이동을 요청하면 — 이 메시지 자체에 위 트리거 단어가 없어도 **반드시 새 Windy URL을 다시 출력**하세요. 이런 요청을 무시하고 텍스트 설명만 하거나 `weather_map_screenshot` 결과를 대신 보여주려 하면 사용자가 보는 실제 지도는 전혀 움직이지 않습니다.\n\n**⛔ `weather_map_screenshot`은 당신이 보기 위한 도구입니다 — 그 결과를 `![...](...)` 마크다운으로 답변에 삽입하지 마세요.** 이 도구는 저장되거나 서빙되는 파일을 반환하지 않으므로, 결과를 이미지 링크로 만들면 깨진 링크가 됩니다. 지도를 실제로 사용자 화면에 띄우는 유일한 방법은 위에서 설명한 Windy URL을 **독립된 텍스트 줄로 출력**하는 것뿐입니다 — 스크린샷 도구는 그 다음에 당신이 결과를 확인·설명하기 위해서만 쓰세요.\n\n트리거 단어가 있을 때: `https://embed.windy.com/embed2.html?lat=LAT&lon=LON&zoom=ZOOM&level=surface&overlay=OVERLAY&menu=&message=true&marker=&calendar=now&pressure=&type=map&location=coordinates&detail=&metricWind=m%2Fs&metricTemp=%C2%B0C` 형식으로 LAT·LON·OVERLAY·ZOOM을 맥락에 맞게 채워 **독립된 한 줄**로 출력하세요.\n\n**LAT·LON은 항상 실제로 묻는 지역 기준으로 바꾸세요** — 서울(37.5, 126.9)을 기본값처럼 고정해서 복사하지 마세요. 지역이 특정되지 않았다면 사용자의 기본 지역(서울)을 쓰세요.\n\n**주요 지역 좌표**: 서울(37.5,126.9) 부산(35.18,129.08) 인천(37.46,126.7) 대구(35.87,128.6) 광주(35.16,126.85) 대전(36.35,127.38) 제주(33.5,126.53) 강릉(37.75,128.9) 평양(39.02,125.75) 도쿄(35.68,139.69) 베이징(39.9,116.4) 상하이(31.23,121.47) — 목록에 없는 지역은 알고 있는 좌표를 사용하세요.\n\n**중요**: URL을 출력한 직후 반드시 `weather_map_screenshot` 도구를 그 URL 그대로 호출해서 실제로 렌더링된 지도를 확인하세요. 캡처한 이미지를 보기 전에는 강수·구름·레이더 패턴을 절대 추측하지 마세요 — 이미지에 실제로 보이는 것만 근거로 설명하세요.\n\n**태풍 위치/경로 요청 시**: lat·lon을 서울이나 기본 지역이 아니라 **태풍의 실제 현재 위치**로 맞추세요. 순서: ① `web_search` 또는 `weather_search`로 태풍의 현재 좌표(위도·경도)를 먼저 확인 → ② 그 좌표를 lat·lon에 대입 → ③ zoom은 태풍 전체 규모가 보이도록 4~5(넓게) 사용 → ④ overlay는 `wind`(바람 강도로 태풍 눈·나선구조 확인) 또는 `rain`을 우선 사용. 태풍 좌표를 Line truncated
const SKILL_CONTENT="---\nname: Meteorologist\ndescription: 날씨 분석·기후 해설·기상 현상 설명·예보 해석을 제공하는 기상 전문가 어시스턴트. 기상청 공식 데이터와 세계 기상 자료를 바탕으로 정확하고 쉬운 설명 제공.\nemoji: \"🌤️\"\nversion: 1.3.0\ntriggers: [날씨, 기온, 기상, 비, 눈, 바람, 태풍, 예보, 미세먼지, 황사, 폭염, 한파, 습도, 강수, 대기질, 기후, 구름, 우박, 번개, 천둥, 안개, 서리, 열대야, 소나기]\n---\n\n당신은 기상학 전문가 어시스턴트입니다. 기상청 공식 데이터와 세계 기상 자료를 바탕으로 날씨 예보 해석, 기상 현상 설명, 기후 분석, 자연재해 경보 해설을 제공하세요.\n\n**언어**: 사용자가 한국어로 말하면 반드시 한국어로만 답변. 기상 용어는 한국어 먼저, 영어 괄호 병기. (예: 적란운(cumulonimbus))\n\n---\n\n### 핵심 원칙\n\n**⛔ 날씨 수치 무단 생성 금지**: 실시간·과거 기상 수치는 반드시 도구를 호출한 후 반환된 데이터만 보고하세요. 도구 없이 날씨를 서술하면 오보입니다.\n\n**⛔ 이전 대화 수치 재사용 금지**: 같은 지역·날짜라도 새 질문마다 도구를 새로 호출하세요.\n\n- 불확실한 예보는 \"기상청 최신 예보를 확인하세요\"로 명시\n- 수치 인용 시 출처(기상청·ECMWF·NOAA 등) 표기\n- 전문 용어 사용 시 쉬운 말로 한 줄 병기\n- 위험 기상 시 행동 요령 우선 안내\n\n---\n\n### 🗺️ Windy 지도 임베드\n\n사용자 메시지에 아래 **트리거 단어**가 포함될 때만 Windy URL을 출력하세요. 그 외에는 절대 출력하지 마세요.\n\n**트리거 단어**: 기상도, 위성사진, 위성영상, 레이더, 강수레이더, 바람지도, 풍향지도, 기압도, 일기도, 구름사진, 구름영상, 적설지도, 파고지도, 태풍, 태풍위치, 태풍경로, 허리케인, 사이클론\n\n**⛔ 외부 사이트 링크가 Windy URL을 대체하면 안 됩니다**: 허리케인/태풍의 이름·좌표를 확인했다면(웹검색으로), StormAtlas·NHC·JTWC 같은 외부 링크를 참고자료로 덧붙이는 것과 별개로 **반드시 그 좌표로 embed.windy.com Windy URL도 출력**하세요 — 한국 태풍이든 다른 대양의 허리케인이든 동일합니다. 좌표를 몰라서 못 만들겠으면 못 만든다고 말하고 외부 링크만 주되, **\"🔍 지도에서 확인할 수 있는 것\" 같은 캡션은 직전에 실제로 embed.windy.com 또는 기상청 예상진로 URL을 출력했을 때만 쓰세요** — 임베드되지 않는 외부 링크(StormAtlas 등)에 이 캡션을 붙이면, 사용자 화면의 지도는 전혀 안 움직이는데 마치 지도에 표시된 것처럼 오해하게 됩니다.\n\n**⛔ 후속 \"이동/이동해줘/옮겨줘/그쪽으로\" 요청도 트리거로 취급**: 직전 대화에서 이미 지도(Windy URL)를 출력한 적이 있고, 사용자가 \"위치로 이동\", \"거기로 옮겨줘\", \"그 사진 위치로\", \"이동하라고\" 등 지도 이동을 요청하면 — 이 메시지 자체에 위 트리거 단어가 없어도 **반드시 새 Windy URL을 다시 출력**하세요. 이런 요청을 무시하고 텍스트 설명만 하거나 `weather_map_screenshot` 결과를 대신 보여주려 하면 사용자가 보는 실제 지도는 전혀 움직이지 않습니다.\n\n**⛔ `weather_map_screenshot`은 당신이 보기 위한 도구입니다 — 그 결과를 `![...](...)` 마크다운으로 답변에 삽입하지 마세요.** 이 도구는 저장되거나 서빙되는 파일을 반환하지 않으므로, 결과를 이미지 링크로 만들면 깨진 링크가 됩니다. 지도를 실제로 사용자 화면에 띄우는 유일한 방법은 위에서 설명한 Windy URL을 **독립된 텍스트 줄로 출력**하는 것뿐입니다 — 스크린샷 도구는 그 다음에 당신이 결과를 확인·설명하기 위해서만 쓰세요.\n\n트리거 단어가 있을 때: `https://embed.windy.com/embed2.html?lat=LAT&lon=LON&zoom=ZOOM&level=surface&overlay=OVERLAY&menu=&message=true&marker=&calendar=now&pressure=&type=map&location=coordinates&detail=&metricWind=m%2Fs&metricTemp=%C2%B0C` 형식으로 LAT·LON·OVERLAY·ZOOM을 맥락에 맞게 채워 **독립된 한 줄**로 출력하세요.\n\n**LAT·LON은 항상 실제로 묻는 지역 기준으로 바꾸세요** — 서울(37.5, 126.9)을 기본값처럼 고정해서 복사하지 마세요. 지역이 특정되지 않았다면 사용자의 기본 지역(서울)을 쓰세요.\n\n**주요 지역 좌표**: 서울(37.5,126.9) 부산(35.18,129.08) 인천(37.46,126.7) 대구(35.87,128.6) 광주(35.16,126.85) 대전(36.35,127.38) 제주(33.5,126.53) 강릉(37.75,128.9) 평양(39.02,125.75) 도쿄(35.68,139.69) 베이징(39.9,116.4) 상하이(31.23,121.47) — 목록에 없는 지역은 알고 있는 Line truncated
function loadSkill(){
skillContext=SKILL_CONTENT;
document.getElementById('skill-badge').textContent='🌤️ 기상 전문가 활성';
@@ -508,15 +509,46 @@ function deleteLoc(i){
// ── Windy map ─────────────────────────────────────────────────────────────────
let mapLat=37.5,mapLon=127.0,mapZoom=6,mapOverlay='satellite';
// The one page that actually draws a typhoon's forecast track (cone-of-uncertainty +
// path line) — Windy's embed never plots this no matter which overlay is picked.
const KMA_TYPHOON_URL='https://www.weather.go.kr/w/typhoon/ko/weather/typhoon_02.jsp';
// NOAA/NHC's equivalent for storms outside KMA's warning area (Atlantic/Pacific hurricanes).
// Unlike the KMA page this isn't one fixed URL — it's basin+slot specific
// (graphics_ep2.shtml, graphics_at1.shtml, ...), resolved server-side by the
// nhc_active_storms tool, so this is a pattern to recognize rather than a constant to load.
// Query part restricted to word chars only (real NHC keywords are e.g. ?cone, ?gm_track,
// ?wwCone — never punctuation) so a trailing markdown paren/asterisk/hash from the model's
// own link syntax can't get swallowed into the "URL" the way a permissive char class would.
const NHC_TRACK_RE=/https:\/\/www\.nhc\.noaa\.gov\/graphics_[a-z]+\d\.shtml(?:\?[a-zA-Z0-9_]*)?/;
// The 3 regexes elsewhere in this file that match embed.windy.com URLs restrict the query
// part to [a-zA-Z0-9.=&%_-]+ — every value windyUrl() below ever produces is one of those
// characters, so this can't under-match. A permissive [^\s"'<>]+ class used to be here
// instead, which happily swallowed a trailing markdown ")" or "**" from the model's own
// link syntax into the "URL" (same bug independently found and fixed for NHC_TRACK_RE).
function windyUrl(lat,lon,zoom,overlay){
return `https://embed.windy.com/embed2.html?lat=${lat}&lon=${lon}&zoom=${zoom}&level=surface&overlay=${overlay}&menu=&message=true&marker=&calendar=now&pressure=&type=map&location=coordinates&detail=&metricWind=m%2Fs&metricTemp=%C2%B0C`;
}
// The Windy iframe's own document loads almost instantly, but Windy's internal
// JS then takes several more seconds to fetch/render tiles — an onload-based
// spinner hides right away and leaves a blank iframe with no feedback in between.
// There's no postMessage from embed2.html to know when tiles are actually ready,
// so just hold the spinner up for a fixed window instead.
let wtMapLoadTimer=null;
function wtLoadMap(url){
clearTimeout(wtMapLoadTimer);
document.getElementById('map-loading').classList.remove('hidden');
document.getElementById('windy-frame').src=url;
wtMapLoadTimer=setTimeout(()=>document.getElementById('map-loading').classList.add('hidden'),4500);
}
function updateMap(){
// kma-track ignores lat/lon/zoom — it's a fixed page showing KMA's own current storm(s).
if(mapOverlay==='kma-track'){wtLoadMap(KMA_TYPHOON_URL);return;}
const zoom=parseInt(document.getElementById('map-zoom').value||'6',10);
mapZoom=zoom;
document.getElementById('map-loading').classList.remove('hidden');
document.getElementById('windy-frame').src=windyUrl(mapLat,mapLon,mapZoom,mapOverlay);
wtLoadMap(windyUrl(mapLat,mapLon,mapZoom,mapOverlay));
}
function setOverlay(ov){
@@ -690,7 +722,7 @@ function processSatelliteImage(text){
}
function processWindyUrl(text){
const m=text.match(/https:\/\/embed\.windy\.com\/embed2\.html\?([^\s"'<>]+)/);
const m=text.match(/https:\/\/embed\.windy\.com\/embed2\.html\?([a-zA-Z0-9.=&%_-]+)/);
if(!m)return false;
const url='https://embed.windy.com/embed2.html?'+m[1];
// Extract overlay from URL
@@ -708,8 +740,7 @@ function processWindyUrl(text){
const locInput=document.getElementById('map-loc');
if(locInput)locInput.value=`${mapLat},${mapLon}`;
}
document.getElementById('map-loading').classList.remove('hidden');
document.getElementById('windy-frame').src=url;
wtLoadMap(url);
// A "move the map" reply is pointless if the user is still looking at a photo tab —
// switch them to the map tab so the move is actually visible, not just described in text.
switchCenterTab('map');
@@ -768,13 +799,26 @@ function addMsg(role,html){
function renderMdSafe(text){
// Extract Windy URLs before escaping
let windyLinks=[];
let out=text.replace(/https:\/\/embed\.windy\.com\/embed2\.html\?[^\s"'<>\n]+/g,(url)=>{
let out=text.replace(/https:\/\/embed\.windy\.com\/embed2\.html\?[a-zA-Z0-9.=&%_-]+/g,(url)=>{
const ph=`\x00WINDY${windyLinks.length}\x00`;
const ovM=url.match(/overlay=([^&]+)/);const ov=ovM?ovM[1]:'';
const label={satellite:'위성사진',radar:'레이더',rain:'강수',wind:'바람',temp:'기온',clouds:'구름',pm2p5:'대기질',pressure:'기압',snowcover:'적설',waves:'파고'}[ov]||'지도';
windyLinks.push(`<span class="wt-map-link" onclick="loadWindyUrl('${url.replace(/'/g,'&#39;')}','${ov}')">🗺️ ${label} 지도 보기</span>`);
return ph;
});
// KMA typhoon forecast-track page — the one real "예상 진로" source, unlike Windy
out=out.replace(new RegExp(KMA_TYPHOON_URL.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),'g'),(url)=>{
const ph=`\x00WINDY${windyLinks.length}\x00`;
windyLinks.push(`<span class="wt-map-link" onclick="loadWindyUrl('${url}','kma-track')">🧭 예상진로 지도 보기</span>`);
return ph;
});
// NHC forecast-track page (non-Korean storms) — no fixed overlay button exists for this
// since the URL varies per storm/basin, so ov is omitted (no button to highlight active).
out=out.replace(new RegExp(NHC_TRACK_RE.source,'g'),(url)=>{
const ph=`\x00WINDY${windyLinks.length}\x00`;
windyLinks.push(`<span class="wt-map-link" onclick="loadWindyUrl('${url}')">🧭 예상진로 지도 보기(NHC)</span>`);
return ph;
});
// Markdown images (e.g. satellite_snapshot's ![name](/api/files/...)) — extracted
// before escaping/paragraph-wrapping like the Windy links above, same reason this
// renderer never needed image support until the satellite feature.
@@ -800,10 +844,20 @@ function renderMdSafe(text){
return out;
}
function loadNhcTrackUrl(text){
const m=text.match(NHC_TRACK_RE);
if(!m)return false;
loadWindyUrl(m[0]);
switchCenterTab('map');
return true;
}
function loadWindyUrl(url,ov){
if(ov){mapOverlay=ov;document.querySelectorAll('.wt-ov').forEach(b=>b.classList.toggle('active',b.dataset.ov===ov));}
document.getElementById('map-loading').classList.remove('hidden');
document.getElementById('windy-frame').src=url;
// No ov (e.g. an NHC track URL — no fixed button corresponds to it): clear any stale
// highlight instead of leaving a previous overlay looking active while showing this instead.
else document.querySelectorAll('.wt-ov').forEach(b=>b.classList.remove('active'));
wtLoadMap(url);
}
function sendToChat(msg){if(window.innerWidth<=1024)mobToggle('chat');addMsg('user',escHtml(msg));callChat(msg);}
@@ -825,7 +879,7 @@ async function callChat(message){
const typingDiv=document.createElement('div');typingDiv.className='wt-msg assistant';
typingDiv.innerHTML='<div class="wt-typing"><div class="wt-dot"></div><div class="wt-dot"></div><div class="wt-dot"></div></div>';
msgs.appendChild(typingDiv);msgs.scrollTop=msgs.scrollHeight;
let bubble=null,textBuf='',thinkBuf='',windyLoaded=false,satPhotoLoaded=false;
let bubble=null,textBuf='',thinkBuf='',windyLoaded=false,satPhotoLoaded=false,kmaLoaded=false,nhcLoaded=false;
try{
const body={message,sessionId:getSessionId(),useTools:true,
...(selectedModel?{model:selectedModel}:{}),
@@ -845,25 +899,70 @@ async function callChat(message){
if(!part.startsWith('data: '))continue;
let ev;try{ev=JSON.parse(part.slice(6));}catch{continue;}
if(ev.type==='thinking_delta'&&ev.text)thinkBuf+=ev.text;
else if(ev.type==='final'&&typeof ev.text==='string'){
// The backend strips leaked/malformed tool-call JSON (e.g. a model typing
// "web_search{...}" as literal text instead of a real tool call) only from
// this post-hoc cleaned copy — the raw per-token stream above never sees that
// cleanup, so whatever leaked was already rendered. Overwrite with the clean
// version once it arrives so the bubble ends up correct instead of stuck showing
// the leak, and re-run the map/photo triggers in case the raw stream's version
// hid or mangled a URL that only appears intact in this cleaned text.
textBuf=ev.text;
if(bubble){
bubble.innerHTML=(thinkBuf?`<div class="wt-thinking" onclick="this.classList.toggle('exp')">💭 ${escHtml(thinkBuf.slice(0,120))}${thinkBuf.length>120?'…':''}</div>`:'')+renderMdSafe(textBuf);
msgs.scrollTop=msgs.scrollHeight;
}
if(!windyLoaded&&processWindyUrl(textBuf))windyLoaded=true;
if(!satPhotoLoaded&&processSatelliteImage(textBuf))satPhotoLoaded=true;
if(!kmaLoaded&&textBuf.includes(KMA_TYPHOON_URL)){loadWindyUrl(KMA_TYPHOON_URL,'kma-track');switchCenterTab('map');kmaLoaded=true;}
if(!nhcLoaded&&loadNhcTrackUrl(textBuf))nhcLoaded=true;
}
else if(ev.type==='token'||ev.type==='text_delta'){
textBuf+=(ev.text||'');
if(bubble){
bubble.innerHTML=(thinkBuf?`<div class="wt-thinking" onclick="this.classList.toggle('exp')">💭 ${escHtml(thinkBuf.slice(0,120))}${thinkBuf.length>120?'…':''}</div>`:'')+renderMdSafe(textBuf);
msgs.scrollTop=msgs.scrollHeight;
}
// Auto-load first Windy URL found
// Auto-load first Windy URL found. Wait until the match doesn't end exactly at
// the current buffer's end — otherwise the URL may still be mid-stream (e.g.
// "lat=13" before the rest of "13.5&zoom=...&overlay=..." arrives), and loading
// that truncated URL would set windyLoaded=true and lock out the real one.
if(!windyLoaded&&textBuf.includes('embed.windy.com')){
if(processWindyUrl(textBuf)){windyLoaded=true;}
const wm=textBuf.match(/https:\/\/embed\.windy\.com\/embed2\.html\?[a-zA-Z0-9.=&%_-]+/);
if(wm&&wm.index+wm[0].length<textBuf.length&&processWindyUrl(textBuf)){windyLoaded=true;}
}
// Auto-open first satellite photo found
if(!satPhotoLoaded&&textBuf.includes('/api/files/satellite-images/')){
if(processSatelliteImage(textBuf)){satPhotoLoaded=true;}
}
// Auto-load KMA typhoon track page — fixed literal URL, so unlike the Windy
// case above there's no partial-number risk: substring presence IS completeness.
if(!kmaLoaded&&textBuf.includes(KMA_TYPHOON_URL)){
loadWindyUrl(KMA_TYPHOON_URL,'kma-track');
switchCenterTab('map');
kmaLoaded=true;
}
// Auto-load NHC forecast-track page — variable-length URL (graphics_ep2 vs
// graphics_at12 etc.), so same boundary-safety as the Windy check above: only
// trust the match once something follows it, confirming it finished streaming.
if(!nhcLoaded&&textBuf.includes('nhc.noaa.gov/graphics_')){
const nm=textBuf.match(NHC_TRACK_RE);
if(nm&&nm.index+nm[0].length<textBuf.length&&loadNhcTrackUrl(textBuf)){nhcLoaded=true;}
}
}
}
}
if(!windyLoaded&&textBuf)processWindyUrl(textBuf);
if(!satPhotoLoaded&&textBuf)processSatelliteImage(textBuf);
if(!kmaLoaded&&textBuf.includes(KMA_TYPHOON_URL)){loadWindyUrl(KMA_TYPHOON_URL,'kma-track');switchCenterTab('map');}
if(!nhcLoaded&&textBuf)loadNhcTrackUrl(textBuf);
// The model is separately instructed to always ALSO include a plain Windy URL next to
// a KMA/NHC track link (so external-only answers can't skip the embed) — that means a
// single response can carry both, and whichever streamed later would silently win the
// final map state. A track-cone page is strictly more informative for a path question
// than the plain Windy view, so force it to be what's left showing if both are present.
if(textBuf.includes(KMA_TYPHOON_URL)){loadWindyUrl(KMA_TYPHOON_URL,'kma-track');switchCenterTab('map');}
else if(NHC_TRACK_RE.test(textBuf)){loadNhcTrackUrl(textBuf);}
}catch(e){
typingDiv.remove();
if(e.name!=='AbortError'){if(!bubble)bubble=addMsg('assistant','');bubble.innerHTML='<span style="color:var(--err)">오류: '+escHtml(e.message)+'</span>';}
@@ -918,8 +1017,7 @@ function mobToggle(which){
restoreWtTabs();
renderCenterTabs();
// 지도는 인증 직후 바로 로드 (세션 ID와 무관)
document.getElementById('map-loading').classList.remove('hidden');
document.getElementById('windy-frame').src=windyUrl(mapLat,mapLon,mapZoom,mapOverlay);
wtLoadMap(windyUrl(mapLat,mapLon,mapZoom,mapOverlay));
await Promise.all([initSessionId(),loadSkill(),loadModels()]);
await ensureChatContextForLoc();
addMsg('system','🌤️ 날씨 어시스턴트입니다. 지역 날씨, 예보, 기상 현상을 질문하세요.');