diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 8922f00..a55dca2 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -88,13 +88,13 @@ sites, search words and RSS feeds on a schedule; there are **no targets by defau - `collect` (new section): `keepDays` (1-365, default 30) and `targets` (default empty), each `{name, kind, value, everyMinutes, enabled}`. `name` is 1-32 letters, digits, `-` or `_` (any script; it names the target's folder, so not a Windows device name like `con` or `nul`), not - listed twice; `kind` is `site`, `search` or `rss`; `value` is an http(s) address for `site` and + listed twice, also not in another case (`News` and `news` would share one Windows folder); `kind` is `site`, `search` or `rss`; `value` is an http(s) address for `site` and `rss` (at most 2,000 characters) and the words for `search` (1-200 characters); `everyMinutes` 15-10080 (default 60); `enabled` on by default. -- On start, with `features.collect` on and at least one enabled target, the app writes - `config/collect.json` (the folder `collect/`, `keepDays` and the enabled targets) and passes it to - the worker as `JARVIS_COLLECT_PATH`; otherwise it removes that file and passes nothing. The worker - collects while the services run (`voice_worker.spec.md`, "Background collection"); results stay +- On every start the app writes `config/collect.json` (the folder `collect/`, `keepDays` and the + enabled targets, none with `features.collect` off) and passes it to the worker as + `JARVIS_COLLECT_PATH`. Without targets the worker collects nothing but still deletes results + older than `keepDays`. The worker collects while the services run (`voice_worker.spec.md`, "Background collection"); results stay in `collect//.jsonl` in the data folder only. - `results(data, target, limit)` reads them newest first (the newest day file first, its last line first), each item with its `target`; a name that is not a valid target name is refused, so no @@ -305,7 +305,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run; `sync` with the chat channels sent to Discord (below) | | `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start | | `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) | -| `collect_results` `{target, limit}` | collected items newest first (`target` null: every target; `limit` 1-500, default 100) | +| `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) | | `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 | | `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 | | `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back | @@ -339,7 +339,7 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A one per line, on/off, delete), and for a saved server a password box per environment variable that stores its value on its own. The 백그라운드 수집 screen has the targets (a table: name, kind, address or words, interval in minutes, on/off, delete), the keep days, and the results (the - newest 100, filtered by target, each with its time, title, link and the start of its text shown + newest 100, filtered by any target that has results, each with its time, title, link and the start of its text shown as plain text). - **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류 복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days. diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index c2fe109..7e71643 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -284,7 +284,9 @@ impl AdminApi { "collect_results" => { let target = args.get("target").and_then(Value::as_str).filter(|t| !t.is_empty()); let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(100).clamp(1, 500) as usize; - Ok(json!(crate::collect::results(self.dir()?.path(), target, limit)?)) + let dir = self.dir()?; + Ok(json!({"targets": crate::collect::result_targets(dir.path()), + "items": crate::collect::results(dir.path(), target, limit)?})) } "channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter() .map(|(id, s)| (id.to_string(), json!(s))).collect())), @@ -409,7 +411,7 @@ mod tests { std::fs::create_dir_all(&day).unwrap(); std::fs::write(day.join("2026-11-13.jsonl"), "{\"at\": \"2026-11-13T09:00:00+09:00\", \"title\": \"t\"}\n").unwrap(); let r = a.call("collect_results", json!({"target": null})).await.unwrap(); - assert_eq!(r, json!([{"at": "2026-11-13T09:00:00+09:00", "title": "t", "target": "뉴스"}])); + assert_eq!(r, json!({"targets": ["뉴스"], "items": [{"at": "2026-11-13T09:00:00+09:00", "title": "t", "target": "뉴스"}]})); assert!(a.call("collect_results", json!({"target": "../config"})).await.is_err()); } diff --git a/app/src/collect.rs b/app/src/collect.rs index 1b9ea02..9e8d670 100644 --- a/app/src/collect.rs +++ b/app/src/collect.rs @@ -10,25 +10,19 @@ use crate::settings::{valid_collect_name, Settings}; /// The worker's environment variable with the collection file (`voice_worker/collect.py`). pub const COLLECT_ENV_VAR: &str = "JARVIS_COLLECT_PATH"; -/// Write `config/collect.json` with the enabled targets and return it; with the feature off or no -/// enabled target, remove it and return None (the worker then collects nothing). -pub fn write_config(data: &Path, settings: &Settings) -> std::io::Result> { +/// Write `config/collect.json` and return it. With the feature off it lists no targets: the worker +/// then collects nothing but still deletes day files older than the keep days. +pub fn write_config(data: &Path, settings: &Settings) -> std::io::Result { let file = data.join("config").join("collect.json"); - let targets: Vec = settings.collect.targets.iter().filter(|t| t.enabled) + let targets: Vec = settings.collect.targets.iter().filter(|t| t.enabled && settings.features.collect) .map(|t| json!({"name": t.name, "kind": t.kind, "value": t.value, "everyMinutes": t.every_minutes})) .collect(); - if !settings.features.collect || targets.is_empty() { - match std::fs::remove_file(&file) { - Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), - _ => return Ok(None), - } - } let cfg = json!({"dir": data.join("collect").to_string_lossy(), "keepDays": settings.collect.keep_days, "targets": targets}); let mut text = serde_json::to_string_pretty(&cfg).unwrap(); text.push('\n'); crate::datadir::write_atomic(&file, text.as_bytes())?; - Ok(Some(file)) + Ok(file) } /// The day files of one target folder, newest first. @@ -41,17 +35,25 @@ fn day_files(folder: &Path) -> Vec { files } +/// The target folders that hold results, sorted. +pub fn result_targets(data: &Path) -> Vec { + let root = data.join("collect"); + let mut names: Vec = std::fs::read_dir(&root).into_iter().flatten().flatten() + .filter(|e| e.path().is_dir()) + .filter_map(|e| e.file_name().to_str().map(str::to_owned)) + .filter(|n| valid_collect_name(n) && !day_files(&root.join(n)).is_empty()) + .collect(); + names.sort(); + names +} + /// Collected items newest first, each with its `target`; `target` None reads every target folder. pub fn results(data: &Path, target: Option<&str>, limit: usize) -> Result, String> { let root = data.join("collect"); let names: Vec = match target { Some(t) if !valid_collect_name(t) => return Err(format!("not a collection target name: {t}")), Some(t) => vec![t.to_owned()], - None => std::fs::read_dir(&root).into_iter().flatten().flatten() - .filter(|e| e.path().is_dir()) - .filter_map(|e| e.file_name().to_str().map(str::to_owned)) - .filter(|n| valid_collect_name(n)) - .collect(), + None => result_targets(data), }; let mut out: Vec = Vec::new(); for name in names { @@ -87,23 +89,21 @@ mod tests { } #[test] - fn the_worker_gets_only_enabled_targets_and_nothing_without_them() { + fn the_worker_gets_only_enabled_targets_and_the_keep_days_also_without_targets() { let data = temp_dir("collect-cfg"); let s = settings(json!({"collect": {"keepDays": 3, "targets": [ {"name": "a", "kind": "rss", "value": "https://a.example/rss", "everyMinutes": 30}, {"name": "b", "kind": "site", "value": "https://b.example", "enabled": false}]}})); - let file = write_config(&data, &s).unwrap().unwrap(); - let cfg: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); - assert_eq!(cfg, json!({"dir": data.join("collect").to_string_lossy(), "keepDays": 3, + let read = |f: &Path| serde_json::from_str::(&std::fs::read_to_string(f).unwrap()).unwrap(); + let dir = data.join("collect").to_string_lossy().into_owned(); + let file = write_config(&data, &s).unwrap(); + assert_eq!(read(&file), json!({"dir": dir, "keepDays": 3, "targets": [{"name": "a", "kind": "rss", "value": "https://a.example/rss", "everyMinutes": 30}]})); - + // Feature off or no targets: nothing to collect, but old results still go after keepDays. let mut off = s.clone(); off.features.collect = false; - assert_eq!(write_config(&data, &off).unwrap(), None); - assert!(!file.exists()); - write_config(&data, &s).unwrap(); - assert_eq!(write_config(&data, &settings(json!({}))).unwrap(), None); - assert!(!file.exists()); + assert_eq!(read(&write_config(&data, &off).unwrap()), json!({"dir": dir, "keepDays": 3, "targets": []})); + assert_eq!(read(&write_config(&data, &settings(json!({}))).unwrap()), json!({"dir": dir, "keepDays": 30, "targets": []})); } #[test] @@ -125,6 +125,9 @@ mod tests { assert_eq!(titles(results(&data, Some("뉴스"), 2).unwrap()), ["뉴스:n2", "뉴스:n1"]); assert_eq!(titles(results(&data, None, 2).unwrap()), ["뉴스:n2", "site:s1"]); assert!(results(&data, Some("missing"), 10).unwrap().is_empty()); + // Every target with results is listed, also one whose items are all older than the newest. + std::fs::create_dir_all(data.join("collect").join("empty")).unwrap(); + assert_eq!(result_targets(&data), ["site", "뉴스"]); assert!(results(&data, Some(".."), 10).is_err()); assert!(results(&data, Some("../config"), 10).is_err()); } diff --git a/app/src/services.rs b/app/src/services.rs index 043d734..d774436 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -70,10 +70,9 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result { wopts.env.insert(crate::collect::COLLECT_ENV_VAR.into(), f.to_string_lossy().into_owned()); } - Ok(None) => {} + Ok(f) => { wopts.env.insert(crate::collect::COLLECT_ENV_VAR.into(), f.to_string_lossy().into_owned()); } Err(e) => return Err(after_llm_stop(&llm, format!("could not write the collection settings: {e}")).await.into()), } let worker_process = match WorkerProcess::new(wopts) { diff --git a/app/src/settings.rs b/app/src/settings.rs index 4e8d64f..037924e 100644 --- a/app/src/settings.rs +++ b/app/src/settings.rs @@ -550,8 +550,9 @@ fn parse_collect(raw: &Map, d: &CollectSettings) -> Result { try { - const items = await api("collect_results", { target: pick.value || null, limit: 100 }); - if (!pick.value) { - for (const name of new Set(items.map((i) => i.target))) - if (![...pick.options].some((o) => o.value === name)) pick.append(h("option", { value: name }, name)); - } + const r = await api("collect_results", { target: pick.value || null, limit: 100 }); + const items = r.items; + for (const name of r.targets) + if (![...pick.options].some((o) => o.value === name)) pick.append(h("option", { value: name }, name)); list.replaceChildren(items.length ? h("table", {}, h("tbody", {}, items.map((i) => h("tr", {}, h("td", { class: "small muted" }, (i.at || "").replace("T", " ").slice(0, 16)), h("td", { class: "small" }, i.target), diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index b9b01e9..190b530 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -10,7 +10,7 @@ | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 2단계 완료(2026-11-11): 대화 루프 `app/src/conversation.rs`가 최종 전사를 호출 판정과 응답 정책에 넣고, 정책의 결정대로 두뇌에 답을 요청해(`reply`, 답은 워커가 같은 id로 읽음) 앱의 재생 대기열에서 재생, 끼어들 때는 그 답만 멈춤, "자비스 멈춰"는 모든 말을 멈춤, 놓친 요청은 글 없이 최근 100개를 남김. 두뇌의 두 판정 `src/voice_worker/judges.py`(봇에게 하는 말인지, 중요도 순위)는 답과 따로 돌아 기다리지 않음. 평가 `evals/test_voice_judges.py` 12개를 qwen2.5:7b에서 모두 통과. 답을 만드는 중에 멈춘 요청은 말하지 않음. 실제 Python 워커(가짜 두뇌)와 앱의 통합 시험 통과. 3단계 완료(2026-11-11): 채팅 채널 호출. 채널마다 `answer`(호출어로 부를 때만 / 모든 메시지에 대답), 채팅 호출어(`call.chatWakeWords`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 음성 답과 채팅 답을 따로 써서 다른 사람의 채팅 답 때문에 음성 답이 기다리지 않음. 한 사람의 답은 물은 순서대로 하나씩 씀. 두 답의 LLM 호출이 동시에 돌려면 Strata를 `--parallel 2`로 띄움, 앱이 Strata를 띄우는 M5 전까지). 5분 넘게 늦은 채팅 답은 올리지 않음. 실제 디스코드 시험과 지연 측정은 4단계. 4단계 첫 측정(2026-11-12): 앱의 실제 서비스(`start_services`: 대화 루프, 응답 정책, 워커, 두뇌)를 게임PC Strata(`--parallel 2`)에 붙이고, 봇 두 개로 질문 5개를 2번씩 말해 잼(`app/tests/live_round_trip.rs`). 10개 모두 소리로 답했고, 말 끝부터 첫 소리까지 중앙값 3.5초(최소 2.8초, 날씨 도구 8.6초). 9명이 동시에 말하는 부하(워커의 두 번째 연결로 녹음 문장 9개를 실시간으로 넣음, 그동안 최종 전사 259개)에서는 중앙값 4.4초, 최종 전사가 0.6~0.9초에서 0.8~1.8초로 늦어졌고 1번은 "기분"을 "딥"으로 잘못 들어 날씨 도구를 불러 18.8초가 걸림. 짧은 답의 시간은 최종 전사 0.65~0.85초, 두뇌 2.0~2.9초(도구 고르기 0.42초, 계획 0.5초, 답 호출의 지시문 약 4,300토큰 읽기 1.1초와 생성), 재생 시작과 전달 약 0.4초. Strata의 Qwen3.6 엔진은 지시문 앞부분 재사용을 하지 않아(`--prompt-cache-every`는 "이 엔진의 옵션이 아님"으로 무시됨, 같은 대화를 그대로 이어 갈 때만 재사용) 매 호출을 처음부터 읽음. 생성은 0.2~0.5초라 문장 단위로 흘려도 짧은 답은 거의 빨라지지 않음. 1.5초 기준은 아직 못 맞춤. 같은 시험에서 찾아 고친 것: v1 TTS 설정(영어 전용 Piper) 때문에 한국어 질문에 영어로 답하던 것(v2 두뇌는 묻는 사람의 언어로 답함), 호출어 뒤에 쉬면 "자비스"만 따로 끊겨 그 이름에만 답하고 이어진 질문은 무시하던 것(이제 같은 사람이 이어서 하는 말과 합침, `call.followUpMs`). 4단계 지연 줄이기(사용자 결정, 2026-11-12): 부름을 받으면 "띠링" 효과음(앱이 만든 0.3초 소리, `call.earcon`, 이름만 부르고 쉬면 그때 바로), 답은 한국어 기본(영어 등은 따로 부탁할 때만), v2 두뇌의 짧은 지시문(성격 설명 7.4천 자를 1.3천 자로, 답은 최대한 짧게, 화면공유 도구는 v2에 없어 뺌: 인사의 답 지시문 4,500토큰이 1,400토큰), 답 전에 판단 한 번(도구 고르기로 도구가 필요한지 정하고, 필요할 때만 계획. 계획 하나로 합치거나 계획을 아예 빼 보니 날씨나 여러 단계 질문이 틀려 이 방식으로 정함), 말하는 중의 중간 전사가 호출로 읽히면 도구 고르기를 미리 해 둠(워커 `prepare`). 평가 전체(v2 설정, 마지막 지시문 수정 전) 219개 통과, 6개 실패: 파리·런던 비교와 지식 그래프 갈래 분류는 전부터 실패, 3개는 v2가 쓰지 않는 v1 개인 기억(그래프·일기) 평가, 1개는 새 답 길이 평가("하늘은 왜 파래"의 답이 72자로 기준 70자를 넘음). 그 뒤 "왜·어떻게" 질문은 핵심 이유만 말하도록 지시문을 고치고 답 길이 평가를 따로 3번 돌려 3번 모두 통과(v2 답 합계 185~205자, 예전 315~356자), 한국어 기본·지난 대화·채팅 채널·건너뛴 도구 평가 22개도 모두 통과(전체 평가는 이 수정 뒤 다시 돌리지 않음). 실제 디스코드 재측정(2026-11-12, `app/tests/live_round_trip.rs`, 질문 5개 2번): 첫 소리(효과음)는 이름 뒤에 쉬면 질문이 끝나기 전에, 쉬지 않으면 0.94~1.10초. 답의 첫 소리는 중앙값 1.9초(1.56~2.30초, 날씨 도구 5.75~5.85초), 9명이 동시에 말할 때 2.8초(2.13~3.41초, "기분"을 "딥"으로 잘못 들은 1번은 웹 검색으로 13.3초). 혼자일 때는 미리 해 둔 판단이 5번 모두 쓰여 말 끝 뒤 두뇌 시간이 0.6~0.74초였고, 9명 부하에서는 중간 전사가 밀려 미리 판단이 한 번도 되지 않음(두뇌 1.4초). 같은 시험에서 찾아 고친 것: 모델이 "10시 37분"을 오후로 읽음(시간 줄에 12시간 표기 추가), 없는 타이머 도구 호출 글자(``)를 답으로 내 TTS가 읽을 뻔함(도구 호출로 읽음) | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 마무리(2026-11-12): 채팅 채널 이름·주제 반영 `app/src/channel_sync.rs`(채널마다 "디스코드에도 반영", 기본 켜짐; 등록하면 디스코드의 이름·주제로 채움, 저장하면 바뀐 채널만 디스코드에 반영하고 디스코드가 바꾼 이름(공백은 `-`)을 화면에 다시 보여 줌, 주제 1,024자 초과는 저장 전에 거절, 10분에 2번 제한에 걸리면 "잠시 뒤 반영" 후 디스코드가 알려 준 시간 뒤 마지막 저장값으로 저절로 다시 시도, 권한이 없으면 이유를 보여 주고 앱에만 저장). 실제 디스코드 시험 채널에서 채움·반영·제한(587초 대기)·자동 재시도까지 확인 후 채널 삭제. 모델 화면에 TTS 말하기 속도(MeloTTS, 0.5~2.0, 기본 1.5; 한국어 모델은 목소리가 KR 하나뿐이라 목소리 선택은 없음). 창을 닫을 때 설치 중이면 취소하고 끝날 때까지 기다림, 정리를 확인하지 못하면 창을 닫지 않고 이유를 보여 줌(한 번 더 닫으면 종료), 실패한 실행이 남긴 Strata도 정리. 창의 WebView 자료는 데이터 폴더(`cache/webview`), 폴더를 고르기 전에는 임시 폴더에 두었다가 다음 시작 때 지움(`%APPDATA%\JarvisBot`에는 위치 파일 하나만). Windows의 UTF-8 옵션이 꺼진 PC의 CP949 출력도 끝까지 읽음. VM에서 다시 확인: 설치 중 창 닫기 뒤 남은 프로세스 없음, `--location` 없이 실행 시 위치 파일 하나만, Windows용 단위 테스트 168개 통과. 게임PC에서 UTF-8 옵션을 끈 상태(코드 페이지 949)로 다시 확인: 전체 설치 7단계, Strata의 대화 모델 22.9GB 다운로드(진행률 10.9%→90%로 표시)와 준비, 워커·디스코드 연결, 시험 봇 질문 5개 모두 소리로 답함(앱이 잰 전체 중앙값 4.0초), 정지 7초에 GPU 메모리 반환, 로그 485줄에 깨진 글자 없음. 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께) | -| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 2단계 완료(2026-11-13): 예약 수집 틀(`app/src/collect.rs`, 워커 `src/voice_worker/collect.py`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Background collection"). 관리 앱 "백그라운드 수집" 화면에서 대상(사이트·검색어·RSS, 주기 15분~7일, 켜기/끄기)과 보관 기간(기본 30일)을 정하고 결과를 봄. 기본 대상은 없음. 기능 화면의 "백그라운드 수집" 스위치를 끄거나 켠 대상이 없으면 워커에 아무것도 넘기지 않음. 워커가 음성·두뇌와 따로 돌며, 사이트는 바뀌었을 때만, RSS·검색은 새 항목만 남김. 모든 요청은 웹 검색의 주소 검사(공개 주소만, 리디렉트마다 다시 검사, 1MB, 15초)를 거치고, 모은 내용은 데이터 폴더 `collect/`에만 쓰며 두뇌나 로그로 가지 않음(로그에는 대상 이름과 개수만). 덕덕고가 봇 확인 화면을 주면 "결과 없음"이 아니라 실패로 남김. 이 서버에서 확인: 실제 인터넷의 RSS(hnrss 20개), Atom(cpython 10개), 검색어(10개), 사이트(1개) 수집, 내부 주소는 거절, 개발용 서버 화면에서 대상 저장·잘못된 이름 거절·결과 보기, 실제 서비스 시작으로 켠 대상만 워커에 넘어가 수집되고 정지 때 워커도 꺼짐. 남은 것: 봇용 크롬과 가상 모니터, 나머지 기능 스위치(브라우저 제어·PC 제어·화면 보기, 각 기능과 함께) | +| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 2단계 완료(2026-11-13): 예약 수집 틀(`app/src/collect.rs`, 워커 `src/voice_worker/collect.py`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Background collection"). 관리 앱 "백그라운드 수집" 화면에서 대상(사이트·검색어·RSS, 주기 15분~7일, 켜기/끄기)과 보관 기간(기본 30일)을 정하고 결과를 봄. 기본 대상은 없음. 기능 화면의 "백그라운드 수집" 스위치를 끄거나 켠 대상이 없으면 수집은 하지 않고 보관 기간이 지난 결과만 지움. 대소문자만 다른 대상 이름은 Windows에서 같은 폴더라 거절. 워커가 음성·두뇌와 따로 돌며, 사이트는 바뀌었을 때만, RSS·검색은 새 항목만 남김. 모든 요청은 공개 주소만 허용하고 검사한 그 주소로만 연결(DNS를 다시 물어 내부망으로 새는 것 막음, 리디렉트마다 다시 검사, 1MB, 전체 15초, 주소는 로그에 남기지 않음)하고, 모은 내용은 데이터 폴더 `collect/`에만 쓰며 두뇌나 로그로 가지 않음(로그에는 대상 이름과 개수만). 덕덕고가 봇 확인 화면을 주면 "결과 없음"이 아니라 실패로 남김. 이 서버에서 확인: 실제 인터넷의 RSS(hnrss 20개), Atom(cpython 10개), 검색어(10개), 사이트(1개) 수집, 내부 주소는 거절, 개발용 서버 화면에서 대상 저장·잘못된 이름 거절·결과 보기, 실제 서비스 시작으로 켠 대상만 워커에 넘어가 수집되고 정지 때 워커도 꺼짐. 남은 것: 봇용 크롬과 가상 모니터, 나머지 기능 스위치(브라우저 제어·PC 제어·화면 보기, 각 기능과 함께) | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | diff --git a/src/voice_worker/collect.py b/src/voice_worker/collect.py index 9fbad62..29e20c1 100644 --- a/src/voice_worker/collect.py +++ b/src/voice_worker/collect.py @@ -4,8 +4,10 @@ collection"). Results go only to day files in the data folder; logs carry target from __future__ import annotations import hashlib +import ipaddress import json import re +import socket import threading import time import urllib.parse @@ -18,7 +20,9 @@ from typing import Callable, Optional from .log import debug_log, notice MAX_BYTES = 1024 * 1024 -TIMEOUT_S = 15 +TOTAL_S = 15.0 +CONNECT_S = 10.0 +READ_S = 5.0 MAX_REDIRECTS = 5 SITE_CHARS = 20_000 SUMMARY_CHARS = 2_000 @@ -49,28 +53,88 @@ def load_config(path) -> Config: [Target(t["name"], t["kind"], t["value"], float(t["everyMinutes"]) * 60) for t in raw.get("targets", [])]) -def safe_get(url: str) -> bytes: - """GET a public http(s) address: every redirect checked again, at most ``MAX_BYTES``.""" - import requests - from jarvis.tools.builtin.web_search import _is_public_url +def _is_public_ip(ip) -> bool: + return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved + or ip.is_multicast or ip.is_unspecified) + +def _public_ips(host: str, port: int) -> list: + """The addresses to connect to: every address the name resolves to must be public. The caller + connects only to these, so a second lookup cannot point elsewhere. Nothing about the address + is logged (it is the user's collection target).""" + try: + addrs = [str(ipaddress.ip_address(host))] + except ValueError: + try: + addrs = list(dict.fromkeys(i[4][0] for i in socket.getaddrinfo(host, port, type=socket.SOCK_STREAM))) + except OSError: + raise ValueError("name not found") from None + if not addrs or not all(_is_public_ip(ipaddress.ip_address(a.split("%")[0])) for a in addrs): + raise ValueError("not a public address") + return addrs + + +def _open(p, port: int, ips: list, host: str, path: str, deadline: float): + """(pool, response) from the first checked address that connects before `deadline`.""" + import certifi + import urllib3 + from urllib3.exceptions import ConnectTimeoutError + + for i, ip in enumerate(ips): + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError("took too long") + timeout = urllib3.Timeout(connect=min(CONNECT_S, left), read=READ_S) + if p.scheme == "https": + pool = urllib3.HTTPSConnectionPool(ip, port, timeout=timeout, retries=False, cert_reqs="CERT_REQUIRED", + ca_certs=certifi.where(), server_hostname=p.hostname, + assert_hostname=p.hostname) + else: + pool = urllib3.HTTPConnectionPool(ip, port, timeout=timeout, retries=False) + try: + return pool, pool.urlopen("GET", path, headers={"Host": host, "User-Agent": USER_AGENT, + "Accept-Encoding": "identity"}, + redirect=False, retries=False, preload_content=False) + except ConnectTimeoutError: # also a refused connection (NewConnectionError) + pool.close() + if i == len(ips) - 1: + raise + + +def safe_get(url: str) -> bytes: + """GET a public http(s) address: every hop's address checked and connected to as checked, at + most ``MAX_BYTES`` and ``TOTAL_S`` seconds in all.""" + # Each socket wait is at most READ_S and none starts after `deadline`, so the whole fetch + # (redirects included) ends within TOTAL_S. + deadline = time.monotonic() + TOTAL_S - READ_S for _ in range(MAX_REDIRECTS + 1): - if not _is_public_url(url): - raise ValueError("not a public address") - with requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=TIMEOUT_S, - allow_redirects=False, stream=True) as r: - if r.is_redirect or r.is_permanent_redirect: + p = urllib.parse.urlsplit(url) + if p.scheme not in ("http", "https") or not p.hostname: + raise ValueError("not an http(s) address") + port = p.port or (443 if p.scheme == "https" else 80) + ips = _public_ips(p.hostname, port) + host = p.hostname if p.port is None else f"{p.hostname}:{p.port}" + if ":" in p.hostname: + host = f"[{p.hostname}]" + ("" if p.port is None else f":{p.port}") + path = (p.path or "/") + (f"?{p.query}" if p.query else "") + pool, r = _open(p, port, ips, host, path, deadline) + try: + if r.status in (301, 302, 303, 307, 308): url = urllib.parse.urljoin(url, r.headers.get("Location", "")) continue - r.raise_for_status() - if r.status_code != 200: # e.g. DuckDuckGo's 202 challenge - raise ValueError(f"status {r.status_code}") + if r.status != 200: # e.g. DuckDuckGo's 202 challenge + raise ValueError(f"status {r.status}") body = b"" - for chunk in r.iter_content(64 * 1024): + while chunk := r.read1(64 * 1024): body += chunk if len(body) > MAX_BYTES: raise ValueError("response too large") + if time.monotonic() > deadline: + raise TimeoutError("took too long") return body + finally: + r.release_conn() + pool.close() raise ValueError("too many redirects") @@ -186,7 +250,7 @@ class Collector: def _run(self, t: Target, state: dict) -> int: if t.kind == "site": [page] = _site(self.fetch(t.value)) - digest = hashlib.sha256(page["text"].encode()).hexdigest() + digest = hashlib.sha256(json.dumps([page["title"], page["text"]]).encode()).hexdigest() if digest == state.get("hash"): return 0 state["hash"] = digest diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index f3ebd68..0bcd517 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -322,17 +322,21 @@ which carry Discord's own time. With `JARVIS_COLLECT_PATH` set, the worker collects on its own thread, apart from the voice and the brain (`app/src/admin.spec.md`, "Background collection"). The file is `{"dir": "/collect", "keepDays": 30, "targets": [{"name", "kind", "value", "everyMinutes"}]}`; -the app writes only enabled targets. Nothing is collected without targets. +the app writes only enabled targets. Nothing is collected without targets, but old day files are +still deleted (below). - A target runs when `everyMinutes` passed since its last run (also across restarts; the last run is kept in `//state.json`), one target at a time, checked every 30 s. A failed run counts as a run, so a broken site is tried again only at its next interval. -- Kinds: `site` keeps the page's title and text (at most 20,000 characters) when it differs from the - last kept one; `rss` (RSS or Atom) keeps each new item (title, link, time, summary of at most 2,000 +- Kinds: `site` keeps the page's title and text (at most 20,000 characters) when either differs from + the last kept ones; `rss` (RSS or Atom) keeps each new item (title, link, time, summary of at most 2,000 characters, new by its id or link); `search` keeps each new web search result (title and link) for the words, from DuckDuckGo's lite page, which needs no key (its bot challenge is a failed run, not "no results"). -- Every request goes through the web search's address check (`web_search.spec.md`): only public - http(s) addresses, every redirect checked again, at most 1 MB, 15 s. The collected text is web +- Every request checks its address like the web search (`web_search.spec.md`): only http(s), and + every address the name resolves to must be public; the connection goes only to the checked + addresses in their order (TLS still checks the name), so a second lookup cannot lead into the + local network. Every redirect is checked the same way. At most 1 MB and 15 s in all (redirects included); a server + that sends slowly is cut off. The check logs nothing about the address. The collected text is web content: it goes only to `//.jsonl` (one JSON object per line: `at`, then `title`, `url`, `text` as the kind has them), never to the brain or a log. - Day files older than `keepDays` are deleted in every folder of `dir` at each check, also of diff --git a/tests/test_voice_worker_collect.py b/tests/test_voice_worker_collect.py index 257420a..f31800c 100644 --- a/tests/test_voice_worker_collect.py +++ b/tests/test_voice_worker_collect.py @@ -8,13 +8,18 @@ and nothing collected reaches the log. from __future__ import annotations +import http.server +import ipaddress import json +import socket +import threading import time from datetime import datetime, timedelta from pathlib import Path import pytest +import voice_worker.collect as collect from voice_worker.collect import Collector, load_config, safe_get RSS = """feed @@ -131,6 +136,17 @@ def test_a_site_is_kept_only_when_it_changed(tmp_path): assert [i["text"] for i in items(tmp_path, "site")] == ["Version 1 is out", "Version 2 is out"] +def test_a_site_whose_title_alone_changed_is_kept_again(tmp_path): + page = "{t}

Same body text

" + fake = Fake({"https://s.example/": page.format(t="Old")}) + c = Collector(config(tmp_path, [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 15}]), + fetch=fake) + c.run_due(now=0.0) + fake.pages["https://s.example/"] = page.format(t="New") + c.run_due(now=900.0) + assert [i["title"] for i in items(tmp_path, "site")] == ["Old", "New"] + + def test_a_target_runs_again_only_after_its_interval_also_after_a_restart(tmp_path): fake = Fake({"https://s.example/": PAGE.format(v=1)}) targets = [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 60}] @@ -186,3 +202,120 @@ def test_the_thread_collects_on_its_own_and_stops(tmp_path): time.sleep(0.02) c.stop() assert not c.running() + + +# ---- the real fetcher, against local servers ----------------------------------------------------- + +def serve(handler): + """A local HTTP server on 127.0.0.1; returns (port, hits list).""" + hits = [] + + class H(http.server.BaseHTTPRequestHandler): + def do_GET(self): + hits.append(self.path) + handler(self) + + def log_message(self, *a): + pass + + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H) + srv.daemon_threads = True + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv.server_address[1], hits + + +def answer(body, status=200, headers=()): + def h(req): + req.send_response(status) + for k, v in headers: + req.send_header(k, v) + req.send_header("Content-Length", str(len(body))) + req.end_headers() + req.wfile.write(body) + return h + + +@pytest.fixture +def loopback_is_public(monkeypatch): + """Lets the fetcher reach the local test servers; every other private address stays refused.""" + real = collect._is_public_ip + monkeypatch.setattr(collect, "_is_public_ip", lambda ip: ip == ipaddress.ip_address("127.0.0.1") or real(ip)) + + +def test_the_fetcher_follows_redirects_and_checks_every_hop(loopback_is_public): + def h(req): + if req.path == "/start": + answer(b"", 302, [("Location", "/end?x=1")])(req) + elif req.path == "/private": + answer(b"", 302, [("Location", "http://10.0.0.1/")])(req) + else: + answer(b"the body")(req) + port, hits = serve(h) + assert safe_get(f"http://127.0.0.1:{port}/start") == b"the body" + assert hits == ["/start", "/end?x=1"] + with pytest.raises(ValueError): + safe_get(f"http://127.0.0.1:{port}/private") + + +def test_the_fetcher_connects_to_the_address_it_checked(monkeypatch): + """A name that resolves to a public address when checked and to a private one afterwards + (DNS rebinding) never reaches the private one.""" + port, hits = serve(answer(b"internal")) + calls = [] + + def resolve(host, *a, **k): + if host == "rebind.example": + calls.append(host) + ip = "1.1.1.1" if len(calls) == 1 else "127.0.0.1" + else: # an address resolves to itself + ip = host + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port))] + + monkeypatch.setattr(socket, "getaddrinfo", resolve) + monkeypatch.setattr(collect, "CONNECT_S", 0.3) + with pytest.raises(Exception): + safe_get(f"http://rebind.example:{port}/") + assert hits == [] + + +def test_the_fetcher_tries_the_next_checked_address_when_one_does_not_connect(loopback_is_public, monkeypatch): + port, hits = serve(answer(b"from the second address")) + real = socket.getaddrinfo + monkeypatch.setattr(socket, "getaddrinfo", lambda host, *a, **k: [ + (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("1.1.1.1", port)), + (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))] if host == "two.example" else real(host, *a, **k)) + monkeypatch.setattr(collect, "CONNECT_S", 0.3) + assert safe_get(f"http://two.example:{port}/") == b"from the second address" + assert hits == ["/"] + + +def test_the_fetcher_stops_a_server_that_sends_slowly(loopback_is_public, monkeypatch): + def drip(req): + req.send_response(200) + req.send_header("Content-Length", "100000") + req.end_headers() + try: + for _ in range(100): + req.wfile.write(b"x") + req.wfile.flush() + time.sleep(0.1) + except OSError: + pass + port, _ = serve(drip) + monkeypatch.setattr(collect, "TOTAL_S", 1.0) + monkeypatch.setattr(collect, "READ_S", 0.5) + t0 = time.monotonic() + with pytest.raises(Exception): + safe_get(f"http://127.0.0.1:{port}/") + assert time.monotonic() - t0 < 1.5 + + +def test_the_fetcher_never_logs_the_address(monkeypatch, capfd): + import jarvis.debug + monkeypatch.setattr(jarvis.debug, "_is_debug_enabled", lambda: True) + monkeypatch.setattr(socket, "getaddrinfo", + lambda host, *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 80))]) + with pytest.raises(ValueError): + safe_get("http://secret-host.example/private/path?token=abc123") + out = capfd.readouterr() + assert "secret-host" not in out.err + out.out and "abc123" not in out.err + out.out