Compare commits

..

7 Commits

Author SHA1 Message Date
javis-bot
b4f8f71dd2 chore(app): version 0.1.29
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:08:15 +09:00
javis-bot
9ba26c5bac feat(weather): districts such as 부산 연제구 found on OpenStreetMap
open-meteo's geocoder knows cities only, in Latin spellings, and matches a
non-Latin name loosely: "부산" gave a village called Pusan 140 km from
Busan. A non-Latin name now goes to OpenStreetMap's Nominatim first (any
language, down to districts), and a Latin name open-meteo does not know
goes there before the LLM romanisation and the wider-area retries. The
answer names the place in the user's own words, and KMA gets that spot's
grid point. Eval: evals/test_weather_district_place.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:08:15 +09:00
javis-bot
1bef5db912 chore(app): version 0.1.28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:57:23 +09:00
javis-bot
17927b6450 feat(weather): KMA forecasts for a later day (days_ahead, days)
getWeather takes days_ahead (days from today, up to 10) and days (a span,
2 for a weekend). Inside Korea with the app's KMA key: 단기예보 for today
to 3 days ahead (morning and afternoon weather, lowest and highest, highest
chance of rain), then 중기기온 and 중기육상 for the nearest of 32 KMA cities
and its region. Days KMA does not give, and every KMA failure, come from
open-meteo's daily forecast. days_ahead 0 with more days gives the weather
now, then each day. Eval: evals/test_weather_forecast_days.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:57:12 +09:00
javis-bot
ecde1e6bd0 chore(app): version 0.1.27
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:05:45 +09:00
javis-bot
282f114e60 feat(weather): KMA current weather inside Korea with the app's stored key
The 기능 screen's 기상청 날씨 card stores the KMA API hub key encrypted
(kmaApiKey, masked in logs). On start the app passes it to the worker in
JARVIS_KMA_API_KEY; the worker takes it out of its environment before any
child process starts. Inside Korea getWeather reads 초단기실황 and the
coming hour's sky from 초단기예보, and falls back to open-meteo, then
met.no, on any KMA failure. The key is in KMA's URLs, so failures are
logged by their kind only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:05:31 +09:00
javis-bot
e99831e540 fix(gitignore): keep ignoring a leftover Gemini login folder
Removing the Gemini backend also dropped the rule, so an older checkout's
docker/gemini-oauth/oauth_creds.json could be committed by git add -A.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:30:38 +09:00
17 changed files with 1096 additions and 44 deletions

3
.gitignore vendored
View File

@@ -29,3 +29,6 @@ src/jarvis/_version.py
.env.bak*
*.bak
# Gemini CLI OAuth login (account tokens) from the removed Gemini search backend. An
# older checkout may still hold docker/gemini-oauth/oauth_creds.json; never commit it.
docker/gemini-oauth/

View File

@@ -36,6 +36,7 @@
- 원하면 게임 중에는 봇을 일시정지할 수 있습니다.
- **안티치트 보호**: 뱅가드 같은 안티치트가 걸린 게임이 실행 중이면 키보드·마우스 자동 조작을 막고 그 이유를 알려 줍니다.
- **기존 기능 유지**: 메모리, 날씨, 웹 검색, 식단 기록, MCP, 브라우저 제어를 그대로 가져갑니다.
- **기상청 날씨**: 관리 앱 "기능" 화면에 기상청 API허브 인증키를 넣으면 한국 안의 현재 날씨와 10일 뒤까지의 예보("내일 날씨", "주말 날씨")를 기상청에서 받습니다. "부산 연제구"처럼 구 단위로 물으면 그 구의 날씨를 답합니다(장소는 OpenStreetMap에서 찾습니다)(초단기실황조회, 초단기예보조회, 단기예보조회, 중기기온조회, 중기육상예보조회 활용신청 필요). 키가 없거나 한국 밖이면 open-meteo에서 받고, 현재 날씨는 그다음 met.no에서 받습니다.
- **관리 앱**:
- 첫 실행 마법사, 대시보드, 모델 다운로드, 기능별 켜기/끄기를 제공합니다.
- 로그 화면에서 로그를 보고, 복사하고, 내려받을 수 있습니다. 비밀값은 자동으로 가립니다.

2
app/Cargo.lock generated
View File

