Files
homeclaw/src/tools/weather.ts
T

2902 lines
159 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ToolResult } from '../types.js';
import { getConfig } from '../config/config.js';
import { getVault } from '../security/vault.js';
import { fetchMidTermLines, pickMidRegion } from './kma-midterm.js';
import { kakaoGeocode } from './kakao-geocode.js';
import { getPaths, getWorkspacePath } from '../config/paths.js';
import { buildImageMarkdown } from './image.js';
import { splitOpenMeteoVariables, formatOpenMeteoReport } from './weather-openmeteo-format.js';
import { AWS_STATIONS } from './kma-aws-stations.js';
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import https from 'https';
// IPv4-forced HTTPS GET — used for hosts whose IPv6 is unreachable from this server
function httpsGetJsonIPv4(url: string, timeoutMs = 30_000): Promise<any> {
return new Promise((resolve, reject) => {
const u = new URL(url);
const req = https.get(
{ hostname: u.hostname, path: u.pathname + u.search, family: 4, timeout: timeoutMs },
(res) => {
let raw = '';
res.on('data', (c: Buffer) => { raw += c.toString(); });
res.on('end', () => {
try { resolve(JSON.parse(raw)); }
catch { reject(new Error(`JSON parse error: ${raw.slice(0, 100)}`)); }
});
}
);
req.on('timeout', () => { req.destroy(); reject(new Error(`요청 타임아웃 (${timeoutMs / 1000}초)`)); });
req.on('error', reject);
});
}
const OW_BASE = 'https://api.openweathermap.org/data/2.5';
const KMA_BASE = 'http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0';
const AIRKOREA_BASE = 'http://apis.data.go.kr/B552584/ArpltnInforInqireSvc';
const AIRKOREA_STATION_BASE = 'http://apis.data.go.kr/B552584/MsrstnInfoInqireSvc';
/**
* Station names belonging to a city/county, from AirKorea's 측정소정보 service.
*
* The realtime feed only tags stations with a province (`sidoName`), and station names give no
* hint of their city — "우현동" is 포항, "중방동" is 경산. So a 구미 question used to be answered
* off the province-wide list with whatever rows came first, presenting other cities' readings as
* 구미 (observed 2026-08-09, twice). This is the mapping that makes city filtering possible.
*
* The upstream `addr` query parameter does not filter, so the full list is fetched and matched
* locally. Cached for a day — station rosters change on the order of years.
*/
const _stationCityCache = new Map<string, { names: string[]; at: number }>();
const STATION_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
async function stationsForCity(city: string, apiKey: string): Promise<string[] | null> {
const key = city.trim();
const hit = _stationCityCache.get(key);
if (hit && Date.now() - hit.at < STATION_CACHE_TTL_MS) return hit.names;
const params = new URLSearchParams({
serviceKey: apiKey, returnType: 'json', numOfRows: '700', pageNo: '1',
});
// data.go.kr answers this endpoint with an intermittent SERVICETIMEOUT_ERROR (~1 in 5 observed
// on 2026-08-09) that clears immediately, so a single failure must not collapse to "no stations".
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const res = await fetch(`${AIRKOREA_STATION_BASE}/getMsrstnList?${params}`, { signal: AbortSignal.timeout(20_000) });
if (!res.ok) throw new Error(`station list HTTP ${res.status}`);
const data: any = await res.json();
if (data?.OpenAPI_ServiceResponse) throw new Error(String(data.OpenAPI_ServiceResponse?.cmmMsgHeader?.errMsg || 'service error'));
const items: any[] = data?.response?.body?.items || [];
if (!items.length) throw new Error('empty station list');
// Match on the address, not the station name: "구미시" appears in addr, never in the name.
const needle = key.endsWith('시') || key.endsWith('군') || key.endsWith('구') ? key : `${key}시`;
const names = items
.filter(it => String(it.addr || '').includes(needle))
.map(it => String(it.stationName || ''))
.filter(Boolean);
_stationCityCache.set(key, { names, at: Date.now() });
return names;
} catch {
if (attempt >= 3) return null; // unknown, not "none" — caller must not claim a city filter
await new Promise(r => setTimeout(r, 400 * attempt));
}
}
return null;
}
// ── API key helpers ───────────────────────────────────────────────────────────
function getApiKey(): string | undefined {
try {
const cm = getConfig();
const cfg = cm.getConfig();
const resolved = cm.resolveSecret(cfg.openweather?.api_key || cfg.weather?.api_key);
if (resolved) return resolved;
const vault = getVault(cm.getConfigDir());
return vault.get('openweather.api_key', 'weather:getkey')?.expose();
} catch {}
return undefined;
}
function getKmaApiKey(): string | undefined {
try {
const cm = getConfig();
const cfg = cm.getConfig();
const resolved = cm.resolveSecret((cfg as any).kma?.api_key);
if (resolved) return resolved;
const vault = getVault(cm.getConfigDir());
return vault.get('kma.api_key', 'weather:kma')?.expose();
} catch {}
return undefined;
}
// 기상청 API허브(apihub.kma.go.kr)는 data.go.kr과 **다른 계정·다른 키**다. 지점정보뿐 아니라
// AWS 매분자료·기후통계·적설·자외선 등이 여기 있고, API별로 또 활용신청이 필요하다.
// 현재 런타임에서 쓰는 곳은 없다 — ASOS 지점 좌표는 정적 표로 박혀 있다(ASOS_STATIONS 주석).
// 이 접근자는 그 표를 갱신하거나 허브의 다른 자료를 붙일 때 쓰는 진입점이다.
export function getKmaApiHubKey(): string | undefined {
try {
const cm = getConfig();
const resolved = cm.resolveSecret((cm.getConfig() as any).kma?.apihub_key);
if (resolved) return resolved;
return getVault(cm.getConfigDir()).get('kma.apihub_key', 'weather:apihub')?.expose();
} catch {}
return undefined;
}
// API허브 공통 페치. 두 가지가 매번 발목을 잡아서 여기 가둬둔다:
// 1) 응답이 EUC-KR이다. UTF-8로 읽으면 한글 지점명이 전부 깨진다.
// 2) 미승인 API는 200이 아니라 403 + JSON으로 "활용신청이 필요한 API 입니다"를 준다.
// 키가 틀리면 401 "유효한 인증키가 아닙니다"라 둘을 구분해서 알려줘야 헛짚지 않는다.
export async function apiHubFetch(pathAndQuery: string): Promise<string> {
const key = getKmaApiHubKey();
if (!key) throw new Error('API허브 키가 없습니다. vault에 kma.apihub_key를 등록하세요 (apihub.kma.go.kr에서 발급, data.go.kr 키와 별개).');
const sep = pathAndQuery.includes('?') ? '&' : '?';
const res = await fetch(`https://apihub.kma.go.kr/api/${pathAndQuery}${sep}authKey=${encodeURIComponent(key)}`,
{ signal: AbortSignal.timeout(30_000) });
const buf = await res.arrayBuffer();
// 인코딩이 응답 종류마다 다르다: 자료 본문은 EUC-KR인데 에러는 UTF-8 JSON이다.
// 에러까지 EUC-KR로 읽으면 "활용신청이 필요합니다"가 깨져서 원인을 못 읽는다.
const utf8 = new TextDecoder('utf-8').decode(buf);
if (utf8.trimStart().startsWith('{')) {
let msg = utf8.slice(0, 200);
try { msg = JSON.parse(utf8)?.result?.message || msg; } catch {}
throw new Error(`API허브 ${res.status}: ${msg}`);
}
if (!res.ok) throw new Error(`API허브 ${res.status}: ${utf8.slice(0, 200)}`);
return new TextDecoder('euc-kr').decode(buf);
}
function getAirKoreaApiKey(): string | undefined {
try {
const cm = getConfig();
const cfg = cm.getConfig();
const resolved = cm.resolveSecret((cfg as any).airkorea?.api_key);
if (resolved) return resolved;
const vault = getVault(cm.getConfigDir());
// AirKorea uses same data.go.kr key as KMA
return vault.get('airkorea.api_key', 'weather:airkorea')?.expose()
?? vault.get('kma.api_key', 'weather:airkorea')?.expose();
} catch {}
return undefined;
}
// ── Shared utilities ──────────────────────────────────────────────────────────
function windDirection(deg: number): string {
const dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
return dirs[Math.round(deg / 22.5) % 16];
}
const windDirectionKo = (deg: number) =>
['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동',
'남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서'][Math.round(deg / 22.5) % 16];
// Geocode city name → lat/lon using Open-Meteo geocoding (no API key required)
// Falls back to a built-in lookup table for common Korean cities.
export const KR_CITY_COORDS: Record<string, [number, number]> = {
// 2026-10-14: Open-Meteo 지오코더가 "현풍"을 경주의 무명 지명(36.03, 129.24)으로 풀어 대구 달성군
// 현풍읍 대신 70km 떨어진 곳 예보가 나갔다. 사용자가 실제로 쓰는 달성군 읍 단위를 직접 넣는다.
'현풍': [35.6955, 128.4477], '현풍읍': [35.6955, 128.4477],
'화원': [35.8026, 128.5008], '화원읍': [35.8026, 128.5008],
'다사': [35.8542, 128.4533], '다사읍': [35.8542, 128.4533],
'논공': [35.7467, 128.4325], '논공읍': [35.7467, 128.4325],
'서울': [37.5665, 126.9780], 'seoul': [37.5665, 126.9780],
'부산': [35.1796, 129.0756], 'busan': [35.1796, 129.0756],
'인천': [37.4563, 126.7052], 'incheon': [37.4563, 126.7052],
'대구': [35.8714, 128.6014], 'daegu': [35.8714, 128.6014],
'광주': [35.1595, 126.8526], 'gwangju': [35.1595, 126.8526],
'대전': [36.3504, 127.3845], 'daejeon': [36.3504, 127.3845],
'울산': [35.5384, 129.3114], 'ulsan': [35.5384, 129.3114],
'세종': [36.4800, 127.2890], 'sejong': [36.4800, 127.2890],
'제주': [33.4996, 126.5312], 'jeju': [33.4996, 126.5312],
'수원': [37.2636, 127.0286], 'suwon': [37.2636, 127.0286],
'창원': [35.2280, 128.6811], 'changwon': [35.2280, 128.6811],
'고양': [37.6584, 126.8320], 'goyang': [37.6584, 126.8320],
'성남': [37.4386, 127.1378], 'seongnam': [37.4386, 127.1378],
'천안': [36.8151, 127.1139], 'cheonan': [36.8151, 127.1139],
'전주': [35.8242, 127.1479], 'jeonju': [35.8242, 127.1479],
'청주': [36.6424, 127.4890], 'cheongju': [36.6424, 127.4890],
'포항': [36.0190, 129.3435], 'pohang': [36.0190, 129.3435],
'여수': [34.7604, 127.6622], 'yeosu': [34.7604, 127.6622],
'춘천': [37.8813, 127.7298], 'chuncheon': [37.8813, 127.7298],
'강릉': [37.7519, 128.8761], 'gangneung': [37.7519, 128.8761],
'목포': [34.8118, 126.3922], 'mokpo': [34.8118, 126.3922],
'진주': [35.1798, 128.1076], 'jinju': [35.1798, 128.1076],
'평택': [36.9921, 127.1128], 'pyeongtaek': [36.9921, 127.1128],
'안산': [37.3219, 126.8310], 'ansan': [37.3219, 126.8310],
'용인': [37.2411, 127.1776], 'yongin': [37.2411, 127.1776],
// 2026-07-29: added after "내일 구미 날씨" silently resolved to the WRONG place. Open-Meteo's
// geocoder returns ten 구미 hits for Korea and the real 구미시 (36.12, 128.34) is not among
// them — the list is dominated by tiny hamlets, and because every entry comes back with an
// empty population field the "pick the most populous" tiebreak degrades to results[0], a
// village in 강원도 at 38.16 — two degrees of latitude away, i.e. a different climate.
// No error was ever raised; the user just got someone else's weather.
// Any mid-size Korean city the geocoder cannot pin down belongs in this table.
'구미': [36.1195, 128.3446], 'gumi': [36.1195, 128.3446],
// 2026-08-16: 관측지점 이름표를 지오코딩 소스로 쓰면서 남은 동명 3건. 같은 이름의 지점이
// 100km 넘게 떨어져 둘씩 있어서 이름표는 "모호"로 넘기는데, 그러면 지오코더로 새고
// 옥천은 북한(39.94, 124.53)으로 간다. 널리 통하는 행정구역 쪽을 여기에 못박는다.
// (버린 쪽은 전부 경기도의 동명 지점 — 진안 439, 옥천 449, 가산 473)
'진안': [35.7604, 127.4374], 'jinan': [35.7604, 127.4374],
'옥천': [36.3000, 127.5965], 'okcheon': [36.3000, 127.5965],
'가산': [36.0956, 128.5001],
'김해': [35.2285, 128.8894], 'gimhae': [35.2285, 128.8894],
'안양': [37.3943, 126.9568], 'anyang': [37.3943, 126.9568],
'부천': [37.5034, 126.7660], 'bucheon': [37.5034, 126.7660],
'남양주': [37.6360, 127.2165], 'namyangju': [37.6360, 127.2165],
'화성': [37.1996, 126.8310], 'hwaseong': [37.1996, 126.8310],
'시흥': [37.3800, 126.8029], 'siheung': [37.3800, 126.8029],
'파주': [37.7599, 126.7800], 'paju': [37.7599, 126.7800],
'의정부': [37.7381, 127.0337], 'uijeongbu': [37.7381, 127.0337],
'김포': [37.6152, 126.7156], 'gimpo': [37.6152, 126.7156],
'광명': [37.4786, 126.8646], 'gwangmyeong': [37.4786, 126.8646],
'군포': [37.3617, 126.9352], 'gunpo': [37.3617, 126.9352],
'이천': [37.2723, 127.4350], 'icheon': [37.2723, 127.4350],
'양산': [35.3350, 129.0372], 'yangsan': [35.3350, 129.0372],
'거제': [34.8806, 128.6212], 'geoje': [34.8806, 128.6212],
'통영': [34.8544, 128.4331], 'tongyeong': [34.8544, 128.4331],
'경주': [35.8562, 129.2247], 'gyeongju': [35.8562, 129.2247],
'안동': [36.5684, 128.7294], 'andong': [36.5684, 128.7294],
'아산': [36.7898, 127.0018], 'asan': [36.7898, 127.0018],
'충주': [36.9910, 127.9259], 'chungju': [36.9910, 127.9259],
'원주': [37.3422, 127.9202], 'wonju': [37.3422, 127.9202],
'군산': [35.9676, 126.7369], 'gunsan': [35.9676, 126.7369],
'익산': [35.9483, 126.9576], 'iksan': [35.9483, 126.9576],
'순천': [34.9506, 127.4872], 'suncheon': [34.9506, 127.4872],
'광양': [34.9407, 127.6959], 'gwangyang': [34.9407, 127.6959],
'서귀포': [33.2541, 126.5601], 'seogwipo': [33.2541, 126.5601],
};
// Same-named cities across countries (e.g. "Rome" → Rome, Italy vs Rome, Georgia US)
// are common — an unqualified geocoding lookup must not blindly trust index 0.
// Shared by geocodeCity() (Open-Meteo) and normalizeLocationForOpenWeather() (OpenWeather).
const COUNTRY_NAME_TO_ISO: Record<string, string> = {
italy: 'IT', france: 'FR', germany: 'DE', spain: 'ES', portugal: 'PT',
'united kingdom': 'GB', uk: 'GB', england: 'GB', netherlands: 'NL', belgium: 'BE',
switzerland: 'CH', austria: 'AT', poland: 'PL', sweden: 'SE', norway: 'NO',
denmark: 'DK', finland: 'FI', greece: 'GR', ireland: 'IE', 'czech republic': 'CZ',
czechia: 'CZ', hungary: 'HU', russia: 'RU', china: 'CN', japan: 'JP',
'south korea': 'KR', korea: 'KR', canada: 'CA', australia: 'AU', brazil: 'BR',
mexico: 'MX', india: 'IN', turkey: 'TR', egypt: 'EG', 'south africa': 'ZA',
vietnam: 'VN', thailand: 'TH', indonesia: 'ID', philippines: 'PH', singapore: 'SG',
malaysia: 'MY', 'new zealand': 'NZ', ukraine: 'UA', romania: 'RO', bulgaria: 'BG',
croatia: 'HR', slovakia: 'SK', slovenia: 'SI', iceland: 'IS', luxembourg: 'LU',
'united states': 'US', usa: 'US', 'united states of america': 'US',
};
// Splits "City,CC" / "City,Country Name" into a bare city name plus an ISO-3166
// country code, if the trailing part after the last comma names one.
function parseExplicitCountry(name: string): { city: string; countryCode?: string } {
const lastComma = name.lastIndexOf(',');
if (lastComma < 0) return { city: name };
const city = name.slice(0, lastComma).trim();
const countryPart = name.slice(lastComma + 1).trim();
if (/^[A-Za-z]{2}$/.test(countryPart)) return { city, countryCode: countryPart.toUpperCase() };
const iso = COUNTRY_NAME_TO_ISO[countryPart.toLowerCase()];
if (iso) return { city, countryCode: iso };
return { city: name };
}
/**
* Did the caller pack several places into one `location`?
*
* Asked to compare cities, models batch them into a single argument
* ("London, Berlin, Paris, Rome, Madrid"). That geocodes to nothing, and the bare
* "위치를 찾을 수 없습니다" gave the model no reason to do anything but reissue the identical
* call — the turn then burned its rounds on an unwinnable loop (observed 2026-08-09 09:09).
*
* Only consulted after whole-string geocoding has already failed, so a legitimate
* "Seoul, Korea" never reaches here (parseExplicitCountry resolves it). Requiring the first
* two segments to geocode independently keeps "Springfield, Freedonia" — one real place plus
* an unknown qualifier — from being misread as a list.
*/
async function looksLikeMultipleLocations(location: string): Promise<string[] | null> {
const parts = location.split(',').map(p => p.trim()).filter(Boolean);
if (parts.length < 2) return null;
const [first, second] = await Promise.all([geocodeCity(parts[0]), geocodeCity(parts[1])]);
return first && second ? parts : null;
}
/**
* The "location not found" result every weather tool returns, upgraded to say what to do next
* when the cause is a batched city list. Shared because all six tools geocode the same way and
* would otherwise each loop on the same input.
*/
export async function locationNotFoundError(location: string, toolName: string): Promise<ToolResult> {
const cities = await looksLikeMultipleLocations(location);
if (!cities) return { success: false, error: `위치를 찾을 수 없습니다: ${location}` };
return {
success: false,
error:
`이 도구는 한 번에 한 곳만 조회합니다. ${cities.length}곳이 한꺼번에 전달됐습니다: ${cities.join(', ')}. `
+ `도시마다 ${toolName}을 따로 호출하세요 — 예: {"location":"${cities[0]}"} 다음에 {"location":"${cities[1]}"}. `
+ `같은 인자로 다시 호출하면 똑같이 실패합니다.`,
};
}
// 기상청 관측지점 이름 → 좌표. ASOS 97개 + AWS 745개에서 만든다.
//
// 왜 필요한가: Open-Meteo 지오코더는 한국 지명에 거의 못 쓴다. 2026-08-16에 ASOS 지명
// 66개(KR_CITY_COORDS에 없는 것)를 공식 좌표와 대조했더니 **44개가 틀렸다** —
// 25개는 아예 조회 실패, 19개는 엉뚱한 좌표. 홍성·보령·서산·홍천·밀양·고산은 북한 동명
// 지역으로, 동해는 408km, 제천 214km, 상주 188km 떨어진 곳으로 갔다. 전부 사람들이
// 실제로 묻는 도시다.
//
// 지점 좌표는 기상청이 발표한 값이라 이 문제가 구조적으로 안 생긴다. 게다가 날씨를 묻는
// 맥락에선 "그 지명의 관측소 위치"가 사실상 정답이다.
//
// 같은 이름이 멀리 떨어져 둘 이상 있으면(739개 중 진안·옥천·가산 3건) 어느 쪽인지 모르므로
// 쓰지 않고 넘긴다 — 조용히 한쪽을 고르면 틀렸을 때 드러나지 않는다.
let stationPlaceIndex: Map<string, { lat: number; lon: number }> | null = null;
function getStationPlaceIndex(): Map<string, { lat: number; lon: number }> {
if (stationPlaceIndex) return stationPlaceIndex;
const groups = new Map<string, Array<[number, string, number, number]>>();
for (const s of [...ASOS_STATIONS, ...AWS_STATIONS]) {
const k = stripAdmin(s[1]);
if (!k) continue;
const list = groups.get(k);
if (list) list.push(s); else groups.set(k, [s]);
}
const index = new Map<string, { lat: number; lon: number }>();
for (const [k, list] of groups) {
let spread = 0;
for (let i = 0; i < list.length; i++) {
for (let j = i + 1; j < list.length; j++) {
spread = Math.max(spread, haversineKm(list[i][2], list[i][3], list[j][2], list[j][3]));
}
}
if (spread > 20) continue; // 모호 — 지오코더로 넘긴다
index.set(k, { lat: list[0][2], lon: list[0][3] });
}
stationPlaceIndex = index;
return index;
}
export function lookupKoreanPlace(name: string): { lat: number; lon: number } | null {
const k = stripAdmin(String(name || ''));
return k ? (getStationPlaceIndex().get(k) ?? null) : null;
}
// 지오코딩 후보 중 하나 고르기. 나라가 명시됐으면 그 나라를 먼저 찾고, 아니면 인구 최다를
// 고른다 — Open-Meteo는 "Rome" 같은 맨 질의에 미국의 작은 동명 도시를 국제적으로 알려진
// 도시보다 위에 올리는 일이 잦아서 results[0]을 그냥 쓰면 안 된다.
//
// 다만 이 규칙은 **후보 목록 안에 정답이 들어 있을 때만** 작동한다. count가 작으면 정답이
// 목록 밖으로 밀려나고, 그러면 남은 것 중 최다를 골라 조용히 틀린다(New York → 네브래스카
// York 사건). 그래서 호출부의 count와 이 함수는 한 몸으로 봐야 한다.
export function pickGeocodeResult(results: any[], countryCode?: string): any | null {
if (!results?.length) return null;
if (countryCode) {
const byCountry = results.find((x: any) => String(x.country_code || '').toUpperCase() === countryCode);
if (byCountry) return byCountry;
}
return results.reduce((best: any, cur: any) => (cur.population || 0) > (best.population || 0) ? cur : best, results[0]);
}
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 };
}
// 손으로 넣은 표 다음, 지오코더보다 먼저. 한글이 섞인 입력만 본다 — 영문/외국 지명은
// 지점명과 부딪힐 일이 없고 지오코더가 제대로 처리한다.
if (/[가-힣]/.test(name)) {
const stn = lookupKoreanPlace(name);
if (stn) return { lat: stn.lat, lon: stn.lon, displayName: name };
}
// 2026-10-14: 한글 지명은 카카오 로컬 주소검색(읍·면·동·시·군·구)을 먼저 본다. Open-Meteo 지오코더는
// 로마자 DB라 "현풍"을 경주의 무명 지명으로 풀었다. 키 없음·REGION 없음·실패면 null → 아래로 폴백.
if (/[가-힣]/.test(name)) {
const kk = await kakaoGeocode(name, {
getKey: () => {
try {
const cm = getConfig();
return cm.resolveSecret((cm.getConfig() as any).channels?.kakao?.appKey)
|| getVault(cm.getConfigDir()).get('channels.kakao.appKey', 'kakao:geocode')?.expose();
} catch { return undefined; }
},
cacheFile: path.join(getConfig().getConfigDir(), 'geocode-kakao-cache.json'),
});
if (kk) return kk;
}
const { city, countryCode } = parseExplicitCountry(name);
// count=10이면 "New York"에 뉴욕시(인구 880만)가 아예 안 딸려온다 — 후보 10개가
// York(네브래스카, 7,864명), Florence(인디애나, 80명), New York(영국/자메이카)로 채워지고,
// 아래 "인구 최다" 규칙이 그중 최다인 네브래스카 York를 고른다. 에러 없이 조용히 틀린다.
// count=20이면 뉴욕시가 후보에 들어온다. 2026-08-16에 주요 도시 23곳을 10 vs 20으로
// 대조했더니 바뀐 건 New York 하나뿐이라, 다른 지명 선택엔 영향이 없다.
const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=20&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").
const r = pickGeocodeResult(results, countryCode);
if (!r) return null;
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 {
const m = location.match(/^(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)$/);
return m ? [parseFloat(m[1]), parseFloat(m[2])] : null;
}
// ── KMA grid coordinate conversion (Lambert Conformal Conic) ─────────────────
// Pre-computed grid coordinates for major Korean cities (official KMA values)
export const KMA_GRID: Record<string, [number, number]> = {
'서울': [60, 127], 'seoul': [60, 127],
'부산': [98, 76], 'busan': [98, 76],
'인천': [55, 124], 'incheon': [55, 124],
'대구': [89, 90], 'daegu': [89, 90],
'광주': [58, 74], 'gwangju': [58, 74],
'대전': [67, 100], 'daejeon': [67, 100],
'울산': [102, 84], 'ulsan': [102, 84],
'세종': [66, 103], 'sejong': [66, 103],
'수원': [60, 121], 'suwon': [60, 121],
'제주': [52, 38], 'jeju': [52, 38],
'천안': [63, 110], 'cheonan': [63, 110],
'전주': [63, 89], 'jeonju': [63, 89],
'청주': [69, 106], 'cheongju': [69, 106],
'춘천': [73, 134], 'chuncheon': [73, 134],
'강릉': [92, 131], 'gangneung': [92, 131],
'포항': [102, 94], 'pohang': [102, 94],
'창원': [91, 77], 'changwon': [91, 77],
'고양': [57, 128], 'goyang': [57, 128],
'성남': [62, 123], 'seongnam': [62, 123],
'진주': [81, 75], 'jinju': [81, 75],
'여수': [73, 66], 'yeosu': [73, 66],
'목포': [50, 67], 'mokpo': [50, 67],
// 2026-08-16: [75,100]이었는데 45km 떨어진 산간 격자였다. ASOS 구미(279) 실측 31.5°C에
// 표는 25.3°C(Δ6.2), 좌표 변환값 [84,96]은 31.9°C(Δ0.4). 표가 틀린 게 확인돼 교체.
'구미': [84, 96], 'gumi': [84, 96],
'안동': [91, 106], 'andong': [91, 106],
'경주': [100, 91], 'gyeongju': [100, 91],
'김해': [95, 77], 'gimhae': [95, 77],
// 2026-08-16: [95,71]은 아예 자료가 없는 격자였다 — T1H가 기상청 결측 표식 -999로 왔다.
// 좌표 변환값 [90,69]는 ASOS 거제(294) 실측 30.8°C에 31.0°C(Δ0.2).
'거제': [90, 69], 'geoje': [90, 69],
'순천': [70, 70], 'suncheon': [70, 70],
'익산': [60, 91], 'iksan': [60, 91],
'원주': [76, 122], 'wonju': [76, 122],
'평택': [62, 114], 'pyeongtaek': [62, 114],
// 2026-08-16: [57,120]이었는데 안산 [58,121]보다 남쪽에 놓여 있었다. 시흥시(37.38°N)는
// 안산시(37.32°N)보다 북쪽이라 ny가 더 커야 한다. ASOS 지점이 없어 실측 대조는 못 했고
// (두 후보 다 값 자체는 그럴듯했다 — 해안 23.9°C/94% vs 내륙 30.2°C/67%), 인접 도시와의
// 남북 순서로 판정했다.
'시흥': [57, 123], 'siheung': [57, 123],
'부천': [56, 125], 'bucheon': [56, 125],
'안산': [57, 121], 'ansan': [57, 121],
};
export function latLonToKmaGrid(lat: number, lon: number): { nx: number; ny: number } {
const DEGRAD = Math.PI / 180;
const re = 6371.00877 / 5.0;
const slat1 = 30.0 * DEGRAD;
const slat2 = 60.0 * DEGRAD;
const olon = 126.0 * DEGRAD;
const olat = 38.0 * DEGRAD;
const XO = 43, YO = 136;
const sn = Math.log(Math.cos(slat1) / Math.cos(slat2)) /
Math.log(Math.tan(Math.PI * 0.25 + slat2 * 0.5) / Math.tan(Math.PI * 0.25 + slat1 * 0.5));
const sf = Math.pow(Math.tan(Math.PI * 0.25 + slat1 * 0.5), sn) * Math.cos(slat1) / sn;
const ro = re * sf / Math.pow(Math.tan(Math.PI * 0.25 + olat * 0.5), sn);
const ra = re * sf / Math.pow(Math.tan(Math.PI * 0.25 + lat * DEGRAD * 0.5), sn);
let theta = lon * DEGRAD - olon;
if (theta > Math.PI) theta -= 2 * Math.PI;
if (theta < -Math.PI) theta += 2 * Math.PI;
theta *= sn;
// 기상청 공식 변환식의 마지막 항은 반올림용 +0.5다. 여기 오래 +1.5가 들어가 있어서
// nx·ny가 나란히 한 칸씩 밀린 셀을 조회했다(격자 1칸 = 5km, 대각 ~7km).
// 이름이 KMA_GRID에 있는 도시는 표를 타서 멀쩡했고 좌표 입력만 틀렸던 탓에 안 드러났다.
// 2026-08-16 발견: 같은 서울을 "서울"과 "37.5665,126.978"로 조회했더니 일 누적이
// 9.8mm vs 29mm로 갈렸다.
return {
nx: Math.floor(ra * Math.sin(theta) + XO + 0.5),
ny: Math.floor(ro - ra * Math.cos(theta) + YO + 0.5),
};
}
function getKmaGrid(locationKey: string, lat: number, lon: number): { nx: number; ny: number } {
const key = locationKey.trim().toLowerCase();
if (KMA_GRID[key]) return { nx: KMA_GRID[key][0], ny: KMA_GRID[key][1] };
return latLonToKmaGrid(lat, lon);
}
// KMA base date/time for API calls (KST = UTC+9)
function getKmaBaseDateTime(type: 'ncst' | 'fcst'): { base_date: string; base_time: string } {
const now = new Date(Date.now() + 9 * 3600 * 1000);
const pad2 = (n: number) => String(n).padStart(2, '0');
const yyyymmdd = now.toISOString().slice(0, 10).replace(/-/g, '');
const hh = now.getUTCHours();
const mm = now.getUTCMinutes();
if (type === 'ncst') {
// Ultra-short-term: published HH:40 for the HH:00 period
const obsHour = mm < 40 ? hh - 1 : hh;
if (obsHour < 0) {
const prev = new Date(now.getTime() - 24 * 3600 * 1000);
return { base_date: prev.toISOString().slice(0, 10).replace(/-/g, ''), base_time: '2300' };
}
return { base_date: yyyymmdd, base_time: `${pad2(obsHour)}00` };
} else {
// Short-term: issued at 0200, 0500, 0800, 1100, 1400, 1700, 2000, 2300 (+10min buffer)
const ISSUE = [2, 5, 8, 11, 14, 17, 20, 23];
const cur = hh + mm / 60;
let baseHour = 23;
for (const h of ISSUE) {
if (cur >= h + 0.17) baseHour = h;
}
if (cur < 2.17) {
const prev = new Date(now.getTime() - 24 * 3600 * 1000);
return { base_date: prev.toISOString().slice(0, 10).replace(/-/g, ''), base_time: '2300' };
}
return { base_date: yyyymmdd, base_time: `${pad2(baseHour)}00` };
}
}
// 초단기예보(getUltraSrtFcst): 매시 30분 기준 발표, 45분 이후 조회 가능, 앞으로 6시간(1시간 간격).
async function fetchUltraSrtFcstLines(nx: number, ny: number): Promise<string[]> {
const now = new Date(Date.now() + 9 * 3600 * 1000);
let t = new Date(now.getTime());
if (now.getUTCMinutes() < 45) t = new Date(now.getTime() - 3600 * 1000);
const base_date = t.toISOString().slice(0, 10).replace(/-/g, '');
const base_time = `${String(t.getUTCHours()).padStart(2, '0')}30`;
const items = await kmaFetch('getUltraSrtFcst', { base_date, base_time, nx: String(nx), ny: String(ny) });
const byTime: Record<string, Record<string, string>> = {};
for (const it of items as any[]) {
const k = `${it.fcstDate}${String(it.fcstTime).slice(0, 2)}`;
(byTime[k] ||= {})[it.category] = String(it.fcstValue);
}
const keys = Object.keys(byTime).sort().slice(0, 6);
if (!keys.length) return [];
const rows = keys.map(k => {
const v = byTime[k];
const sky = v.PTY && v.PTY !== '0' ? (PTY_LABEL[v.PTY] ?? v.PTY) : (SKY_SHORT[v.SKY] ?? '');
const rn = v.RN1 && v.RN1 !== '강수없음' ? `강수 ${v.RN1}` : '';
const parts = [v.T1H != null ? `${v.T1H}°C` : null, v.REH != null ? `습도 ${v.REH}%` : null,
v.WSD != null ? `${v.WSD}m/s` : null, sky || null, rn || null].filter(Boolean);
return ` ${k.slice(8, 10)}시 ${parts.join(', ')}`;
});
const rainy = keys.filter(k => (byTime[k].PTY && byTime[k].PTY !== '0') || (byTime[k].RN1 && byTime[k].RN1 !== '강수없음'));
const head = rainy.length
? `🔮 앞으로 6시간 (초단기예보): ${rainy[0].slice(8, 10)}시부터 비/눈 예상`
: '🔮 앞으로 6시간 (초단기예보): 강수 없음';
return [head, ...rows];
}
// 단기예보 시간별 표. 오늘(지금 이후)·내일을 3시간 간격으로: 기온(TMP)·습도(REH)·풍속(WSD)·풍향(VEC)·
// 강수확률(POP)·하늘(SKY)/강수형태(PTY)·적설(SNO). 일별 요약만으론 "내일 아침 몇 도/바람 세?"에 못 답한다.
const SKY_SHORT: Record<string, string> = { '1': '맑음', '3': '구름많음', '4': '흐림' };
function windDir16(deg: number): string {
const d = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서'];
return d[Math.round(((deg % 360) / 22.5)) % 16];
}
function formatKmaHourly(hourly: Record<string, Record<string, string>>, days: string[]): string[] {
const nowKst = new Date(Date.now() + 9 * 3600 * 1000);
const today = nowKst.toISOString().slice(0, 10).replace(/-/g, '');
const nowHour = nowKst.getUTCHours();
const out: string[] = ['⏱ 시간별 예보 (3시간 간격, 기상청):'];
for (const day of days) {
const rows: string[] = [];
for (let h = 0; h < 24; h += 3) {
if (day === today && h < nowHour) continue;
const v = hourly[`${day}${String(h).padStart(2, '0')}`];
if (!v) continue;
const sky = v.PTY && v.PTY !== '0' ? (PTY_LABEL[v.PTY] ?? v.PTY) : (SKY_SHORT[v.SKY] ?? '');
const parts = [
v.TMP != null ? `${v.TMP}°C` : null,
v.REH != null ? `습도 ${v.REH}%` : null,
v.WSD != null ? `${windDir16(Number(v.VEC ?? 0))}풍 ${v.WSD}m/s` : null,
v.POP != null ? `강수확률 ${v.POP}%` : null,
sky || null,
v.SNO && v.SNO !== '적설없음' ? `적설 ${v.SNO}` : null,
].filter(Boolean);
rows.push(` ${day.slice(4, 6)}/${day.slice(6, 8)} ${String(h).padStart(2, '0')}시 ${parts.join(', ')}`);
}
out.push(...rows);
}
return out.length > 1 ? out : [];
}
// 단기예보 PCP(1시간 강수량) 문자열: "강수없음" / "1mm 미만" / "1.0mm" / "30.0~50.0mm" / "50.0mm 이상".
// 시간대별 목록과 하루 대략 합계(범위는 중간값, "1mm 미만"은 0.5)를 만든다. 합계는 추정치임을 밝힌다.
function pcpToMm(raw: string): number | null {
if (!raw || raw === '강수없음' || raw === '0') return 0;
if (raw.includes('미만')) return 0.5;
const nums = (raw.match(/\d+(?:\.\d+)?/g) || []).map(Number);
if (!nums.length) return null;
if (raw.includes('이상')) return nums[0];
if (nums.length >= 2) return (nums[0] + nums[1]) / 2;
return nums[0];
}
function summarizePcp(list?: Array<{ hour: string; raw: string }>): string[] | null {
if (!list || !list.length) return null;
const wet = list.filter(x => (pcpToMm(x.raw) ?? 0) > 0);
if (!wet.length) return [' 예상 강수량: 없음'];
const total = wet.reduce((a, x) => a + (pcpToMm(x.raw) ?? 0), 0);
const hours = wet.map(x => `${x.hour}시 ${x.raw.replace('강수없음', '0mm')}`).join(', ');
return [
` 예상 강수량(시간별): ${hours}`,
` 예상 강수량 합계: 약 ${Math.round(total * 10) / 10}mm (시간별 예보값 합산 추정, "1mm 미만"은 0.5mm로 계산)`,
];
}
const PTY_LABEL: Record<string, string> = { '0': '없음', '1': '비', '2': '비/눈', '3': '눈', '4': '소나기' };
const SKY_LABEL: Record<string, string> = { '1': '맑음', '3': '구름많음', '4': '흐림' };
// ── OpenWeather helpers ───────────────────────────────────────────────────────
async function owFetch(endpoint: string, params: Record<string, string>): Promise<any> {
const apiKey = getApiKey();
if (!apiKey) throw new Error('OpenWeather API key not configured (set openweather.api_key in .smallclaw/config.json)');
const p = new URLSearchParams({ ...params, appid: apiKey });
const res = await fetch(`${OW_BASE}/${endpoint}?${p}`, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) {
const body = await res.text().catch(() => '');
const msg = body ? JSON.parse(body)?.message || body : res.statusText;
throw new Error(`OpenWeather API error ${res.status}: ${msg}`);
}
return res.json();
}
// Geocode city via lookup table → Open-Meteo geocoding → OpenWeather
async function owGeocode(location: string): Promise<{ lat: number; lon: number; name: string }> {
const coords = parseCoords(location);
if (coords) return { lat: coords[0], lon: coords[1], name: location };
// Try internal table + Open-Meteo first (handles Korean city names)
const geo = await geocodeCity(location);
if (geo) return { lat: geo.lat, lon: geo.lon, name: geo.displayName };
// Fallback: OpenWeather geocoding (works for English names)
const data: any = await owFetch('weather', { q: location });
return { lat: data.coord.lat, lon: data.coord.lon, name: `${data.name}, ${data.sys?.country || ''}` };
}
// ── Format helpers ────────────────────────────────────────────────────────────
function formatCurrent(data: any, units: string): string {
const unitSymbol = units === 'imperial' ? '°F' : '°C';
const speedUnit = units === 'imperial' ? 'mph' : 'm/s';
const w = data.weather?.[0] || {};
const m = data.main || {};
const wind = data.wind || {};
const loc = `${data.name}${data.sys?.country ? ', ' + data.sys.country : ''}`;
const dt = new Date((data.dt + (data.timezone || 0)) * 1000).toUTCString().replace(' GMT', '');
return [
`Weather: ${loc}`,
`Time: ${dt}`,
``,
`${w.main || ''} — ${w.description || ''}`,
`Temperature: ${m.temp}${unitSymbol} (feels like ${m.feels_like}${unitSymbol})`,
`Min/Max: ${m.temp_min}${unitSymbol} / ${m.temp_max}${unitSymbol}`,
`Humidity: ${m.humidity}%`,
`Pressure: ${m.pressure} hPa`,
wind.speed != null ? `Wind: ${wind.speed} ${speedUnit} ${windDirection(wind.deg ?? 0)} (gusts ${wind.gust ?? wind.speed} ${speedUnit})` : '',
data.visibility != null ? `Visibility: ${(data.visibility / 1000).toFixed(1)} km` : '',
data.clouds?.all != null ? `Cloudiness: ${data.clouds.all}%` : '',
data.rain?.['1h'] != null ? `Rain (1h): ${data.rain['1h']} mm` : '',
data.snow?.['1h'] != null ? `Snow (1h): ${data.snow['1h']} mm` : '',
].filter(Boolean).join('\n');
}
function formatForecast(data: any, units: string): string {
const unitSymbol = units === 'imperial' ? '°F' : '°C';
const city = `${data.city?.name || ''}${data.city?.country ? ', ' + data.city.country : ''}`;
const list: any[] = data.list || [];
const tzOffset = data.city?.timezone || 0;
const byDay: Record<string, any[]> = {};
for (const item of list) {
const localMs = (item.dt + tzOffset) * 1000;
const day = new Date(localMs).toISOString().slice(0, 10);
(byDay[day] ||= []).push(item);
}
const dayLines = Object.entries(byDay).slice(0, 5).map(([day, items]) => {
const temps = items.map((i) => i.main?.temp).filter((t) => t != null);
const min = Math.min(...temps).toFixed(1);
const max = Math.max(...temps).toFixed(1);
const desc = items[Math.floor(items.length / 2)]?.weather?.[0]?.description || '';
const rain = items.reduce((s, i) => s + (i.rain?.['3h'] || 0), 0);
const rainStr = rain > 0 ? ` | Rain: ${rain.toFixed(1)} mm` : '';
return ` ${day} ${min}–${max}${unitSymbol} ${desc}${rainStr}`;
});
return [`5-day Forecast: ${city}`, '', ...dayLines].join('\n');
}
// ── weather_search ────────────────────────────────────────────────────────────
// OpenWeather's `q` param disambiguates same-named cities by ISO-3166 country CODE
// ("Rome,IT"), not by full country name — "Rome, Italy" silently resolves to whichever
// "Rome" ranks first in its index (observed: Rome, Georgia, US instead of Rome, Italy).
// The tool schema already documents the "City,CountryCode" format, but models often write
// the full country name anyway — normalize the common ones rather than trust every caller
// to follow the format, and verify the response actually landed in the right country.
// (COUNTRY_NAME_TO_ISO / parseExplicitCountry live near geocodeCity() above, shared by both paths.)
// Returns the OpenWeather `q` string to send plus the ISO country code we expect back
// (undefined if we couldn't determine one — no mismatch check in that case).
function normalizeLocationForOpenWeather(location: string): { query: string; expectedCountry?: string } {
const { city, countryCode } = parseExplicitCountry(location);
if (!countryCode) return { query: location };
return { query: `${city},${countryCode}`, expectedCountry: countryCode };
}
export const weatherSearchTool = {
name: 'weather_search',
description: 'Get current weather or 5-day forecast for any city or coordinates using OpenWeather API. Returns temperature, humidity, wind, conditions, and more.',
schema: {
location: 'City name (e.g. "Seoul"), "City,CountryCode" (e.g. "London,GB"), or "lat,lon" coordinates',
type: '"current" (default) for real-time weather, or "forecast" for 5-day / 3-hour forecast',
units: '"metric" (°C, default), "imperial" (°F), or "standard" (Kelvin)',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name, "City,CountryCode", or "lat,lon"' },
type: { type: 'string', description: '"current" or "forecast"' },
units: { type: 'string', description: '"metric" (default), "imperial", or "standard"' },
},
required: ['location'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
const type = args?.type === 'forecast' ? 'forecast' : 'current';
const units = ['metric', 'imperial', 'standard'].includes(args?.units) ? args.units : 'metric';
if (!location) return { success: false, error: 'location is required' };
const coordMatch = location.match(/^(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)$/);
const normalized = coordMatch ? null : normalizeLocationForOpenWeather(location);
let locationParams: Record<string, string> = coordMatch
? { lat: coordMatch[1], lon: coordMatch[2] }
: { q: normalized!.query };
// Bare city name, no explicit country (e.g. "Rome") — OpenWeather's own name index
// can rank a small same-named US town above the internationally-known city, and with
// no expectedCountry the mismatch check below never fires. Cross-check via Open-Meteo's
// geocoder (population-ranked, see geocodeCity()) and query OpenWeather by lat/lon
// instead, which sidesteps the name ambiguity entirely.
if (!coordMatch && !normalized!.expectedCountry) {
const geo = await geocodeCity(location);
if (geo) locationParams = { lat: String(geo.lat), lon: String(geo.lon) };
}
try {
if (type === 'forecast') {
const data = await owFetch('forecast', { ...locationParams, units, cnt: '40' });
const gotCountry = String(data.city?.country || '').toUpperCase();
if (normalized?.expectedCountry && gotCountry && gotCountry !== normalized.expectedCountry) {
return { success: false, error: `Ambiguous city name: "${location}" resolved to ${data.city?.name}, ${gotCountry} instead of ${normalized.expectedCountry}. Retry with "City,${normalized.expectedCountry}" — if that still doesn't land in the right country, try a nearby larger city or include a state/region qualifier.` };
}
return { success: true, stdout: formatForecast(data, units), data: { location, type, units, raw: data } };
} else {
const data = await owFetch('weather', { ...locationParams, units });
const gotCountry = String(data.sys?.country || '').toUpperCase();
if (normalized?.expectedCountry && gotCountry && gotCountry !== normalized.expectedCountry) {
return { success: false, error: `Ambiguous city name: "${location}" resolved to ${data.name}, ${gotCountry} instead of ${normalized.expectedCountry}. Retry with "City,${normalized.expectedCountry}" — if that still doesn't land in the right country, try a nearby larger city or include a state/region qualifier.` };
}
return { success: true, stdout: formatCurrent(data, units), data: { location, type, units, raw: data } };
}
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_airpollution (OpenWeather Air Pollution API) ──────────────────────
const AQI_LABEL = ['', '좋음(Good)', '보통(Fair)', '중간(Moderate)', '나쁨(Poor)', '매우나쁨(Very Poor)'];
export const weatherAirPollutionTool = {
name: 'weather_airpollution',
description: 'Get real-time air quality data (AQI, PM2.5, PM10, O3, NO2, CO, SO2) for any city using OpenWeather Air Pollution API. Uses the same API key as weather_search.',
schema: {
location: 'City name (e.g. "Seoul") or "lat,lon" coordinates',
type: '"current" (default) or "forecast" (96-hour air quality forecast)',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name or "lat,lon"' },
type: { type: 'string', description: '"current" (default) or "forecast"' },
},
required: ['location'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
if (!location) return { success: false, error: 'location is required' };
const type = args?.type === 'forecast' ? 'air_pollution/forecast' : 'air_pollution';
try {
const { lat, lon, name } = await owGeocode(location);
const data = await owFetch(type, { lat: String(lat), lon: String(lon) });
const items: any[] = data.list || [];
if (!items.length) return { success: false, error: 'No air pollution data available' };
if (args?.type === 'forecast') {
// Show next 24h (8 entries × 3h)
const lines = [`Air Quality Forecast: ${name}`, ''];
lines.push('시각\t\t\tAQI\tPM2.5\tPM10\tO3\tNO2');
lines.push('─'.repeat(70));
for (const item of items.slice(0, 8)) {
const t = new Date(item.dt * 1000).toISOString().replace('T', ' ').slice(0, 16);
const c = item.components || {};
lines.push(`${t}\t${AQI_LABEL[item.main?.aqi]}\t${c.pm2_5?.toFixed(1)}μg\t${c.pm10?.toFixed(1)}μg\t${c.o3?.toFixed(1)}μg\t${c.no2?.toFixed(1)}μg`);
}
return { success: true, stdout: lines.join('\n'), data: { location: name, lat, lon } };
} else {
const item = items[0];
const aqi = item.main?.aqi;
const c = item.components || {};
const lines = [
`Air Quality: ${name}`,
`AQI: ${aqi}/5 — ${AQI_LABEL[aqi] || aqi}`,
'',
`PM2.5: ${c.pm2_5?.toFixed(1) ?? 'N/A'} μg/m³ (나쁨 기준: 36μg↑)`,
`PM10: ${c.pm10?.toFixed(1) ?? 'N/A'} μg/m³ (나쁨 기준: 81μg↑)`,
`O3: ${c.o3?.toFixed(1) ?? 'N/A'} μg/m³`,
`NO2: ${c.no2?.toFixed(1) ?? 'N/A'} μg/m³`,
`SO2: ${c.so2?.toFixed(1) ?? 'N/A'} μg/m³`,
`CO: ${c.co?.toFixed(1) ?? 'N/A'} μg/m³`,
`NH3: ${c.nh3?.toFixed(1) ?? 'N/A'} μg/m³`,
];
return { success: true, stdout: lines.join('\n'), data: { location: name, lat, lon, aqi, components: c } };
}
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_openmeteo (Open-Meteo, free, no API key) ─────────────────────────
const WMO_CODES: Record<number, string> = {
0: '맑음', 1: '대체로 맑음', 2: '부분 흐림', 3: '흐림',
45: '안개', 48: '안개(서리)',
51: '이슬비(약)', 53: '이슬비(중)', 55: '이슬비(강)',
61: '비(약)', 63: '비(중)', 65: '비(강)',
71: '눈(약)', 73: '눈(중)', 75: '눈(강)', 77: '싸락눈',
80: '소나기(약)', 81: '소나기(중)', 82: '소나기(강)',
85: '눈소나기(약)', 86: '눈소나기(강)',
95: '뇌우', 96: '뇌우+우박(약)', 99: '뇌우+우박(강)',
};
// 2026-10-14: 한국 좌표의 Open-Meteo 예보에 기상청 중기예보(4~10일, 공식)를 덧붙인다. 같은 "이번 주"
// 질문에 kma 경로와 openmeteo 경로가 다른 강수확률을 내던 문제(10/18: 78% vs 오전40·오후60%)를
// 모델의 도구 선택에 맡기지 않고 여기서 맞춘다. 일별 구간이 4일 이상 나갈 때만 붙이고, 실패하면
// 아무것도 붙이지 않는다(기존 출력 그대로).
async function withKmaMidTerm(text: string, lat: number, lon: number, days: number, hours: number): Promise<string> {
try {
if (days < 5 && hours < 96) return text;
if (!pickMidRegion(lat, lon)) return text;
const key = getKmaApiKey();
if (!key) return text;
const kst = new Date(Date.now() + 9 * 3600_000);
kst.setUTCDate(kst.getUTCDate() + 3);
const lastCovered = `${kst.getUTCFullYear()}${String(kst.getUTCMonth() + 1).padStart(2, '0')}${String(kst.getUTCDate()).padStart(2, '0')}`;
const lines = await fetchMidTermLines(key, lat, lon, lastCovered);
if (!lines) return text;
return `${text}\n\n※ 위 [일별]의 4일 이후 값은 Open-Meteo 모델값이다. 한국 지역은 아래 기상청 공식 중기예보를 우선해 답할 것.\n${lines.join('\n')}`;
} catch {
return text;
}
}
// 국내 위치는 weather_kma가 맡는다(관측망이 촘촘하고 4~10일 중기예보까지 같이 준다). Open-Meteo는 해외용이다.
// 예외는 10일을 넘는 구간(days>10 또는 hours>240) — 기상청 예보가 닿지 않는 장기 구간뿐이다.
// 2026-10-19 사용자 결정: "weather_openmeteo는 국내 검색에서 제외, 장기예보 외에는".
const KOREA_BBOX = { latMin: 33.0, latMax: 38.7, lonMin: 124.5, lonMax: 131.9 };
export function isKoreanLatLon(lat: number, lon: number): boolean {
return lat >= KOREA_BBOX.latMin && lat <= KOREA_BBOX.latMax && lon >= KOREA_BBOX.lonMin && lon <= KOREA_BBOX.lonMax;
}
export function openMeteoKoreaBlockMessage(place: string): string {
return `${place}은(는) 국내 지역입니다. 국내 날씨·예보(3일 단기 + 4~10일 중기)는 weather_kma로 조회하세요 — 이 도구(weather_openmeteo)는 해외 지역과 10일을 넘는 장기 예보(days>10)에만 씁니다.`;
}
export const weatherOpenMeteoTool = {
name: 'weather_openmeteo',
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: 'A SINGLE city name (Korean or English) or "lat,lon" coordinates. One place per call — to compare several cities, call this tool once per city; passing "London, Berlin, Paris" resolves to nothing and fails.',
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, precipitation_probability_max, sunrise, …) are routed to the daily block automatically; everything else is treated as hourly. precipitation (mm) is NOT a probability — for "will it rain / rain chance" questions you must include precipitation_probability (hourly) or precipitation_probability_max (daily), or the answer has no probability data at all. Default: temperature_2m,precipitation,precipitation_probability,wind_speed_10m,wind_direction_10m,relative_humidity_2m,uv_index,weather_code',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'A SINGLE city name or "lat,lon". One place per call — never a comma-separated list of cities.' },
hours: { type: 'number', description: 'Hours ahead (1–384, default 24)' },
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,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
if (!location) return { success: false, error: 'location is required' };
const hours = Math.min(Math.max(1, Math.round(Number(args?.hours) || 24)), 384);
// 2026-10-14 실사고: "이번 주 구미 날씨" → 모델이 hours:168만 주고 days는 안 줘서 일별 구간이 3일로
// 끊겼다(시간별은 48시간 표시 제한). days를 안 주면 hours가 덮는 일수만큼 일별을 요청한다.
const requestedHours = Number(args?.hours) || 0;
const defaultDays = Math.max(3, Math.ceil(requestedHours / 24));
const days = Math.min(Math.max(1, Math.round(Number(args?.days) || defaultDays)), 16);
// 기본 변수에 일별 요약(최고·최저·강수확률·강수량)을 포함한다. 시간별만 있으면 3일 밖의 날은 아예 안 나온다.
const vars = String(args?.variables || 'temperature_2m,precipitation,precipitation_probability,wind_speed_10m,wind_direction_10m,relative_humidity_2m,uv_index,weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,precipitation_sum');
// 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);
const fetchOneCity = async (lat: number, lon: number, displayName: string) => {
const params = new URLSearchParams({
latitude: String(lat),
longitude: String(lon),
// '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 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' || k === 'wind_direction_10m_dominant') return `${windDirectionKo(v)}(${v}°)`;
return String(v);
},
});
return { text, lat, lon, raw: data };
};
try {
const longRange = days > 10 || hours > 240;
const coords = parseCoords(location);
if (coords) {
const [lat, lon] = coords;
if (!longRange && isKoreanLatLon(lat, lon)) return { success: false, error: openMeteoKoreaBlockMessage(location) };
const { text, raw } = await fetchOneCity(lat, lon, location);
return { success: true, stdout: await withKmaMidTerm(text, lat, lon, days, hours), data: { location, lat, lon, raw } };
}
const geo = await geocodeCity(location);
if (geo) {
if (!longRange && isKoreanLatLon(geo.lat, geo.lon)) return { success: false, error: openMeteoKoreaBlockMessage(geo.displayName || location) };
const { text, raw } = await fetchOneCity(geo.lat, geo.lon, geo.displayName);
return { success: true, stdout: await withKmaMidTerm(text, geo.lat, geo.lon, days, hours), data: { location: geo.displayName, lat: geo.lat, lon: geo.lon, raw } };
}
// 2026-08-10: the error path below already tells the model exactly how to retry
// ("call once per city"), but a real incident showed that guidance only gets partially
// followed — asked for 5 cities, it retried 2 and silently dropped 3 (no fabrication,
// just incomplete: it said "let me know if you need the others" instead of finishing the
// list it had already committed to). Rather than trust N follow-up calls to all happen,
// fetch every city here and return one combined report — there is no follow-up to skip.
const cities = await looksLikeMultipleLocations(location);
if (!cities) return await locationNotFoundError(location, 'weather_openmeteo');
const settled = await Promise.allSettled(cities.map(async (c) => {
const g = await geocodeCity(c);
if (!g) throw new Error(`${c}: 위치를 찾을 수 없음`);
if (!longRange && isKoreanLatLon(g.lat, g.lon)) throw new Error(`${c}: 국내 지역은 weather_kma로 조회`);
const { text } = await fetchOneCity(g.lat, g.lon, g.displayName);
return { city: c, text };
}));
const ok = settled.filter((r): r is PromiseFulfilledResult<{ city: string; text: string }> => r.status === 'fulfilled').map(r => r.value);
const failed = settled
.map((r, i) => (r.status === 'rejected' ? cities[i] : null))
.filter((c): c is string => c !== null);
if (!ok.length) return { success: false, error: `${cities.length}개 도시 전부 조회 실패: ${cities.join(', ')}` };
const combined = ok.map(r => r.text).join('\n\n' + '─'.repeat(40) + '\n\n')
+ (failed.length ? `\n\n(다음 도시는 조회 실패: ${failed.join(', ')})` : '');
return { success: true, stdout: combined, data: { locations: ok.map(r => r.city), failed } };
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_kma (기상청 공식 API) ─────────────────────────────────────────────
async function kmaFetch(endpoint: string, params: Record<string, string>): Promise<any[]> {
const apiKey = getKmaApiKey();
if (!apiKey) {
throw new Error(
'기상청 API 키가 없습니다. ' +
'공공데이터포털(data.go.kr)에서 "기상청_단기예보 ((구)동네예보) 조회서비스" API를 신청한 후 ' +
'vault에 kma.api_key를 등록하세요.'
);
}
const p = new URLSearchParams({ serviceKey: apiKey, dataType: 'JSON', numOfRows: '1000', pageNo: '1', ...params });
const res = await fetch(`${KMA_BASE}/${endpoint}?${p}`, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) throw new Error(`기상청 API 오류 ${res.status}`);
const json: any = await res.json();
const header = json?.response?.header;
if (header?.resultCode !== '00') throw new Error(`기상청 API: ${header?.resultMsg || '알 수 없는 오류'} (${header?.resultCode})`);
return json?.response?.body?.items?.item || [];
}
// 2026-08-16: weather_kma only ever reported RN1 (the last hour), so "오늘 비 얼마나 왔어?"
// had no data behind it and the model correctly-but-uselessly said it couldn't answer.
// 초단기실황 accepts past base_times for the same day (verified against the live API), so the
// daily total is just a sum of the hourly observations — no new API approval needed.
//
// RN1 at base_time HH00 is the rain that fell during the hour ENDING at HH00. So "today
// 00:00 → now" is base_times 0100..HH00; base_time 0000 covers yesterday 23:00–24:00 and is
// deliberately excluded.
export function sumKmaHourlyRain(
hours: Array<{ hour: number; rn1: string | null | undefined }>,
): { mm: number; missing: number[] } {
let mm = 0;
const missing: number[] = [];
for (const { hour, rn1 } of hours) {
if (rn1 == null || rn1 === '') { missing.push(hour); continue; }
// 초단기실황 sends a bare number, but sibling KMA endpoints use "강수없음" for zero —
// strip to digits so either shape lands on a number rather than counting as a gap.
const n = parseFloat(String(rn1).replace(/[^0-9.]/g, ''));
if (Number.isFinite(n)) mm += n;
}
// Sum of one-decimal observations, so bare addition drifts (0.1+0.2 = 0.30000000000000004).
return { mm: Math.round(mm * 10) / 10, missing };
}
// 강수 사상(event) 판정 상수. 6시간은 기상청이 강수 계속시간을 끊을 때 쓰는 관례에 맞춘 것 —
// 장마철처럼 오다 말다 하는 비를 매번 새 사상으로 쪼개지 않으면서, 며칠 전 다른 비까지
// 끌어오지도 않는 선이다. 0.1mm는 관측 최소 단위라 그 미만은 "비가 온 시간"으로 안 친다.
const RAIN_EPISODE_GAP_HOURS = 6;
const RAIN_WET_HOUR_MM = 0.1;
// 마지막 시각부터 거꾸로 걸어서 이번 강수가 언제 시작됐는지 찾는다.
// 반환이 null이면 (a) 비가 아예 없었거나 (b) 이미 GAP_HOURS 이상 그친 = 진행 중이 아닌 경우다.
// (b)를 굳이 걸러내는 이유: 그친 지 한참인 비의 합계를 "누적"이라고 계속 띄우면
// 지금 오고 있는 비의 양으로 읽힌다.
export function findRainEpisode(
hours: Array<{ time: string; mm: number; wet?: boolean }>,
opts: { gapHours?: number; wetMm?: number } = {},
): { startTime: string; totalMm: number; wetHours: number; truncated: boolean } | null {
const gapHours = opts.gapHours ?? RAIN_EPISODE_GAP_HOURS;
const wetMm = opts.wetMm ?? RAIN_WET_HOUR_MM;
if (!hours.length) return null;
// `wet`을 명시로 받는 이유: ASOS는 무강수를 rn=""로, 미량 강수를 rn="0.0"으로 구분한다.
// 0.0mm지만 비는 온 시각이라 mm만 보면 소강으로 오판해서 사상이 끊긴다.
// 안 주면(Open-Meteo처럼 그 구분이 없는 소스) 종전대로 mm 임계로 판정한다.
const isWet = (i: number) => hours[i].wet ?? ((hours[i].mm ?? 0) >= wetMm);
let lastWet = -1;
for (let i = hours.length - 1; i >= 0; i--) {
if (isWet(i)) { lastWet = i; break; }
}
if (lastWet === -1) return null;
// 마지막 강수 이후 지금까지 그친 시간이 이미 사상을 끊을 만큼 길면 진행 중이 아니다.
if (hours.length - 1 - lastWet >= gapHours) return null;
let start = lastWet;
let dryRun = 0;
for (let i = lastWet - 1; i >= 0; i--) {
if (isWet(i)) { start = i; dryRun = 0; continue; }
if (++dryRun >= gapHours) break;
}
let totalMm = 0;
let wetHours = 0;
for (let i = start; i < hours.length; i++) {
totalMm += hours[i].mm ?? 0;
if (isWet(i)) wetHours++;
}
return {
startTime: hours[start].time,
totalMm: Math.round(totalMm * 10) / 10,
wetHours,
// 조회 창 첫 시각까지 끊기지 않고 닿았으면 그 이전은 안 본 것이라 합계가 하한이다.
truncated: start === 0,
};
}
// ASOS(종관기상관측) 지점 목록 — [지점번호, 지점명, 위도, 경도]. 97개.
//
// 출처는 기상청 API허브 `typ01/url/stn_inf.php?inf=SFC` (2026-08-16 수신). 응답이 EUC-KR이라
// UTF-8로 읽으면 지점명이 깨지고, 컬럼 순서가 LON→LAT이라 뒤집어 읽기 쉽다.
//
// 정적 표로 박아둔 건 의도적이다. 관측소 좌표는 거의 안 바뀌는데 런타임에 API허브를 타면
// 별도 인증키(data.go.kr 키와 다른 계정)에 매 요청이 묶인다. 갱신이 필요하면 위 URL을
// 다시 받아 이 표만 갈아끼우면 된다.
//
// 좌표를 지오코딩으로 만들려던 앞선 시도는 폐기됐다: 지오코더가 홍성·보령·밀양을 북한
// 동명 지역으로, 남원을 제주도로, 남해를 충청으로 돌려줬다. 공식 좌표와 대조해 전부 확인됨.
// (검증에 Open-Meteo 기온을 쓰려던 것도 실패했다 — 좌표가 정확한 서울조차 Δ3.1°C라
// 도시열섬·모델편차에 묻혀 판별자가 못 된다. ASOS 실측끼리 비교해야 갈린다.)
const ASOS_STATIONS: Array<[number, string, number, number]> = [
[90, '속초', 38.2508, 128.5647], [93, '북춘천', 37.9474, 127.7544], [95, '철원', 38.1479, 127.3042],
[98, '동두천', 37.9019, 127.0607], [99, '파주', 37.8859, 126.7665], [100, '대관령', 37.6771, 128.7183],
[101, '춘천', 37.9026, 127.7357], [102, '백령도', 37.9740, 124.7124], [104, '북강릉', 37.8046, 128.8553],
[105, '강릉', 37.7515, 128.8910], [106, '동해', 37.5071, 129.1243], [108, '서울', 37.5714, 126.9658],
[112, '인천', 37.4777, 126.6249], [114, '원주', 37.3375, 127.9466], [115, '울릉도', 37.4813, 130.8986],
[119, '수원', 37.2575, 126.9830], [121, '영월', 37.1813, 128.4574], [127, '충주', 36.9704, 127.9525],
[129, '서산', 36.7766, 126.4939], [130, '울진', 36.9918, 129.4128], [131, '청주', 36.6392, 127.4407],
[133, '대전', 36.3720, 127.3721], [135, '추풍령', 36.2203, 127.9946], [136, '안동', 36.5729, 128.7073],
[137, '상주', 36.4084, 128.1574], [138, '포항', 36.0320, 129.3800], [140, '군산', 36.0053, 126.7613],
[143, '대구', 35.8780, 128.6530], [146, '전주', 35.8409, 127.1172], [152, '울산', 35.5824, 129.3347],
[155, '창원', 35.1702, 128.5728], [156, '광주', 35.1729, 126.8916], [159, '부산', 35.1047, 129.0320],
[162, '통영', 34.8454, 128.4356], [165, '목포', 34.8173, 126.3815], [168, '여수', 34.7393, 127.7406],
[169, '흑산도', 34.6872, 125.4510], [170, '완도', 34.3959, 126.7018], [172, '고창', 35.3482, 126.5990],
[174, '순천', 35.0204, 127.3694], [177, '홍성', 36.6576, 126.6877], [181, '서청주', 36.6399, 127.3846],
[184, '제주', 33.5141, 126.5297], [185, '고산', 33.2938, 126.1628], [188, '성산', 33.3868, 126.8802],
[189, '서귀포', 33.2462, 126.5653], [192, '진주', 35.1638, 128.0400], [201, '강화', 37.7074, 126.4463],
[202, '양평', 37.4886, 127.4945], [203, '이천', 37.2640, 127.4842], [211, '인제', 38.0599, 128.1681],
[212, '홍천', 37.6836, 127.8804], [216, '태백', 37.1704, 128.9893], [217, '정선군', 37.3807, 128.6731],
[221, '제천', 37.1593, 128.1943], [226, '보은', 36.4876, 127.7341], [232, '천안', 36.7622, 127.2928],
[235, '보령', 36.3272, 126.5574], [236, '부여', 36.2724, 126.9208], [238, '금산', 36.1056, 127.4818],
[239, '세종', 36.4852, 127.2444], [243, '부안', 35.7296, 126.7166], [244, '임실', 35.6120, 127.2856],
[245, '정읍', 35.5633, 126.8390], [247, '남원', 35.4213, 127.3965], [248, '장수', 35.6570, 127.5203],
[251, '고창군', 35.4235, 126.6923], [252, '영광군', 35.2837, 126.4778], [253, '김해시', 35.2298, 128.8907],
[254, '순창군', 35.3713, 127.1286], [255, '북창원', 35.2266, 128.6726], [257, '양산시', 35.3074, 129.0201],
[258, '보성군', 34.7634, 127.2123], [259, '강진군', 34.6446, 126.7841], [260, '장흥', 34.6889, 126.9195],
[261, '해남', 34.5538, 126.5691], [262, '고흥', 34.6183, 127.2757], [263, '의령군', 35.3226, 128.2881],
[264, '함양군', 35.5114, 127.7454], [266, '광양시', 34.9434, 127.6914], [268, '진도군', 34.4730, 126.2585],
[271, '봉화', 36.9436, 128.9145], [272, '영주', 36.8718, 128.5169], [273, '문경', 36.6273, 128.1488],
[276, '청송군', 36.4351, 129.0401], [277, '영덕', 36.5334, 129.4093], [278, '의성', 36.3561, 128.6886],
[279, '구미', 36.1305, 128.3205], [281, '영천', 35.9774, 128.9514], [283, '경주시', 35.8175, 129.2012],
[284, '거창', 35.6674, 127.9099], [285, '합천', 35.5650, 128.1699], [288, '밀양', 35.4915, 128.7441],
[289, '산청', 35.4130, 127.8791], [294, '거제', 34.8882, 128.6046], [295, '남해', 34.8166, 127.9264],
[296, '북부산', 35.2178, 128.9602],
];
// "부산광역시" → "부산", "김해시" → "김해". 지점명 쪽도 같은 함수를 태워서 양쪽을 맞춘다.
const stripAdmin = (s: string) =>
s.trim().replace(/\s+/g, '').replace(/(특별자치도|특별자치시|특별시|광역시)$/, '').replace(/(시|군|구)$/, '');
// 지점명에는 방위 접두사가 붙은 게 있다(북창원, 서청주, 북부산…). 사용자는 "창원"이라고
// 쓰므로 접두사를 벗겨서도 비교하되, 정확히 일치하는 지점이 있으면 그쪽을 먼저 쓴다.
export function findAsosStation(location: string): { id: number; name: string } | null {
const q = stripAdmin(location);
if (!q) return null;
const cand = ASOS_STATIONS.map(([id, name]) => ({ id, name, bare: stripAdmin(name) }));
const exact = cand.find(c => c.bare === q);
if (exact) return { id: exact.id, name: exact.name };
const deprefixed = cand.find(c => c.bare.replace(/^(북|서|남|동)/, '') === q);
if (deprefixed) return { id: deprefixed.id, name: deprefixed.name };
return null;
}
// 두 지점망(ASOS 97개 / AWS 745개)이 같은 계산을 쓰므로 하버사인을 한 번만 둔다.
function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number {
const toRad = (d: number) => d * Math.PI / 180;
const dLat = toRad(lat2 - lat1), dLon = toRad(lon2 - lon1);
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
return 6371 * 2 * Math.asin(Math.min(1, Math.sqrt(a)));
}
function nearestIn(
stations: Array<[number, string, number, number]>, lat: number, lon: number, maxKm: number,
): { id: number; name: string; km: number } | null {
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
let best: { id: number; name: string; km: number } | null = null;
for (const [id, name, sLat, sLon] of stations) {
const km = haversineKm(lat, lon, sLat, sLon);
if (!best || km < best.km) best = { id, name, km: Math.round(km * 10) / 10 };
}
return best && best.km <= maxKm ? best : null;
}
// AWS는 745개로 훨씬 촘촘해서 반경을 좁게 잡아도 대부분 걸린다. 20km면 웬만한 동네가
// 자기 관측소를 쓴다 — ASOS(40km)보다 좁힌 건 그만큼 대표성을 높게 요구할 수 있어서다.
export function nearestAwsStation(
lat: number, lon: number, maxKm = 20,
): { id: number; name: string; km: number } | null {
return nearestIn(AWS_STATIONS, lat, lon, maxKm);
}
// 이름으로 못 맞힌 위치(좌표 입력, ASOS 없는 소도시)를 위한 최근접 지점 선택.
// maxKm 밖이면 null — 멀리 있는 관측소를 조용히 빌려 쓰면 "관측값"이라는 라벨이 거짓말이 된다.
// 40km는 우리 ASOS 망(97개) 간격을 보고 잡은 값이고, 넘으면 Open-Meteo 추정으로 물러난다.
// 호출부가 거리를 같이 출력하므로 사용자가 대표성을 직접 판단할 수 있다.
export function nearestAsosStation(
lat: number, lon: number, maxKm = 40,
): { id: number; name: string; km: number } | null {
return nearestIn(ASOS_STATIONS, lat, lon, maxKm);
}
// ASOS 시간자료의 rn 인코딩: ""=무강수, "0.0"=미량(관측은 됐으나 0.05mm 미만), "1.0"=1.0mm.
// ""와 "0.0"을 같게 뭉개면 이슬비로 이어지던 비가 소강으로 잡혀 사상이 끊긴다.
export function normalizeAsosHour(tm: string, rn: string | null | undefined): { time: string; mm: number; wet: boolean } {
const time = String(tm).trim().replace(' ', 'T').slice(0, 16);
if (rn == null || String(rn).trim() === '') return { time, mm: 0, wet: false };
const mm = parseFloat(String(rn));
return { time, mm: Number.isFinite(mm) ? mm : 0, wet: true };
}
// AWS 매분자료 컬럼 순서. 헤더에 이름은 나오지만 CSV에는 안 붙어서 위치로 읽어야 하고,
// 한 칸 밀리면 기온을 강수량으로 읽는다(실제로 RN-12H를 RN-DAY로 착각해 한 번 틀렸다).
const AWS_COL = { TM: 0, STN: 1, TA: 8, RE: 9, RN15: 10, RN60: 11, RN12H: 12, RNDAY: 13, HM: 14 } as const;
// -50 이하는 "관측 없음/에러"를 뜻하는 센티널이다(-99.9로 온다). 0으로 읽으면
// 비가 안 온 것처럼 보이고, 그대로 더하면 합계가 음수로 망가진다.
export function awsNum(raw: string | undefined): number | null {
if (raw == null) return null;
const v = parseFloat(String(raw).trim());
return Number.isFinite(v) && v > -50 ? v : null;
}
// 한 지점의 오늘 매분자료(00:00~현재)를 한 번에 받는다. 781행 74KB, 0.8초 정도.
// RN-DAY가 그대로 일 누적이라 초단기실황을 시간별로 23번 부르던 걸 대체한다.
// 시간별 값도 같이 뽑아 사상 판정에 넘긴다 — RE(강수감지)는 전 지점 null이라 못 쓰고,
// 매분 RN-60m이 그 시각까지의 60분 누적이라 정시 값을 그 시간의 강수량으로 쓴다.
export async function parseAwsDay(csv: string): Promise<{
rnDay: number | null; ta: number | null; hm: number | null; tm: string | null;
hours: Array<{ time: string; mm: number; wet: boolean }>;
}> {
const rows = csv.split('\n').filter(l => l.trim() && !l.startsWith('#')).map(l => l.split(',').map(s => s.trim()));
if (!rows.length) return { rnDay: null, ta: null, hm: null, tm: null, hours: [] };
// 맨 끝 행은 "지금 이 분"이라 아직 안 채워진 경우가 많다 — 전 컬럼이 -99.9로 온다.
// 그걸 그대로 쓰면 관측이 멀쩡한데도 전부 null이 되어 폴백으로 새버린다.
// 뒤에서부터 RN-DAY가 실제 값인 첫 행을 쓴다.
const last = [...rows].reverse().find(r => awsNum(r[AWS_COL.RNDAY]) != null) ?? rows[rows.length - 1];
const hours: Array<{ time: string; mm: number; wet: boolean }> = [];
for (const r of rows) {
const tm = r[AWS_COL.TM];
if (!/^\d{12}$/.test(tm) || tm.slice(10) !== '00') continue; // 정시만
const rn60 = awsNum(r[AWS_COL.RN60]);
if (rn60 == null) continue;
const iso = `${tm.slice(0,4)}-${tm.slice(4,6)}-${tm.slice(6,8)}T${tm.slice(8,10)}:00`;
hours.push({ time: iso, mm: rn60, wet: rn60 >= RAIN_WET_HOUR_MM });
}
const rnDay = awsNum(last[AWS_COL.RNDAY]);
const tm = /^\d{12}$/.test(last[AWS_COL.TM]) ? last[AWS_COL.TM] : null;
// 정시 RN-60m만 더하면 마지막 정시 이후의 자투리(예: 13:00~13:27)가 빠진다. 그대로 두면
// "오늘 누적"(RN-DAY)이 "이번 강수 누적"(시간 합)보다 커지는 모순이 화면에 그대로 뜬다 —
// 실제로 부산에서 27분 사이 4mm가 빠져 23.6 vs 19.6으로 갈렸다.
// 차액을 현재 시각의 한 칸으로 넣어 시간 배열의 합이 RN-DAY와 맞게 만든다.
if (rnDay != null && tm) {
const summed = hours.reduce((s, h) => s + h.mm, 0);
const rest = Math.round((rnDay - summed) * 10) / 10;
if (rest > 0) {
hours.push({
time: `${tm.slice(0,4)}-${tm.slice(4,6)}-${tm.slice(6,8)}T${tm.slice(8,10)}:${tm.slice(10,12)}`,
mm: rest,
wet: rest >= RAIN_WET_HOUR_MM,
});
}
}
return { rnDay, ta: awsNum(last[AWS_COL.TA]), hm: awsNum(last[AWS_COL.HM]), tm, hours };
}
async function fetchAwsToday(stnId: number, todayKst: string) {
const now = new Date(Date.now() + 9 * 3600 * 1000);
const tm2 = todayKst + String(now.getUTCHours()).padStart(2, '0') + String(now.getUTCMinutes()).padStart(2, '0');
const csv = await apiHubFetch(
`typ01/cgi-bin/url/nph-aws2_min?tm1=${todayKst}0000&tm2=${tm2}&stn=${stnId}&disp=1&help=0`);
return parseAwsDay(csv);
}
// 과거 날짜의 하루 요약. 2026-08-16에 붙였다 — "어제 제주 비 얼마나 왔어"를 물었을 때
// 도구에 과거 조회가 아예 없어서 모델이 web_search로 새고, 기상청 도움말 페이지만 긁어와
// "정확한 수치를 찾지 못했다"고 답한 실사례가 있었다. 일자료는 한 번의 호출로 끝난다.
//
// 기간 제약: ASOS 일자료는 "전날까지"만 제공한다(오늘을 넣으면 resultCode 99).
// 오늘치는 type="current"의 AWS RN-DAY가 담당한다.
// 모델이 "어제"를 그대로 넘기는 일이 잦아서 상대어도 받는다. 기준은 KST — 서버가 UTC라
// new Date()로 날짜를 뽑으면 한국 시각 09시 이전에는 하루 어긋난다.
export function parseKstDate(input: string, now = new Date()): string | null {
const s = String(input || '').trim();
if (!s) return null;
const kst = new Date(now.getTime() + 9 * 3600 * 1000);
const shift = (days: number) =>
new Date(kst.getTime() - days * 86400 * 1000).toISOString().slice(0, 10).replace(/-/g, '');
if (/^(오늘|today)$/i.test(s)) return shift(0);
if (/^(어제|어저께|yesterday)$/i.test(s)) return shift(1);
if (/^(그제|그저께|엊그제)$/i.test(s)) return shift(2);
const rel = s.match(/^(\d+)\s*일\s*전$/);
if (rel) return shift(parseInt(rel[1], 10));
const iso = s.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);
if (iso) return `${iso[1]}${iso[2].padStart(2, '0')}${iso[3].padStart(2, '0')}`;
if (/^\d{8}$/.test(s)) return s;
// "8월 15일" / "08-15" — 연도가 없으면 올해로 본다.
const md = s.match(/^(\d{1,2})\s*월\s*(\d{1,2})\s*일?$/) || s.match(/^(\d{1,2})[-/.](\d{1,2})$/);
if (md) return `${kst.toISOString().slice(0, 4)}${md[1].padStart(2, '0')}${md[2].padStart(2, '0')}`;
return null;
}
export function parseAsosDaily(item: any): string[] {
const num = (v: any) => {
const s = String(v ?? '').trim();
return s === '' ? null : (Number.isFinite(parseFloat(s)) ? parseFloat(s) : null);
};
// sumRn의 빈 값은 결측이 아니라 **그날 비가 안 왔다**는 뜻이다. 시간자료 rn과 같은 규칙이고,
// 실제 데이터로도 확인된다(서울 8/10~8/13은 빈 값이고 그 기간 다른 소스에서도 무강수,
// 8/14는 "0.2"). 이걸 "관측값 없음"으로 내보내면 맑았던 날마다 모델이 "자료가 없다"고
// 답하게 되므로 0으로 말하되, 미량("0.0")과는 구분해서 표기한다.
const rn = num(item?.sumRn);
const lines = [
`📅 ${item?.tm} — ${item?.stnNm}`,
rn == null ? ' 강수량: 0 mm (강수 없음)'
: ` 강수량: ${rn} mm${rn === 0 ? ' (미량)' : ''}`,
];
const tmax = num(item?.maxTa), tmin = num(item?.minTa), tavg = num(item?.avgTa);
if (tmax != null || tmin != null) lines.push(` 기온: ${tmin ?? '?'}~${tmax ?? '?'}°C${tavg != null ? ` (평균 ${tavg})` : ''}`);
const rhm = num(item?.avgRhm); if (rhm != null) lines.push(` 평균습도: ${rhm}%`);
const ws = num(item?.maxInsWs); if (ws != null) lines.push(` 최대순간풍속: ${ws} m/s`);
const ss = num(item?.sumSsHr); if (ss != null) lines.push(` 일조시간: ${ss} h`);
const snow = num(item?.ddMefs); if (snow) lines.push(` 최심신적설: ${snow} cm`);
return lines;
}
const ASOS_DAILY_BASE = 'http://apis.data.go.kr/1360000/AsosDalyInfoService';
async function fetchAsosDaily(stnId: number, startDt: string, endDt: string): Promise<any[]> {
const apiKey = getKmaApiKey();
if (!apiKey) throw new Error('기상청 API 키가 없습니다.');
const p = new URLSearchParams({
serviceKey: apiKey, dataType: 'JSON', numOfRows: '100', pageNo: '1',
dataCd: 'ASOS', dateCd: 'DAY', stnIds: String(stnId), startDt, endDt,
});
const res = await fetch(`${ASOS_DAILY_BASE}/getWthrDataList?${p}`, { signal: AbortSignal.timeout(20_000) });
if (!res.ok) throw new Error(`기상청 일자료 오류 ${res.status}`);
const json: any = await res.json();
const code = json?.response?.header?.resultCode;
if (code !== '00') throw new Error(`기상청 일자료: ${json?.response?.header?.resultMsg || code}`);
return json?.response?.body?.items?.item || [];
}
// ── CCTV 기반 도로날씨 (안개) ───────────────────────────────────────────────
//
// 안개는 ASOS·AWS·Open-Meteo 어디에도 없는 값이라, 도로 CCTV 영상 분석 결과가 유일한 소스다.
// API허브 `typ01/url/cctv_ana_info.php`가 전국 도로 CCTV 지점별로 안개/비/눈 코드를 준다.
//
// 성격이 관측소와 다르다는 걸 감안해야 한다:
// - 지점이 **도로변**에만 있다(2026-08-21 기준 593곳). 가까운 지점이 없는 동네가 많다.
// - **영상 분석이라 주간에만 생산된다**(대략 06~19시). 야간에 값이 없는 건 고장이 아니다.
// - 자료가 **며칠에 걸쳐 뒤늦게 채워진다**. 08-15~17이 한동안 0행이다가 나중에 채워졌고,
// 08-14 행수도 57,247 → 67,937로 늘었다. 그래서 "지금 0행"으로 서비스 종료를 단정하면 안 된다.
const FOG_LABEL: Record<string, string> = { '00': '없음', '11': '약함', '12': '보통', '13': '짙음' };
// 같은 지점이 몇 분 간격으로 반복 보고되므로, 지점별 **가장 최근 행**만 남긴다.
export function pickLatestFogByStation(
rows: string[][],
): Array<{ tm: string; id: string; name: string; lat: number; lon: number; fog: string }> {
const best = new Map<string, { tm: string; id: string; name: string; lat: number; lon: number; fog: string }>();
for (const r of rows) {
if (r.length < 8) continue;
const [tm, id, name, latS, lonS] = r;
const fog = String(r[7] || '').trim();
const lat = parseFloat(latS), lon = parseFloat(lonS);
if (!/^\d{12}$/.test(tm) || !id || !Number.isFinite(lat) || !Number.isFinite(lon)) continue;
const prev = best.get(id);
if (!prev || tm > prev.tm) best.set(id, { tm, id, name: String(name || '').trim(), lat, lon, fog });
}
return [...best.values()];
}
// 안개가 잡힌 지점 중 가장 가까운 곳. maxKm 밖이면 null — 도로변 지점이라 성기게 깔려 있어서
// ASOS(40km)보다 넉넉히 잡되, 거리를 같이 돌려줘 호출부가 화면에 밝히게 한다.
export function nearestFogReport(
stations: Array<{ tm: string; name: string; lat: number; lon: number; fog: string }>,
lat: number, lon: number, maxKm = 30,
): { name: string; km: number; fog: string; tm: string } | null {
let best: { name: string; km: number; fog: string; tm: string } | null = null;
for (const s of stations) {
if (!FOG_LABEL[s.fog] || s.fog === '00') continue; // 안개 없는 지점은 후보에서 제외
const km = Math.round(haversineKm(lat, lon, s.lat, s.lon) * 10) / 10;
if (!best || km < best.km) best = { name: s.name, km, fog: s.fog, tm: s.tm };
}
return best && best.km <= maxKm ? best : null;
}
// 전국 한 벌을 받아 지점별 최신값만 남긴 것. 위치가 달라도 같은 응답을 쓰므로 캐시한다.
// 자료가 10분 간격으로 갱신되고 조회에 ~3초가 걸려서, 캐시가 없으면 날씨 질문마다
// 응답이 그만큼 느려진다(실측 7초 → 11초).
let _fogCache: { at: number; stations: ReturnType<typeof pickLatestFogByStation> } | null = null;
const FOG_CACHE_MS = 5 * 60 * 1000;
async function fetchRoadFog(lat: number, lon: number): Promise<string | null> {
try {
if (!_fogCache || Date.now() - _fogCache.at > FOG_CACHE_MS) {
const now = new Date(Date.now() + 9 * 3600 * 1000);
const f = (d: Date) => d.toISOString().slice(0, 13).replace(/[-T]/g, '') + d.toISOString().slice(14, 16);
// 30분 창이면 지점 커버리지는 그대로(584/593)면서 응답이 591KB → 87KB로 줄었다.
// 더 넓히면 이미 걷힌 안개를 현재처럼 보고하게 되기도 한다.
const tm1 = f(new Date(now.getTime() - 30 * 60 * 1000));
const csv = await apiHubFetch(`typ01/url/cctv_ana_info.php?tm1=${tm1}&tm2=${f(now)}&disp=0&help=0`);
const rows = csv.split('\n').filter(l => l.trim() && !l.startsWith('#')).map(l => l.split(',').map(x => x.trim()));
_fogCache = { at: Date.now(), stations: pickLatestFogByStation(rows) };
}
if (!_fogCache.stations.length) return null; // 야간이거나 아직 안 채워짐 — 정상
const hit = nearestFogReport(_fogCache.stations, lat, lon);
if (!hit) return null; // 근처에 안개 없음 → 아무 줄도 안 붙인다
return `도로 안개: ${FOG_LABEL[hit.fog]} (CCTV ${hit.name} 관측, ${hit.km}km · `
+ `${hit.tm.slice(8, 10)}:${hit.tm.slice(10, 12)} 기준)`;
} catch {
return null;
}
}
const ASOS_BASE = 'http://apis.data.go.kr/1360000/AsosHourlyInfoService';
async function asosFetch(params: Record<string, string>): Promise<any[]> {
const apiKey = getKmaApiKey();
if (!apiKey) return [];
const p = new URLSearchParams({ serviceKey: apiKey, dataType: 'JSON', numOfRows: '999', pageNo: '1', ...params });
const res = await fetch(`${ASOS_BASE}/getWthrDataList?${p}`, { signal: AbortSignal.timeout(20_000) });
if (!res.ok) throw new Error(`ASOS API 오류 ${res.status}`);
const json: any = await res.json();
if (json?.response?.header?.resultCode !== '00') {
throw new Error(`ASOS: ${json?.response?.header?.resultMsg || json?.OpenAPI_ServiceResponse?.cmmMsgHeader?.errMsg || '알 수 없는 오류'}`);
}
return json?.response?.body?.items?.item || [];
}
// 두 KMA 소스를 이어붙여 사상 누적을 관측값만으로 낸다. 창이 정확히 맞물린다:
// ASOS 시간자료는 "전날 자료까지"(오늘치는 resultCode 99), 초단기실황은 "최근 1일".
// 그래서 어제 이전은 ASOS, 오늘은 초단기실황으로 자정에서 딱 나눈다.
// 지점명을 못 맞히면(좌표 입력, ASOS 없는 소도시) null을 주고 호출부가 Open-Meteo로 물러난다.
async function fetchKmaRainEpisode(
stnId: number, todayKst: string, todayHours: Array<{ time: string; mm: number; wet: boolean }>,
): Promise<{ startTime: string; totalMm: number; wetHours: number; truncated: boolean } | null> {
try {
const d = (back: number) =>
new Date(Date.now() + 9 * 3600 * 1000 - back * 86400 * 1000).toISOString().slice(0, 10).replace(/-/g, '');
const items = await asosFetch({
dataCd: 'ASOS', dateCd: 'HR', stnIds: String(stnId),
startDt: d(7), startHh: '00', endDt: d(1), endHh: '23',
});
const past = items
.map((it: any) => normalizeAsosHour(it.tm, it.rn))
.filter(h => h.time.slice(0, 10) < `${todayKst.slice(0,4)}-${todayKst.slice(4,6)}-${todayKst.slice(6,8)}`)
.sort((a, b) => a.time.localeCompare(b.time));
if (!past.length) return null;
return findRainEpisode([...past, ...todayHours]);
} catch {
return null;
}
}
// 지점명을 못 맞힌 위치(좌표 입력 등)를 위한 폴백. 모델 추정이라 출력에 출처를 밝힌다.
// (2026-08-16 서울 실측 교차검증: 같은 구간 KMA 9.8mm vs Open-Meteo 10.3mm, 5% 이내)
async function fetchRainEpisode(
lat: number, lon: number,
): Promise<{ startTime: string; totalMm: number; wetHours: number; truncated: boolean } | null> {
try {
const p = new URLSearchParams({
latitude: String(lat), longitude: String(lon),
hourly: 'precipitation', past_days: '7', forecast_days: '1', timezone: 'Asia/Seoul',
});
const res = await fetch(`https://api.open-meteo.com/v1/forecast?${p}`, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) return null;
const data: any = await res.json();
const times: string[] = data?.hourly?.time || [];
const values: number[] = data?.hourly?.precipitation || [];
if (!times.length) return null;
// forecast_days=1이라 뒤쪽은 아직 안 온 예보다. 현재 시각까지만 남긴다 —
// 안 그러면 "예보된 비"가 누적에 섞여 이미 내린 양으로 보고된다.
const nowKstHour = new Date(Date.now() + 9 * 3600 * 1000).toISOString().slice(0, 13);
const hours = times
.map((t, i) => ({ time: t, mm: values[i] ?? 0 }))
.filter(h => h.time.slice(0, 13) <= nowKstHour);
return findRainEpisode(hours);
} catch {
return null;
}
}
async function fetchKmaTodayRain(
nx: number, ny: number, base_date: string, latestHour: number,
): Promise<{ mm: number; missing: number[]; throughHour: number; perHour: Array<{ time: string; mm: number; wet: boolean }> } | null> {
if (latestHour < 1) return null;
const hours = Array.from({ length: latestHour }, (_, i) => i + 1);
const results: Array<{ hour: number; rn1: string | null }> = [];
// data.go.kr throttles bursts, so walk in small batches rather than firing 23 at once.
for (let i = 0; i < hours.length; i += 6) {
const batch = hours.slice(i, i + 6);
const settled = await Promise.all(batch.map(async (hour) => {
try {
const items = await kmaFetch('getUltraSrtNcst', {
base_date, base_time: `${String(hour).padStart(2, '0')}00`, nx: String(nx), ny: String(ny),
});
const rn1 = items.find((it: any) => it.category === 'RN1')?.obsrValue;
return { hour, rn1: rn1 == null ? null : String(rn1) };
} catch {
// A single missing hour (NO_DATA, timeout) must not sink the whole total — it is
// reported as a gap so the caller can say the sum is partial instead of wrong.
return { hour, rn1: null };
}
}));
results.push(...settled);
}
const { mm, missing } = sumKmaHourlyRain(results);
if (missing.length === hours.length) return null;
// 시간별 값도 같이 돌려준다 — 사상 누적이 오늘 구간을 다시 받아오지 않게(호출 2배 방지).
// 초단기실황에는 ASOS의 미량("0.0") 구분이 없어서 wet은 mm 임계로 정한다.
const iso = `${base_date.slice(0,4)}-${base_date.slice(4,6)}-${base_date.slice(6,8)}`;
const perHour = results
.filter(r => r.rn1 != null && r.rn1 !== '')
.map(r => {
const v = parseFloat(String(r.rn1).replace(/[^0-9.]/g, ''));
const val = Number.isFinite(v) ? v : 0;
return { time: `${iso}T${String(r.hour).padStart(2, '0')}:00`, mm: val, wet: val >= RAIN_WET_HOUR_MM };
});
return { mm, missing, throughHour: latestHour, perHour };
}
// Pure formatting/filtering half of the KMA→Open-Meteo forecast merge — split out (2026-08-10)
// so it's unit-testable without a live API call. Given Open-Meteo's daily arrays and the last
// YYYYMMDD date KMA's own forecast already covered, returns the lines for whatever days remain
// beyond that, or null if there's nothing beyond what KMA already had.
export function formatDailySupplement(
dates: string[],
tmax: (number | null | undefined)[],
tmin: (number | null | undefined)[],
pop: (number | null | undefined)[],
lastCoveredYmd: string,
): string[] | null {
const lastCoveredIso = lastCoveredYmd
? `${lastCoveredYmd.slice(0, 4)}-${lastCoveredYmd.slice(4, 6)}-${lastCoveredYmd.slice(6, 8)}`
: '';
const lines: string[] = [];
for (let i = 0; i < dates.length; i++) {
if (lastCoveredIso && dates[i] <= lastCoveredIso) continue; // KMA already covered this day
lines.push(`📅 ${dates[i]}`);
lines.push(` 기온: ${tmin[i] ?? '?'}~${tmax[i] ?? '?'}°C`);
if (pop[i] != null) lines.push(` 강수확률: ${pop[i]}%`);
}
return lines.length ? ['── 3일 이후 예보 (Open-Meteo, 참고용) ──', ...lines] : null;
}
// weather_kma's forecast type is structurally capped at ~3-4 days (KMA's getVilageFcst just
// doesn't return more, and the caller loop above only reads the first 4 groups it does return).
// 2026-08-10 real incident: "이번 주말 날씨 어때?" (5 days out) hit this ceiling — the model
// called only weather_kma, saw the range fell short, and told the user to ask again closer to
// the weekend instead of calling weather_openmeteo (up to 16 days), even though weather_kma's
// own description already said to do exactly that for >3-day requests. Prose guidance
// repeatedly failed to change this model's behavior today (see news_search's git history for
// the same pattern with different symptoms), so this fetches the extension itself and merges
// it into one answer — no second tool call for the model to remember or skip.
// Best-effort: any failure here (network, malformed response) just means no supplement — never
// breaks the KMA forecast this is attached to.
async function fetchOpenMeteoDailySupplement(lat: number, lon: number, lastCoveredYmd: string): Promise<string[] | null> {
try {
const params = new URLSearchParams({
latitude: String(lat),
longitude: String(lon),
timezone: 'auto',
daily: 'temperature_2m_max,temperature_2m_min,precipitation_probability_max',
forecast_days: '7',
});
const res = await fetch(`https://api.open-meteo.com/v1/forecast?${params}`, { signal: AbortSignal.timeout(10_000) });
if (!res.ok) return null;
const data: any = await res.json();
return formatDailySupplement(
data.daily?.time || [],
data.daily?.temperature_2m_max || [],
data.daily?.temperature_2m_min || [],
data.daily?.precipitation_probability_max || [],
lastCoveredYmd,
);
} catch {
return null;
}
}
export const weatherKmaTool = {
name: 'weather_kma',
description: '기상청 공식 API로 한국 날씨 조회. 초단기실황(현재 기온·강수·바람·습도)에는 1시간 강수량과 함께 **오늘 00시부터 현재까지의 누적 강수량**(시간별 실측 합산)이 포함되므로, "오늘 비 얼마나 왔어" 같은 일 누적 질문도 이 도구 한 번으로 답할 수 있다. 비가 어제 이전부터 이어지고 있으면 **"이번 강수 누적"**(사상 시작 시각부터의 합계)도 함께 나오므로 "이번 비 얼마나 왔어"도 답할 수 있다 — 이 값만 Open-Meteo 추정이고 나머지는 기상청 실측이라, 답할 때 두 숫자를 섞지 말 것. **지난 날짜의 강수량·기온을 물으면 type="past"에 date를 넣어 호출할 것**("어제 비 얼마나 왔어", "8월 15일 제주 강수량" 등) — 관측 일자료가 바로 나오므로 web_search로 돌아가지 말 것. 기간은 endDate로 준다. 그리고 단기예보(기상청 단기 3일 + 기상청 중기예보 4~10일차, 중기 조회 실패 시 Open-Meteo 4~7일차)를 제공. type="forecast"에는 날짜별 요약 외에 **시간별 예상 강수량(mm)과 합계, 3시간 간격 기온·습도·풍속·강수확률**이 포함되므로 "비 얼마나 와?", "내일 아침 몇 도야?", "오후에 바람 세?"도 이 도구 한 번으로 답할 것(기상청이 수치를 안 준다고 답하지 말 것). type="current"에는 **앞으로 6시간 초단기예보**("한 시간 뒤 비 와?")가 붙는다. 한국 내 위치에 가장 정확한 기상 데이터. type="forecast"는 이번 주말처럼 3일을 넘는 날짜도 한 번의 호출로 답변 가능(참고용 보완 데이터 자동 포함). API 키(data.go.kr) 필요.',
schema: {
location: '한국 도시명 (예: "서울", "부산") 또는 "위도,경도" 형식',
type: '"current" (초단기실황, 기본값) | "forecast" (단기예보) | "past" (과거 관측)',
date: 'type="past"일 때 조회할 날짜. "어제", "2026-08-15", "8월 15일" 등',
endDate: 'type="past"에서 기간 조회 시 마지막 날짜 (생략하면 date 하루만)',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: '한국 도시명 또는 "lat,lon"' },
type: { type: 'string', description: '"current" | "forecast" | "past"' },
date: { type: 'string', description: '과거 날짜 ("어제", "2026-08-15", "8월 15일")' },
endDate: { type: 'string', description: '기간 조회의 마지막 날짜' },
},
required: ['location'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
if (!location) return { success: false, error: 'location이 필요합니다' };
// date만 주고 type을 빠뜨리는 호출이 흔해서, date가 있으면 past로 본다.
const type = args?.type === 'forecast' ? 'forecast'
: (args?.type === 'past' || args?.date) ? 'past'
: 'current';
try {
let lat: number, lon: number, displayName: string;
const coords = parseCoords(location);
if (coords) {
[lat, lon] = coords;
displayName = location;
} else {
const geo = await geocodeCity(location);
if (!geo) return await locationNotFoundError(location, 'weather_kma');
({ lat, lon, displayName } = geo);
}
const { nx, ny } = getKmaGrid(location, lat, lon);
if (type === 'past') {
const start = parseKstDate(String(args?.date || '어제'));
if (!start) return { success: false, error: `날짜를 해석할 수 없습니다: ${args?.date}. "어제" 또는 "2026-08-15" 형식으로 주세요.` };
const end = args?.endDate ? parseKstDate(String(args.endDate)) : start;
if (!end) return { success: false, error: `endDate를 해석할 수 없습니다: ${args.endDate}` };
const todayKst = new Date(Date.now() + 9 * 3600 * 1000).toISOString().slice(0, 10).replace(/-/g, '');
if (start >= todayKst) {
// 일자료는 전날까지다. 오늘을 넣으면 resultCode 99가 나므로 미리 갈라준다 —
// 안 그러면 모델이 "조회 실패"로 읽고 web_search로 새버린다(실제로 겪은 경로).
return { success: false, error: `${start.slice(0,4)}-${start.slice(4,6)}-${start.slice(6,8)}은 아직 일자료가 없습니다(전날까지 제공). 오늘 값은 type="current"로 조회하세요.` };
}
const station = findAsosStation(location) ?? findAsosStation(displayName) ?? nearestAsosStation(lat, lon);
if (!station) return { success: false, error: `${displayName} 근처 40km 안에 ASOS 관측소가 없어 과거 관측을 조회할 수 없습니다.` };
const items = await fetchAsosDaily(station.id, start, end > start ? end : start);
if (!items.length) return { success: false, error: `${displayName}(${station.name})의 해당 기간 관측자료가 없습니다.` };
const lines = [`기상청 과거 관측: ${displayName} — ${station.name} 관측소`, ''];
for (const it of items) lines.push(...parseAsosDaily(it), '');
if (items.length > 1) {
const total = items.reduce((s, it) => s + (parseFloat(String(it?.sumRn ?? '')) || 0), 0);
lines.push(`기간 합계 강수량: ${Math.round(total * 10) / 10} mm (${items.length}일)`);
}
return { success: true, stdout: lines.join('\n').trim(), data: { location: displayName, station, items } };
}
if (type === 'current') {
const { base_date, base_time } = getKmaBaseDateTime('ncst');
const items = await kmaFetch('getUltraSrtNcst', { base_date, base_time, nx: String(nx), ny: String(ny) });
const get = (cat: string) => items.find((i: any) => i.category === cat)?.obsrValue ?? 'N/A';
const pty = get('PTY');
const vecDeg = parseFloat(get('VEC')) || 0;
// Only meaningful when base_date is still today — between 00:00 and 00:40 KST
// getKmaBaseDateTime falls back to yesterday 2300, and there is no "today" to total yet.
const todayKst = new Date(Date.now() + 9 * 3600 * 1000).toISOString().slice(0, 10).replace(/-/g, '');
// 이름으로 지점을 맞히고, 안 되면 좌표로 최근접 지점(40km 이내)을 잡는다.
// 둘 다 실패해야 Open-Meteo 추정으로 물러난다.
const named = findAsosStation(location) ?? findAsosStation(displayName);
const near = named ? null : nearestAsosStation(lat, lon);
const station = named ?? near;
// 오늘 누적은 AWS 매분자료의 RN-DAY를 쓴다 — 관측소 실측이고 1회 호출이다.
// 지점은 ASOS(97개)가 아니라 AWS(745개) 중 최근접으로 따로 고른다. ASOS에 묶어두면
// 시흥이 19.1km 떨어진 인천을 읽는데, AWS로 고르면 2.5km 시흥 관측소가 잡힌다.
//
// 사상 누적은 과거 구간이 ASOS라서 관측소가 갈릴 수 있다. 그래도 "오늘 > 사상" 같은
// 모순은 안 난다 — 사상 합계는 오늘치를 통째로 포함하고 과거 몫은 음수가 될 수 없다.
// 두 줄에 각각 관측소 이름이 찍히므로 어디서 온 값인지도 드러난다.
// 둘 다 없으면 초단기실황 합산으로 물러난다(격자 보간이라 값은 조금 다르지만 어디서든 나온다).
const awsStn = nearestAwsStation(lat, lon) ?? station;
let aws: Awaited<ReturnType<typeof fetchAwsToday>> | null = null;
if (awsStn && base_date === todayKst) {
try { aws = await fetchAwsToday(awsStn.id, todayKst); } catch { aws = null; }
}
// 안개는 있을 때만 한 줄 붙인다 — 매번 "안개 없음"을 쓰면 소음이 된다.
// 실패하거나 근처에 없으면 null이라 그대로 빠진다.
const fogLine = await fetchRoadFog(lat, lon);
const todayRain = (aws?.rnDay == null && base_date === todayKst)
? await fetchKmaTodayRain(nx, ny, base_date, parseInt(base_time.slice(0, 2), 10))
: null;
// 사상 판정에 넘길 오늘 구간: AWS를 썼으면 그 시간별 값, 아니면 초단기실황 쪽.
const todayHours = aws?.hours.length ? aws.hours : (todayRain?.perHour ?? []);
const observed = station && todayHours.length
? await fetchKmaRainEpisode(station.id, todayKst, todayHours)
: null;
const episode = observed ?? await fetchRainEpisode(lat, lon);
// 최근접으로 잡았으면 거리를 밝힌다 — 그 지점이 대표성이 있는지는 사용자가 판단할 몫이다.
const episodeSource = observed
? `기상청 ${station!.name} 관측${near ? ` (${near.km}km)` : ''}`
: 'Open-Meteo 추정';
const rainLine = aws?.rnDay != null
? `오늘 누적 강수량: ${aws.rnDay} mm (AWS ${awsStn!.name} 관측`
+ (aws.tm ? `, ${aws.tm.slice(8,10)}:${aws.tm.slice(10,12)} 기준` : '')
+ ')'
: todayRain
? `오늘 누적 강수량: ${todayRain.mm} mm (00시~${String(todayRain.throughHour).padStart(2, '0')}시 격자 합산`
+ (todayRain.missing.length ? `, ${todayRain.missing.length}개 시각 결측` : '')
+ ')'
: '오늘 누적 강수량: 조회 불가';
// 사상이 오늘 안에서 시작했으면 위 "오늘 누적"과 같은 구간이라 한 줄 더 쓸 이유가 없다.
// 어제 이전부터 이어진 비일 때만 붙인다 — 사용자가 원한 게 정확히 그 경우다.
const epStartDay = episode?.startTime.slice(0, 10);
const episodeLine = episode && epStartDay && epStartDay < `${todayKst.slice(0,4)}-${todayKst.slice(4,6)}-${todayKst.slice(6,8)}`
? `이번 강수 누적: ${episode.truncated ? '≥' : ''}${episode.totalMm} mm `
+ `(${epStartDay.slice(5,7)}/${epStartDay.slice(8,10)} ${episode.startTime.slice(11,13)}시부터 이어짐, `
+ `강수 ${episode.wetHours}시간${episode.truncated ? ', 7일 조회창을 넘겨 하한값' : ''} · ${episodeSource})`
: null;
// 이번 강수 사상은 비가 그친 지 몇 시간 지나면 사라진다. 그 뒤 "이번 비 얼마나 왔어"를 받으면
// 모델이 type=past를 이어서 부르지 않고 "어제 값을 조회해야 한다"며 멈췄다(2026-10-19).
// 어제 비가 있었으면 그 일강수량을 같이 준다 — 일자료는 전날까지라 오늘과 겹치지 않는다.
let yesterdayLine: string | null = null;
if (!episodeLine && station && base_date === todayKst) {
try {
const yd = new Date(Date.now() + 9 * 3600 * 1000 - 24 * 3600 * 1000).toISOString().slice(0, 10).replace(/-/g, '');
const yItems = await fetchAsosDaily(station.id, yd, yd);
const ymm = parseFloat(String(yItems[0]?.sumRn ?? ''));
if (Number.isFinite(ymm) && ymm > 0) {
yesterdayLine = `어제(${yd.slice(4, 6)}/${yd.slice(6, 8)}) 일강수량: ${ymm} mm (ASOS ${station.name} 관측소) — 비가 어제부터 이어졌다면 "이번 비"는 어제 값 + 위 오늘 누적`;
}
} catch { /* 어제 값은 덤이라 실패해도 실황은 그대로 준다 */ }
}
const lines = [
`기상청 초단기실황: ${displayName}`,
`기준시각: ${base_date.slice(0,4)}-${base_date.slice(4,6)}-${base_date.slice(6,8)} ${base_time.slice(0,2)}:${base_time.slice(2,4)} KST`,
'',
`기온: ${get('T1H')}°C`,
`강수형태: ${PTY_LABEL[pty] ?? pty}`,
`1시간 강수량: ${get('RN1')} mm`,
rainLine,
...(episodeLine ? [episodeLine] : []),
...(yesterdayLine ? [yesterdayLine] : []),
...(fogLine ? [fogLine] : []),
`습도: ${get('REH')}%`,
`풍향: ${windDirectionKo(vecDeg)} (${get('VEC')}°)`,
`풍속: ${get('WSD')} m/s`,
'',
'(미세먼지/PM2.5/PM10/황사는 이 데이터에 없음 — weather_airkorea 사용)',
];
// 초단기예보(앞으로 6시간): "한 시간 뒤 비 와?"에 답하려면 필요. 실패해도 현재 실황은 그대로 준다.
const ultra = await fetchUltraSrtFcstLines(nx, ny).catch(() => [] as string[]);
if (ultra.length) lines.splice(lines.length - 2, 0, ...ultra, '');
return { success: true, stdout: lines.join('\n'), data: { location: displayName, nx, ny, items, todayRain, aws, episode, fogLine } };
} else {
// 2026-10-14: 발표 직후(11:04 등) API가 NO_DATA(03)를 내는 순간이 있다. 이때 모델이 openmeteo로
// 도망가 기상청 값이 답에서 빠졌다. 03이면 직전 발표(3시간 전)로 최대 2번 내려가 다시 받는다.
let { base_date, base_time } = getKmaBaseDateTime('fcst');
let items: any[];
for (let attempt = 0; ; attempt++) {
try {
items = await kmaFetch('getVilageFcst', { base_date, base_time, nx: String(nx), ny: String(ny) });
break;
} catch (e: any) {
if (attempt >= 2 || !/\(03\)|NO_DATA/.test(String(e?.message || ''))) throw e;
const t = new Date(Date.UTC(+base_date.slice(0, 4), +base_date.slice(4, 6) - 1, +base_date.slice(6, 8), +base_time.slice(0, 2)) - 3 * 3600_000);
base_date = `${t.getUTCFullYear()}${String(t.getUTCMonth() + 1).padStart(2, '0')}${String(t.getUTCDate()).padStart(2, '0')}`;
base_time = `${String(t.getUTCHours()).padStart(2, '0')}00`;
console.log(`[weather_kma] 단기예보 NO_DATA → 직전 발표 ${base_date} ${base_time}로 재시도`);
}
}
// Group forecast by date
const byDay: Record<string, Record<string, string[]>> = {};
// 시간별 강수량(PCP): "비 얼마나 와?"에 답하려면 필요 — 예전엔 POP/PTY만 뽑아 "수치 없음"으로 답했다
const pcpByDay: Record<string, Array<{ hour: string; raw: string }>> = {};
// 시간별 값(기온·습도·바람·적설…): "내일 아침 기온/바람"에 답하려면 필요 — 일별 요약만으론 부족했다
const hourly: Record<string, Record<string, string>> = {};
for (const item of items as any[]) {
const day = item.fcstDate as string;
if (!byDay[day]) byDay[day] = {};
const cat = item.category as string;
(byDay[day][cat] ||= []).push(item.fcstValue as string);
if (cat === 'PCP') (pcpByDay[day] ||= []).push({ hour: String(item.fcstTime).slice(0, 2), raw: String(item.fcstValue) });
const hk = `${day}${String(item.fcstTime).slice(0, 2)}`;
(hourly[hk] ||= {})[cat] = String(item.fcstValue);
}
const lines = [
`기상청 단기예보: ${displayName}`,
`발표: ${base_date.slice(0,4)}-${base_date.slice(4,6)}-${base_date.slice(6,8)} ${base_time.slice(0,2)}:${base_time.slice(2,4)} KST`,
'',
];
const coveredDays: string[] = [];
for (const [day, cats] of Object.entries(byDay).slice(0, 4)) {
coveredDays.push(day);
const ymd = `${day.slice(0,4)}-${day.slice(4,6)}-${day.slice(6,8)}`;
const tmx = cats.TMX?.[0];
const tmn = cats.TMN?.[0];
const maxPop = cats.POP?.length ? Math.max(...cats.POP.map(Number)) : undefined;
const skies = cats.SKY || [];
const ptys = cats.PTY || [];
const dominantSky = skies.sort((a, b) => skies.filter(v => v === b).length - skies.filter(v => v === a).length)[0];
const dominantPty = ptys.find(p => p !== '0');
lines.push(`📅 ${ymd}`);
if (tmx || tmn) lines.push(` 기온: ${tmn ?? '?'}~${tmx ?? '?'}°C`);
if (maxPop != null) lines.push(` 강수확률: ${maxPop}%`);
if (dominantPty) lines.push(` 강수형태: ${PTY_LABEL[dominantPty] ?? dominantPty}`);
else if (dominantSky) lines.push(` 날씨: ${SKY_LABEL[dominantSky] ?? dominantSky}`);
const pcp = summarizePcp(pcpByDay[day]);
if (pcp) lines.push(...pcp);
}
const hourlyLines = formatKmaHourly(hourly, coveredDays.slice(0, 2));
if (hourlyLines.length) lines.push('', ...hourlyLines);
lines.push('', '(미세먼지/PM2.5/PM10/황사는 이 데이터에 없음 — weather_airkorea 사용)');
// 2026-08-10 real incident: "이번 주말 날씨 어때?" (5 days out) hit this exact 3-4일
// ceiling — the model called only weather_kma, saw the range fell short, and told the
// user to ask again closer to the weekend instead of calling weather_openmeteo (up to
// 16 days), even though weather_kma's own description already says to do exactly that
// for >3-day requests. Prose guidance repeatedly failed to change this model's behavior
// today (see news_search's git history for the same pattern with different symptoms),
// so instead of asking the model to remember a second tool call, fetch the extension
// here and merge it into one answer — no second call, no chance to skip it.
const lastCovered = coveredDays.sort().slice(-1)[0];
// 2026-10-14: 4일 이후는 기상청 중기예보(MidFcstInfoService)를 먼저 쓴다. 승인이 없거나 실패하면
// (null) 예전처럼 Open-Meteo 보완으로 폴백한다.
const midKey = getKmaApiKey();
const midLines = midKey ? await fetchMidTermLines(midKey, lat, lon, lastCovered) : null;
const supplement = midLines ?? await fetchOpenMeteoDailySupplement(lat, lon, lastCovered);
if (supplement) lines.push('', ...supplement);
return { success: true, stdout: lines.join('\n'), data: { location: displayName, nx, ny } };
}
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_nasa_power (NASA POWER API, 키 불필요) ────────────────────────────
const NASA_POWER_BASE = 'https://power.larc.nasa.gov/api/temporal';
const NASA_PARAM_LABELS: Record<string, string> = {
T2M: '기온(°C)', T2M_MAX: '최고기온(°C)', T2M_MIN: '최저기온(°C)',
PRECTOTCORR: '강수량(mm)', RH2M: '습도(%)', WS2M: '풍속(m/s)',
WD2M: '풍향(°)', PS: '기압(kPa)', T2MDEW: '이슬점(°C)',
ALLSKY_SFC_SW_DWN: '일사량(kWh/m²)', ALLSKY_SFC_UV_INDEX: 'UV지수',
GWETTOP: '표층토양수분',
};
const MONTH_LABELS = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC','ANN'];
const MONTH_KO = ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월','연평균'];
export const weatherNasaPowerTool = {
name: 'weather_nasa_power',
description: 'NASA POWER API로 기후 데이터 조회 (키 불필요). 1981년~현재 일별/월별 기상 데이터 또는 30년 기후 평균(climatology). 기온·강수량·UV지수·일사량·습도·풍속 포함. 기후 변화 분석, 연간 기온 추이, 계절 통계에 활용.',
schema: {
location: '도시명 또는 "lat,lon" 좌표',
temporal: '"daily" (일별, 기본) | "monthly" (월별) | "climatology" (30년 기후 평균)',
start: '시작 날짜. daily: YYYYMMDD, monthly: YYYY. climatology는 불필요',
end: '종료 날짜. daily: YYYYMMDD, monthly: YYYY. climatology는 불필요',
parameters: 'NASA POWER 변수 코드 (쉼표 구분). 기본: T2M,T2M_MAX,T2M_MIN,PRECTOTCORR,RH2M,WS2M,ALLSKY_SFC_UV_INDEX',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: '도시명 또는 "lat,lon"' },
temporal: { type: 'string', description: '"daily" | "monthly" | "climatology"' },
start: { type: 'string', description: 'YYYYMMDD (daily) 또는 YYYY (monthly)' },
end: { type: 'string', description: 'YYYYMMDD (daily) 또는 YYYY (monthly)' },
parameters: { type: 'string', description: 'NASA POWER 변수 코드 (쉼표 구분)' },
},
required: ['location'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
if (!location) return { success: false, error: 'location이 필요합니다' };
const temporal = ['daily','monthly','climatology'].includes(args?.temporal) ? args.temporal : 'daily';
const paramStr = String(args?.parameters || 'T2M,T2M_MAX,T2M_MIN,PRECTOTCORR,RH2M,WS2M,ALLSKY_SFC_UV_INDEX').trim();
try {
let lat: number, lon: number, displayName: string;
const coords = parseCoords(location);
if (coords) {
[lat, lon] = coords;
displayName = location;
} else {
const geo = await geocodeCity(location);
if (!geo) return await locationNotFoundError(location, 'weather_nasa_power');
({ lat, lon, displayName } = geo);
}
const p: Record<string, string> = {
latitude: String(lat),
longitude: String(lon),
community: 'RE',
parameters: paramStr,
format: 'JSON',
user: 'homeclaw',
};
if (temporal !== 'climatology') {
// Provide sensible defaults when start/end are missing
const today = new Date(Date.now() + 9 * 3600_000);
if (temporal === 'daily') {
const end = args?.end || today.toISOString().slice(0, 10).replace(/-/g, '');
const startDate = new Date(today.getTime() - 29 * 86_400_000);
const start = args?.start || startDate.toISOString().slice(0, 10).replace(/-/g, '');
p.start = start;
p.end = end;
} else {
const year = today.getUTCFullYear();
p.start = args?.start || String(year - 1);
p.end = args?.end || String(year);
}
}
const qs = new URLSearchParams(p);
const url = `${NASA_POWER_BASE}/${temporal}/point?${qs}`;
const res = await fetch(url, { signal: AbortSignal.timeout(30_000) });
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`NASA POWER API 오류 ${res.status}: ${body.slice(0, 200)}`);
}
const data: any = await res.json();
const params_data: Record<string, any> = data?.properties?.parameter || {};
const paramCodes = paramStr.split(',').map(s => s.trim());
if (temporal === 'climatology') {
// Monthly climatology: {JAN: val, FEB: val, ..., ANN: val}
const lines = [
`NASA POWER 30년 기후 평균: ${displayName} (${lat.toFixed(2)}°N, ${lon.toFixed(2)}°E)`,
'',
['월', ...paramCodes.map(c => NASA_PARAM_LABELS[c] || c)].join('\t'),
'─'.repeat(80),
];
for (let i = 0; i < MONTH_LABELS.length; i++) {
const monthKey = MONTH_LABELS[i];
const vals = paramCodes.map(c => {
const v = params_data[c]?.[monthKey];
return v != null ? Number(v).toFixed(1) : '-';
});
lines.push([MONTH_KO[i], ...vals].join('\t'));
}
lines.push('', '출처: NASA POWER (MERRA-2 기반, 1981~현재)');
return { success: true, stdout: lines.join('\n'), data: { location: displayName, lat, lon, temporal } };
} else if (temporal === 'monthly') {
// Monthly: {YYYYMM: val}
const keys = Object.keys(params_data[paramCodes[0]] || {}).sort();
const lines = [
`NASA POWER 월별 데이터: ${displayName} (${p.start}~${p.end})`,
'',
['연월', ...paramCodes.map(c => NASA_PARAM_LABELS[c] || c)].join('\t'),
'─'.repeat(80),
];
for (const k of keys) {
const label = `${k.slice(0, 4)}-${k.slice(4, 6)}`;
const vals = paramCodes.map(c => {
const v = params_data[c]?.[k];
return v != null ? Number(v).toFixed(1) : '-';
});
lines.push([label, ...vals].join('\t'));
}
lines.push('', '출처: NASA POWER (MERRA-2 기반)');
return { success: true, stdout: lines.join('\n'), data: { location: displayName, lat, lon, temporal } };
} else {
// Daily: {YYYYMMDD: val}
const keys = Object.keys(params_data[paramCodes[0]] || {}).sort();
const SHOW = Math.min(keys.length, 31);
const lines = [
`NASA POWER 일별 데이터: ${displayName} (${p.start}~${p.end})`,
'',
['날짜', ...paramCodes.map(c => NASA_PARAM_LABELS[c] || c)].join('\t'),
'─'.repeat(80),
];
for (const k of keys.slice(0, SHOW)) {
const label = `${k.slice(0,4)}-${k.slice(4,6)}-${k.slice(6,8)}`;
const vals = paramCodes.map(c => {
const v = params_data[c]?.[k];
return v != null ? Number(v).toFixed(1) : '-';
});
lines.push([label, ...vals].join('\t'));
}
if (keys.length > SHOW) lines.push(`... (총 ${keys.length}일 중 ${SHOW}일 표시)`);
lines.push('', '출처: NASA POWER (MERRA-2 기반)');
return { success: true, stdout: lines.join('\n'), data: { location: displayName, lat, lon, temporal } };
}
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_airkorea (에어코리아 실시간 대기질) ───────────────────────────────
const SIDO_MAP: Record<string, string> = {
'서울': '서울', 'seoul': '서울',
'부산': '부산', 'busan': '부산',
'대구': '대구', 'daegu': '대구',
'인천': '인천', 'incheon': '인천',
'광주': '광주', 'gwangju': '광주',
'대전': '대전', 'daejeon': '대전',
'울산': '울산', 'ulsan': '울산',
'세종': '세종', 'sejong': '세종',
'경기': '경기', '경기도': '경기',
'강원': '강원', '강원도': '강원',
'충북': '충북', '충청북도': '충북',
'충남': '충남', '충청남도': '충남',
'전북': '전북', '전라북도': '전북',
'전남': '전남', '전라남도': '전남',
'경북': '경북', '경상북도': '경북',
'경남': '경남', '경상남도': '경남',
'제주': '제주', 'jeju': '제주',
// AirKorea's API only accepts province-level (시도) names, but users/models ask about
// specific cities/counties ("구미 미세먼지") — without this, that lookup fails outright
// (city name doesn't match any 시도) and a model with no other guidance can loop retrying
// instead of falling back to the parent province (observed 2026-08-06: gemma-4-26b-a4b hit
// its max-step limit doing exactly this on "구미 미세먼지"). Not exhaustive — covers the
// more commonly-asked non-metro cities; add more here if a gap surfaces.
'구미': '경북', '포항': '경북', '경주': '경북', '안동': '경북', '김천': '경북', '영주': '경북',
'천안': '충남', '아산': '충남', '서산': '충남', '당진': '충남',
'청주': '충북', '충주': '충북', '제천': '충북',
'전주': '전북', '군산': '전북', '익산': '전북',
'여수': '전남', '순천': '전남', '목포': '전남', '광양': '전남',
'창원': '경남', '진주': '경남', '김해': '경남', '양산': '경남', '거제': '경남', '통영': '경남',
'춘천': '강원', '원주': '강원', '강릉': '강원', '속초': '강원',
'수원': '경기', '성남': '경기', '용인': '경기', '고양': '경기', '부천': '경기', '안양': '경기',
'평택': '경기', '안산': '경기', '화성': '경기',
};
const AK_GRADE: Record<string, string> = { '1': '좋음', '2': '보통', '3': '나쁨', '4': '매우나쁨' };
export const weatherAirKoreaTool = {
name: 'weather_airkorea',
description: '에어코리아 API로 한국 실시간 대기질(PM2.5, PM10, 오존, 이산화질소, 일산화탄소, 이산화황) 조회. data.go.kr API 키 필요. 시/군 이름을 주면 그 도시의 측정소만 골라서 반환한다(예: sido="구미" → 구미시 5개 측정소). 시/도 이름을 주면 그 도 전체 측정소가 나오는데, 측정소 이름에는 소속 시/군이 안 들어있으므로(예: "우현동"은 포항, "중방동"은 경산) 그중 일부를 특정 도시 값으로 제시하면 안 된다 — 도시 수치를 물으면 반드시 도시 이름을 그대로 넣을 것.',
schema: {
sido: '시/군 이름(예: "구미", "포항") 또는 시도명(예: "서울", "경기", "경북")',
},
jsonSchema: {
type: 'object',
properties: {
sido: { type: 'string', description: '시/군 이름(구미/포항/성남 등) 또는 시도명(서울/부산/대구/인천/광주/대전/울산/세종/경기/강원/충북/충남/전북/전남/경북/경남/제주). 도시를 물으면 도시 이름을 넣을 것.' },
},
required: ['sido'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const sidoInput = String(args?.sido || '').trim();
if (!sidoInput) return { success: false, error: 'sido가 필요합니다' };
const sido = SIDO_MAP[sidoInput.toLowerCase()] ?? SIDO_MAP[sidoInput] ?? sidoInput;
// Caller named a city/county (mapped up to its province): resolve which stations actually
// belong to it. Until the 측정소정보 service was approved (2026-08-09) this was impossible —
// the realtime feed carries only sidoName, so a 구미 question got the whole 경북 list and the
// model presented 포항/영주/경산 stations as 구미. See stationsForCity().
const isCityLookup = sidoInput !== sido && sidoInput.toLowerCase() !== sido.toLowerCase();
const apiKey = getAirKoreaApiKey();
if (!apiKey) {
return {
success: false,
error: '에어코리아 API 키가 없습니다. data.go.kr에서 "에어코리아_대기오염정보 조회서비스"를 신청 후 vault에 airkorea.api_key(또는 kma.api_key)를 등록하세요.',
};
}
try {
const params = new URLSearchParams({
serviceKey: apiKey,
returnType: 'json',
// Must cover the whole province, not just the first page: 경북 alone has 53 stations, and
// at 20 rows a city filter silently found nothing whenever that city's stations sorted
// past the cut (포항 did, so "포항 미세먼지" fell back to the province list). Display is
// still capped further down; this only widens what there is to filter from.
numOfRows: '200',
pageNo: '1',
sidoName: sido,
ver: '1.0',
});
// data.go.kr answers this endpoint with SERVICETIMEOUT_ERROR (HTTP 504) intermittently —
// measured at roughly half of all calls on 2026-08-09, identically from curl and node, so
// it is upstream and not a client quirk. A single attempt turned that into a hard tool
// failure and the user saw the air-quality feature as simply broken half the time.
let res!: Response;
for (let attempt = 1; attempt <= 4; attempt++) {
res = await fetch(`${AIRKOREA_BASE}/getCtprvnRltmMesureDnsty?${params}`, { signal: AbortSignal.timeout(15_000) });
if (res.ok || res.status < 500) break; // 4xx (e.g. 403 approval) will not improve on retry
if (attempt < 4) await new Promise(r => setTimeout(r, 500 * attempt));
}
if (!res.ok) {
// data.go.kr treats each API ("서비스") as a separate approval even under one key —
// a working weather_kma key can still 403 here with SERVICE_KEY_IS_NOT_REGISTERED_ERROR
// if the account never applied for (or hasn't yet been approved for) AirKorea's
// "대기오염정보 조회서비스" specifically. That failure is permanent until approved on
// data.go.kr, so say so plainly — otherwise a model just retries or loops on this tool.
let detail = '';
try {
const errJson: any = await res.json();
const errMsg = errJson?.OpenAPI_ServiceResponse?.cmmMsgHeader?.returnAuthMsg
|| errJson?.OpenAPI_ServiceResponse?.cmmMsgHeader?.errMsg;
if (errMsg) detail = ` (${errMsg})`;
} catch {}
if (res.status === 403) {
return {
success: false,
error: `에어코리아 API 사용 승인이 안 되어 있습니다${detail} — data.go.kr에서 "에어코리아_대기오염정보 조회서비스"를 별도로 활용신청/승인받아야 합니다 (기상청 키와는 별개 승인). 재시도해도 승인 전까지는 계속 실패하므로, 이 요청에는 대신 web_search를 사용할 것.`,
};
}
throw new Error(`에어코리아 API 오류 ${res.status}${detail} — 재시도 4회 모두 실패`);
}
const data: any = await res.json();
const items: any[] = data?.response?.body?.items || [];
if (!items.length) return { success: false, error: `${sido} 측정 데이터가 없습니다` };
// For a city lookup, keep only that city's stations. Resolution can fail (upstream flakiness)
// — that is "unknown", not "no stations", so fall back to the province list WITH the warning
// rather than silently presenting a filtered-looking result that isn't filtered.
let displayItems = items;
let cityStations: string[] | null = null;
if (isCityLookup) {
cityStations = await stationsForCity(sidoInput, apiKey);
if (cityStations && cityStations.length) {
const set = new Set(cityStations);
const matched = items.filter(it => set.has(String(it.stationName || '')));
if (matched.length) displayItems = matched;
else cityStations = null; // city has stations, but none reporting right now
} else if (cityStations && !cityStations.length) {
cityStations = null; // no such city in the roster — do not claim a filter
}
}
const cityFiltered = isCityLookup && !!cityStations && displayItems !== items;
const header = cityFiltered
? `에어코리아 실시간 대기질: ${sidoInput} (${sido}) — ${sidoInput} 소속 측정소 ${displayItems.length}곳`
: `에어코리아 실시간 대기질: ${sido}${isCityLookup ? ` (요청: "${sidoInput}" — 시/군 필터 실패, ${sido} 전체를 표시)` : ''}`;
const lines = [header, `측정 시각: ${items[0]?.dataTime || 'N/A'}`, ''];
if (!cityFiltered) {
// Station names carry no city ("우현동" gives no hint it is 포항), so without this a model
// asked about one city presents whatever rows came back as that city's: 2026-08-09
// "오늘 구미 미세먼지" was answered with 포항 stations, then again with 영주/경산 ones.
lines.push(
`※ 아래는 ${sido} 전체 측정소이며, 특정 시/군만 추린 것이 아닙니다. 측정소 이름만으로는`,
` 소속 시/군을 알 수 없으므로, 특정 도시의 수치라고 단정해서 답하지 마세요.`,
'',
);
}
lines.push(
`${'측정소'.padEnd(12)} PM2.5 PM10 O3 NO2 CO SO2 PM2.5등급`,
'─'.repeat(75),
);
for (const item of displayItems.slice(0, 15)) {
const station = String(item.stationName || '').slice(0, 10).padEnd(12);
const pm25 = String(item.pm25Value ?? '-').padEnd(7);
const pm10 = String(item.pm10Value ?? '-').padEnd(7);
const o3 = String(item.o3Value ?? '-').padEnd(8);
const no2 = String(item.no2Value ?? '-').padEnd(8);
const co = String(item.coValue ?? '-').padEnd(7);
const so2 = String(item.so2Value ?? '-').padEnd(7);
const grade = AK_GRADE[item.pm25Grade] ?? item.pm25Grade ?? '-';
lines.push(`${station}${pm25}${pm10}${o3}${no2}${co}${so2}${grade}`);
}
lines.push('', '단위: PM2.5/PM10 μg/m³, O3/NO2/SO2 ppm, CO ppm');
return { success: true, stdout: lines.join('\n'), data: { sido, items } };
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_era5 (Open-Meteo Historical Archive, ERA5 기반, 키 불필요) ──────────
const ERA5_DAILY_LABELS: Record<string, string> = {
temperature_2m_max: '최고기온(°C)', temperature_2m_min: '최저기온(°C)',
temperature_2m_mean: '평균기온(°C)',
apparent_temperature_max: '체감최고(°C)', apparent_temperature_min: '체감최저(°C)',
precipitation_sum: '강수량(mm)', rain_sum: '강우량(mm)', snowfall_sum: '적설(cm)',
precipitation_hours: '강수시간(h)',
wind_speed_10m_max: '최대풍속(m/s)', wind_gusts_10m_max: '순간최대풍속(m/s)',
wind_direction_10m_dominant: '주풍향(°)',
shortwave_radiation_sum: '일사량(MJ/m²)', et0_fao_evapotranspiration: '증발산(mm)',
sunshine_duration: '일조시간(h)',
};
export const weatherEra5Tool = {
name: 'weather_era5',
description: 'ERA5 재분석 데이터 조회 (Open-Meteo 히스토리 API, 키 불필요). 1940년~5일 전까지 일별·시간별 기상 데이터. 기온·강수량·바람·일사량·증발산 등. 과거 날씨 확인, 특정 사건 당시 기상, 월별·계절별 통계 분석에 활용.',
schema: {
location: '도시명 또는 "lat,lon" 좌표',
start_date: '시작 날짜 (YYYY-MM-DD)',
end_date: '종료 날짜 (YYYY-MM-DD). 생략 시 start_date와 동일',
variables: '쉼표 구분 일별 변수 (기본: temperature_2m_max,temperature_2m_min,precipitation_sum,wind_speed_10m_max,sunshine_duration)',
hourly: 'true이면 시간별 데이터 반환',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: '도시명 또는 "lat,lon"' },
start_date: { type: 'string', description: 'YYYY-MM-DD' },
end_date: { type: 'string', description: 'YYYY-MM-DD (생략 시 start_date와 동일)' },
variables: { type: 'string', description: '쉼표 구분 변수 코드' },
hourly: { type: 'boolean', description: 'true = 시간별 데이터' },
},
required: ['location', 'start_date'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
const start_date = String(args?.start_date || '').trim();
if (!location) return { success: false, error: 'location이 필요합니다' };
if (!start_date) return { success: false, error: 'start_date가 필요합니다' };
const end_date = String(args?.end_date || start_date).trim();
const isHourly = Boolean(args?.hourly);
try {
let lat: number, lon: number, displayName: string;
const coords = parseCoords(location);
if (coords) {
[lat, lon] = coords;
displayName = location;
} else {
const geo = await geocodeCity(location);
if (!geo) return await locationNotFoundError(location, 'weather_era5');
({ lat, lon, displayName } = geo);
}
const params: Record<string, string> = {
latitude: String(lat), longitude: String(lon),
start_date, end_date, timezone: 'Asia/Seoul',
};
if (isHourly) {
params.hourly = args?.variables || 'temperature_2m,precipitation,wind_speed_10m,relative_humidity_2m,surface_pressure,shortwave_radiation';
} else {
params.daily = args?.variables || 'temperature_2m_max,temperature_2m_min,precipitation_sum,wind_speed_10m_max,sunshine_duration';
}
const qs = new URLSearchParams(params);
const data: any = await httpsGetJsonIPv4(`https://archive-api.open-meteo.com/v1/archive?${qs}`, 30_000);
const section = isHourly ? data.hourly : data.daily;
const unitMap = isHourly ? (data.hourly_units || {}) : (data.daily_units || {});
if (!section?.time?.length) return { success: false, error: '데이터가 없습니다 (날짜 범위 또는 변수 확인)' };
const times: string[] = section.time;
const varKeys = Object.keys(section).filter(k => k !== 'time');
const SHOW = Math.min(times.length, isHourly ? 48 : 365);
const headerCols = ['날짜/시각', ...varKeys.map(k => ERA5_DAILY_LABELS[k] || `${k}(${unitMap[k] || ''})`)];
const rows = times.slice(0, SHOW).map((t, i) => {
const vals = varKeys.map(k => {
const v = section[k]?.[i];
if (v == null) return '-';
if (k === 'sunshine_duration') return (Number(v) / 3600).toFixed(1);
return typeof v === 'number' ? v.toFixed(1) : String(v);
});
return [t, ...vals].join('\t');
});
const truncNote = times.length > SHOW ? `(총 ${times.length}건 중 ${SHOW}건 표시)` : '';
const text = [
`ERA5 ${isHourly ? '시간별' : '일별'} 데이터: ${displayName} (${start_date} ~ ${end_date})`,
'출처: ERA5 재분석 (Open-Meteo Historical Archive)',
'',
headerCols.join('\t'),
'─'.repeat(80),
...rows,
...(truncNote ? [truncNote] : []),
].join('\n');
return { success: true, stdout: text, data: { location: displayName, lat, lon, start_date, end_date } };
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_cds (Copernicus CDS 정식 API, cdsapi, 자격증명 필요) ──────────────
function getCdsApiKey(): string | undefined {
try {
const cm = getConfig();
const vault = getVault(cm.getConfigDir());
return vault.get('cds.api_key', 'weather:cds')?.expose();
} catch {}
return undefined;
}
function runPythonCds(input: object, timeoutMs = 300_000): Promise<any> {
return new Promise((resolve, reject) => {
const scriptPath = path.join(getPaths().scripts, 'era5_cds_fetch.py');
const child = spawn('python3', [scriptPath], { stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
child.stdout.on('data', (d: Buffer) => { stdout += d.toString(); });
child.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });
const timer = setTimeout(() => {
child.kill();
reject(new Error(`CDS 요청 타임아웃 (${timeoutMs / 1000}초)`));
}, timeoutMs);
child.on('close', () => {
clearTimeout(timer);
if (!stdout.trim()) {
reject(new Error(`Python 오류: ${stderr.slice(0, 500)}`));
return;
}
try { resolve(JSON.parse(stdout.trim())); }
catch { reject(new Error(`JSON 파싱 오류: ${stdout.slice(0, 200)}`)); }
});
child.stdin.write(JSON.stringify(input));
child.stdin.end();
});
}
const CDS_PRESETS: Record<string, (loc: {lat: number, lon: number}, year: string, month: string) => object> = {
surface_daily: ({ lat, lon }, year, month) => ({
product_type: 'reanalysis',
variable: ['2m_temperature', 'total_precipitation', '10m_u_component_of_wind', '10m_v_component_of_wind', 'surface_pressure'],
year, month,
day: Array.from({length: 31}, (_, i) => String(i + 1).padStart(2, '0')),
time: ['00:00', '06:00', '12:00', '18:00'],
area: [lat + 0.5, lon - 0.5, lat - 0.5, lon + 0.5],
data_format: 'netcdf',
}),
pressure_500hpa: ({ lat, lon }, year, month) => ({
product_type: 'reanalysis',
variable: ['geopotential', 'temperature', 'u_component_of_wind', 'v_component_of_wind'],
pressure_level: ['500'],
year, month,
day: Array.from({length: 31}, (_, i) => String(i + 1).padStart(2, '0')),
time: ['00:00', '12:00'],
area: [lat + 0.5, lon - 0.5, lat - 0.5, lon + 0.5],
data_format: 'netcdf',
}),
// CMIP6 SSP scenarios — dataset must be 'projections-cmip6'
cmip6_ssp126: ({ lat, lon }, year, month) => ({
model: 'mri_esm2_0',
experiment: 'ssp1_2_6',
variable: ['air_temperature'],
temporal_resolution: 'monthly',
year, month,
area: [lat + 1, lon - 1, lat - 1, lon + 1],
data_format: 'netcdf',
}),
cmip6_ssp245: ({ lat, lon }, year, month) => ({
model: 'mri_esm2_0',
experiment: 'ssp2_4_5',
variable: ['air_temperature'],
temporal_resolution: 'monthly',
year, month,
area: [lat + 1, lon - 1, lat - 1, lon + 1],
data_format: 'netcdf',
}),
cmip6_ssp585: ({ lat, lon }, year, month) => ({
model: 'mri_esm2_0',
experiment: 'ssp5_8_5',
variable: ['air_temperature'],
temporal_resolution: 'monthly',
year, month,
area: [lat + 1, lon - 1, lat - 1, lon + 1],
data_format: 'netcdf',
}),
};
export const weatherCdsTool = {
name: 'weather_cds',
description: 'Copernicus CDS 정식 API (cdsapi). ERA5 압력면 데이터(500hPa 지위고도·기온), ERA5-Land, CMIP6 등 고급 기후 데이터. vault에 cds.api_key 등록 필요. 일반 과거 날씨 조회는 weather_era5 사용 권장.',
schema: {
location: '도시명 또는 "lat,lon" 좌표',
dataset: 'CDS 데이터셋 ID (기본: reanalysis-era5-single-levels)',
preset: '"surface_daily" (기본) | "pressure_500hpa" (500hPa 압력면)',
year: '연도 (예: "2024")',
month: '월 (01~12)',
request: '직접 CDS request 딕셔너리 (JSON 문자열, 고급)',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: '도시명 또는 "lat,lon"' },
dataset: { type: 'string', description: 'CDS 데이터셋 ID' },
preset: { type: 'string', description: '"surface_daily" | "pressure_500hpa"' },
year: { type: 'string', description: '4자리 연도' },
month: { type: 'string', description: '2자리 월' },
request: { type: 'string', description: 'CDS request JSON (고급)' },
},
required: ['location', 'year', 'month'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const apiKey = getCdsApiKey();
if (!apiKey) {
return {
success: false,
error: [
'CDS API 키 미등록. 설정 방법:',
'1. https://cds.climate.copernicus.eu/ 가입',
'2. 프로필 페이지 → "Personal Access Token" 복사',
'3. vault 등록: smallclaw vault set cds.api_key <token>',
].join('\n'),
};
}
const location = String(args?.location || '').trim();
const year = String(args?.year || '').trim();
const month = String(args?.month || '').trim().padStart(2, '0');
if (!location) return { success: false, error: 'location이 필요합니다' };
if (!year) return { success: false, error: 'year가 필요합니다' };
try {
let lat: number, lon: number, displayName: string;
const coords = parseCoords(location);
if (coords) { [lat, lon] = coords; displayName = location; }
else {
const geo = await geocodeCity(location);
if (!geo) return await locationNotFoundError(location, 'weather_cds');
({ lat, lon, displayName } = geo);
}
const dataset = String(args?.dataset || 'reanalysis-era5-single-levels');
const presetKey = String(args?.preset || 'surface_daily');
let cdsRequest: object;
if (args?.request) {
try { cdsRequest = JSON.parse(String(args.request)); }
catch { return { success: false, error: 'request JSON 파싱 오류' }; }
} else {
const fn = CDS_PRESETS[presetKey];
if (!fn) return { success: false, error: `알 수 없는 프리셋: ${presetKey}` };
cdsRequest = fn({ lat, lon }, year, month);
}
const result: any = await runPythonCds({ url: 'https://cds.climate.copernicus.eu/api', key: apiKey, dataset, request: cdsRequest, lat, lon }, 300_000);
if (!result.ok) return { success: false, error: result.error };
const { data, times, meta } = result;
const lines = [
`CDS ERA5: ${displayName} ${year}년 ${month}월`,
`데이터셋: ${dataset} | 변수: ${meta.variables?.join(', ')}`,
`기간: ${times[0] ?? '-'} ~ ${times[times.length - 1] ?? '-'} (${meta.n_times}건)`,
'',
];
for (const [varName, info] of Object.entries(data) as any) {
const vals: number[] = (info.values as any[]).filter(v => v != null);
if (!vals.length) continue;
const avg = (vals.reduce((a, b) => a + b, 0) / vals.length).toFixed(2);
lines.push(`${info.long_name} (${info.units}): 평균 ${avg} 최소 ${Math.min(...vals).toFixed(2)} 최대 ${Math.max(...vals).toFixed(2)}`);
}
lines.push('', '출처: Copernicus CDS ERA5 (ECMWF)');
return { success: true, stdout: lines.join('\n'), data: { location: displayName, lat, lon, year, month, meta } };
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_cmip6 (Open-Meteo Climate API, CMIP6 기반, 키 불필요) ─────────────
const CMIP6_VAR_LABELS: Record<string, string> = {
temperature_2m_max: '최고기온(°C)',
temperature_2m_min: '최저기온(°C)',
precipitation_sum: '강수량(mm)',
wind_speed_10m_mean: '평균풍속(m/s)',
relative_humidity_2m_max: '최대습도(%)',
snowfall_sum: '적설(cm)',
shortwave_radiation_sum: '일사량(MJ/m²)',
};
// Aggregate daily → monthly statistics
function aggregateMonthly(times: string[], varData: Record<string, number[]>): {
months: string[];
stats: Record<string, { mean: number; min: number; max: number }[]>;
} {
const byMonth: Record<string, Record<string, number[]>> = {};
times.forEach((t, i) => {
const ym = t.slice(0, 7); // 'YYYY-MM'
if (!byMonth[ym]) byMonth[ym] = {};
for (const [k, vals] of Object.entries(varData)) {
const v = vals[i];
if (v == null || isNaN(v)) continue;
(byMonth[ym][k] ||= []).push(v);
}
});
const months = Object.keys(byMonth).sort();
const stats: Record<string, { mean: number; min: number; max: number }[]> = {};
for (const k of Object.keys(varData)) {
stats[k] = months.map(m => {
const arr = byMonth[m]?.[k] || [];
if (!arr.length) return { mean: NaN, min: NaN, max: NaN };
const sum = arr.reduce((a, b) => a + b, 0);
return { mean: sum / arr.length, min: Math.min(...arr), max: Math.max(...arr) };
});
}
return { months, stats };
}
// Aggregate monthly → annual statistics
function aggregateAnnual(months: string[], stats: Record<string, { mean: number; min: number; max: number }[]>): {
years: string[];
annual: Record<string, { mean: number; min: number; max: number }[]>;
} {
const byYear: Record<string, Record<string, number[]>> = {};
months.forEach((m, i) => {
const y = m.slice(0, 4);
if (!byYear[y]) byYear[y] = {};
for (const [k, arr] of Object.entries(stats)) {
const v = arr[i]?.mean;
if (v == null || isNaN(v)) continue;
(byYear[y][k] ||= []).push(v);
}
});
const years = Object.keys(byYear).sort();
const annual: Record<string, { mean: number; min: number; max: number }[]> = {};
for (const k of Object.keys(stats)) {
annual[k] = years.map(y => {
const arr = byYear[y]?.[k] || [];
if (!arr.length) return { mean: NaN, min: NaN, max: NaN };
const s = arr.reduce((a, b) => a + b, 0);
return { mean: s / arr.length, min: Math.min(...arr), max: Math.max(...arr) };
});
}
return { years, annual };
}
export const weatherCmip6Tool = {
name: 'weather_cmip6',
description: 'CMIP6 기후 모델 시나리오 조회 (Open-Meteo Climate API, 키 불필요). 1950년부터 2050년까지 기후 데이터. 과거 기후 모델 검증 및 근미래(2050년까지) 기후 변화 전망. 기온·강수량·바람·일사량. aggregate 파라미터로 월별/연별 집계 가능. SSP 시나리오 비교는 weather_cds 사용.',
schema: {
location: '도시명 또는 "lat,lon" 좌표',
start_date: '시작 날짜 (YYYY-MM-DD, 1950-01-01 ~ 2050-12-31)',
end_date: '종료 날짜 (YYYY-MM-DD)',
variables: '변수 코드 쉼표 구분 (기본: temperature_2m_max,temperature_2m_min,precipitation_sum)',
aggregate: '"daily" (기본) | "monthly" | "annual" — 시계열 집계 단위',
},
jsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: '도시명 또는 "lat,lon"' },
start_date: { type: 'string', description: 'YYYY-MM-DD (1950~2050)' },
end_date: { type: 'string', description: 'YYYY-MM-DD' },
variables: { type: 'string', description: '변수 코드 쉼표 구분' },
aggregate: { type: 'string', description: '"daily" | "monthly" | "annual"' },
},
required: ['location', 'start_date', 'end_date'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const location = String(args?.location || '').trim();
const start_date = String(args?.start_date || '').trim();
const end_date = String(args?.end_date || '').trim();
if (!location || !start_date || !end_date)
return { success: false, error: 'location, start_date, end_date가 필요합니다' };
const varStr = String(args?.variables || 'temperature_2m_max,temperature_2m_min,precipitation_sum');
const aggMode = ['monthly', 'annual'].includes(args?.aggregate) ? args.aggregate : 'daily';
try {
let lat: number, lon: number, displayName: string;
const coords = parseCoords(location);
if (coords) { [lat, lon] = coords; displayName = location; }
else {
const geo = await geocodeCity(location);
if (!geo) return await locationNotFoundError(location, 'weather_cmip6');
({ lat, lon, displayName } = geo);
}
const qs = new URLSearchParams({
latitude: String(lat), longitude: String(lon),
start_date, end_date,
daily: varStr,
});
const data: any = await httpsGetJsonIPv4(`https://climate-api.open-meteo.com/v1/climate?${qs}`, 30_000);
if (data.error) throw new Error(data.reason || 'Climate API 오류');
const times: string[] = data.daily?.time || [];
const varKeys = varStr.split(',').map(s => s.trim()).filter(k => data.daily?.[k]);
if (!times.length) return { success: false, error: '데이터가 없습니다 (날짜 범위: 1950-01-01 ~ 2050-12-31)' };
const varData: Record<string, number[]> = {};
for (const k of varKeys) varData[k] = data.daily[k] || [];
const header = ['기간', ...varKeys.map(k => CMIP6_VAR_LABELS[k] || k)];
let rows: string[] = [];
if (aggMode === 'daily') {
const SHOW = Math.min(times.length, 365);
rows = times.slice(0, SHOW).map((t, i) => {
const vals = varKeys.map(k => {
const v = varData[k]?.[i];
return v != null && !isNaN(v) ? v.toFixed(1) : '-';
});
return [t, ...vals].join('\t');
});
if (times.length > SHOW) rows.push(`(총 ${times.length}일 중 ${SHOW}일 표시)`);
} else if (aggMode === 'monthly') {
const { months, stats } = aggregateMonthly(times, varData);
rows = months.map((m, i) => {
const vals = varKeys.map(k => {
const s = stats[k]?.[i];
return s && !isNaN(s.mean) ? s.mean.toFixed(1) : '-';
});
return [m, ...vals].join('\t');
});
} else {
const { months, stats } = aggregateMonthly(times, varData);
const { years, annual } = aggregateAnnual(months, stats);
rows = years.map((y, i) => {
const vals = varKeys.map(k => {
const s = annual[k]?.[i];
return s && !isNaN(s.mean) ? s.mean.toFixed(1) : '-';
});
return [y, ...vals].join('\t');
});
}
const note = aggMode !== 'daily'
? `(${aggMode === 'monthly' ? '월별 평균값' : '연별 평균값'})`
: '';
const text = [
`CMIP6 기후 모델 데이터 ${note}: ${displayName} (${start_date} ~ ${end_date})`,
'출처: Open-Meteo Climate API (CMIP6 기반) | 2015년 이후: SSP2-4.5 시나리오 추정',
'',
header.join('\t'),
'─'.repeat(80),
...rows,
].join('\n');
return { success: true, stdout: text, data: { location: displayName, lat, lon, start_date, end_date, aggregate: aggMode, n: times.length } };
} catch (err: any) {
return { success: false, error: err.message };
}
},
};
// ── weather_map_screenshot (headless capture of Windy embed map) ─────────────
// The Windy iframe embedded in the weather app UI is rendered client-side for
// the human user only — the model never sees it. This tool actually opens the
// same embed URL in a headless browser and screenshots it, so the model can
// look at the rendered map instead of guessing what its own coordinates show.
let _mapPlaywrightModule: any = null;
let _mapBrowser: any = null;
let _mapChromiumPath: string | null | undefined = undefined; // undefined = not probed yet
async function findMapChromiumExecutable(): Promise<string | null> {
const candidates = [
process.env.CHROME_PATH,
'/usr/bin/chromium-browser',
'/usr/bin/chromium',
'/usr/bin/google-chrome',
'/usr/bin/google-chrome-stable',
'/snap/bin/chromium',
].filter(Boolean) as string[];
for (const p of candidates) {
if (fs.existsSync(p)) return p;
}
return null;
}
async function getMapBrowser(): Promise<any> {
if (_mapBrowser) {
try {
await _mapBrowser.version();
return _mapBrowser;
} catch {
_mapBrowser = null;
}
}
if (!_mapPlaywrightModule) {
if (!process.env.PLAYWRIGHT_BROWSERS_PATH) {
const os = await import('os');
process.env.PLAYWRIGHT_BROWSERS_PATH = path.join(os.homedir(), '.playwright-browsers');
}
_mapPlaywrightModule = await (Function('return import("playwright")')() as Promise<any>);
}
if (_mapChromiumPath === undefined) _mapChromiumPath = await findMapChromiumExecutable();
_mapBrowser = await _mapPlaywrightModule.chromium.launch({
headless: true,
...(_mapChromiumPath ? { executablePath: _mapChromiumPath } : {}),
});
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(?:\?.*)?$/;
// JMA (RSMC Tokyo) is the actual regional warning center for the WHOLE Western North
// Pacific basin — unlike KMA's page (only shows the storm KMA itself has designated,
// i.e. ones close enough to threaten Korea) and NHC's page (Atlantic/EPac/CPac only).
// A typhoon sitting near Taiwan/Philippines/Guam/Japan with no Korea impact yet is
// invisible to both, so this plugs that gap. typhoon=all draws every active WNP storm's
// forecast track at once — no per-storm slot lookup needed, so (like KMA) this is a
// single fixed URL rather than something resolved per-storm.
const JMA_TYPHOON_MAP_URL = 'https://www.jma.go.jp/bosai/map.html#4/17.686/133.792/&elem=root&typhoon=all&contents=typhoon';
export const weatherMapScreenshotTool = {
name: 'weather_map_screenshot',
description: 'Capture a real screenshot of a rendered weather map — the Windy embed (radar, satellite, wind, precipitation, etc.), the KMA typhoon forecast-track page, the JMA (RSMC Tokyo) all-active-typhoons forecast-track map, 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, the literal ${KMA_TYPHOON_TRACK_URL} for KMA, the literal ${JMA_TYPHOON_MAP_URL} for JMA, 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, KMA typhoon track, JMA 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'],
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const urlStr = String(args?.url || '').trim();
if (!urlStr) return { success: false, error: 'url is required' };
let parsed: URL;
try { parsed = new URL(urlStr); } catch { return { success: false, error: 'Invalid URL' }; }
const isKmaTrack = urlStr === KMA_TYPHOON_TRACK_URL;
const isJmaTrack = urlStr === JMA_TYPHOON_MAP_URL;
const isNhcTrack = NHC_TRACK_URL_RE.test(urlStr);
if (parsed.hostname !== 'embed.windy.com' && !isKmaTrack && !isJmaTrack && !isNhcTrack) {
return { success: false, error: `Only embed.windy.com, ${KMA_TYPHOON_TRACK_URL}, ${JMA_TYPHOON_MAP_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);
let context: any = null;
try {
const browser = await getMapBrowser();
// Bigger viewport than before (was 900x620) for more legible city labels/numbers —
// safe because JPEG capture below keeps the file small despite the larger canvas.
context = await browser.newContext({ viewport: { width: 1280, height: 880 } });
const page = await context.newPage();
await page.goto(parsed.toString(), { waitUntil: 'load', timeout: 20_000 });
await page.waitForTimeout(waitMs);
// Capture as JPEG (not PNG) so the file lands under the 300KB threshold in
// resolveToolImageContent (server-v2.ts) that otherwise re-downscales anything
// bigger to a blurry 600x600 thumbnail — losing exactly the city-name/temperature
// text and color-band precision the model needs to read the map accurately.
const buf: Buffer = await page.screenshot({ type: 'jpeg', quality: 90 });
const workspacePath = getWorkspacePath(args);
const outDir = path.join(workspacePath, 'weather-maps');
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
const filePath = path.join(outDir, `windy-${Date.now()}.jpg`);
fs.writeFileSync(filePath, buf);
const label = isKmaTrack
? 'KMA 태풍 예상진로 페이지 캡처 완료'
: isJmaTrack
? 'JMA(RSMC 도쿄) 태풍 예상진로 지도 캡처 완료'
: isNhcTrack
? 'NHC 허리케인 예상진로 페이지 캡처 완료'
: `Windy 지도 캡처 완료 (overlay=${parsed.searchParams.get('overlay') || 'map'}, zoom=${parsed.searchParams.get('zoom') || '?'})`;
return {
success: true,
stdout: `${label}:\n\n${buildImageMarkdown(filePath, workspacePath)}\n\n위 이미지에 실제로 보이는 내용만 근거로 설명하세요. 보이지 않는 세부사항을 추측하지 마세요.`,
};
} catch (err: any) {
return { success: false, error: `지도 캡처 실패: ${err.message}` };
} finally {
try { if (context) await context.close(); } catch {}
}
},
};
// ── 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}` };
}
},
};