Compare commits
20 Commits
v1.5.1
...
4f90701112
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f90701112 | ||
|
|
4a15384bc6 | ||
|
|
bb60c4db3b | ||
|
|
8562548571 | ||
|
|
db51bb92e6 | ||
|
|
ffc16665e5 | ||
|
|
5629da7e9f | ||
|
|
83999a5b0b | ||
|
|
d5fd218c86 | ||
|
|
23b1fe692b | ||
|
|
7bb9718c34 | ||
|
|
7da2fcb5e5 | ||
|
|
680f5a656a | ||
|
|
b52ffd2b18 | ||
|
|
140fc56f18 | ||
|
|
5ee47827f3 | ||
|
|
c189ce2e65 | ||
|
|
086dd5cde7 | ||
|
|
f64d76e737 | ||
|
|
11c3621093 |
61
.env.example
61
.env.example
@@ -29,29 +29,45 @@ BRIDGE_PORT=8765
|
||||
JARVIS_BRAIN_ENABLED=1
|
||||
JARVIS_TTS_ENABLED=1
|
||||
# faster-whisper device/compute. GPU by default (RTX 5050 / sm_120, verified).
|
||||
# Falls back to CPU automatically if no GPU is passed to the container.
|
||||
# On a NO-GPU host (e.g. an app host that offloads the LLM to a separate GPU box)
|
||||
# set WHISPER_DEVICE=cpu AND WHISPER_COMPUTE_TYPE=int8 — float16 is GPU-only, so
|
||||
# CPU needs int8 (STT is slower on CPU).
|
||||
WHISPER_DEVICE=cuda
|
||||
WHISPER_COMPUTE_TYPE=float16
|
||||
# Optional explicit Piper voice model (.onnx). If empty, the jarvis default is used.
|
||||
TTS_PIPER_MODEL_PATH=
|
||||
# TTS engine: "melo" (default) uses the MeloTTS Korean voice served by the warm
|
||||
# melo-worker (Korean speaker, speed 1.5). Set to "piper" to use Piper directly.
|
||||
# TTS engine:
|
||||
# melo (default) GPU MeloTTS — offline Korean voice, privacy-first (text never
|
||||
# leaves the host), synthesises on the GPU via the melo-worker. Needs a
|
||||
# GPU (MELO_DEVICE=cuda); falls back to CPU (slow) with MELO_DEVICE=cpu.
|
||||
# edge Microsoft Edge TTS — natural Korean neural voice, but ONLINE: reply
|
||||
# text is sent to Microsoft's servers and needs internet.
|
||||
# piper offline English voice (fallback).
|
||||
TTS_ENGINE=melo
|
||||
# Melo-only by default: if MeloTTS synthesis fails the bridge returns no audio
|
||||
# rather than speaking Korean through the English Piper voice (which mangles it).
|
||||
# Set to 1 only if you explicitly want the Piper fallback.
|
||||
MELO_FALLBACK_PIPER=0
|
||||
# Where the bridge reaches the in-container MeloTTS worker, and how long it
|
||||
# waits for a synthesis. Speaking rate is set on the worker via MELO_SPEED.
|
||||
MELO_WORKER_URL=http://127.0.0.1:8770
|
||||
MELO_TIMEOUT=30
|
||||
# GPU MeloTTS knobs (used when TTS_ENGINE=melo).
|
||||
MELO_DEVICE=cuda
|
||||
MELO_SPEED=1.5
|
||||
# Edge voice + speaking rate (used when TTS_ENGINE=edge). Rate is a percentage
|
||||
# (+45% ≈ 1.45×). Korean voices: ko-KR-HyunsuMultilingualNeural (M),
|
||||
# ko-KR-InJoonNeural (M), ko-KR-SunHiNeural (F).
|
||||
EDGE_TTS_VOICE=ko-KR-HyunsuMultilingualNeural
|
||||
EDGE_TTS_RATE=+45%
|
||||
# Neural-only by default: if synthesis fails the bridge returns no audio rather
|
||||
# than speaking Korean through the English Piper voice. Set to 1 to allow the
|
||||
# Piper fallback.
|
||||
MELO_FALLBACK_PIPER=0
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Jarvis brain (Ollama-backed). In Docker these populate the rendered
|
||||
# config (docker/jarvis-config.template.json). See src/jarvis/config.py.
|
||||
# ---------------------------------------------------------------------------
|
||||
# In docker-compose this is overridden to http://ollama:11434 automatically.
|
||||
# In docker-compose this defaults to the in-stack `ollama` service
|
||||
# (http://ollama:11434). To use an EXTERNAL Ollama on another LAN machine (e.g. a
|
||||
# GPU host), set it here to that host's IP — the compose now respects this value:
|
||||
# OLLAMA_BASE_URL=http://192.168.10.9:11434 # Ollama runs on the .9 host
|
||||
# In that split setup: do NOT start the in-stack ollama/ollama-init (run
|
||||
# `docker compose up -d javis`), pull the models on the LLM host, and make that
|
||||
# host's Ollama listen on the LAN (OLLAMA_HOST=0.0.0.0:11434).
|
||||
OLLAMA_BASE_URL=http://127.0.0.1:11434
|
||||
# qwen2.5:3b — small non-reasoning instruct model. ~2.4GB, runs 100% on the GPU
|
||||
# (the 8B offloads ~8% to CPU), warm voice turns ~2-4s vs ~5-7s on 8B. Clean
|
||||
@@ -59,11 +75,15 @@ OLLAMA_BASE_URL=http://127.0.0.1:11434
|
||||
# free-form chit-chat. Swap back to qwen3:8b for the strongest tool-calling.
|
||||
OLLAMA_CHAT_MODEL=qwen2.5:3b
|
||||
# Model for the auxiliary small-model calls: intent judge, tool router, weather
|
||||
# place extraction, query decomposition. BLANK (default) reuses OLLAMA_CHAT_MODEL
|
||||
# so the stack runs on one already-warm model. The code's built-in default
|
||||
# (gemma4:e2b) is NOT pulled by this stack, so leaving this unset previously made
|
||||
# every router/extractor call silently fail. Only set this if you also pull the
|
||||
# model into Ollama.
|
||||
# place extraction, query decomposition. These are classification/JSON calls,
|
||||
# NOT the spoken answer, so a small fast model here cuts 2-3 big-model round
|
||||
# trips per command without touching answer quality. BLANK uses the stack
|
||||
# default qwen2.5:3b, which ollama-init pulls automatically. Set it equal to
|
||||
# OLLAMA_CHAT_MODEL to run everything on one resident model instead (saves VRAM
|
||||
# at the cost of slower routing when the chat model is large).
|
||||
# NEVER set this LARGER than OLLAMA_CHAT_MODEL: the auxiliary calls would then
|
||||
# run on the bigger, slower model and add latency to every command (the exact
|
||||
# opposite of the split's purpose). Keep it <= the chat model, blank, or equal.
|
||||
OLLAMA_INTENT_MODEL=
|
||||
OLLAMA_EMBED_MODEL=nomic-embed-text
|
||||
WHISPER_MODEL=small
|
||||
@@ -77,7 +97,7 @@ OUTPUT_LANGUAGE=
|
||||
# Operator instruction folder: every *.md in this dir is appended to the main
|
||||
# reply LLM's system prompt (filename order), re-read each turn so edits apply
|
||||
# without a rebuild/restart. ./agents is bind-mounted here read-only; only
|
||||
# change this to relocate the folder inside the container. See README "운영자 지시문".
|
||||
# change this to relocate the folder inside the container. See docs/v1/README.md "운영자 지시문".
|
||||
AGENTS_DIR=/app/agents
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -193,6 +213,10 @@ VOICE_SILENCE_MS=800
|
||||
# full (default) everything in one container
|
||||
# browser ONLY the desktop + Chrome + control-server (driven over the LAN)
|
||||
# bot ONLY the bot + bridge + TTS (drives a REMOTE browser)
|
||||
# brain ONLY the bridge (STT + reply + TTS) on a GPU host — no bot/desktop.
|
||||
# The app host reaches it via BRIDGE_URL. See docs/DEPLOY.md "GPU split".
|
||||
# app the bot + desktop/Chrome, but NOT the local bridge: offloads
|
||||
# STT/LLM/TTS to a remote brain host (set BRIDGE_URL=http://<brain>:8765).
|
||||
JARVIS_ROLE=full
|
||||
|
||||
# --- GPU per OS: pick the matching compose override via COMPOSE_FILE ---
|
||||
@@ -226,6 +250,7 @@ COMPOSE_FILE=docker-compose.yml:docker-compose.gpu-linux.yml
|
||||
# OLLAMA_CHAT_MODEL=qwen2.5:7b # quality (needs ~5GB VRAM + whisper small)
|
||||
# OLLAMA_CHAT_MODEL=qwen2.5:3b # speed (fits easily, faster on 8GB GPUs)
|
||||
# WHISPER_MODEL=small # small frees VRAM for a bigger LLM; medium=more accurate
|
||||
# STT_BEAM_SIZE=5 # beam search (5) > greedy (1) for accuracy; lower for speed
|
||||
# MELO_DEVICE=cuda # cpu if no GPU on the bot host
|
||||
|
||||
# --- Settings web UI (http://localhost:8765/settings on the bot host) ---
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Data privacy comes first, always.
|
||||
|
||||
All user-facing command line output should make use of emojis. Especially an initial emoji to start off the lines that depict what the line is about. Output should make use of indentation spacing to establish a visual hierarchy and aim to make output as easy to sift through as possible. Exception: Windows .bat scripts cannot use emojis (cmd.exe doesn't render Unicode properly).
|
||||
This assistant is used through a Discord bot with voice (TTS) replies, not a CLI. Do not add emojis to user-facing assistant output. Keep output plain and readable. (Runtime assistant behaviour lives in `agents/*.md`, which is injected into the reply LLM's prompt.)
|
||||
|
||||
Any important point in our logical flows should have debug logs using the `debug_log` method from `src/jarvis/debug.py`. Avoid excessive logging to keep the logs easily readable and actionable.
|
||||
|
||||
|
||||
23
Dockerfile
23
Dockerfile
@@ -65,20 +65,23 @@ RUN ls -d /opt/venv/lib/python*/site-packages/nvidia/cublas/lib \
|
||||
> /etc/ld.so.conf.d/nvidia-cu12.conf 2>/dev/null \
|
||||
&& /sbin/ldconfig || true
|
||||
|
||||
# --- MeloTTS Korean voice (separate /opt/melo py3.11 venv; see setup-melo.sh).
|
||||
# Heavy layer (torch CPU + transformers + MeCab); placed before the app
|
||||
# COPY so it stays cached across source-only changes. ---
|
||||
# --- Korean voice: GPU MeloTTS (offline, privacy-first) in a separate /opt/melo
|
||||
# py3.11 venv; see docker/setup-melo.sh. Heavy layer (torch cu128 GPU +
|
||||
# transformers + MeCab + baked KR model), placed before the app COPY so it
|
||||
# stays cached across source-only changes. Runtime device is MELO_DEVICE=cuda
|
||||
# (compose), so TTS synthesises on the GPU next to Ollama + Whisper. Started
|
||||
# only in full/bot/brain roles (see docker/supervisord.conf). The offline
|
||||
# Edge TTS (`edge-tts`, in requirements-bridge.txt) remains available as an
|
||||
# opt-in fallback via TTS_ENGINE=edge, but it is ONLINE (text leaves the
|
||||
# host), so MeloTTS is the default. ---
|
||||
COPY docker/setup-melo.sh /app/docker/setup-melo.sh
|
||||
# Strip CR before running: a Windows checkout (autocrlf) yields CRLF, which makes
|
||||
# bash read line 18 as `set -euxo pipefail\r` and abort with
|
||||
# "set: pipefail: invalid option name". .gitattributes pins *.sh to LF, but this
|
||||
# keeps the build working even on a not-yet-renormalised working tree.
|
||||
# Strip CR first: a Windows (autocrlf) checkout yields CRLF, which makes bash
|
||||
# read `set -euxo pipefail\r` and abort. Idempotent on an LF tree.
|
||||
RUN sed -i 's/\r$//' /app/docker/setup-melo.sh && bash /app/docker/setup-melo.sh
|
||||
|
||||
# --- Human input + window management for the on-screen Chrome control tool.
|
||||
# Placed AFTER the heavy melo layer so it doesn't bust that cache. xdotool
|
||||
# injects real X pointer/keyboard events (visible cursor, char-by-char
|
||||
# typing) into the broadcast; wmctrl lists/moves windows. ---
|
||||
# xdotool injects real X pointer/keyboard events (visible cursor,
|
||||
# char-by-char typing) into the broadcast; wmctrl lists/moves windows. ---
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
xdotool wmctrl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
344
README.md
344
README.md
@@ -1,280 +1,86 @@
|
||||
# Javis Bot
|
||||
|
||||
Ubuntu 데스크톱(VNC) 위에서 도는 **디스코드 네이티브 음성 비서**입니다.
|
||||
[isair/jarvis](https://github.com/isair/jarvis)의 성숙한 AI "두뇌"(메모리·툴·답변엔진·STT/TTS)를 그대로 쓰면서,
|
||||
입출력 인터페이스를 로컬 마이크/스피커에서 **디스코드 음성 + 화면 방송**으로 바꾼 하이브리드 구성입니다.
|
||||
|
||||
- 🎙️ 디스코드 음성 채널에서 말로 대화 (음성 입력 → 두뇌 → 음성 출력)
|
||||
- 🖥️ VNC 화면을 디스코드로 송출해서 같이 보기 (셀프봇 실시간 / noVNC / 스크린샷 선택)
|
||||
- ⌨️ `/자비스` 슬래시 명령으로 호출 — 호출한 사람이 음성 채널에 있으면 그 채널로 접속
|
||||
- 🔒 모든 슬래시 명령 응답은 **호출한 사람만 보이는 ephemeral** 메시지
|
||||
- 🧠 크롬/웹 제어, 메모리, MCP 툴 등 jarvis의 기능 유지
|
||||
|
||||
> 언어 선택 근거(Python 유지 vs 재작성)는 [docs/language-comparison.md](docs/language-comparison.md) 참고.
|
||||
> VNC + XFCE 호스트 셋업은 [docs/vnc-xfce-setup.md](docs/vnc-xfce-setup.md) 참고.
|
||||
> 원본 jarvis README는 [docs/UPSTREAM-README.md](docs/UPSTREAM-README.md)에 보존했습니다.
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처 (하이브리드)
|
||||
|
||||
```
|
||||
Discord ──voice / video / slash──▶ bot/ (Node + bun, discord.js)
|
||||
│ HTTP(localhost)
|
||||
▼
|
||||
bridge/ (Python, Flask)
|
||||
│ in-process import
|
||||
▼
|
||||
src/jarvis (기존 두뇌: STT·답변엔진·메모리·툴·TTS)
|
||||
```
|
||||
|
||||
- **bot/** — 디스코드 관련 전부. 슬래시 명령, 음성 송수신, VNC 화면 송출. AI 로직 없음.
|
||||
- **bridge/** — 얇은 HTTP 서비스. 음성(WAV) → 텍스트(STT) → 두뇌(답변) → 음성(TTS).
|
||||
- **src/jarvis** — 원본 jarvis 두뇌. 거의 손대지 않음. (PyQt 데스크톱 GUI/단축키 받아쓰기는 이 배포에선 사용하지 않음.)
|
||||
|
||||
왜 이렇게? 디스코드 봇은 정책상 영상(Go Live)을 송출할 수 없고, 봇 영상 송출이 되는 라이브러리는 Node 전용 + 셀프봇만 가능합니다. 반면 jarvis 두뇌는 검증된 Python 39k줄입니다. 그래서 영상이 가능한 Node로 인터페이스만 새로 짜고 두뇌는 Python 그대로 두는 하이브리드가 비용/위험 대비 최선입니다.
|
||||
|
||||
---
|
||||
|
||||
## 요구 사항
|
||||
|
||||
Docker로 돌리면(권장) 호스트에는 Docker + (GPU 쓸 경우) NVIDIA 드라이버만 있으면 되고, Python/bun/Ollama/ffmpeg/Whisper/Piper는 전부 컨테이너 안에 포함됩니다.
|
||||
|
||||
OS별 호스트 준비물:
|
||||
|
||||
| | Linux (Ubuntu 등) | Windows 11 |
|
||||
|---|---|---|
|
||||
| 컨테이너 런타임 | Docker Engine (CDI 지원, Docker 25+) | Docker Desktop + WSL2 백엔드 |
|
||||
| GPU 가속(선택) | `nvidia-container-toolkit` + `nvidia-ctk cdi generate` | NVIDIA 드라이버 + Docker Desktop GPU(WSL2) 활성화 |
|
||||
| GPU 넣는 compose | `docker-compose.gpu-linux.yml` | `docker-compose.gpu-windows.yml` |
|
||||
|
||||
- 디스코드 **봇** 토큰 1개 (음성/슬래시) — 또는 (셀프봇 송출 사용 시) 디스코드 **버너 유저** 토큰 1개
|
||||
- (도커 없이 수동 실행 시에만) Python 3.11+, [bun](https://bun.sh), Ollama, `ffmpeg`를 호스트에 직접 설치 — 아래 "수동" 절 참고
|
||||
|
||||
> VNC 데스크톱 호스트를 직접 구성하는 경우(도커 미사용)는 `docs/vnc-xfce-setup.md` 참고. 도커 실행에서는 VNC+XFCE가 컨테이너 안에 이미 들어 있습니다.
|
||||
|
||||
---
|
||||
|
||||
## 실행 — Docker (권장)
|
||||
|
||||
환경 설정 없이 통째로 컨테이너에서 돌립니다. VNC 데스크톱 + 크롬 + Python 브릿지 + Node 봇이 한 컨테이너(`javis`)에, LLM 백엔드(Ollama)가 별도 컨테이너에 뜹니다. **올리기만 하면 Ollama 모델까지 자동으로** 받아집니다.
|
||||
|
||||
베이스 `docker-compose.yml`에는 GPU 설정이 없습니다(이식성 유지). GPU는 OS에 맞는 override 파일을 같이 얹어서 켭니다. **돌리는 OS에 따라 명령이 다릅니다:**
|
||||
|
||||
```bash
|
||||
# ── Linux (Ubuntu 등, nvidia-container-toolkit + CDI) ──
|
||||
docker compose -f docker-compose.yml -f docker-compose.gpu-linux.yml up -d --build
|
||||
|
||||
# ── Windows 11 (Docker Desktop + WSL2 + NVIDIA) ──
|
||||
docker compose -f docker-compose.yml -f docker-compose.gpu-windows.yml up -d --build
|
||||
|
||||
# ── GPU 없이 (CPU 전용 호스트) ──
|
||||
# .env 에 WHISPER_DEVICE=cpu, MELO_DEVICE=cpu 를 넣고 베이스만 사용
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
매번 `-f`를 치기 싫으면 `.env`에 한 줄 넣어두면 그냥 `docker compose up -d`로 됩니다(override가 자동 적용):
|
||||
|
||||
```bash
|
||||
# Linux / macOS (구분자 = 콜론 ":")
|
||||
COMPOSE_FILE=docker-compose.yml:docker-compose.gpu-linux.yml
|
||||
# Windows 11 (구분자 = 세미콜론 ";" — 콜론은 드라이브 문자 C: 와 충돌)
|
||||
COMPOSE_FILE=docker-compose.yml;docker-compose.gpu-windows.yml
|
||||
```
|
||||
|
||||
> ⚠️ `COMPOSE_FILE`의 파일 구분자는 OS마다 다릅니다: Linux/macOS는 `:`, Windows는 `;`. Windows에서 `:`를 쓰면 Docker가 전체를 파일 하나 이름으로 읽어 `... The system cannot find the file specified` 에러가 납니다. 헷갈리면 `COMPOSE_FILE`을 비워두고 실행 시 직접 지정하세요: `docker compose -f docker-compose.yml -f docker-compose.gpu-windows.yml up -d --build`.
|
||||
|
||||
> Linux와 Windows는 GPU를 컨테이너에 넣는 방식이 달라서 override 파일이 갈립니다. Linux는 CDI(`devices: nvidia.com/gpu=all`), Windows(Docker Desktop)는 Compose의 `deploy.resources.reservations.devices`(`driver: nvidia`)를 씁니다. 호스트 사전 준비는 아래 "GPU 가속" 절 참고.
|
||||
|
||||
`docker compose up` 한 번이면 자동으로:
|
||||
- Ollama 서버가 뜨고, `ollama-init`이 채팅/임베딩 모델을 **자동 pull**
|
||||
- VNC+XFCE 데스크톱 + 크롬 + Python 브릿지가 기동
|
||||
- Whisper STT 모델 / Piper TTS 음성 자동 다운로드(볼륨에 캐시)
|
||||
|
||||
화면 보기: VNC 뷰어 → `localhost:5901` (비밀번호 = `.env`의 `VNC_PASSWORD`, 기본 `javis123`) 또는 브라우저 → `http://localhost:6080/vnc.html`.
|
||||
로그: `docker compose logs -f javis`.
|
||||
|
||||
### 디스코드 토큰은 마지막에
|
||||
|
||||
토큰 없이도 위의 모든 게 정상 동작합니다(봇만 대기). 준비되면 `.env`를 만들어 토큰을 채웁니다.
|
||||
|
||||
기본 모드는 **유저봇(selfbot)** 입니다. 음성 참여와 화면 송출(Go Live)을 한 유저 계정으로 처리하며, Discord가 일반 봇 계정에는 Go Live를 허용하지 않기 때문에 이 방식이 기본입니다.
|
||||
|
||||
```bash
|
||||
cp .env.example .env # DISCORD_SELFBOT_TOKEN(버너 계정) + DISCORD_VOICE_CHANNEL_ID 채우기
|
||||
docker compose up -d # 유저봇이 로그인해 지정 음성채널에 자동 참여
|
||||
```
|
||||
|
||||
유저봇은 슬래시 명령을 쓸 수 없으므로 텍스트로 제어합니다: 음성 채널에서 `!자비스 join` / `!자비스 leave`. `DISCORD_VOICE_CHANNEL_ID`를 채워두면 시작 시 자동 참여합니다.
|
||||
|
||||
> ⚠️ 유저봇은 Discord ToS 위반이며 계정 정지 위험이 있습니다. 반드시 일회용 **버너 계정** 토큰만 사용하세요. 자세한 주의사항은 아래 "셀프봇 주의" 절을 참고하세요.
|
||||
|
||||
일반 봇(슬래시 명령 `/자비스`)으로 돌리려면 `DISCORD_BOT_TOKEN` / `DISCORD_APP_ID` / `DISCORD_GUILD_ID`를 채우세요. 다만 일반 봇은 화면 송출(Go Live)을 할 수 없습니다. `DISCORD_BOT_TOKEN`이 비어 있고 `DISCORD_SELFBOT_TOKEN`이 있으면 자동으로 유저봇 모드로 동작합니다. (`OLLAMA_CHAT_MODEL` 등 모델을 바꾸려면 `.env`에서 지정 후 `docker compose up -d`.)
|
||||
|
||||
### GPU 가속 (OS별)
|
||||
|
||||
LLM(Ollama), Whisper STT, MeloTTS가 GPU에서 돕니다(env 기본 `WHISPER_DEVICE=cuda`, `MELO_DEVICE=cuda`). NVIDIA Blackwell(sm_120, 예: RTX 5050/5070Ti)에서 검증: 컨테이너 내 torch cu128 CUDA 동작, Ollama GPU 오프로드, faster-whisper float16, MeloTTS GPU 합성 모두 확인.
|
||||
|
||||
GPU는 위 "실행 — Docker"의 OS별 override 파일로 켜집니다. 호스트 사전 준비는 OS마다 다릅니다:
|
||||
|
||||
**Linux (Ubuntu 등) — CDI 방식, 1회:**
|
||||
|
||||
```bash
|
||||
# nvidia-container-toolkit 설치 후 CDI 스펙 생성 (Docker 25+ CDI, 데몬 재시작 불필요)
|
||||
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
|
||||
docker run --rm --device nvidia.com/gpu=all ubuntu nvidia-smi -L # GPU 보이면 OK
|
||||
```
|
||||
|
||||
`docker-compose.gpu-linux.yml`이 두 컨테이너에 `devices: ["nvidia.com/gpu=all"]`(CDI)로 GPU를 넣습니다.
|
||||
|
||||
**Windows 11 — Docker Desktop + WSL2:**
|
||||
|
||||
- 최신 NVIDIA 게임/스튜디오 드라이버 설치(별도 CUDA 툴킷 불필요).
|
||||
- Docker Desktop → Settings → Resources → WSL Integration 활성화(WSL2 백엔드). 최신 Docker Desktop은 WSL2에서 GPU를 자동 노출합니다.
|
||||
- 확인: PowerShell에서 `docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi`.
|
||||
- `docker-compose.gpu-windows.yml`이 `deploy.resources.reservations.devices`(`driver: nvidia`, `count: all`)로 GPU를 넣습니다.
|
||||
|
||||
**공통:**
|
||||
|
||||
- 모델: 베이스 compose 기본은 `qwen2.5:3b`(8GB VRAM에서 도구호출 안정적). 더 무겁게(`qwen2.5:7b`, `qwen3:8b` 등) 쓰려면 `.env`의 `OLLAMA_CHAT_MODEL` 변경.
|
||||
- **GPU가 없거나 인식 실패 시 자동으로 CPU 폴백**(Whisper)하므로 안전합니다. 명시적으로 CPU만 쓰려면 override 파일 없이 베이스만 올리고 `.env`에 `WHISPER_DEVICE=cpu`, `MELO_DEVICE=cpu`를 두세요.
|
||||
|
||||
- 데이터(메모리 DB), Whisper 캐시, Piper 음성은 named volume에 영속됩니다.
|
||||
- 셀프봇 영상 송출 의존성은 이미지에 기본 포함하지 않습니다. 쓰려면 컨테이너에서 `cd /app/bot && bun add discord.js-selfbot-v13 @dank074/discord-video-stream` 후 재시작(또는 Dockerfile에 추가).
|
||||
|
||||
---
|
||||
|
||||
## 실행 — 수동(도커 없이)
|
||||
|
||||
도커 없이 호스트에서 직접 돌릴 때는 OS별로 venv 활성화·ffmpeg 설치·실행 스크립트가 다릅니다.
|
||||
|
||||
**Linux / macOS:**
|
||||
|
||||
```bash
|
||||
# 1) 환경 변수
|
||||
cp .env.example .env # DISCORD_BOT_TOKEN / DISCORD_APP_ID / DISCORD_GUILD_ID 등 채우기
|
||||
|
||||
# 2) Python 두뇌 + 브릿지 의존성
|
||||
python3 -m venv .venv && . .venv/bin/activate
|
||||
pip install -r requirements.txt # jarvis 두뇌
|
||||
pip install flask # 브릿지(없으면)
|
||||
|
||||
# 3) 디스코드 봇 의존성 (bun)
|
||||
cd bot && bun install && cd ..
|
||||
|
||||
# 4) 한 번에 실행 (브릿지 + 봇)
|
||||
./scripts/dev.sh
|
||||
# 또는 따로: ./scripts/start_bridge.sh / ./scripts/start_bot.sh
|
||||
```
|
||||
|
||||
- `ffmpeg`: Ubuntu `sudo apt install ffmpeg`, macOS `brew install ffmpeg`.
|
||||
|
||||
**Windows 11 (PowerShell):**
|
||||
|
||||
```powershell
|
||||
# 1) 환경 변수
|
||||
copy .env.example .env # 같은 키들 채우기
|
||||
|
||||
# 2) Python 두뇌 + 브릿지 의존성 (venv 활성화 경로가 다름)
|
||||
py -3 -m venv .venv; .\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
pip install flask
|
||||
|
||||
# 3) 디스코드 봇 의존성 (bun — Windows 네이티브 또는 WSL2)
|
||||
cd bot; bun install; cd ..
|
||||
|
||||
# 4) 실행: .sh 스크립트는 bash 전용이라 Windows에서는 두 프로세스를 따로 띄웁니다
|
||||
# (PowerShell 창 2개, 또는 WSL2에서 위 Linux 절차 그대로 사용 권장)
|
||||
python -m bridge.server # 창 1: 브릿지
|
||||
cd bot; bun run register; bun run start # 창 2: (일반 봇이면) 슬래시 등록 후 봇 기동
|
||||
```
|
||||
|
||||
- `ffmpeg`: `winget install Gyan.FFmpeg` 또는 `choco install ffmpeg` 후 PATH 확인.
|
||||
- `scripts/*.sh`(dev/start_bridge/start_bot)는 bash 스크립트라 순수 Windows에선 동작하지 않습니다. 가장 간단한 길은 **WSL2 안에서 위 Linux 절차를 그대로** 쓰는 것입니다(도커도 WSL2 백엔드와 동일).
|
||||
|
||||
봇이 뜨면 디스코드에서 `/자비스 join` 으로 음성 채널에 부르세요.
|
||||
|
||||
---
|
||||
|
||||
## 슬래시 명령 (`/자비스`)
|
||||
|
||||
| 명령 | 동작 |
|
||||
# Javis Bot v2
|
||||
|
||||
게임PC 한 대에서 **완전 로컬**로 도는 디스코드 음성 비서입니다. 설치 파일 하나로 깔리는 **Windows 관리 앱(exe)** 에서 모든 설정과 관리를 합니다.
|
||||
|
||||
> **상태: 설계 단계.** 이 문서와 [docs/v2/](docs/v2/)는 v2 계획입니다. 지금 저장소의 코드는 v1(Docker + VNC 구성)이고, v1 사용법은 [docs/v1/README.md](docs/v1/README.md)에 있습니다.
|
||||
|
||||
## 개인정보 우선
|
||||
|
||||
- 음성 인식(STT), 답변(LLM), 음성 합성(TTS)을 모두 게임PC 안에서 처리합니다. 클라우드 AI API는 쓰지 않습니다. 밖으로 나가는 요청은 웹 검색과 날씨 조회뿐입니다.
|
||||
- 음성 원본과 화면 캡처는 기본적으로 저장하지 않습니다.
|
||||
- 대화 기록은 사람별로 보고 지울 수 있습니다.
|
||||
- 봇 토큰 같은 비밀값은 Windows DPAPI로 암호화해서 저장합니다.
|
||||
|
||||
자세한 내용: [docs/v2/privacy.md](docs/v2/privacy.md)
|
||||
|
||||
## 주요 기능
|
||||
|
||||
- **빠른 음성 대화**: 말하는 도중에 전사하고 답은 문장 단위로 바로 읽어서, 말이 끝난 뒤 첫 소리까지 약 1~1.5초를 목표로 합니다.
|
||||
- **최대 10명 동시 대화**: 화자별로 따로 받아 전사합니다. 여러 명이 동시에 부를 때 어떻게 답할지(처음 대화만 / 들어온 순서대로 / 마지막 대화만 / 제일 중요한 대화만)는 GUI에서 고릅니다.
|
||||
- **호출어와 지정한 사람**:
|
||||
- 호출어는 GUI에서 여러 개 등록합니다.
|
||||
- "지정한 사람만 응답"과 "지정한 사람은 호출어 없이 대답"을 각각 켜고 끕니다.
|
||||
- **AI 채팅 채널**: 등록한 디스코드 채팅 채널을 자비스가 읽고, 메시지를 보내고, 자기 메시지를 고칩니다. 채널 ID, 이름, 설명은 GUI에서 편집하고, 고친 이름·설명은 실제 디스코드 채널 이름·주제에도 반영합니다(끌 수 있음).
|
||||
- **대화 기억**: 본인이 말했던 기록, 등록한 채팅 채널, 같은 음성 채널에 함께 있던 다른 사람 말에서 이번 질문과 관련된 내용을 찾아 답할 때 참고합니다. 다른 사람 말 참고는 GUI에서 끌 수 있습니다.
|
||||
- **화면 보기**:
|
||||
- 전체 화면, 모니터별, 프로그램(창)별 화면을 자비스가 직접 봅니다.
|
||||
- "2번 화면에 뭐 떠 있어?" 같은 질문도 1.5~2.5초 안에 답하는 것을 목표로 합니다.
|
||||
- 다른 사람의 디스코드 화면공유는 자비스가 말로 공유 창 분리(팝아웃)를 부탁하고, 분리된 창만 캡처해서 봅니다.
|
||||
- **게임 모드**:
|
||||
- 전체화면 게임과 테두리 없는 창 모드 게임을 감지합니다.
|
||||
- 게임 중에는 LLM을 RAM 위주로 옮기거나, 빠른 모델로 바꾸거나, 봇을 일시정지합니다. 세 동작은 각각 켜고 끕니다.
|
||||
- **안티치트 보호**: 뱅가드 같은 안티치트가 걸린 게임이 실행 중이면 키보드·마우스 자동 조작을 막고 그 이유를 알려 줍니다.
|
||||
- **기존 기능 유지**: 메모리, 날씨, 웹 검색, 식단 기록, MCP, 브라우저 제어를 그대로 가져갑니다.
|
||||
- **관리 앱**:
|
||||
- 첫 실행 마법사, 대시보드, 모델 다운로드·전환, 기능별 켜기/끄기를 제공합니다.
|
||||
- 로그 화면에서 로그를 보고, 복사하고, 내려받을 수 있습니다. 비밀값은 자동으로 가립니다.
|
||||
|
||||
## 요구 사항 (예정)
|
||||
|
||||
| 항목 | 기준 |
|
||||
|---|---|
|
||||
| `/자비스 join` | 호출자가 있는 음성 채널에 접속해 듣기 시작 |
|
||||
| `/자비스 leave` | 음성 채널에서 나감 |
|
||||
| `/자비스 ask 질문:<내용>` | 텍스트로 질문하고 답을 받음 |
|
||||
| `/자비스 stream` | VNC 화면을 디스코드에 송출 시작 |
|
||||
| `/자비스 stop` | 송출 중단 |
|
||||
| `/자비스 status` | 브릿지 두뇌/세션/송출 상태 확인 |
|
||||
| OS | Windows 11 |
|
||||
| GPU | NVIDIA RTX 계열, VRAM 16GB 권장 (기준 PC: RTX 5070 Ti 16GB) |
|
||||
| 드라이버 | NVIDIA 580 이상 (CUDA 13). 낮으면 CUDA 12 빌드를 씁니다 |
|
||||
| RAM | 빠름 모델 32GB 이상, 권장 모델 64GB 이상 (기준 PC: 128GB) |
|
||||
| 디스크 | 최소 120GB, 권장 200GB 이상 여유 (NVMe 권장) |
|
||||
| 디스코드 | 봇 토큰 1개. 채팅 채널을 쓰려면 개발자 포털에서 Message Content Intent를 켭니다 |
|
||||
|
||||
모든 응답은 **호출한 사람에게만** 보입니다(ephemeral).
|
||||
Python, CUDA 라이브러리, 모델, 브라우저는 첫 실행 때 사용자가 고른 데이터 폴더에 자동으로 받습니다. 따로 설치할 것은 NVIDIA 드라이버뿐입니다.
|
||||
|
||||
---
|
||||
## 설치 (예정)
|
||||
|
||||
## VNC 화면 송출 백엔드 (`STREAM_BACKEND`)
|
||||
1. 설치 파일(exe)을 실행합니다. 서명되지 않은 파일이라 SmartScreen 경고가 뜨면 "추가 정보 → 실행"을 누릅니다.
|
||||
2. 첫 실행 마법사를 따라갑니다.
|
||||
1. 데이터 폴더를 고릅니다.
|
||||
2. PC 점검을 합니다.
|
||||
3. 모델 프리셋을 고릅니다.
|
||||
4. 자동 설치를 기다립니다.
|
||||
5. 디스코드 봇을 연결합니다.
|
||||
6. 테스트합니다.
|
||||
3. 대시보드에서 봇을 시작합니다.
|
||||
|
||||
`.env`에서 교체 가능합니다. 코드 변경 없이 위험/방식만 바꿉니다.
|
||||
## 알려진 제한 (예정)
|
||||
|
||||
| 값 | 방식 | 실시간 | 디스코드 native | 밴 위험 |
|
||||
|---|---|---|---|---|
|
||||
| `selfbot` (기본) | 버너 유저 계정으로 Go Live 실시간 송출 | ✅ | ✅ | ⚠️ ToS 위반·정지 위험 |
|
||||
| `novnc` | noVNC 브라우저 링크 공유 | ✅ | ❌ | 없음 |
|
||||
| `screenshot` | N초마다 채널에 스크린샷 업로드 | ❌ | ❌ | 없음 |
|
||||
| `none` | 비활성화 | — | — | — |
|
||||
- 저작권 보호 영상, 일부 게임의 독점 전체화면, 최소화된 창은 캡처가 검게 나올 수 있습니다. 게임은 테두리 없는 창 모드면 대부분 보입니다.
|
||||
- 화면 보기는 이미지 입력을 지원하는 LLM에서만 됩니다.
|
||||
- 디스코드 봇은 다른 사람의 메시지를 수정할 수 없습니다. 삭제와 고정만 됩니다.
|
||||
- 공식 봇 계정은 화면공유 영상을 직접 받을 수 없습니다. 그래서 게임PC의 디스코드 앱 창을 캡처하는 방식을 씁니다.
|
||||
|
||||
### 셀프봇(selfbot) 주의
|
||||
## 문서
|
||||
|
||||
- 디스코드 봇은 영상 송출이 불가능해, 실시간 화면 방송은 **유저 계정 토큰(셀프봇)** 으로만 됩니다.
|
||||
- 이는 Discord ToS 위반이며 계정이 영구 정지될 수 있습니다.
|
||||
- 반드시 **버너(일회용) 계정**을 만들어 그 토큰을 `DISCORD_SELFBOT_TOKEN`에 넣고, 본계정은 절대 쓰지 마세요.
|
||||
- 영상 송출만 조용히 하는 패턴은 상대적으로 위험이 낮지만 0은 아닙니다.
|
||||
- 의존성(네이티브)은 선택 설치입니다:
|
||||
```bash
|
||||
cd bot && bun add discord.js-selfbot-v13 @dank074/discord-video-stream
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 환경 변수
|
||||
|
||||
전체 목록과 설명은 [`.env.example`](.env.example)에 있습니다. 핵심:
|
||||
|
||||
- `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`, `DISCORD_GUILD_ID` — 봇/길드
|
||||
- `BRIDGE_URL` — 봇이 호출할 브릿지 주소 (기본 `http://127.0.0.1:8765`)
|
||||
- `STREAM_BACKEND`, `DISCORD_SELFBOT_TOKEN`, `NOVNC_URL` — 화면 송출
|
||||
- `VNC_DISPLAY=:1`, `VNC_RESOLUTION`, `VNC_FRAMERATE`, `VNC_BITRATE_KBPS` — 캡처
|
||||
- `WHISPER_DEVICE/COMPUTE_TYPE`, `MELO_DEVICE` — GPU 호스트면 `cuda`/`float16`, CPU 전용이면 `cpu`(GPU 자체는 OS별 override compose 파일로 켬)
|
||||
- `OLLAMA_CHAT_MODEL` — 두뇌 LLM (기본 `qwen2.5:3b`)
|
||||
- `COMPOSE_FILE` — OS별 GPU override를 매번 `-f`로 안 치고 자동 적용 (위 "실행 — Docker" 참고)
|
||||
- `output_language` — 출력 언어 고정(비우면 사용자 언어). 설정 웹 UI(`/settings`)에서 바꾸면 env 기본값보다 우선하며 컨테이너 재생성 후에도 유지됩니다.
|
||||
- `AGENTS_DIR` — 운영자 지시문 폴더(기본 `/app/agents`, `./agents`가 read-only로 마운트됨). 아래 "운영자 지시문" 참고.
|
||||
|
||||
---
|
||||
|
||||
## 운영자 지시문 (`agents/*.md`)
|
||||
|
||||
`agents/` 폴더에 마크다운 파일을 넣으면 그 내용이 어시스턴트의 메인 답변 시스템 프롬프트 뒤에 그대로 추가됩니다. 페르소나(집사 성격)는 그대로 두고 규칙·말투·금칙어 등을 덧붙일 때 쓰세요.
|
||||
|
||||
- `agents/` 안의 모든 `*.md`를 **파일명 순서**로 이어 붙입니다. 순서를 정하려면 `00-tone.md`, `10-rules.md`처럼 숫자 접두사를 쓰세요.
|
||||
- **매 답변마다 다시 읽습니다.** 파일을 저장하면 다음 발화부터 바로 반영되며, 재빌드/재시작이 필요 없습니다(폴더가 read-only로 마운트됨).
|
||||
- 폴더가 없거나 비어 있으면 아무 일도 일어나지 않습니다(fail-open).
|
||||
- `agents/example.md.sample`을 `rules.md` 등 `*.md`로 복사해서 시작하세요. `.sample` 파일은 로드되지 않습니다.
|
||||
|
||||
---
|
||||
|
||||
## 현재 상태 / 남은 작업
|
||||
|
||||
이 레포는 동작하는 **스캐폴드**입니다. 구조·명령·송출 백엔드·브릿지 연동은 완성되어 있고, 실제 토큰/모델/VNC 디스플레이를 붙여 런타임 검증이 필요한 부분이 남아 있습니다.
|
||||
|
||||
- [ ] 실제 디스코드 봇/버너 토큰으로 음성 송수신 end-to-end 검증
|
||||
- [ ] faster-whisper(CUDA) + Piper 모델로 STT/TTS 실측
|
||||
- [ ] 셀프봇 영상 송출 라이브러리 버전별 API 실연결(현재 v6 API 기준 작성)
|
||||
- [ ] Ollama 모델 다운로드 및 두뇌 응답 품질 점검
|
||||
|
||||
---
|
||||
| 문서 | 내용 |
|
||||
|---|---|
|
||||
| [docs/v2/architecture.md](docs/v2/architecture.md) | 목표, v1과 비교, 하드웨어 자원 배분, 전체 구조, 기술 선택 |
|
||||
| [docs/v2/voice-and-llm.md](docs/v2/voice-and-llm.md) | 실시간 음성 파이프라인(STT, TTS, 지연 목표)과 LLM(Strata, 모델) |
|
||||
| [docs/v2/conversation.md](docs/v2/conversation.md) | 10명 동시 대화, 호출어와 지정한 사람, 응답 정책, AI 채팅 채널 |
|
||||
| [docs/v2/memory.md](docs/v2/memory.md) | 이전 대화 참고(대화 기억) |
|
||||
| [docs/v2/desktop-app.md](docs/v2/desktop-app.md) | 관리 앱: 첫 실행 마법사, 데이터 폴더, 설정 화면, 로그 화면 |
|
||||
| [docs/v2/pc-features.md](docs/v2/pc-features.md) | 게임 모드, 화면 보기, 키보드·마우스와 안티치트, 봇용 크롬창, 화면공유 보기, 정보 수집 |
|
||||
| [docs/v2/privacy.md](docs/v2/privacy.md) | 개인정보·법적 안전장치 |
|
||||
| [docs/v2/roadmap.md](docs/v2/roadmap.md) | 구현 단계(M0~M8)와 위험 요소 |
|
||||
| [docs/v2/decisions.md](docs/v2/decisions.md) | 확정된 결정 |
|
||||
|
||||
## 크레딧
|
||||
|
||||
- 두뇌: [isair/jarvis](https://github.com/isair/jarvis) (라이선스는 [LICENSE](LICENSE) 참고)
|
||||
- 디스코드 음성: [discord.js](https://discord.js.org) / [@discordjs/voice](https://github.com/discordjs/voice)
|
||||
- 영상 송출: [@dank074/discord-video-stream](https://github.com/Discord-RE/Discord-video-stream)
|
||||
두뇌(메모리, 도구, 답변 엔진)는 [isair/jarvis](https://github.com/isair/jarvis)를 기반으로 합니다. 원본 README는 [docs/UPSTREAM-README.md](docs/UPSTREAM-README.md)에 있습니다.
|
||||
|
||||
13
agents/llm.md
Normal file
13
agents/llm.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# 자비스 운영자 지시
|
||||
|
||||
- 너의 이름은 자비스다.
|
||||
- 모든 답변은 음성(TTS)으로 읽혀 나간다. 그러니 무조건 한 문장으로만 답한다. 두 문장 이상 쓰지 않는다. 목록, 마크다운, 이모지, 그리고 소리 내어 읽기 어려운 특수문자는 쓰지 않는다.
|
||||
- 정해진 문구에만 반응하지 말고, 실제 사람처럼 말의 뉘앙스와 맥락으로 의도를 알아듣고 처리한다.
|
||||
|
||||
화면 속 크롬(방송 화면)에서 유튜브를 다룰 때 (화면에 보여야 하므로 반드시 on-screen 브라우저 제어 도구로 수행한다):
|
||||
|
||||
- "유튜브 켜줘" → 방송 크롬에서 유튜브를 연다.
|
||||
- "유튜브에서 OO 검색해줘" → 유튜브로 가서 검색창에 OO를 사람이 직접 타이핑하듯 입력하고 검색한다.
|
||||
- "위에서 N번째 영상 재생해줘" 또는 "왼쪽에서 N번째 영상 재생해줘" → 검색 결과 목록에서 그 위치의 영상을 재생한다.
|
||||
- "일시정지해줘" → 현재 영상을 일시정지한다. "다시 재생해줘" → 이어서 재생한다.
|
||||
- "영상 종료" 또는 "그만 보여줘" → 뒤로 가서 직전 화면으로 돌아간다.
|
||||
@@ -2,10 +2,11 @@
|
||||
// 9222) so the action is visible on the Go-Live broadcast, and prints a JSON
|
||||
// result on stdout for the Python `browseAndSearch` tool to wrap.
|
||||
//
|
||||
// node browse-search.mjs "<query>" [search|youtube]
|
||||
// node browse-search.mjs "<query>" [search|youtube] [index]
|
||||
//
|
||||
// - search : Google-search the query, return the top organic results.
|
||||
// - youtube : search YouTube and play the first result.
|
||||
// - youtube : search YouTube and play a result. `index` is the 1-based position
|
||||
// from the top of the result list (default 1 = first result).
|
||||
//
|
||||
// Backend selection for `search`:
|
||||
// 1. The broadcast Chrome over CDP (visible on the Go-Live stream).
|
||||
@@ -29,6 +30,9 @@ const UA =
|
||||
'(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36';
|
||||
const query = process.argv[2] || '';
|
||||
const mode = (process.argv[3] || 'search').toLowerCase();
|
||||
// 1-based position of the YouTube result to play, counted from the top of the
|
||||
// list. Defaults to 1 (first result). Anything <1 or non-numeric falls back to 1.
|
||||
const playIndex = Math.max(1, parseInt(process.argv[4], 10) || 1);
|
||||
const out = (o) => { process.stdout.write(JSON.stringify(o)); };
|
||||
|
||||
if (!query) { out({ ok: false, error: 'no query' }); process.exit(1); }
|
||||
@@ -105,15 +109,21 @@ try {
|
||||
await page.bringToFront().catch(() => {});
|
||||
|
||||
if (mode === 'youtube') {
|
||||
// Type into YouTube's search box like a person, then play the first result.
|
||||
// Type into YouTube's search box like a person, then play the requested
|
||||
// result (the Nth from the top of the list; default the first).
|
||||
await typeSearch('https://www.youtube.com/?hl=ko', 'input#search, input[name="search_query"]', query);
|
||||
await page.waitForSelector('ytd-video-renderer a#video-title, a#video-title', { timeout: 20000 });
|
||||
const first = page.locator('ytd-video-renderer a#video-title, a#video-title').first();
|
||||
const title = (await first.getAttribute('title').catch(() => '')) || (await first.innerText().catch(() => ''));
|
||||
await first.click();
|
||||
const results = page.locator('ytd-video-renderer a#video-title, a#video-title');
|
||||
// Clamp to what's actually on the page so "play the 5th" still plays the
|
||||
// last available result rather than failing when fewer were returned.
|
||||
const available = await results.count();
|
||||
const targetIdx = Math.min(playIndex, Math.max(available, 1)) - 1;
|
||||
const target = results.nth(targetIdx);
|
||||
const title = (await target.getAttribute('title').catch(() => '')) || (await target.innerText().catch(() => ''));
|
||||
await target.click();
|
||||
await page.waitForSelector('#movie_player', { timeout: 20000 });
|
||||
await page.evaluate(() => { const v = document.querySelector('video'); if (v && v.paused) v.play(); });
|
||||
out({ ok: true, mode, title: (title || '').trim(), url: page.url() });
|
||||
out({ ok: true, mode, index: targetIdx + 1, title: (title || '').trim(), url: page.url() });
|
||||
} else {
|
||||
// Type into Google's search box like a person, then read the results.
|
||||
await typeSearch('https://www.google.com/?hl=ko', 'textarea[name="q"], input[name="q"]', query);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
// status | listTabs
|
||||
// navigate {url} | back | forward | refresh
|
||||
// newTab {url?} | closeTab {index?} | activateTab {index} | closePopups
|
||||
// moveMouse {selector | site} (hover the real cursor, no click)
|
||||
// click {selector} | type {text, selector?} | scroll {dir, notches?}
|
||||
// pressKey {key} | screenshot {path}
|
||||
import { chromium } from 'playwright';
|
||||
@@ -40,6 +41,15 @@ if (!action) { out({ ok: false, error: 'no action' }); process.exit(1); }
|
||||
|
||||
const norm = (u) => (/^https?:\/\//i.test(u) ? u : `https://${u}`);
|
||||
|
||||
// Per-site homepage + search-box selector, shared by `search` and `moveMouse`.
|
||||
const SITES = {
|
||||
naver: { home: 'https://www.naver.com', box: '#query, input[name="query"]' },
|
||||
google: { home: 'https://www.google.com', box: 'textarea[name="q"], input[name="q"]' },
|
||||
daum: { home: 'https://www.daum.net', box: '#q, input[name="q"]' },
|
||||
youtube: { home: 'https://www.youtube.com', box: 'input#search, input[name="search_query"]' },
|
||||
bing: { home: 'https://www.bing.com', box: '#sb_form_q, input[name="q"]' },
|
||||
};
|
||||
|
||||
// The genuinely-active tab is the one whose document is visible. Playwright has
|
||||
// no "active page" accessor over CDP, so probe visibilityState (fixes treating
|
||||
// tab 0 as active and breaking sequential ops on a specific tab).
|
||||
@@ -103,13 +113,6 @@ try {
|
||||
const q = String(cmd.query || '').trim();
|
||||
if (!q) throw new Error('search: no query');
|
||||
const siteKey = String(cmd.site || 'google').toLowerCase();
|
||||
const SITES = {
|
||||
naver: { home: 'https://www.naver.com', box: '#query, input[name="query"]' },
|
||||
google: { home: 'https://www.google.com', box: 'textarea[name="q"], input[name="q"]' },
|
||||
daum: { home: 'https://www.daum.net', box: '#q, input[name="q"]' },
|
||||
youtube: { home: 'https://www.youtube.com', box: 'input#search, input[name="search_query"]' },
|
||||
bing: { home: 'https://www.bing.com', box: '#sb_form_q, input[name="q"]' },
|
||||
};
|
||||
const s = SITES[siteKey] || SITES.google;
|
||||
await front(page);
|
||||
// 1) Go to the homepage.
|
||||
@@ -122,23 +125,31 @@ try {
|
||||
// 2) Click the on-page search box, type the query, submit.
|
||||
const box = page.locator(s.box).first();
|
||||
await box.waitFor({ state: 'visible', timeout: 15000 }).catch(() => {});
|
||||
// Report which input path actually ran: 'human' = real xdotool cursor
|
||||
// move + char typing; 'api-fallback' = the humanClick path threw and we
|
||||
// fell back to cursor-less DOM click/fill; 'api' = no xdotool at all. This
|
||||
// makes "did the cursor really move" verifiable from the result.
|
||||
let searchInput;
|
||||
if (HAS_XDOTOOL && cmd.human !== false) {
|
||||
try {
|
||||
await human.humanClick(page, box);
|
||||
await human.humanType(q);
|
||||
await human.pressKey('Return');
|
||||
searchInput = 'human';
|
||||
} catch {
|
||||
searchInput = 'api-fallback';
|
||||
await box.click().catch(() => {});
|
||||
await box.fill(q).catch(() => {});
|
||||
await page.keyboard.press('Enter').catch(() => {});
|
||||
}
|
||||
} else {
|
||||
searchInput = 'api';
|
||||
await box.click().catch(() => {});
|
||||
await box.fill(q);
|
||||
await page.keyboard.press('Enter');
|
||||
}
|
||||
await page.waitForLoadState('domcontentloaded').catch(() => {});
|
||||
out({ ok: true, site: SITES[siteKey] ? siteKey : 'google', query: q, url: page.url(), title: await page.title().catch(() => '') });
|
||||
out({ ok: true, site: SITES[siteKey] ? siteKey : 'google', query: q, url: page.url(), title: await page.title().catch(() => ''), input: searchInput });
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -205,6 +216,45 @@ try {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'moveMouse': {
|
||||
// Move/hover the REAL cursor onto an element WITHOUT clicking. Target is a
|
||||
// CSS selector, or site=naver/google/... for that site's search box.
|
||||
// Only meaningful with xdotool (the visible cursor); with no xdotool there
|
||||
// is no cursor to move, so report that rather than faking success. Every
|
||||
// failure to actually move (no xdotool, selector never matches, element
|
||||
// has no on-screen box) returns ok:false — we must never claim the cursor
|
||||
// moved when it did not (the exact bug the user reported).
|
||||
const siteKey = String(cmd.site || '').toLowerCase();
|
||||
const selector = String(cmd.selector || '').trim() || (SITES[siteKey] ? SITES[siteKey].box : '');
|
||||
if (!selector) throw new Error('moveMouse: no selector or known site');
|
||||
if (!(HAS_XDOTOOL && cmd.human !== false)) {
|
||||
out({ ok: false, error: 'no xdotool: cannot move the visible cursor on this host' });
|
||||
break;
|
||||
}
|
||||
await front(page);
|
||||
let locator = page.locator(selector).first();
|
||||
let visible = await locator.waitFor({ state: 'visible', timeout: 8000 }).then(() => true).catch(() => false);
|
||||
// A named site whose search box isn't on the current page: go to its home
|
||||
// first (real omnibox), then target the box there.
|
||||
if (!visible && SITES[siteKey]) {
|
||||
try { await human.navigateOmnibox(SITES[siteKey].home); await page.waitForLoadState('domcontentloaded').catch(() => {}); }
|
||||
catch { await page.goto(SITES[siteKey].home, { waitUntil: 'domcontentloaded' }).catch(() => {}); }
|
||||
locator = page.locator(SITES[siteKey].box).first();
|
||||
visible = await locator.waitFor({ state: 'visible', timeout: 8000 }).then(() => true).catch(() => false);
|
||||
}
|
||||
if (!visible) {
|
||||
out({ ok: false, error: `moveMouse: target not found (${cmd.selector || siteKey})` });
|
||||
break;
|
||||
}
|
||||
const moved = await human.humanHover(page, locator);
|
||||
if (!moved) {
|
||||
out({ ok: false, error: 'moveMouse: element has no on-screen box; cursor not moved' });
|
||||
break;
|
||||
}
|
||||
out({ ok: true, target: cmd.selector || siteKey, input: 'human' });
|
||||
break;
|
||||
}
|
||||
|
||||
case 'click': {
|
||||
const selector = String(cmd.selector || '').trim();
|
||||
if (!selector) throw new Error('click: no selector');
|
||||
|
||||
@@ -136,14 +136,18 @@ export async function navigateOmnibox(text) {
|
||||
}
|
||||
|
||||
// Move the real cursor over an element (hover, no click) - e.g. to reveal a
|
||||
// video player's controls or to focus it for a keyboard shortcut.
|
||||
// video player's controls or to focus it for a keyboard shortcut. Returns true
|
||||
// only if the element had an on-screen box and the cursor was actually moved;
|
||||
// returns false when there is nothing to move to (so callers must not report
|
||||
// success). Brings the element into view with a real wheel scroll first.
|
||||
export async function humanHover(page, locator) {
|
||||
const box = await locator.boundingBox().catch(() => null);
|
||||
if (!box) return;
|
||||
const box = await bringIntoView(page, locator);
|
||||
if (!box) return false;
|
||||
const g = await page.evaluate(() => ({ sx: window.screenX, sy: window.screenY, ow: window.outerWidth, oh: window.outerHeight, iw: window.innerWidth, ih: window.innerHeight }));
|
||||
const bx = Math.max(0, Math.round((g.ow - g.iw) / 2));
|
||||
const oy = g.sy + Math.max(0, g.oh - g.ih - bx);
|
||||
await humanMove(Math.round(g.sx + bx + box.x + box.width * 0.5), Math.round(oy + box.y + box.height * 0.4));
|
||||
return true;
|
||||
}
|
||||
|
||||
export { sleep, rand };
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* Does not broadcast natively into Discord. Instead it shares a noVNC web URL
|
||||
* that anyone can open in a browser to watch (and optionally control) the VNC
|
||||
* desktop live. Set NOVNC_URL in .env (e.g. http://192.168.10.9:6080/vnc.html).
|
||||
* desktop live. Set NOVNC_URL in .env to the browser host's LAN IP
|
||||
* (e.g. http://<browser-host-ip>:6080/vnc.html).
|
||||
*
|
||||
* Stand up noVNC once on the host with websockify, e.g.:
|
||||
* websockify --web=/usr/share/novnc 6080 localhost:5901
|
||||
@@ -22,7 +23,7 @@ export class NoVncStreamer implements ScreenStreamer {
|
||||
|
||||
async start(_ctx: StreamContext): Promise<string> {
|
||||
if (!this.config.novncUrl) {
|
||||
return "NOVNC_URL이 설정되지 않았습니다 (.env). 예: http://192.168.10.9:6080/vnc.html";
|
||||
return "NOVNC_URL이 설정되지 않았습니다 (.env). 예: http://<브라우저호스트IP>:6080/vnc.html";
|
||||
}
|
||||
this.active = true;
|
||||
return `🖥️ VNC 화면 실시간 보기 (브라우저): ${this.config.novncUrl}`;
|
||||
|
||||
@@ -21,7 +21,11 @@ nvidia-cudnn-cu12
|
||||
# --- Bridge HTTP service ---
|
||||
flask>=3.0.0
|
||||
|
||||
# --- Text-to-speech (Piper) ---
|
||||
# --- Text-to-speech ---
|
||||
# Edge TTS: the primary Korean voice (online MS neural). Lightweight (httpx);
|
||||
# emits MP3, transcoded to PCM16 by the system ffmpeg in the bridge.
|
||||
edge-tts>=6.1.0
|
||||
# Piper: offline English fallback.
|
||||
piper-tts>=1.3.0
|
||||
|
||||
# --- Built-in tools (lazily imported; needed for full functionality) ---
|
||||
|
||||
107
bridge/server.py
107
bridge/server.py
@@ -87,12 +87,22 @@ VAD_MIN_SPEECH_MS = int(os.environ.get("VAD_MIN_SPEECH_MS", "200"))
|
||||
# Korean phrase decoded as Chinese) and shaves a little latency. Empty = auto.
|
||||
STT_LANGUAGE = os.environ.get("STT_LANGUAGE", "ko").strip() or None
|
||||
|
||||
# TTS engine: "melo" (MeloTTS Korean speaker, the warm worker) is the primary
|
||||
# voice; Piper is kept as a fallback if the worker is unreachable. Set
|
||||
# TTS_ENGINE=piper to disable MeloTTS entirely.
|
||||
# Whisper decoding accuracy knobs. beam_size=1 is greedy decoding — fast but the
|
||||
# least accurate; beam search (5 is the Whisper default) explores alternatives
|
||||
# and noticeably improves recognition on short, accented, or noisy Discord-mic
|
||||
# speech. condition_on_previous_text=False stops Whisper from feeding a previous
|
||||
# clip's transcript back in as a prompt, which on isolated short utterances
|
||||
# causes repetition loops and drift rather than helping. Both are env-tunable so
|
||||
# accuracy/latency can be traded without a code change (lower STT_BEAM_SIZE for
|
||||
# speed, raise it for accuracy).
|
||||
STT_BEAM_SIZE = max(1, int(os.environ.get("STT_BEAM_SIZE", "5")))
|
||||
STT_CONDITION_ON_PREV = os.environ.get("STT_CONDITION_ON_PREV", "0") in ("1", "true", "True", "yes", "on")
|
||||
|
||||
# TTS engine: "edge" (Microsoft Edge TTS, natural Korean neural voice) is the
|
||||
# primary voice. "melo" (a warm MeloTTS worker) and "piper" remain selectable.
|
||||
def _tts_engine_setting() -> str:
|
||||
"""TTS engine: settings-UI value (runtime config JSON) wins, else env, else
|
||||
melo. Read at startup; the settings UI restarts the bridge on apply."""
|
||||
edge. Read at startup; the settings UI restarts the bridge on apply."""
|
||||
try:
|
||||
_cp = os.environ.get("JARVIS_CONFIG_PATH", "/app/config/jarvis.json")
|
||||
_v = json.loads(open(_cp, encoding="utf-8").read()).get("tts_engine")
|
||||
@@ -100,16 +110,22 @@ def _tts_engine_setting() -> str:
|
||||
return str(_v).strip().lower()
|
||||
except Exception:
|
||||
pass
|
||||
return os.environ.get("TTS_ENGINE", "melo").strip().lower()
|
||||
return os.environ.get("TTS_ENGINE", "edge").strip().lower()
|
||||
|
||||
|
||||
TTS_ENGINE = _tts_engine_setting()
|
||||
# Edge TTS (online MS neural voice). Voice + rate are env-driven so they can be
|
||||
# changed without code. Default: Korean "Hyunsu" multilingual voice at +45%
|
||||
# (≈1.45×), the chosen settings. NOTE: edge synthesis sends the reply TEXT to
|
||||
# Microsoft's servers and needs internet — an intentional privacy trade-off for
|
||||
# the more natural voice.
|
||||
EDGE_TTS_VOICE = os.environ.get("EDGE_TTS_VOICE", "ko-KR-HyunsuMultilingualNeural").strip()
|
||||
EDGE_TTS_RATE = os.environ.get("EDGE_TTS_RATE", "+45%").strip()
|
||||
MELO_WORKER_URL = os.environ.get("MELO_WORKER_URL", "http://127.0.0.1:8770")
|
||||
MELO_TIMEOUT = float(os.environ.get("MELO_TIMEOUT", "30"))
|
||||
# When MeloTTS is the engine, do NOT silently fall back to the English Piper
|
||||
# voice on failure: speaking Korean text through an English voice produces
|
||||
# mangled audio. Default is melo-only (return no audio on failure); set
|
||||
# MELO_FALLBACK_PIPER=1 to opt into the Piper fallback.
|
||||
# Do NOT silently fall back to the English Piper voice on a neural-voice failure:
|
||||
# speaking Korean through an English voice produces mangled audio. Default is
|
||||
# neural-only (return no audio on failure); set MELO_FALLBACK_PIPER=1 to opt in.
|
||||
MELO_FALLBACK_PIPER = os.environ.get("MELO_FALLBACK_PIPER", "0") in ("1", "true", "True", "yes", "on")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -238,7 +254,12 @@ def transcribe(wav_bytes: bytes) -> dict:
|
||||
print("[bridge] no speech detected (VAD) — skipping STT", flush=True)
|
||||
return {"text": "", "language": None, "note": "음성 아님(VAD 차단)"}
|
||||
|
||||
segments, info = _whisper.transcribe(audio, beam_size=1, language=STT_LANGUAGE)
|
||||
segments, info = _whisper.transcribe(
|
||||
audio,
|
||||
beam_size=STT_BEAM_SIZE,
|
||||
language=STT_LANGUAGE,
|
||||
condition_on_previous_text=STT_CONDITION_ON_PREV,
|
||||
)
|
||||
# Second line of defence: drop non-speech / hallucinated segments by
|
||||
# Whisper's own no_speech_prob. The no_speech_prob hard cutoff (plus the VAD
|
||||
# pre-gate above) is what rejects noise/hallucinations. The avg_logprob
|
||||
@@ -302,6 +323,54 @@ def _coerce_bool(value) -> Optional[bool]:
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _edge_synthesize(text: str) -> Optional[bytes]:
|
||||
"""Synthesise via Microsoft Edge TTS (online neural voice) and return a
|
||||
16-bit PCM WAV, or None on any failure. Edge emits MP3; we transcode to
|
||||
PCM16 mono with the system ffmpeg, writing to a temp file (seekable) so the
|
||||
WAV header carries a correct length. Needs internet."""
|
||||
import asyncio
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
try:
|
||||
import edge_tts # type: ignore
|
||||
|
||||
async def _gen() -> bytes:
|
||||
comm = edge_tts.Communicate(text, EDGE_TTS_VOICE, rate=EDGE_TTS_RATE)
|
||||
buf = bytearray()
|
||||
async for chunk in comm.stream():
|
||||
if chunk.get("type") == "audio":
|
||||
buf.extend(chunk["data"])
|
||||
return bytes(buf)
|
||||
|
||||
mp3 = asyncio.run(_gen())
|
||||
if not mp3:
|
||||
print("[bridge] edge TTS returned no audio", flush=True)
|
||||
return None
|
||||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as t:
|
||||
out_path = t.name
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
|
||||
"-i", "pipe:0", "-ac", "1", "-ar", "24000",
|
||||
"-acodec", "pcm_s16le", out_path],
|
||||
input=mp3, capture_output=True,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
print(f"[bridge] edge ffmpeg transcode failed: {proc.stderr.decode('utf-8','ignore')[:200]}", flush=True)
|
||||
return None
|
||||
with open(out_path, "rb") as f:
|
||||
return f.read()
|
||||
finally:
|
||||
try:
|
||||
os.unlink(out_path)
|
||||
except OSError:
|
||||
pass
|
||||
except Exception as e: # pragma: no cover - network / dep dependent
|
||||
print(f"[bridge] edge synth failed: {e}", flush=True)
|
||||
return None
|
||||
|
||||
|
||||
def _melo_synthesize(text: str) -> Optional[bytes]:
|
||||
"""Synthesise via the warm MeloTTS worker (separate /opt/melo venv, Korean
|
||||
speaker @ speed 1.5). Returns a 16-bit PCM WAV, or None on any failure so
|
||||
@@ -361,20 +430,22 @@ def _tts_ready() -> bool:
|
||||
|
||||
|
||||
def synthesize(text: str) -> Optional[bytes]:
|
||||
"""Synthesize text to a 16-bit PCM WAV. The primary voice is MeloTTS
|
||||
(Korean speaker, speed 1.5) served by the warm melo worker; Piper is a
|
||||
fallback if the worker is unavailable. Returns None if TTS is off."""
|
||||
"""Synthesize text to a 16-bit PCM WAV. The primary voice is Edge TTS (a
|
||||
natural Korean neural voice); "melo" uses the warm MeloTTS worker. For a
|
||||
neural engine, Piper (English) is only used if explicitly enabled, since
|
||||
speaking Korean through an English voice mangles it. Returns None if off."""
|
||||
if not TTS_ENABLED or not text.strip():
|
||||
return None
|
||||
if TTS_ENGINE == "melo":
|
||||
audio = _melo_synthesize(text)
|
||||
_neural = {"edge": _edge_synthesize, "melo": _melo_synthesize}.get(TTS_ENGINE)
|
||||
if _neural is not None:
|
||||
audio = _neural(text)
|
||||
if audio:
|
||||
return audio
|
||||
if not MELO_FALLBACK_PIPER:
|
||||
# Melo-only: better silent than mangled English for Korean text.
|
||||
print("[bridge] melo synth failed; no audio (Piper fallback disabled)", flush=True)
|
||||
# Neural-only: better silent than mangled English for Korean text.
|
||||
print(f"[bridge] {TTS_ENGINE} synth failed; no audio (Piper fallback disabled)", flush=True)
|
||||
return None
|
||||
print("[bridge] melo synth failed; falling back to Piper", flush=True)
|
||||
print(f"[bridge] {TTS_ENGINE} synth failed; falling back to Piper", flush=True)
|
||||
return _piper_synthesize(text)
|
||||
|
||||
|
||||
|
||||
@@ -22,8 +22,7 @@ from typing import Any, Dict
|
||||
FIELDS = [
|
||||
("ollama_chat_model", "LLM 모델", "model"),
|
||||
("whisper_model", "STT(Whisper) 모델", "select:tiny,base,small,medium,large,large-v3"),
|
||||
("tts_engine", "TTS 엔진", "select:melo,piper"),
|
||||
("melo_speed", "TTS 속도 (MeloTTS)", "number:0.5:2.5:0.1"),
|
||||
("tts_engine", "TTS 엔진", "select:edge,piper"),
|
||||
("output_language", "출력 언어 (비우면 사용자 언어)", "text"),
|
||||
("llm_thinking_enabled", "LLM 사고(thinking) 모드", "bool"),
|
||||
("agentic_max_turns", "에이전트 최대 반복", "number:1:12:1"),
|
||||
@@ -54,9 +53,7 @@ def _current() -> Dict[str, Any]:
|
||||
cfg = _read_config()
|
||||
out: Dict[str, Any] = {}
|
||||
for k in _KEYS:
|
||||
if k == "melo_speed":
|
||||
out[k] = cfg.get("melo_speed", os.environ.get("MELO_SPEED", "1.5"))
|
||||
elif k == "output_language":
|
||||
if k == "output_language":
|
||||
out[k] = cfg.get("output_language", os.environ.get("OUTPUT_LANGUAGE", ""))
|
||||
else:
|
||||
out[k] = cfg.get(k, "")
|
||||
@@ -78,12 +75,7 @@ def _coerce(updates: Dict[str, Any]) -> Dict[str, Any]:
|
||||
for k, v in updates.items():
|
||||
if k not in _KEYS:
|
||||
continue
|
||||
if k == "melo_speed":
|
||||
try:
|
||||
v = float(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
elif k == "agentic_max_turns":
|
||||
if k == "agentic_max_turns":
|
||||
try:
|
||||
v = int(v)
|
||||
except (TypeError, ValueError):
|
||||
@@ -114,15 +106,15 @@ def _save(updates: Dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _apply() -> str:
|
||||
# Restart melo + bridge AFTER this response is sent. Detached (new session)
|
||||
# so the bridge being killed mid-restart doesn't drop the restart itself,
|
||||
# and the HTTP client still receives this response.
|
||||
# Restart the bridge AFTER this response is sent. Detached (new session) so
|
||||
# the bridge being killed mid-restart doesn't drop the restart itself, and
|
||||
# the HTTP client still receives this response. (Edge TTS has no worker.)
|
||||
try:
|
||||
subprocess.Popen(
|
||||
["sh", "-c", "sleep 1; supervisorctl restart melo-worker bridge"],
|
||||
["sh", "-c", "sleep 1; supervisorctl restart bridge"],
|
||||
start_new_session=True,
|
||||
)
|
||||
return "1초 후 브리지/TTS 워커가 재시작되어 반영됩니다."
|
||||
return "1초 후 브리지가 재시작되어 반영됩니다."
|
||||
except Exception as e: # pragma: no cover
|
||||
return str(e)
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@ services:
|
||||
environment:
|
||||
OLLAMA_HOST: http://ollama:11434
|
||||
CHAT_MODEL: ${OLLAMA_CHAT_MODEL:-qwen2.5:3b}
|
||||
# Small auxiliary model for intent/router/extraction calls (see javis
|
||||
# service). Pulled here so the split is ready out of the box.
|
||||
INTENT_MODEL: ${OLLAMA_INTENT_MODEL:-qwen2.5:3b}
|
||||
EMBED_MODEL: ${OLLAMA_EMBED_MODEL:-nomic-embed-text}
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
@@ -48,6 +51,10 @@ services:
|
||||
until ollama list >/dev/null 2>&1; do sleep 2; done;
|
||||
echo "[ollama-init] pulling $$CHAT_MODEL";
|
||||
ollama pull "$$CHAT_MODEL";
|
||||
if [ -n "$$INTENT_MODEL" ] && [ "$$INTENT_MODEL" != "$$CHAT_MODEL" ]; then
|
||||
echo "[ollama-init] pulling $$INTENT_MODEL (auxiliary intent/router model)";
|
||||
ollama pull "$$INTENT_MODEL";
|
||||
fi;
|
||||
echo "[ollama-init] pulling $$EMBED_MODEL";
|
||||
ollama pull "$$EMBED_MODEL";
|
||||
echo "[ollama-init] models ready.";
|
||||
@@ -59,20 +66,41 @@ services:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
# Point the brain at the ollama service and the bot at the in-container bridge.
|
||||
OLLAMA_BASE_URL: http://ollama:11434
|
||||
# Point the brain at Ollama. Default is the in-stack `ollama` service
|
||||
# (all-in-one). Override OLLAMA_BASE_URL in .env to reach an EXTERNAL Ollama
|
||||
# over the LAN (e.g. a GPU host at http://192.168.10.9:11434) — used when
|
||||
# this stack runs on a separate machine from the LLM. When overridden, do
|
||||
# NOT start the in-stack `ollama`/`ollama-init` services (bring the app up
|
||||
# with `docker compose up -d javis`) and pull the models on the LLM host.
|
||||
OLLAMA_BASE_URL: ${OLLAMA_BASE_URL:-http://ollama:11434}
|
||||
OLLAMA_CHAT_MODEL: ${OLLAMA_CHAT_MODEL:-qwen2.5:3b}
|
||||
# Auxiliary small-model calls (intent judge, tool router, arg extraction,
|
||||
# query decomposition) run on this fast model so the big chat model only
|
||||
# runs for the actual spoken answer. With the GPU on, this is the main
|
||||
# per-turn latency win: a command no longer pays the big model's cost 2-3
|
||||
# times for routing/extraction. Defaults to qwen2.5:3b (the project's
|
||||
# reference small model, clean Korean on classification); set it equal to
|
||||
# OLLAMA_CHAT_MODEL to fold everything back onto one resident model.
|
||||
OLLAMA_INTENT_MODEL: ${OLLAMA_INTENT_MODEL:-qwen2.5:3b}
|
||||
OLLAMA_EMBED_MODEL: ${OLLAMA_EMBED_MODEL:-nomic-embed-text}
|
||||
WHISPER_MODEL: ${WHISPER_MODEL:-medium}
|
||||
WHISPER_DEVICE: ${WHISPER_DEVICE:-cuda}
|
||||
WHISPER_COMPUTE_TYPE: ${WHISPER_COMPUTE_TYPE:-float16}
|
||||
# MeloTTS on the GPU (cu128 torch baked by docker/setup-melo.sh). CPU synth
|
||||
# serialised under load and pushed TTS to 7-8s; GPU does ~0.3s/sentence.
|
||||
# TTS engine. Rendered into /app/config/jarvis.json via envsubst (the
|
||||
# bridge reads that JSON BEFORE the env, so it must carry the real engine).
|
||||
# Default melo: GPU MeloTTS (offline, privacy-first) via the melo-worker.
|
||||
# Override with TTS_ENGINE=edge for the online Microsoft neural voice (text
|
||||
# leaves the host) or piper for the offline English voice.
|
||||
TTS_ENGINE: ${TTS_ENGINE:-melo}
|
||||
# GPU MeloTTS worker knobs. MELO_DEVICE=cuda runs synth on the GPU (next to
|
||||
# Ollama + Whisper); cpu is the no-GPU fallback. MELO_SPEED must always be
|
||||
# set — supervisord's melo-worker expands %(ENV_MELO_SPEED)s at startup.
|
||||
MELO_DEVICE: ${MELO_DEVICE:-cuda}
|
||||
# Speaking rate for MeloTTS. Set here (with a default) so supervisord's
|
||||
# %(ENV_MELO_SPEED)s passthrough always resolves and an .env override
|
||||
# actually reaches the melo-worker. Lower it (e.g. 1.1) for a calmer pace.
|
||||
MELO_SPEED: ${MELO_SPEED:-1.5}
|
||||
# Edge TTS voice + rate (used only when TTS_ENGINE=edge). NOTE: edge is an
|
||||
# ONLINE engine — reply text is sent to Microsoft and needs internet.
|
||||
EDGE_TTS_VOICE: ${EDGE_TTS_VOICE:-ko-KR-HyunsuMultilingualNeural}
|
||||
EDGE_TTS_RATE: ${EDGE_TTS_RATE:-+45%}
|
||||
# Optional single-language lock for replies (empty = user's own language).
|
||||
OUTPUT_LANGUAGE: ${OUTPUT_LANGUAGE:-ko}
|
||||
# Drop the pre-loop planner LLM call to cut voice-reply latency on small
|
||||
@@ -80,11 +108,21 @@ services:
|
||||
PLANNER_ENABLED: ${PLANNER_ENABLED:-0}
|
||||
# Lock STT to Korean (skip Whisper auto-detect).
|
||||
STT_LANGUAGE: ${STT_LANGUAGE:-ko}
|
||||
# Whisper decode accuracy: beam search (5) over greedy (1) lifts recognition
|
||||
# on short/noisy Discord speech. Lower to 1 for minimum latency.
|
||||
STT_BEAM_SIZE: ${STT_BEAM_SIZE:-5}
|
||||
VOICE_SILENCE_MS: ${VOICE_SILENCE_MS:-600}
|
||||
BRIDGE_URL: http://127.0.0.1:8765
|
||||
# Split-deployment role: full (default, all-in-one), browser (only the
|
||||
# desktop + Chrome + CDP, reused over the LAN), or bot (only bot + bridge
|
||||
# + TTS, driving a remote browser via CDP_HOST). See docker/run-if-role.sh.
|
||||
# Where the bot reaches the brain bridge (STT + reply + TTS). Loopback for
|
||||
# all-in-one. In a GPU-split layout the bot host (JARVIS_ROLE=app) points
|
||||
# this at the brain host: BRIDGE_URL=http://192.168.10.9:8765 (that host
|
||||
# runs JARVIS_ROLE=brain with BRIDGE_HOST=0.0.0.0 + SETTINGS_PUBLISH_BIND=0.0.0.0).
|
||||
BRIDGE_URL: ${BRIDGE_URL:-http://127.0.0.1:8765}
|
||||
# Split-deployment role (see docker/run-if-role.sh):
|
||||
# full (default) everything in one container
|
||||
# browser only desktop + Chrome + control-server (driven over the LAN)
|
||||
# bot only bot + bridge + TTS (drives a remote browser)
|
||||
# brain only the bridge (STT + reply + TTS) — GPU host, no bot/desktop
|
||||
# app bot + browser/desktop, NO local bridge (uses a remote brain)
|
||||
JARVIS_ROLE: ${JARVIS_ROLE:-full}
|
||||
# Chrome CDP bind address INSIDE the container. 0.0.0.0 lets a remote bot
|
||||
# (JARVIS_ROLE=bot on another PC) drive this host's browser. Loopback by
|
||||
@@ -92,7 +130,7 @@ services:
|
||||
CDP_BIND: ${CDP_BIND:-127.0.0.1}
|
||||
CDP_PORT: ${CDP_PORT:-9222}
|
||||
# Where the bot drives Chrome. Loopback for full/browser; on a remote bot
|
||||
# set CDP_HOST to the browser host's LAN IP (e.g. 192.168.10.9).
|
||||
# set CDP_HOST to the browser host's LAN IP (e.g. 192.168.10.5).
|
||||
CDP_HOST: ${CDP_HOST:-127.0.0.1}
|
||||
# Browser-control endpoint. The browser host serves it (BIND/PORT); a
|
||||
# remote bot sets BROWSER_CONTROL_URL=http://<browser-host>:8777 so its
|
||||
|
||||
@@ -10,12 +10,15 @@ set -euo pipefail
|
||||
: "${OLLAMA_BASE_URL:=http://ollama:11434}"
|
||||
: "${OLLAMA_CHAT_MODEL:=qwen3:8b}"
|
||||
# Auxiliary small-model calls (intent judge, tool router, weather place
|
||||
# extraction, query decomposition). The code default is gemma4:e2b, which this
|
||||
# stack does not pull, so those calls would silently fail and fall open —
|
||||
# crippling tool routing and arg extraction. Reuse the (already warm) chat model
|
||||
# by default so everything runs on one resident model; override if you pull a
|
||||
# dedicated small model.
|
||||
: "${OLLAMA_INTENT_MODEL:=${OLLAMA_CHAT_MODEL}}"
|
||||
# extraction, query decomposition). Default to a small fast model so the big
|
||||
# chat model only runs for the actual spoken answer — the main per-turn latency
|
||||
# win once the GPU is in use, since the 2-3 routing/extraction calls per command
|
||||
# no longer pay the big model's cost. ollama-init pulls this model. Set it equal
|
||||
# to OLLAMA_CHAT_MODEL to fold everything back onto one resident model.
|
||||
: "${OLLAMA_INTENT_MODEL:=qwen2.5:3b}"
|
||||
# Cap chat-model output tokens per turn (worst-case latency guard). Spoken
|
||||
# answers are 1-2 sentences; 512 is safe headroom above tool-call JSON. 0 = off.
|
||||
: "${OLLAMA_NUM_PREDICT:=512}"
|
||||
: "${OLLAMA_EMBED_MODEL:=nomic-embed-text}"
|
||||
: "${WHISPER_MODEL:=small}"
|
||||
: "${WHISPER_DEVICE:=cuda}"
|
||||
@@ -32,7 +35,7 @@ set -euo pipefail
|
||||
: "${XDG_RUNTIME_DIR:=/run/user/0}"
|
||||
: "${PULSE_SERVER:=unix:${XDG_RUNTIME_DIR}/pulse/native}"
|
||||
|
||||
export VNC_RESOLUTION OLLAMA_BASE_URL OLLAMA_CHAT_MODEL OLLAMA_INTENT_MODEL OLLAMA_EMBED_MODEL \
|
||||
export VNC_RESOLUTION OLLAMA_BASE_URL OLLAMA_CHAT_MODEL OLLAMA_NUM_PREDICT OLLAMA_INTENT_MODEL OLLAMA_EMBED_MODEL \
|
||||
WHISPER_MODEL WHISPER_DEVICE WHISPER_COMPUTE_TYPE JARVIS_DB_PATH \
|
||||
PIPER_VOICE PIPER_VOICE_DIR TTS_PIPER_MODEL_PATH BRIDGE_HOST BRIDGE_PORT \
|
||||
XDG_RUNTIME_DIR PULSE_SERVER
|
||||
@@ -51,12 +54,18 @@ export JARVIS_CONFIG_PATH=/app/config/jarvis.json
|
||||
# the env-rendered config, so changes survive container recreate.
|
||||
if [ -f /data/jarvis-settings.json ]; then
|
||||
python3 - <<'PY' || true
|
||||
import json
|
||||
import json, os
|
||||
try:
|
||||
base = json.load(open("/app/config/jarvis.json"))
|
||||
ov = json.load(open("/data/jarvis-settings.json"))
|
||||
if isinstance(base, dict) and isinstance(ov, dict):
|
||||
base.update(ov)
|
||||
# A stale persisted tts_engine from an earlier voice (melo/xtts, no
|
||||
# longer built into the image) would override the configured engine and
|
||||
# leave the bot silent. Reset those to the env-configured engine.
|
||||
if base.get("tts_engine") in ("melo", "xtts"):
|
||||
base["tts_engine"] = os.environ.get("TTS_ENGINE", "edge")
|
||||
print(f"[entrypoint] reset stale tts_engine -> {base['tts_engine']}")
|
||||
json.dump(base, open("/app/config/jarvis.json", "w"), ensure_ascii=False, indent=2)
|
||||
print("[entrypoint] merged persistent settings overrides")
|
||||
except Exception as e:
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
"ollama_base_url": "${OLLAMA_BASE_URL}",
|
||||
"ollama_embed_model": "${OLLAMA_EMBED_MODEL}",
|
||||
"ollama_chat_model": "${OLLAMA_CHAT_MODEL}",
|
||||
"ollama_num_predict": "${OLLAMA_NUM_PREDICT}",
|
||||
"intent_judge_model": "${OLLAMA_INTENT_MODEL}",
|
||||
"tts_enabled": true,
|
||||
"tts_engine": "piper",
|
||||
"tts_engine": "${TTS_ENGINE}",
|
||||
"tts_piper_model_path": "${TTS_PIPER_MODEL_PATH}",
|
||||
"whisper_model": "${WHISPER_MODEL}",
|
||||
"whisper_backend": "faster-whisper",
|
||||
|
||||
@@ -18,6 +18,27 @@ cat > /etc/opt/chrome/policies/managed/jarvis.json <<'JSON'
|
||||
{ "CommandLineFlagSecurityWarningsEnabled": false }
|
||||
JSON
|
||||
|
||||
# Seed the profile's web-content language to Korean so sites (YouTube, Google,
|
||||
# Naver) render in Korean. --lang sets Chrome's own UI, but the Accept-Language
|
||||
# sent to sites comes from the profile's intl.accept_languages, which a persisted
|
||||
# user-data-dir would otherwise keep at en-US regardless of --accept-lang.
|
||||
PREFS_DIR="${CHROME_PROFILE_DIR:-/root/chrome-profile}/Default"
|
||||
PREFS="${PREFS_DIR}/Preferences"
|
||||
mkdir -p "$PREFS_DIR"
|
||||
if [ -f "$PREFS" ]; then
|
||||
python3 - "$PREFS" <<'PY' 2>/dev/null || true
|
||||
import json, sys
|
||||
p = sys.argv[1]
|
||||
d = json.load(open(p))
|
||||
d.setdefault("intl", {})
|
||||
d["intl"]["accept_languages"] = "ko-KR,ko"
|
||||
d["intl"]["selected_languages"] = "ko-KR,ko"
|
||||
json.dump(d, open(p, "w"), ensure_ascii=False)
|
||||
PY
|
||||
else
|
||||
printf '%s' '{"intl":{"accept_languages":"ko-KR,ko","selected_languages":"ko-KR,ko"}}' > "$PREFS"
|
||||
fi
|
||||
|
||||
# Minimal, non-automation flags. --remote-debugging exposes CDP so the brain can
|
||||
# drive this on-screen Chrome (Google/YouTube/Naver), --disable-features=Translate
|
||||
# hides the translate popup. NO --test-type / --disable-blink-features.
|
||||
@@ -26,6 +47,7 @@ exec google-chrome \
|
||||
--no-default-browser-check \
|
||||
--disable-features=Translate,TranslateUI \
|
||||
--lang=ko-KR \
|
||||
--accept-lang=ko-KR,ko \
|
||||
--remote-debugging-port="${CDP_PORT:-9222}" \
|
||||
--remote-debugging-address="${CDP_BIND:-127.0.0.1}" \
|
||||
--user-data-dir="${CHROME_PROFILE_DIR:-/root/chrome-profile}" \
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
# JARVIS_ROLE=browser only the desktop + Chrome + CDP (reused over the LAN)
|
||||
# JARVIS_ROLE=bot only the bot + bridge + TTS (drives a remote browser
|
||||
# via CDP_HOST/CDP_PORT)
|
||||
# JARVIS_ROLE=brain only the bridge (STT + reply + TTS) on a GPU host; no
|
||||
# bot, no desktop. The app host reaches it via BRIDGE_URL.
|
||||
# JARVIS_ROLE=app the bot + desktop/Chrome, but NOT the local bridge:
|
||||
# offloads STT/LLM/TTS to a remote brain host (BRIDGE_URL)
|
||||
set -e
|
||||
want="$1"; shift
|
||||
role="${JARVIS_ROLE:-full}"
|
||||
|
||||
@@ -14,7 +14,7 @@ serverurl=unix:///run/supervisor.sock
|
||||
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
|
||||
|
||||
[program:xvnc]
|
||||
command=/app/docker/run-if-role.sh full,browser /app/docker/run-xvnc.sh
|
||||
command=/app/docker/run-if-role.sh full,browser,app /app/docker/run-xvnc.sh
|
||||
priority=100
|
||||
autorestart=true
|
||||
stdout_logfile=/dev/stdout
|
||||
@@ -23,7 +23,7 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:pulse]
|
||||
command=/app/docker/run-if-role.sh full,browser /app/docker/run-pulse.sh
|
||||
command=/app/docker/run-if-role.sh full,browser,app /app/docker/run-pulse.sh
|
||||
priority=150
|
||||
autorestart=true
|
||||
stdout_logfile=/dev/stdout
|
||||
@@ -32,7 +32,7 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:xfce]
|
||||
command=/app/docker/run-if-role.sh full,browser /app/docker/run-xfce.sh
|
||||
command=/app/docker/run-if-role.sh full,browser,app /app/docker/run-xfce.sh
|
||||
priority=200
|
||||
autorestart=true
|
||||
stdout_logfile=/dev/stdout
|
||||
@@ -41,7 +41,7 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:novnc]
|
||||
command=/app/docker/run-if-role.sh full,browser websockify --web=/usr/share/novnc 6080 localhost:5901
|
||||
command=/app/docker/run-if-role.sh full,browser,app websockify --web=/usr/share/novnc 6080 localhost:5901
|
||||
priority=250
|
||||
autorestart=true
|
||||
stdout_logfile=/dev/stdout
|
||||
@@ -50,23 +50,19 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:melo-worker]
|
||||
; Warm MeloTTS Korean voice (speed 1.5) in its own py3.11 venv. The bridge's
|
||||
; synthesize() POSTs here; if this is down the bridge falls back to Piper.
|
||||
command=/app/docker/run-if-role.sh full,bot /opt/melo/bin/python /app/bridge/melo_worker.py
|
||||
; Warm GPU MeloTTS Korean voice (offline) in its own py3.11 venv (/opt/melo). The
|
||||
; bridge's synthesize() POSTs here when TTS_ENGINE=melo. Runs wherever the bridge
|
||||
; runs (full/bot/brain) so a GPU brain host serves TTS on the GPU. If TTS_ENGINE
|
||||
; =edge the bridge synthesises in-process and never calls this worker.
|
||||
command=/app/docker/run-if-role.sh full,bot,brain /opt/melo/bin/python /app/bridge/melo_worker.py
|
||||
directory=/app
|
||||
; HF_HOME points at the dedicated, image-baked melo cache (warmed in
|
||||
; setup-melo.sh). The brain's whisper_cache volume is mounted over
|
||||
; /root/.cache/huggingface, so without this the pre-cached BERT + KR checkpoint
|
||||
; would be shadowed and re-downloaded (and would fail if the host is offline).
|
||||
; HF_HUB_OFFLINE/TRANSFORMERS_OFFLINE force pure-cache reads: the pinned old
|
||||
; transformers/huggingface_hub otherwise retry the network on every load and
|
||||
; error out instead of falling back to the (complete) baked cache.
|
||||
; MELO_DEVICE and MELO_SPEED inherit from the container env (compose sets both
|
||||
; with defaults: cuda / 1.5) so the worker runs MeloTTS on the GPU at the
|
||||
; configured rate. supervisord interpolates %(ENV_x)s from its own environment,
|
||||
; which is the container's — so MELO_SPEED must always be set in the env
|
||||
; (compose guarantees it) or this expansion fails at startup. Hardcoding 1.5
|
||||
; here previously shadowed the .env value, so lowering MELO_SPEED had no effect.
|
||||
; setup-melo.sh). The whisper_cache volume is mounted over /root/.cache/huggingface,
|
||||
; so without this the pre-cached BERT + KR checkpoint would be shadowed and
|
||||
; re-downloaded (and would fail offline). HF_HUB_OFFLINE/TRANSFORMERS_OFFLINE
|
||||
; force pure-cache reads. MELO_DEVICE/MELO_SPEED inherit from the container env
|
||||
; (compose sets both with defaults cuda / 1.5), so MELO_SPEED must always be set
|
||||
; in the env or this %(ENV_x)s expansion fails at startup (compose guarantees it).
|
||||
environment=MELO_LANGUAGE="KR",MELO_SPEED="%(ENV_MELO_SPEED)s",MELO_DEVICE="%(ENV_MELO_DEVICE)s",MELO_WORKER_HOST="127.0.0.1",MELO_WORKER_PORT="8770",HF_HOME="/opt/melo-cache",HF_HUB_OFFLINE="1",TRANSFORMERS_OFFLINE="1"
|
||||
priority=280
|
||||
autorestart=true
|
||||
@@ -76,7 +72,7 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:bridge]
|
||||
command=/app/docker/run-if-role.sh full,bot /opt/venv/bin/python -m bridge.server
|
||||
command=/app/docker/run-if-role.sh full,bot,brain /opt/venv/bin/python -m bridge.server
|
||||
directory=/app
|
||||
priority=300
|
||||
autorestart=true
|
||||
@@ -86,7 +82,7 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:chrome]
|
||||
command=/app/docker/run-if-role.sh full,browser /app/docker/run-chrome.sh
|
||||
command=/app/docker/run-if-role.sh full,browser,app /app/docker/run-chrome.sh
|
||||
priority=350
|
||||
autorestart=true
|
||||
stdout_logfile=/dev/stdout
|
||||
@@ -98,7 +94,7 @@ stderr_logfile_maxbytes=0
|
||||
; Browser-control HTTP endpoint on the BROWSER HOST. A remote `bot` posts
|
||||
; commands here so xdotool / CDP run on THIS machine (real input on this
|
||||
; screen). Only meaningful in full/browser roles. Internal network only.
|
||||
command=/app/docker/run-if-role.sh full,browser node /app/bot/scripts/stream-test/control-server.mjs
|
||||
command=/app/docker/run-if-role.sh full,browser,app node /app/bot/scripts/stream-test/control-server.mjs
|
||||
directory=/app/bot
|
||||
priority=360
|
||||
autorestart=true
|
||||
@@ -108,7 +104,7 @@ stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
|
||||
[program:bot]
|
||||
command=/app/docker/run-if-role.sh full,bot /app/docker/run-bot.sh
|
||||
command=/app/docker/run-if-role.sh full,bot,app /app/docker/run-bot.sh
|
||||
directory=/app/bot
|
||||
priority=400
|
||||
autorestart=true
|
||||
|
||||
@@ -30,7 +30,7 @@ The on-screen Chrome, real mouse/keyboard (xdotool) and screen live on the
|
||||
**browser host**. Your PC runs the **bot** and drives that browser over the
|
||||
internal network — no auth (internal only).
|
||||
|
||||
### Browser host (the LAN machine that shows Chrome, e.g. 192.168.10.9)
|
||||
### Browser host (the LAN machine that shows Chrome, e.g. 192.168.10.5)
|
||||
|
||||
```
|
||||
# .env
|
||||
@@ -50,7 +50,7 @@ Watch it on this machine’s VNC (`localhost:5901`) / noVNC (`localhost:6080`).
|
||||
```
|
||||
# .env
|
||||
JARVIS_ROLE=bot
|
||||
BROWSER_CONTROL_URL=http://192.168.10.9:8777 # the browser host's LAN IP
|
||||
BROWSER_CONTROL_URL=http://192.168.10.5:8777 # the browser host's LAN IP
|
||||
COMPOSE_FILE=docker-compose.yml:docker-compose.gpu-linux.yml # Ubuntu/macOS (":" )
|
||||
# COMPOSE_FILE=docker-compose.yml;docker-compose.gpu-windows.yml # Windows 11 (";" )
|
||||
DISCORD_SELFBOT_TOKEN=...
|
||||
@@ -63,6 +63,73 @@ The bot’s `controlBrowser` tool posts commands to `BROWSER_CONTROL_URL`, so
|
||||
"네이버에서 X 검색", "구글로 돌아가" etc. drive the **browser host’s** Chrome with real
|
||||
human-style input (visible on its VNC).
|
||||
|
||||
### External Ollama (LLM on a separate host)
|
||||
|
||||
To run Ollama on a different LAN machine (e.g. a dedicated GPU host at
|
||||
`192.168.10.9`) instead of inside this stack:
|
||||
|
||||
```
|
||||
# .env on the app host
|
||||
OLLAMA_BASE_URL=http://192.168.10.9:11434
|
||||
```
|
||||
|
||||
Then start the app WITHOUT the in-stack LLM services: `docker compose up -d javis`
|
||||
(do not `docker compose up -d`, which would also start `ollama`/`ollama-init`).
|
||||
On the LLM host, make Ollama listen on the LAN (`OLLAMA_HOST=0.0.0.0:11434`) and
|
||||
pull the models there (`ollama pull <chat>`, `<intent>`, `<embed>`). The compose
|
||||
respects `OLLAMA_BASE_URL`, defaulting to the in-stack `ollama` service when unset.
|
||||
|
||||
## C. GPU split: brain host (.9, GPU) + app host (.5, no GPU)
|
||||
|
||||
All the GPU-heavy compute (Whisper STT, the Ollama LLM, and TTS) runs on the
|
||||
**brain host** (a GPU box, e.g. `192.168.10.9`). The **app host** (no GPU, e.g.
|
||||
`192.168.10.5`) runs the Discord bot and the on-screen browser, and offloads
|
||||
every STT/LLM/TTS call to the brain over the LAN.
|
||||
|
||||
Flow: the bot (app host) POSTs captured voice to the brain's bridge; the brain
|
||||
runs STT -> LLM -> TTS on the GPU and returns the reply audio; when the LLM
|
||||
drives the browser, the brain's `controlBrowser` tool POSTs to the app host's
|
||||
control-server (port 8777), so Chrome moves on the app host's screen.
|
||||
|
||||
### Brain host (.9 — GPU: STT + LLM + TTS)
|
||||
|
||||
```
|
||||
# .env
|
||||
JARVIS_ROLE=brain
|
||||
BRIDGE_HOST=0.0.0.0 # bridge listens on the LAN
|
||||
SETTINGS_PUBLISH_BIND=0.0.0.0 # publish bridge port 8765 to the LAN
|
||||
OLLAMA_BASE_URL=http://192.168.10.9:11434 # Ollama on this host (bind 0.0.0.0)
|
||||
OLLAMA_CHAT_MODEL=qwen2.5:7b
|
||||
WHISPER_DEVICE=cuda # STT on the GPU
|
||||
WHISPER_COMPUTE_TYPE=float16
|
||||
TTS_ENGINE=melo # GPU MeloTTS (offline, privacy-first)
|
||||
MELO_DEVICE=cuda # TTS on the GPU (melo-worker)
|
||||
BROWSER_CONTROL_URL=http://192.168.10.5:8777 # drive the app host's Chrome
|
||||
COMPOSE_FILE=docker-compose.yml:docker-compose.gpu-linux.yml # GPU (":" on Linux)
|
||||
|
||||
# STT (Whisper), LLM (Ollama) and TTS (MeloTTS) all run on this host's GPU.
|
||||
# Ollama listens on 0.0.0.0:11434 (systemd or a container).
|
||||
docker compose up -d javis # brain bridge + melo-worker only (no bot, no desktop)
|
||||
```
|
||||
|
||||
### App host (.5 — bot + browser, no GPU)
|
||||
|
||||
```
|
||||
# .env
|
||||
JARVIS_ROLE=app
|
||||
BRIDGE_URL=http://192.168.10.9:8765 # offload STT/LLM/TTS to the brain
|
||||
CDP_PUBLISH_BIND=0.0.0.0 # publish control-server 8777 to the LAN
|
||||
STREAM_HW=0 # no NVENC on a no-GPU host
|
||||
DISCORD_SELFBOT_TOKEN=...
|
||||
DISCORD_GUILD_ID=...
|
||||
# no GPU → leave COMPOSE_FILE unset (base compose only)
|
||||
|
||||
docker compose up -d javis # bot + desktop + Chrome + control-server
|
||||
```
|
||||
|
||||
The `brain` and `app` roles are backward-compatible additions to `full`/`browser`
|
||||
/`bot`; see `docker/run-if-role.sh`.
|
||||
|
||||
## Windows 11 notes
|
||||
|
||||
- Install the NVIDIA driver on Windows and enable GPU in Docker Desktop
|
||||
|
||||
@@ -19,14 +19,14 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i
|
||||
- Time + location context (re-injected each turn)
|
||||
- Tool schema: native via `generate_tools_json_schema()` ([src/jarvis/tools/registry.py](src/jarvis/tools/registry.py)) or text fallback via `_text_tool_call_guidance()` ([engine.py:68](src/jarvis/reply/engine.py:68))
|
||||
- Tool results from prior turns (raw or digested — see #5)
|
||||
- **Output**: OpenAI-style `{content, tool_calls, thinking}`. Consumed by the tool orchestrator and TTS pipeline. Natural-language content is delivered immediately; no post-turn evaluator runs.
|
||||
- **Limits**: `num_ctx: 8192` (explicit). Timeout `llm_chat_timeout_sec` (45s). Auto-fallback from native to text tool-calls on HTTP 400 (`ToolsNotSupportedError`), sticky for the session. Risk: `fetch_web_page` truncates at 50,000 chars (~37k tokens) — mitigated for SMALL models by tool-result digest (#5) which compresses the payload before it enters the messages history. LARGE models receive the raw payload and may silently see a truncated context.
|
||||
- **Output**: OpenAI-style `{content, tool_calls, thinking}`. Consumed by the tool orchestrator and TTS pipeline. Natural-language content is delivered immediately; no post-turn evaluator runs. Spoken-answer length: the persona (`system_prompt.py`) and `voice_style` (`prompts/system.py`) both constrain the reply to a SINGLE sentence — any dry aside must fold into that one sentence as a trailing clause, never a second sentence. This keeps TTS latency down (synth time scales with text length) and matches the `agents/llm.md` operator instruction.
|
||||
- **Limits**: `num_ctx: 8192` (explicit). Output `num_predict: cfg.ollama_num_predict` (default 512, `0`/negative disables) caps generated tokens per turn — a worst-case latency guard for short spoken answers; the headroom stays above tool-call JSON so it does not truncate tool calls (both native and text tool-call paths). Timeout `llm_chat_timeout_sec` (45s). Auto-fallback from native to text tool-calls on HTTP 400 (`ToolsNotSupportedError`), sticky for the session. Risk: `fetch_web_page` truncates at 50,000 chars (~37k tokens) — mitigated for SMALL models by tool-result digest (#5) which compresses the payload before it enters the messages history. LARGE models receive the raw payload and may silently see a truncated context.
|
||||
|
||||
## 2. Intent Judge
|
||||
|
||||
- **File**: [src/jarvis/listening/intent_judge.py](src/jarvis/listening/intent_judge.py) — `IntentJudge.evaluate()`.
|
||||
- **Trigger**: on a speech segment *only if* there is an engagement signal (wake word detected, hot-window active, or TTS playing). Pure ambient speech skips it.
|
||||
- **Model / gating**: `cfg.intent_judge_model` (default `gemma4:e2b`, ~2B). Falls back to text-based wake detection if Ollama is unavailable.
|
||||
- **Model / gating**: `cfg.intent_judge_model`. Code-level default `gemma4:e2b` (~2B); the **Docker stack** renders it from `OLLAMA_INTENT_MODEL` (default `qwen2.5:3b`, pulled by `ollama-init`), kept deliberately **separate from `ollama_chat_model`** so this judge and the tool router (#3, #7) run on a small fast model while the big chat model is reserved for the spoken answer. Setting `OLLAMA_INTENT_MODEL = OLLAMA_CHAT_MODEL` folds them back onto one resident model. Falls back to text-based wake detection if Ollama is unavailable.
|
||||
- **Inputs**:
|
||||
- Rolling transcript buffer (last 120s, with timestamps)
|
||||
- Wake-word timestamp (if any), normalised aliases
|
||||
@@ -246,7 +246,7 @@ user input
|
||||
3. Pre-warm the intent-judge model before TTS finishes.
|
||||
4. Cache tool-router (#7) output by query hash.
|
||||
5. Give each digest its own timeout budget rather than sharing `llm_digest_timeout_sec` (today a slow memory digest can starve the max-turn digest).
|
||||
6. Consider single-model deployments: router+planner prefer `intent_judge_model`; loading a second model hurts cold-start latency on small hardware.
|
||||
6. Two-model vs single-model tradeoff: the Docker default keeps a **separate** small `intent_judge_model` (`OLLAMA_INTENT_MODEL=qwen2.5:3b`) so routing/judging/extraction don't pay the big chat model's per-call cost — the main win once the GPU holds both models resident. On VRAM-constrained hardware, fold them onto one model by setting `OLLAMA_INTENT_MODEL = OLLAMA_CHAT_MODEL` (saves a resident model at the cost of slower routing when the chat model is large).
|
||||
7. Narrow `llm_thinking_enabled` to router/planner only, not every context.
|
||||
8. Reduce `intent_judge_timeout_sec` (15s) or race it against text-based wake detection to avoid blocking the audio loop.
|
||||
|
||||
|
||||
282
docs/v1/README.md
Normal file
282
docs/v1/README.md
Normal file
@@ -0,0 +1,282 @@
|
||||
# Javis Bot
|
||||
|
||||
> 이 문서는 v1(Docker + VNC 구성) README입니다. v2 계획은 저장소 루트의 [README.md](../../README.md)를 보세요.
|
||||
|
||||
Ubuntu 데스크톱(VNC) 위에서 도는 **디스코드 네이티브 음성 비서**입니다.
|
||||
[isair/jarvis](https://github.com/isair/jarvis)의 성숙한 AI "두뇌"(메모리·툴·답변엔진·STT/TTS)를 그대로 쓰면서,
|
||||
입출력 인터페이스를 로컬 마이크/스피커에서 **디스코드 음성 + 화면 방송**으로 바꾼 하이브리드 구성입니다.
|
||||
|
||||
- 🎙️ 디스코드 음성 채널에서 말로 대화 (음성 입력 → 두뇌 → 음성 출력)
|
||||
- 🖥️ VNC 화면을 디스코드로 송출해서 같이 보기 (셀프봇 실시간 / noVNC / 스크린샷 선택)
|
||||
- ⌨️ `/자비스` 슬래시 명령으로 호출 — 호출한 사람이 음성 채널에 있으면 그 채널로 접속
|
||||
- 🔒 모든 슬래시 명령 응답은 **호출한 사람만 보이는 ephemeral** 메시지
|
||||
- 🧠 크롬/웹 제어, 메모리, MCP 툴 등 jarvis의 기능 유지
|
||||
|
||||
> 언어 선택 근거(Python 유지 vs 재작성)는 [docs/language-comparison.md](../language-comparison.md) 참고.
|
||||
> VNC + XFCE 호스트 셋업은 [docs/vnc-xfce-setup.md](../vnc-xfce-setup.md) 참고.
|
||||
> 원본 jarvis README는 [docs/UPSTREAM-README.md](../UPSTREAM-README.md)에 보존했습니다.
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처 (하이브리드)
|
||||
|
||||
```
|
||||
Discord ──voice / video / slash──▶ bot/ (Node + bun, discord.js)
|
||||
│ HTTP(localhost)
|
||||
▼
|
||||
bridge/ (Python, Flask)
|
||||
│ in-process import
|
||||
▼
|
||||
src/jarvis (기존 두뇌: STT·답변엔진·메모리·툴·TTS)
|
||||
```
|
||||
|
||||
- **bot/** — 디스코드 관련 전부. 슬래시 명령, 음성 송수신, VNC 화면 송출. AI 로직 없음.
|
||||
- **bridge/** — 얇은 HTTP 서비스. 음성(WAV) → 텍스트(STT) → 두뇌(답변) → 음성(TTS).
|
||||
- **src/jarvis** — 원본 jarvis 두뇌. 거의 손대지 않음. (PyQt 데스크톱 GUI/단축키 받아쓰기는 이 배포에선 사용하지 않음.)
|
||||
|
||||
왜 이렇게? 디스코드 봇은 정책상 영상(Go Live)을 송출할 수 없고, 봇 영상 송출이 되는 라이브러리는 Node 전용 + 셀프봇만 가능합니다. 반면 jarvis 두뇌는 검증된 Python 39k줄입니다. 그래서 영상이 가능한 Node로 인터페이스만 새로 짜고 두뇌는 Python 그대로 두는 하이브리드가 비용/위험 대비 최선입니다.
|
||||
|
||||
---
|
||||
|
||||
## 요구 사항
|
||||
|
||||
Docker로 돌리면(권장) 호스트에는 Docker + (GPU 쓸 경우) NVIDIA 드라이버만 있으면 되고, Python/bun/Ollama/ffmpeg/Whisper/Piper는 전부 컨테이너 안에 포함됩니다.
|
||||
|
||||
OS별 호스트 준비물:
|
||||
|
||||
| | Linux (Ubuntu 등) | Windows 11 |
|
||||
|---|---|---|
|
||||
| 컨테이너 런타임 | Docker Engine (CDI 지원, Docker 25+) | Docker Desktop + WSL2 백엔드 |
|
||||
| GPU 가속(선택) | `nvidia-container-toolkit` + `nvidia-ctk cdi generate` | NVIDIA 드라이버 + Docker Desktop GPU(WSL2) 활성화 |
|
||||
| GPU 넣는 compose | `docker-compose.gpu-linux.yml` | `docker-compose.gpu-windows.yml` |
|
||||
|
||||
- 디스코드 **봇** 토큰 1개 (음성/슬래시) — 또는 (셀프봇 송출 사용 시) 디스코드 **버너 유저** 토큰 1개
|
||||
- (도커 없이 수동 실행 시에만) Python 3.11+, [bun](https://bun.sh), Ollama, `ffmpeg`를 호스트에 직접 설치 — 아래 "수동" 절 참고
|
||||
|
||||
> VNC 데스크톱 호스트를 직접 구성하는 경우(도커 미사용)는 `docs/vnc-xfce-setup.md` 참고. 도커 실행에서는 VNC+XFCE가 컨테이너 안에 이미 들어 있습니다.
|
||||
|
||||
---
|
||||
|
||||
## 실행 — Docker (권장)
|
||||
|
||||
환경 설정 없이 통째로 컨테이너에서 돌립니다. VNC 데스크톱 + 크롬 + Python 브릿지 + Node 봇이 한 컨테이너(`javis`)에, LLM 백엔드(Ollama)가 별도 컨테이너에 뜹니다. **올리기만 하면 Ollama 모델까지 자동으로** 받아집니다.
|
||||
|
||||
베이스 `docker-compose.yml`에는 GPU 설정이 없습니다(이식성 유지). GPU는 OS에 맞는 override 파일을 같이 얹어서 켭니다. **돌리는 OS에 따라 명령이 다릅니다:**
|
||||
|
||||
```bash
|
||||
# ── Linux (Ubuntu 등, nvidia-container-toolkit + CDI) ──
|
||||
docker compose -f docker-compose.yml -f docker-compose.gpu-linux.yml up -d --build
|
||||
|
||||
# ── Windows 11 (Docker Desktop + WSL2 + NVIDIA) ──
|
||||
docker compose -f docker-compose.yml -f docker-compose.gpu-windows.yml up -d --build
|
||||
|
||||
# ── GPU 없이 (CPU 전용 호스트) ──
|
||||
# .env 에 WHISPER_DEVICE=cpu 를 넣고 베이스만 사용
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
매번 `-f`를 치기 싫으면 `.env`에 한 줄 넣어두면 그냥 `docker compose up -d`로 됩니다(override가 자동 적용):
|
||||
|
||||
```bash
|
||||
# Linux / macOS (구분자 = 콜론 ":")
|
||||
COMPOSE_FILE=docker-compose.yml:docker-compose.gpu-linux.yml
|
||||
# Windows 11 (구분자 = 세미콜론 ";" — 콜론은 드라이브 문자 C: 와 충돌)
|
||||
COMPOSE_FILE=docker-compose.yml;docker-compose.gpu-windows.yml
|
||||
```
|
||||
|
||||
> ⚠️ `COMPOSE_FILE`의 파일 구분자는 OS마다 다릅니다: Linux/macOS는 `:`, Windows는 `;`. Windows에서 `:`를 쓰면 Docker가 전체를 파일 하나 이름으로 읽어 `... The system cannot find the file specified` 에러가 납니다. 헷갈리면 `COMPOSE_FILE`을 비워두고 실행 시 직접 지정하세요: `docker compose -f docker-compose.yml -f docker-compose.gpu-windows.yml up -d --build`.
|
||||
|
||||
> Linux와 Windows는 GPU를 컨테이너에 넣는 방식이 달라서 override 파일이 갈립니다. Linux는 CDI(`devices: nvidia.com/gpu=all`), Windows(Docker Desktop)는 Compose의 `deploy.resources.reservations.devices`(`driver: nvidia`)를 씁니다. 호스트 사전 준비는 아래 "GPU 가속" 절 참고.
|
||||
|
||||
`docker compose up` 한 번이면 자동으로:
|
||||
- Ollama 서버가 뜨고, `ollama-init`이 채팅/보조(의도·라우팅)/임베딩 모델을 **자동 pull** (보조 모델 `OLLAMA_INTENT_MODEL`은 기본 `qwen2.5:3b`로, 큰 채팅 모델은 답변에만 쓰고 내부 분류 호출은 이 작은 모델이 처리)
|
||||
- VNC+XFCE 데스크톱 + 크롬 + Python 브릿지가 기동
|
||||
- Whisper STT 모델 / Piper TTS 음성 자동 다운로드(볼륨에 캐시)
|
||||
|
||||
화면 보기: VNC 뷰어 → `localhost:5901` (비밀번호 = `.env`의 `VNC_PASSWORD`, 기본 `javis123`) 또는 브라우저 → `http://localhost:6080/vnc.html`.
|
||||
로그: `docker compose logs -f javis`.
|
||||
|
||||
### 디스코드 토큰은 마지막에
|
||||
|
||||
토큰 없이도 위의 모든 게 정상 동작합니다(봇만 대기). 준비되면 `.env`를 만들어 토큰을 채웁니다.
|
||||
|
||||
기본 모드는 **유저봇(selfbot)** 입니다. 음성 참여와 화면 송출(Go Live)을 한 유저 계정으로 처리하며, Discord가 일반 봇 계정에는 Go Live를 허용하지 않기 때문에 이 방식이 기본입니다.
|
||||
|
||||
```bash
|
||||
cp .env.example .env # DISCORD_SELFBOT_TOKEN(버너 계정) + DISCORD_VOICE_CHANNEL_ID 채우기
|
||||
docker compose up -d # 유저봇이 로그인해 지정 음성채널에 자동 참여
|
||||
```
|
||||
|
||||
유저봇은 슬래시 명령을 쓸 수 없으므로 텍스트로 제어합니다: 음성 채널에서 `!자비스 join` / `!자비스 leave`. `DISCORD_VOICE_CHANNEL_ID`를 채워두면 시작 시 자동 참여합니다.
|
||||
|
||||
> ⚠️ 유저봇은 Discord ToS 위반이며 계정 정지 위험이 있습니다. 반드시 일회용 **버너 계정** 토큰만 사용하세요. 자세한 주의사항은 아래 "셀프봇 주의" 절을 참고하세요.
|
||||
|
||||
일반 봇(슬래시 명령 `/자비스`)으로 돌리려면 `DISCORD_BOT_TOKEN` / `DISCORD_APP_ID` / `DISCORD_GUILD_ID`를 채우세요. 다만 일반 봇은 화면 송출(Go Live)을 할 수 없습니다. `DISCORD_BOT_TOKEN`이 비어 있고 `DISCORD_SELFBOT_TOKEN`이 있으면 자동으로 유저봇 모드로 동작합니다. (`OLLAMA_CHAT_MODEL` 등 모델을 바꾸려면 `.env`에서 지정 후 `docker compose up -d`.)
|
||||
|
||||
### GPU 가속 (OS별)
|
||||
|
||||
LLM(Ollama)과 Whisper STT가 GPU에서 돕니다(env 기본 `WHISPER_DEVICE=cuda`). TTS는 기본값이 Edge TTS(온라인 한국어 음성)라 GPU를 쓰지 않습니다. NVIDIA Blackwell(sm_120, 예: RTX 5050/5070Ti)에서 검증: 컨테이너 내 torch cu128 CUDA 동작, Ollama GPU 오프로드, faster-whisper float16 모두 확인.
|
||||
|
||||
GPU는 위 "실행 — Docker"의 OS별 override 파일로 켜집니다. 호스트 사전 준비는 OS마다 다릅니다:
|
||||
|
||||
**Linux (Ubuntu 등) — CDI 방식, 1회:**
|
||||
|
||||
```bash
|
||||
# nvidia-container-toolkit 설치 후 CDI 스펙 생성 (Docker 25+ CDI, 데몬 재시작 불필요)
|
||||
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
|
||||
docker run --rm --device nvidia.com/gpu=all ubuntu nvidia-smi -L # GPU 보이면 OK
|
||||
```
|
||||
|
||||
`docker-compose.gpu-linux.yml`이 두 컨테이너에 `devices: ["nvidia.com/gpu=all"]`(CDI)로 GPU를 넣습니다.
|
||||
|
||||
**Windows 11 — Docker Desktop + WSL2:**
|
||||
|
||||
- 최신 NVIDIA 게임/스튜디오 드라이버 설치(별도 CUDA 툴킷 불필요).
|
||||
- Docker Desktop → Settings → Resources → WSL Integration 활성화(WSL2 백엔드). 최신 Docker Desktop은 WSL2에서 GPU를 자동 노출합니다.
|
||||
- 확인: PowerShell에서 `docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi`.
|
||||
- `docker-compose.gpu-windows.yml`이 `deploy.resources.reservations.devices`(`driver: nvidia`, `count: all`)로 GPU를 넣습니다.
|
||||
|
||||
**공통:**
|
||||
|
||||
- 모델: 베이스 compose 기본은 `qwen2.5:3b`(8GB VRAM에서 도구호출 안정적). 더 무겁게(`qwen2.5:7b`, `qwen3:8b` 등) 쓰려면 `.env`의 `OLLAMA_CHAT_MODEL` 변경.
|
||||
- **GPU가 없거나 인식 실패 시 자동으로 CPU 폴백**(Whisper)하므로 안전합니다. 명시적으로 CPU만 쓰려면 override 파일 없이 베이스만 올리고 `.env`에 `WHISPER_DEVICE=cpu`를 두세요.
|
||||
|
||||
- 데이터(메모리 DB), Whisper 캐시, Piper 음성은 named volume에 영속됩니다.
|
||||
- 셀프봇 영상 송출 의존성은 이미지에 기본 포함하지 않습니다. 쓰려면 컨테이너에서 `cd /app/bot && bun add discord.js-selfbot-v13 @dank074/discord-video-stream` 후 재시작(또는 Dockerfile에 추가).
|
||||
|
||||
---
|
||||
|
||||
## 실행 — 수동(도커 없이)
|
||||
|
||||
도커 없이 호스트에서 직접 돌릴 때는 OS별로 venv 활성화·ffmpeg 설치·실행 스크립트가 다릅니다.
|
||||
|
||||
**Linux / macOS:**
|
||||
|
||||
```bash
|
||||
# 1) 환경 변수
|
||||
cp .env.example .env # DISCORD_BOT_TOKEN / DISCORD_APP_ID / DISCORD_GUILD_ID 등 채우기
|
||||
|
||||
# 2) Python 두뇌 + 브릿지 의존성
|
||||
python3 -m venv .venv && . .venv/bin/activate
|
||||
pip install -r requirements.txt # jarvis 두뇌
|
||||
pip install flask # 브릿지(없으면)
|
||||
|
||||
# 3) 디스코드 봇 의존성 (bun)
|
||||
cd bot && bun install && cd ..
|
||||
|
||||
# 4) 한 번에 실행 (브릿지 + 봇)
|
||||
./scripts/dev.sh
|
||||
# 또는 따로: ./scripts/start_bridge.sh / ./scripts/start_bot.sh
|
||||
```
|
||||
|
||||
- `ffmpeg`: Ubuntu `sudo apt install ffmpeg`, macOS `brew install ffmpeg`.
|
||||
|
||||
**Windows 11 (PowerShell):**
|
||||
|
||||
```powershell
|
||||
# 1) 환경 변수
|
||||
copy .env.example .env # 같은 키들 채우기
|
||||
|
||||
# 2) Python 두뇌 + 브릿지 의존성 (venv 활성화 경로가 다름)
|
||||
py -3 -m venv .venv; .\.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
pip install flask
|
||||
|
||||
# 3) 디스코드 봇 의존성 (bun — Windows 네이티브 또는 WSL2)
|
||||
cd bot; bun install; cd ..
|
||||
|
||||
# 4) 실행: .sh 스크립트는 bash 전용이라 Windows에서는 두 프로세스를 따로 띄웁니다
|
||||
# (PowerShell 창 2개, 또는 WSL2에서 위 Linux 절차 그대로 사용 권장)
|
||||
python -m bridge.server # 창 1: 브릿지
|
||||
cd bot; bun run register; bun run start # 창 2: (일반 봇이면) 슬래시 등록 후 봇 기동
|
||||
```
|
||||
|
||||
- `ffmpeg`: `winget install Gyan.FFmpeg` 또는 `choco install ffmpeg` 후 PATH 확인.
|
||||
- `scripts/*.sh`(dev/start_bridge/start_bot)는 bash 스크립트라 순수 Windows에선 동작하지 않습니다. 가장 간단한 길은 **WSL2 안에서 위 Linux 절차를 그대로** 쓰는 것입니다(도커도 WSL2 백엔드와 동일).
|
||||
|
||||
봇이 뜨면 디스코드에서 `/자비스 join` 으로 음성 채널에 부르세요.
|
||||
|
||||
---
|
||||
|
||||
## 슬래시 명령 (`/자비스`)
|
||||
|
||||
| 명령 | 동작 |
|
||||
|---|---|
|
||||
| `/자비스 join` | 호출자가 있는 음성 채널에 접속해 듣기 시작 |
|
||||
| `/자비스 leave` | 음성 채널에서 나감 |
|
||||
| `/자비스 ask 질문:<내용>` | 텍스트로 질문하고 답을 받음 |
|
||||
| `/자비스 stream` | VNC 화면을 디스코드에 송출 시작 |
|
||||
| `/자비스 stop` | 송출 중단 |
|
||||
| `/자비스 status` | 브릿지 두뇌/세션/송출 상태 확인 |
|
||||
|
||||
모든 응답은 **호출한 사람에게만** 보입니다(ephemeral).
|
||||
|
||||
---
|
||||
|
||||
## VNC 화면 송출 백엔드 (`STREAM_BACKEND`)
|
||||
|
||||
`.env`에서 교체 가능합니다. 코드 변경 없이 위험/방식만 바꿉니다.
|
||||
|
||||
| 값 | 방식 | 실시간 | 디스코드 native | 밴 위험 |
|
||||
|---|---|---|---|---|
|
||||
| `selfbot` (기본) | 버너 유저 계정으로 Go Live 실시간 송출 | ✅ | ✅ | ⚠️ ToS 위반·정지 위험 |
|
||||
| `novnc` | noVNC 브라우저 링크 공유 | ✅ | ❌ | 없음 |
|
||||
| `screenshot` | N초마다 채널에 스크린샷 업로드 | ❌ | ❌ | 없음 |
|
||||
| `none` | 비활성화 | — | — | — |
|
||||
|
||||
### 셀프봇(selfbot) 주의
|
||||
|
||||
- 디스코드 봇은 영상 송출이 불가능해, 실시간 화면 방송은 **유저 계정 토큰(셀프봇)** 으로만 됩니다.
|
||||
- 이는 Discord ToS 위반이며 계정이 영구 정지될 수 있습니다.
|
||||
- 반드시 **버너(일회용) 계정**을 만들어 그 토큰을 `DISCORD_SELFBOT_TOKEN`에 넣고, 본계정은 절대 쓰지 마세요.
|
||||
- 영상 송출만 조용히 하는 패턴은 상대적으로 위험이 낮지만 0은 아닙니다.
|
||||
- 의존성(네이티브)은 선택 설치입니다:
|
||||
```bash
|
||||
cd bot && bun add discord.js-selfbot-v13 @dank074/discord-video-stream
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 환경 변수
|
||||
|
||||
전체 목록과 설명은 [`.env.example`](../../.env.example)에 있습니다. 핵심:
|
||||
|
||||
- `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`, `DISCORD_GUILD_ID` — 봇/길드
|
||||
- `BRIDGE_URL` — 봇이 호출할 브릿지 주소 (기본 `http://127.0.0.1:8765`)
|
||||
- `STREAM_BACKEND`, `DISCORD_SELFBOT_TOKEN`, `NOVNC_URL` — 화면 송출
|
||||
- `VNC_DISPLAY=:1`, `VNC_RESOLUTION`, `VNC_FRAMERATE`, `VNC_BITRATE_KBPS` — 캡처
|
||||
- `WHISPER_DEVICE/COMPUTE_TYPE` — GPU 호스트면 `cuda`/`float16`, CPU 전용이면 `cpu`(GPU 자체는 OS별 override compose 파일로 켬)
|
||||
- `OLLAMA_CHAT_MODEL` — 두뇌 LLM (기본 `qwen2.5:3b`)
|
||||
- `COMPOSE_FILE` — OS별 GPU override를 매번 `-f`로 안 치고 자동 적용 (위 "실행 — Docker" 참고)
|
||||
- `output_language` — 출력 언어 고정(비우면 사용자 언어). 설정 웹 UI(`/settings`)에서 바꾸면 env 기본값보다 우선하며 컨테이너 재생성 후에도 유지됩니다.
|
||||
- `AGENTS_DIR` — 운영자 지시문 폴더(기본 `/app/agents`, `./agents`가 read-only로 마운트됨). 아래 "운영자 지시문" 참고.
|
||||
|
||||
---
|
||||
|
||||
## 운영자 지시문 (`agents/*.md`)
|
||||
|
||||
`agents/` 폴더에 마크다운 파일을 넣으면 그 내용이 어시스턴트의 메인 답변 시스템 프롬프트 뒤에 그대로 추가됩니다. 페르소나(집사 성격)는 그대로 두고 규칙·말투·금칙어 등을 덧붙일 때 쓰세요.
|
||||
|
||||
- `agents/` 안의 모든 `*.md`를 **파일명 순서**로 이어 붙입니다. 순서를 정하려면 `00-tone.md`, `10-rules.md`처럼 숫자 접두사를 쓰세요.
|
||||
- **매 답변마다 다시 읽습니다.** 파일을 저장하면 다음 발화부터 바로 반영되며, 재빌드/재시작이 필요 없습니다(폴더가 read-only로 마운트됨).
|
||||
- 폴더가 없거나 비어 있으면 아무 일도 일어나지 않습니다(fail-open).
|
||||
- `agents/example.md.sample`을 `rules.md` 등 `*.md`로 복사해서 시작하세요. `.sample` 파일은 로드되지 않습니다.
|
||||
|
||||
---
|
||||
|
||||
## 현재 상태 / 남은 작업
|
||||
|
||||
이 레포는 동작하는 **스캐폴드**입니다. 구조·명령·송출 백엔드·브릿지 연동은 완성되어 있고, 실제 토큰/모델/VNC 디스플레이를 붙여 런타임 검증이 필요한 부분이 남아 있습니다.
|
||||
|
||||
- [ ] 실제 디스코드 봇/버너 토큰으로 음성 송수신 end-to-end 검증
|
||||
- [ ] faster-whisper(CUDA) + Piper 모델로 STT/TTS 실측
|
||||
- [ ] 셀프봇 영상 송출 라이브러리 버전별 API 실연결(현재 v6 API 기준 작성)
|
||||
- [ ] Ollama 모델 다운로드 및 두뇌 응답 품질 점검
|
||||
|
||||
---
|
||||
|
||||
## 크레딧
|
||||
|
||||
- 두뇌: [isair/jarvis](https://github.com/isair/jarvis) (라이선스는 [LICENSE](../../LICENSE) 참고)
|
||||
- 디스코드 음성: [discord.js](https://discord.js.org) / [@discordjs/voice](https://github.com/discordjs/voice)
|
||||
- 영상 송출: [@dank074/discord-video-stream](https://github.com/Discord-RE/Discord-video-stream)
|
||||
87
docs/v2/architecture.md
Normal file
87
docs/v2/architecture.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# v2 전체 구조
|
||||
|
||||
## 목표
|
||||
|
||||
지금 서버와 Windows Docker에 나뉘어 돌던 자비스봇을 **게임PC 한 대에서 완전 로컬로** 돌립니다. 설치 파일 하나로 깔리는 **Windows 관리 앱**에서 모든 것을 설정·관리합니다. 기존 기능(음성 대화, 메모리, 날씨, 웹 검색, 식단 기록, MCP, 브라우저 제어)은 그대로 유지합니다.
|
||||
|
||||
## v1과 비교
|
||||
|
||||
| 항목 | v1 (지금) | v2 |
|
||||
|---|---|---|
|
||||
| LLM 엔진 | Ollama, 기본 `qwen2.5:3b` | Strata (RAM+VRAM 하이브리드, OpenAI 호환 API). MoE 모델로 교체 |
|
||||
| LLM 모델 | 3B급 소형 모델 | 빠름: Qwen3.6-35B-A3B / 권장: Qwen3.8-Flash-Next (앱에서 선택) |
|
||||
| STT | faster-whisper(small/medium), 말이 끝나고 0.8초 침묵 후 통째 전사, beam 5 | faster-whisper large-v3-turbo 상주, 말하는 중 부분 전사, 발화 종료 즉시 확정 |
|
||||
| TTS | MeloTTS (GPU) | MeloTTS 유지(한국어 검증됨), 문장 단위 스트리밍. CosyVoice2 선택지 추가 |
|
||||
| 실행 위치 | Windows Docker(약 25GB 이미지) + 서버(브라우저) | 게임PC 단독, Docker 없음 |
|
||||
| 관리 방법 | `.env` 파일 직접 수정 | Windows exe 앱(GUI) |
|
||||
| 동시 대화 | 사실상 1명씩 처리 | 최대 10명 동시 수신·전사. 응답 정책은 GUI에서 선택, 기본은 "처음 대화만" |
|
||||
| 채팅 채널 | 슬래시 명령만. 채팅은 읽지 못함 | 등록한 채팅 채널을 AI가 읽고, 보내고, 수정 |
|
||||
| 대화 기억 | 최근 5분 원문 + 과거 기록에서 관련 내용 3개 | 본인이 말했던 기록 전체, 등록한 채팅 채널, 같은 음성 채널에 함께 있던 다른 사람 말에서 관련 내용을 찾아 참고 |
|
||||
| 화면 보기 | 없음 | 전체 화면, 모니터별, 창별 화면을 봇이 직접 봄 |
|
||||
| 설치 | Docker, CUDA, 환경변수 수동 구성 | 설치 파일 하나. 첫 실행 때 고른 폴더에 전부 저장 |
|
||||
|
||||
v1 기준 값: `bot/src/config.ts`의 `VOICE_SILENCE_MS=800`, `bridge/server.py`의 `STT_BEAM_SIZE=5`, `src/jarvis/config.py`의 `dialogue_memory_timeout=300`, `memory_enrichment_max_results=3`.
|
||||
|
||||
v1도 STT는 이미 faster-whisper입니다. 느린 진짜 이유는 엔진이 아니라 다음 세 가지입니다.
|
||||
|
||||
1. 말이 끝난 뒤 0.8초를 기다립니다.
|
||||
2. 끝난 다음에야 통째로 전사합니다.
|
||||
3. beam 5로 정확도 위주 설정입니다.
|
||||
|
||||
그래서 v2의 STT 개선은 엔진 교체보다 **스트리밍 전사와 종료 판정 방식 변경**이 핵심입니다.
|
||||
|
||||
## 하드웨어 기준과 자원 배분
|
||||
|
||||
기준 게임PC: RTX 5070 Ti 16GB (Blackwell, sm_120), DDR5 128GB, Ryzen 9 9950X3D (16코어/32스레드)
|
||||
|
||||
| 자원 | 용도 | 예상 사용량 |
|
||||
|---|---|---|
|
||||
| VRAM 16GB | STT: faster-whisper large-v3-turbo (int8_float16) | 약 1.5~2.5GB (동시 처리 배치 포함) |
|
||||
| | TTS: MeloTTS 한국어 | 약 1GB |
|
||||
| | LLM 활성 부분 (Strata가 자동 배치) | 나머지 11~13GB |
|
||||
| RAM 128GB | LLM 전체 가중치(전문가 층), 브라우저, 앱 | 빠름 모델 약 32~52GB / 권장 모델 약 44~60GB |
|
||||
| CPU 32스레드 | 화자별 VAD(Silero), Opus 디코딩, 리샘플, 크로미움 | 10명 동시여도 여유 있음 |
|
||||
| 디스크 | 모델, Python 런타임, 캐시 | 최소 120GB, 권장 200GB 이상 (NVMe 권장) |
|
||||
|
||||
게임을 켜면 VRAM을 두고 다투므로 게임 모드를 둡니다. 게임 모드는 [pc-features.md](pc-features.md#게임-모드)에 정리했습니다.
|
||||
|
||||
## 구성 요소
|
||||
|
||||
```
|
||||
[게임PC (Windows 11) 한 대에서 전부 실행]
|
||||
|
||||
1. Jarvis 관리 앱 (exe, Electron + TypeScript)
|
||||
├─ GUI: 대시보드 / 봇 / 채널·호출 / 채팅 채널 / 대화 기억 / 모델 / 기능
|
||||
│ / 게임 모드 / PC 제어 / 화면 보기 / 데이터 / 로그
|
||||
├─ 서비스 관리자: 아래 프로세스를 띄우고, 감시하고, 죽으면 재시작
|
||||
├─ 디스코드 음성 코어 (discord.js + @discordjs/voice + DAVE 복호화)
|
||||
│ 화자별 Opus 수신 → PCM → 음성 워커로 전달 / TTS 음성 재생
|
||||
├─ 채팅 채널 연결 (등록한 채널 읽기·보내기·수정·검색)
|
||||
├─ 브라우저 에이전트 (Playwright + 봇용 크롬창, 백그라운드 가능)
|
||||
├─ 게임·안티치트 감지 (게임 모드 전환, 자동 입력 차단)
|
||||
└─ PC 제어 모듈 (전체·모니터별·창별 화면 캡처, 키보드/마우스 입력)
|
||||
│
|
||||
│ 로컬 WebSocket (127.0.0.1, 앱이 발급한 토큰으로만 접속)
|
||||
▼
|
||||
2. 음성·두뇌 워커 (Python, 데이터 폴더 안 가상환경)
|
||||
├─ STT: 화자별 VAD → 공용 faster-whisper(GPU, 배치) → 부분/최종 전사
|
||||
├─ 두뇌: 기존 jarvis 코드 재사용 (메모리, 날씨, 웹 검색, 식단, MCP, 플래너)
|
||||
├─ 대화 기록 저장소: 음성 전사와 채팅 채널 메시지 저장·검색 (SQLite)
|
||||
└─ TTS: MeloTTS / CosyVoice2, 문장 단위 스트리밍
|
||||
│
|
||||
│ OpenAI 호환 HTTP (127.0.0.1:8080)
|
||||
▼
|
||||
3. Strata LLM 서버
|
||||
strata launch --yes --no-tui --data-dir <데이터 폴더>\models\llm
|
||||
```
|
||||
|
||||
## 기술 선택과 이유
|
||||
|
||||
| 부분 | 선택 | 이유 |
|
||||
|---|---|---|
|
||||
| GUI 앱 | Electron + TypeScript (React UI) | 디스코드 음성 코어(discord.js), Playwright, 화면 캡처가 모두 Node 생태계라 한 언어로 묶입니다. v1 봇 코드(TypeScript)를 옮길 수 있습니다. Tauri는 가볍지만 Rust와 Node 사이드카를 따로 둬야 해서 복잡해집니다. |
|
||||
| 음성 워커 | Python (faster-whisper, MeloTTS, 기존 jarvis) | STT·TTS 모델과 기존 두뇌 코드(메모리, 도구, 스펙 문서)가 Python입니다. 다시 짜는 것보다 재사용이 안전합니다. |
|
||||
| LLM 엔진 | Strata (MIT) | Windows 설치 지원, RTX 50 지원, `--data-dir`로 저장 위치 지정, 헤드리스 실행(`--no-tui`). 앱에 포함해 배포해도 라이선스 문제가 없습니다. |
|
||||
| LLM 예비 엔진 | OpenAI 호환 주소 직접 입력 | Strata에 문제가 생기면 llama.cpp, Ollama 같은 다른 로컬 엔진으로 바꿔 끼웁니다. |
|
||||
| Python 런타임 | uv + 독립 실행형 Python 3.12 | 사용자가 Python을 따로 깔 필요가 없고 시스템 Python과 섞이지 않습니다. 전부 데이터 폴더 안에 설치됩니다. |
|
||||
| 설치 파일 | NSIS (electron-builder) | 설치 파일은 약 200MB 내외로 두고, 모델과 런타임은 첫 실행 때 받습니다. |
|
||||
71
docs/v2/conversation.md
Normal file
71
docs/v2/conversation.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# 대화: 10명 동시 대화, 호출, 응답 정책, 채팅 채널
|
||||
|
||||
## 최대 10명 동시 대화
|
||||
|
||||
- **수신·전사는 동시에**:
|
||||
- 디스코드는 화자별로 따로 스트림을 줍니다.
|
||||
- 10명 각각 VAD를 돌리고, 공용 STT 모델 하나가 여러 화자의 조각을 묶어서(배치) 처리합니다.
|
||||
- 최대 화자 수는 설정에서 1~10으로 정합니다.
|
||||
- **누가 말했는지 구분**:
|
||||
- 디스코드 사용자 ID로 화자를 확정합니다. 음성 분석으로 추측하지 않습니다.
|
||||
- LLM에는 `[닉네임] 말: ...` 형식으로 넘기고, 기록도 사람별로 저장합니다.
|
||||
- **끼어들기**:
|
||||
- 봇이 말하는 중에 누가 말한다고 바로 멈추지는 않습니다. 10명이 있는 채널에서는 잡담만으로도 답이 계속 끊기기 때문입니다.
|
||||
- 들어온 말이 호출 조건을 통과한 새 요청일 때만, 응답 정책에 따라 계속할지 멈출지 정합니다.
|
||||
- "자비스, 멈춰"처럼 호출어와 정지 명령을 같이 말하면 어떤 정책에서든 바로 멈춥니다.
|
||||
|
||||
## 호출어와 호출 방식
|
||||
|
||||
| 설정 | 내용 |
|
||||
|---|---|
|
||||
| 호출어(prefix) | GUI에서 여러 개 등록·수정·삭제 (예: "자비스", "야 자비스", "javis"). 음성과 채팅에 같이 쓰고, 채팅용은 따로 지정할 수도 있습니다. 비슷한 발음 허용 정도(예: "자비즈")도 조절합니다. |
|
||||
| 호출 방식 | (1) 호출어로 부를 때만 응답 **(기본값)** / (2) 봇에게 하는 말로 판단되면 응답 / (3) 모든 말에 응답 |
|
||||
| 지정한 사람 | GUI에서 서버 멤버 목록으로 고릅니다. 아래 두 설정을 **각각 켜고 끕니다**. |
|
||||
| └ 지정한 사람만 응답 | 기본: 꺼짐. 켜면 지정하지 않은 사람이 불러도 대답하지 않습니다. |
|
||||
| └ 지정한 사람은 호출어 없이 대답 | 기본: 꺼짐. 켜면 지정한 사람이 하는 말에는 호출어 없이도 대답합니다. 다른 사람은 "호출 방식"을 그대로 따릅니다. |
|
||||
|
||||
두 설정의 조합:
|
||||
|
||||
| 지정한 사람만 응답 | 호출어 없이 대답 | 결과 |
|
||||
|---|---|---|
|
||||
| 켜짐 | 꺼짐 | 지정한 사람이 호출어로 부를 때만 대답 |
|
||||
| 켜짐 | 켜짐 | 지정한 사람 말에만, 호출어 없이 대답 |
|
||||
| 꺼짐 | 켜짐 | 누구든 호출어로 부르면 대답하고, 지정한 사람 말에는 호출어 없이도 대답 |
|
||||
| 꺼짐 | 꺼짐 | 누구든 호출어로 부를 때만 대답 (기본) |
|
||||
|
||||
## 동시 대화 응답 정책 (GUI에서 선택)
|
||||
|
||||
봇의 입은 하나라서 답은 한 번에 하나씩 합니다. 여러 사람이 동시에 부르거나 봇이 말하는 중에 새 요청이 들어올 때 어떻게 할지 고릅니다.
|
||||
|
||||
| 정책 | 새 요청 처리 | 봇이 말하는 중에 새 요청이 오면 |
|
||||
|---|---|---|
|
||||
| **처음 대화만 (기본값)** | 봇이 답을 준비하거나 말하는 동안 들어온 새 요청은 버립니다. 지금 답이 끝나야 다음 요청을 받습니다. 여러 명이 거의 동시에 부르면 **말이 먼저 끝난 사람** 하나에 답합니다. 먼저 끝난 말이 아직 전사 중이면 호출인지 확인될 때까지 잠깐 기다립니다. | 지금 답을 끝까지 재생하고, 새 요청은 버립니다. |
|
||||
| 들어온 순서대로 | 요청마다 **말이 끝난 시각**으로 순번을 붙여 그 순서대로 답합니다. 전사가 끝난 순서가 아니므로 길게 말한 사람이 뒤로 밀리지 않습니다. 대기열 최대 길이를 넘으면 가장 오래된 요청부터 버립니다. | 지금 답을 끝까지 재생하고, 새 요청은 대기열에 넣습니다. |
|
||||
| 마지막 대화만 | 대기열에 가장 최근 요청 하나만 남깁니다. | 지금 답을 멈추고 가장 최근 요청에 바로 답합니다. 멈춘 답은 다시 재생하지 않습니다. |
|
||||
| 제일 중요한 대화만 | 짧은 수집 시간(기본 0.7초)과 봇이 말하는 동안 들어온 요청을 모아 점수를 매기고, 가장 높은 하나에만 답합니다. 판단 기준은 (1) 사람별 우선순위, (2) 호출어로 직접 불렀는지, (3) LLM이 판단한 중요도 순입니다. 후보가 2개 이상일 때만 LLM 판단을 하므로 평소에는 지연이 늘지 않습니다. | 새 요청의 점수가 더 높으면 멈추고 새 요청에 답합니다. 낮거나 같으면 끝까지 재생하고, 그 뒤 남은 후보 중 가장 높은 것에 답합니다. |
|
||||
|
||||
버려진 요청과 중간에 멈춘 답은 대시보드의 "놓친 요청" 목록에 남아서, 무엇이 왜 빠졌는지 볼 수 있습니다.
|
||||
|
||||
## AI 채팅 채널
|
||||
|
||||
음성 말고 디스코드 채팅으로도 자비스를 쓰고, 자비스가 채팅 채널을 직접 다룰 수 있게 합니다. v1 봇은 `Guilds`, `GuildVoiceStates` 인텐트만 써서 슬래시 명령만 받고 채팅은 읽지 못하므로 새로 만드는 기능입니다.
|
||||
|
||||
| GUI 설정 | 내용 |
|
||||
|---|---|
|
||||
| 채널 목록 | 여러 개 등록·수정·삭제. 채널마다 **채널 ID**(붙여넣기 또는 서버 채널 목록에서 고르기), **이름**, **설명**을 편집합니다. 이름과 설명은 AI에게 "이 채널은 무엇을 하는 곳인지"로 전달됩니다. 예를 들어 "일정 채널에 올려 줘"라고 하면 설명을 보고 맞는 채널을 고릅니다. |
|
||||
| 디스코드에도 반영 | 기본: **켜짐**. GUI에서 고친 이름·설명을 실제 디스코드 채널 이름·주제에도 바꿉니다. 끄면 이름·설명은 AI에게 채널 용도를 알려 주는 데만 씁니다. |
|
||||
| AI가 할 수 있는 일 (채널별) | 읽기·검색 **켜짐** / 메시지 보내기 **켜짐** / 봇이 쓴 메시지 수정 **켜짐** / 이모지 반응 **켜짐** / 메시지 삭제 꺼짐 / 고정 꺼짐 / 스레드 만들기 꺼짐 |
|
||||
| 채팅으로 부르기 | 채널마다 "호출어로 부를 때만"(기본) 또는 "모든 메시지에 대답". 호출어와 지정한 사람 설정은 음성과 같이 씁니다. |
|
||||
|
||||
- **음성과 연결**: 음성으로 "자비스, 채팅 채널에 오늘 할 일 올려 줘", "채팅에 방금 뭐 올라왔어?"처럼 시킬 수 있습니다.
|
||||
- **디스코드 제약**: 봇은 자기가 쓴 메시지만 수정할 수 있습니다. 다른 사람 메시지는 삭제·고정만 되고, 서버에서 메시지 관리 권한을 줘야 합니다.
|
||||
- **채널 이름·주제 반영**:
|
||||
- 봇에 서버의 채널 관리 권한이 있어야 합니다. 권한이 없으면 GUI에 실패 이유를 보여 주고, 고친 이름·설명은 앱에만 저장합니다.
|
||||
- 채널을 등록하면 지금 디스코드에 있는 채널 이름과 주제를 불러와 이름·설명 칸에 채웁니다.
|
||||
- 설명은 채널 주제로 들어가며 디스코드 길이 제한(1,024자)을 넘으면 저장 전에 알려 줍니다. 텍스트 채널 이름은 디스코드 규칙대로 공백이 `-`로 바뀌므로, 바뀐 이름을 GUI에 다시 보여 줍니다.
|
||||
- 디스코드는 채널 이름·주제 변경 횟수를 짧은 시간 안에 제한합니다(채널당 10분에 2번 정도). 제한에 걸리면 GUI에 "잠시 뒤 반영"으로 표시하고 자동으로 다시 시도합니다.
|
||||
- **안전장치**:
|
||||
- 삭제처럼 되돌릴 수 없는 일은 실행 전에 한 번 더 확인합니다.
|
||||
- 채팅에 올라온 다른 사람의 글은 명령이 아니라 데이터로 다룹니다. 누군가 "자비스, 메시지 다 지워"라고 써 두어도, 그 글을 읽었다는 이유만으로 실행하지 않습니다.
|
||||
- **필요한 설정**: 채팅 내용을 읽으려면 디스코드 개발자 포털에서 봇의 Message Content Intent를 켜야 합니다. 첫 실행 마법사가 켜졌는지 확인하고 안내합니다.
|
||||
- 채팅 채널 메시지는 대화 기록 저장소에 저장되어 대화 기억에 쓰입니다([memory.md](memory.md)).
|
||||
26
docs/v2/decisions.md
Normal file
26
docs/v2/decisions.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# 결정 사항
|
||||
|
||||
## 확정된 것
|
||||
|
||||
| 항목 | 결정 |
|
||||
|---|---|
|
||||
| 게임PC 접근 방법 | 측정 스크립트를 사용자가 게임PC에서 직접 실행하고 결과를 보내 주는 방식 |
|
||||
| exe가 돌아가는 곳 | 게임PC 한 대에서만. 원격 관리 기능은 만들지 않음 |
|
||||
| 백그라운드 수집 대상 | 기본은 비워 둠. 요청이 있을 때 추가 |
|
||||
| Go Live 송출(셀프봇) | 뺌. 대신 봇용 크롬창 화면공유 선택 표시 설정 ([pc-features.md](pc-features.md#봇용-크롬창과-디스코드-화면공유)) |
|
||||
| 저장소 처리 | v1 마지막 상태(`bb60c4d`)를 원격 저장소 `legacy` 브랜치로 보존하고 같은 저장소에서 v2 시작. v1 README는 [docs/v1/README.md](../v1/README.md)로 옮김 |
|
||||
| 호출 방식 기본값 | 호출어로 부를 때만 응답 |
|
||||
| 지정한 사람 설정 | "지정한 사람만 응답"과 "지정한 사람은 호출어 없이 대답"을 각각 켜기/끄기. 기본은 둘 다 꺼짐 ([conversation.md](conversation.md#호출어와-호출-방식)) |
|
||||
| 동시 대화 응답 정책 기본값 | 처음 대화만 |
|
||||
| "제일 중요한 대화" 판단 기준 | 사람별 우선순위 → 호출어로 직접 불렀는지 → LLM이 판단한 중요도 |
|
||||
| 대화 기억 범위 기본값 | 본인 기록 + 등록한 채팅 채널 + 같은 음성 채널에 함께 있던 다른 사람 말. 채팅 채널과 다른 사람 말은 각각 켜기/끄기, 기본은 둘 다 켜짐 ([memory.md](memory.md)) |
|
||||
| 가상 디스플레이 드라이버 | 필요해지면 설치. 설치 때 관리자 권한 1회 |
|
||||
| 게임 모드 | 테두리 없는 창 게임도 감지. (a) RAM 위주로 / (b) 빠름 모델로 / (c) 일시정지 각각 켜기/끄기, 기본은 (a)만 ([pc-features.md](pc-features.md#게임-모드)) |
|
||||
| 안티치트 | 안티치트 게임 실행 중에는 키보드·마우스 제어를 막고 안티치트 이름으로 안내 |
|
||||
| 다른 사람 화면공유 보기 | 자비스가 말로 창 분리(팝아웃)를 요청하고 분리된 창만 캡처. 디스코드 앱을 직접 조작하지 않음 ([pc-features.md](pc-features.md#다른-사람의-디스코드-화면공유-보기-창-분리-방식)) |
|
||||
| AI 채팅 채널 | GUI에서 채널 ID·이름·설명 편집, AI가 읽기·보내기·수정 등 수행 ([conversation.md](conversation.md#ai-채팅-채널)) |
|
||||
| 채팅 채널 이름·설명 반영 | 실제 디스코드 채널 이름·주제까지 바꿈. "디스코드에도 반영" 켜기/끄기, 기본 켜짐 |
|
||||
|
||||
## 확인이 필요한 질문
|
||||
|
||||
지금은 없습니다.
|
||||
84
docs/v2/desktop-app.md
Normal file
84
docs/v2/desktop-app.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Windows 관리 앱 (exe)
|
||||
|
||||
## 첫 실행 마법사
|
||||
|
||||
1. **데이터 저장 위치 선택**: 폴더를 고르면 남은 용량을 확인하고(권장 200GB), 모델과 데이터가 전부 그 안에 저장된다고 안내합니다.
|
||||
2. **PC 점검**: GPU, NVIDIA 드라이버 버전(CUDA 13용 580 이상), RAM, 디스크를 확인합니다. 드라이버가 오래됐으면 업데이트 링크를 보여 줍니다.
|
||||
3. **모델 프리셋 선택**: 빠름 / 권장 중에서 고르면 다운로드 크기와 예상 시간을 보여 줍니다.
|
||||
4. **자동 설치**: 다음을 데이터 폴더에 받습니다. 이어받기와 해시 검증을 지원합니다.
|
||||
- Python 런타임과 가상환경
|
||||
- CUDA 라이브러리
|
||||
- Strata
|
||||
- STT·TTS 모델
|
||||
- 크로미움
|
||||
- ffmpeg
|
||||
5. **디스코드 봇 연결**: 아래 순서로 진행합니다.
|
||||
1. 봇 토큰 입력(숨김 표시)
|
||||
2. 연결 확인
|
||||
3. Message Content Intent 켜짐 확인
|
||||
4. 초대 링크 생성(채팅 채널 이름·주제 반영에 쓰는 채널 관리 권한 포함)
|
||||
5. 서버와 음성 채널 선택
|
||||
6. AI 채팅 채널 선택(건너뛰기 가능)
|
||||
7. 호출어 입력
|
||||
8. 슬래시 명령 등록
|
||||
6. **테스트**: 마이크 없이도 "테스트 문장 읽기", "LLM 응답 확인" 버튼으로 각 부분을 확인합니다.
|
||||
|
||||
## 데이터 폴더 구조
|
||||
|
||||
```
|
||||
<사용자가 고른 폴더>\
|
||||
config\ settings.json, secrets.dat (봇 토큰 등, Windows DPAPI로 암호화)
|
||||
runtime\ python\, venv\, strata\, ffmpeg\, chromium\
|
||||
models\ llm\ (Strata --data-dir), stt\, tts\, vad\
|
||||
memory\ 대화 기록 저장소, 메모리, 식단 기록 DB (SQLite)
|
||||
browser\ 앱 전용 크로미움 프로필
|
||||
collect\ 백그라운드 수집 결과 (기본은 비어 있음)
|
||||
cache\ HF_HOME, pip/uv 캐시, 임시 파일(TEMP 재지정)
|
||||
logs\ 서비스별 로그 (기간 지나면 자동 정리)
|
||||
```
|
||||
|
||||
폴더 밖에 남는 것은 피할 수 없는 최소한입니다.
|
||||
|
||||
1. 앱 실행 파일 자체. 설치 경로도 같은 폴더로 고를 수 있습니다.
|
||||
2. 데이터 폴더 위치를 기억하는 파일 1개(`%APPDATA%\JarvisBot\location.json`).
|
||||
3. NVIDIA 드라이버. 시스템 구성 요소라 앱이 설치하지 않습니다.
|
||||
|
||||
그 외 다운로드, 캐시, 임시 파일은 모두 데이터 폴더로 보냅니다. 위치를 옮기는 "데이터 이동" 기능도 넣습니다.
|
||||
|
||||
## 설정 화면
|
||||
|
||||
| 화면 | 내용 |
|
||||
|---|---|
|
||||
| 대시보드 | 서비스 상태(디스코드, LLM, STT, TTS), GPU/VRAM/RAM 사용량, 현재 음성 채널과 참가자, 실시간 자막, 단계별 지연 시간, 게임 모드 상태, 놓친 요청, 봇 시작/정지 |
|
||||
| 봇 | 봇 토큰, 애플리케이션 ID, 봇 이름(닉네임), 아바타, 상태 메시지, 성격(시스템 프롬프트), 슬래시 명령 이름, 명령 응답 공개 범위 |
|
||||
| 채널·호출 | 서버·채널 선택, 자동 입장, 입장/퇴장 버튼, 최대 동시 화자 수(1~10), 호출어 목록, 호출 방식, 지정한 사람 목록과 "지정한 사람만 응답"·"호출어 없이 대답" 켜기/끄기, 동시 대화 응답 정책, 사람별 우선순위, 정지 명령, 입장 시 전사 고지 문구 |
|
||||
| 채팅 채널 | 채널 목록(ID·이름·설명) 추가·수정·삭제, 디스코드에도 반영 여부, 채널별 AI 권한, 채팅 호출 방식 |
|
||||
| 대화 기억 | 참고 범위, 최근 대화 원문 양, 과거 기록 가져올 개수, 참고 분량 상한, 등록한 채팅 채널 참고 켜기/끄기, 같은 음성 채널의 다른 사람 말 참고 켜기/끄기, 보관 기간 |
|
||||
| 모델 | LLM 프리셋(빠름/권장/사용자 지정) 다운로드·전환·삭제, STT 모델(turbo/medium/small), 말 끝 판정 시간, TTS 엔진·목소리·속도, 각 모델 테스트 버튼 |
|
||||
| 기능 | 메모리, 날씨, 웹 검색, 식단 기록, 브라우저 제어, PC 제어, 화면 보기, 백그라운드 수집 각각 켜기/끄기와 세부 설정. MCP 서버 추가·삭제·켜기/끄기 |
|
||||
| 게임 모드 | 게임 감지 켜기/끄기, 동작 (a) RAM 위주로 · (b) 빠름 모델로 · (c) 일시정지 각각 켜기/끄기, 게임용으로 비울 VRAM, 되돌리기 대기 시간, 게임 목록과 "게임 아님" 목록, 현재 감지 상태 |
|
||||
| PC 제어 | 실시간 화면 미리보기, GUI에서 키보드·마우스 조작, 허용 범위(보기만 / 브라우저만 / 전체), 비상 정지 단축키, 안티치트 감지 목록 보기·추가 |
|
||||
| 화면 보기 | 볼 수 있는 대상(전체 화면, 모니터별, 창별), 캡처 제외 프로그램 목록, 볼 수 있는 조건, 캡처 미리 준비(말하는 중에만/항상/끔), 기본 화질 단계, 화면공유 창 분리 대기 시간, "봇용 크롬창 화면공유 선택 표시" 켜기/끄기 |
|
||||
| 백그라운드 수집 | 수집 대상(사이트, 검색어, RSS), 주기, 보관 기간, 결과 보기. 기본 수집 대상은 비워 둠 |
|
||||
| 데이터 | 폴더별 사용량, 캐시 정리, 데이터 이동, 설정 내보내기/가져오기, 메모리 백업 |
|
||||
| 로그 | 실시간 로그 보기·검색·복사·다운로드 |
|
||||
| 업데이트 | 새 버전 확인과 설치 (Gitea 릴리스 기준) |
|
||||
|
||||
기능별 세부 동작은 [conversation.md](conversation.md), [memory.md](memory.md), [pc-features.md](pc-features.md)에 있습니다.
|
||||
|
||||
## 로그 화면
|
||||
|
||||
오류가 나면 로그를 바로 복사하거나 파일로 받아서 디스코드로 보낼 수 있게 만듭니다.
|
||||
|
||||
- **보기**:
|
||||
- 실시간으로 흘러가는 로그를 봅니다.
|
||||
- 서비스별 탭: 앱, 디스코드, 채팅 채널, STT, LLM, TTS, 브라우저, 화면 캡처, 게임 감지
|
||||
- 수준 필터(오류/경고/정보/디버그), 검색, 일시정지를 지원합니다.
|
||||
- **복사**:
|
||||
- 원하는 줄을 골라 복사합니다.
|
||||
- "최근 오류 복사" 버튼은 마지막 오류 앞뒤 로그와 앱 버전, PC 사양 요약을 한 번에 복사합니다.
|
||||
- 디스코드 메시지 길이(2,000자)를 넘으면 파일로 받으라고 안내합니다.
|
||||
- **다운로드**: 기간을 골라 zip으로 저장합니다. 디스코드 첨부 한도(10MB) 안에 들어가게 압축합니다.
|
||||
- **오류 알림**: 오류가 나면 대시보드에 알림이 뜨고, 알림에서 바로 "로그 복사"를 누를 수 있습니다.
|
||||
- **비밀값 보호**: 복사·다운로드할 때 봇 토큰 같은 비밀값은 자동으로 지웁니다. 대화 내용을 가릴지는 내보낼 때 고릅니다(기본: 가림).
|
||||
- **디버그 로그**: 평소에는 꺼 두고, 문제를 재현할 때만 켭니다.
|
||||
32
docs/v2/memory.md
Normal file
32
docs/v2/memory.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# 이전 대화 참고 (대화 기억)
|
||||
|
||||
v1 코드는 최근 5분 대화 원문과, 과거 기록(일기 요약, 메모리 그래프)에서 관련 내용 3개만 가져옵니다(`src/jarvis/config.py`: `dialogue_memory_timeout=300`, `memory_enrichment_max_results=3`).
|
||||
|
||||
v2에서는 다음 두 가지를 **전부** 대화 기록 저장소(SQLite)에 남깁니다. 답할 때마다 지난 기록 전체에서 관련된 부분을 찾아 넣습니다.
|
||||
|
||||
- 음성 전사
|
||||
- 등록한 채팅 채널([conversation.md](conversation.md#ai-채팅-채널))의 메시지
|
||||
|
||||
## "전부 참고"의 실제 방식
|
||||
|
||||
몇 달 치 대화를 통째로 LLM에 넣지 않습니다. 모델이 한 번에 읽을 수 있는 양을 넘고, 넣는 양이 많을수록 첫 소리도 늦어지기 때문입니다.
|
||||
|
||||
그래서 전체 기록은 **검색 대상**으로 두고, 이번 질문과 관련된 부분과 최근 대화 원문만 골라 넣습니다. 오래된 대화는 요약본으로, 최근 대화는 원문으로 들어갑니다.
|
||||
|
||||
## GUI 설정
|
||||
|
||||
| 설정 | 기본값 | 설명 |
|
||||
|---|---|---|
|
||||
| 참고 범위 | 전체 기간 | 끔 / 최근 N일 / 전체 기간 |
|
||||
| 최근 대화 원문 | 최근 30분 또는 20턴 | 요약하지 않고 그대로 넣는 최근 대화의 양 |
|
||||
| 과거 기록에서 가져올 개수 | 5개 | 1~20개. 관련도가 높은 순서로 가져옴 |
|
||||
| 참고 분량 상한 | 약 4,000토큰 | 참고 내용 전체의 최대 길이. 화면에 "예상 추가 지연"을 같이 보여 줌 |
|
||||
| 등록한 채팅 채널 참고 | **켜짐** | 켜짐 / 꺼짐 |
|
||||
| 같은 음성 채널의 다른 사람 말 참고 | **켜짐** | 켜짐 / 꺼짐. 끄면 본인 기록(과 채팅 채널)만 참고 |
|
||||
| 기록 보관 기간 | 무기한 | 기간이 지나면 자동 삭제. 데이터 화면에서 사람별 기록 보기·삭제 |
|
||||
|
||||
- **본인 기록**: 그 사람이 음성·채팅으로 한 말과, 그에 대한 봇의 답입니다. 항상 참고합니다.
|
||||
- **같은 음성 채널의 다른 사람 말**: 질문한 사람이 같은 음성 채널에 함께 있던 동안 다른 사람이 한 말과, 그에 대한 봇의 답입니다. 질문한 사람이 없던 때의 대화는 넣지 않습니다.
|
||||
- **채팅 채널**: 등록한 채널의 메시지 전체입니다. 다른 사람이 쓴 글도 포함합니다.
|
||||
|
||||
숫자 기본값은 M0에서 맥락 길이별 첫 토큰 시간을 재서 확정합니다.
|
||||
148
docs/v2/pc-features.md
Normal file
148
docs/v2/pc-features.md
Normal file
@@ -0,0 +1,148 @@
|
||||
# PC 기능: 게임 모드, 화면 보기, 키보드·마우스, 화면공유
|
||||
|
||||
디스코드 봇만으로는 할 수 없고, 게임PC에서 도는 exe라서 가능한 기능입니다.
|
||||
|
||||
## 게임 모드
|
||||
|
||||
게임을 켜면 VRAM을 두고 다툽니다. 앱이 게임 실행을 스스로 감지해서, GUI에서 켜 둔 동작만 자동으로 실행합니다.
|
||||
|
||||
### 게임 감지 기준
|
||||
|
||||
| 기준 | 내용 |
|
||||
|---|---|
|
||||
| 독점 전체화면 | Windows가 알려 주는 "전체화면 D3D 앱 실행 중" 상태로 감지합니다. |
|
||||
| 테두리 없는 창 모드 (borderless) | 앞에 있는 창이 아래 세 조건을 모두 만족하면 게임으로 봅니다. 셋 다 맞아야 하므로 일반 프로그램을 최대화한 것과 구분됩니다. (1) 모니터 한 장을 빈틈없이 덮습니다. (2) 제목 표시줄·테두리가 없습니다. (3) 그 프로세스가 GPU 3D 엔진을 일정 수준 이상 씁니다. |
|
||||
| 게임 폴더·목록 | Steam, Epic, Riot, Battle.net 게임 폴더에서 실행된 프로그램과 GUI에서 직접 등록한 게임은 창 모양과 상관없이 게임으로 봅니다. |
|
||||
| 게임이 아닌 것 | 브라우저 전체화면 영상, 동영상 플레이어, 바탕화면, 디스코드, 봇용 크롬은 제외합니다. 잘못 잡히는 프로그램은 "게임 아님" 목록에 넣습니다. |
|
||||
|
||||
한 번 게임으로 감지되면 게임 프로세스가 끝날 때까지 게임 모드를 유지합니다. Alt+Tab으로 다른 창을 봐도 마찬가지입니다. 게임이 뒤에 있어도 VRAM은 계속 쓰기 때문입니다. 대시보드에는 "게임 모드: 켜짐 (게임 이름, 감지 이유)"를 표시합니다.
|
||||
|
||||
### 게임 모드 동작 (각각 켜기/끄기)
|
||||
|
||||
| 동작 | 기본값 | 내용 |
|
||||
|---|---|---|
|
||||
| (a) LLM을 RAM 위주로 | **켜짐** | LLM이 쓰던 VRAM을 줄여 게임에 내줍니다. "게임용으로 비울 VRAM"(기본 8GB)을 GUI에서 정합니다. 답은 조금 느려집니다. |
|
||||
| (b) 빠름 모델로 바꾸기 | 꺼짐 | 권장 모델을 쓰던 중이면 빠름 모델로 바꿉니다. (a)와 같이 켜면 빠름 모델을 RAM 위주로 올립니다. |
|
||||
| (c) 봇 일시정지 | 꺼짐 | 게임 중에는 대답하지 않습니다. 켜면 (a)(b)는 의미가 없어서 GUI에서 흐리게 표시합니다. |
|
||||
| 게임 종료 후 되돌리기 | 30초 뒤 | 게임을 껐다 바로 다시 켤 때 모델을 반복해서 옮기지 않도록, 게임이 끝나고 정한 시간 뒤에 원래 상태로 돌립니다. |
|
||||
|
||||
(a)(b)는 LLM 서버를 다른 배치로 다시 띄우는 것이라 전환하는 몇 초~수십 초 동안은 대답이 늦어집니다. 전환 시간은 M0에서 재고, 전환 중에는 "모델 전환 중"을 대시보드에 표시합니다. 모든 판단은 PC 안에서만 하고 게임 화면은 보지 않습니다.
|
||||
|
||||
## 화면 보기: 전체 화면, 모니터별, 프로그램(창)별
|
||||
|
||||
- Windows Graphics Capture API로 다음을 볼 수 있습니다.
|
||||
- 전체 화면: 모니터 여러 대를 한 장으로 이어 붙인 화면
|
||||
- 모니터별 화면: 1번, 2번, 3번 모니터를 따로
|
||||
- 프로그램(창)별 화면: 켜져 있는 창 하나하나. 다른 창에 가려져 있어도 캡처됩니다.
|
||||
- 자비스에게는 "화면 보기" 도구로 연결합니다. "2번 모니터 뭐 떠 있어?", "크롬 창 내용 읽어 줘"처럼 물으면 해당 화면을 캡처해 이미지로 판단합니다.
|
||||
- GUI 미리보기에서도 같은 대상을 고를 수 있습니다.
|
||||
- **캡처 제외 목록**: 은행, 비밀번호 관리자처럼 봇이 보면 안 되는 프로그램을 지정합니다. 그 창은 캡처하지 않고, 전체 화면 캡처에서도 가립니다.
|
||||
- **안 보이는 경우**: 최소화된 창, 저작권 보호 영상(넷플릭스 등), 일부 게임의 독점 전체화면은 검게 나올 수 있습니다. 게임은 테두리 없는 창 모드면 대부분 보입니다. 캡처가 실패하면 자비스가 "그 화면은 볼 수 없다"고 그대로 말합니다.
|
||||
|
||||
## 화면 질문을 빠르게
|
||||
|
||||
"2번 화면에 뭐 떠 있어?"에서 시간이 드는 곳은 세 군데입니다. 셋 다 줄입니다.
|
||||
|
||||
1. 화면 캡처
|
||||
2. 이미지 줄이기·변환
|
||||
3. LLM이 이미지를 읽는 시간
|
||||
|
||||
| 방법 | 내용 |
|
||||
|---|---|
|
||||
| 캡처 미리 준비 | 캡처 세션은 새로 열 때 시간이 걸립니다. 그래서 누군가 말을 시작하면(음성 감지 시점) 모니터별 캡처 세션을 미리 열어 두고, 각 모니터의 **가장 최근 한 장만** GPU 메모리에 들고 있습니다. 질문이 끝났을 때는 이미 있는 한 장을 꺼내기만 하면 됩니다. 말이 끝나고 일정 시간 질문이 없으면 세션을 닫습니다. 설정: 말하는 중에만(기본) / 항상 / 끔. 미리 잡아 둔 화면은 메모리에만 있고 저장하거나 밖으로 보내지 않으며, 계속 새 화면으로 덮어씁니다. |
|
||||
| GPU에서 바로 줄이기 | 4K 원본을 CPU로 옮기지 않고 GPU에서 모델이 읽기 좋은 크기로 줄인 뒤 JPEG로 만듭니다. 캡처 제외 프로그램 가리기도 이 단계에서 같이 합니다. |
|
||||
| 화질 단계 | 빠름(긴 변 약 768px) / 보통(약 1280px, 기본) / 자세히(원본을 나눠서 여러 장). 이미지가 작을수록 LLM이 읽는 양이 줄어 빨라집니다. "글자 읽어 줘"처럼 세밀한 질문이면 AI가 스스로 "자세히"를 고릅니다. |
|
||||
| 도구 호출 한 번으로 | AI가 "화면 보기" 도구를 부르면 캡처 이미지를 바로 같은 대화에 붙여 이어서 답합니다. LLM 엔진이 지원하면 고정된 앞부분(시스템 프롬프트 등)은 다시 계산하지 않게 캐시합니다. |
|
||||
| 창 단위로 좁히기 | "크롬 창"처럼 창을 말하면 모니터 전체가 아니라 그 창만 캡처합니다. |
|
||||
| 답도 문장 단위로 | 이미지를 읽은 뒤 답의 첫 문장이 나오면 바로 읽기 시작합니다. |
|
||||
|
||||
| 단계 (질문이 끝난 뒤) | 목표 |
|
||||
|---|---|
|
||||
| 최근 화면 꺼내기 + 줄이기·JPEG | 50ms 이내 |
|
||||
| AI가 "화면 보기" 도구 고르기 | 100~250ms |
|
||||
| LLM이 이미지 읽기 (보통 화질) | 300~800ms |
|
||||
| 첫 문장 + TTS | 일반 질문과 같음 |
|
||||
| **합계** | **일반 질문보다 0.5~1초 더, 약 1.5~2.5초** |
|
||||
|
||||
**확인이 필요한 점**: 이미지를 읽으려면 LLM이 이미지 입력을 지원해야 합니다. M0에서 다음을 잽니다.
|
||||
|
||||
- 빠름/권장 모델의 이미지 입력 지원
|
||||
- Strata의 이미지 입력 지원
|
||||
- 화질 단계별 실제 시간
|
||||
|
||||
못 읽으면 작은 이미지 전용 모델을 하나 더 올리는 예비안을 쓰고, VRAM 배분을 다시 계산합니다. Windows 11에서는 캡처할 때 노란 테두리가 뜨지 않게 설정합니다.
|
||||
|
||||
## 키보드·마우스 제어와 안티치트
|
||||
|
||||
- 키보드·마우스는 Windows 입력 API로 넣습니다.
|
||||
- 자비스가 직접 조작할 때는 **허용 범위**와 **위험 동작 확인**을 거칩니다. 파일 삭제, 결제, 전송 등은 음성/GUI로 한 번 더 확인합니다.
|
||||
- **비상 정지 단축키**를 누르면 모든 자동 조작이 즉시 멈춥니다.
|
||||
|
||||
### 안티치트 게임 실행 중에는 제어를 막습니다
|
||||
|
||||
발로란트(Vanguard) 같은 커널 안티치트는 프로그램이 넣는 입력을 감지해 계정을 제재할 수 있습니다. 그래서 안티치트가 걸린 게임이 실행 중이면 키보드·마우스 조작 요청을 받아도 아무것도 입력하지 않습니다. 음성, 채팅, GUI 조작 모두 같습니다. 대신 이렇게 안내합니다.
|
||||
|
||||
> 뱅가드가 적용된 게임(VALORANT)이 실행 중이어서 키보드/마우스 제어를 할 수 없습니다.
|
||||
|
||||
- 안티치트 이름과 게임 이름은 실제로 감지한 것으로 바뀝니다.
|
||||
- 음성으로 시켰으면 음성으로, 채팅으로 시켰으면 채팅으로 답하고, GUI에도 표시합니다.
|
||||
- 게임을 끄면 다시 제어할 수 있습니다.
|
||||
- 화면 보기는 화면을 읽기만 하므로 그대로 됩니다.
|
||||
|
||||
| 안티치트 (기본 목록) | 감지 방법 |
|
||||
|---|---|
|
||||
| 뱅가드 (Vanguard) | 뱅가드 드라이버는 PC를 켤 때부터 항상 올라와 있습니다. 그래서 드라이버가 아니라 **Riot 게임 프로세스**(VALORANT, 리그 오브 레전드)가 실행 중인지로 판단합니다. |
|
||||
| Easy Anti-Cheat, BattlEye, FACEIT AC, nProtect GameGuard, XIGNCODE3 등 | 게임과 함께 실행되는 안티치트 프로세스·서비스가 떠 있는지로 판단합니다. |
|
||||
| 목록에 없는 게임 | PC 제어 화면에서 "이 게임은 안티치트 있음"으로 직접 추가합니다. 감지를 끄는 우회 설정은 만들지 않습니다(계정 정지 위험). |
|
||||
|
||||
정확한 프로세스 이름 목록은 M0에서 게임PC에 설치된 게임으로 확인하고, 앱 업데이트로 늘려 갑니다.
|
||||
|
||||
## 봇용 크롬창과 디스코드 화면공유
|
||||
|
||||
셀프봇 Go Live 송출은 v2에서 뺍니다. 대신 봇이 쓰는 크롬창을 사용자가 디스코드 앱에서 직접 화면공유할 수 있게 합니다.
|
||||
|
||||
- **GUI 설정 "봇용 크롬창 화면공유 선택 표시"**:
|
||||
- 켜짐: 봇용 크롬창이 디스코드 "화면 공유 → 창" 목록에 "Jarvis 브라우저"로 나타납니다.
|
||||
- 꺼짐(기본): 봇용 크롬창은 화면 없이(백그라운드) 돌고, 디스코드 목록에도 나오지 않습니다.
|
||||
- **Alt+Tab, Win+Tab, 작업 표시줄에는 항상 안 보입니다.** 켜짐 상태에서도 창을 "도구 창" 속성으로 바꿔 창 전환 목록에서 빼고, 다른 창들 뒤(맨 아래)에 둡니다.
|
||||
- 크롬은 가려진 창의 그리기를 멈추는 기능이 있습니다. 봇용 크롬은 이 기능을 끄고 실행해서, 다른 창 뒤에 있어도 화면공유 영상이 멈추지 않게 합니다.
|
||||
|
||||
**먼저 확인할 점**: 디스코드가 화면공유 목록을 Alt+Tab과 같은 기준으로 거르면, 도구 창 속성 때문에 목록에서도 빠질 수 있습니다. M0 확인 스크립트에서 가장 먼저 봅니다.
|
||||
|
||||
**안 될 때 예비안**: 가상 모니터를 하나 만들고 봇용 크롬을 그 모니터에 둡니다.
|
||||
|
||||
- 가상 디스플레이 드라이버를 씁니다. 설치 때 관리자 권한을 한 번 묻습니다(설치 승인받음).
|
||||
- 디스코드에서는 "화면" 탭에서 그 가상 모니터를 고릅니다.
|
||||
- Alt+Tab에서는 그대로 빠지고, 실제 모니터에도 보이지 않습니다.
|
||||
|
||||
## 다른 사람의 디스코드 화면공유 보기 (창 분리 방식)
|
||||
|
||||
**쓰지 않는 방법**: discord.exe의 앱 데이터에서 로그인 토큰을 꺼내 쓰는 방식은 하지 않습니다.
|
||||
|
||||
- 디스코드 약관 위반이라 계정이 정지될 수 있습니다.
|
||||
- 백신이 토큰 탈취 악성코드로 탐지하는 동작과 같습니다.
|
||||
- 토큰이 새면 계정 전체가 넘어갑니다.
|
||||
|
||||
공식 봇 계정은 원래 화면공유 영상을 받을 수 없습니다.
|
||||
|
||||
**쓰는 방법**: 화면공유 창을 분리(팝아웃)해서 그 창만 캡처합니다.
|
||||
|
||||
디스코드 앱에는 시청 중인 화면공유를 별도 창으로 떼어 내는 "팝아웃" 기능이 있습니다. 분리된 창에는 채팅·멤버 목록이 섞이지 않고 공유 화면만 담겨 있습니다. 그래서 그 창만 캡처하면 이미지가 작고 깨끗해서 빠르고 정확합니다. 계정이나 토큰은 건드리지 않습니다.
|
||||
|
||||
1. "철수 화면 뭐 하고 있어?"라고 물으면 앱이 분리된 화면공유 창이 있는지 찾습니다.
|
||||
2. 없으면 자비스가 "디스코드에서 철수님 화면공유를 창 분리(팝아웃)해 주세요."라고 말하고 기다립니다(기본 30초). 아직 시청 중이 아니면 먼저 시청을 눌러 달라고 안내합니다. 자비스가 디스코드 앱을 직접 눌러 창을 분리하지는 않습니다. 디스코드 화면 배치가 바뀌면 자동 조작이 깨지기 쉽기 때문입니다.
|
||||
3. 분리된 창이 나타나면 그 창만 캡처해서 답합니다. 한 번 분리해 두면 이후 질문은 기다리지 않고 바로 답합니다.
|
||||
4. 분리된 창이 여러 개면 창 제목(공유한 사람 이름)으로 고릅니다. 이름으로 구분이 안 되면 누구 화면인지 되묻습니다.
|
||||
|
||||
**M0에서 확인할 점**:
|
||||
|
||||
1. 분리된 화면공유 창을 프로그램에서 정확히 알아보는 방법. 창 제목에 공유자 이름이 들어가는지 봅니다.
|
||||
2. 분리된 창이 다른 창에 완전히 가려지면 디스코드가 영상 그리기를 멈추는지. 멈춘다면 분리된 창을 보조 모니터나 가상 모니터로 옮겨 둡니다.
|
||||
|
||||
최소화하면 캡처가 안 되므로 그때는 창을 다시 열어 달라고 안내합니다.
|
||||
|
||||
## 백그라운드 크로미움으로 정보 수집
|
||||
|
||||
- 봇용 크롬(데이터 폴더 안)을 Playwright로 조종합니다. 웹 검색, 페이지 읽기, 예약 수집에 씁니다.
|
||||
- 기존 webSearch 도구의 보안 장치를 그대로 가져갑니다. 내부망 접근을 막고, 웹 내용은 명령이 아닌 데이터로 다룹니다.
|
||||
- 예약 수집은 기능 틀(사이트·검색어·RSS를 주기적으로 모으는 기능)만 만들고 **수집 대상은 비워 둡니다**. 수집 결과는 데이터 폴더에만 저장합니다.
|
||||
14
docs/v2/privacy.md
Normal file
14
docs/v2/privacy.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# 개인정보·법적 안전장치
|
||||
|
||||
- 모든 처리는 게임PC 안에서만 합니다. 클라우드 API를 쓰지 않습니다. 밖으로 나가는 것은 웹 검색과 날씨 조회 요청뿐입니다.
|
||||
- 봇이 음성 채널에 들어가면 "대화가 전사됩니다" 고지 메시지를 보냅니다. 문구는 설정에서 수정합니다.
|
||||
- 봇이 참여한 음성 채널의 대화만 처리합니다. 봇이 없는 대화를 몰래 듣는 기능은 만들지 않습니다.
|
||||
- 채팅은 GUI에 등록한 채팅 채널만 읽고 저장합니다. 그 밖의 채널은 읽지 않습니다. 채팅에 올라온 글은 명령이 아니라 데이터로 다룹니다.
|
||||
- 음성 원본은 기본적으로 저장하지 않습니다. 디버그용 저장은 직접 켰을 때만 하고, 기간이 지나면 자동 삭제합니다.
|
||||
- 대화 기록(음성 전사, 채팅 채널 메시지)은 [memory.md](memory.md) 설정대로 저장하고, 사람별로 보고 지울 수 있습니다. 기본으로 참고하는 것은 말한 사람 본인의 기록, 등록한 채팅 채널, 그리고 그 사람과 같은 음성 채널에 함께 있던 동안 다른 사람이 한 말입니다. 다른 사람 말 참고는 GUI에서 끌 수 있습니다.
|
||||
- 화면 캡처는 자비스가 볼 때만 쓰고 기본적으로 저장하지 않습니다.
|
||||
- 빠른 응답을 위해 미리 잡아 두는 화면도 메모리에 최근 한 장만 두고 계속 덮어씁니다.
|
||||
- 캡처 제외 목록에 넣은 프로그램은 보지 않습니다.
|
||||
- 게임·안티치트 감지는 실행 중인 프로세스와 창 상태만 봅니다. 게임 화면이나 게임 파일은 읽지 않습니다.
|
||||
- 봇 토큰 같은 비밀값은 Windows DPAPI로 암호화해 저장하고, 로그를 복사·다운로드할 때 자동으로 지웁니다.
|
||||
- 워커들은 127.0.0.1에서만 엽니다. 앱이 실행할 때마다 새로 발급하는 토큰이 있어야 접속됩니다.
|
||||
60
docs/v2/roadmap.md
Normal file
60
docs/v2/roadmap.md
Normal file
@@ -0,0 +1,60 @@
|
||||
# 구현 단계와 위험 요소
|
||||
|
||||
## 구현 단계
|
||||
|
||||
| 단계 | 내용 | 완료 기준 |
|
||||
|---|---|---|
|
||||
| M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. |
|
||||
| M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과 |
|
||||
| M2 | 디스코드 음성 코어 이전 | v1 봇 코드를 Electron 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기) |
|
||||
| M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과 |
|
||||
| M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트 |
|
||||
| M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드) |
|
||||
| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬, 예약 수집 틀(대상은 비움) |
|
||||
| M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. |
|
||||
| M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 |
|
||||
|
||||
M0에서 확인할 항목:
|
||||
|
||||
- Strata에서 빠름/권장 모델의 실제 속도와 첫 토큰 시간(맥락 길이별)
|
||||
- 도구 호출·이미지 입력 가능 여부
|
||||
- 화질 단계별 이미지 읽기 시간
|
||||
- 한국어 품질
|
||||
- 게임 모드 전환 시간
|
||||
- faster-whisper turbo와 MeloTTS/CosyVoice2 속도
|
||||
- 봇용 크롬창의 Alt+Tab 숨김과 디스코드 화면공유 목록 표시
|
||||
- 디스코드 분리 화면공유 창 식별과, 가려졌을 때 영상이 멈추는지
|
||||
- 설치된 게임으로 테두리 없는 창 게임 감지와 안티치트 감지
|
||||
|
||||
M7 완료 기준:
|
||||
|
||||
- 전체·모니터별·창별 화면 보기
|
||||
- 빠른 화면 응답(캡처 미리 준비, 화질 단계)
|
||||
- 캡처 제외 목록
|
||||
- 분리된 화면공유 창 보기
|
||||
- 봇용 크롬창 화면공유 표시
|
||||
- 키보드·마우스 제어와 비상 정지
|
||||
- 안티치트 감지·차단 안내
|
||||
- 게임 감지(테두리 없는 창 포함)와 게임 모드 (a)(b)(c)
|
||||
|
||||
M0~M4는 "더 빠르고 똑똑한 음성 대화"의 핵심이고, M5~M8은 "설치 하나로 끝나는 관리 앱"입니다. 로그 화면은 M5에 넣어서 그 뒤 테스트할 때부터 바로 쓸 수 있게 합니다. M4까지 끝나면 GUI 없이도 새 엔진을 먼저 써 볼 수 있습니다.
|
||||
|
||||
## 위험 요소와 대응
|
||||
|
||||
| 위험 | 대응 |
|
||||
|---|---|
|
||||
| Strata가 도구 호출이나 동시 요청을 지원하지 않음 | 플래너(JSON) 방식으로 우회, 또는 같은 모델을 llama.cpp 서버로 실행 |
|
||||
| 게임과 VRAM 경쟁 | 게임 모드(RAM 위주/빠름 모델/일시정지 각각 켜기), VRAM 사용량 실시간 표시 |
|
||||
| 테두리 없는 창 게임을 놓치거나 일반 프로그램을 게임으로 잘못 봄 | 창 모양 + GPU 사용량 + 게임 폴더를 같이 보고, 게임 목록·"게임 아님" 목록으로 바로잡음. 감지 이유를 대시보드에 표시 |
|
||||
| 안티치트 목록에 없는 게임에서 자동 입력 | GUI에서 직접 추가, 앱 업데이트로 목록 확장. 독점 전체화면 게임 중에는 자동 입력 기본 차단 유지 |
|
||||
| LLM이 이미지 입력을 지원하지 않거나 이미지 읽기가 느림 | M0에서 측정. 화질 단계 낮추기, 창 단위 캡처, 이미지 전용 소형 모델 예비안 |
|
||||
| 분리된 화면공유 창이 가려지면 영상이 멈춤 | M0에서 확인. 보조 모니터나 가상 모니터로 옮겨 두기 |
|
||||
| Message Content Intent가 꺼져 있으면 채팅을 못 읽음 | 첫 실행 마법사와 대시보드에서 확인·안내 |
|
||||
| CUDA 13은 드라이버 580 이상 필요 | 첫 실행 점검에서 확인하고 안내. 안 되면 CUDA 12 빌드 사용 |
|
||||
| 서명 안 된 exe라 SmartScreen 경고 | 처음에는 "추가 정보 → 실행"으로 안내. 필요하면 코드 서명 인증서 구매 검토(유료) |
|
||||
| 디스코드 음성 암호화(DAVE) 변경 | v1에서 쓰는 `@snazzah/davey` 기반 유지, 라이브러리 업데이트 추적 |
|
||||
| 모델 다운로드가 수십 GB | 이어받기, 해시 검증, 진행률 표시. 빠름 모델 먼저 받고 권장 모델은 나중에 받기 가능 |
|
||||
| CosyVoice2 한국어 품질·속도 미검증 | M0에서 측정. 기준 미달이면 MeloTTS만 기본 제공 |
|
||||
| 디스코드 화면공유 목록이 Alt+Tab에서 숨긴 창도 빼 버림 | M0에서 확인. 안 되면 가상 모니터 예비안(드라이버 설치 승인받음) |
|
||||
| 지난 대화를 많이 넣을수록 첫 소리가 늦어짐 | 관련 부분만 검색해 넣고 분량 상한을 둠. GUI에 예상 지연 표시 |
|
||||
| 일부 화면이 검게 캡처됨 (보호 영상, 독점 전체화면 게임) | 테두리 없는 창 모드 안내. 캡처 실패 시 자비스가 "그 화면은 볼 수 없다"고 그대로 말함 |
|
||||
61
docs/v2/voice-and-llm.md
Normal file
61
docs/v2/voice-and-llm.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# 실시간 음성 파이프라인과 LLM
|
||||
|
||||
## 흐름
|
||||
|
||||
```
|
||||
사용자 발화 ─▶ 화자별 Opus 스트림 ─▶ DAVE 복호화 ─▶ 48kHz 스테레오 PCM
|
||||
─▶ 16kHz 모노 + 음량 정규화 ─▶ 화자별 Silero VAD
|
||||
─▶ (말하는 중) 0.3~0.5초마다 부분 전사 → GUI 실시간 자막
|
||||
─▶ (말 끝: 디스코드 speaking 종료 + VAD 무음 250~400ms) 최종 전사
|
||||
─▶ 호출 판정 (호출어/지정한 사람) ─▶ 응답 정책 ─▶ 응답 대기열
|
||||
─▶ Strata 스트리밍 응답 ─▶ 문장이 하나 완성될 때마다 TTS ─▶ 바로 재생
|
||||
─▶ 봇이 말하는 중 새 호출이 오면 응답 정책에 따라 계속 재생 또는 중단
|
||||
```
|
||||
|
||||
호출 판정과 응답 정책은 [conversation.md](conversation.md)에 있습니다.
|
||||
|
||||
## STT
|
||||
|
||||
- **모델 상주**: large-v3-turbo를 앱 시작 때 한 번 올리고 계속 유지합니다.
|
||||
- **스트리밍 전사**: 말하는 동안 조각을 계속 전사해서, 말이 끝났을 때는 마지막 조각만 처리합니다.
|
||||
- **종료 판정 단축**: 고정 0.8초 침묵 대기 대신 디스코드 speaking 종료 이벤트와 VAD를 같이 써서 250~400ms 안에 확정합니다(설정에서 조절).
|
||||
- **2단 디코딩**: 부분 전사는 beam 1(빠름), 최종 전사는 beam 2~3(정확도)입니다.
|
||||
- **호출어 힌트**: 등록한 호출어를 STT에 힌트로 넘겨 잘못 알아듣는 일을 줄입니다.
|
||||
- **RealtimeSTT 사용 범위**: RealtimeSTT는 화자 하나에 인스턴스 하나 구조라 10명이면 모델을 10번 올립니다. 그래서 설계(부분/최종 전사, VAD 결합)만 참고하고, **모델 1개를 10명이 공유하는 배치 방식**으로 직접 구현합니다.
|
||||
- **선택지**: 더 낮은 지연이 필요하면 sherpa-onnx 스트리밍 모델을 "초고속" 옵션으로 검토합니다(한국어 정확도 확인 후).
|
||||
|
||||
## TTS
|
||||
|
||||
- Piper는 공식 한국어 음성이 없습니다(비공식 KSS 모델만 있음). 그래서 기본값은 v1에서 쓰고 있고 한국어가 검증된 **MeloTTS**입니다.
|
||||
- 고품질 옵션으로 CosyVoice2(한국어 지원, 목소리 복제 가능)를 넣고, M0에서 속도와 품질을 비교해 기본값을 정합니다.
|
||||
- LLM 답변을 문장 단위로 끊어 첫 문장부터 바로 읽습니다.
|
||||
|
||||
## 목표 지연 시간 (말이 끝난 뒤 첫 소리까지)
|
||||
|
||||
| 단계 | v1 (추정) | v2 목표 |
|
||||
|---|---|---|
|
||||
| 말 끝 판정 | 800ms | 250~400ms |
|
||||
| 최종 전사 | 500~1500ms (통째 전사) | 100~250ms (남은 조각만) |
|
||||
| LLM 첫 문장 | 모델 크기에 따라 다름 | 300~700ms |
|
||||
| TTS 첫 문장 | 문장 전체 생성 후 | 150~300ms |
|
||||
| **합계** | **2~4초** | **약 1~1.5초** |
|
||||
|
||||
수치는 목표치입니다. M0에서 게임PC 실측으로 확정하고, 대시보드에 단계별 실측 지연을 표시합니다. 화면 질문의 지연 목표는 [pc-features.md](pc-features.md#화면-질문을-빠르게)에 따로 있습니다.
|
||||
|
||||
## LLM: Strata와 모델
|
||||
|
||||
| 앱 표시 | 모델 | 크기 / RAM | 속도(공개 수치) | 용도 |
|
||||
|---|---|---|---|---|
|
||||
| **빠름** | Qwen3.6-35B-A3B (UD-Q4_K_XL) | 파일 약 23GB / RAM 32GB~ | 약 118 tok/s (R9700 기준) | 반응 속도 최우선. 게임 중에도 쓰기 좋음 |
|
||||
| **권장** | Qwen3.8-Flash-Next (Q2_0~IQ3_S) | 파일 66~76GB / RAM 44~60GB | 약 94 tok/s (RTX 5070, 짧은 대화) | 더 똑똑하고 한중일 다국어 지원 |
|
||||
| 실험 (텍스트 전용) | DeepSeek V4.1-Flash | 파일 239~274GB | 약 5 tok/s | RAM 128GB를 넘어 디스크에서 읽으므로 음성용으로는 느림. 기본 목록에서 뺌 |
|
||||
| 사용자 지정 | GGUF 직접 선택 또는 외부 OpenAI 호환 주소 | - | - | 고급 사용자용 |
|
||||
|
||||
속도는 Strata 공식 문서의 다른 GPU 기준 수치입니다. 5070 Ti + 128GB 실측은 M0에서 다시 잽니다. 30 tok/s 이상이면 실시간으로 느껴집니다.
|
||||
|
||||
**확인이 필요한 위험**: Strata 문서에 도구 호출(tool calling) 지원, 동시 요청 처리, 이미지 입력 지원이 명시돼 있지 않습니다. M0에서 먼저 확인하고, 안 되면 다음 중 하나로 갑니다.
|
||||
|
||||
1. 기존 jarvis의 플래너 방식(JSON 출력으로 도구 선택)으로 우회합니다.
|
||||
2. 같은 GGUF를 llama.cpp 서버로 돌립니다.
|
||||
|
||||
참고: Strata https://github.com/Niko1221/Strata (docs/MODELS.md, docs/INSTALL.md), RealtimeSTT https://github.com/KoljaB/RealtimeSTT, Piper 한국어 미지원 https://github.com/rhasspy/piper/discussions/680
|
||||
@@ -85,6 +85,12 @@ class Settings:
|
||||
llm_digest_timeout_sec: float
|
||||
llm_embedding_timeout_sec: float
|
||||
llm_profile_select_timeout_sec: float
|
||||
# Upper bound on tokens the chat model may generate per reply turn. Spoken
|
||||
# (TTS) answers are 1-2 sentences, so a cap bounds the worst-case latency of
|
||||
# a model that occasionally rambles or loops without changing normal answers.
|
||||
# The headroom (default 512) sits well above this app's short tool-call JSON,
|
||||
# so capping never truncates a tool call. 0 (or negative) disables the cap.
|
||||
ollama_num_predict: int
|
||||
|
||||
# Profiles & Behavior
|
||||
active_profiles: list[str]
|
||||
@@ -394,6 +400,9 @@ def get_default_config() -> Dict[str, Any]:
|
||||
"llm_digest_timeout_sec": 8.0,
|
||||
"llm_embedding_timeout_sec": 60.0,
|
||||
"llm_profile_select_timeout_sec": 30.0,
|
||||
# Cap on chat-model output tokens per turn (worst-case latency guard).
|
||||
# 512 is safe headroom above short TTS answers and tool-call JSON; 0 off.
|
||||
"ollama_num_predict": 512,
|
||||
|
||||
# Profiles & Behavior
|
||||
"active_profiles": ["developer", "business", "life"],
|
||||
@@ -608,7 +617,11 @@ def load_settings() -> Settings:
|
||||
active_profiles = _ensure_list(merged.get("active_profiles"))
|
||||
tts_enabled = bool(merged.get("tts_enabled", True))
|
||||
tts_engine = str(merged.get("tts_engine", "piper")).lower()
|
||||
if tts_engine not in ("piper", "chatterbox"):
|
||||
# "edge" (Microsoft Edge TTS) is the containerized bridge's Korean voice;
|
||||
# "melo" is the legacy warm-worker voice. Both are multilingual, so they must
|
||||
# be preserved here — coercing them to "piper" would mislabel the engine as
|
||||
# English-only in reply_language_directive().
|
||||
if tts_engine not in ("piper", "chatterbox", "edge", "melo"):
|
||||
tts_engine = "piper" # Default to piper if invalid value
|
||||
tts_voice_val = merged.get("tts_voice")
|
||||
tts_voice = None if tts_voice_val in (None, "", "null") else str(tts_voice_val)
|
||||
@@ -759,6 +772,10 @@ def load_settings() -> Settings:
|
||||
llm_digest_timeout_sec = float(merged.get("llm_digest_timeout_sec", 8.0))
|
||||
llm_embedding_timeout_sec = float(merged.get("llm_embedding_timeout_sec", 60.0))
|
||||
llm_profile_select_timeout_sec = float(merged.get("llm_profile_select_timeout_sec", 30.0))
|
||||
try:
|
||||
ollama_num_predict = int(merged.get("ollama_num_predict", 512))
|
||||
except (TypeError, ValueError):
|
||||
ollama_num_predict = 512
|
||||
|
||||
return Settings(
|
||||
# Database & Storage
|
||||
@@ -774,6 +791,7 @@ def load_settings() -> Settings:
|
||||
llm_digest_timeout_sec=llm_digest_timeout_sec,
|
||||
llm_embedding_timeout_sec=llm_embedding_timeout_sec,
|
||||
llm_profile_select_timeout_sec=llm_profile_select_timeout_sec,
|
||||
ollama_num_predict=ollama_num_predict,
|
||||
|
||||
# Profiles & Behavior
|
||||
active_profiles=active_profiles,
|
||||
|
||||
@@ -2233,6 +2233,16 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
has_tool_calls = " (has tool_calls)" if msg.get("tool_calls") else ""
|
||||
debug_log(f" [{i}] {role}: {content}{has_tool_calls}", "planning")
|
||||
|
||||
# Bound worst-case generation latency: spoken answers are 1-2 sentences,
|
||||
# so cap the chat model's output tokens. The default headroom sits well
|
||||
# above this app's tool-call JSON, so capping never truncates a tool
|
||||
# call. 0/negative disables it. See config.ollama_num_predict.
|
||||
try:
|
||||
_num_predict = int(getattr(cfg, 'ollama_num_predict', 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
_num_predict = 0
|
||||
_chat_extra_options = {"num_predict": _num_predict} if _num_predict > 0 else None
|
||||
|
||||
# Send messages to Ollama — try native tool calling first, fall back to text-based
|
||||
# if the model returns HTTP 400 (native tools API not supported).
|
||||
_dump_tools_schema = None if use_text_tools else tools_json_schema
|
||||
@@ -2242,7 +2252,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
chat_model=cfg.ollama_chat_model,
|
||||
messages=messages,
|
||||
timeout_sec=float(getattr(cfg, 'llm_chat_timeout_sec', 45.0)),
|
||||
extra_options=None,
|
||||
extra_options=_chat_extra_options,
|
||||
tools=_dump_tools_schema,
|
||||
thinking=getattr(cfg, 'llm_thinking_enabled', False),
|
||||
)
|
||||
@@ -2273,7 +2283,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
|
||||
chat_model=cfg.ollama_chat_model,
|
||||
messages=messages,
|
||||
timeout_sec=float(getattr(cfg, 'llm_chat_timeout_sec', 45.0)),
|
||||
extra_options=None,
|
||||
extra_options=_chat_extra_options,
|
||||
tools=None,
|
||||
thinking=getattr(cfg, 'llm_thinking_enabled', False),
|
||||
)
|
||||
|
||||
@@ -22,11 +22,15 @@ class ModelSize(Enum):
|
||||
LARGE = "large" # 8b+ - can infer tool usage from context
|
||||
|
||||
|
||||
# Model size patterns - models matching these are considered SMALL
|
||||
# Model size patterns - models matching these are considered SMALL.
|
||||
# Covers every sub-8B size (1b-7b): these models need the explicit, repeated
|
||||
# tool/greeting/instruction constraints and falter on the terse LARGE prompt.
|
||||
# Without 2b/4b/5b/6b here a genuinely small model (e.g. qwen*:4b) was
|
||||
# misclassified as LARGE and given the less-guided prompt set.
|
||||
_SMALL_MODEL_PATTERNS = (
|
||||
":1b", ":3b", ":7b",
|
||||
"-1b", "-3b", "-7b",
|
||||
"_1b", "_3b", "_7b",
|
||||
":1b", ":2b", ":3b", ":4b", ":5b", ":6b", ":7b",
|
||||
"-1b", "-2b", "-3b", "-4b", "-5b", "-6b", "-7b",
|
||||
"_1b", "_2b", "_3b", "_4b", "_5b", "_6b", "_7b",
|
||||
"gemma4", # Gemma 4 - always small regardless of tag
|
||||
)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ This module provides model-size-aware prompt generation for the reply engine.
|
||||
|
||||
### Problem Statement
|
||||
|
||||
Small models (1b, 3b, 7b parameters) lack the reasoning capacity to infer when NOT to use tools. When given prompts like "Proactively use available tools," they may incorrectly call tools for simple greetings like "hello" or "ni hao" because they cannot distinguish between:
|
||||
Small models (every sub-8B size, 1b-7b parameters) lack the reasoning capacity to infer when NOT to use tools. When given prompts like "Proactively use available tools," they may incorrectly call tools for simple greetings like "hello" or "ni hao" because they cannot distinguish between:
|
||||
- Requests that require tools (weather, search, data retrieval)
|
||||
- Simple conversation (greetings, small talk, general knowledge)
|
||||
|
||||
@@ -14,7 +14,7 @@ The module detects model size from the model name and selects appropriate prompt
|
||||
|
||||
| Model Size | Detection Pattern | Tool Prompts |
|
||||
|------------|-------------------|--------------|
|
||||
| SMALL | `:1b`, `:3b`, `:7b`, `gemma4` | Conservative — explicit "DO NOT use tools for greetings" + worked negative examples + repetition |
|
||||
| SMALL | `:1b`-`:7b` (every size 1-7B, all separators), `gemma4` | Conservative — explicit "DO NOT use tools for greetings" + worked negative examples + repetition |
|
||||
| LARGE | All others (8b+) | Proactive — "use tools confidently" + short anti-confabulation + auto-derive clause |
|
||||
|
||||
### Architecture
|
||||
@@ -43,7 +43,7 @@ from jarvis.reply.prompts import (
|
||||
Both model sizes share these base components:
|
||||
- `asr_note`: Voice transcription error handling
|
||||
- `inference_guidance`: Prefer inference over clarification
|
||||
- `voice_style`: Concise, conversational responses
|
||||
- `voice_style`: Single-sentence, conversational responses (spoken aloud, so one sentence only — never more)
|
||||
|
||||
Model-size-specific components:
|
||||
- `tool_incentives`: When/how aggressively to use tools
|
||||
|
||||
@@ -26,8 +26,8 @@ INFERENCE_GUIDANCE = (
|
||||
# Voice assistant communication style - concise, conversational
|
||||
VOICE_STYLE = (
|
||||
"Keep responses concise and conversational since this is a voice assistant. "
|
||||
"Two to three sentences maximum. Prioritize clarity and brevity - users are listening, not reading. "
|
||||
"Avoid unnecessary elaboration unless specifically requested. "
|
||||
"Reply in a SINGLE sentence - never more than one sentence. Prioritize clarity and brevity - users are listening, not reading. "
|
||||
"Avoid unnecessary elaboration. "
|
||||
"Do NOT offer follow-up suggestions or ask if the user wants more info - just respond directly. "
|
||||
"IMPORTANT: Always respond in natural language - never output JSON, code, or structured data as your response. "
|
||||
"NEVER use markdown formatting in your replies: no asterisks for emphasis (**bold**, *italic*), "
|
||||
|
||||
@@ -287,6 +287,8 @@ Turn 4: LLM → {content: "Here's a comprehensive comparison of the iPhone 15 mo
|
||||
- `llm_tools_timeout_sec` (enrichment extraction)
|
||||
- `llm_embed_timeout_sec` (vector search)
|
||||
- `llm_chat_timeout_sec` (messages loop turn)
|
||||
- Output bound:
|
||||
- `ollama_num_predict` (default `512`, `0`/negative disables) caps the chat model's generated tokens per turn via the Ollama `num_predict` option on the messages-loop call. Spoken (TTS) answers are 1-2 sentences, so this never clips a normal answer; it bounds the worst-case latency of a model that occasionally rambles or loops. The default headroom sits well above this app's short tool-call JSON, so it does not truncate tool calls. Applied uniformly to the reply loop's chat call (both native-tools and text-tools paths); the small classification passes (intent judge, digests) keep their own caps. Note: this is a worst-case guard, not the primary latency lever, which is model size and GPU residency.
|
||||
- Memory enrichment:
|
||||
- `memory_enrichment_max_results` limits recalled snippets.
|
||||
- `memory_digest_enabled` (default `null` = auto-on for SMALL models ≤7B, off for LARGE) distils the combined diary + graph dump into a short relevance-filtered note via a cheap LLM pass before injecting into the system prompt. See **Memory Digest for Small Models** below.
|
||||
|
||||
@@ -62,10 +62,11 @@ _SYSTEM_PROMPT_TEMPLATE: str = (
|
||||
"Tone rails (hard): never mean, never condescending, never passive-aggressive, never "
|
||||
"sulking, never preachy, never sycophantic ('great question', 'I'd be happy to'). "
|
||||
"Sarcasm points at the situation, the topic, or mildly at yourself — never at the user. "
|
||||
"Shape for casual, factual, or small-talk replies: state the answer in a sentence, then add "
|
||||
"one short dry observation about it (an understated aside, a raised-eyebrow remark, a gentle "
|
||||
"noticing of the irony). One aside — not two, not a joke opener, not a joke-shaped sentence "
|
||||
"replacing the answer. The aside is a tail, not the head. "
|
||||
"Shape for casual, factual, or small-talk replies: give the answer in a SINGLE sentence. If a "
|
||||
"dry aside fits, fold it into that same sentence as a short trailing clause — never add it as "
|
||||
"a second sentence, never a joke opener, never a joke-shaped sentence replacing the answer. "
|
||||
"Whenever the wit would require a second sentence, drop the wit and keep the one-sentence "
|
||||
"answer. The aside is a tail inside the sentence, not a head and not a new sentence. "
|
||||
"Examples of the MOVE (shape, not wording — never copy these): stating a fact and then noting "
|
||||
"its mild absurdity; giving the weather and then commenting on what it implies for the day; "
|
||||
"answering a trivia question and then offering a wry footnote about the subject; admitting "
|
||||
@@ -79,8 +80,8 @@ _SYSTEM_PROMPT_TEMPLATE: str = (
|
||||
"butler clichés, and never address the user as 'sir', 'madam', 'my liege', or similar. "
|
||||
"Never stack multiple jokes in one reply. "
|
||||
"Be concise, conversational, and actionable. "
|
||||
"This is a spoken voice assistant: answer in ONE short sentence whenever possible "
|
||||
"(two at the very most). No lists, no preamble, no 'is there anything else' offers. "
|
||||
"This is a spoken voice assistant: your ENTIRE reply must be a single short sentence. "
|
||||
"Never write a second sentence. No lists, no preamble, no 'is there anything else' offers. "
|
||||
"When a controlBrowser tool is available, use IT (never webSearch) for anything that "
|
||||
"should happen in the on-screen browser — opening a site, searching on a site "
|
||||
"(controlBrowser action 'search' with the right site), clicking, typing — because only "
|
||||
@@ -119,10 +120,13 @@ _SYSTEM_PROMPT_TEMPLATE: str = (
|
||||
"'tell me a joke', 'chat with me'), never reply with a bare greeting like 'Hey there!', "
|
||||
"'Hi!', 'How can I help you?', or a generic observation about an unrelated topic. "
|
||||
"When the 'Information the user has shared…' section is present, you MUST pick one concrete "
|
||||
"fact from it and build the reply around that fact (e.g. 'You mentioned you box at Trenches "
|
||||
"Gym — how's training going this week?'). Do not talk about things that are not in that "
|
||||
"section. Only when that section is absent may you invent a fresh observation, question, or "
|
||||
"joke. Produce a varied response each time — do not repeat a previous reply verbatim. "
|
||||
"fact from it and build the reply around that fact, opening with a short natural reference to "
|
||||
"it. CRITICAL: use ONLY names, places, activities, and details that literally appear in that "
|
||||
"section — never borrow any name, place, or activity from these instructions or from any "
|
||||
"example wording, and never invent specifics that are not in that section. Do not talk about "
|
||||
"things that are not in that section. Only when that section is absent may you invent a fresh "
|
||||
"observation, question, or joke. Produce a varied response each time — do not repeat a "
|
||||
"previous reply verbatim. "
|
||||
"Banned phrasings: 'I can only tell you what you have shared with me in this conversation', "
|
||||
"'I don't have access to any personal information outside of what you tell me', 'I don't have "
|
||||
"personal details outside of our conversation history', 'I do not store personal details "
|
||||
|
||||
@@ -30,8 +30,10 @@ class BrowseAndPlayTool(Tool):
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"Play a song / music video / clip on the shared screen by searching YouTube "
|
||||
"and playing the first result. Use when the user asks you to play or watch "
|
||||
"something. Only available in screen-share mode."
|
||||
"and playing a result. Use when the user asks you to play or watch "
|
||||
"something. Plays the first result by default; pass 'index' to play the "
|
||||
"Nth result from the top of the search list (e.g. 'play the 3rd video' -> "
|
||||
"index=3). Only available in screen-share mode."
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -42,7 +44,16 @@ class BrowseAndPlayTool(Tool):
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "What to play, e.g. 'IU Good Day' or 'lofi hip hop'.",
|
||||
}
|
||||
},
|
||||
"index": {
|
||||
"type": "integer",
|
||||
"description": (
|
||||
"1-based position of the video to play in the search results, "
|
||||
"counted from the top of the list. Defaults to 1 (first result). "
|
||||
"Use for 'play the Nth video' / 'play the second one'."
|
||||
),
|
||||
"minimum": 1,
|
||||
},
|
||||
},
|
||||
"required": ["query"],
|
||||
}
|
||||
@@ -55,18 +66,25 @@ class BrowseAndPlayTool(Tool):
|
||||
reply_text="화면 공유 모드(STREAM_BROWSER=true)에서만 영상을 재생할 수 있습니다.",
|
||||
)
|
||||
query = ""
|
||||
index = 1
|
||||
if args and isinstance(args, dict):
|
||||
query = str(args.get("query", "")).strip()
|
||||
try:
|
||||
index = int(args.get("index", 1) or 1)
|
||||
except (TypeError, ValueError):
|
||||
index = 1
|
||||
if index < 1:
|
||||
index = 1
|
||||
if not query:
|
||||
return ToolExecutionResult(success=False, reply_text="재생할 내용을 알려주세요.")
|
||||
if not _NODE_SCRIPT.exists():
|
||||
return ToolExecutionResult(success=False, reply_text="브라우저 재생 도구를 찾을 수 없습니다.")
|
||||
|
||||
context.user_print(f"▶️ 화면에서 '{query}' 재생 중…")
|
||||
debug_log(f" ▶️ browseAndPlay '{query}'", "tools")
|
||||
context.user_print(f"▶️ 화면에서 '{query}' 재생 중… (#{index})")
|
||||
debug_log(f" ▶️ browseAndPlay '{query}' index={index}", "tools")
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["node", str(_NODE_SCRIPT), query, "youtube"],
|
||||
["node", str(_NODE_SCRIPT), query, "youtube", str(index)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=40,
|
||||
|
||||
@@ -6,16 +6,24 @@ video, or clip.
|
||||
|
||||
### Behaviour
|
||||
|
||||
- Public schema is a single required `query` string (what to play).
|
||||
- Public schema is a required `query` string (what to play) plus an optional
|
||||
`index` integer (1-based position in the search results, counted from the top
|
||||
of the list). `index` defaults to `1` (first result), so existing callers and
|
||||
"play X" requests are unchanged; "play the 3rd video" / "play the second one"
|
||||
map to `index=3` / `index=2`.
|
||||
- **Mode-gated**: only acts when `STREAM_BROWSER` is true (`cfg.stream_browser`).
|
||||
In voice-only mode (false) there is no screen to show, so it returns a short
|
||||
message and does nothing.
|
||||
- Drives the on-screen Chrome by subprocessing the Node CDP helper
|
||||
`bot/scripts/stream-test/browse-search.mjs <query> youtube`, which searches
|
||||
YouTube and plays the first result on display `:1`. The broadcast captures
|
||||
that display, so the playback is what viewers see.
|
||||
- Returns `success` with the played video's title, or a failure message if the
|
||||
helper/Chrome is unavailable. It does NOT make an LLM call.
|
||||
`bot/scripts/stream-test/browse-search.mjs <query> youtube <index>`, which
|
||||
searches YouTube and plays the chosen result on display `:1`. The broadcast
|
||||
captures that display, so the playback is what viewers see.
|
||||
- The helper clicks the `index`-th `a#video-title` in the results list. The
|
||||
index is clamped to the number of results actually returned, so asking for a
|
||||
position beyond the list plays the last available result rather than failing.
|
||||
- Returns `success` with the played video's title (and the resolved `index`), or
|
||||
a failure message if the helper/Chrome is unavailable. It does NOT make an LLM
|
||||
call.
|
||||
|
||||
### Principles
|
||||
|
||||
|
||||
@@ -45,9 +45,16 @@ class ControlBrowserTool(Tool):
|
||||
"Use this (NOT webSearch) whenever the user wants something done or shown IN the "
|
||||
"browser on screen: open a website or URL, search on a specific site (action "
|
||||
"'search' with site=naver/google/daum/youtube/bing), go back/forward, refresh, "
|
||||
"manage tabs (list/new/close/switch), close popups, click, type, scroll, or "
|
||||
"screenshot. webSearch only returns text and shows nothing on screen; this tool "
|
||||
"actually navigates the visible browser. Only available in screen-share mode. "
|
||||
"manage tabs (list/new/close/switch), close popups, move the mouse onto an element, "
|
||||
"click, type, scroll, or screenshot. webSearch only returns text and shows nothing "
|
||||
"on screen; this tool actually navigates the visible browser. "
|
||||
"Cursor behaviour matters: 'search' and 'type' (with a selector) move the REAL mouse "
|
||||
"cursor to the on-page box, click it, then type one character at a time — use these "
|
||||
"when the user wants to search or type on a page. 'navigate' only types the URL into "
|
||||
"the address bar (no mouse movement). 'moveMouse' moves/hovers the visible cursor "
|
||||
"onto an element (selector, or site=naver/... for that site's search box) WITHOUT "
|
||||
"clicking — use it when the user just asks to move the mouse somewhere. "
|
||||
"Only available in screen-share mode. "
|
||||
"Never claim you did any of this unless this tool returns success."
|
||||
)
|
||||
|
||||
@@ -61,16 +68,16 @@ class ControlBrowserTool(Tool):
|
||||
"enum": [
|
||||
"status", "listTabs", "navigate", "search", "back",
|
||||
"forward", "refresh", "newTab", "closeTab", "activateTab",
|
||||
"closePopups", "click", "type", "scroll", "pressKey",
|
||||
"closePopups", "moveMouse", "click", "type", "scroll", "pressKey",
|
||||
"screenshot",
|
||||
],
|
||||
"description": "What to do in the browser.",
|
||||
},
|
||||
"url": {"type": "string", "description": "Target URL/site for navigate/newTab (e.g. 'naver.com')."},
|
||||
"query": {"type": "string", "description": "Search text for action 'search'."},
|
||||
"site": {"type": "string", "description": "Search site for action 'search': naver, google, daum, youtube, bing."},
|
||||
"site": {"type": "string", "description": "Site for action 'search' or 'moveMouse': naver, google, daum, youtube, bing. For moveMouse it targets that site's search box."},
|
||||
"index": {"type": "integer", "description": "Tab index for closeTab/activateTab (from listTabs)."},
|
||||
"selector": {"type": "string", "description": "CSS selector for click/type."},
|
||||
"selector": {"type": "string", "description": "CSS selector for click/type/moveMouse."},
|
||||
"text": {"type": "string", "description": "Text to type."},
|
||||
"key": {"type": "string", "description": "Key to press, e.g. 'Return', 'Escape'."},
|
||||
"dir": {"type": "string", "description": "Scroll direction: 'down' or 'up'."},
|
||||
@@ -149,7 +156,12 @@ class ControlBrowserTool(Tool):
|
||||
if action == "navigate":
|
||||
return f"브라우저에서 {data.get('url', args.get('url'))} 로 이동했습니다."
|
||||
if action == "search":
|
||||
return f"{data.get('site', '')}에서 '{data.get('query', args.get('query'))}'를 검색해 화면에 띄웠습니다."
|
||||
base = f"{data.get('site', '')}에서 '{data.get('query', args.get('query'))}'를 검색해 화면에 띄웠습니다."
|
||||
# Flag when the real cursor path didn't run, so a silent fallback to
|
||||
# cursor-less DOM input is visible rather than reported as "human".
|
||||
if data.get("input") in ("api", "api-fallback"):
|
||||
base += " (참고: 실제 마우스 커서 이동 없이 처리됨)"
|
||||
return base
|
||||
if action in ("back", "forward", "refresh"):
|
||||
return f"브라우저: {action} 완료 ({data.get('url', '')})."
|
||||
if action in ("status", "listTabs"):
|
||||
@@ -164,6 +176,9 @@ class ControlBrowserTool(Tool):
|
||||
return f"탭 {data.get('active')}번으로 전환했습니다."
|
||||
if action == "closePopups":
|
||||
return f"팝업/빈 탭 {data.get('closed')}개를 닫았습니다."
|
||||
if action == "moveMouse":
|
||||
target = data.get("target") or args.get("selector") or args.get("site") or "대상"
|
||||
return f"마우스 커서를 {target} 위치로 옮겼습니다."
|
||||
if action == "screenshot":
|
||||
return f"화면을 캡처했습니다: {data.get('path')}"
|
||||
return "완료했습니다."
|
||||
|
||||
79
tests/test_browse_and_play_index.py
Normal file
79
tests/test_browse_and_play_index.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""Tests for browseAndPlay's ``index`` argument (play the Nth search result).
|
||||
|
||||
Behaviour verified:
|
||||
- default plays the first result (index 1) and stays backward-compatible,
|
||||
- an explicit index is forwarded to the Node helper as the 4th argv,
|
||||
- bad / sub-1 index values clamp to 1,
|
||||
- the index is advertised in the tool schema.
|
||||
"""
|
||||
|
||||
import json
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from src.jarvis.tools.builtin.browse_and_play import BrowseAndPlayTool, _NODE_SCRIPT
|
||||
|
||||
|
||||
def _ctx():
|
||||
cfg = Mock()
|
||||
cfg.stream_browser = True
|
||||
return Mock(cfg=cfg, user_print=Mock())
|
||||
|
||||
|
||||
def _run(args):
|
||||
tool = BrowseAndPlayTool()
|
||||
with patch("src.jarvis.tools.builtin.browse_and_play.subprocess.run") as mock_run:
|
||||
mock_run.return_value = Mock(
|
||||
stdout=json.dumps({"ok": True, "title": "Some Video"}),
|
||||
stderr="",
|
||||
)
|
||||
result = tool.run(args, _ctx())
|
||||
return mock_run, result
|
||||
|
||||
|
||||
def _argv(mock_run):
|
||||
return list(mock_run.call_args[0][0])
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_schema_exposes_index():
|
||||
schema = BrowseAndPlayTool().inputSchema
|
||||
assert "index" in schema["properties"]
|
||||
assert schema["properties"]["index"]["type"] == "integer"
|
||||
assert "query" in schema["required"]
|
||||
assert "index" not in schema["required"] # optional
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_default_index_is_first():
|
||||
mock_run, result = _run({"query": "IU Good Day"})
|
||||
argv = _argv(mock_run)
|
||||
assert argv[:4] == ["node", str(_NODE_SCRIPT), "IU Good Day", "youtube"]
|
||||
assert argv[4] == "1"
|
||||
assert result.success is True
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_explicit_index_forwarded():
|
||||
mock_run, _ = _run({"query": "lofi", "index": 3})
|
||||
assert _argv(mock_run)[4] == "3"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("bad", [0, -2, "nope", None])
|
||||
def test_bad_index_clamps_to_one(bad):
|
||||
mock_run, _ = _run({"query": "lofi", "index": bad})
|
||||
assert _argv(mock_run)[4] == "1"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_voice_only_mode_does_not_play():
|
||||
tool = BrowseAndPlayTool()
|
||||
cfg = Mock()
|
||||
cfg.stream_browser = False
|
||||
ctx = Mock(cfg=cfg, user_print=Mock())
|
||||
with patch("src.jarvis.tools.builtin.browse_and_play.subprocess.run") as mock_run:
|
||||
result = tool.run({"query": "x", "index": 2}, ctx)
|
||||
assert result.success is False
|
||||
mock_run.assert_not_called()
|
||||
56
tests/test_control_browser.py
Normal file
56
tests/test_control_browser.py
Normal file
@@ -0,0 +1,56 @@
|
||||
"""Tests for the controlBrowser tool's action surface.
|
||||
|
||||
These are deterministic schema/summary checks — they do not drive a real
|
||||
browser. The actual cursor movement is exercised live on the browser host
|
||||
(xdotool + CDP), which these tests cannot reach.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from jarvis.tools.builtin.control_browser import ControlBrowserTool
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tool():
|
||||
return ControlBrowserTool()
|
||||
|
||||
|
||||
def test_movemouse_is_an_exposed_action(tool):
|
||||
# A weak model confabulated "moved the mouse" because no move/hover action
|
||||
# existed to call. The cursor-move capability must be a real action so the
|
||||
# request "move the mouse to the search box" maps to a tool call.
|
||||
enum = tool.inputSchema["properties"]["action"]["enum"]
|
||||
assert "moveMouse" in enum
|
||||
|
||||
|
||||
def test_movemouse_summary_reports_the_target(tool):
|
||||
summary = tool._summarise("moveMouse", {"site": "naver"}, {"ok": True, "target": "naver"})
|
||||
assert "마우스" in summary and "naver" in summary
|
||||
|
||||
|
||||
def test_description_distinguishes_cursor_paths(tool):
|
||||
# The model must know navigate is address-bar only (no mouse) while
|
||||
# search/type/moveMouse move the real cursor — that distinction is the
|
||||
# whole point of the fix.
|
||||
desc = tool.description
|
||||
assert "moveMouse" in desc
|
||||
assert "address bar" in desc # navigate is described as address-bar typing
|
||||
|
||||
|
||||
def test_search_summary_flags_cursorless_fallback(tool):
|
||||
# When the real xdotool cursor path didn't run, the summary must say so
|
||||
# rather than implying a human-like search happened.
|
||||
human = tool._summarise("search", {"query": "날씨"}, {"ok": True, "site": "naver", "query": "날씨", "input": "human"})
|
||||
assert "참고: 실제 마우스" not in human
|
||||
|
||||
fell_back = tool._summarise("search", {"query": "날씨"}, {"ok": True, "site": "naver", "query": "날씨", "input": "api-fallback"})
|
||||
assert "실제 마우스 커서 이동 없이" in fell_back
|
||||
|
||||
|
||||
def test_movemouse_summary_only_runs_on_success(tool):
|
||||
# _summarise is only called on ok:true; an ok:false (target not found / no
|
||||
# xdotool) is handled by run() as a failure reply, so a failed move can no
|
||||
# longer be reported as "moved". Sanity-check the success summary names a
|
||||
# target rather than a placeholder when one is present.
|
||||
summary = tool._summarise("moveMouse", {"selector": "#query"}, {"ok": True, "target": "#query"})
|
||||
assert "#query" in summary
|
||||
62
tests/test_intent_model_split.py
Normal file
62
tests/test_intent_model_split.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""The docker deployment must run auxiliary calls on a small model.
|
||||
|
||||
Latency win: intent judging, tool routing and arg extraction are
|
||||
classification/JSON calls, not the spoken answer. Running them on a small fast
|
||||
model means the big chat model only runs once per command (for the answer),
|
||||
instead of 2-3 times per command for routing/extraction too.
|
||||
|
||||
The wiring is: docker/jarvis-config.template.json renders `intent_judge_model`
|
||||
from `${OLLAMA_INTENT_MODEL}`, and the reply engine's resolver falls through
|
||||
`tool_router_model -> intent_judge_model -> ollama_chat_model`. The template
|
||||
sets no `tool_router_model`, so the auxiliary model is whatever
|
||||
`OLLAMA_INTENT_MODEL` renders to. These tests pin that behaviour end to end.
|
||||
"""
|
||||
|
||||
import json
|
||||
import string
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from jarvis.reply.engine import resolve_tool_router_model
|
||||
|
||||
TEMPLATE = Path(__file__).resolve().parent.parent / "docker" / "jarvis-config.template.json"
|
||||
|
||||
|
||||
def _render(**env) -> dict:
|
||||
raw = TEMPLATE.read_text(encoding="utf-8")
|
||||
return json.loads(string.Template(raw).safe_substitute(**env))
|
||||
|
||||
|
||||
class _Cfg:
|
||||
"""cfg stand-in carrying only the fields the resolver reads. The template
|
||||
does not render `tool_router_model`, so it stays empty here too."""
|
||||
|
||||
def __init__(self, rendered: dict):
|
||||
self.tool_router_model = rendered.get("tool_router_model", "") or ""
|
||||
self.intent_judge_model = rendered.get("intent_judge_model", "") or ""
|
||||
self.ollama_chat_model = rendered.get("ollama_chat_model", "") or ""
|
||||
|
||||
|
||||
def test_template_renders_separate_intent_model():
|
||||
cfg = _render(OLLAMA_CHAT_MODEL="qwen3:8b", OLLAMA_INTENT_MODEL="qwen2.5:3b")
|
||||
assert cfg["ollama_chat_model"] == "qwen3:8b"
|
||||
assert cfg["intent_judge_model"] == "qwen2.5:3b"
|
||||
assert cfg["intent_judge_model"] != cfg["ollama_chat_model"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_aux_calls_route_to_small_model_not_chat_model():
|
||||
"""The whole point: with a big chat model and a small intent model, tool
|
||||
routing must resolve to the small model, leaving the big model for answers."""
|
||||
cfg = _Cfg(_render(OLLAMA_CHAT_MODEL="qwen3:8b", OLLAMA_INTENT_MODEL="qwen2.5:3b"))
|
||||
assert resolve_tool_router_model(cfg) == "qwen2.5:3b"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_folding_intent_onto_chat_model_keeps_one_model():
|
||||
"""Setting OLLAMA_INTENT_MODEL == OLLAMA_CHAT_MODEL folds everything back
|
||||
onto a single resident model (the documented VRAM-saving opt-out)."""
|
||||
cfg = _Cfg(_render(OLLAMA_CHAT_MODEL="qwen2.5:3b", OLLAMA_INTENT_MODEL="qwen2.5:3b"))
|
||||
assert resolve_tool_router_model(cfg) == "qwen2.5:3b"
|
||||
assert cfg.intent_judge_model == cfg.ollama_chat_model
|
||||
112
tests/test_ollama_num_predict.py
Normal file
112
tests/test_ollama_num_predict.py
Normal file
@@ -0,0 +1,112 @@
|
||||
"""Tests for the ``ollama_num_predict`` chat-output cap.
|
||||
|
||||
The cap bounds worst-case reply latency by limiting how many tokens the chat
|
||||
model may generate per turn. Spoken (TTS) answers are 1-2 sentences, so the
|
||||
default headroom never clips a normal answer and stays above tool-call JSON.
|
||||
|
||||
These tests verify behaviour:
|
||||
- the config default is present,
|
||||
- the value is threaded into the Ollama request as the ``num_predict`` option,
|
||||
- the reply loop forwards it to the chat call (and disables it at 0).
|
||||
"""
|
||||
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from src.jarvis.config import get_default_config
|
||||
from src.jarvis.memory.conversation import DialogueMemory
|
||||
from src.jarvis.reply.engine import run_reply_engine
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config default
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_default_config_has_num_predict_cap():
|
||||
config = get_default_config()
|
||||
assert config["ollama_num_predict"] == 512
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transport: extra_options.num_predict reaches the Ollama payload options
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@patch("jarvis.llm.requests.post")
|
||||
def test_chat_with_messages_forwards_num_predict(mock_post):
|
||||
from jarvis.llm import chat_with_messages
|
||||
|
||||
mock_resp = Mock()
|
||||
mock_resp.status_code = 200
|
||||
mock_resp.json.return_value = {"message": {"content": "ok"}}
|
||||
mock_resp.raise_for_status = Mock()
|
||||
mock_post.return_value = mock_resp
|
||||
|
||||
chat_with_messages(
|
||||
"http://localhost:11434",
|
||||
"test-large",
|
||||
[{"role": "user", "content": "hi"}],
|
||||
extra_options={"num_predict": 512},
|
||||
)
|
||||
_, kwargs = mock_post.call_args
|
||||
options = (kwargs.get("json") or {}).get("options") or {}
|
||||
assert options.get("num_predict") == 512
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reply loop wiring
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _mock_cfg(num_predict):
|
||||
cfg = Mock()
|
||||
cfg.ollama_base_url = "http://localhost:11434"
|
||||
cfg.ollama_chat_model = "test-large" # avoid SMALL-model text-tool path
|
||||
cfg.ollama_num_predict = num_predict
|
||||
cfg.voice_debug = False
|
||||
cfg.llm_tools_timeout_sec = 8.0
|
||||
cfg.llm_embed_timeout_sec = 10.0
|
||||
cfg.llm_chat_timeout_sec = 45.0
|
||||
cfg.llm_digest_timeout_sec = 8.0
|
||||
cfg.memory_enrichment_max_results = 5
|
||||
cfg.memory_enrichment_source = "diary"
|
||||
cfg.memory_digest_enabled = False
|
||||
cfg.tool_result_digest_enabled = False
|
||||
cfg.location_ip_address = None
|
||||
cfg.location_auto_detect = False
|
||||
cfg.location_enabled = False
|
||||
cfg.agentic_max_turns = 8
|
||||
cfg.tool_search_max_calls = 3
|
||||
cfg.tool_selection_strategy = "all"
|
||||
cfg.tool_carryover_max_turns = 2
|
||||
cfg.tool_carryover_per_entry_chars = 1200
|
||||
cfg.mcps = {}
|
||||
cfg.llm_thinking_enabled = False
|
||||
cfg.tts_engine = "none"
|
||||
cfg.ollama_embed_model = "test-embed"
|
||||
return cfg
|
||||
|
||||
|
||||
def _run_single_turn(cfg):
|
||||
"""Drive one reply turn that answers in plain text and capture the
|
||||
chat call's extra_options."""
|
||||
with patch("src.jarvis.reply.engine.plan_query", return_value=[]), \
|
||||
patch("src.jarvis.reply.engine.extract_search_params_for_memory", return_value={}), \
|
||||
patch("src.jarvis.reply.engine.extract_text_from_response", return_value="Hello."), \
|
||||
patch("src.jarvis.reply.engine.chat_with_messages") as mock_chat:
|
||||
mock_chat.return_value = {"message": {"content": "Hello."}}
|
||||
run_reply_engine(db=Mock(), cfg=cfg, tts=None,
|
||||
text="hi", dialogue_memory=DialogueMemory())
|
||||
assert mock_chat.called
|
||||
return mock_chat.call_args.kwargs.get("extra_options")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_reply_loop_caps_output_when_enabled():
|
||||
extra = _run_single_turn(_mock_cfg(512))
|
||||
assert extra == {"num_predict": 512}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_reply_loop_no_cap_when_zero():
|
||||
extra = _run_single_turn(_mock_cfg(0))
|
||||
assert extra is None
|
||||
@@ -21,9 +21,15 @@ class TestModelSizeDetection:
|
||||
("gemma:7b", True),
|
||||
("phi3:3b", True),
|
||||
("qwen2:7b", True),
|
||||
# Sub-8B sizes that were previously misclassified as LARGE.
|
||||
("qwen3.5:4b", True), # the deployed model that produced weak, off-tone replies
|
||||
("gemma2:2b", True),
|
||||
("model:5b", True),
|
||||
("model:6b", True),
|
||||
# Various separators
|
||||
("model-3b-instruct", True),
|
||||
("model_1b_chat", True),
|
||||
("model-4b-instruct", True),
|
||||
# Large models (should return LARGE)
|
||||
("gpt-oss:20b", False),
|
||||
("llama3.1:8b", False),
|
||||
@@ -121,6 +127,18 @@ class TestPromptComponents:
|
||||
assert prompts.voice_style, f"{size.value} missing voice_style"
|
||||
assert prompts.tool_guidance, f"{size.value} missing tool_guidance"
|
||||
|
||||
def test_voice_style_enforces_single_sentence(self):
|
||||
"""voice_style must cap replies at one sentence (spoken aloud). The old
|
||||
'Two to three sentences maximum' wording let the model run long, which
|
||||
also slowed TTS since synth time scales with text length."""
|
||||
from jarvis.reply.prompts import get_system_prompts, ModelSize
|
||||
|
||||
for size in [ModelSize.SMALL, ModelSize.LARGE]:
|
||||
voice_style = get_system_prompts(size).voice_style
|
||||
assert "SINGLE sentence" in voice_style, f"{size.value} voice_style not single-sentence"
|
||||
assert "never more than one sentence" in voice_style
|
||||
assert "Two to three" not in voice_style
|
||||
|
||||
def test_to_list_returns_non_empty_strings(self):
|
||||
"""to_list() returns only non-empty prompt strings."""
|
||||
from jarvis.reply.prompts import get_system_prompts, ModelSize
|
||||
|
||||
@@ -44,6 +44,32 @@ class TestBuildSystemPrompt:
|
||||
assert "in the user's language" not in prompt
|
||||
assert "in Korean" in prompt
|
||||
|
||||
def test_persona_enforces_single_sentence(self):
|
||||
# Spoken replies must be one sentence (TTS latency scales with text
|
||||
# length, and the user asked for one-sentence answers). The persona must
|
||||
# state the single-sentence rule and must NOT carry the old "two at the
|
||||
# very most" allowance that let the model run long.
|
||||
prompt = build_system_prompt("Jarvis")
|
||||
assert "single short sentence" in prompt
|
||||
assert "Never write a second sentence" in prompt
|
||||
assert "two at the very most" not in prompt
|
||||
|
||||
def test_persona_aside_does_not_authorise_a_second_sentence(self):
|
||||
# The dry aside must fold into the one sentence, not become a 2nd one.
|
||||
prompt = build_system_prompt("Jarvis")
|
||||
assert "SINGLE sentence" in prompt
|
||||
assert "never add it as " in prompt
|
||||
|
||||
def test_persona_has_no_copyable_proper_noun_examples(self):
|
||||
# A weak model parroted the literal "Trenches Gym" example from the
|
||||
# persona as if it were a real user fact (boxing mangled to tennis).
|
||||
# The persona must not embed copyable personal proper nouns, and must
|
||||
# tell the model to use ONLY facts that literally appear in the memory
|
||||
# section — never borrow names/places from the instructions themselves.
|
||||
prompt = build_system_prompt("Jarvis")
|
||||
assert "Trenches" not in prompt
|
||||
assert "never borrow any name, place, or activity from these instructions" in prompt
|
||||
|
||||
|
||||
class TestOutputLanguageDirective:
|
||||
"""A deployment may lock replies to a single language via OUTPUT_LANGUAGE.
|
||||
@@ -110,6 +136,14 @@ class TestReplyLanguageDirective:
|
||||
directive = reply_language_directive("Korean", "melo")
|
||||
assert directive is not None and "Korean" in directive
|
||||
|
||||
def test_edge_is_multilingual(self):
|
||||
# Edge TTS (the default Korean voice) is not English-only: no lock → the
|
||||
# user's own language, and a lock is honoured (not forced to English).
|
||||
assert reply_language_directive(None, "edge") is None
|
||||
directive = reply_language_directive("Korean", "edge")
|
||||
assert directive is not None and "Korean" in directive
|
||||
assert directive != ENGLISH_ONLY_DIRECTIVE
|
||||
|
||||
|
||||
class TestLoadAgentInstructions:
|
||||
"""Operator can extend the reply LLM's system prompt by dropping *.md files
|
||||
|
||||
35
tests/test_tts_engine_config.py
Normal file
35
tests/test_tts_engine_config.py
Normal file
@@ -0,0 +1,35 @@
|
||||
"""The container's TTS engine must be env-driven, not hardcoded.
|
||||
|
||||
Regression for a bug where docker/jarvis-config.template.json hardcoded
|
||||
`"tts_engine": "piper"`. The bridge reads the rendered /app/config/jarvis.json
|
||||
*before* the environment, so a hardcoded "piper" overrode `TTS_ENGINE=melo` in
|
||||
.env and the bot read Korean text with the English Piper voice ("foreign
|
||||
accent"). The template must carry `${TTS_ENGINE}` so envsubst (entrypoint.sh)
|
||||
renders whatever engine the deployment configured.
|
||||
"""
|
||||
|
||||
import json
|
||||
import string
|
||||
from pathlib import Path
|
||||
|
||||
TEMPLATE = Path(__file__).resolve().parent.parent / "docker" / "jarvis-config.template.json"
|
||||
|
||||
|
||||
def _render(**env) -> dict:
|
||||
"""Mimic entrypoint.sh `envsubst < template`: substitute env vars, leaving
|
||||
any unset ones as literal text (valid JSON string values)."""
|
||||
raw = TEMPLATE.read_text(encoding="utf-8")
|
||||
return json.loads(string.Template(raw).safe_substitute(**env))
|
||||
|
||||
|
||||
def test_template_does_not_hardcode_an_engine():
|
||||
raw = TEMPLATE.read_text(encoding="utf-8")
|
||||
assert '"tts_engine": "${TTS_ENGINE}"' in raw
|
||||
assert '"tts_engine": "piper"' not in raw
|
||||
assert '"tts_engine": "melo"' not in raw
|
||||
|
||||
|
||||
def test_rendered_engine_follows_env():
|
||||
assert _render(TTS_ENGINE="melo")["tts_engine"] == "melo"
|
||||
assert _render(TTS_ENGINE="piper")["tts_engine"] == "piper"
|
||||
assert _render(TTS_ENGINE="xtts")["tts_engine"] == "xtts"
|
||||
Reference in New Issue
Block a user