@@ -1520,7 +1520,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jarvis-app"
version = "0.1.26"
version = "0.1.29"
dependencies = [
"async-trait",
"base64 0.22.1",

View File

@@ -1,6 +1,6 @@
[package]
name = "jarvis-app"
version = "0.1.26"
version = "0.1.29"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 Windows app core: Discord voice, voice worker supervisor, chat channels"

4
app/shell/Cargo.lock generated
View File

@@ -2637,7 +2637,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jarvis-app"
version = "0.1.26"
version = "0.1.29"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2666,7 +2666,7 @@ dependencies = [
[[package]]
name = "jarvis-shell"
version = "0.1.26"
version = "0.1.29"
dependencies = [
"jarvis-app",
"serde_json",

View File

@@ -1,6 +1,6 @@
[package]
name = "jarvis-shell"
version = "0.1.26"
version = "0.1.29"
edition = "2021"
rust-version = "1.85"
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"

View File

@@ -81,6 +81,13 @@ manages the MCP servers it connects.
listed. On start the app passes the enabled servers' stored values to the worker in its
environment, `JARVIS_MCP_ENV` (`{server: {NAME: value}}`); the brain takes that variable out of
its own environment and gives each server only its own values.
- **The KMA key** (기상청 API허브, for `getWeather` inside Korea): the 기능 screen's "기상청 날씨" card
takes it (`kma_key_set`; an empty value removes it) and shows it only masked. It is stored as
`kmaApiKey`, never in the settings file or `config/brain.json`, and saving `mcpServers` keeps it.
On start the app passes it to the worker in `JARVIS_KMA_API_KEY`; the worker takes that variable
out of its environment before any child process starts, and only the weather tool uses it
(the weather now and the forecast up to 10 days ahead inside Korea from KMA, else open-meteo;
the weather now then met.no). Without a key nothing changes.
- Each server's outcome (its tool count, or why it failed) is a worker line in the LLM log tab,
also without debug logging. MCP servers are programs the PC runs; the screen says to add only
trusted ones.
@@ -342,7 +349,7 @@ channel, titles and links only (no LLM, nothing Jarvis writes about them).
## Secrets (`app/src/secrets.rs`)
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`, the MCP servers'
environment values `mcp:<server>:<NAME>`). On Windows the bytes are
environment values `mcp:<server>:<NAME>`, the KMA API hub key `kmaApiKey`). On Windows the bytes are
encrypted with DPAPI for the current Windows user (`CryptProtectData`, no prompt), so the file is
useless copied to another account or PC. Elsewhere (development only) the file is plain JSON with
owner-only permissions (0600). Writes are atomic. `get`, `set`, `remove`, `names`; `masked(value)` shows only
@@ -375,7 +382,7 @@ STT, LLM and TTS lines go to `stt`, `llm`, `tts` by their worker category), `bro
sentence dots around it), becomes `[비밀값]`. So a secret replaced or removed later never shows on
the screen, in a copy, a file or an export, also after a restart. The values masked are the
stored secrets and the ones the running services were started with (the bot token, the MCP
servers' values; `set_secrets_in_use` on each start): a key replaced or removed while the
servers' values, the KMA key; `set_secrets_in_use` on each start): a key replaced or removed while the
services run stays masked in their late lines (the worker and MCP servers keep it until they are
restarted), until the next start gives them only the current values.
- Errors the voice worker reports to the app (`error` messages: code and request id) are always
@@ -771,6 +778,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv
| `activity_list` `{limit}` | what Jarvis did (above, "Activity"), newest first |
| `schedules_list` / `schedule_delete` `{id}` | every person's schedules (above), soonest first, with IDs as strings / delete one |
| `collect_results` `{target, limit}` | `{targets, items}`: every target folder with results, and the collected items newest first (`target` null: every target; `limit` 1-500, default 100) |
| `kma_key_status` / `kma_key_set` `{value}` | `set` and the masked form, never the key / store it (an empty value removes it); `restartNeeded` while the services run |
| `mcp_env_status` / `mcp_env_set` `{server, name, value}` | which MCP environment values are stored (`{server: {NAME: bool}}`, never the values) / store one (an empty value removes it); only for a saved server and name |
| `display_driver_status` / `display_driver_install` / `display_driver_uninstall` | the virtual monitor's driver: `{supported, installed, leftover, other, action}` (Windows only, above) / install or remove it elevated (above), then its status; refused unless the services are stopped or failed, and `service_start` / `service_restart` are refused meanwhile |
| `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it |

View File

@@ -12,7 +12,7 @@ use serde_json::{json, Map, Value};
use crate::control::{Controller, ServicesHost, State};
use crate::datadir::{free_bytes, DataDir, RECOMMENDED_FREE_BYTES};
use crate::logs::{Level, LogHub};
use crate::secrets::{masked, Secrets, DISCORD_TOKEN};
use crate::secrets::{masked, Secrets, DISCORD_TOKEN, KMA_KEY};
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -291,6 +291,19 @@ impl AdminApi {
let t = self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?;
Ok(json!({"set": t.is_some(), "masked": t.as_deref().map(masked)}))
}
"kma_key_status" => {
let k = self.secrets()?.get(KMA_KEY).map_err(|e| e.to_string())?;
Ok(json!({"set": k.is_some(), "masked": k.as_deref().map(masked)}))
}
"kma_key_set" => {
let value = arg_str(&args, "value")?.trim();
let secrets = self.secrets()?;
if value.is_empty() { secrets.remove(KMA_KEY) } else { secrets.set(KMA_KEY, value) }.map_err(|e| e.to_string())?;
self.hub.set_secrets(secrets.values());
crate::info_log!("admin", "kma key {}", if value.is_empty() { "removed" } else { "saved" });
Ok(json!({"set": !value.is_empty(), "masked": (!value.is_empty()).then(|| masked(value)),
"restartNeeded": self.controller()?.state() == crate::control::State::Running}))
}
"discord_guilds" => Ok(json!(crate::discord_setup::guilds(&self.token()?).await?)),
"discord_channels" => {
let guild: u64 = arg_str(&args, "guildId")?.parse().map_err(|_| "서버 ID가 올바르지 않습니다")?;
@@ -793,6 +806,28 @@ mod tests {
assert!(a.call("collect_results", json!({"target": "../config"})).await.is_err());
}
#[tokio::test]
async fn the_kma_key_is_stored_encrypted_shown_masked_kept_by_mcp_saves_and_removed_when_empty() {
let (a, base) = api("api-kma");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap()["set"], json!(false));
let r = a.call("kma_key_set", json!({"value": " kma-key-5678 "})).await.unwrap();
assert_eq!((r["set"].clone(), r["masked"].clone()), (json!(true), json!("••••5678")));
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap(), json!({"set": true, "masked": "••••5678"}));
if cfg!(windows) {
assert!(!String::from_utf8_lossy(&std::fs::read(data.join("config").join("secrets.dat")).unwrap()).contains("kma-key-5678"));
}
a.hub.push(Level::Error, "llm", "weather said kma-key-5678");
assert!(!a.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().contains("kma-key-5678"));
// Saving the MCP servers removes only their own values.
a.call("settings_apply", json!({"changes": {"mcpServers": []}})).await.unwrap();
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap()["set"], json!(true));
assert!(!std::fs::read_to_string(data.join("config").join("settings.json")).unwrap_or_default().contains("kma-key-5678"));
a.call("kma_key_set", json!({"value": ""})).await.unwrap();
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap(), json!({"set": false, "masked": null}));
}
#[tokio::test]
async fn mcp_values_are_stored_encrypted_shown_only_as_set_masked_in_logs_and_go_with_their_server() {
let (a, base) = api("api-mcp");

View File

@@ -9,6 +9,8 @@ use crate::datadir::write_atomic;
/// The Discord bot token's name in the store.
pub const DISCORD_TOKEN: &str = "discordToken";
/// The KMA API hub key (기상청 API허브) for the weather inside Korea.
pub const KMA_KEY: &str = "kmaApiKey";
#[derive(Debug)]
pub struct SecretsError(pub String);

View File

@@ -143,6 +143,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
// The MCP servers' environment values stay encrypted on disk: they reach the brain only in the
// worker's environment (admin.spec.md, "Features and MCP servers").
let mcp_env = crate::features::mcp_env(&secrets, &settings.mcp_servers)?;
let kma_key = secrets.get(crate::secrets::KMA_KEY)?;
let token = match stored {
Some(t) => t,
None => std::env::var("JARVIS_DISCORD_TOKEN").map_err(|_| "no bot token: set it in the app or JARVIS_DISCORD_TOKEN")?,
@@ -151,7 +152,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
// What these services are given stays masked in the logs until the next start, also if it is
// replaced or removed in the store meanwhile (admin.spec.md, "Logs").
if let Some(hub) = crate::logs::installed() {
hub.set_secrets_in_use(secrets_in_use(&token, &mcp_env));
hub.set_secrets_in_use(secrets_in_use(&token, &mcp_env, kma_key.as_deref()));
}
let (base_url, model) = llm.start(&settings).await?;
@@ -170,6 +171,9 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
}
wopts.env.insert("JARVIS_CONFIG_PATH".into(), brain_config.to_string_lossy().into_owned());
wopts.env.insert(crate::features::MCP_ENV_VAR.into(), mcp_env.to_string());
if let Some(k) = &kma_key {
wopts.env.insert(KMA_ENV_VAR.into(), k.clone());
}
if let BrowserRun::Running(b, _) = &browser {
wopts.env.insert("JARVIS_BROWSER_CDP".into(), b.cdp_url());
}
@@ -238,6 +242,8 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
/// The voice worker writes its recordings where this names (voice_worker.spec.md, "Recordings").
pub const RECORDINGS_ENV_VAR: &str = "JARVIS_RECORDINGS_DIR";
/// The stored KMA key reaches the brain's weather tool only in the worker's environment.
pub const KMA_ENV_VAR: &str = "JARVIS_KMA_API_KEY";
/// Where the voice worker keeps its recordings, when `voice.record` is on.
pub fn recordings_dir(data_dir: &Path, settings: &crate::settings::Settings) -> Option<std::path::PathBuf> {
@@ -349,8 +355,9 @@ async fn perf_loop(settings: crate::settings::Settings, llm: Arc<Llm>, brain: Ar
/// The secret values the services get: the bot token and the MCP servers' environment values.
pub fn secrets_in_use(token: &str, mcp_env: &Value) -> Vec<String> {
pub fn secrets_in_use(token: &str, mcp_env: &Value, kma_key: Option<&str>) -> Vec<String> {
let mut v = vec![token.to_owned()];
v.extend(kma_key.map(str::to_owned));
for vars in mcp_env.as_object().into_iter().flat_map(|m| m.values()) {
v.extend(vars.as_object().into_iter().flat_map(|m| m.values()).filter_map(Value::as_str).map(str::to_owned));
}
@@ -588,11 +595,12 @@ mod tests {
use super::*;
#[test]
fn the_services_secrets_are_the_token_and_every_mcp_value() {
fn the_services_secrets_are_the_token_every_mcp_value_and_the_kma_key() {
let env = serde_json::json!({"brave": {"BRAVE_API_KEY": "k1"}, "other": {"A": "k2", "B": "k3"}});
let mut v = secrets_in_use("tok", &env);
let mut v = secrets_in_use("tok", &env, Some("kma"));
v.sort();
assert_eq!(v, vec!["k1", "k2", "k3", "tok"]);
assert_eq!(v, vec!["k1", "k2", "k3", "kma", "tok"]);
assert_eq!(secrets_in_use("tok", &env, None).len(), 4);
}
#[test]

View File

@@ -685,6 +685,28 @@ async function tokenCard() {
} }, "확인 후 저장")), out);
}
/** The KMA API hub key for the weather inside Korea: typed here, stored encrypted, only shown masked. */
async function kmaKeyCard() {
const label = h("span");
const input = h("input", { type: "password", placeholder: "기상청 API허브 인증키", autocomplete: "off" });
const clear = h("button", { class: "btn" }, "키 지우기");
const show = (st) => { label.textContent = st.set ? st.masked : "저장된 키 없음"; clear.hidden = !st.set; };
const put = async (value) => {
try {
const r = await api("kma_key_set", { value });
input.value = "";
show(r);
toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다.");
} catch (e) { fail(e); }
};
clear.onclick = () => put("");
show(await api("kma_key_status"));
return h("div", { class: "card" }, h("h2", {}, "기상청 날씨"),
h("p", { class: "small muted" }, "기상청 API허브(apihub.kma.go.kr) 인증키를 넣으면 한국 안의 현재 날씨를 기상청에서 받습니다. 키가 없거나 기상청이 답하지 않으면 open-meteo, met.no 순서로 받습니다. API허브에서 단기예보의 초단기실황조회와 초단기예보조회를 활용신청해야 합니다."),
h("div", { class: "row" }, label, input,
h("button", { class: "btn", onclick: () => input.value.trim() ? put(input.value) : toast("키를 입력해 주세요", true) }, "저장"), clear));
}
/** The virtual monitor's driver for "봇용 크롬창 화면공유 선택 표시" (Windows only). */
async function displayDriverCard() {
const st = await api("display_driver_status");
@@ -991,7 +1013,7 @@ async function show(name) {
const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능",
collect: "백그라운드 수집", game: "게임 모드", schedule: "예약", pcControl: "PC 제어", app: "앱" };
const update = name === "app" ? updateCard() : null;
const extra = name === "bot" ? await tokenCard() : name === "features" ? await displayDriverCard()
const extra = name === "bot" ? await tokenCard() : name === "features" ? h("div", {}, await kmaKeyCard(), await displayDriverCard())
: name === "app" ? h("div", {}, update.view, h("div", { class: "hint", style: "margin:12px 0" }, "트레이로 최소화하면 창만 숨고 봇과 서비스는 계속 돕니다. 작업 표시줄 오른쪽의 Jarvis 아이콘을 누르면 창이 다시 열리고, 아이콘의 오른쪽 클릭 메뉴에서 완전 종료할 수 있습니다. 저장하면 바로 적용됩니다.")) : null;
const view = await settingsScreen(name, titles[name], extra);
if (name === "collect") view.append(await collectResults());

View File

@@ -0,0 +1,25 @@
"""
Eval: a district the user names reaches getWeather whole ("부산 연제구"), not only its city.
getWeather finds districts on OpenStreetMap (2026-11-18), so the place argument must keep
the district for the answer to be about that spot.
Run: EVAL_JUDGE_MODEL=qwen3:8b ./scripts/run_evals.sh weather_district_place
"""
import pytest
from conftest import requires_judge_llm
from test_weather_forecast_days import _ask
@pytest.mark.eval
@requires_judge_llm
@pytest.mark.parametrize("query,district", [
("부산 연제구 날씨 어때?", "연제"),
("서울 강남구 내일 날씨 알려 줘", "강남"),
])
def test_the_district_is_in_the_place(mock_config, eval_db, eval_dialogue_memory, query, district):
args = _ask(mock_config, eval_db, eval_dialogue_memory, query)
assert args is not None, "getWeather was not called"
assert district in (args.get("location") or ""), args

View File

@@ -0,0 +1,78 @@
"""
Eval: a question about a later day reaches getWeather as that day (days_ahead/days).
Before getWeather took days_ahead/days (2026-11-18), "내일 날씨 어때?" was answered
with the weather now. The model counts the days from today's date in the context:
tomorrow is 1, this weekend is the coming Saturday with 2 days, and a plain
question about the weather stays the weather now (no days_ahead or 0).
Runs like the v2 brain (compact prompt, intent judge, Korean replies).
Run: EVAL_JUDGE_MODEL=qwen3:8b ./scripts/run_evals.sh weather_forecast_days
"""
from datetime import date
from unittest.mock import patch
import pytest
from conftest import requires_judge_llm
from helpers import JUDGE_BASE_URL, ToolCallCapture, create_mock_tool_run
def _ask(mock_config, eval_db, eval_dialogue_memory, query):
from helpers import JUDGE_MODEL
from jarvis.memory.history import HistoryContext
from jarvis.reply import turn_state
from jarvis.reply.engine import run_reply_engine
mock_config.ollama_base_url = JUDGE_BASE_URL
mock_config.ollama_chat_model = JUDGE_MODEL
capture = ToolCallCapture()
turn_state.reset()
try:
with patch('jarvis.reply.engine.run_tool_with_retries', side_effect=create_mock_tool_run(capture, {
"getWeather": "서울 날씨는 맑음, 최저 -1도, 최고 4도, 강수확률 0%입니다.",
})), patch('jarvis.reply.engine.get_location_context_with_timezone',
return_value=("Location: Seoul, South Korea", None)):
reply = run_reply_engine(db=eval_db, cfg=mock_config, tts=None, text=query,
dialogue_memory=eval_dialogue_memory, history=HistoryContext(),
legacy_memory=False, default_language="Korean",
compact_prompt=True, intent_judge=True)
finally:
turn_state.reset()
args = capture.get_args("getWeather")
print(f"\n forecast days [{JUDGE_MODEL}] {query!r}: tools={capture.tool_names()} "
f"args={args} reply={(reply or '')[:160]!r}")
return args
def _num(args, name):
try:
return int(float((args or {}).get(name) or 0))
except (TypeError, ValueError):
return 0
@pytest.mark.eval
@requires_judge_llm
class TestWeatherForecastDays:
@pytest.mark.parametrize("query", ["내일 날씨 어때?", "what's the weather tomorrow?"])
def test_tomorrow_is_one_day_ahead(self, mock_config, eval_db, eval_dialogue_memory, query):
args = _ask(mock_config, eval_db, eval_dialogue_memory, query)
assert args is not None, "getWeather was not called"
assert _num(args, "days_ahead") == 1, args
def test_the_weekend_is_the_coming_saturday_and_sunday(self, mock_config, eval_db, eval_dialogue_memory):
today = date.today()
if today.weekday() >= 5:
pytest.skip("on a weekend day 'this weekend' has two readings")
args = _ask(mock_config, eval_db, eval_dialogue_memory, "이번 주말 날씨 어때?")
assert args is not None, "getWeather was not called"
assert _num(args, "days_ahead") == 5 - today.weekday(), args
assert _num(args, "days") >= 2, args
def test_the_weather_now_stays_now(self, mock_config, eval_db, eval_dialogue_memory):
args = _ask(mock_config, eval_db, eval_dialogue_memory, "지금 날씨 어때?")
assert args is not None, "getWeather was not called"
assert _num(args, "days_ahead") == 0 and _num(args, "days") <= 1, args

View File

@@ -1,4 +1,9 @@
"""Weather tool implementation using Open-Meteo API (free, no API key required)."""
"""Weather tool: KMA inside Korea when the app gives a key, else Open-Meteo (no key), then met.no."""
import math
import os
from collections import Counter
from datetime import datetime, timedelta, timezone
import requests
from typing import Dict, Any, Optional
@@ -202,6 +207,28 @@ _MET_NO_URL = "https://api.met.no/weatherapi/locationforecast/2.0/compact"
_MET_NO_HEADERS = {"User-Agent": "jarvis-voice-assistant/2 github.com/isair/jarvis"}
# OpenStreetMap's place search: any language, down to districts (부산 연제구), which open-meteo's
# geocoder (cities, Latin spellings) does not know. Its policy asks for an identifying User-Agent.
_NOMINATIM_URL = "https://nominatim.openstreetmap.org/search"
def _osm_place(name: str) -> Optional[Dict[str, Any]]:
"""The place OpenStreetMap finds for a name: {'lat', 'lon', 'country_code'}; None if none or on failure."""
try:
resp = requests.get(_NOMINATIM_URL, headers=_MET_NO_HEADERS, timeout=_OPEN_METEO_TIMEOUT_SEC,
params={"q": name, "format": "jsonv2", "limit": 1, "addressdetails": 1})
resp.raise_for_status()
found = resp.json()
if not isinstance(found, list) or not found:
return None
place = found[0]
code = ((place.get("address") or {}).get("country_code") or "").upper() or None
return {"lat": float(place["lat"]), "lon": float(place["lon"]), "country_code": code}
except Exception as e:
debug_log(f" ⚠️ OpenStreetMap place search failed ({type(e).__name__})", "tools")
return None
def _met_no_wmo(symbol: str) -> Optional[int]:
"""The WMO code closest to a met.no symbol code ('lightrainshowers_night' -> 80)."""
s = (symbol or "").split("_")[0]
@@ -246,6 +273,266 @@ def _met_no_current(lat: float, lon: float) -> Dict[str, Any]:
return {}
# KMA (기상청 API허브): current weather inside Korea when the app gives a key (admin.spec.md).
KMA_KEY_ENV = "JARVIS_KMA_API_KEY"
_KMA_API = "https://apihub.kma.go.kr/api/typ02/openApi/"
_KMA_URL = _KMA_API + "VilageFcstInfoService_2.0/"
_KMA_MID_URL = _KMA_API + "MidFcstInfoService/"
_KMA_TIMEOUT_SEC = 5
_KST = timezone(timedelta(hours=9))
# KMA's own words: PTY (precipitation type, 0 = none) wins over SKY (sky state).
_KMA_PTY_KO = {1: "비", 2: "비나 눈", 3: "눈", 5: "빗방울", 6: "빗방울과 눈날림", 7: "눈날림"}
_KMA_PTY_WMO = {1: 63, 2: 69, 3: 73, 5: 51, 6: 68, 7: 71}
_KMA_SKY_KO = {1: "맑음", 3: "구름 많음", 4: "흐림"}
_KMA_SKY_WMO = {1: 0, 3: 2, 4: 3}
_kma_key = ""
# 중기예보 places: (getMidTa city, lat, lon); getMidLandFcst's region comes from the city's code.
# Every code checked live against KMA on 2026-11-18.
_KMA_MID_CITIES = (
("11B10101", 37.5665, 126.9780), ("11B20201", 37.4563, 126.7052), ("11B20601", 37.2636, 127.0286),
("11B20305", 37.7599, 126.7800), ("11B20701", 37.2720, 127.4350), ("11B20606", 36.9921, 127.1129),
("11D10301", 37.8813, 127.7298), ("11D10401", 37.3422, 127.9202), ("11D20501", 37.7519, 128.8761),
("11D20401", 38.2070, 128.5918), ("11C20401", 36.3504, 127.3845), ("11C20404", 36.4800, 127.2890),
("11C20104", 36.6013, 126.6608), ("11C20101", 36.7845, 126.4503), ("11C20301", 36.8151, 127.1139),
("11C10301", 36.6424, 127.4890), ("11C10101", 36.9910, 127.9259), ("11F10201", 35.8242, 127.1480),
("21F10501", 35.9676, 126.7369), ("11F20501", 35.1595, 126.8526), ("21F20801", 34.8118, 126.3922),
("11F20401", 34.7604, 127.6622), ("11F20405", 34.9507, 127.4872), ("11H10701", 35.8714, 128.6014),
("11H10501", 36.5684, 128.7294), ("11H10201", 36.0190, 129.3435), ("11H20201", 35.1796, 129.0756),
("11H20101", 35.5384, 129.3114), ("11H20301", 35.2280, 128.6811), ("11H20701", 35.1800, 128.1076),
("11G00201", 33.4996, 126.5312), ("11G00401", 33.2541, 126.5600),
)
_KMA_MID_REGIONS = {"11B": "11B00000", "11D1": "11D10000", "11D2": "11D20000", "11C1": "11C10000",
"11C2": "11C20000", "11F1": "11F10000", "11F2": "11F20000", "11H1": "11H10000",
"11H2": "11H20000", "11G": "11G00000"}
# A forecast goes this many days ahead (KMA 중기예보's last day).
MAX_DAYS_AHEAD = 10
_WEEKDAYS_KO = "월화수목금토일"
_DAY_NAMES_KO = {0: "오늘", 1: "내일", 2: "모레"}
def _now() -> datetime:
return datetime.now(_KST)
def take_kma_key() -> None:
"""Keep the app's KMA key here and take it out of the environment, so no child process
(MCP servers, MeloTTS) inherits it. Without a call the environment is read on each request."""
global _kma_key
_kma_key = os.environ.pop(KMA_KEY_ENV, "").strip()
def _kma_key_now() -> str:
return _kma_key or os.environ.get(KMA_KEY_ENV, "").strip()
def _kma_grid(lat: float, lon: float) -> tuple:
"""KMA's 5 km forecast grid point (nx, ny) for a place (the Lambert conformal conic of KMA's guide)."""
re_, grid = 6371.00877 / 5.0, math.radians(1)
slat1, slat2, olon, olat = 30 * grid, 60 * grid, 126 * grid, 38 * grid
sn = math.log(math.cos(slat1) / math.cos(slat2)) / math.log(
math.tan(math.pi / 4 + slat2 / 2) / math.tan(math.pi / 4 + slat1 / 2))
sf = math.tan(math.pi / 4 + slat1 / 2) ** sn * math.cos(slat1) / sn
ro = re_ * sf / math.tan(math.pi / 4 + olat / 2) ** sn
ra = re_ * sf / math.tan(math.pi / 4 + lat * grid / 2) ** sn
theta = lon * grid - olon
theta = (theta + math.pi) % (2 * math.pi) - math.pi
theta *= sn
return int(ra * math.sin(theta) + 43 + 0.5), int(ro - ra * math.cos(theta) + 136 + 0.5)
def _kma_get(url: str, key: str, params: Dict[str, Any]) -> list:
"""One KMA call's items; raises on any failure. The key is in the URL: never log the error text."""
resp = requests.get(url, timeout=_KMA_TIMEOUT_SEC, params={
"pageNo": 1, "numOfRows": 100, "dataType": "JSON", **params, "authKey": key})
resp.raise_for_status()
body = (resp.json() or {}).get("response") or {}
code = (body.get("header") or {}).get("resultCode")
if code != "00":
raise ValueError(f"KMA result code {code}")
return ((body.get("body") or {}).get("items") or {}).get("item") or []
def _kma_items(service: str, key: str, base: datetime, nx: int, ny: int, rows: int = 100) -> list:
return _kma_get(_KMA_URL + service, key, {"numOfRows": rows, "base_date": base.strftime("%Y%m%d"),
"base_time": base.strftime("%H%M"), "nx": nx, "ny": ny})
def _kma_failed(what: str, e: Exception) -> None:
why = str(e) if isinstance(e, (ValueError, KeyError)) else type(e).__name__
debug_log(f"KMA {what} failed ({why}); using open-meteo", "tools")
def _kma_half(cats: Dict[str, Dict[str, str]], pm: bool) -> Optional[str]:
"""Half a day's weather from 단기예보's hours: the commonest precipitation if any, else the commonest
(on a tie the cloudier) sky. None when the forecast has no hour of that half left."""
times = [t for t in cats.get("SKY", {}) if (t >= "1200") == pm]
if not times:
return None
wet = [p for p in (int(float(cats.get("PTY", {}).get(t, 0))) for t in times) if p in _KMA_PTY_KO]
if wet:
return _KMA_PTY_KO[Counter(wet).most_common(1)[0][0]]
skies = Counter(int(float(cats["SKY"][t])) for t in times)
return _KMA_SKY_KO.get(max(skies, key=lambda v: (skies[v], v)))
def _kma_short_days(lat: float, lon: float, key: str, now: datetime, offsets: list) -> Dict[int, Dict[str, Any]]:
"""단기예보 (out about 10 minutes after 02, 05, ..., 23 h) for the days it covers: today to 3 days ahead."""
t = now - timedelta(minutes=15)
hours = [h for h in (2, 5, 8, 11, 14, 17, 20, 23) if h <= t.hour]
base = (t.replace(hour=hours[-1]) if hours else (t - timedelta(days=1)).replace(hour=23)).replace(
minute=0, second=0, microsecond=0)
nx, ny = _kma_grid(lat, lon)
by_date: Dict[str, Dict[str, Dict[str, str]]] = {}
for i in _kma_items("getVilageFcst", key, base, nx, ny, rows=1500):
by_date.setdefault(i.get("fcstDate"), {}).setdefault(i.get("category"), {})[i.get("fcstTime")] = i.get("fcstValue")
out = {}
for off in offsets:
date = now.date() + timedelta(days=off)
cats = by_date.get(date.strftime("%Y%m%d")) or {}
if not (cats.get("TMN") or cats.get("TMX")): # a day the forecast does not (fully) cover
continue
temps = [float(v) for v in cats.get("TMP", {}).values()]
lo = float(next(iter(cats["TMN"].values()))) if cats.get("TMN") else min(temps, default=None)
hi = float(next(iter(cats["TMX"].values()))) if cats.get("TMX") else max(temps, default=None)
out[off] = {"date": date, "am": _kma_half(cats, False), "pm": _kma_half(cats, True), "min": lo,
"max": hi, "pop": max((int(float(v)) for v in cats.get("POP", {}).values()), default=None)}
return out
def _kma_mid_days(lat: float, lon: float, key: str, now: datetime, offsets: list) -> Dict[int, Dict[str, Any]]:
"""중기예보 (out about 30 minutes after 06 and 18 h) for the nearest KMA city and its region; its days
are counted from the day it came out, up to 10 days ahead."""
t = now - timedelta(minutes=30)
base = (t.replace(hour=18) if t.hour >= 18 else t.replace(hour=6) if t.hour >= 6
else (t - timedelta(days=1)).replace(hour=18)).replace(minute=0, second=0, microsecond=0)
city = min(_KMA_MID_CITIES, key=lambda c: (c[1] - lat) ** 2 + ((c[2] - lon) * math.cos(math.radians(lat))) ** 2)[0]
region = _KMA_MID_REGIONS.get(city[:3]) or _KMA_MID_REGIONS["11" + city[2:4]]
tm_fc = base.strftime("%Y%m%d%H%M")
ta = _kma_get(_KMA_MID_URL + "getMidTa", key, {"regId": city, "tmFc": tm_fc})[0]
land = _kma_get(_KMA_MID_URL + "getMidLandFcst", key, {"regId": region, "tmFc": tm_fc})[0]
out = {}
for off in offsets:
date = now.date() + timedelta(days=off)
n = (date - base.date()).days
am = land.get(f"wf{n}Am") or land.get(f"wf{n}")
pops = [p for p in (land.get(f"rnSt{n}Am"), land.get(f"rnSt{n}Pm"), land.get(f"rnSt{n}")) if p is not None]
if am is None and ta.get(f"taMax{n}") is None:
continue
out[off] = {"date": date, "am": am, "pm": land.get(f"wf{n}Pm") or am, "min": ta.get(f"taMin{n}"),
"max": ta.get(f"taMax{n}"), "pop": max(pops) if pops else None}
return out
def _kma_days(lat: float, lon: float, key: str, offsets: list) -> Dict[int, Dict[str, Any]]:
"""KMA's forecast for each day it has: 단기예보 first, 중기예보 for the rest; {} on failure."""
now = _now().astimezone(_KST)
out: Dict[int, Dict[str, Any]] = {}
if any(off <= 3 for off in offsets):
try:
out.update(_kma_short_days(lat, lon, key, now, offsets))
except Exception as e:
_kma_failed("short-term forecast", e)
rest = [off for off in offsets if off not in out]
if any(off >= 3 for off in rest):
try:
out.update(_kma_mid_days(lat, lon, key, now, rest))
except Exception as e:
_kma_failed("mid-term forecast", e)
return out
def _open_meteo_days(lat: float, lon: float, offsets: list) -> Dict[int, Dict[str, Any]]:
"""open-meteo's daily forecast (the place's own days) for the given days; {} on failure."""
try:
resp = requests.get("https://api.open-meteo.com/v1/forecast", timeout=_OPEN_METEO_TIMEOUT_SEC, params={
"latitude": lat, "longitude": lon, "timezone": "auto", "forecast_days": max(offsets) + 1,
"daily": "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"})
resp.raise_for_status()
daily = (resp.json() or {}).get("daily") or {}
except Exception as e:
debug_log(f"open-meteo daily forecast failed ({type(e).__name__})", "tools")
return {}
def at(name: str, off: int):
values = daily.get(name) or []
return values[off] if off < len(values) else None
out = {}
for off in offsets:
code, date = at("weather_code", off), at("time", off)
if date is None or (code is None and at("temperature_2m_max", off) is None):
continue
ko = WMO_CODES_KO.get(code) if code is not None else None
out[off] = {"date": datetime.fromisoformat(date).date(), "am": ko, "pm": ko,
"min": at("temperature_2m_min", off), "max": at("temperature_2m_max", off),
"pop": at("precipitation_probability_max", off)}
return out
def _day_span(args: Optional[Dict[str, Any]]) -> tuple:
"""(first, last) day asked for, counted from today: (0, 0) is the weather now."""
def num(name: str, default: int) -> int:
try:
return int(float((args or {}).get(name)))
except (TypeError, ValueError):
return default
first = min(max(num("days_ahead", 0), 0), MAX_DAYS_AHEAD)
return first, min(first + max(num("days", 1), 1) - 1, MAX_DAYS_AHEAD)
def _day_sentence(off: int, day: Dict[str, Any], place: str) -> str:
"""'내일(11월 19일 목요일) 서울 날씨는 오전 맑음, 오후 비, 최저 -1도, 최고 4도, 강수확률 60%입니다.'"""
d = day["date"]
when = f"{d.month}월 {d.day}일 {_WEEKDAYS_KO[d.weekday()]}요일"
if off in _DAY_NAMES_KO:
when = f"{_DAY_NAMES_KO[off]}({when})"
am, pm = day.get("am"), day.get("pm")
parts = [f"오전 {am}, 오후 {pm}" if am and pm and am != pm else am or pm]
if day.get("min") is not None:
parts.append(f"최저 {round(float(day['min']))}도")
if day.get("max") is not None:
parts.append(f"최고 {round(float(day['max']))}도")
if day.get("pop") is not None:
parts.append(f"강수확률 {round(float(day['pop']))}%")
return f"{when} {place} 날씨는 " + ", ".join(p for p in parts if p) + "입니다."
def _kma_current(lat: float, lon: float, key: str, now: Optional[datetime] = None) -> Dict[str, Any]:
"""Current weather from KMA in open-meteo's 'current' keys plus 'condition_ko'; {} on failure.
초단기실황 (each hour's observation, out at about :40) gives the temperature, humidity, wind and
precipitation; it has no sky state, so 초단기예보 (out at about :45) gives the coming hour's SKY.
"""
now = (now or datetime.now(_KST)).astimezone(_KST)
nx, ny = _kma_grid(lat, lon)
try:
obs_base = (now - timedelta(minutes=40)).replace(minute=0, second=0, microsecond=0)
obs = {i.get("category"): i.get("obsrValue") for i in _kma_items("getUltraSrtNcst", key, obs_base, nx, ny)}
fc_base = (now - timedelta(minutes=45)).replace(minute=30, second=0, microsecond=0)
sky = sorted((i.get("fcstDate", "") + i.get("fcstTime", ""), i.get("fcstValue"))
for i in _kma_items("getUltraSrtFcst", key, fc_base, nx, ny) if i.get("category") == "SKY")
temp, pty, sky_v = float(obs["T1H"]), int(float(obs.get("PTY") or 0)), int(sky[0][1]) if sky else None
if pty in _KMA_PTY_KO:
ko, wmo = _KMA_PTY_KO[pty], _KMA_PTY_WMO[pty]
elif sky_v in _KMA_SKY_KO:
ko, wmo = _KMA_SKY_KO[sky_v], _KMA_SKY_WMO[sky_v]
else:
raise ValueError("KMA gave no sky state")
wind = obs.get("WSD")
return {
"temperature_2m": temp,
"apparent_temperature": None,
"relative_humidity_2m": float(obs["REH"]) if obs.get("REH") is not None else None,
"weather_code": wmo,
"condition_ko": ko,
"wind_speed_10m": round(float(wind) * 3.6, 1) if wind is not None else None,
}
except Exception as e:
why = str(e) if isinstance(e, (ValueError, KeyError)) else type(e).__name__
debug_log(f"KMA failed ({why}); using open-meteo", "tools")
return {}
class WeatherTool(Tool):
"""Tool for getting current weather using Open-Meteo API."""
@@ -259,6 +546,10 @@ class WeatherTool(Tool):
"Weather only (current + forecast). NOT for time-of-day, date, or "
"location questions — those are already in the assistant's context. "
"Use for ANY weather question: now, later today, tomorrow, this week. "
"For another day set days_ahead, the days from today's date in the "
"context to that day (tomorrow 1, up to 10), and days for more than one "
"day: a weekend is days_ahead to the coming Saturday with days 2, a week "
"is days 7. "
"Set location to the place the user asked about. If they named none, "
"set it to where the user has said they are, from the conversation or "
"what you remember about them. Otherwise leave it empty: the tool "
@@ -274,6 +565,14 @@ class WeatherTool(Tool):
"location": {
"type": "string",
"description": "City name or location (e.g., 'London', 'New York', 'Tokyo'): the place the user asked about, or else where the user has said they are (the conversation or your memory of them). Omit otherwise; the tool then auto-detects the user's location. Never ask the user for this argument."
},
"days_ahead": {
"type": "integer",
"description": "Days from today's date in the context to the day asked about: omit or 0 for now, 1 for tomorrow, 2 for the day after, up to 10. For a weekday count from today's weekday (on a Wednesday the coming Saturday is 3)."
},
"days": {
"type": "integer",
"description": "How many days from days_ahead on (default 1): 2 for a weekend (Saturday and Sunday), 7 for a week."
}
},
"required": []
@@ -318,13 +617,33 @@ class WeatherTool(Tool):
display_name = ", ".join(display_parts) if display_parts else "your location"
return {"lat": lat, "lon": lon, "display_name": display_name}
return {"lat": lat, "lon": lon, "display_name": display_name,
"country_code": location_info.get("country_code")}
except Exception as e:
debug_log(f" ⚠️ location detection error: {e}", "tools")
return None
@staticmethod
def _forecast_lines(lat: float, lon: float, country_code: Optional[str], first: int, last: int,
location_display: str) -> list:
"""A sentence for each day from first to last that a forecast has: KMA inside Korea with the
app's key, open-meteo for the days KMA does not give."""
offsets = list(range(first, last + 1))
days: Dict[int, Dict[str, Any]] = {}
kma_key = _kma_key_now()
if kma_key and country_code == "KR":
days = _kma_days(lat, lon, kma_key, offsets)
from_kma = len(days)
rest = [off for off in offsets if off not in days]
if rest:
days.update(_open_meteo_days(lat, lon, rest))
debug_log(f" 🌤️ forecast days {first}-{last}: {from_kma} from KMA, "
f"{len(days) - from_kma} from open-meteo", "tools")
place = location_display.split(",")[0].strip() or location_display
return [_day_sentence(off, days[off], place) for off in offsets if off in days]
def run(self, args: Optional[Dict[str, Any]], context: ToolContext) -> ToolExecutionResult:
"""Get current weather for a location."""
"""Get the weather now, or the forecast for the days asked about, for a location."""
context.user_print("🌤️ Checking weather...")
try:
@@ -339,6 +658,7 @@ class WeatherTool(Tool):
lat: Optional[float] = None
lon: Optional[float] = None
location_display: str = ""
country_code: Optional[str] = None
# Track whether we inferred the place name from the user's text
# rather than receiving it from the caller — used only for the
@@ -359,6 +679,7 @@ class WeatherTool(Tool):
lat = user_loc["lat"]
lon = user_loc["lon"]
location_display = user_loc["display_name"]
country_code = user_loc.get("country_code")
debug_log(
f" 📍 using detected location: {location_display} ({lat}, {lon})",
"tools",
@@ -409,13 +730,24 @@ class WeatherTool(Tool):
"format": "json"
}
geo_response = requests.get(geocode_url, params=geocode_params, timeout=10)
geo_response.raise_for_status()
geo_data = geo_response.json()
# Open-Meteo knows cities only, in Latin spellings, and matches a
# non-Latin name loosely (live 2026-11-18: "부산" gave a village
# called Pusan 140 km away). A non-Latin name, and a Latin one
# open-meteo does not know (a district), is looked up on
# OpenStreetMap in the words the user used.
geo_data: Dict[str, Any] = {}
if location_str.isascii():
geo_response = requests.get(geocode_url, params=geocode_params, timeout=10)
geo_response.raise_for_status()
geo_data = geo_response.json()
osm = None if geo_data.get("results") else _osm_place(location_str)
if osm:
debug_log(" 📍 found on OpenStreetMap", "tools")
geo_data = {"results": [{"latitude": osm["lat"], "longitude": osm["lon"],
"name": location_str, "country_code": osm["country_code"]}]}
# Open-Meteo only matches Latin spellings, so a non-Latin name
# (e.g. Korean "서울") returns nothing. Retry once with an
# LLM-romanised name before giving up.
# Not on OpenStreetMap either (or it failed): retry open-meteo
# once with an LLM-romanised name before giving up.
if not geo_data.get("results"):
romanised = _romanise_place(location_str, getattr(context, "cfg", None))
if romanised:
@@ -456,6 +788,7 @@ class WeatherTool(Tool):
place_name = place.get("name", location_str)
country = place.get("country", "")
admin1 = place.get("admin1", "") # State/region
country_code = place.get("country_code")
# Build display name
location_display = place_name
@@ -466,6 +799,17 @@ class WeatherTool(Tool):
debug_log(f" 📍 resolved to {location_display} ({lat}, {lon})", "tools")
first, last = _day_span(args)
if first > 0:
lines = self._forecast_lines(lat, lon, country_code, first, last, location_display)
if not lines:
return ToolExecutionResult(
success=False,
reply_text=f"Weather forecast temporarily unavailable for {location_display}."
)
context.user_print(f"✅ Forecast for {location_display.split(',')[0].strip()}")
return ToolExecutionResult(success=True, reply_text="\n".join(lines))
# Step 2: Get current weather + forecast
weather_url = "https://api.open-meteo.com/v1/forecast"
weather_params = {
@@ -480,15 +824,22 @@ class WeatherTool(Tool):
"timezone": "auto"
}
try:
weather_response = requests.get(weather_url, params=weather_params,
timeout=_OPEN_METEO_TIMEOUT_SEC)
weather_response.raise_for_status()
current = (weather_response.json() or {}).get("current", {})
except Exception as e:
# Live 2026-11-18: the forecast server stopped answering while geocoding worked.
debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools")
current = _met_no_current(lat, lon)
current: Dict[str, Any] = {}
kma_key = _kma_key_now()
if kma_key and country_code == "KR":
current = _kma_current(lat, lon, kma_key)
if current:
debug_log(" 🌤️ current weather from KMA", "tools")
if not current:
try:
weather_response = requests.get(weather_url, params=weather_params,
timeout=_OPEN_METEO_TIMEOUT_SEC)
weather_response.raise_for_status()
current = (weather_response.json() or {}).get("current", {})
except Exception as e:
# Live 2026-11-18: the forecast server stopped answering while geocoding worked.
debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools")
current = _met_no_current(lat, lon)
if not current:
return ToolExecutionResult(
success=False,
@@ -514,7 +865,7 @@ class WeatherTool(Tool):
# tool result is normally re-synthesised by the LLM, but a small
# model rambles and leaks °F / CJK fragments, so we hand it a clean
# Korean sentence it can echo verbatim (one-sentence system rule).
_ko = WMO_CODES_KO.get(weather_code, weather_desc)
_ko = current.get("condition_ko") or WMO_CODES_KO.get(weather_code, weather_desc)
_short_loc = location_display.split(",")[0].strip() or location_display
_ko_parts = [f"지금 {_short_loc} 날씨는 {_ko}"]
if temp_c is not None:
@@ -528,6 +879,8 @@ class WeatherTool(Tool):
# for the model to echo ("25도 Celsius"), no forecast firehose to
# ramble over. The model just echoes this one sentence.
lines = [ko_sentence]
if last > 0: # "this week": now, then each day
lines += self._forecast_lines(lat, lon, country_code, 0, last, location_display)
reply_text = "\n".join(lines)

View File

@@ -38,10 +38,12 @@ def main() -> int:
print("JARVIS_VOICE_TOKEN is not set", file=sys.stderr)
return 2
# The MCP servers' secrets leave the environment before any child process (MeloTTS) starts;
# The MCP servers' secrets and the KMA key leave the environment before any child process (MeloTTS) starts;
# only the brain gets them (voice_worker.spec.md, "Tools").
from .brain import take_mcp_env
mcp_env = take_mcp_env()
from jarvis.tools.builtin.weather import take_kma_key
take_kma_key()
from .server import VoiceWorker, is_loopback, nvidia_card
from .stt_whisper import WhisperTranscriber

View File

@@ -288,6 +288,19 @@ which carry Discord's own time.
environment at start, before any child process (MeloTTS) runs, hands it to the brain, and the
brain adds each server's values to that server's environment only. Each server's outcome is printed without debug logging (category `llm`):
`MCP server <name>: <n> tool(s)`, or `Warning: MCP server <name> failed: <reason>`.
The KMA key (`JARVIS_KMA_API_KEY`, `app/src/admin.spec.md`) leaves the environment at the same
point; the weather tool keeps it and uses it only for the weather inside Korea (geocoded or
detected country `KR`). Now: KMA's 초단기실황 (temperature, humidity, wind, precipitation) and
초단기예보 (the coming hour's sky). A later day (`getWeather` `days_ahead`, 1 to 10, and `days`
for a span such as a weekend): 단기예보 for today to 3 days ahead (the morning's and the
afternoon's commonest precipitation or sky, the day's lowest and highest, the highest chance of
rain), then 중기예보 for the nearest of the KMA cities in `weather.py` and its region (중기기온,
중기육상). Days KMA does not give, and every KMA failure, come from open-meteo (now: then
met.no; later days: open-meteo's daily forecast only). The key is in KMA's URLs, so a failure is
logged by its kind only. The place is found by open-meteo's geocoder (cities, Latin spellings)
or OpenStreetMap's Nominatim (any language, down to districts such as 부산 연제구; a non-Latin
name goes there first, since open-meteo matches it loosely); only the place name is sent, with
the app's User-Agent, and the answer names the place in the user's own words.
- `prepare` tells the brain that `user` is saying a call whose partial transcript is `text` (the app
sends it while the speaker is still talking, `app/src/conversation.spec.md`). The brain runs the
intent judge's tool pick for it on its own thread, with the asker's dialogue memory and the tool

View File

@@ -3,6 +3,7 @@
import pytest
from unittest.mock import Mock, patch
import requests
from datetime import datetime, timedelta, timezone
from src.jarvis.tools.builtin.weather import (
WeatherTool,
@@ -106,16 +107,13 @@ class TestWeatherTool:
def test_run_non_latin_location_romanises_and_retries(self, mock_get, mock_romanise):
"""A Korean city name Open-Meteo can't geocode is romanised and retried.
Open-Meteo's geocoder only matches Latin spellings, so ``서울`` returns
no results. The tool must romanise to ``Seoul`` and retry rather than
Open-Meteo's geocoder only matches Latin spellings, so ``서울`` is first
looked up on OpenStreetMap (any language). When that finds nothing,
the tool must romanise to ``Seoul`` and retry rather than
dead-ending with "could not find location" (the failure the Korean-
locked deployment hit on every weather request)."""
mock_romanise.return_value = "Seoul"
geo_empty = Mock()
geo_empty.raise_for_status = Mock()
geo_empty.json.return_value = {} # no "results"
geo_seoul = Mock()
geo_seoul.raise_for_status = Mock()
geo_seoul.json.return_value = {
@@ -153,14 +151,16 @@ class TestWeatherTool:
},
}
mock_get.side_effect = [geo_empty, geo_seoul, weather_response]
osm_empty = Mock(raise_for_status=Mock())
osm_empty.json.return_value = []
mock_get.side_effect = [osm_empty, geo_seoul, weather_response]
result = self.tool.run({"location": "서울"}, self.context)
assert result.success is True
assert "Seoul" in result.reply_text
mock_romanise.assert_called_once()
# The romanised name must be what the second geocode actually queried.
# The romanised name must be what the geocode actually queried.
assert mock_get.call_args_list[1].kwargs["params"]["name"] == "Seoul"
@patch('requests.get')
@@ -426,7 +426,7 @@ class TestWeatherTool:
return met
mock_get.side_effect = get
result = self.tool.run({"location": "서울"}, self.context)
result = self.tool.run({"location": "Seoul"}, self.context)
assert result.success is True
assert "서울" in result.reply_text
@@ -453,7 +453,7 @@ class TestWeatherTool:
raise requests.exceptions.Timeout("timed out")
mock_get.side_effect = get
result = self.tool.run({"location": "서울"}, self.context)
result = self.tool.run({"location": "Seoul"}, self.context)
assert result.success is False
assert "unavailable" in result.reply_text.lower()
@@ -649,3 +649,505 @@ class TestExtractPlaceFromUserText:
with patch("src.jarvis.llm.call_llm_direct", return_value="x" * 200):
got = _extract_place_from_user_text("weather", self._cfg())
assert got is None
class TestKmaWeather:
"""Inside Korea, with the app's KMA key, the current weather comes from KMA (기상청 API허브)."""
KEY = "kma-test-key-123"
def setup_method(self):
self.tool = WeatherTool()
self.context = Mock(spec=ToolContext)
self.context.user_print = Mock()
self.context.cfg = Mock()
self.context.cfg.location_name = None
self.context.redacted_text = ""
@staticmethod
def _geo(country_code):
geo = Mock(status_code=200, raise_for_status=Mock())
geo.json.return_value = {"results": [{"latitude": 37.566, "longitude": 126.9784,
"name": "Seoul", "country_code": country_code}]}
return geo
@staticmethod
def _kma(items, code="00"):
r = Mock(status_code=200, raise_for_status=Mock())
r.json.return_value = {"response": {"header": {"resultCode": code},
"body": {"items": {"item": items}}}}
return r
def _obs(self, pty="0", t1h="4.9"):
return self._kma([{"category": c, "obsrValue": v} for c, v in
[("PTY", pty), ("REH", "72"), ("RN1", "0"), ("T1H", t1h), ("WSD", "2.5")]])
def _sky(self, first="3"):
# The coming hours, out of order: the earliest one is the sky now.
return self._kma([
{"category": "SKY", "fcstDate": "20261118", "fcstTime": "1100", "fcstValue": "1"},
{"category": "SKY", "fcstDate": "20261118", "fcstTime": "1000", "fcstValue": first},
{"category": "T1H", "fcstDate": "20261118", "fcstTime": "1000", "fcstValue": "6"},
])
def _routes(self, country_code="KR", obs=None, sky=None, calls=None):
weather = Mock(status_code=200, raise_for_status=Mock())
weather.json.return_value = {"current": {"temperature_2m": 11.0, "weather_code": 0}}
def get(url, *a, **k):
if calls is not None:
calls.append((url, k.get("params") or {}))
if "geocoding" in url:
return self._geo(country_code)
if "getUltraSrtNcst" in url:
return obs if obs is not None else self._obs()
if "getUltraSrtFcst" in url:
return sky if sky is not None else self._sky()
assert "open-meteo" in url, url
return weather
return get
@patch('requests.get')
def test_with_a_key_korean_weather_comes_from_kma(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
calls = []
mock_get.side_effect = self._routes(calls=calls)
result = self.tool.run({"location": "Seoul"}, self.context)
assert result.success is True
assert "구름 많음" in result.reply_text and "기온 5도" in result.reply_text
assert not any("api.open-meteo.com/v1/forecast" in u for u, _ in calls)
kma = [p for u, p in calls if "apihub.kma.go.kr" in u]
assert len(kma) == 2 and all(p["authKey"] == self.KEY for p in kma)
assert all((p["nx"], p["ny"]) == (60, 127) for p in kma)
@patch('requests.get')
def test_precipitation_wins_over_the_sky(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
mock_get.side_effect = self._routes(obs=self._obs(pty="3", t1h="-1.4"), sky=self._sky(first="1"))
result = self.tool.run({"location": "Seoul"}, self.context)
assert "눈" in result.reply_text and "맑음" not in result.reply_text
assert "기온 -1도" in result.reply_text
@patch('requests.get')
def test_without_a_key_open_meteo_answers_also_in_korea(self, mock_get, monkeypatch):
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
mock_get.side_effect = self._routes(calls=calls)
result = self.tool.run({"location": "Seoul"}, self.context)
assert "기온 11도" in result.reply_text
assert not any("apihub.kma.go.kr" in u for u, _ in calls)
@patch('requests.get')
def test_outside_korea_kma_is_not_asked(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
calls = []
mock_get.side_effect = self._routes(country_code="JP", calls=calls)
result = self.tool.run({"location": "Fukuoka"}, self.context)
assert "기온 11도" in result.reply_text
assert not any("apihub.kma.go.kr" in u for u, _ in calls)
@pytest.mark.parametrize("failure", ["result_code", "timeout", "no_sky"])
@patch('requests.get')
def test_when_kma_fails_open_meteo_answers_and_the_key_is_not_logged(
self, mock_get, failure, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
if failure == "result_code": # e.g. the API's use not applied for
routes = self._routes(obs=self._kma([], code="30"))
elif failure == "timeout":
base = self._routes()
def routes(url, *a, **k):
if "apihub.kma.go.kr" in url:
raise requests.exceptions.Timeout(f"timed out: {url}?authKey={self.KEY}")
return base(url, *a, **k)
else:
routes = self._routes(sky=self._kma([]))
mock_get.side_effect = routes
with patch("src.jarvis.tools.builtin.weather.debug_log") as log:
result = self.tool.run({"location": "Seoul"}, self.context)
assert result.success is True and "기온 11도" in result.reply_text
assert not any(self.KEY in str(c) for c in log.call_args_list)
@pytest.mark.parametrize("place,lat,lon,grid", [
("서울", 37.5665, 126.9780, (60, 127)),
("부산", 35.1796, 129.0756, (98, 76)),
("제주", 33.4996, 126.5312, (53, 38)),
])
def test_kma_grid_point(self, place, lat, lon, grid):
from src.jarvis.tools.builtin.weather import _kma_grid
assert _kma_grid(lat, lon) == grid, place
@patch('requests.get')
def test_kma_base_times_are_the_latest_published(self, mock_get):
"""초단기실황 for hour H is out at about H:40, 초단기예보 for H:30 at about H:45 (KST)."""
from datetime import datetime, timezone, timedelta
from src.jarvis.tools.builtin.weather import _kma_current
calls = []
mock_get.side_effect = self._routes(calls=calls)
# 00:20 KST on 1 Jan: both still from the day before.
_kma_current(37.566, 126.978, self.KEY,
now=datetime(2026, 12, 31, 15, 20, tzinfo=timezone.utc))
(_, obs), (_, fc) = calls
assert (obs["base_date"], obs["base_time"]) == ("20261231", "2300")
assert (fc["base_date"], fc["base_time"]) == ("20261231", "2330")
calls.clear()
_kma_current(37.566, 126.978, self.KEY,
now=datetime(2026, 11, 18, 9, 50, tzinfo=timezone(timedelta(hours=9))))
(_, obs), (_, fc) = calls
assert obs["base_time"] == "0900" and fc["base_time"] == "0930"
@patch('requests.get')
def test_the_worker_takes_the_key_out_of_the_environment_and_still_uses_it(self, mock_get, monkeypatch):
"""No child process (MCP servers, MeloTTS) inherits the key; the weather tool keeps it."""
import os
import src.jarvis.tools.builtin.weather as weather
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
monkeypatch.setattr(weather, "_kma_key", "")
weather.take_kma_key()
assert "JARVIS_KMA_API_KEY" not in os.environ
calls = []
mock_get.side_effect = self._routes(calls=calls)
result = self.tool.run({"location": "Seoul"}, self.context)
assert "흐림" in result.reply_text or "구름 많음" in result.reply_text
assert any(p.get("authKey") == self.KEY for u, p in calls if "apihub.kma.go.kr" in u)
class TestForecast:
"""A later day (days_ahead/days): KMA 단기예보 and 중기예보 inside Korea, else open-meteo's daily forecast."""
KEY = "kma-test-key-123"
# Wednesday 18 November 2026, 10:20 KST.
NOW = datetime(2026, 11, 18, 10, 20, tzinfo=timezone(timedelta(hours=9)))
def setup_method(self):
self.tool = WeatherTool()
self.context = Mock(spec=ToolContext)
self.context.user_print = Mock()
self.context.cfg = Mock()
self.context.cfg.location_name = None
self.context.redacted_text = ""
@staticmethod
def _ok(payload):
r = Mock(status_code=200, raise_for_status=Mock())
r.json.return_value = payload
return r
def _kma(self, items):
return self._ok({"response": {"header": {"resultCode": "00"}, "body": {"items": {"item": items}}}})
@staticmethod
def _vilage_items():
"""단기예보: tomorrow (19th) clear in the morning, rain in the afternoon; Saturday (21st) cloudy."""
items = []
for date, sky_am, sky_pm, pty_pm, pops in [
("20261119", "1", "4", "1", ("10", "60")),
("20261120", "3", "3", "0", ("20", "20")),
("20261121", "4", "4", "0", ("30", "30")),
]:
for hour in range(0, 24):
t = f"{hour:02d}00"
am = hour < 12
items += [
{"category": "SKY", "fcstDate": date, "fcstTime": t, "fcstValue": sky_am if am else sky_pm},
{"category": "PTY", "fcstDate": date, "fcstTime": t, "fcstValue": "0" if am else pty_pm},
{"category": "POP", "fcstDate": date, "fcstTime": t, "fcstValue": pops[0] if am else pops[1]},
{"category": "TMP", "fcstDate": date, "fcstTime": t, "fcstValue": str(hour % 7)},
]
items += [{"category": "TMN", "fcstDate": date, "fcstTime": "0600", "fcstValue": "-1.0"},
{"category": "TMX", "fcstDate": date, "fcstTime": "1500", "fcstValue": "4.0"}]
return items
def _routes(self, country_code="KR", lat=37.566, lon=126.9784, calls=None, fail_kma=False):
def get(url, *a, **k):
params = k.get("params") or {}
if calls is not None:
calls.append((url, params))
if "geocoding" in url:
return self._ok({"results": [{"latitude": lat, "longitude": lon, "name": "Seoul",
"country_code": country_code}]})
if "apihub.kma.go.kr" in url:
if fail_kma:
raise requests.exceptions.Timeout(f"timed out: {url}?authKey={self.KEY}")
if "getVilageFcst" in url:
return self._kma(self._vilage_items())
if "getMidTa" in url:
return self._kma([{"regId": params["regId"], "taMin4": -4, "taMax4": 5,
"taMin5": -2, "taMax5": 7, "taMin10": 2, "taMax10": 10}])
if "getMidLandFcst" in url:
return self._kma([{"regId": params["regId"], "wf4Am": "맑음", "wf4Pm": "구름많음",
"rnSt4Am": 10, "rnSt4Pm": 20, "wf5Am": "흐림", "wf5Pm": "흐리고 비",
"rnSt5Am": 30, "rnSt5Pm": 60, "wf10": "맑음", "rnSt10": 10}])
raise AssertionError(url)
assert "api.open-meteo.com/v1/forecast" in url, url
return self._ok({"current": {"temperature_2m": 11.0, "weather_code": 0}, "daily": {
"time": [f"2026-11-{d}" for d in range(18, 29)],
"weather_code": [0, 61, 3, 2, 0, 0, 0, 0, 0, 0, 0],
"temperature_2m_min": [1.2, 2.6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"temperature_2m_max": [9.0, 11.4, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"precipitation_probability_max": [0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0],
}})
return get
def _run(self, args, monkeypatch, key=True, now=None, **routes):
if key:
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
else:
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
with patch('requests.get', side_effect=self._routes(calls=calls, **routes)), \
patch('src.jarvis.tools.builtin.weather._now', return_value=now or self.NOW):
result = self.tool.run({"location": "Seoul", **args}, self.context)
return result, calls
def test_the_schema_offers_a_later_day_and_a_span_of_days(self):
props = self.tool.inputSchema["properties"]
assert props["days_ahead"]["type"] == "integer" and props["days"]["type"] == "integer"
assert self.tool.inputSchema["required"] == []
def test_tomorrow_in_korea_comes_from_the_kma_short_term_forecast(self, monkeypatch):
result, calls = self._run({"days_ahead": 1}, monkeypatch)
assert result.success is True
text = result.reply_text
assert text.startswith("내일(11월 19일 목요일) Seoul 날씨는")
assert "오전 맑음" in text and "오후 비" in text
assert "최저 -1도" in text and "최고 4도" in text and "강수확률 60%" in text
assert not any("open-meteo.com/v1/forecast" in u for u, _ in calls)
vilage = [p for u, p in calls if "getVilageFcst" in u]
assert len(vilage) == 1 and vilage[0]["authKey"] == self.KEY
assert (vilage[0]["nx"], vilage[0]["ny"]) == (60, 127)
assert (vilage[0]["base_date"], vilage[0]["base_time"]) == ("20261118", "0800")
assert not any("MidFcstInfoService" in u for u, _ in calls)
def test_five_days_ahead_in_korea_comes_from_the_kma_mid_term_forecast(self, monkeypatch):
result, calls = self._run({"days_ahead": 5}, monkeypatch)
text = result.reply_text
assert text.startswith("11월 23일 월요일 Seoul 날씨는")
assert "오전 흐림" in text and "오후 흐리고 비" in text
assert "최저 -2도" in text and "최고 7도" in text and "강수확률 60%" in text
mid = {u.rsplit("/", 1)[-1]: p for u, p in calls if "MidFcstInfoService" in u}
assert mid["getMidTa"]["regId"] == "11B10101" and mid["getMidLandFcst"]["regId"] == "11B00000"
assert mid["getMidTa"]["tmFc"] == "202611180600" and mid["getMidTa"]["authKey"] == self.KEY
assert not any("getVilageFcst" in u for u, _ in calls)
def test_the_weekend_spans_the_short_and_mid_term_forecasts(self, monkeypatch):
result, _ = self._run({"days_ahead": 3, "days": 2}, monkeypatch)
lines = result.reply_text.split("\n")
assert len(lines) == 2
assert lines[0].startswith("11월 21일 토요일") and "흐림" in lines[0] and "강수확률 30%" in lines[0]
assert lines[1].startswith("11월 22일 일요일") and "오전 맑음" in lines[1] and "오후 구름많음" in lines[1]
assert "최저 -4도" in lines[1] and "최고 5도" in lines[1]
def test_the_same_weather_all_day_is_said_once(self, monkeypatch):
result, _ = self._run({"days_ahead": 2}, monkeypatch)
assert result.reply_text.startswith("모레(11월 20일 금요일) Seoul 날씨는 구름 많음,")
assert "오전" not in result.reply_text
@pytest.mark.parametrize("lat,lon,city,region", [
(35.1796, 129.0756, "11H20201", "11H20000"), # 부산
(33.4996, 126.5312, "11G00201", "11G00000"), # 제주
(35.9676, 126.7369, "21F10501", "11F10000"), # 군산
(37.7519, 128.8761, "11D20501", "11D20000"), # 강릉
])
def test_the_mid_term_forecast_is_for_the_nearest_kma_city_and_its_region(
self, lat, lon, city, region, monkeypatch):
_, calls = self._run({"days_ahead": 6}, monkeypatch, lat=lat, lon=lon)
mid = {u.rsplit("/", 1)[-1]: p for u, p in calls if "MidFcstInfoService" in u}
assert mid["getMidTa"]["regId"] == city and mid["getMidLandFcst"]["regId"] == region
@pytest.mark.parametrize("now,vilage,tmfc", [
(datetime(2026, 11, 18, 1, 50), ("20261117", "2300"), "202611171800"),
(datetime(2026, 11, 18, 2, 20), ("20261118", "0200"), "202611171800"),
(datetime(2026, 11, 18, 6, 40), ("20261118", "0500"), "202611180600"),
(datetime(2026, 11, 18, 23, 59), ("20261118", "2300"), "202611181800"),
])
def test_kma_forecasts_are_the_latest_published(self, now, vilage, tmfc, monkeypatch):
"""단기예보 is out about 10 minutes after 02, 05, ..., 23 h; 중기예보 about 30 minutes after 06 and 18 h."""
now = now.replace(tzinfo=timezone(timedelta(hours=9)))
_, calls = self._run({"days_ahead": 1}, monkeypatch, now=now)
_, mid_calls = self._run({"days_ahead": 7}, monkeypatch, now=now)
(p,) = [p for u, p in calls if "getVilageFcst" in u]
assert (p["base_date"], p["base_time"]) == vilage
assert {p["tmFc"] for u, p in mid_calls if "MidFcstInfoService" in u} == {tmfc}
def test_an_evening_mid_term_forecast_from_yesterday_counts_its_days_from_yesterday(self, monkeypatch):
# 05:00 on the 19th: the latest 중기예보 is the 18th's 18:00, whose day 5 is the 23rd = 4 days ahead.
now = datetime(2026, 11, 19, 5, 0, tzinfo=timezone(timedelta(hours=9)))
result, _ = self._run({"days_ahead": 4}, monkeypatch, now=now)
assert result.reply_text.startswith("11월 23일 월요일") and "최고 7도" in result.reply_text
def test_when_kma_fails_open_meteo_gives_the_forecast_and_the_key_is_not_logged(self, monkeypatch):
with patch("src.jarvis.tools.builtin.weather.debug_log") as log:
result, calls = self._run({"days_ahead": 1}, monkeypatch, fail_kma=True)
assert result.success is True
assert result.reply_text.startswith("내일(11월 19일 목요일) Seoul 날씨는 약한 비,")
assert "최저 3도" in result.reply_text and "최고 11도" in result.reply_text
assert "강수확률 80%" in result.reply_text
assert not any(self.KEY in str(c) for c in log.call_args_list)
def test_outside_korea_the_forecast_is_open_meteos_daily_one(self, monkeypatch):
result, calls = self._run({"days_ahead": 1}, monkeypatch, country_code="JP")
assert "약한 비" in result.reply_text and "최고 11도" in result.reply_text
assert not any("apihub.kma.go.kr" in u for u, _ in calls)
(p,) = [p for u, p in calls if "open-meteo.com/v1/forecast" in u]
assert "precipitation_probability_max" in p["daily"] and p["forecast_days"] >= 2
def test_this_week_starts_with_the_weather_now(self, monkeypatch):
"""days_ahead 0 with more days: the current weather, then a line for each day."""
result, _ = self._run({"days": 3}, monkeypatch, key=False)
lines = result.reply_text.split("\n")
assert lines[0].startswith("지금 Seoul 날씨는")
assert lines[1].startswith("오늘(11월 18일 수요일)") and lines[2].startswith("내일(11월 19일 목요일)")
assert lines[3].startswith("모레(11월 20일 금요일)") and len(lines) == 4
def test_more_than_ten_days_ahead_is_the_tenth_day(self, monkeypatch):
result, _ = self._run({"days_ahead": 30, "days": 5}, monkeypatch)
assert result.reply_text.split("\n") == [result.reply_text]
assert result.reply_text.startswith("11월 28일 토요일") and "맑음" in result.reply_text
def test_when_no_forecast_is_available_the_answer_says_so(self, monkeypatch):
def down(url, *a, **k):
if "geocoding" in url:
return self._ok({"results": [{"latitude": 1.0, "longitude": 2.0, "name": "X",
"country_code": "FR"}]})
raise requests.exceptions.ConnectionError("down")
with patch('requests.get', side_effect=down), \
patch('src.jarvis.tools.builtin.weather._now', return_value=self.NOW):
result = self.tool.run({"location": "X", "days_ahead": 2}, self.context)
assert result.success is False and "forecast" in result.reply_text.lower()
class TestDistrictPlaces:
"""A district such as 부산 연제구 is found by OpenStreetMap's search (any language) when
open-meteo's geocoder, which knows cities only, does not find it; the weather is for that spot."""
KEY = "kma-test-key-123"
def setup_method(self):
self.tool = WeatherTool()
self.context = Mock(spec=ToolContext)
self.context.user_print = Mock()
self.context.cfg = Mock()
self.context.cfg.location_name = None
self.context.redacted_text = ""
@staticmethod
def _ok(payload):
r = Mock(status_code=200, raise_for_status=Mock())
r.json.return_value = payload
return r
def _routes(self, calls, osm=None, osm_fails=False):
def get(url, *a, **k):
params = k.get("params") or {}
calls.append((url, params, k.get("headers") or {}))
if "geocoding-api.open-meteo.com" in url:
return self._ok({})
if "nominatim.openstreetmap.org" in url:
if osm_fails:
raise requests.exceptions.Timeout("timed out")
return self._ok(osm if osm is not None else [{
"lat": "35.1762", "lon": "129.0797", "name": "연제구", "addresstype": "borough",
"address": {"borough": "연제구", "city": "부산광역시", "country_code": "kr"}}])
if "getUltraSrtNcst" in url:
return self._ok({"response": {"header": {"resultCode": "00"}, "body": {"items": {"item": [
{"category": c, "obsrValue": v} for c, v in
[("PTY", "0"), ("REH", "60"), ("T1H", "8.2"), ("WSD", "3.1")]]}}}})
if "getUltraSrtFcst" in url:
return self._ok({"response": {"header": {"resultCode": "00"}, "body": {"items": {"item": [
{"category": "SKY", "fcstDate": "20261118", "fcstTime": "1200", "fcstValue": "1"}]}}}})
assert "api.open-meteo.com/v1/forecast" in url, url
return self._ok({"current": {"temperature_2m": 11.0, "weather_code": 0}})
return get
@patch('src.jarvis.tools.builtin.weather._romanise_place')
def test_a_district_gets_its_own_spots_weather_from_kma(self, mock_romanise, monkeypatch):
from src.jarvis.tools.builtin.weather import _kma_grid
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
calls = []
with patch('requests.get', side_effect=self._routes(calls)):
result = self.tool.run({"location": "부산 연제구"}, self.context)
assert result.success is True
assert result.reply_text.startswith("지금 부산 연제구 날씨는 맑음") and "기온 8도" in result.reply_text
kma = [p for u, p, _ in calls if "apihub.kma.go.kr" in u]
assert kma and all((p["nx"], p["ny"]) == _kma_grid(35.1762, 129.0797) for p in kma)
mock_romanise.assert_not_called()
def test_the_place_search_asks_for_one_place_with_its_country_and_names_the_app(self, monkeypatch):
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
with patch('requests.get', side_effect=self._routes(calls)):
self.tool.run({"location": "부산 연제구"}, self.context)
((_, params, headers),) = [c for c in calls if "nominatim.openstreetmap.org" in c[0]]
assert params["q"] == "부산 연제구" and params["limit"] == 1 and params["addressdetails"] == 1
assert "jarvis" in headers.get("User-Agent", "").lower()
@pytest.mark.parametrize("osm,osm_fails", [([], False), (None, True), ({"error": "x"}, False)])
@patch('src.jarvis.tools.builtin.weather._romanise_place', return_value=None)
def test_when_the_place_search_finds_nothing_or_fails_the_place_is_not_found(
self, _rom, osm, osm_fails, monkeypatch):
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
with patch('requests.get', side_effect=self._routes(calls, osm=osm, osm_fails=osm_fails)):
result = self.tool.run({"location": "없는 동네"}, self.context)
assert result.success is False and "could not find" in result.reply_text.lower()
@patch('src.jarvis.tools.builtin.weather._romanise_place')
def test_a_non_latin_city_name_is_not_matched_loosely_by_open_meteo(self, mock_romanise, monkeypatch):
"""Live 2026-11-18: open-meteo matched "부산" to a village called Pusan 140 km from Busan."""
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
osm = [{"lat": "35.1799", "lon": "129.0752", "name": "부산광역시", "address": {"country_code": "kr"}}]
with patch('requests.get', side_effect=self._routes(calls, osm=osm)):
result = self.tool.run({"location": "부산"}, self.context)
assert result.reply_text.startswith("지금 부산 날씨는")
assert not any("geocoding-api.open-meteo.com" in u for u, _, _ in calls)
(_, p, _), = [c for c in calls if "api.open-meteo.com/v1/forecast" in c[0]]
assert (p["latitude"], p["longitude"]) == (35.1799, 129.0752)
mock_romanise.assert_not_called()
def test_a_latin_name_open_meteo_knows_does_not_ask_openstreetmap(self, monkeypatch):
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
base = self._routes(calls)
def get(url, *a, **k):
if "geocoding-api.open-meteo.com" in url:
calls.append((url, k.get("params"), {}))
return self._ok({"results": [{"latitude": 51.5, "longitude": -0.12, "name": "London",
"country_code": "GB"}]})
return base(url, *a, **k)
with patch('requests.get', side_effect=get):
result = self.tool.run({"location": "London"}, self.context)
assert result.success and not any("nominatim" in u for u, _, _ in calls)