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>
This commit is contained in:
@@ -36,6 +36,7 @@
|
||||
- 원하면 게임 중에는 봇을 일시정지할 수 있습니다.
|
||||
- **안티치트 보호**: 뱅가드 같은 안티치트가 걸린 게임이 실행 중이면 키보드·마우스 자동 조작을 막고 그 이유를 알려 줍니다.
|
||||
- **기존 기능 유지**: 메모리, 날씨, 웹 검색, 식단 기록, MCP, 브라우저 제어를 그대로 가져갑니다.
|
||||
- **기상청 날씨**: 관리 앱 "기능" 화면에 기상청 API허브 인증키를 넣으면 한국 안의 현재 날씨를 기상청에서 받습니다(초단기실황조회, 초단기예보조회 활용신청 필요). 키가 없거나 한국 밖이면 open-meteo, 그다음 met.no에서 받습니다.
|
||||
- **관리 앱**:
|
||||
- 첫 실행 마법사, 대시보드, 모델 다운로드, 기능별 켜기/끄기를 제공합니다.
|
||||
- 로그 화면에서 로그를 보고, 복사하고, 내려받을 수 있습니다. 비밀값은 자동으로 가립니다.
|
||||
|
||||
@@ -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
|
||||
(current weather inside Korea from KMA, else open-meteo, 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 |
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
"""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 datetime import datetime, timedelta, timezone
|
||||
|
||||
import requests
|
||||
from typing import Dict, Any, Optional
|
||||
@@ -246,6 +250,94 @@ 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_URL = "https://apihub.kma.go.kr/api/typ02/openApi/VilageFcstInfoService_2.0/"
|
||||
_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 = ""
|
||||
|
||||
|
||||
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_items(service: str, key: str, base: datetime, nx: int, ny: int) -> list:
|
||||
"""One KMA call's items; raises on any failure. The key is in the URL: never log the error text."""
|
||||
resp = requests.get(_KMA_URL + service, timeout=_KMA_TIMEOUT_SEC, params={
|
||||
"pageNo": 1, "numOfRows": 100, "dataType": "JSON", "base_date": base.strftime("%Y%m%d"),
|
||||
"base_time": base.strftime("%H%M"), "nx": nx, "ny": ny, "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_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."""
|
||||
|
||||
@@ -318,7 +410,8 @@ 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
|
||||
@@ -339,6 +432,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 +453,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",
|
||||
@@ -456,6 +551,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
|
||||
@@ -480,15 +576,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 +617,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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -288,6 +288,11 @@ 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 current weather inside Korea
|
||||
(geocoded or detected country `KR`): KMA's 초단기실황 (temperature, humidity, wind,
|
||||
precipitation) and 초단기예보 (the coming hour's sky). Any KMA failure falls back to open-meteo,
|
||||
then met.no; the key is in KMA's URLs, so a failure is logged by its kind only.
|
||||
- `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
|
||||
|
||||
@@ -649,3 +649,178 @@ 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)
|
||||
|
||||
Reference in New Issue
Block a user