diff --git a/.dockerignore b/.dockerignore index 57b3379..8e4f16d 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,3 +2,8 @@ target relay/target shots *.png +# The server's own settings (its keys, an older setup's password) never go into a build — and +# an edit there no longer makes a new image (every cloud brain used to be made again for it). +deploy/server/.env +deploy/server/.env.* +deploy/server/Caddyfile diff --git a/FEATURES.md b/FEATURES.md index 1060550..0139196 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -546,7 +546,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **群組沒有 @ 時看擅長分派**:訊息的內容對得上某些成員「擅長」寫的事(而且不在它「不找它做的事」裡),就只由那幾位回答,聊天裡會有一行「這題看擅長交給「…」。要其他人也回答,用 @ 點名。」;對不上任何人、或每個人都對得上,就跟以前一樣全員輪流。 - **手機也能改個人檔案**(擁有者):Bot 設定頁多了「擅長」「不找它做的事」,以及「能力」「會的技能」「可以用的電腦」的開關。區網連線只能勾掉「能力」和「可以用的電腦」、不能勾回,電腦工具只能關、不能開(跟其他放寬權限的設定一樣;以前連勾掉也被擋)。 - **視窗沒在前面也照常運作**:視窗縮小、隱藏或被別的 App 整個蓋住時,Bot 送來的東西照樣處理——要你允許的請求會響提示音、任務完成會通知、例行任務準時開始(以前要等你切回 AnyBot 才一起發生)。任務完成且你不在 AnyBot 前面時,也響同一個提示音(設定裡的「提示音」關掉就不響)。Mac 的 App 關掉了 App Nap,被蓋住時系統不會讓它睡著。 -- **伺服器的 Docker**:setup.sh 檢查到用的是 root 的 Docker 會警告(大腦被攻破等於拿到整台主機),建議改 rootless。 +- **伺服器的 Docker**:setup.sh 檢查到用的是 root 的 Docker 會說一聲(新裝的 Docker 都是),不再停下來等 Enter;用自己的網域對外公開時,完成畫面才警告(大腦被攻破等於拿到整台主機),建議改 rootless。 - 手機頁面最多留 40 個圖片/檔案的快取;收起的步驟和歸檔的舊對話不再把截圖留在記憶體。 ### Bot 之間共用的東西 @@ -719,6 +719,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 思考內容會即時顯示: - OpenAI 相容的供應商:讀取 reasoning_content 或 reasoning 欄位。 - Claude:讀取思考區塊。思考的簽章原封不動保存,下次照原樣送回去。 + - Claude 的思考區塊綁著產生它時的整段對話(system、工具和它前面的每一個字):轉繁體只轉最後一個思考區塊之後的字。帳號被要求檢查時,對不上的那一步收到 400(Invalid signature in thinking block),就帶 `drop_block` 再送一次,請 API 把對不上的思考丟掉,之後同一個服務和模型都這樣送(沒被要求的帳號不送,免得反而開啟檢查);中轉服務不認得這個設定(400 或 422)就拿掉它,還是不接受思考內容就拿掉思考區塊再送(每種只一次,其他錯誤照常)。丟過一次後,這一輪之前的思考區塊就不再送,後面的步驟不會一再被丟掉或拒絕。 - 模型要用工具時,畫面上立刻出現那一步,等這一步的文字結束才真的執行。沒有編號的工具會自動編成 call_0、call_1。 ### Claude 的特殊結尾 @@ -1499,7 +1500,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 中文辨識結果會轉成繁體和台灣用語(xAI 和 Whisper 常回簡體);日文不轉。 - 從舊版升級:原本有 OpenAI 金鑰(語音輸入本來就能用)的人,「聽」自動設成 OpenAI;其他人預設關閉。舊的 macOS 聲音名稱(美佳…)會清掉。 - OpenAI 的轉文字模型依序試 gpt-transcribe、gpt-4o-mini-transcribe、whisper-1(後兩個 OpenAI 在 2027-02-26 停用)。 -- 伺服器上的大腦可以自己架語音服務(`make server` 會問):Whisper 在 CPU 上轉文字,大腦第一次啟動時自動把「聽」設成它(之後改掉就不再動)。它不會念中文,「說」請另外選。 +- 伺服器上的大腦可以自己架語音服務(`setup.sh --ask` 會問;不問的裝法用 `ANYBOT_SETUP_VOICE=1`):Whisper 在 CPU 上轉文字,大腦第一次啟動時自動把「聽」設成它(之後改掉就不再動)。它不會念中文,「說」請另外選。 - 服務回了 200 卻沒有聲音(例如不支援那個語言)時,會說「沒有產生聲音」,不會靜靜地什麼都沒唸。 ### 語音輸入 @@ -2387,7 +2388,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 部署檔: - 雲端:`deploy/server/`(帳號伺服器、Caddy、AnyBot 三合一); - Mac mini:`deploy/mac/com.anybot.serve.plist`。 -- 伺服器的網址(`setup.sh` 會問): +- **一行裝好、每個帳號自己的雲端大腦**(2026-11-23,`docs/plan-2026-11-install.md`): + - 在 Linux 上貼 `curl … install.sh | sh -s -- server`,**不問任何問題**:沒有 Docker 就裝好並設成開機自動跑(rootless 也打開 linger)、裝系統套件(含 `make`)、建置、啟動;最後只印網址和**邀請碼**。剛加進 docker 群組的人用 `sg` 跑設定(不再用 sudo:以前 `.env`、`Caddyfile`、`~/.docker` 變成 root 的,之後的更新全部「Permission denied」);之前留下的 root 檔案會自己改回來。 + - 網址自己找:`ANYBOT_SETUP_DOMAIN` 給了就用;Tailscale 有發憑證用 `https://名字`;tailnet 不發憑證(headscale)用 `http://tailnet 位址`(WireGuard 加密,AnyBot 只在 tailnet 上收 http;任何指到這台的名字也通,`https://位址` 也在,手機通知用);都沒有用 `https://區網 IP`(自簽,每台裝置先信任一次);公開的位址(VPS)又沒給網域就停下來,請你給網域或裝 Tailscale。以前 headscale 會被給一個永遠連不上的 `https://名字`。綁在某個位址時設 `net.ipv4.ip_nonlocal_bind=1`:重開機時 tailnet 比 Docker 晚起來,caddy 也綁得到。 + - 帳號在 App 或手機上註冊(要邀請碼,第一個人也要)。**大腦管理員**(compose 的 `brains`,`anybot --brains`)看到新帳號就替它開一個雲端大腦 `anybot-brain-帳號`:自己的資料卷,用帳號伺服器發的登入憑證(`/relay/manager/brain`,伺服器上不存密碼);停了會叫醒,重開機自己回來,映像檔換了(更新後)用同一份資料和登入換成新版,不刪任何大腦。**只有擁有者(第一個帳號,管理員第一次看到就記住;完成畫面提醒先自己註冊)和 `ANYBOT_BRAINS_DOCKER` 列的帳號有 Docker**(自己的 Bot 電腦和家目錄卷):大腦上可以跑 hook 和連接器,能動 Docker 就能讀別人的大腦、拿到整台主機;其他帳號的大腦用自己的電腦當手腳。**拿到邀請碼的人,雲端大腦能在這台伺服器的網路裡跑程式**(連得到它的區網、tailnet、主機上的服務):使用者選擇每個帳號都開、只把邀請碼給信任的人,完成畫面寫著。每個大腦都 `--cap-drop NET_RAW`、`no-new-privileges`,有記憶體(`ANYBOT_BRAIN_MEMORY`,預設 4g,不准用 swap 多拿)、CPU(`ANYBOT_BRAIN_CPUS`,預設 2、不超過主機的核心數;Docker 不能限 CPU 時——沒有 CFS 配額,例如沒交出 cpu controller 的 rootless——不設,否則 Docker 拒絕建立)和程序數上限,最多 `ANYBOT_BRAINS_MAX`(預設 20)個,新帳號的大腦排在重建前面;帳號伺服器只相信帶著 `ANYBOT_PROXY_SECRET` 的 Caddy 說的請求來源(大腦直接連進去自己寫 X-Forwarded-For 不算,繞不過註冊、登入、配對的次數限制)——只在 Caddy 是唯一入口時:舊的 Caddyfile(手改的也是)更新時在每個 `reverse_proxy relay:8080 {` 區塊補上送暗號的那行(註解掉的不算),Caddy 檢查過才換上,並重開 caddy;有一行寫法的、補不了或是 Tailscale serve 模式就不用暗號、照舊;從 `.env` 拿掉的設定(暗號、語音)這次啟動就不再算;要停掉某個帳號的大腦,把它加進 `.env` 的 `ANYBOT_BRAINS_SKIP` 再 `docker stop`。不能在跟帳號伺服器共用的網路上偽造或偷聽封包;管理員跟帳號伺服器講話走只有它們兩個的 `manager` 網路(`relay-manager`),金鑰不經過大腦們的網路。重建前先 `docker stop` 讓它收尾,新的先在舊的旁邊建好(Docker 建立時就檢查所有參數,拒絕的話舊的照常在跑、完全不動),才停舊的、換名字、啟動,新的跑起來才刪舊的,換不成就放回舊的;要新登入的先拿到登入再動舊的;舊的停不下來(或 Docker 沒說它停了)就不換;同一個帳號一直失敗時,隔 1、2、4…分鐘再試,最多隔半小時(不會一直停掉跑得好好的大腦);管理員中途被停掉的下次接回來;更新時先建置,成功了才停管理員(建置失敗它照常在跑;啟動失敗或被 Ctrl-C 中斷也會把它開回來),它收到停止是做完手上那件才結束(最多兩分鐘);問不到 Docker 能不能限 CPU 就重啟再問;停掉(skip)的大腦不算進上限;看的是映像檔裡裝了什麼(各層內容的雜湊,建立時記在標籤上——每次建置映像檔 ID 都不同,舊的那個重建後在 containerd 的儲存裡也查不到),只改 `.env` 或重建出一樣的東西不會重開大腦;開法變了(標籤裡記著雜湊)也重建;`.dockerignore` 不讓 `deploy/server/.env`、`Caddyfile` 進建置;帳號伺服器不再認得它的登入(`/relay/manager/users` 的 `brains`)時發新的。管理員第一次啟動以前就有的帳號不開(`ANYBOT_BRAINS_ALL=1` 才開);它不取代帳號裡不是它開的同名電腦(409),登入的電腦也不能取代它開的大腦(409)。管理員的 API 只認 `ANYBOT_RELAY_MANAGER_TOKEN`、只收伺服器內部直接來的請求(經 Caddy 的一律 404,Caddy 也擋 `/relay/manager/`);`/api/hello` 只在管理員最近一分鐘來過時說 `brains: true`。 + - 電腦註冊或登入這種伺服器(`/api/hello` 有 `brains: true`)時,等那個雲端大腦上線再當它的螢幕(「正在等你的雲端大腦開好…」,最多約一分半),不會先把自己當成大腦。 + - 舊的單一帳號伺服器(`.env` 有 `ANYBOT_USER`):原本的大腦照舊(compose 的 `owner-brain` 設定檔,更新時自動打開),管理員不替那個帳號再開;更新時補上管理員的金鑰。舊的問答流程:`setup.sh --ask`。 + - 實測:全新 Ubuntu 24.04(有 systemd、沒有 Docker)一行裝好約 14 分鐘;註冊兩個帳號,各自的雲端大腦 5 秒內出現、只看得到自己的;`make update-server`、重開機都自己回來。 +- 伺服器的網址(`setup.sh --ask` 會問): - Tailscale:`https://那台.xxx.ts.net`,只有 Tailscale 裡的裝置連得到; - 自己的網域:憑證自動申請; - 區網 IP(例如 `https://10.0.0.25`):憑證由伺服器自己簽(Caddy 的 `tls internal`),只有同一個區網連得到;可以和 Tailscale 一起用。 diff --git a/Makefile b/Makefile index 3134d13..effe19d 100644 --- a/Makefile +++ b/Makefile @@ -176,7 +176,14 @@ update-server: update-box: @if [ -f deploy/server/.env ]; then \ s=$$(sed -n "s/^DOCKER_SOCKET=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$$/\1/p" deploy/server/.env | tail -n 1); \ - cd deploy/server && env $${s:+DOCKER_HOST=unix://$$s} docker compose exec -T anybot anybot --update-box; \ + u=$$(sed -n "s/^ANYBOT_USER=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$$/\1/p" deploy/server/.env | tail -n 1); \ + if [ -n "$$u" ]; then \ + cd deploy/server && env $${s:+DOCKER_HOST=unix://$$s} docker compose exec -T anybot anybot --update-box; \ + else \ + ids=$$(env $${s:+DOCKER_HOST=unix://$$s} docker ps -q --filter label=anybot.brain.docker=1); \ + [ -n "$$ids" ] || { echo " 沒有雲端大腦有 Bot 的電腦(只有擁有者的有)"; exit 0; }; \ + for c in $$ids; do env $${s:+DOCKER_HOST=unix://$$s} docker exec $$c anybot --update-box || exit 1; done; \ + fi; \ else \ b="$(HOME)/.local/bin/anybot"; [ -x "$$b" ] || b="$(APPDIR)/AnyBot.app/Contents/MacOS/AnyBot"; \ [ -x "$$b" ] || { echo " ✗ 這台還沒裝 AnyBot(make install),沒有 Bot 的電腦可以更新"; exit 1; }; \ diff --git a/README.md b/README.md index 476d481..eb681bf 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ irm https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.ps1 | iex 它會自己裝好需要的東西、問你要裝哪一種,然後做第一次設定。第一次編譯 5–15 分鐘,之後更新 1–2 分鐘;裝在你的使用者資料夾,不需要系統管理員。 -**帳號伺服器 + 大腦**(任何有 Docker 的 Linux,2 GB 以上;只問網址、帳號、密碼,HTTPS 它自己處理): +**帳號伺服器 + 雲端大腦**(任何 Linux,2 GB 以上;不問任何問題——Docker、網址、HTTPS 它自己處理,最後給你網址和邀請碼。之後在 AnyBot 裡「登入帳號 › 註冊」,每個帳號幾秒後就有自己的雲端大腦): ```sh curl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh \ diff --git a/deploy/ci/package-linux.sh b/deploy/ci/package-linux.sh index 6288fe1..3e71cad 100755 --- a/deploy/ci/package-linux.sh +++ b/deploy/ci/package-linux.sh @@ -36,7 +36,9 @@ cp "$BIN" "$RELAY" "$D/bin/" cp deploy/server/setup.sh deploy/server/.env.example "$D/deploy/server/" cp deploy/ci/server-compose.yml "$D/deploy/server/docker-compose.yml" cp deploy/ci/Dockerfile.server-relay deploy/ci/Dockerfile.server-anybot "$D/deploy/server/" -cp relay/Caddyfile "$D/relay/Caddyfile" +cp relay/Caddyfile relay/Caddyfile.lan relay/Caddyfile.open "$D/relay/" +# (The local network's and a tailnet's address: setup.sh picks these by itself.) +cp deploy/server/docker-compose.lan.yml deploy/server/docker-compose.tailscale.yml "$D/deploy/server/" printf 'AnyBot %s 伺服器(帳號伺服器 + 大腦 + HTTPS,用 Docker)\n\n cd deploy/server && ./setup.sh\n' "$VERSION" > "$D/讀我.txt" tar -C "$OUT" -czf "$D.tar.gz" "$(basename "$D")" diff --git a/deploy/ci/server-compose.yml b/deploy/ci/server-compose.yml index 6cb186c..6f8f97f 100644 --- a/deploy/ci/server-compose.yml +++ b/deploy/ci/server-compose.yml @@ -24,30 +24,47 @@ services: # Your public address (for the links of sites the bots publish), e.g. https://anybot.example.com ANYBOT_RELAY_PUBLIC_URL: "${ANYBOT_RELAY_PUBLIC_URL:-}" ANYBOT_RELAY_INVITE: "${ANYBOT_RELAY_INVITE:-}" + # 大腦管理員 (brains, below) asks for each account's cloud brain with this key. + ANYBOT_RELAY_MANAGER_TOKEN: "${ANYBOT_RELAY_MANAGER_TOKEN:-}" # Caddy (or `tailscale serve`) is in front: the caller's address is the one it reports. # Without this every login attempt counts as coming from the proxy, and a few wrong # passwords from anyone lock that account for everyone. RELAY_TRUST_PROXY: "1" + # Who asked is believed only from Caddy (it sends this): a cloud brain talking to the + # account server straight can't make up the address of its requests. + ANYBOT_RELAY_PROXY_SECRET: "${ANYBOT_PROXY_SECRET:-}" volumes: - relay-data:/data + # The 大腦管理員 reaches it on a network of its own (relay-manager): its key never crosses + # the one the brains share. + networks: + default: {} + manager: + aliases: [relay-manager] caddy: image: caddy:2 restart: unless-stopped + environment: + ANYBOT_PROXY_SECRET: "${ANYBOT_PROXY_SECRET:-}" ports: ["80:80", "443:443"] volumes: # Written by setup.sh (your domain); ../../relay/Caddyfile is the template. - ./Caddyfile:/etc/caddy/Caddyfile:ro - caddy-data:/data depends_on: [relay] + # A server set up for one account (.env has ANYBOT_USER: the owner-brain profile). Set up the + # easy way there is none: 大腦管理員 (brains) gives every account a cloud brain of its own. anybot: + profiles: ["owner-brain"] + image: anybot-brain:local build: context: ../.. dockerfile: deploy/server/Dockerfile.server-anybot restart: unless-stopped depends_on: [relay] environment: - ANYBOT_ACCOUNT: "http://relay:8080|${ANYBOT_USER}" - ANYBOT_ACCOUNT_PASSWORD: "${ANYBOT_PASSWORD}" + ANYBOT_ACCOUNT: "http://relay:8080|${ANYBOT_USER:-}" + ANYBOT_ACCOUNT_PASSWORD: "${ANYBOT_PASSWORD:-}" ANYBOT_HOST_NAME: "${ANYBOT_HOST_NAME:-雲端 AnyBot}" # First start on a new server: make the account (the first one needs no invite). ANYBOT_ACCOUNT_CREATE: "1" @@ -63,6 +80,36 @@ services: networks: [default, docker-api] volumes: - anybot-data:/data + # 大腦管理員 (src/brains.rs): a cloud brain `anybot-brain-` for every account, made with + # this same image, signed in with a host token from the account server (no password here). + brains: + image: anybot-brain:local + build: + context: ../.. + dockerfile: deploy/server/Dockerfile.server-anybot + restart: unless-stopped + depends_on: [relay, docker-socket-proxy] + command: ["anybot", "--brains"] + # (A stop is a stop: an init passes it on and the manager ends between jobs — given the time + # a brain needs to finish its own turn.) + init: true + stop_grace_period: 2m + environment: + ANYBOT_RELAY_MANAGER_TOKEN: "${ANYBOT_RELAY_MANAGER_TOKEN:-}" + ANYBOT_RELAY_INTERNAL: "http://relay-manager:8080" + ANYBOT_BRAIN_RELAY: "http://relay:8080" + # The one-account setup's own brain, and accounts you list to stop theirs (then + # `docker stop` it: the manager leaves it stopped). + ANYBOT_BRAINS_SKIP: "${ANYBOT_USER:-},${ANYBOT_BRAINS_SKIP:-}" + ANYBOT_BRAINS_MAX: "${ANYBOT_BRAINS_MAX:-}" + ANYBOT_BRAIN_CPUS: "${ANYBOT_BRAIN_CPUS:-}" + ANYBOT_BRAINS_DOCKER: "${ANYBOT_BRAINS_DOCKER:-}" + ANYBOT_BRAINS_ALL: "${ANYBOT_BRAINS_ALL:-}" + ANYBOT_BRAIN_MEMORY: "${ANYBOT_BRAIN_MEMORY:-}" + DOCKER_HOST: "tcp://docker-socket-proxy:2375" + networks: [default, docker-api, manager] + volumes: + - brains-data:/data docker-socket-proxy: image: tecnativa/docker-socket-proxy:0.3.0 restart: unless-stopped @@ -75,6 +122,7 @@ services: SESSION: "1" VOLUMES: "1" NETWORKS: "1" + INFO: "1" # docker info: whether a brain can be held to a share of the CPUs POST: "1" GET: "1" networks: [docker-api] @@ -83,7 +131,10 @@ services: networks: docker-api: internal: true + manager: + internal: true volumes: relay-data: caddy-data: anybot-data: + brains-data: diff --git a/deploy/server/docker-compose.yml b/deploy/server/docker-compose.yml index 3d1c2d8..6c99345 100644 --- a/deploy/server/docker-compose.yml +++ b/deploy/server/docker-compose.yml @@ -24,22 +24,40 @@ services: # Your public address (for the links of sites the bots publish), e.g. https://anybot.example.com ANYBOT_RELAY_PUBLIC_URL: "${ANYBOT_RELAY_PUBLIC_URL:-}" ANYBOT_RELAY_INVITE: "${ANYBOT_RELAY_INVITE:-}" + # 大腦管理員 (brains, below) asks for each account's cloud brain with this key. + ANYBOT_RELAY_MANAGER_TOKEN: "${ANYBOT_RELAY_MANAGER_TOKEN:-}" # Caddy (or `tailscale serve`) is in front: the caller's address is the one it reports. # Without this every login attempt counts as coming from the proxy, and a few wrong # passwords from anyone lock that account for everyone. RELAY_TRUST_PROXY: "1" + # Who asked is believed only from Caddy (it sends this): a cloud brain talking to the + # account server straight can't make up the address of its requests. + ANYBOT_RELAY_PROXY_SECRET: "${ANYBOT_PROXY_SECRET:-}" volumes: - relay-data:/data + # The 大腦管理員 reaches it on a network of its own (relay-manager): its key never crosses + # the one the brains share. + networks: + default: {} + manager: + aliases: [relay-manager] caddy: image: caddy:2 restart: unless-stopped + environment: + ANYBOT_PROXY_SECRET: "${ANYBOT_PROXY_SECRET:-}" ports: ["80:80", "443:443"] volumes: # Written by setup.sh (your domain); ../../relay/Caddyfile is the template. - ./Caddyfile:/etc/caddy/Caddyfile:ro - caddy-data:/data depends_on: [relay] + # The brain of a server set up for one account (.env has ANYBOT_USER — setup.sh turns this + # profile on for it). A server set up the easy way has none: 大腦管理員 (brains) gives every + # account, this one's included, a cloud brain of its own. anybot: + profiles: ["owner-brain"] + image: anybot-brain:local build: context: ../.. dockerfile: deploy/server/Dockerfile @@ -54,8 +72,8 @@ services: # kernel and Chromium's own sandbox comes back on. On a host without runsc the box won't # start — switch 容器隔離 back to 標準. environment: - ANYBOT_ACCOUNT: "http://relay:8080|${ANYBOT_USER}" - ANYBOT_ACCOUNT_PASSWORD: "${ANYBOT_PASSWORD}" + ANYBOT_ACCOUNT: "http://relay:8080|${ANYBOT_USER:-}" + ANYBOT_ACCOUNT_PASSWORD: "${ANYBOT_PASSWORD:-}" ANYBOT_HOST_NAME: "${ANYBOT_HOST_NAME:-雲端 AnyBot}" # First start on a new server: make the account (the first one needs no invite). ANYBOT_ACCOUNT_CREATE: "1" @@ -86,6 +104,48 @@ services: networks: [default, docker-api] volumes: - anybot-data:/data + # 大腦管理員 (src/brains.rs): every account on this account server gets a cloud brain of its + # own, a container `anybot-brain-` made with this same image (own data, own bots' + # computer), signed in with a host token the account server hands it — no password on the + # server. Docker only through the filtered proxy, as for the bots' computer. + brains: + image: anybot-brain:local + build: + context: ../.. + dockerfile: deploy/server/Dockerfile + args: { JOBS: "${ANYBOT_BUILD_JOBS:-}" } + restart: unless-stopped + depends_on: [relay, docker-socket-proxy] + command: ["anybot", "--brains"] + # (A stop is a stop: an init passes it on and the manager ends between jobs — given the time + # a brain needs to finish its own turn.) + init: true + stop_grace_period: 2m + environment: + ANYBOT_RELAY_MANAGER_TOKEN: "${ANYBOT_RELAY_MANAGER_TOKEN:-}" + # The account server on the manager's own network; the brains reach it on theirs. + ANYBOT_RELAY_INTERNAL: "http://relay-manager:8080" + ANYBOT_BRAIN_RELAY: "http://relay:8080" + # Accounts whose brains get Docker besides the owner's; every account from before the + # manager too; each brain's memory. + ANYBOT_BRAINS_DOCKER: "${ANYBOT_BRAINS_DOCKER:-}" + ANYBOT_BRAINS_ALL: "${ANYBOT_BRAINS_ALL:-}" + ANYBOT_BRAIN_MEMORY: "${ANYBOT_BRAIN_MEMORY:-}" + # The one-account setup's own brain (anybot, above) is left to itself. + # The one-account setup's own brain, and accounts you list to stop theirs (then + # `docker stop` it: the manager leaves it stopped). + ANYBOT_BRAINS_SKIP: "${ANYBOT_USER:-},${ANYBOT_BRAINS_SKIP:-}" + ANYBOT_BRAINS_MAX: "${ANYBOT_BRAINS_MAX:-}" + ANYBOT_BRAIN_CPUS: "${ANYBOT_BRAIN_CPUS:-}" + DOCKER_HOST: "tcp://docker-socket-proxy:2375" + ANYBOT_VOICE_URL: "${ANYBOT_VOICE_URL:-}" + ANYBOT_VOICE_LISTEN_MODEL: "${ANYBOT_VOICE_LISTEN_MODEL:-}" + ANYBOT_VOICE_SPEAK_MODEL: "${ANYBOT_VOICE_SPEAK_MODEL:-}" + ANYBOT_VOICE_VOICE: "${ANYBOT_VOICE_VOICE:-}" + ANYBOT_HF_BASE: "${ANYBOT_HF_BASE:-}" + networks: [default, docker-api, manager] + volumes: + - brains-data:/data # 語音 (optional: ./setup.sh asks; COMPOSE_PROFILES=voice in .env turns it on): speech to text # (Whisper) on this server's CPU for every screen and phone, with no key. speaches (MIT) speaks # OpenAI's audio API. No port is published: only the brain reaches it, at http://voice:8000/v1. @@ -122,6 +182,7 @@ services: SESSION: "1" VOLUMES: "1" # anybot-box-home: inspect, create, rm (Reset/Restore) NETWORKS: "1" # inspect/attach (docker run needs the bridge network) + INFO: "1" # docker info: whether a brain can be held to a share of the CPUs POST: "1" GET: "1" # DOCKER_SOCKET in .env: the Docker this server lives on (setup.sh writes it at the first setup, @@ -131,12 +192,17 @@ services: volumes: - ${DOCKER_SOCKET:-/var/run/docker.sock}:/var/run/docker.sock:ro networks: - # Only `anybot` shares this internal network with `docker-socket-proxy`; `relay`, `caddy` and - # `voice` cannot reach port 2375. + # Only `anybot`, `brains` and the cloud brains given Docker (the owner's) share this internal + # network with `docker-socket-proxy`; `relay`, `caddy`, `voice` and the other brains cannot + # reach port 2375. docker-api: internal: true + # The account server and the 大腦管理員 only. + manager: + internal: true volumes: relay-data: caddy-data: anybot-data: + brains-data: voice-models: diff --git a/deploy/server/setup.sh b/deploy/server/setup.sh index efd068f..596d6be 100755 --- a/deploy/server/setup.sh +++ b/deploy/server/setup.sh @@ -1,7 +1,11 @@ #!/usr/bin/env bash # AnyBot 伺服器設定: the account server, HTTPS and the brain on this server, step by step. # -# make server (= ./setup.sh) ask, write .env and Caddyfile, start, check +# make server (= ./setup.sh) the first time: no questions — find the address, make up the +# invite and the manager's key, write .env and Caddyfile, start, +# check. Accounts are made in the app; each gets its own cloud +# brain from 大腦管理員 (the brains service). +# ./setup.sh --ask the questions instead (a domain, one account with its brain) # make update-server (= ./setup.sh --start after git pull) start with .env as it is: no questions # make server-logs (= ./setup.sh --logs) follow the brain's log # ./setup.sh --dry-run ask and write the files, but don't start anything @@ -21,19 +25,45 @@ # An existing setup is kept (updated and restarted). set -u cd "$(dirname "$0")" -DRY=0; START=0; LOGS=0 +DRY=0; START=0; LOGS=0; ASK=0 case "${1:-}" in --dry-run) DRY=1 ;; --start) START=1 ;; --logs) LOGS=1 ;; + --ask) ASK=1 ;; esac if [ "$START" = 1 ] || [ "$LOGS" = 1 ]; then [ -f .env ] || { printf '這台還沒架伺服器。第一次架:make server\n' >&2; exit 1; } fi +# A setup once run under sudo (an older install.sh did, before the new docker group counted) left +# .env, Caddyfile and ~/.docker to root, and every run as the user after it stopped at +# "Permission denied". Hand them back (sudo asks only when it must), or say exactly how. +if [ "$(id -u)" != 0 ]; then + me=$(id -un) + for f in .env Caddyfile "${HOME:-/nonexistent}/.docker"; do + [ -e "$f" ] || continue + [ -n "$(find "$f" ! -user "$me" -print -quit 2>/dev/null)" ] || continue + if sudo -n chown -R "$me" "$f" 2>/dev/null; then continue; fi + if [ -t 0 ]; then + printf '%s 是 root 的(之前用 sudo 設定過),改回給 %s(要你的密碼):\n' "$f" "$me" + sudo chown -R "$me" "$f" && continue + fi + printf '%s 是 root 的(之前用 sudo 設定過),這次讀寫不了。請執行:\n sudo chown -R %s %s\n再跑一次。\n' "$f" "$me" "$(cd "$(dirname "$f")" && pwd)/$(basename "$f")" >&2 + exit 1 + done +fi +# Run as root through sudo: what is written here belongs to the person who ran it. +own_files() { + [ "$(id -u)" = 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ] && chown "$SUDO_USER" .env Caddyfile 2>/dev/null + return 0 +} AUTO=0 [ -n "${ANYBOT_SETUP_USER:-}" ] && [ -n "${ANYBOT_SETUP_PASSWORD:-}" ] && AUTO=1 # --start asks nothing: it keeps .env as it is. [ "$START" = 1 ] && AUTO=1 +# The first setup asks nothing either (the easy way below), unless --ask. +EASY=0 +if [ ! -f .env ] && [ "$ASK" = 0 ] && [ -z "${ANYBOT_SETUP_USER:-}" ]; then EASY=1; AUTO=1; fi # The Docker this server lives on: the daemon that holds its data (the volumes). Picked once, at # the first setup, from the docker CLI as it was then, and kept in .env as DOCKER_SOCKET; every @@ -55,7 +85,9 @@ if [ -n "$SOCK" ]; then export DOCKER_HOST="unix://$SOCK" DOCKER_SOCKET="$SOCK" fi if [ "$LOGS" = 1 ]; then - exec docker compose logs -f --tail 100 "${2:-anybot}" + # (Set up the easy way there is no one brain: the manager's log, which says what it made.) + svc=anybot; grep -q "^COMPOSE_PROFILES=.*owner-brain" .env 2>/dev/null || svc=brains + exec docker compose logs -f --tail 100 "${2:-$svc}" fi # 語音 on this server (docker-compose's voice service, speaches): speech to text with Whisper on # the CPU. large-v3-turbo got every word of a Mandarin test right, about 3.5 s for 11 s of speech @@ -177,6 +209,17 @@ lan_ip() { [ -z "$a" ] && a=$(hostname -I 2>/dev/null | awk '{print $1}') printf '%s' "$a" } +# A tailnet's address (100.64.0.0/10) and the local network's own (RFC 1918). +is_tailnet() { case "$1" in 100.*) local o=${1#100.}; o=${o%%.*}; [ "$o" -ge 64 ] 2>/dev/null && [ "$o" -le 127 ] ;; *) return 1 ;; esac; } +is_private() { case "$1" in 10.*|192.168.*) return 0 ;; 172.*) local o=${1#172.}; o=${o%%.*}; [ "$o" -ge 16 ] 2>/dev/null && [ "$o" -le 31 ] ;; *) return 1 ;; esac; } + +# Questions need a terminal: without one (a pipe, a script) a setup already made is kept and +# updated; one that would have to ask stops and says so (its question loops used to run forever). +if [ "$AUTO" = 0 ] && [ ! -t 0 ]; then + if [ -f .env ] && [ -f Caddyfile ]; then AUTO=1 + else printf '這次要回答問題(--ask,或只給了帳號沒給密碼):請在終端機執行。不想回答就什麼都不給,用不問問題的裝法。\n' >&2; exit 1; fi +fi + # ---------- 0. this server ---------- AT=0; header; card_open "檢查這台伺服器" FAIL=0; WARNED=0 @@ -198,9 +241,49 @@ fi # The brain drives Docker (through docker-socket-proxy, which can limit the kinds of calls but # not what a container mounts). On the root daemon, whoever takes over the brain can mount this # host's disk as root; on rootless Docker the most they get is this one user. +# A Docker just installed (get.docker.com) always runs as root: a note here, not a stop — it +# matters once the server is open to the internet (a domain), and is said again there. +ROOTDOCKER=0 if [ $FAIL = 0 ] && [ "$(docker info --format '{{range .SecurityOptions}}{{.}} {{end}}' 2>/dev/null | grep -c rootless)" = 0 ]; then - warn "這個 Docker 用 root 身分在跑:大腦萬一被攻破,對方等於拿到整台主機" - note "對外公開前建議改用 rootless Docker:https://docs.docker.com/engine/security/rootless/" + ROOTDOCKER=1 + note "Docker 用 root 身分在跑(一般安裝都是這樣):只在區網、tailnet 裡用沒關係" +fi +# 開機自動啟動: the containers come back by themselves (restart: unless-stopped) once Docker runs, +# so Docker itself has to start at boot — a rootless one also with nobody logged in (linger). +# Turned on here when it can be (sudo asks only in a terminal); otherwise said how. +BOOT="" +boot_check() { + local me lg + BOOT=""; BOOTFIX="" + command -v systemctl >/dev/null || { BOOT=unknown; return; } + case "$SOCK" in + /run/user/*) + me=$(id -un) + [ "$(systemctl --user is-enabled docker 2>/dev/null)" = enabled ] || systemctl --user enable docker >/dev/null 2>&1 || true + lg=$(loginctl show-user "$me" -p Linger --value 2>/dev/null) + if [ "$lg" != yes ]; then + sudo -n loginctl enable-linger "$me" 2>/dev/null || { [ "$AUTO" = 0 ] && [ -t 0 ] && sudo loginctl enable-linger "$me"; } || true + lg=$(loginctl show-user "$me" -p Linger --value 2>/dev/null) + fi + if [ "$(systemctl --user is-enabled docker 2>/dev/null)" = enabled ] && [ "$lg" = yes ]; then BOOT=1 + else BOOTFIX="systemctl --user enable docker && sudo loginctl enable-linger $me"; fi + ;; + *) + if [ "$(systemctl is-enabled docker 2>/dev/null)" != enabled ]; then + if [ "$(id -u)" = 0 ]; then systemctl enable docker >/dev/null 2>&1 + else sudo -n systemctl enable docker >/dev/null 2>&1 || { [ "$AUTO" = 0 ] && [ -t 0 ] && sudo systemctl enable docker >/dev/null 2>&1; }; fi || true + fi + if [ "$(systemctl is-enabled docker 2>/dev/null)" = enabled ]; then BOOT=1; else BOOTFIX="sudo systemctl enable docker"; fi + ;; + esac +} +if [ $FAIL = 0 ]; then + boot_check + case "$BOOT" in + 1) ok "開機會自己啟動(Docker 開機就跑,大腦跟著起來)" ;; + unknown) note "這台沒有 systemd:請自己讓 Docker 開機啟動,大腦會跟著起來" ;; + *) warn "重開機後大腦不會自己回來。執行:$BOOTFIX" ;; + esac fi # A kept Tailscale-only setup has no Caddy: 80 and 443 aren't this server's business then. TSONLY=0 @@ -235,35 +318,151 @@ if [ -f .env ] && { [ -f Caddyfile ] || [ "$START" = 1 ]; }; then # Toggle the voice service in the kept .env, then update and restart like 0. if grep -q "^COMPOSE_PROFILES=.*voice" .env; then (umask 077; grep -v -e '^COMPOSE_PROFILES=' -e '^ANYBOT_VOICE_' .env >.env.new) && mv .env.new .env + unset COMPOSE_PROFILES ANYBOT_VOICE_URL ANYBOT_VOICE_LISTEN_MODEL ANYBOT_VOICE_SPEAK_MODEL ANYBOT_VOICE_VOICE else (umask 077; { grep -v -e '^COMPOSE_PROFILES=' -e '^ANYBOT_VOICE_' .env; voice_lines; } >.env.new) && mv .env.new .env fi set -a; . ./.env; set +a KEEP=0 fi + # Set up again, a server set up the easy way (no ANYBOT_USER) stays that way: its address is + # found again; its invite, the manager's key and the cloud brains stay. (Asking for one account + # here would make that account a second brain the account server refuses.) + if [ "$KEEP" = 1 ] && [ -z "${ANYBOT_USER:-}" ]; then + EASY=1 + unset COMPOSE_FILE ANYBOT_LAN_IP ANYBOT_TAILSCALE ANYBOT_RELAY_PUBLIC_URL + fi if [ "$KEEP" = 0 ]; then - DOMAIN=${ANYBOT_RELAY_PUBLIC_URL#https://}; USERNAME=$ANYBOT_USER; INVITE=${ANYBOT_RELAY_INVITE:-}; BRAIN=${ANYBOT_HOST_NAME:-} + # (An address served over plain http — a tailnet's, the easy way's — is kept without it too: + # it used to come out as https://http://….) + DOMAIN=${ANYBOT_RELAY_PUBLIC_URL#https://}; DOMAIN=${DOMAIN#http://}; USERNAME=${ANYBOT_USER:-}; INVITE=${ANYBOT_RELAY_INVITE:-}; BRAIN=${ANYBOT_HOST_NAME:-} LANIP=${ANYBOT_LAN_IP:-} AT=3; SKIP=1 fi fi +# Made-up keys: a long one for the manager, a short one people type (the invite). +gen_key() { head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'; } +gen_code() { local c; c=$(LC_ALL=C tr -dc 'abcdefghjkmnpqrstuvwxyz23456789' /dev/null | head -c 8); printf '%s-%s' "${c:0:4}" "${c:4:4}"; } + +# ---------- the easy way: a first setup, no questions ---------- +# The address is found here; the accounts are made in the app, and each gets a cloud brain of its +# own from 大腦管理員 (no account or password on the server). The invite is needed by the first +# account too — or whoever reached the server first would own it. +if [ "$EASY" = 1 ] && [ "${SKIP:-0}" != 1 ]; then + AT=1; TS=0; LAN=0; OPEN=0; LANIP=""; USERNAME=""; BRAIN="雲端大腦" + TSNAME=$(tailscale status --json 2>/dev/null | sed -n 's/.*"DNSName": *"\([^"]*\)\.".*/\1/p' | head -1) + TSIP="" + if [ -n "$TSNAME" ] && ! tailscale status --json 2>/dev/null | tr -d ' \n' | grep -q '"CertDomains":\["'; then + # (headscale, or Tailscale with HTTPS off: no certificate for the name — its address instead.) + TSIP=$(tailscale ip -4 2>/dev/null | head -1) + TSNAME="" + fi + # Plain http only on a tailnet (WireGuard already encrypts it; AnyBot takes http only there). + # The local network gets https with a certificate this server signs; an address open to the + # internet without a domain gets nothing in the clear — a domain or Tailscale is asked for. + if [ -n "${ANYBOT_SETUP_DOMAIN:-}" ]; then + DOMAIN=${ANYBOT_SETUP_DOMAIN#https://}; DOMAIN=${DOMAIN#http://}; DOMAIN=${DOMAIN%%/*} + if is_ip "$DOMAIN"; then + LANIP=$DOMAIN + if is_tailnet "$DOMAIN"; then OPEN=1; else LAN=1; fi + fi + elif [ -n "$TSNAME" ]; then + DOMAIN=$TSNAME; TS=1 + elif [ -n "$TSIP" ]; then + OPEN=1; LANIP=$TSIP; DOMAIN=$TSIP + else + LANIP=$(lan_ip) + if ! is_ip "${LANIP:-}"; then + header; card_open "網址"; bad "找不到這台的位址:請加上 ANYBOT_SETUP_DOMAIN=網域或 IP 再執行一次"; die + fi + if ! is_private "$LANIP"; then + header; card_open "網址" + bad "這台的位址 $LANIP 在網路上是公開的:不把帳號用明文開在網路上" + note "給它一個網域:ANYBOT_SETUP_DOMAIN=你的網域(DNS 先指到這台,HTTPS 憑證自動申請)" + note "或先裝 Tailscale(只有你的裝置連得到),再執行一次" + die + fi + LAN=1; DOMAIN=$LANIP + fi + INVITE=${ANYBOT_RELAY_INVITE:-} + [ -n "$INVITE" ] || INVITE=$(gen_code) + VOICE=1; [ "${ANYBOT_SETUP_VOICE:-}" = 1 ] && VOICE=0 + q() { printf "%s='%s'\n" "$1" "$2"; } + # (Set up again: every other line of the older .env stays — settings added by hand, the + # voice service unless asked anew, the Docker it is on.) + keep="" + if [ -f .env ]; then + drop='^(#|ANYBOT_HOST_NAME=|ANYBOT_RELAY_INVITE=|ANYBOT_RELAY_MANAGER_TOKEN=|ANYBOT_RELAY_PUBLIC_URL=|ANYBOT_RESTORE_FROM_ACCOUNT=|ANYBOT_TAILSCALE=|ANYBOT_LAN_IP=|COMPOSE_FILE=' + [ "$VOICE" = 0 ] && drop="$drop|ANYBOT_VOICE_" + keep=$(grep -E -v "$drop)" .env || true) + fi + umask 077 + { + echo "# Written by setup.sh (the easy way). Change it, then make update-server." + [ -n "$keep" ] && printf '%s\n' "$keep" + q ANYBOT_HOST_NAME "$BRAIN" + q ANYBOT_RELAY_INVITE "$INVITE" + q ANYBOT_RELAY_MANAGER_TOKEN "${ANYBOT_RELAY_MANAGER_TOKEN:-$(gen_key)}" + if [ "$OPEN" = 1 ]; then q ANYBOT_RELAY_PUBLIC_URL "http://$DOMAIN"; else q ANYBOT_RELAY_PUBLIC_URL "https://$DOMAIN"; fi + q ANYBOT_RESTORE_FROM_ACCOUNT "" + [ "$TS" = 1 ] && q ANYBOT_TAILSCALE 1 + [ -n "$LANIP" ] && q ANYBOT_LAN_IP "$LANIP" + [ "$TS" = 1 ] && q COMPOSE_FILE "docker-compose.yml:docker-compose.tailscale.yml" + [ -n "$LANIP" ] && q COMPOSE_FILE "docker-compose.yml:docker-compose.lan.yml" + [ "$VOICE" = 0 ] && voice_lines + true + } >.env + chmod 600 .env + umask 022 + if [ "$OPEN" = 1 ]; then + sed "s/ADDR/$LANIP/g" ../../relay/Caddyfile.open >Caddyfile + elif [ "$LAN" = 1 ]; then + sed "s/LAN_IP/$LANIP/g" ../../relay/Caddyfile.lan >Caddyfile + else + sed "s/^anybot.example.com {/$DOMAIN {/" ../../relay/Caddyfile >Caddyfile + fi + [ "$TS" = 2 ] && TS=0 + SKIP=1 +fi + if [ "${SKIP:-0}" != 1 ]; then # ---------- 1. the address ---------- - AT=1; MSG=""; TS=0; LAN=0; LANIP="" + AT=1; MSG=""; TS=0; LAN=0; LANIP=""; LANASKED=0 # On a tailnet: offer its address (HTTPS from Tailscale, no domain, nothing open to the internet). TSNAME=$(tailscale status --json 2>/dev/null | sed -n 's/.*"DNSName": *"\([^"]*\)\.".*/\1/p' | head -1) + # A tailnet that hands out no certificates (headscale; Tailscale with HTTPS off in its admin + # page) can't give https://its-name: offered was an address that never answered. Its own + # address works, with a certificate this server signs (as for the local network). + TSIP="" + if [ -n "$TSNAME" ] && ! tailscale status --json 2>/dev/null | tr -d ' \n' | grep -q '"CertDomains":\["'; then + TSIP=$(tailscale ip -4 2>/dev/null | head -1) + TSNAME="" + fi if [ "$AUTO" = 1 ] && [ -n "${ANYBOT_SETUP_DOMAIN:-}" ]; then DOMAIN=${ANYBOT_SETUP_DOMAIN#https://}; TSNAME=""; TS=2 is_ip "$DOMAIN" && { LAN=1; LANIP=$DOMAIN; } fi if [ "$AUTO" = 1 ] && [ -n "$TSNAME" ] && [ -n "${ANYBOT_SETUP_LAN_IP:-}" ]; then LAN=1; LANIP=$ANYBOT_SETUP_LAN_IP; fi + # Without questions and no address given: the tailnet's own address when it has no certificates. + if [ "$AUTO" = 1 ] && [ "$TS" = 0 ] && [ -z "$TSNAME" ] && [ -n "$TSIP" ]; then + DOMAIN=$TSIP; LAN=1; LANIP=$TSIP; TS=2 + fi if [ "$AUTO" = 1 ] && [ "$TS" = 0 ] && [ -z "$TSNAME" ]; then header; card_open "網址"; bad "這台沒有 Tailscale:請加上 ANYBOT_SETUP_DOMAIN=你的網域(或區網 IP)"; die fi # The local network's own address: HTTPS with a certificate this server signs itself. LANDESC="憑證是這台自己簽的:每台手機和電腦要先信任一次。位址要固定(在路由器設成固定 IP)" - if [ -n "$TSNAME" ]; then + if [ -n "$TSIP" ] && [ "$AUTO" = 0 ]; then + choose HOW "手機和其他電腦用哪個網址連到這台?" \ + "用 tailnet 位址:https://$TSIP|只有你 tailnet 裡的手機和電腦連得到,不用網域。這個 tailnet 不發 HTTPS 憑證(headscale,或 Tailscale 管理頁沒開 HTTPS),憑證由這台自己簽:每台手機和電腦先信任一次" \ + "只用區網 IP:https://$(lan_ip)|只有同一個區網連得到。$LANDESC" \ + "用自己的網域|任何地方都連得到(網域要先指到這台)" + case "$HOW" in + 0) LAN=1; LANIP=$TSIP; TS=2; LANASKED=1 ;; + 1) LAN=1; TS=2 ;; + esac + elif [ -n "$TSNAME" ]; then choose HOW "手機和其他電腦用哪個網址連到這台?" \ "用 Tailscale:https://$TSNAME|只有你 Tailscale 裡的手機和電腦連得到。不用網域,也不用開 80、443 埠" \ "Tailscale + 區網 IP:https://$(lan_ip)|在同一個區網用 IP 連,出門用 Tailscale。$LANDESC" \ @@ -280,7 +479,7 @@ if [ "${SKIP:-0}" != 1 ]; then "用自己的網域|任何地方都連得到(網域要先指到這台)" [ "$HOW" = 0 ] && { LAN=1; TS=2; } fi - while [ "$LAN" = 1 ] && [ "$AUTO" = 0 ]; do + while [ "$LAN" = 1 ] && [ "$AUTO" = 0 ] && [ "$LANASKED" = 0 ]; do header; card_open "這台在區網的 IP" note "手機和電腦在同一個區網打開 https://這個 IP。${LANDESC}。" line "" @@ -344,7 +543,9 @@ if [ "${SKIP:-0}" != 1 ]; then fi # Only this account (others can be let in later: ANYBOT_RELAY_INVITE in .env). AI keys are set # in the app (設定 › 模型); they stay on the brain. - INVITE=""; XAI=""; ANT=""; OAI=""; GEM=""; RESTORE="" + # (A server set up again keeps its invite and the manager's key: people still sign up with + # the same invite, and the cloud brains already made stay theirs.) + INVITE=${ANYBOT_RELAY_INVITE:-}; XAI=""; ANT=""; OAI=""; GEM=""; RESTORE="" q() { printf "%s='%s'\n" "$1" "$2"; } umask 077 @@ -385,6 +586,76 @@ if [ -n "$SOCK" ] && ! grep -qxF "DOCKER_SOCKET='$SOCK'" .env; then (umask 077; { grep -v '^DOCKER_SOCKET=' .env; printf "DOCKER_SOCKET='%s'\n" "$SOCK"; } >.env.new) \ && mv .env.new .env fi +own_files +# Every setup — and every update of an older one — has the manager's key (each account its cloud +# brain); one set up for a single account (ANYBOT_USER) keeps that account's own brain running +# as before (the owner-brain profile), next to the voice service when it is on. +if [ -f .env ] && [ "$DRY" = 0 ]; then + if ! grep -q "^ANYBOT_RELAY_MANAGER_TOKEN=['\"]\{0,1\}[0-9a-f]\{32,\}" .env; then + (umask 077; { grep -v '^ANYBOT_RELAY_MANAGER_TOKEN=' .env; printf "ANYBOT_RELAY_MANAGER_TOKEN='%s'\n" "$(gen_key)"; } >.env.new) && mv .env.new .env + fi + # Who asked is believed only from Caddy, which sends this secret — where Caddy is the only way + # in (Tailscale serve can't send it: there the account server believes it as before). An older + # Caddyfile (one written by hand too) gets the line that sends it, and caddy is made again so it + # reads it; one where that line can't go keeps the old way. + secret=1 + grep -q "^ANYBOT_TAILSCALE=['\"]\{0,1\}1" .env && secret=0 + [ -f Caddyfile ] || secret=0 + # (Spaces and tabs written out: the awk of older Debian and Ubuntu, mawk 1.3.3, has no + # [[:space:]] and would match nothing.) + ws="[ $(printf '\t')]" + block="^$ws*reverse_proxy$ws+relay:8080$ws*[{]$ws*\$" + oneline="^$ws*reverse_proxy$ws+relay:8080$ws*\$" + if [ "$secret" = 1 ] && ! grep -q 'X-AnyBot-Proxy' Caddyfile; then + # Only where every way to the account server is a block the line can go in (a one-line + # reverse_proxy, or none: the old way), each one got its line, and Caddy reads the file; + # written back into the same file (caddy has that one file mounted), the one before put back + # if that write fails half way. + blocks=$(grep -Ec "$block" Caddyfile || true) + if [ "${blocks:-0}" -gt 0 ] && ! grep -Eq "$oneline" Caddyfile \ + && awk -v re="$block" '{ print } $0 ~ re { print "\t\theader_up X-AnyBot-Proxy {$ANYBOT_PROXY_SECRET}" }' Caddyfile >Caddyfile.new \ + && [ "$(grep -c 'X-AnyBot-Proxy' Caddyfile.new)" = "$blocks" ] \ + && docker run --rm -e ANYBOT_PROXY_SECRET=check -v "$PWD/Caddyfile.new:/etc/caddy/Caddyfile:ro" caddy:2 caddy adapt --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null 2>&1 \ + && cp Caddyfile Caddyfile.before \ + && { cat Caddyfile.new >Caddyfile || { cat Caddyfile.before >Caddyfile; false; }; }; then + CADDY_PATCHED=1 + else + secret=0 + fi + rm -f Caddyfile.new Caddyfile.before + fi + if [ "$secret" = 1 ] && ! grep -q "^ANYBOT_PROXY_SECRET=['\"]\{0,1\}[0-9a-f]\{32,\}" .env; then + (umask 077; { grep -v '^ANYBOT_PROXY_SECRET=' .env; printf "ANYBOT_PROXY_SECRET='%s'\n" "$(gen_key)"; } >.env.new) && mv .env.new .env + elif [ "$secret" = 0 ] && grep -q '^ANYBOT_PROXY_SECRET=' .env; then + (umask 077; grep -v '^ANYBOT_PROXY_SECRET=' .env >.env.new) && mv .env.new .env + fi + owner=$(sed -n "s/^ANYBOT_USER=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" .env | tail -n 1) + # (Profiles put there by hand stay; only these two follow the settings.) + profiles=$(sed -n "s/^COMPOSE_PROFILES=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" .env | tr ',' '\n' | grep -v -x -e owner-brain -e voice -e '' | sort -u | paste -sd, - || true) + [ -n "$owner" ] && profiles="${profiles:+$profiles,}owner-brain" + grep -q '^ANYBOT_VOICE_URL=' .env && profiles="${profiles:+$profiles,}voice" + (umask 077; { grep -v '^COMPOSE_PROFILES=' .env; if [ -n "$profiles" ]; then printf "COMPOSE_PROFILES='%s'\n" "$profiles"; fi; } >.env.new) + if cmp -s .env.new .env; then rm -f .env.new; else mv .env.new .env; fi + own_files + # (What was taken out above or by hand is out for this start too: what was read earlier stays + # in this shell, and docker compose takes the shell's before the file's.) + unset ANYBOT_PROXY_SECRET COMPOSE_PROFILES ANYBOT_VOICE_URL ANYBOT_VOICE_LISTEN_MODEL ANYBOT_VOICE_SPEAK_MODEL ANYBOT_VOICE_VOICE + set -a; . ./.env; set +a +fi +# At boot Docker can be up before the address caddy listens on (a tailnet's comes up late): +# caddy then fails to start, and Docker doesn't try again — the server is gone until someone +# starts it. Letting the system take an address that isn't up yet keeps that from happening. +BINDFIX="" +if [ -n "${ANYBOT_LAN_IP:-}" ] && [ "$DRY" = 0 ] && command -v sysctl >/dev/null && [ "$(sysctl -n net.ipv4.ip_nonlocal_bind 2>/dev/null)" != 1 ]; then + fix="echo net.ipv4.ip_nonlocal_bind=1 >/etc/sysctl.d/90-anybot.conf && sysctl -q -p /etc/sysctl.d/90-anybot.conf" + if [ "$(id -u)" = 0 ]; then sh -c "$fix" 2>/dev/null || BINDFIX="sudo sh -c '$fix'" + elif ! sudo -n sh -c "$fix" 2>/dev/null; then + if [ "$START" = 0 ] && [ -t 0 ]; then + printf ' 讓這台重開機時一定綁得到 %s(要你的密碼):\n' "$ANYBOT_LAN_IP" + sudo sh -c "$fix" || BINDFIX="sudo sh -c '$fix'" + else BINDFIX="sudo sh -c '$fix'"; fi + fi +fi # ---------- 4. start ---------- AT=3; header; card_open "啟動" @@ -404,7 +675,18 @@ if [ -z "${ANYBOT_BUILD_JOBS:-}" ] && [ -r /proc/meminfo ]; then export ANYBOT_BUILD_JOBS=$j [ "$mem" -lt 3000 ] && warn "記憶體只有 ${mem} MB:編譯會比較久。被中斷的話先加 2 GB swap(見 docs/install.md)" fi -spin "建置並啟動(第一次約 5–15 分鐘)" docker compose up -d --build || die +spin "建置(第一次約 5–15 分鐘)" docker compose build || die +# (From here the manager's start line is this start's: one from before doesn't count.) +started=$(date -u +%Y-%m-%dT%H:%M:%SZ) +docker compose stop -t 120 brains >/dev/null 2>&1 || true +# (Stopped above: started again however this ends — a failed start, Ctrl-C — not left stopped.) +trap 'docker compose start brains >/dev/null 2>&1' EXIT +trap 'exit 130' INT TERM +spin "啟動" docker compose up -d || die +trap - EXIT INT TERM +if [ "${CADDY_PATCHED:-0}" = 1 ]; then + spin "Caddy 換上新設定" docker compose up -d --force-recreate --no-deps caddy || true +fi [ "${ANYBOT_TAILSCALE:-}" = 1 ] && TS=1 if [ "${TS:-0}" = 1 ]; then # Tailscale gives the address HTTPS and passes it to the account server (remembered across reboots). @@ -424,23 +706,39 @@ if [ "${TS:-0}" = 1 ]; then fi fi -# The brain joins the account (and makes it, the first time). +# The brain joins the account (and makes it, the first time) — a setup for one account. Set up +# the easy way there is no account yet: 大腦管理員 is up, waiting for the first sign-up. f=0; c=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏"); joined="" +manager="" +for _ in $(seq 1 200); do + mlogs=$(docker compose logs --no-color --since "$started" brains 2>/dev/null) + if docker compose ps --status running --services 2>/dev/null | grep -qx brains && printf '%s' "$mlogs" | grep -q "大腦管理員:每個帳號一個雲端大腦"; then manager=1; break; fi + printf '\r\e[K %s│%s %s%s%s 大腦管理員啟動中…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N"; f=$((f + 1)); sleep 0.3 +done +printf '\r\e[K' +if [ -n "$manager" ]; then ok "大腦管理員就緒:每個註冊的帳號會自動有自己的雲端大腦" +else + bad "大腦管理員沒有啟動。最近的紀錄:" + printf '%s\n' "$mlogs" | grep "大腦管理員" | tail -n 4 | while IFS= read -r l; do note " ${l#*| }"; done +fi +[ -z "${USERNAME:-}" ] && joined=$manager for _ in $(seq 1 600); do + [ -z "${USERNAME:-}" ] && break logs=$(docker compose logs --no-color anybot 2>/dev/null | tail -n 40) if printf '%s' "$logs" | grep -q "透過帳號"; then joined=1; break; fi printf '\r\e[K %s│%s %s%s%s 大腦正在登入帳號…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N"; f=$((f + 1)); sleep 0.3 done printf '\r\e[K' -if [ -n "$joined" ]; then +if [ -z "${USERNAME:-}" ]; then : +elif [ -n "$joined" ]; then printf '%s' "$logs" | grep -q "已建立帳號" && ok "建立帳號 ${USERNAME}" || ok "大腦「${BRAIN}」已登入帳號" else bad "大腦沒有登入帳號。最近的紀錄:" printf '%s\n' "$logs" | grep "AnyBot:" | tail -n 4 | while IFS= read -r l; do note " ${l#*| }"; done fi -# HTTPS from outside (the certificate can take a minute). -if [ "$DOMAIN" != "${LANIP:-}" ]; then +# HTTPS from outside (the certificate can take a minute). Not for an address kept as plain http. +if [ "$DOMAIN" != "${LANIP:-}" ] && [ "${ANYBOT_RELAY_PUBLIC_URL#http://}" = "${ANYBOT_RELAY_PUBLIC_URL:-}" ]; then https="" for _ in $(seq 1 120); do if curl -fsS --max-time 5 "https://$DOMAIN/api/hello" 2>/dev/null | grep -q anybot-relay; then https=1; break; fi @@ -463,8 +761,20 @@ if [ -n "${LANIP:-}" ]; then if [ -n "$lanok" ]; then ok "https://$LANIP 可以連(憑證:http://$LANIP/anybot-ca.crt)" else warn "https://$LANIP 還連不到(80/443 埠被防火牆擋住?)。看紀錄:deploy/server/setup.sh --logs caddy"; fi fi +# The address served over plain http (a tailnet's, the easy way's): what AnyBot and the phone open. +URL=${ANYBOT_RELAY_PUBLIC_URL:-https://$DOMAIN} +if [ "${URL#http://}" != "$URL" ]; then + plain="" + for _ in $(seq 1 60); do + if curl -fsS --max-time 5 "$URL/api/hello" 2>/dev/null | grep -q anybot-relay; then plain=1; break; fi + printf '\r\e[K %s│%s %s%s%s 等 %s…' "$D" "$N" "$A" "${c[$((f % 10))]}" "$N" "$URL"; f=$((f + 1)); sleep 1 + done + printf '\r\e[K' + if [ -n "$plain" ]; then ok "$URL 可以連"; else warn "$URL 還連不到(80 埠被防火牆擋住?)。看紀錄:deploy/server/setup.sh --logs caddy"; fi +fi if [ "$START" = 1 ]; then docker compose ps --format ' {{.Service}} {{.Status}}' 2>/dev/null | while IFS= read -r l; do note "$l"; done + [ -n "${BINDFIX:-}" ] && warn "重開機時可能綁不到 ${ANYBOT_LAN_IP:-}:執行 $BINDFIX" note "看紀錄:make server-logs" card_close [ -n "$joined" ]; exit $? @@ -473,6 +783,44 @@ card_close printf '\n' card_open "$([ -n "$joined" ] && echo "完成了" || echo "差一點")" +boot_line() { + [ -n "${BINDFIX:-}" ] && line "${B}開機${N} ${Y}重開機時可能綁不到 ${ANYBOT_LAN_IP:-}${N}:執行 $BINDFIX" + case "$BOOT" in + 1) line "${B}開機${N} 這台重開機後,帳號伺服器和每個雲端大腦會自己起來" ;; + unknown) ;; + *) line "${B}開機${N} ${Y}重開機後不會自己起來${N}:執行 $BOOTFIX" ;; + esac +} +# Set up the easy way: no account here — they are made in the app, each with its own cloud brain. +if [ -z "${USERNAME:-}" ]; then + line "${B}網址${N} ${A}$URL${N}" + line "${B}邀請碼${N} ${A}${ANYBOT_RELAY_INVITE:-}${N} 註冊要填(第一個人也要;給家人朋友也是這組)" + note " ${Y}先自己註冊${N}:第一個註冊的帳號是擁有者,只有它的雲端大腦有 Bot 的電腦(能動整台伺服器)" + note " ${Y}只給你信任的人${N}:每個帳號的雲端大腦能在這台伺服器的網路裡跑程式(連得到你的區網、tailnet)" + line "" + line "${B}電腦${N} 裝好 AnyBot 打開 →「登入帳號」→ 填上面的網址 →「註冊」" + note " 註冊好幾秒後就用上你自己的雲端大腦,這台電腦也自動是它的手腳" + line "${B}手機${N} 打開 ${A}$URL${N},登入同一個帳號(可以「加入主畫面」)" + if [ "${URL#http://}" != "$URL" ] && [ -n "${LANIP:-}" ]; then + note " 要手機通知:先打開 http://$LANIP/anybot-ca.crt 安裝並信任,再改用 https://$LANIP" + elif [ -n "${LANIP:-}" ]; then + line "${B}信任憑證${N} 每台電腦和手機先打開 ${A}http://$LANIP/anybot-ca.crt${N} 安裝它(一次就好)" + note " iPhone:裝好描述檔後,到 設定 › 一般 › 關於本機 › 憑證信任設定 打開它" + note " Mac:在「鑰匙圈存取」把它設成「永遠信任」;Linux:放進 /usr/local/share/ca-certificates/ 再執行 update-ca-certificates" + fi + if [ "$ROOTDOCKER" = 1 ] && [ "${TS:-0}" != 1 ] && ! is_ip "$DOMAIN"; then + line "${B}安全${N} ${Y}對外公開的網域${N}:Docker 用 root 在跑,伺服器萬一被攻破,對方等於拿到整台主機。" + note " 建議改用 rootless Docker:https://docs.docker.com/engine/security/rootless/" + fi + boot_line + line "${B}AI 金鑰${N} 第一次聊天前:AnyBot › 設定 › 模型(只存在你的雲端大腦上)" + line "" + note "看紀錄 make server-logs(大腦管理員:deploy/server/setup.sh --logs brains)" + note "更新 make update-server" + card_close + printf '\n' + exit 0 +fi line "${B}手機${N} 打開 ${A}https://$DOMAIN${N},用 ${B}$USERNAME${N} 登入,可以「加入主畫面」" if [ -n "${LANIP:-}" ]; then [ "$DOMAIN" != "$LANIP" ] && line "${B}區網${N} 也可以打開 ${A}https://$LANIP${N}(同一個區網)" @@ -480,7 +828,13 @@ if [ -n "${LANIP:-}" ]; then note " iPhone:裝好描述檔後,到 設定 › 一般 › 關於本機 › 憑證信任設定 打開它" note " Mac:在「鑰匙圈存取」把它設成「永遠信任」;Linux:放進 /usr/local/share/ca-certificates/ 再執行 update-ca-certificates" fi -line "${B}電腦${N} AnyBot › 設定 › 一般 › 手機與帳號 登入,在「大腦」選「${BRAIN}」" +line "${B}電腦${N} 打開 AnyBot,歡迎畫面按「登入帳號」(已經在用:設定 › 一般 › 手機與帳號)," +line " 填 ${A}https://$DOMAIN${N} 和 ${B}$USERNAME${N}:登入後就用「${BRAIN}」當大腦" +if [ "$ROOTDOCKER" = 1 ] && [ "${TS:-0}" != 1 ] && ! is_ip "$DOMAIN"; then + line "${B}安全${N} ${Y}對外公開的網域${N}:Docker 用 root 在跑,大腦萬一被攻破,對方等於拿到整台主機。" + note " 建議改用 rootless Docker:https://docs.docker.com/engine/security/rootless/" +fi +boot_line line "${B}AI 金鑰${N} 手機或電腦的 AnyBot › 設定 › 模型(只存在大腦上)" line "${B}加一台電腦${N} 手機 AnyBot 右上 ⋯ › 加一台電腦,把那一行貼到那台的終端機" line "" diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index 979b735..887c3af 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -114,6 +114,7 @@ Bot 讀得到的是開頭、子功能、使用者怎麼到、Bot 那一行和沒 - [phone](phone.md):手機頁面、手機上的卡、長相與顏色、裝成 App。 - [phonefit](phonefit.md):手機畫面貼齊:主畫面 App 自己量螢幕,iOS 少給下面一條時讓開上面的霧面、不重複留底;鍵盤收起沒長回來就重排;設定 › 更新 › 畫面的量尺。 - [account](account.md):AnyBot 帳號、備份、大腦、同一個網路直接連、推播通知。 +- [server](server.md):一行裝好的伺服器、邀請碼、每個帳號自己的雲端大腦、註冊後等大腦、開機自己回來。 ### 管住它、調整它 - [safety](safety.md):允許請求、拒絕、一律允許、「在這台電腦上執行」、鎖定、關卡順序。 diff --git a/docs/feature-map/models.md b/docs/feature-map/models.md index 47bba12..ce8886b 100644 --- a/docs/feature-map/models.md +++ b/docs/feature-map/models.md @@ -6,11 +6,11 @@ - `models-providers` 供應商:xAI Grok、OpenAI、ChatGPT 方案、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama、自訂(OpenAI 相容),每個 Bot 各選各的。 - `models-where` 在哪裡跑:每家依服務網址標「本機」(localhost)、「區網」(私有位址、tailnet、.local、沒有點的名字)或「雲端」(其他;分不出來也算雲端),本機、區網是綠字。標在:設定 › 模型 每列右邊、標題下一句(在哪台跑、會不會送出去);Bot 設定「AI 供應商與模型」;聊天頂端名字後面;空聊天的模型那行;+ 的模型選單每家後面;手機上同樣這些地方。螢幕電腦和手機上,「本機」是大腦那台。只看網址、不查名字。 -- `models-switch` 換模型:資料、記憶、聊天都不用動;換過之後的第一個回答前面,聊天裡留一行「改用 ○○ 回答(上一個回答是 ○○)」(從哪裡換的都一樣;不送給模型;群組聊天不寫)。正在跑的那一輪照舊。換過去的第一個請求先把舊步驟的結果收起(要用再讀);另一個模型的思考內容不會送過去(它會拒絕);模型說過的可讀長度各記各的。 -- `models-fallback` 備用模型(Bot 設定,最多 8 個,依序):Bot 自己的模型額度用完(402、「已達用量上限」)、太忙(429)、金鑰或登入不能用(401、403)、服務出錯(5xx)或連不上,換下一個還沒休息的,從同一步接著做,聊天裡一行「改用 ○○ 繼續(○○:原因,10 分鐘內先不用它)」。不能用的休息 10 分鐘,這段時間新的一輪直接用備用(「改用 ○○ 回答(○○ 剛剛不能用…)」)。對話太長、不支援工具、模型名稱錯不換;沒金鑰的跳過;換過去不用思考和快速模型。手機這兩行是星星圖示。 +- `models-switch` 換模型:資料、記憶、聊天都不用動;換過之後的第一個回答前面,聊天裡留一行「改用 ○○ 回答(上一個回答是 ○○)」(不送給模型;群組聊天不寫)。正在跑的那一輪照舊。換過去的第一個請求先把舊步驟的結果收起(要用再讀);思考內容只送回寫它的模型,之前的歷史對不上就不用那段思考、照樣回答(不會整輪停在「Invalid signature in thinking block」);模型說過的可讀長度各記各的。 +- `models-fallback` 備用模型(Bot 設定,最多 8 個,依序):Bot 自己的模型額度用完(402、「已達用量上限」)、太忙(429)、金鑰或登入不能用(401、403)、服務出錯(5xx)或連不上,換下一個還沒休息的,從同一步接著做,聊天裡一行「改用 ○○ 繼續(○○:原因,10 分鐘內先不用它)」。不能用的休息 10 分鐘,這段時間新的一輪直接用備用(「改用 ○○ 回答(○○ 剛剛不能用…)」)。對話太長、不支援工具、模型名稱錯不換;沒金鑰的跳過;換過去不用思考和快速模型。 - `models-bot` 「AI 供應商與模型」(Bot 設定裡):供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」、「備用模型」——欄位名稱在上,說明在名稱旁的「?」。 - `models-thinking` 思考模式:「自動(模型自己決定)」「快速(想得少,回得快)」「平衡」「深入(想得久,較慢)」。執行步驟用的模型:「自動」、「不分開(每一步都用上面的模型)」或指定一個;上面的模型負責想計畫、遇到問題和最後確認,中間的步驟交給快的模型。 -- `models-chatgpt` 「ChatGPT 方案」:用 ChatGPT 帳號登入(OpenAI 的 Sign in with ChatGPT),用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰。第一次登入時 AnyBot 向 OpenAI 註冊自己,之後重用;登入後 設定 › 模型 寫「已用 ChatGPT 登入(信箱)」,第一次回答會說一次「你正在使用你的 ChatGPT 方案」。 +- `models-chatgpt` 「ChatGPT 方案」:用 ChatGPT 帳號登入(OpenAI 的 Sign in with ChatGPT),用你 ChatGPT 方案(Plus、Pro、Business…)的額度,不用 API 金鑰。登入後 設定 › 模型 寫「已用 ChatGPT 登入(信箱)」,第一次回答會說一次「你正在使用你的 ChatGPT 方案」。 ## 使用者怎麼到 diff --git a/docs/feature-map/server.md b/docs/feature-map/server.md new file mode 100644 index 0000000..cf459c6 --- /dev/null +++ b/docs/feature-map/server.md @@ -0,0 +1,43 @@ +# 伺服器與雲端大腦 + +一行裝好的 AnyBot 伺服器:帳號伺服器、每個帳號自己的雲端大腦、HTTPS。裝的時候不問問題;帳號在電腦或手機的 AnyBot 註冊,幾秒後那個帳號就有自己的雲端大腦,電腦登入後自動當它的螢幕和手腳(遠端+地端)。 + +## 子功能 + +- `server-install` 安裝:在 Linux 上貼一行 `install.sh … server`。沒有 Docker 就裝(設成開機自動跑),系統套件(含 `make`)、原始碼、建置、啟動都自己來,不問問題。剛加進 docker 群組的使用者用 `sg` 執行,寫出來的 `.env`、`Caddyfile`、`~/.docker` 是那個人的;之前用 sudo 留下的 root 檔案自己改回來,改不了說確切的指令。最後印出網址和邀請碼。 +- `server-address` 網址自己找:給了 `ANYBOT_SETUP_DOMAIN` 就用它(網域:自動申請憑證;IP:那個 IP);否則 Tailscale 有發憑證時用 https://它的名字;tailnet 不發憑證(headscale)時用 http://tailnet 位址(WireGuard 已經加密,AnyBot 只在 tailnet 上收 http;任何指到這台的名字也通;https 也在,手機通知用);都沒有就用 https://區網 IP(這台自己簽的憑證:每台電腦和手機先開 http://位址/anybot-ca.crt 信任一次)。位址在網路上是公開的(VPS)又沒給網域:停下來,請你給網域或裝 Tailscale,不把帳號用明文開在網路上。綁在某個位址時,讓系統可以先綁還沒出現的位址(`net.ipv4.ip_nonlocal_bind`),重開機時 tailnet 比 Docker 晚起來也綁得到。 +- `server-invite` 邀請碼:安裝時產生,註冊都要填,第一個人也要(免得先連到的人變成擁有者);在 `deploy/server/.env` 的 `ANYBOT_RELAY_INVITE`。沒填或填錯不能註冊。完成畫面提醒先自己註冊再給別人(第一個註冊的帳號是擁有者),而且只給信任的人:每個帳號的雲端大腦都能在這台伺服器的網路裡跑程式(連得到它的區網、tailnet)。 +- `server-brains` 每個帳號一個雲端大腦:大腦管理員看到新帳號就開一個(`anybot-brain-帳號`),有自己的資料;用帳號伺服器發的登入憑證,伺服器上不存密碼。只有擁有者(第一個註冊的帳號,管理員第一次看到就記住)和 `ANYBOT_BRAINS_DOCKER` 列的帳號,雲端大腦有 Docker,也就有自己的 Bot 電腦和它的家目錄——能動 Docker 等於能動整台伺服器(讀得到別人的大腦);其他帳號的雲端大腦沒有,用自己的電腦當手腳。大腦上可以跑帳號主人的指令(hook、連接器),所以每個大腦都不能偽造或偷聽網路封包(沒有 NET_RAW、不能提升權限),有記憶體、CPU 和程序數的上限,最多 `ANYBOT_BRAINS_MAX`(預設 20)個;管理員跟帳號伺服器講話走自己的網路,金鑰不經過大腦們的網路;帳號伺服器只相信 Caddy(帶著 `.env` 的 `ANYBOT_PROXY_SECRET`)說的請求來源,大腦直接連進去寫的不算。要停掉某個帳號的雲端大腦:`.env` 的 `ANYBOT_BRAINS_SKIP` 加它、`make update-server`,再 `docker stop` 它(管理員不再叫醒)。停掉的會叫醒;伺服器更新後(映像檔或開法變了)先讓它收尾再換成新版(同一份資料、同一個登入),新的建不起來就放回原本的;帳號伺服器不再認得它的登入時換一個新的;不刪任何大腦和資料。管理員第一次啟動以前就有的帳號(舊伺服器更新上來的)不開(`ANYBOT_BRAINS_ALL=1` 才開);不取代帳號裡不是它開的同名電腦,用帳號登入的電腦也不能取代它開的大腦。舊的單一帳號伺服器(`.env` 有 `ANYBOT_USER`)原本的大腦照舊。 +- `server-join` 註冊或登入後:伺服器會開雲端大腦(管理員最近一分鐘有在跑)時,電腦先等它上線(「正在等你的雲端大腦開好(第一次約半分鐘)…」,最多約一分半)再當它的螢幕,不把自己當大腦;這台原本的 Bot 搬過去,這台也是它的手腳。雲端大腦還沒有 Bot 時,電腦是歡迎畫面、手機是「還沒有 Bot」,照著建第一個。 +- `server-boot` 開機與更新:Docker 開機就跑(rootless 也打開 linger),帳號伺服器、大腦管理員和每個雲端大腦都跟著回來;檢查那一步寫「開機會自己啟動」,開不了說指令。更新用 `make update-server`;舊的伺服器更新時會補上大腦管理員的金鑰。 + +## 使用者怎麼到 + +- 伺服器:`curl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh | sh -s -- server`;之後在原始碼資料夾 `make update-server`、`make server-logs`(管理員:`deploy/server/setup.sh --logs brains`);要問問題的舊流程:`deploy/server/setup.sh --ask`。 +- 電腦:歡迎畫面「登入帳號」(已經在用:設定 › 一般 › 帳戶 › 登入),填網址,勾「建立新帳號」填邀請碼。 +- 手機:打開網址,註冊或登入同一個帳號([account](account.md))。 + +## 怎麼操作(verify-anybot) + +- Bot:沒有裝伺服器、開大腦的工具;雲端大腦裡的 Bot 照常用 [computers](computers.md) 列的電腦。 + +前提: + +- scratch 走不到:要一台可以清掉、有 systemd 的 Linux 和它自己的 Docker。實測用 root Docker 裡的 Ubuntu 24.04 容器(`--privileged`,`/var/lib/docker`、`/var/lib/containerd` 放在 volume),裡面放這份原始碼。 + +- **一行裝好**(covers `server-install`、`server-address`、`server-invite`、`server-boot`):以一般使用者執行、不給任何環境變數。指令:`sh AnyBot/install.sh server`,再 `cd AnyBot && PULL=0 make update-server`。看到:沒有問題;完成畫面只有網址、邀請碼、電腦和手機怎麼連、「開機:…會自己起來」;`.env`、`Caddyfile`、`~/.docker` 是那個使用者的;更新也過。 +- **註冊就有大腦**(covers `server-brains`、`server-invite`):用邀請碼註冊兩個帳號(第一個是擁有者)。指令:`curl -s -X POST 網址/relay/signup -d '{"user":"amy","password":"…","invite":"邀請碼"}'`(bob 同樣),再 `docker ps --filter label=anybot.brain.user` 和各自登入後的 `GET /relay/me`。看到:各自的雲端大腦幾秒內出現、資料卷各一份;只有擁有者的有 Bot 的電腦(標籤 `anybot.brain.docker=1`、連得到 docker-socket-proxy),另一個連不到 Docker;各自只看得到自己的、在線上;沒有或錯的邀請碼 403。換了映像檔(更新後重建),大腦換成新版、登入照舊;刪掉大腦容器,管理員再開一個、用原本的資料。 +- **電腦註冊後等大腦**(covers `server-join`):指令:`ANYBOT_RELAY_URL=… ANYBOT_RELAY_INVITE=… cargo test --bin anybot a_new_account_on_a_brains -- --ignored --nocapture`。看到:說「正在等你的雲端大腦開好」,幾秒後找到「雲端大腦」,沒有拿備份。 +- **重開機**(covers `server-boot`):把那台重開。指令:`sudo reboot`(測試容器:`docker restart 容器`),再 `curl 網址/api/hello` 和各自的 `GET /relay/me`。看到:帳號伺服器、大腦管理員和每個雲端大腦自己回來、在線上。 +- 自動測試:`cargo test brains::`、`cargo test --bin anybot a_new_account_waits_for_its_cloud_brain a_cloud_brain_signs_in`、`relay/` 裡 `cargo test the_brain_manager`。 + +## 陷阱 + +- 舊的伺服器(`.env` 有 `ANYBOT_USER`、沒有 `ANYBOT_RELAY_INVITE`)不開放註冊:要讓別人註冊,在 `.env` 加 `ANYBOT_RELAY_INVITE` 再 `make update-server`。 +- 大腦管理員的 API(`/relay/manager/…`)只給伺服器裡面的管理員:沒有金鑰、或經過前面的 Caddy 進來,一律 404。 +- `Caddyfile` 是單一檔案掛進 caddy:換了檔案要重開 caddy 容器,`caddy reload` 讀到的還是舊的。 +- 雲端主機(AWS、GCP…)網卡上是私有 IP:自動找到的 https://10.x 從外面連不到,要用 `ANYBOT_SETUP_DOMAIN=網域`。 +- 有 Docker 的雲端大腦不只一個時(`ANYBOT_BRAINS_DOCKER`),它們的 Bot 電腦會搶同一個連接埠,第二個開不起來。 +- 簡單裝的伺服器在 `make server` 選「重新設定」:照樣不問問題、重找網址,邀請碼和雲端大腦都留著。 +- (驗證)測試容器裡的 Docker 要把 `/var/lib/containerd` 放在 volume,否則建置時 overlay 掛不上;不要拿正式伺服器的 Docker 試。 +- (驗證)用 SSH 通道從別台連進測試機時,http 那段接受任何名字,https 只認那個位址。 diff --git a/docs/multi-device.md b/docs/multi-device.md index b6c49ca..df3206d 100644 --- a/docs/multi-device.md +++ b/docs/multi-device.md @@ -39,7 +39,7 @@ curl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh | sh -s -- server ``` -只問幾件事:網域、帳號、密碼,以及要不要在這台架語音服務。會自動申請 HTTPS 憑證、建立帳號、啟動大腦。完成畫面會告訴你手機和電腦怎麼連。之後在伺服器上執行 `cd ~/AnyBot && make server`,可以選「用現有設定,更新並重新啟動」或「加上/拿掉語音服務」;平常更新用 `make update-server`。 +不問任何問題:沒有 Docker 就裝好並設成開機自動跑,網址自己找(Tailscale 有憑證用 `https://名字`;headscale 這類不發憑證的 tailnet 用它的位址;都沒有用區網 IP;`ANYBOT_SETUP_DOMAIN=網域` 指定網域),最後印出網址和**邀請碼**。帳號不在伺服器上建:打開 AnyBot →「登入帳號」→ 填網址 → 勾「建立新帳號」填邀請碼。註冊好幾秒後,伺服器的大腦管理員就替這個帳號開好**它自己的雲端大腦**(自己的資料、自己的 Bot 電腦),電腦自動當它的螢幕和手腳;家人朋友用同一組邀請碼註冊,也各有自己的。之後在伺服器上 `cd ~/AnyBot && make update-server` 更新;要舊的問答流程(指定網域、單一帳號、語音服務):`deploy/server/setup.sh --ask`。 **語音服務**(選配):在這台的 CPU 上用 Whisper([speaches](https://speaches.ai),large-v3-turbo)把說的話轉成文字,每台電腦和手機的麥克風都用它,不用金鑰、不花錢。第一次下載約 1.6 GB 的模型;11 秒的中文約 3.5 秒轉完(12 核測得)。想快一點:設定前 `ANYBOT_VOICE_LISTEN_MODEL=Systran/faster-whisper-small`(約快三倍,偶爾錯一個字)。它只開在伺服器內部,不對外。朗讀(把回答唸出來)它目前不會中文,請在 App 的 設定 › 語音 › 說 選 xAI 之類的服務。不用問題的設定方式加 `ANYBOT_SETUP_VOICE=1`。 diff --git a/docs/plan-2026-11-install.md b/docs/plan-2026-11-install.md new file mode 100644 index 0000000..9ebdb68 --- /dev/null +++ b/docs/plan-2026-11-install.md @@ -0,0 +1,93 @@ +# 安裝流程計畫(2026-11):server 和 App 各裝一次就能用 + +> 依據:使用者 2026-11-23 全新安裝的回饋——「在 server 上要好多步,還要 Claude 幫我」: +> 1. 不會自動建立 server;2. 不會自動安裝 Docker;3. 裝好 server 不會自己開出連得上的大腦; +> 4. 裝完 server 還要自己建帳號(先有雞還是先有蛋);5. 要傻瓜安裝,中間設定太複雜。 +> 以及「server 啟動要自動為每個註冊的帳號用上雲端大腦,這樣既有遠端也有地端」。 +> 實測:一台全新的 Ubuntu 24.04(nobledesktop 上 root Docker 裡的隔離容器,有 systemd、沒有 Docker) +> 照 README 跑 `install.sh server`(見「實測」)。 +> +> 狀態標記:✅ 做完(附 commit)、🚧 進行中、⬜ 還沒做。 + +--- + +## 目標:使用者看到的流程 + +| 步驟 | 在哪裡 | 發生什麼 | +|---|---|---| +| 1 | server | 貼一行 `curl … install.sh \| sh -s -- server`,**什麼都不問**。沒有 Docker 就裝好,設成開機自動啟動。 | +| 2 | 同上 | 網址自己抓:tailnet(Tailscale 有憑證用 https 名字;headscale 用 tailnet 位址)優先,沒有就區網 IP。 | +| 3 | 同上 | 最後印出:網址、**邀請碼**(第一個註冊的人也要它,免得別人搶先成為擁有者)。 | +| 4 | Mac/手機 | 裝 App → 打開 →「登入帳號」→ 填網址 → 沒帳號就「註冊」(填邀請碼)。 | +| 5 | server(自動) | 每個註冊的帳號,大腦管理員幾秒內替它起一個**雲端大腦**(自己的資料、自己的 Bot 電腦)。 | +| 6 | Mac(自動) | 註冊/登入後等雲端大腦上線,自動當它的螢幕;這台也自動是它的手腳(遠端+地端)。 | +| 7 | 第一次聊天 | 大腦還沒有模型:照現在的提示到 設定 › 模型 貼金鑰(存在大腦上)。 | + +順序固定:**server 先裝 → 帳號在 App 裡註冊 → 雲端大腦自動出生**。任何時候都不用先有帳號才能裝 server。 + +## 架構 + +- **帳號伺服器(relay)**:註冊照舊;`ANYBOT_RELAY_INVITE` 由 setup 自動產生(設了它,第一個帳號也要它)。 + 新增管理員 API(`/relay/manager/…`):列出帳號、替帳號發雲端大腦的登入憑證(host token)。 + 只認 `ANYBOT_RELAY_MANAGER_TOKEN`,而且只接受伺服器內部直接來的請求(經 Caddy 進來的一律 404)。 +- **大腦**:除了帳號密碼,也能用帳號伺服器發的憑證啟動(`ANYBOT_HOST_TOKEN`、`ANYBOT_HOST_ID`), + 密碼不用留在 server 上。 +- **大腦管理員**(`anybot --brains`,compose 的 `brains`):每幾秒看一次帳號清單,沒有雲端大腦的帳號就 + `docker run` 一個 `anybot-brain-<帳號>`(同一個映像、自己的資料卷、自己的 Bot 電腦名字、`restart: unless-stopped`), + 已經有的確保在跑。它透過 docker-socket-proxy 動 Docker,跟大腦建 Bot 電腦一樣。 +- **舊的 server**(`.env` 有 `ANYBOT_USER`,例如 nobledesktop):原本的 `anybot` 大腦照舊,管理員不替那個帳號 + 再開一個;之後新註冊的帳號才由管理員開。 +- **App**:註冊/登入的伺服器說它會開雲端大腦(`/api/hello` 的 `brains: true`)時,等那個大腦上線(最多約一分鐘) + 再決定,不會先把自己當成大腦。 + +## 實測(全新 Ubuntu 24.04,舊流程) + +| 步驟 | 結果 | +|---|---| +| 系統套件、裝 Docker(get.docker.com) | ✓ 裝好、開機啟動,約 1 分鐘 | +| 下載原始碼 | ✓ | +| 檢查 | ✓,但跳一條「Docker 用 root 身分在跑…建議改用 rootless」,沒說要不要管、怎麼做 | +| 第一次設定 | 用 `sudo` 跑(剛加進 docker 群組,下次登入才算):`.env`、`Caddyfile`、`~/.docker` 都變成 root 的 | +| 再跑一次(或之後 `make update-server`) | ✗ `.env: Permission denied`、`unbound variable`;修了 `.env` 再來是 `~/.docker/buildx/.lock: permission denied` | +| 修好權限後 | ✓ 建置約 14 分鐘、建立帳號、`https://IP` 連得上;但完成畫面要每台裝置手動信任憑證、自己去登入 | + +(測試容器自己的問題不算:容器裡的 Docker 要把 `/var/lib/containerd` 放在真的磁碟上。) + +nobledesktop 的 tailnet 是 headscale,不發 HTTPS 憑證(`CertDomains` 是空的),舊的 `setup.sh` 卻給 +「用 Tailscale:https://名字」——永遠連不上;現在的 `http://100.64.0.5` 是手改的。 + +## 要做的 + +### S1. 第一次設定不再用 sudo 跑 ✅(實測) +- `install.sh`:剛加進 docker 群組時用 `sg docker` 以使用者身分跑 `setup.sh`(沒有 `sg` 才用 sudo)。 +- `setup.sh`:用 sudo 跑時寫好的檔案交還使用者;之前留下的 root 檔案(`.env`、`Caddyfile`、`~/.docker`)自己改回來。 + +### S2. 開機自動啟動 ✅(實測:重開後全部自己回來;綁位址用 ip_nonlocal_bind) +- root Docker 看 `systemctl is-enabled docker`;rootless 看 `systemctl --user is-enabled docker` 和 linger;沒開就開。 + +### S3. 什麼都不問的 setup ✅(實測) +- 網址自動(tailnet 優先;headscale 用 tailnet 位址走 http——WireGuard 已經加密;區網 IP 用自簽 https,要先信任憑證,S8 做完才免;公開位址沒有網域就停下來); + `ANYBOT_SETUP_DOMAIN` 才用網域。邀請碼、管理員憑證自動產生;語音預設不裝(之後 `make server` 加)。 +- 完成畫面只有:網址、邀請碼、「打開 AnyBot › 登入帳號 › 註冊」,加上開機自動啟動的結果。 + +### S4. 帳號伺服器的管理員 API ✅ +### S5. 大腦用憑證啟動 ✅ +### S6. 大腦管理員 ✅(只有擁有者的大腦有 Docker——審查 P0:能動 Docker 等於能動整台伺服器) +### S7. App 註冊後等雲端大腦 ✅(實測:6 秒找到) +### S8. App 自己信任伺服器自簽的憑證(區網 https)⬜ +- 登入時連不上是因為自簽憑證:抓 `http://位址/anybot-ca.crt`,顯示指紋請人按「信任這台伺服器」,只對這個網址記住。 + +### S9. 裝 server 時這台也當手腳 ⬜ +- 管理員開好大腦後,可選擇在這台裝手腳(配對碼由大腦產生)。 + +## 驗證 + +在全新測試機(同上)從頭:`install.sh server`(不回答任何問題)→ 用 scratch App 註冊(邀請碼)→ +雲端大腦幾秒內出現、上線 → scratch App 自動當它的螢幕、聊得了天 → 再註冊第二個帳號,也有自己的大腦 → +重開測試機,兩個大腦自己回來。 + +## 不做的 + +- 不另外寫開機腳本(systemd unit 包 docker compose):開機靠 Docker 自己的 `restart: unless-stopped` + 加上 Docker 本身開機啟動;多包一層可能開到另一套 Docker(root/rootless 兩套並存時出過事)。 +- 不讓帳號伺服器自己動 Docker:它對外,給它 Docker 等於把整台主機交出去;改由內部的大腦管理員做。 diff --git a/install.sh b/install.sh index 9e9b418..6d51d8c 100755 --- a/install.sh +++ b/install.sh @@ -352,7 +352,7 @@ linux_packages() { case $PM in apt-get) case $1 in - server) pkgs_in="curl ca-certificates git" ;; + server) pkgs_in="curl ca-certificates git make" ;; build) pkgs_in="build-essential pkg-config git curl ca-certificates libasound2-dev|libasound-dev" ;; # 手腳:虛擬螢幕、視窗管理員、輔助使用(讀按鈕)、session bus。各發行版名字不同,有的才裝。 hands) pkgs_in="build-essential pkg-config git curl ca-certificates libasound2-dev|libasound-dev libasound2t64|libasound2 xvfb openbox at-spi2-core libatk-adaptor dbus-x11 dbus-user-session dbus xauth fonts-noto-cjk fonts-noto-cjk-extra" ;; @@ -377,7 +377,7 @@ linux_packages() { extra="" [ "$1" = app ] && extra="libxkbcommon libxkbcommon-x11 mesa-libGL mesa-libEGL vulkan-loader libwayland-client libX11 libXcursor libXi libXrandr xdg-utils libnotify libsecret espeak-ng zenity xclip wl-clipboard ffmpeg-free google-noto-sans-cjk-fonts gtk3" [ "$1" = hands ] && extra="xorg-x11-server-Xvfb openbox at-spi2-core at-spi2-atk dbus-x11 xorg-x11-xauth google-noto-sans-cjk-fonts" - [ "$1" = server ] && base="curl git ca-certificates" && extra="" + [ "$1" = server ] && base="curl git ca-certificates make" && extra="" [ "$1" = build ] && extra="" picked=$(dnf_pick "$PM" $base $extra | tr '\n' ' ') [ -n "$picked" ] || picked="$base $extra" @@ -388,7 +388,7 @@ linux_packages() { base="base-devel git curl alsa-lib" [ "$1" = app ] && base="$base libxkbcommon libxkbcommon-x11 mesa vulkan-icd-loader wayland libx11 libxcursor libxi libxrandr xdg-utils libnotify libsecret espeak-ng zenity xclip wl-clipboard ffmpeg noto-fonts-cjk gtk3" [ "$1" = hands ] && base="$base xorg-server-xvfb openbox at-spi2-core dbus xorg-xauth noto-fonts-cjk" - [ "$1" = server ] && base="curl git ca-certificates" + [ "$1" = server ] && base="curl git ca-certificates make" $SUDO pacman -Sy --needed --noconfirm $base || die "安裝系統套件失敗。" "sudo pacman -S --needed $base" ;; zypper) @@ -396,7 +396,7 @@ linux_packages() { extra="" [ "$1" = app ] && extra="libxkbcommon0 libxkbcommon-x11-0 Mesa-libGL1 libGL1 xdg-utils libnotify-tools libsecret-1-0 espeak zenity xclip wl-clipboard ffmpeg fonts-noto gtk3-tools" [ "$1" = hands ] && extra="xorg-x11-server-Xvfb openbox at-spi2-core at-spi2-atk-common dbus-1-x11 xauth fonts-noto" - [ "$1" = server ] && base="curl git ca-certificates" && extra="" + [ "$1" = server ] && base="curl git ca-certificates make" && extra="" pkgs=$(zypper_pick $base $extra) $SUDO zypper -n install $pkgs || die "安裝系統套件失敗。" "sudo zypper install $pkgs" ;; @@ -405,7 +405,7 @@ linux_packages() { extra="" [ "$1" = app ] && extra="alsa-lib libxkbcommon libxkbcommon-x11 mesa-egl mesa-gl libx11 libxcursor libxi libxrandr wayland-libs-client xdg-utils libnotify font-noto-cjk ffmpeg gtk+3.0" [ "$1" = hands ] && extra="xvfb openbox at-spi2-core dbus xauth font-noto-cjk" - [ "$1" = server ] && base="curl git ca-certificates" && extra="" + [ "$1" = server ] && base="curl git ca-certificates make" && extra="" $SUDO apk update >/dev/null || warn "apk update 有錯誤,繼續試試看" picked=$(apk_pick $base $extra | tr '\n' ' ') [ -n "$picked" ] || picked="$base $extra" @@ -417,7 +417,7 @@ linux_packages() { extra="" [ "$1" = app ] && extra="alsa-lib libxkbcommon libxkbcommon-x11 MesaLib wayland libX11 libXcursor libXi libXrandr xdg-utils libnotify font-noto-cjk ffmpeg gtk+3" [ "$1" = hands ] && extra="xorg-server openbox at-spi2-core dbus font-noto" - [ "$1" = server ] && base="curl git" && extra="" + [ "$1" = server ] && base="curl git make" && extra="" $SUDO xbps-install -S || warn "xbps-install -S 有錯誤,繼續試試看" picked=$(xbps_pick $base $extra | tr '\n' ' ') [ -n "$picked" ] || picked="$base $extra" @@ -685,12 +685,23 @@ case $MODE in step "原始碼" find_source step "設定和啟動" - info "接下來會問網址、帳號、密碼。免問:ANYBOT_SETUP_USER、ANYBOT_SETUP_PASSWORD、ANYBOT_SETUP_DOMAIN。" + info "不用回答任何問題:網址自己找,帳號在 AnyBot 裡註冊(每個帳號自動有雲端大腦)。指定網域或 IP:ANYBOT_SETUP_DOMAIN=…" cd "$SRC/deploy/server" - IN=$TTY - if [ -n "${ANYBOT_SETUP_USER:-}" ] && [ -n "${ANYBOT_SETUP_PASSWORD:-}" ]; then IN=/dev/null - else [ -n "$TTY" ] || die "需要一個終端機回答問題。" "在伺服器上直接執行,或用 ANYBOT_SETUP_USER、ANYBOT_SETUP_PASSWORD(不給網域就用 Tailscale)。"; fi + # (The first setup asks nothing; one run again in a terminal offers to keep or change it.) + IN=${TTY:-/dev/null} + if [ -n "${ANYBOT_SETUP_USER:-}" ] && [ -n "${ANYBOT_SETUP_PASSWORD:-}" ]; then IN=/dev/null; fi if [ "${DOCKER_SUDO:-0}" = 1 ]; then + # Just put in the docker group (it counts from the next login): the setup runs as this user + # with that group now (sg), so what it writes — .env, Caddyfile, ~/.docker — stays this + # user's. Under sudo they were root's, and every later run as the user (make update-server, + # the same line again) stopped at "Permission denied". sudo only where there is no sg. + if have sg && sg docker -c 'docker info' >/dev/null 2>&1; then + args="" + for a in ${SAVED_1:+"$SAVED_1"} ${SAVED_2:+"$SAVED_2"}; do + args="$args '$(printf '%s' "$a" | sed "s/'/'\\\\''/g")'" + done + exec sg docker -c "exec ./setup.sh$args" <"$IN" + fi if [ -n "$SAVED_1" ]; then exec $SUDO -E ./setup.sh "$SAVED_1" ${SAVED_2:+"$SAVED_2"} <"$IN"; else exec $SUDO -E ./setup.sh <"$IN"; fi else if [ -n "$SAVED_1" ]; then exec ./setup.sh "$SAVED_1" ${SAVED_2:+"$SAVED_2"} <"$IN"; else exec ./setup.sh <"$IN"; fi diff --git a/relay/Caddyfile b/relay/Caddyfile index 9c2fec4..48468c4 100644 --- a/relay/Caddyfile +++ b/relay/Caddyfile @@ -13,7 +13,12 @@ anybot.example.com { request_body { max_size 210MB } + # The 大腦管理員 API is for this server's own manager, inside (deploy/server: brains). + respond /relay/manager/* 404 reverse_proxy relay:8080 { + # Who asked, believed only from here (ANYBOT_PROXY_SECRET in .env; a cloud brain + # talking to the account server straight can't send it). + header_up X-AnyBot-Proxy {$ANYBOT_PROXY_SECRET} # The phone's "anything new?" request waits up to 35 s. Each AnyBot also keeps one # WebSocket open here (pinged every 15–20 s, so it never sits idle for 60 s). transport http { diff --git a/relay/Caddyfile.lan b/relay/Caddyfile.lan index 3be14e0..860272c 100644 --- a/relay/Caddyfile.lan +++ b/relay/Caddyfile.lan @@ -23,7 +23,12 @@ https://LAN_IP { request_body { max_size 210MB } + # The 大腦管理員 API is for this server's own manager, inside (deploy/server: brains). + respond /relay/manager/* 404 reverse_proxy relay:8080 { + # Who asked, believed only from here (ANYBOT_PROXY_SECRET in .env; a cloud brain + # talking to the account server straight can't send it). + header_up X-AnyBot-Proxy {$ANYBOT_PROXY_SECRET} # The phone's "anything new?" request waits up to 35 s. Each AnyBot also keeps one # WebSocket open here (pinged every 15–20 s, so it never sits idle for 60 s). transport http { diff --git a/relay/Caddyfile.open b/relay/Caddyfile.open new file mode 100644 index 0000000..8ee9f97 --- /dev/null +++ b/relay/Caddyfile.open @@ -0,0 +1,61 @@ +# This server's own address on a tailnet (headscale, or Tailscale without its certificates) or in +# the local network, set up the easy way (setup.sh with no questions): AnyBot and the phone just +# open http://ADDR — nothing to trust first. On a tailnet the line is already encrypted +# (WireGuard). setup.sh writes this with ADDR replaced by the address. +# +# https://ADDR is here too, with a certificate Caddy signs itself (its own small authority, kept +# in the caddy-data volume): the phone's notifications need https. Trust it once on that phone: +# open http://ADDR/anybot-ca.crt and install it (iPhone: then 設定 › 一般 › 關於本機 › 憑證信任設定). +{ + # A browser asking for an IP address doesn't say which name it wants (no SNI). + default_sni ADDR + # The authority lives in this container only; nothing is installed on the server itself. + skip_install_trust + # http is served, not sent on to https. + auto_https disable_redirects +} + +(anybot) { + encode gzip + header { + X-Content-Type-Options "nosniff" + X-Frame-Options "SAMEORIGIN" + Referrer-Policy "no-referrer" + } + request_body { + max_size 210MB + } + # The 大腦管理員 API is for this server's own manager, inside (deploy/server: brains). + respond /relay/manager/* 404 + reverse_proxy relay:8080 { + # Who asked, believed only from here (ANYBOT_PROXY_SECRET in .env; a cloud brain + # talking to the account server straight can't send it). + header_up X-AnyBot-Proxy {$ANYBOT_PROXY_SECRET} + # The phone's "anything new?" request waits up to 35 s. Each AnyBot also keeps one + # WebSocket open here (pinged every 15–20 s, so it never sits idle for 60 s). + transport http { + read_timeout 620s + } + # Reloading this file doesn't cut those connections at once. + stream_close_delay 5m + } +} + +https://ADDR { + tls internal + import anybot +} + +# Any name or address that reaches this server on port 80 (the tailnet's name for it, another +# address of it): the same account server, not a blank page. +http:// { + handle /anybot-ca.crt { + root * /data/caddy/pki/authorities/local + rewrite * /root.crt + header Content-Type application/x-x509-ca-cert + file_server + } + handle { + import anybot + } +} diff --git a/relay/src/main.rs b/relay/src/main.rs index 35c402c..ab837ee 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -153,6 +153,10 @@ struct Host { /// 團隊: other accounts this AnyBot is shared with, and what they may do. #[serde(default)] members: Vec, + /// A cloud brain the server's 大腦管理員 made for the account: never taken over by a + /// computer signing in under the same name, nor it over one that wasn't made so. + #[serde(default)] + managed: bool, } #[derive(Clone, Serialize, Deserialize, Default)] @@ -342,6 +346,10 @@ struct Relay { /// 2FA: a right password opens a five-minute challenge (user, device, made, tries) awaiting the code. challenges: Mutex>, invite: String, + /// 大腦管理員 (the server's own, inside it — deploy/server's `brains`): its key, from + /// ANYBOT_RELAY_MANAGER_TOKEN (32+ characters; empty = no manager, the API answers 404). + manager: String, + manager_seen: Mutex>, vapid: push::Vapid, contact: String, } @@ -442,6 +450,8 @@ impl Relay { dirty: std::sync::atomic::AtomicBool::new(false), challenges: Mutex::new(HashMap::new()), invite: std::env::var("ANYBOT_RELAY_INVITE").unwrap_or_default(), + manager: std::env::var("ANYBOT_RELAY_MANAGER_TOKEN").ok().filter(|t| t.trim().len() >= 32).map(|t| t.trim().to_string()).unwrap_or_default(), + manager_seen: Mutex::new(None), vapid, // Push services want a way to reach whoever runs the server. contact: std::env::var("ANYBOT_RELAY_CONTACT").ok().filter(|c| c.starts_with("mailto:") || c.starts_with("https://")).unwrap_or_else(|| "mailto:anybot-relay@example.com".into()), @@ -1062,7 +1072,41 @@ impl Relay { // (The icons are kept a day: the page shows one while it connects, on every opening.) ("GET", ["icon.svg"]) => Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", [name]) if ICON_PNGS.iter().any(|(n, _)| n == name) => Resp::bytes("image/png", ICON_PNGS.iter().find(|(n, _)| n == name).map(|(_, b)| b.to_vec()).unwrap_or_default()).with_header("Cache-Control", "public, max-age=86400"), - ("GET", ["api", "hello"]) => Resp::json(&json!({"app": "anybot-relay"})), + // (`brains`: every account here gets a cloud brain of its own — an app that signs up + // waits for it rather than becoming the brain itself.) + ("GET", ["api", "hello"]) => Resp::json(&if self.manager_alive() { json!({"app": "anybot-relay", "brains": true}) } else { json!({"app": "anybot-relay"}) }), + // 大腦管理員: the accounts, and a cloud brain's sign-in for one (a new host token; the + // brain it replaces, same name, is signed out). Only the manager inside this server: + // its key, and never through the proxy in front (that adds X-Forwarded-For). + ("GET", ["relay", "manager", "users"]) if self.manager_ok(&req) => { + let d = self.data.lock().unwrap(); + // (When each was made: the first is the server's owner, and accounts made before + // the manager came are left as they were.) + let created: serde_json::Map = d.users.iter().map(|u| (u.name.clone(), json!(u.created))).collect(); + // (Each account's brain the manager made, by its id: one taken off the account — + // removed, an older data file put back — is made again with a new sign-in.) + let brains: serde_json::Map = d.hosts.iter().filter(|h| h.managed).map(|h| (h.user.clone(), json!(h.id))).collect(); + Resp::json(&json!({"users": d.users.iter().map(|u| u.name.clone()).collect::>(), "created": created, "brains": brains})) + } + ("POST", ["relay", "manager", "brain"]) if self.manager_ok(&req) => { + let v = req.json(); + let user = v["user"].as_str().unwrap_or("").trim().to_lowercase(); + let name: String = v["name"].as_str().filter(|n| !n.trim().is_empty()).unwrap_or("雲端大腦").chars().take(60).collect(); + { + let d = self.data.lock().unwrap(); + if !d.users.iter().any(|u| u.name == user) { + return Resp::error(404, "沒有這個帳號"); + } + // (Never over a computer of the account that the manager didn't make — an + // older setup's brain of the same name.) + if d.hosts.iter().any(|x| x.user == user && x.name == name && !x.managed) { + return Resp::error(409, &format!("這個帳號已經有一台叫「{name}」的電腦(不是伺服器開的)")); + } + } + let (h, token) = self.add_host(&user, &name, true); + Resp::json(&json!({"id": h.id, "token": token, "user": user, "name": name})) + } + ("GET" | "POST", ["relay", "manager", ..]) => Resp::error(404, "not found"), // 連線體檢 (/doctor): `bytes` of noise (256 KB, at most 1 MB) to time a download over the // whole road — Cloudflare, Caddy, a tailnet relay. Noise: none of them can shrink it. ("GET", ["api", "speed"]) => { @@ -1256,7 +1300,11 @@ impl Relay { return Resp::error(403, "要加入一台電腦,請在那台電腦上重新登入帳號(登入後 15 分鐘內有效)"); } let name: String = req.json()["name"].as_str().unwrap_or("AnyBot").chars().take(60).collect(); - let (h, token) = self.add_host(&user, &name); + // (Not over the cloud brain the server made for this account: it holds the bots.) + if self.data.lock().unwrap().hosts.iter().any(|x| x.user == user && x.name == name && x.managed) { + return Resp::error(409, &format!("這個帳號已經有伺服器開的「{name}」,這台換個名字")); + } + let (h, token) = self.add_host(&user, &name, false); Resp::json(&json!({"id": h.id, "token": token})) } // 加一台電腦: a signed-in phone or non-paired AnyBot asks for a code; the new computer gives it back. @@ -1579,9 +1627,9 @@ impl Relay { /// Register an AnyBot of `user`. The same name again replaces its old key (keeping who it's /// shared with, and hanging up the replaced connection). - fn add_host(&self, user: &str, name: &str) -> (Host, String) { + fn add_host(&self, user: &str, name: &str, managed: bool) -> (Host, String) { let token = httpd::random_hex(32); - let mut h = Host { id: httpd::random_hex(8), name: name.to_string(), user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: false, members: vec![] }; + let mut h = Host { id: httpd::random_hex(8), name: name.to_string(), user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: false, members: vec![], managed }; let replaced: Vec = { let mut d = self.data.lock().unwrap(); if let Some(old) = d.hosts.iter().find(|x| x.user == user && x.name == name) { @@ -1615,7 +1663,7 @@ impl Relay { } else { (2..1000).map(|n| format!("{base} ({n})")).find(|cand| !d.hosts.iter().any(|x| x.user == user && x.name == *cand)).unwrap_or_else(|| format!("{base}-{}", httpd::random_hex(2))) }; - let h = Host { id: httpd::random_hex(8), name: chosen, user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: true, members: vec![] }; + let h = Host { id: httpd::random_hex(8), name: chosen, user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: true, members: vec![], managed: false }; d.hosts.push(h.clone()); self.save(&d); (h, token) @@ -1725,8 +1773,29 @@ impl Relay { token } + /// A call from this server's own 大腦管理員: its key, straight from inside (a request that + /// came through the proxy in front carries X-Forwarded-For). + fn manager_ok(&self, req: &Req) -> bool { + let ok = !self.manager.is_empty() && req.header("x-forwarded-for").is_empty() && httpd::constant_time_eq(&req.bearer(), &self.manager); + if ok { + *self.manager_seen.lock().unwrap() = Some(Instant::now()); + } + ok + } + + /// The manager asked within the last minute (it looks every few seconds): only then is a + /// cloud brain promised — an app that signs up waits for it, in vain if none comes. + fn manager_alive(&self) -> bool { + !self.manager.is_empty() && self.manager_seen.lock().unwrap().is_some_and(|t| t.elapsed() < Duration::from_secs(60)) + } + fn peer_ip(req: &Req) -> String { let trust = matches!(std::env::var("RELAY_TRUST_PROXY").ok().map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("1" | "true" | "yes")); + // With ANYBOT_RELAY_PROXY_SECRET set, only the proxy in front (it sends the secret as + // X-AnyBot-Proxy) is believed about who asked: a cloud brain on the same network, talking + // to this server straight, wrote any X-Forwarded-For it liked and got past every + // per-address limit (sign-ups, sign-ins, pairing). + let trust = trust && proxy_vouches(req); match (trust, req.header("x-forwarded-for")) { // (Kept short: it is a key in the table of failures.) (true, xff) if !xff.is_empty() => xff.rsplit(',').next().unwrap_or(xff).trim().chars().take(64).collect(), @@ -2044,6 +2113,17 @@ fn reset_password(dir: &std::path::Path, user: &str, port: u16) -> i32 { 0 } +/// Whether the proxy in front sent this request (ANYBOT_RELAY_PROXY_SECRET, as X-AnyBot-Proxy); +/// with no secret set, every proxy is believed as before. +fn proxy_vouches(req: &Req) -> bool { + proxy_vouches_with(req, &std::env::var("ANYBOT_RELAY_PROXY_SECRET").unwrap_or_default()) +} + +fn proxy_vouches_with(req: &Req, secret: &str) -> bool { + let secret = secret.trim(); + secret.is_empty() || httpd::constant_time_eq(req.header("x-anybot-proxy").trim(), secret) +} + #[cfg(test)] mod tests { use super::*; @@ -2376,6 +2456,97 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Only the proxy that knows the secret is believed about who asked: a request straight from + /// a cloud brain on the same network, with an X-Forwarded-For of its own, isn't. + #[test] + fn only_the_proxy_in_front_says_who_asked() { + let req = |h: &[(&str, &str)]| Req { headers: h.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), peer: "172.18.0.9".into(), ..Req::default() }; + let forged = req(&[("x-forwarded-for", "198.51.100.7")]); + let proxied = req(&[("x-forwarded-for", "198.51.100.7"), ("x-anybot-proxy", "s3cret")]); + assert!(!proxy_vouches_with(&forged, "s3cret"), "no secret: not the proxy"); + assert!(!proxy_vouches_with(&req(&[("x-anybot-proxy", "guess")]), "s3cret")); + assert!(proxy_vouches_with(&proxied, "s3cret")); + // No secret set (an older setup): every proxy believed, as before. + assert!(proxy_vouches_with(&forged, "")); + } + + /// 大腦管理員: with its key, from inside, it lists the accounts and gets a cloud brain's + /// sign-in for one — a host token that works like any AnyBot's. Without the key, through the + /// proxy (X-Forwarded-For), or on a server with no manager: nothing (404). /api/hello says + /// the server gives every account a brain. + #[test] + fn the_brain_manager_gets_a_brain_for_each_account() { + let dir = std::env::temp_dir().join(format!("anybot-relay-manager-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let key = "m".repeat(40); + let mut relay = Relay::load(dir.clone()); + relay.invite = "join-us".into(); + relay.manager = key.clone(); + let relay = Arc::new(relay); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let r = relay.clone(); + std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true))); + let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); + let hello = || -> Value { serde_json::from_str(&agent.get(&format!("http://127.0.0.1:{port}/api/hello")).call().unwrap().body_mut().read_to_string().unwrap()).unwrap() }; + // (No brains promised until the manager has come asking: one that never came, or died, + // would leave every sign-up waiting in vain.) + assert!(hello()["brains"].is_null()); + assert_eq!(post(port, "/relay/signup", "", json!({"user": "Boss", "password": "12345678", "invite": "join-us"})).0, 200); + assert_eq!(post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678", "invite": "join-us"})).0, 200); + + let (st, v) = { let (s, b) = get(port, "/relay/manager/users", &key); (s, serde_json::from_slice::(&b).unwrap_or(Value::Null)) }; + assert_eq!(st, 200); + assert_eq!(v["users"], json!(["boss", "amy"])); + assert!(v["created"]["boss"].as_i64().unwrap() > 0 && v["created"]["amy"].as_i64().is_some()); + assert!(v["brains"].as_object().unwrap().is_empty(), "no brains made yet"); + assert_eq!(hello()["brains"], true, "the manager came: brains promised"); + let (st, b) = post(port, "/relay/manager/brain", &key, json!({"user": "Amy"})); + assert_eq!(st, 200, "{b}"); + let (id, token) = (b["id"].as_str().unwrap().to_string(), b["token"].as_str().unwrap().to_string()); + assert_eq!(b["name"], "雲端大腦"); + let users: Value = serde_json::from_slice(&get(port, "/relay/manager/users", &key).1).unwrap(); + assert_eq!(users["brains"]["amy"], id.as_str(), "the manager sees which brain it made for amy"); + // The token is a host's like any other: it waits for work as that account's brain. + let peers: Value = { let (s, body) = get(port, "/relay/host/peers", &token); assert_eq!(s, 200); serde_json::from_slice(&body).unwrap() }; + assert!(peers["hosts"].as_array().unwrap().iter().any(|h| h["id"] == id.as_str()), "{peers}"); + assert_eq!(post(port, "/relay/manager/brain", &key, json!({"user": "nobody"})).0, 404); + // A computer signing in can't take the managed brain's place (it holds the bots)… + let (_, s) = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678", "device": "Mac"})); + let (st, _) = post(port, "/relay/hosts", s["token"].as_str().unwrap(), json!({"name": "雲端大腦"})); + assert_eq!(st, 409); + assert!(get(port, "/relay/host/peers", &token).0 == 200, "the managed brain still signed in"); + // …and the manager never takes the place of one the account had before (an older setup's). + let (_, s) = post(port, "/relay/login", "", json!({"user": "boss", "password": "12345678", "device": "Server"})); + let (_, own) = post(port, "/relay/hosts", s["token"].as_str().unwrap(), json!({"name": "雲端大腦"})); + assert_eq!(post(port, "/relay/manager/brain", &key, json!({"user": "boss"})).0, 409); + assert_eq!(get(port, "/relay/host/peers", own["token"].as_str().unwrap()).0, 200, "boss's own brain still signed in"); + + // Not without the key, not through the proxy in front. + assert_eq!(get(port, "/relay/manager/users", "wrong").0, 404); + assert_eq!(post(port, "/relay/manager/brain", "", json!({"user": "amy"})).0, 404); + let through = agent.get(&format!("http://127.0.0.1:{port}/relay/manager/users")).header("Authorization", &format!("Bearer {key}")).header("X-Forwarded-For", "203.0.113.9").call().unwrap(); + assert_eq!(through.status().as_u16(), 404); + // A session (a person signed in) is not the manager either. + let (_, s) = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678", "device": "Mac"})); + assert_eq!(get(port, "/relay/manager/users", s["token"].as_str().unwrap()).0, 404); + let _ = std::fs::remove_dir_all(&dir); + + // A server with no manager key: no manager, and hello doesn't promise brains. + let dir = std::env::temp_dir().join(format!("anybot-relay-nomanager-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let relay = Arc::new(Relay::load(dir.clone())); + assert!(relay.manager.is_empty()); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let r = relay.clone(); + std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true))); + let hello: Value = serde_json::from_str(&agent.get(&format!("http://127.0.0.1:{port}/api/hello")).call().unwrap().body_mut().read_to_string().unwrap()).unwrap(); + assert!(hello["brains"].is_null()); + assert_eq!(get(port, "/relay/manager/users", "").0, 404); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn team_members_get_their_role() { let dir = std::env::temp_dir().join(format!("anybot-relay-team-{}", std::process::id())); @@ -2460,7 +2631,7 @@ mod tests { // Another account whose name and site come to the same folder (「boss-trip」): told // so, and the first one's pages stay (it can't delete them either). relay.data.lock().unwrap().users.push(User { name: "boss-trip".into(), pass: httpd::hash_password("12345678"), ..Default::default() }); - let (other, other_key) = relay.add_host("boss-trip", "n"); + let (other, other_key) = relay.add_host("boss-trip", "n", false); assert_eq!(other.user, "boss-trip"); let (st, _) = post(port, "/relay/host/sites/x", &other_key, json!({"files": [{"path": "index.html", "data": b("mine")}]})); assert_eq!(st, 200, "its own names are its own"); diff --git a/src/agent.rs b/src/agent.rs index c3b2625..6e9510f 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -2517,6 +2517,13 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< runs_with.insert(c.id.clone(), args); } } + // Earlier thinking that no longer holds (the history changed under it): sent without + // it from here on — or every later step of the turn leaves it out again, or behind a + // proxy is refused first. + if out.old_thinking_left_out { + crate::providers::forget_thinking(&mut history); + send(StreamEvent::ThinkingForgotten); + } let msg = Message { role: Role::Assistant, text: out.text, @@ -5863,6 +5870,33 @@ echo 'done送出了' > done.html; (setsid pyt assert!(!providers::sees_images(&req), "no more pictures for this model"); } + /// A turn with Claude whose earlier thinking no longer holds (the history changed under it — + /// 「錯誤 400:…Invalid signature in thinking block… bound to a different conversation」, + /// 2026-11-23): the step is asked again with `drop_block` and answers; the API said it left + /// that thinking out, so the chat is told to let go of it (not sent again next turn), and the + /// step's own answer comes after that. + #[test] + fn a_turn_whose_old_thinking_no_longer_holds_answers_and_lets_it_go() { + let refused = r#"{"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.2: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to \"drop_block\"."}}"#; + let ok = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"input_transformations\":[{\"type\":\"thinking_dropped\",\"path\":\"messages.1.content.2\",\"reason\":\"prefix_binding_mismatch\"}]}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"new\"}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"text_delta\",\"text\":\"好了\"}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"; + let f = crate::testkit::Fake::start(crate::testkit::Format::Anthropic, vec![crate::testkit::Reply::Raw(400, refused.into()), crate::testkit::Reply::Raw(200, ok.into())], None); + let mut before = Message::assistant("看看", "Anthropic · claude-opus-5-5"); + before.blocks = vec![serde_json::json!({"type": "thinking", "thinking": "", "signature": "old"}), serde_json::json!({"type": "text", "text": "看看"})]; + let history = vec![Message::user("hi"), before, Message::user("再一次")]; + let job = Job { req: ChatRequest { kind: ProviderKind::Anthropic, base_url: format!("http://127.0.0.1:{}/v1", f.port), api_key: "k".into(), model: "claude-opus-5-5".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() }, ..test_job() }; + let (evs, _) = drive(job, ApprovalAnswer::Reject); + assert!(matches!(evs.last(), Some(StreamEvent::Done)), "{:?}", evs.iter().filter_map(|e| if let StreamEvent::Error(e) = e { Some(e.clone()) } else { None }).collect::>()); + let forgot = evs.iter().position(|e| matches!(e, StreamEvent::ThinkingForgotten)).expect("the chat is told to let the old thinking go"); + let answered = evs.iter().position(|e| matches!(e, StreamEvent::StepDone(m) if m.text == "好了")).expect("the step answered"); + assert!(forgot < answered, "let go before the step's own answer (with its new thinking) is kept"); + if let StreamEvent::StepDone(m) = &evs[answered] { + assert_eq!(m.blocks[0]["signature"], "new", "the new thinking is kept"); + } + let raw = f.raw.lock().unwrap(); + assert_eq!(raw.len(), 2); + assert!(!raw[0].contains("block_binding") && raw[1].contains("drop_block"), "{}", raw[1]); + } + /// One request and many steps (a routine): old results are set aside first, then the turn's /// earlier steps are summarized inside it — the request stays, the newest steps stay. #[test] diff --git a/src/app.rs b/src/app.rs index adc3674..b306098 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3530,6 +3530,9 @@ impl App { m.images.clear(); } } + // Earlier thinking no longer held for this conversation: not sent next turn either + // (the turn's own new thinking comes with its step, after this). + StreamEvent::ThinkingForgotten => crate::providers::forget_thinking(&mut b.messages), // The model said how much it reads: this bot summarizes in time from now on. // (For this model only: another one the bot switches to reads what it reads.) StreamEvent::ContextLimit(n) => { @@ -7209,10 +7212,28 @@ impl App { /// (and, with ANYBOT_RESTORE_FROM_ACCOUNT=1, start once from the newest backup). An account /// with 兩步驗證 on also needs ANYBOT_ACCOUNT_CODE (a recovery code: it is used once). fn serve_join(&mut self) { - let (Ok(acct), Ok(pw)) = (std::env::var("ANYBOT_ACCOUNT"), std::env::var("ANYBOT_ACCOUNT_PASSWORD")) else { return }; + // A cloud brain the server's 大腦管理員 started (`anybot --brains`): signed in with the + // account server's own host token, ANYBOT_HOST_ID + ANYBOT_HOST_TOKEN — no password + // anywhere on the server. (No backup key without one: its data lives on the server.) + // The manager's sign-in wins over the one saved: a brain made again with its old volume + // and a new token kept trying the old one, which the account server had let go. + if let Some((url, user, id, token)) = token_join_env() { + if self.state.remote.host_id == id && self.state.remote.host_token == token { + return; + } + let r = &mut self.state.remote; + r.relay_url = url.clone(); + r.relay_user = user.clone(); + r.host_id = id; + r.host_token = token; + self.dirty = true; + log::info!("AnyBot:已加入帳號 {user}({url},帳號伺服器發的登入憑證)"); + return; + } if !self.state.remote.host_token.is_empty() { return; } + let (Ok(acct), Ok(pw)) = (std::env::var("ANYBOT_ACCOUNT"), std::env::var("ANYBOT_ACCOUNT_PASSWORD")) else { return }; let Some((url, user)) = acct.rsplit_once('|') else { return }; // ANYBOT_ACCOUNT_CREATE=1 (the server's own brain, first start): make the account if it isn't there. let code = std::env::var("ANYBOT_ACCOUNT_CODE").unwrap_or_default(); @@ -8895,6 +8916,21 @@ fn dialog_body(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, +/// ANYBOT_ACCOUNT=url|user with ANYBOT_HOST_ID and ANYBOT_HOST_TOKEN (a cloud brain started by the +/// server's 大腦管理員): (url, user, host id, host token), when all are there. +fn token_join_env() -> Option<(String, String, String, String)> { + token_join_from(|k| std::env::var(k).ok()) +} + +fn token_join_from(var: impl Fn(&str) -> Option) -> Option<(String, String, String, String)> { + let acct = var("ANYBOT_ACCOUNT")?; + let (url, user) = acct.rsplit_once('|')?; + let id = var("ANYBOT_HOST_ID").map(|v| v.trim().to_string()).filter(|v| !v.is_empty())?; + let token = var("ANYBOT_HOST_TOKEN").map(|v| v.trim().to_string()).filter(|v| !v.is_empty())?; + let (url, user) = (url.trim().trim_end_matches('/').to_string(), user.trim().to_string()); + (!url.is_empty() && !user.is_empty()).then_some((url, user, id, token)) +} + #[cfg(test)] mod tests { /// 換了模型: a line in the chat where the model changed — not on the first answer, not when @@ -9312,6 +9348,37 @@ mod tests { } } + /// A cloud brain started by the server's 大腦管理員 signs in with the account server's own + /// host token (no password on the server); anything missing, and it doesn't. + #[test] + fn a_cloud_brain_signs_in_with_the_servers_token() { + let env = |pairs: &'static [(&'static str, &'static str)]| move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()); + assert_eq!(super::token_join_from(env(&[("ANYBOT_ACCOUNT", "http://relay:8080/|amy"), ("ANYBOT_HOST_ID", "ab12"), ("ANYBOT_HOST_TOKEN", " t0ken ")])), Some(("http://relay:8080".into(), "amy".into(), "ab12".into(), "t0ken".into()))); + assert_eq!(super::token_join_from(env(&[("ANYBOT_ACCOUNT", "http://relay:8080|amy"), ("ANYBOT_HOST_ID", "ab12")])), None, "no token"); + assert_eq!(super::token_join_from(env(&[("ANYBOT_ACCOUNT", "http://relay:8080|amy"), ("ANYBOT_HOST_ID", ""), ("ANYBOT_HOST_TOKEN", "t")])), None, "an empty id"); + assert_eq!(super::token_join_from(env(&[("ANYBOT_ACCOUNT", "http://relay:8080"), ("ANYBOT_HOST_ID", "a"), ("ANYBOT_HOST_TOKEN", "t")])), None, "no account name"); + assert_eq!(super::token_join_from(env(&[("ANYBOT_HOST_ID", "a"), ("ANYBOT_HOST_TOKEN", "t")])), None); + } + + /// The turn said the chat's older thinking no longer holds (providers::forget_thinking): the + /// saved chat lets go of those thinking blocks — words and calls as they were — so the next + /// turn doesn't send them again. + #[test] + fn the_chat_lets_go_of_thinking_that_no_longer_holds() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-forget-thinking.png"))); + let id = app.state.bots[0].id; + let mut a = Message::assistant("看看", "Anthropic · claude-opus-5-5"); + a.blocks = vec![serde_json::json!({"type": "thinking", "thinking": "", "signature": "old"}), serde_json::json!({"type": "text", "text": "看看"})]; + app.state.bot_mut(id).unwrap().messages = vec![Message::user("hi"), a].into(); + app.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 }); + app.tx.send((id, 1, StreamEvent::ThinkingForgotten)).unwrap(); + app.drain_events(&ctx); + let b = app.state.bot(id).unwrap(); + assert_eq!(b.messages[1].blocks, vec![serde_json::json!({"type": "text", "text": "看看"})]); + assert_eq!(b.messages[1].text, "看看"); + } + /// 待改進: the look back that finds AnyBot's own problems runs after the turn has ended /// (agent::learn, after Done) — what it reports is queued then, like the skill it learns, /// not dropped with a finished turn's leftovers. diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 5891c4b..a0a3f99 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -961,10 +961,16 @@ impl App { let (tx, rx) = channel(); self.rm.join_rx = Some(rx); let (url, user, pass, create, invite, base, code) = (self.rm.relay_url.clone(), self.rm.user.trim().to_string(), self.rm.pass.clone(), self.rm.create, self.rm.invite.clone(), self.state.remote.clone(), self.rm.code.clone()); + let note = self.rm.note.clone(); + let repaint = self.repaint_fn(); std::thread::spawn(move || { - // Signed in: look right away for the bots the account already has. + // Signed in: look right away for the bots the account already has (on + // a server that gives each account a cloud brain, wait for it). let r = remote::relay_join(&base, &url, &user, &pass, create, &invite, &code).map(|s| { - let found = remote::find_account_bots(&s, &pass, &code); + let found = remote::find_account_bots_noting(&s, &pass, &code, remote::BRAIN_WAIT, &|n| { + *note.lock().unwrap() = n.to_string(); + repaint(); + }); (s, found) }); let _ = tx.send(r); diff --git a/src/brains.rs b/src/brains.rs new file mode 100644 index 0000000..5e9f348 --- /dev/null +++ b/src/brains.rs @@ -0,0 +1,776 @@ +//! 大腦管理員 (`anybot --brains`, deploy/server's `brains` service): every account on this +//! server's account server gets a cloud brain of its own — signed up from the app, it is there a +//! few seconds later, with nothing to set on the server. One container a brain +//! (`anybot-brain-`): the same image, its own data volume, `restart: unless-stopped` +//! (back after a reboot), signed in with a host token the account server hands the manager +//! (`/relay/manager/brain`): no password is kept on the server. +//! +//! An account holder runs commands on their brain (hooks, connectors). So: +//! - Docker is the whole server: only the owner's brain (the first account, kept once seen) and +//! the accounts named in ANYBOT_BRAINS_DOCKER get it (through the filtered proxy, their own box +//! and its home volume); the others work on their own computers. +//! - No brain may forge or overhear traffic on the network it shares with the account server +//! (no NET_RAW, no new privileges), and the manager talks to the account server on a network of +//! its own (its key never crosses the brains' one); each brain has a memory and process limit. +//! +//! Accounts made before the manager first ran (an older server updated) are left as they were: +//! they have their own brains already. ANYBOT_BRAINS_ALL=1 gives them one too. +//! +//! A brain from an older image or other settings (after `make update-server`) is made again with +//! the same volume and sign-in, after it is let to finish (stopped, not killed); one whose sign-in +//! the account server no longer has gets a new one. The manager never removes a brain's data. + +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// What the manager starts brains with. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Config { + /// The account server as the manager reaches it (its own network): http://relay-manager:8080. + pub relay: String, + /// The account server as the brains reach it: http://relay:8080. + pub brain_relay: String, + pub key: String, + /// The image the brains run (the manager's own: one build for both). + pub image: String, + /// The account server's network (every brain) and Docker's proxy's (only brains with Docker). + pub network: String, + pub docker_network: Option, + /// Accounts left alone: the older single-account setup's own brain (ANYBOT_USER) runs as + /// before, as the compose file's `anybot`. + pub skip: Vec, + /// Accounts whose brains get Docker besides the owner's (ANYBOT_BRAINS_DOCKER). + pub docker_users: Vec, + /// Accounts made before this (seconds): left alone, unless `all`. + pub since: i64, + pub all: bool, + /// Each brain's memory limit (docker's form: 4g; no swap beyond it) and CPUs (2). + pub memory: String, + /// None: this Docker can't hold a container to a share of the CPUs (no CFS quota — rootless + /// without the cpu controller), where `--cpus` is refused and no brain could be made. + pub cpus: Option, + /// At most this many cloud brains (one invite can sign up many accounts). + pub max: usize, + /// Passed on to every brain as it is (語音, the model mirror). + pub env: Vec<(String, String)>, + /// Passed on only to brains with Docker (DOCKER_HOST: the proxy). + pub docker_env: Vec<(String, String)>, +} + +/// An account as the account server lists it: its name and when it was made (seconds). +#[derive(Clone, Debug, PartialEq)] +pub struct Account { + pub name: String, + pub created: i64, +} + +/// One account's brain container as Docker has it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Existing { + pub name: String, + pub running: bool, + /// What its image holds (a hash of the image's layers — the image ID changes with every + /// build, even one that changed nothing), whether it was given Docker, the hash of how it was + /// made (create_args without its sign-in), and the account server's id for it. + pub image: String, + pub docker: bool, + pub args: String, + pub host: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + /// A brain made before, not running (stopped by hand, or its start failed): start it — joined to + /// Docker's network first when it has Docker (a manager stopped between making and joining + /// left the owner's brain without it). + Start(String, bool), + /// An account with no brain yet: make one (with Docker or not). + Create(String, bool), + /// A brain from an older image or other settings: made again with the same volume — and the + /// same sign-in, or (true) a new one when the account server no longer has its. + Remake(String, bool, bool), +} + +/// Whether this account's brain gets Docker: the owner's and the ones named. +pub fn gets_docker(user: &str, owner: Option<&str>, named: &[String]) -> bool { + owner == Some(user) || named.iter().any(|n| n.eq_ignore_ascii_case(user)) +} + +/// The brains that count toward ANYBOT_BRAINS_MAX: not the ones stopped on purpose (skipped). +fn counted(existing: &HashMap, c: &Config) -> usize { + existing.keys().filter(|u| !c.skip.iter().any(|s| s.eq_ignore_ascii_case(u))).count() +} + +/// The server's owner: the first account made (kept by the manager once it has seen it — a +/// clock set back, an account taken away, never hands Docker to another). +pub fn first_account(accounts: &[Account]) -> Option<&str> { + accounts.iter().min_by_key(|a| a.created).map(|a| a.name.as_str()) +} + +/// What to do for each account. `managed`: the account server's id of the brain it knows for +/// each account (None: an older account server that doesn't say). +pub fn plan(accounts: &[Account], existing: &HashMap, image: &str, owner: Option<&str>, managed: Option<&HashMap>, c: &Config) -> Vec { + let mut out = vec![]; + // (At most `max` brains: the ones there and the ones about to be made.) + let mut room = c.max.saturating_sub(counted(existing, c)); + for a in accounts { + let u = &a.name; + if c.skip.iter().any(|s| s.eq_ignore_ascii_case(u)) { + continue; + } + let docker = gets_docker(u, owner, &c.docker_users); + match existing.get(u) { + Some(e) => { + // (Its sign-in gone from the account server: removed, an older data file.) + let lost = managed.is_some_and(|m| !e.host.is_empty() && m.get(u) != Some(&e.host)); + let stale = (!image.is_empty() && e.image != image) || e.docker != docker || e.args != args_hash(u, docker, c); + if lost || stale { + out.push(Action::Remake(u.clone(), docker, lost)); + } else if !e.running { + out.push(Action::Start(e.name.clone(), docker)); + } + } + // (An account from before the manager: its own brain is elsewhere.) + None if a.created < c.since && !c.all => {} + None if room == 0 => {} + None => { + room -= 1; + out.push(Action::Create(u.clone(), docker)); + } + } + } + // A new account's brain first (someone is waiting for it), the updates last. + out.sort_by_key(|a| match a { + Action::Create(..) => 0, + Action::Start(..) => 1, + Action::Remake(..) => 2, + }); + out +} + +/// An account name as a Docker name: letters, digits and - (a name of `.`, `_` or `@` keeps +/// apart from another by a short hash of the whole name). +pub fn slug(user: &str) -> String { + let mut s: String = user.to_lowercase().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); + while s.contains("--") { + s = s.replace("--", "-"); + } + let s: String = s.trim_matches('-').chars().take(30).collect(); + let hash = crate::httpd::sha256_hex(user); + format!("{}-{}", if s.is_empty() { "user" } else { s.trim_end_matches('-') }, &hash[..6]) +} + +pub fn container_name(user: &str) -> String { + format!("anybot-brain-{}", slug(user)) +} + +/// How a brain is made, but its sign-in: what decides whether one made earlier is still right. +fn base_args(user: &str, docker: bool, c: &Config) -> Vec { + let s = slug(user); + let mut a: Vec = ["--restart", "unless-stopped"].iter().map(|x| x.to_string()).collect(); + a.extend(["--name".into(), container_name(user)]); + a.extend(["--label".into(), format!("anybot.brain.user={user}")]); + a.extend(["--label".into(), format!("anybot.brain.docker={}", if docker { 1 } else { 0 })]); + a.extend(["-v".into(), format!("anybot-brain-{s}:/data")]); + a.extend(["--network".into(), c.network.clone()]); + // Commands run here are the account holder's: no forging or overhearing on the network shared + // with the account server, no gaining privileges, and a share of the machine only. + a.extend(["--cap-drop".into(), "NET_RAW".into(), "--security-opt".into(), "no-new-privileges".into()]); + a.extend(["--pids-limit".into(), "2048".into(), "--memory".into(), c.memory.clone(), "--memory-swap".into(), c.memory.clone()]); + if let Some(n) = &c.cpus { + a.extend(["--cpus".into(), n.clone()]); + } + let mut env: Vec<(String, String)> = vec![("ANYBOT_ACCOUNT".into(), format!("{}|{user}", c.brain_relay)), ("ANYBOT_HOST_NAME".into(), "雲端大腦".into())]; + if docker { + // Its own bots' computer and that computer's home: never another account's files. + env.push(("ANYBOT_BOX_NAME".into(), format!("anybot-box-{s}"))); + env.push(("ANYBOT_BOX_VOLUME".into(), format!("anybot-box-home-{s}"))); + env.extend(c.docker_env.iter().cloned()); + } + env.extend(c.env.iter().cloned()); + for (k, v) in env { + a.extend(["-e".into(), format!("{k}={v}")]); + } + a +} + +pub fn args_hash(user: &str, docker: bool, c: &Config) -> String { + let mut all = base_args(user, docker, c); + all.push(c.image.clone()); + crate::httpd::sha256_hex(&all.join("\u{1f}"))[..16].to_string() +} + +/// The `docker create` arguments of an account's brain (started after its networks are joined). +/// `holds`: what the image holds (layers()), kept as a label — the image it was made from can't be +/// looked at once a rebuild has moved the name on (Docker's containerd store: "No such image"). +pub fn create_args(user: &str, host_id: &str, host_token: &str, docker: bool, holds: &str, c: &Config) -> Vec { + let mut a = vec!["create".to_string()]; + a.extend(base_args(user, docker, c)); + a.extend(["--label".into(), format!("anybot.brain.args={}", args_hash(user, docker, c))]); + a.extend(["--label".into(), format!("anybot.brain.layers={holds}")]); + a.extend(["--label".into(), format!("anybot.brain.host={host_id}")]); + a.extend(["-e".into(), format!("ANYBOT_HOST_ID={host_id}"), "-e".into(), format!("ANYBOT_HOST_TOKEN={host_token}")]); + a.push(c.image.clone()); + a.extend(["anybot".into(), "--serve".into()]); + a +} + +/// `anybot --brains`: the manager, until stopped. +pub fn run() -> ! { + let cfg = match config() { + Ok(c) => c, + Err(e) => { + log::warn!("AnyBot 大腦管理員:{e}"); + std::process::exit(2); + } + }; + log::info!("AnyBot 大腦管理員:每個帳號一個雲端大腦(映像 {},網路 {})", cfg.image, cfg.network); + // A stop (docker compose stop / an update) ends it after the job under way. + let _ = ctrlc::set_handler(|| STOPPING.store(true, std::sync::atomic::Ordering::SeqCst)); + let mut said = String::new(); + // Accounts whose last tries failed, and how many times in a row: tried again a minute later, + // then two, four… up to half an hour (each try asks for a sign-in, and a remake stops the + // brain that runs). + let mut resting: HashMap = HashMap::new(); + loop { + let errors = tick(&cfg, &mut resting); + // (Said once until it changes: an account server still starting would fill the log.) + let now = errors.join(";"); + if now != said { + if !now.is_empty() { + log::warn!("AnyBot 大腦管理員:{now}"); + } + said = now; + } + for _ in 0..50 { + if STOPPING.load(std::sync::atomic::Ordering::SeqCst) { + log::info!("AnyBot 大腦管理員:停止"); + std::process::exit(0); + } + std::thread::sleep(Duration::from_millis(100)); + } + } +} + +static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The owner, kept in the manager's data folder the first time there is one. +fn owner(accounts: &[Account]) -> Option { + let file = data_folder().join("brains-owner"); + if let Some(o) = std::fs::read_to_string(&file).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) { + return Some(o); + } + let first = first_account(accounts)?.to_string(); + let _ = std::fs::write(&file, &first); + log::info!("AnyBot 大腦管理員:擁有者是 {first}(它的雲端大腦有 Bot 的電腦)"); + Some(first) +} + +/// How long an account rests after this many failed tries in a row. +fn rest_for(fails: u32) -> Duration { + Duration::from_secs((60u64 << fails.saturating_sub(1).min(5)).min(30 * 60)) +} + +fn tick(cfg: &Config, resting: &mut HashMap) -> Vec { + let (accounts, managed) = match accounts(cfg) { + Ok(a) => a, + Err(e) => return vec![e], + }; + let existing = match existing() { + Ok(e) => e, + Err(e) => return vec![e], + }; + let image = layers(&cfg.image); + let owner = owner(&accounts); + let mut errors = vec![]; + let waiting = accounts.iter().filter(|a| !existing.contains_key(&a.name) && !cfg.skip.iter().any(|s| s.eq_ignore_ascii_case(&a.name)) && (a.created >= cfg.since || cfg.all)).count(); + if counted(&existing, cfg) + waiting > cfg.max { + errors.push(format!("雲端大腦已經 {} 個,到上限(ANYBOT_BRAINS_MAX={}):新的帳號先不開", counted(&existing, cfg), cfg.max)); + } + let actions = plan(&accounts, &existing, &image, owner.as_deref(), managed.as_ref(), cfg); + let who = |a: &Action| match a { + Action::Start(n, _) => n.clone(), + Action::Create(u, _) | Action::Remake(u, _, _) => u.clone(), + }; + // (One with nothing left to do starts afresh the next time it has something.) + resting.retain(|w, _| actions.iter().any(|a| &who(a) == w)); + // Each on its own: one that fails doesn't keep the others from their brains. + for (i, a) in actions.into_iter().enumerate() { + // (Stopping: after the job under way, never in the middle of one.) + if STOPPING.load(std::sync::atomic::Ordering::SeqCst) { + break; + } + // (Asked again between long jobs — remaking many brains takes minutes: the account server + // keeps saying brains are made, and a sign-up meanwhile still waits for its own.) + if i > 0 { + let _ = self::accounts(cfg); + } + let who = who(&a); + if resting.get(&who).is_some_and(|(t, n)| t.elapsed() < rest_for(*n)) { + continue; + } + let r = match &a { + Action::Start(name, d) => { + log::info!("AnyBot 大腦管理員:叫醒 {name}"); + if *d { + if let Some(n) = &cfg.docker_network { + // (Already joined: Docker says so, and that is fine.) + let _ = docker(&["network", "connect", n, name]); + } + } + docker(&["start", name]).map(|_| ()) + } + Action::Create(user, d) => create(cfg, user, *d, None), + Action::Remake(user, d, fresh) => remake(cfg, user, *d, *fresh), + }; + match r { + Err(e) => { + let n = resting.get(&who).map_or(0, |r| r.1) + 1; + resting.insert(who, (Instant::now(), n)); + errors.push(e); + } + Ok(()) => { + resting.remove(&who); + } + } + } + errors +} + +/// Made again: the same volume, and the same sign-in read back from the old container (no new +/// token, nothing else of the account changes) — or a new one when that one is gone. Stopped +/// first, so a turn under way is ended the way a stop ends it, its work saved. +fn remake(cfg: &Config, user: &str, d: bool, fresh: bool) -> Result<(), String> { + let name = container_name(user); + let env = docker(&["inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", &name]).unwrap_or_default(); + let val = |k: &str| env.lines().find_map(|l| l.strip_prefix(&format!("{k}=")).map(String::from)).filter(|v| !v.is_empty()); + let sign_in = if fresh { None } else { val("ANYBOT_HOST_ID").zip(val("ANYBOT_HOST_TOKEN")) }; + // A new sign-in, if one is needed, before the old brain is touched (a refusal touches nothing). + let (id, token) = match sign_in { + Some(s) => s, + None => issue(cfg, user)?, + }; + // Made beside the running one, under a name of its own: Docker checks everything when making + // a container, so one it refuses (a limit it won't take, a full disk) leaves the old brain + // running, untouched — it used to be stopped and started again every try. + let new = format!("{name}-new"); + let aside = format!("{name}-old"); + let _ = docker(&["rm", "-f", &new]); + let mut args = create_args(user, &id, &token, d, &layers(&cfg.image), cfg); + if let Some(i) = args.iter().position(|a| a == "--name") { + args[i + 1] = new.clone(); + } + let a: Vec<&str> = args.iter().map(String::as_str).collect(); + let made = docker(&a).and_then(|_| match (d, &cfg.docker_network) { + (true, Some(n)) => docker(&["network", "connect", n, &new]), + _ => Ok(String::new()), + }); + if let Err(e) = made { + let _ = docker(&["rm", "-f", &new]); + return Err(format!("{user} 的新版雲端大腦開不起來,原本的照常在跑:{e}")); + } + // Then the swap: the old one stopped (its turn ended the way a stop ends it), put aside, the + // new one under its name and started; the old one gone only once the new one runs. + // (The name it goes aside under is free first: one left there would keep the swap from + // happening only after the old one was stopped.) + let _ = docker(&["rm", "-f", &aside]); + if docker(&["inspect", "-f", "{{.Id}}", &aside]).is_ok() { + let _ = docker(&["rm", "-f", &new]); + return Err(format!("{user} 旁邊還有一個換下來的雲端大腦({aside})拿不掉,先不換")); + } + // (Gone on only when Docker says it stopped: a stop that failed and an answer that didn't + // come are both 「not sure」, and a running brain is never renamed under its own turn.) + let stopped = |n: &str| docker(&["inspect", "-f", "{{.State.Running}}", n]).is_ok_and(|s| s.trim() == "false"); + if docker(&["stop", "-t", "30", &name]).is_err() && !stopped(&name) { + let _ = docker(&["rm", "-f", &new]); + return Err(format!("{user} 原本的雲端大腦停不下來,先不換")); + } + log::info!("AnyBot 大腦管理員:{user} 的雲端大腦{}", if fresh { "登入不在了,換一個新的" } else { "換成新版" }); + let back = |why: String| { + let _ = docker(&["rm", "-f", &name]); + let _ = docker(&["rename", &aside, &name]); + let _ = docker(&["start", &name]); + let _ = docker(&["rm", "-f", &new]); + Err(format!("{user} 的新版雲端大腦開不起來,先用原本的:{why}")) + }; + if let Err(e) = docker(&["rename", &name, &aside]) { + let _ = docker(&["start", &name]); + let _ = docker(&["rm", "-f", &new]); + return Err(format!("{user} 的雲端大腦換不了:{e}")); + } + if let Err(e) = docker(&["rename", &new, &name]) { + return back(e); + } + if let Err(e) = docker(&["start", &name]) { + return back(e); + } + let _ = docker(&["rm", "-f", &aside]); + log::info!("AnyBot 大腦管理員:{user} 的雲端大腦開好了({name}{})", if d { ",有 Bot 的電腦" } else { "" }); + Ok(()) +} + +/// A cloud brain's sign-in from the account server (a new host token for 「雲端大腦」). +fn issue(cfg: &Config, user: &str) -> Result<(String, String), String> { + let v = post(cfg, "/relay/manager/brain", &json!({"user": user, "name": "雲端大腦"}))?; + let (id, token) = (v["id"].as_str().unwrap_or("").to_string(), v["token"].as_str().unwrap_or("").to_string()); + if id.is_empty() || token.is_empty() { + return Err(format!("帳號伺服器沒有給 {user} 的登入憑證")); + } + Ok((id, token)) +} + +fn create(cfg: &Config, user: &str, d: bool, sign_in: Option<(String, String)>) -> Result<(), String> { + let (id, token) = match sign_in { + Some(s) => s, + None => issue(cfg, user)?, + }; + let args = create_args(user, &id, &token, d, &layers(&cfg.image), cfg); + let a: Vec<&str> = args.iter().map(String::as_str).collect(); + docker(&a)?; + let name = container_name(user); + // Made, joined to its networks, then started — or taken away whole, to be made again. + let rest = (|| { + if d { + if let Some(n) = &cfg.docker_network { + docker(&["network", "connect", n, &name])?; + } + } + docker(&["start", &name]) + })(); + if let Err(e) = rest { + let _ = docker(&["rm", "-f", &name]); + return Err(e); + } + log::info!("AnyBot 大腦管理員:{user} 的雲端大腦開好了({name}{})", if d { ",有 Bot 的電腦" } else { "" }); + Ok(()) +} + +/// The accounts, and the brain the account server knows for each (an older one doesn't say). +fn accounts(cfg: &Config) -> Result<(Vec, Option>), String> { + let mut r = crate::net::agent(15) + .get(&format!("{}/relay/manager/users", cfg.relay)) + .header("Authorization", &format!("Bearer {}", cfg.key)) + .call() + .map_err(|e| format!("連不到帳號伺服器({}):{e}", cfg.relay))?; + let status = r.status().as_u16(); + let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); + if status != 200 { + return Err(format!("帳號伺服器不讓大腦管理員進來({status}):ANYBOT_RELAY_MANAGER_TOKEN 兩邊要一樣")); + } + Ok((parse_accounts(&v), parse_managed(&v))) +} + +pub fn parse_accounts(v: &Value) -> Vec { + v["users"].as_array().into_iter().flatten().filter_map(|u| u.as_str()).map(|n| Account { name: n.to_string(), created: v["created"][n].as_i64().unwrap_or(0) }).collect() +} + +pub fn parse_managed(v: &Value) -> Option> { + v["brains"].as_object().map(|m| m.iter().filter_map(|(u, id)| Some((u.clone(), id.as_str()?.to_string()))).collect()) +} + +fn post(cfg: &Config, path: &str, body: &Value) -> Result { + let mut r = crate::net::agent(15) + .post(&format!("{}{path}", cfg.relay)) + .header("Authorization", &format!("Bearer {}", cfg.key)) + .send_json(body) + .map_err(|e| format!("連不到帳號伺服器:{e}"))?; + let status = r.status().as_u16(); + let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); + if status != 200 { + return Err(format!("帳號伺服器回 {status}:{}", v["error"].as_str().unwrap_or(""))); + } + Ok(v) +} + +/// The brains Docker has (made by this manager: labelled with their account). +fn existing() -> Result, String> { + let ids = docker(&["ps", "-aq", "--filter", "label=anybot.brain.user"])?; + let ids: Vec<&str> = ids.split_whitespace().collect(); + if ids.is_empty() { + return Ok(HashMap::new()); + } + let mut args = vec!["inspect", "-f", "{{index .Config.Labels \"anybot.brain.user\"}}\t{{.Name}}\t{{.State.Running}}\t{{index .Config.Labels \"anybot.brain.layers\"}}\t{{index .Config.Labels \"anybot.brain.docker\"}}\t{{index .Config.Labels \"anybot.brain.args\"}}\t{{index .Config.Labels \"anybot.brain.host\"}}"]; + args.extend(ids); + // (What each was made from is the label set then: a brain from before the label has none, and + // is made again once.) + let out = docker(&args)?; + let (aside, found) = parse_inspect_aside(&out); + // One made beside a brain by a remake that was cut short: never swapped in — gone. + for (_, e) in parse_inspect_lines(&out).into_iter().filter(|(_, e)| e.name.ends_with("-new")) { + let _ = docker(&["rm", "-f", &e.name]); + } + // One kept aside by a remake that was cut short (the manager stopped in the middle): put back + // when there is no new one, gone when there is. + let mut found = found; + for (user, e) in aside { + let name = container_name(&user); + if found.contains_key(&user) { + let _ = docker(&["rm", "-f", &e.name]); + } else if docker(&["rename", &e.name, &name]).is_ok() { + found.insert(user, Existing { name, ..e }); + } + } + Ok(found) +} + +/// The brains and the ones kept aside (named …-old) by a remake. +pub fn parse_inspect_aside(out: &str) -> (Vec<(String, Existing)>, HashMap) { + let mut aside = vec![]; + let mut found = HashMap::new(); + for (user, e) in parse_inspect_lines(out) { + if e.name.ends_with("-old") { + aside.push((user, e)); + } else if !e.name.ends_with("-new") { + found.insert(user, e); + } + } + (aside, found) +} + +/// What an image holds: a hash of its layers (empty when Docker can't say). The same after a +/// build that changed nothing; another when the program changed. +fn layers(image: &str) -> String { + match docker(&["image", "inspect", "-f", "{{range .RootFS.Layers}}{{.}},{{end}}", image]) { + Ok(l) if !l.trim().is_empty() => crate::httpd::sha256_hex(l.trim())[..16].to_string(), + _ => String::new(), + } +} + +pub fn parse_inspect(out: &str) -> HashMap { + parse_inspect_lines(out).into_iter().collect() +} + +fn parse_inspect_lines(out: &str) -> Vec<(String, Existing)> { + out.lines() + .filter_map(|l| { + let f: Vec<&str> = l.split('\t').map(str::trim).collect(); + let (user, name) = (*f.first()?, f.get(1)?.trim_start_matches('/')); + let at = |i: usize| f.get(i).copied().unwrap_or("").trim_start_matches("").to_string(); + (!user.is_empty() && !name.is_empty()).then(|| (user.to_string(), Existing { name: name.to_string(), running: f.get(2) == Some(&"true"), image: at(3), docker: f.get(4) == Some(&"1"), args: at(5), host: at(6) })) + }) + .collect() +} + +fn docker(args: &[&str]) -> Result { + let out = Command::new("docker").args(args).output().map_err(|e| format!("執行不了 docker:{e}"))?; + if out.status.success() { + Ok(String::from_utf8_lossy(&out.stdout).to_string()) + } else { + // (The token is in `docker create`'s arguments: never in what is said.) + Err(format!("docker {} 失敗:{}", args.first().unwrap_or(&""), String::from_utf8_lossy(&out.stderr).trim())) + } +} + +fn data_folder() -> std::path::PathBuf { + crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir) +} + +/// From the environment, and from the manager's own container: its image and networks. The day +/// it first ran is kept in its data folder (accounts made before it are left alone). +fn config() -> Result { + let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()); + let list = |k: &str| var(k).map(|s| s.split(',').map(|x| x.trim().to_lowercase()).filter(|x| !x.is_empty()).collect()).unwrap_or_default(); + let key = var("ANYBOT_RELAY_MANAGER_TOKEN").filter(|k| k.len() >= 32).ok_or("沒有 ANYBOT_RELAY_MANAGER_TOKEN(32 個字以上,跟帳號伺服器的一樣)")?; + let relay = var("ANYBOT_RELAY_INTERNAL").unwrap_or_else(|| "http://relay-manager:8080".into()); + let brain_relay = var("ANYBOT_BRAIN_RELAY").unwrap_or_else(|| "http://relay:8080".into()); + let me = var("HOSTNAME").ok_or("不知道自己的容器(沒有 HOSTNAME)")?; + let image = match var("ANYBOT_BRAIN_IMAGE") { + Some(i) => i, + None => docker(&["inspect", "-f", "{{.Config.Image}}", &me])?.trim().to_string(), + }; + let nets = docker(&["inspect", "-f", "{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}", &me])?; + let nets: Vec = nets.split_whitespace().map(String::from).collect(); + // The account server's network is the compose project's default one; Docker's proxy's ends + // in docker-api (the manager's own network with the account server is neither). + let network = nets.iter().find(|n| n.ends_with("_default")).cloned().ok_or("找不到帳號伺服器的網路")?; + let docker_network = nets.iter().find(|n| n.ends_with("docker-api")).cloned(); + let folder = data_folder(); + let since_file = folder.join("brains-since"); + let since = match std::fs::read_to_string(&since_file).ok().and_then(|s| s.trim().parse::().ok()) { + Some(t) => t, + None => { + let t = chrono::Utc::now().timestamp(); + std::fs::create_dir_all(&folder).map_err(|e| format!("寫不了資料夾:{e}"))?; + std::fs::write(&since_file, t.to_string()).map_err(|e| format!("寫不了 {}:{e}", since_file.display()))?; + t + } + }; + let env = ["ANYBOT_VOICE_URL", "ANYBOT_VOICE_LISTEN_MODEL", "ANYBOT_VOICE_SPEAK_MODEL", "ANYBOT_VOICE_VOICE", "ANYBOT_HF_BASE"].iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(); + let docker_env = ["DOCKER_HOST"].iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(); + let memory = var("ANYBOT_BRAIN_MEMORY").filter(|m| m.chars().all(|c| c.is_ascii_alphanumeric())).unwrap_or_else(|| "4g".into()); + // A share of the CPUs only where Docker can hold a container to one, and never more than the + // machine has (a one-CPU server refused --cpus 2, and no brain was made). + let have = std::thread::available_parallelism().map(|n| n.get() as f32).unwrap_or(1.0); + let want = var("ANYBOT_BRAIN_CPUS").and_then(|m| m.parse::().ok()).filter(|n| *n > 0.0).unwrap_or(2.0); + // (Not answered — the proxy still starting, an older one without INFO: asked again after a + // restart, rather than every brain made again without its CPU limit and again later with.) + let cfs = docker(&["info", "-f", "{{.CPUCfsQuota}}"]).map_err(|e| format!("問不到 Docker 能不能限 CPU({e})"))?.trim() == "true"; + let cpus = cfs.then(|| format!("{}", want.min(have))); + let max = var("ANYBOT_BRAINS_MAX").and_then(|m| m.parse::().ok()).unwrap_or(20); + Ok(Config { relay, brain_relay, key, image, network, docker_network, skip: list("ANYBOT_BRAINS_SKIP"), docker_users: list("ANYBOT_BRAINS_DOCKER"), since, all: var("ANYBOT_BRAINS_ALL").as_deref() == Some("1"), memory, cpus, max, env, docker_env }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn acct(n: &str, created: i64) -> Account { + Account { name: n.into(), created } + } + + fn cfg() -> Config { + Config { relay: "http://relay-manager:8080".into(), brain_relay: "http://relay:8080".into(), key: "k".into(), image: "anybot-brain:local".into(), network: "server_default".into(), docker_network: Some("server_docker-api".into()), since: 100, memory: "4g".into(), cpus: Some("2".into()), max: 20, docker_env: vec![("DOCKER_HOST".into(), "tcp://docker-socket-proxy:2375".into())], ..Default::default() } + } + + fn made(user: &str, docker: bool, image: &str, host: &str, c: &Config) -> Existing { + Existing { name: container_name(user), running: true, image: image.into(), docker, args: args_hash(user, docker, c), host: host.into() } + } + + /// Every account made since the manager came gets one brain: made once, started again when + /// stopped, made again from a newer image or other settings, left alone while right; the + /// older setup's own account and accounts from before the manager are left as they were. + #[test] + fn each_account_gets_one_brain() { + let c = Config { skip: vec!["OLD".into()], ..cfg() }; + let accounts = vec![acct("boss", 150), acct("amy", 160), acct("bob", 170), acct("old", 120), acct("family", 50), acct("new", 180), acct("set", 190)]; + let mut have = HashMap::new(); + have.insert("amy".to_string(), made("amy", false, "sha:1", "", &c)); + have.insert("bob".to_string(), Existing { running: false, ..made("bob", false, "sha:1", "", &c) }); + have.insert("new".to_string(), made("new", false, "sha:0", "", &c)); + have.insert("set".to_string(), Existing { args: "made-another-way".into(), ..made("set", false, "sha:1", "", &c) }); + assert_eq!( + plan(&accounts, &have, "sha:1", Some("boss"), None, &c), + vec![Action::Create("boss".into(), true), Action::Start(container_name("bob"), false), Action::Remake("new".into(), false, false), Action::Remake("set".into(), false, false)], + "family (made before the manager) is left alone; a new brain first, the updates last" + ); + // At most `max` brains: four there, room for none. + let full = Config { max: 4, ..c.clone() }; + assert!(!plan(&accounts, &have, "sha:1", Some("boss"), None, &full).iter().any(|a| matches!(a, Action::Create(..)))); + let one = Config { max: 5, ..c.clone() }; + assert_eq!(plan(&accounts, &have, "sha:1", Some("boss"), None, &one).iter().filter(|a| matches!(a, Action::Create(..))).count(), 1); + // A brain stopped on purpose (skipped) doesn't take a place. + let stopped = Config { max: 4, skip: vec!["OLD".into(), "bob".into()], ..c.clone() }; + assert_eq!(plan(&accounts, &have, "sha:1", Some("boss"), None, &stopped).iter().filter(|a| matches!(a, Action::Create(..))).count(), 1); + // With every account from before too. + let all = Config { all: true, ..c.clone() }; + assert!(plan(&accounts, &have, "sha:1", Some("boss"), None, &all).contains(&Action::Create("family".into(), false))); + // An image not known (inspect failed): no remake for it. + assert!(!plan(&accounts, &have, "", Some("boss"), None, &c).iter().any(|a| matches!(a, Action::Remake(n, ..) if n == "new"))); + } + + /// A brain whose sign-in the account server no longer has is made again with a new one; an + /// older account server that doesn't say leaves it be. + #[test] + fn a_brain_whose_sign_in_is_gone_gets_a_new_one() { + let c = cfg(); + let accounts = vec![acct("boss", 150), acct("amy", 160)]; + let mut have = HashMap::new(); + have.insert("boss".to_string(), made("boss", true, "i", "b1", &c)); + have.insert("amy".to_string(), made("amy", false, "i", "a1", &c)); + let mut m = HashMap::new(); + m.insert("boss".to_string(), "b1".to_string()); + assert_eq!(plan(&accounts, &have, "i", Some("boss"), Some(&m), &c), vec![Action::Remake("amy".into(), false, true)]); + m.insert("amy".to_string(), "a1".to_string()); + assert!(plan(&accounts, &have, "i", Some("boss"), Some(&m), &c).is_empty()); + assert!(plan(&accounts, &have, "i", Some("boss"), None, &c).is_empty()); + } + + /// Docker is the whole server: only the owner's brain and the ones named; the owner is the + /// first account made. + #[test] + fn only_the_owner_and_the_named_get_docker() { + let accounts = vec![acct("amy", 200), acct("boss", 150), acct("bob", 300)]; + assert_eq!(first_account(&accounts), Some("boss")); + assert!(gets_docker("boss", Some("boss"), &[])); + assert!(!gets_docker("amy", Some("boss"), &[]) && !gets_docker("bob", Some("boss"), &[])); + assert!(gets_docker("bob", Some("boss"), &["BOB".into()])); + assert!(!gets_docker("boss", None, &[])); + // A brain given Docker it shouldn't have is made again without. + let c = cfg(); + let mut have = HashMap::new(); + have.insert("amy".to_string(), made("amy", true, "i", "", &c)); + have.insert("boss".to_string(), made("boss", true, "i", "", &c)); + assert_eq!(plan(&accounts, &have, "i", Some("boss"), None, &c), vec![Action::Create("bob".into(), false), Action::Remake("amy".into(), false, false)]); + } + + /// Docker names from account names: allowed letters only, apart when the names differ. + #[test] + fn account_names_make_docker_names() { + let ok = |n: &str| n.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') && n.len() <= 60; + for u in ["amy", "a.b", "a_b", "a@b.com", "Ünïcode", "-x-", "", "a-b"] { + assert!(ok(&slug(u)), "{u} → {}", slug(u)); + assert!(ok(&format!("anybot-box-home-{}", slug(u)))); + } + assert_ne!(slug("a.b"), slug("a_b")); + assert_ne!(slug("a@b"), slug("a-b")); + assert_eq!(slug("amy"), slug("amy")); + assert!(container_name("amy").starts_with("anybot-brain-amy-")); + } + + /// A brain's `docker create`: its account, sign-in, own volume, the account server's network, + /// no raw packets or new privileges, its limits; Docker, its box and the box's home only for a + /// brain given Docker; how it was made and its sign-in's id as labels; the image and + /// `anybot --serve` last; no password. + #[test] + fn a_brain_runs_with_its_own_things() { + let s = slug("amy"); + let has = |a: &[String], pair: [&str; 2]| a.windows(2).any(|w| w[0] == pair[0] && w[1] == pair[1]); + let with = create_args("amy", "id1", "tok1", true, "abc123", &cfg()); + assert_eq!(with[0], "create"); + assert!(has(&with, ["--restart", "unless-stopped"]) && has(&with, ["--name", &container_name("amy")])); + assert!(has(&with, ["-v", &format!("anybot-brain-{s}:/data")]) && has(&with, ["--network", "server_default"])); + assert!(has(&with, ["--cap-drop", "NET_RAW"]) && has(&with, ["--security-opt", "no-new-privileges"]) && has(&with, ["--memory", "4g"]) && has(&with, ["--memory-swap", "4g"]) && has(&with, ["--cpus", "2"]) && has(&with, ["--pids-limit", "2048"])); + assert!(has(&with, ["--label", "anybot.brain.user=amy"]) && has(&with, ["--label", "anybot.brain.docker=1"]) && has(&with, ["--label", "anybot.brain.host=id1"])); + assert!(has(&with, ["--label", &format!("anybot.brain.args={}", args_hash("amy", true, &cfg()))]) && has(&with, ["--label", "anybot.brain.layers=abc123"])); + for e in ["ANYBOT_ACCOUNT=http://relay:8080|amy", "ANYBOT_HOST_ID=id1", "ANYBOT_HOST_TOKEN=tok1", &format!("ANYBOT_BOX_NAME=anybot-box-{s}"), &format!("ANYBOT_BOX_VOLUME=anybot-box-home-{s}"), "DOCKER_HOST=tcp://docker-socket-proxy:2375"] { + assert!(has(&with, ["-e", e]), "{e} in {with:?}"); + } + assert_eq!(&with[with.len() - 3..], ["anybot-brain:local", "anybot", "--serve"]); + assert!(!with.iter().any(|x| x.contains("PASSWORD") || x.contains("relay-manager")), "no password; the manager's own way to the account server isn't the brain's"); + // A Docker that can't hold a container to a share of the CPUs: no --cpus (it was refused). + assert!(!create_args("amy", "id1", "tok1", true, "abc123", &Config { cpus: None, ..cfg() }).iter().any(|x| x == "--cpus")); + // Without Docker: no proxy, no box; the network is the account server's only. + let without = create_args("amy", "id1", "tok1", false, "abc123", &cfg()); + assert!(!without.iter().any(|x| x.contains("DOCKER_HOST") || x.contains("ANYBOT_BOX") || x.contains("docker-api")), "{without:?}"); + assert!(has(&without, ["--label", "anybot.brain.docker=0"]) && has(&without, ["--cap-drop", "NET_RAW"])); + // The sign-in isn't part of how it was made: a new one doesn't make it "different". + assert_eq!(args_hash("amy", true, &cfg()), args_hash("amy", true, &cfg())); + assert_ne!(args_hash("amy", true, &cfg()), args_hash("amy", false, &cfg())); + assert_ne!(args_hash("amy", true, &cfg()), args_hash("amy", true, &Config { memory: "8g".into(), ..cfg() })); + } + + /// A brain kept aside by a remake (…-old) is told apart from the brains. + #[test] + fn a_brain_kept_aside_is_told_apart() { + let (aside, found) = parse_inspect_aside("amy\t/anybot-brain-amy-1-old\tfalse\tl1\t1\th\tid\nbob\t/anybot-brain-bob-2\ttrue\tl1\t0\th\tid\nbob\t/anybot-brain-bob-2-new\tfalse\tl2\t0\th\tid\n"); + assert_eq!(aside.len(), 1); + assert_eq!(found["bob"].name, "anybot-brain-bob-2", "one made beside it isn't the brain"); + assert_eq!(aside[0].0, "amy"); + assert!(found.contains_key("bob") && !found.contains_key("amy")); + } + + /// An account that keeps failing is tried less and less often, never less than every half hour. + #[test] + fn an_account_that_keeps_failing_rests_longer() { + let mins: Vec = (1..=8).map(|n| super::rest_for(n).as_secs() / 60).collect(); + assert_eq!(mins, [1, 2, 4, 8, 16, 30, 30, 30]); + assert_eq!(super::rest_for(0).as_secs(), 60); + } + + #[test] + fn what_docker_and_the_account_server_say_reads_back() { + let m = parse_inspect("amy\t/anybot-brain-amy-1\ttrue\tsha256:aa\t1\th1\tid9\nbob\t/anybot-brain-bob-2\tfalse\tsha256:bb\t0\t\t\n\n\tx\ty\n"); + assert_eq!(m.len(), 2); + assert!(m["amy"].running && m["amy"].docker && !m["bob"].running && !m["bob"].docker); + assert_eq!((m["amy"].args.as_str(), m["amy"].host.as_str()), ("h1", "id9")); + assert_eq!((m["bob"].name.as_str(), m["bob"].image.as_str(), m["bob"].args.as_str(), m["bob"].host.as_str()), ("anybot-brain-bob-2", "sha256:bb", "", "")); + let v = json!({"users": ["boss", "amy"], "created": {"boss": 10, "amy": 20}, "brains": {"amy": "a1"}}); + assert_eq!(parse_accounts(&v), vec![acct("boss", 10), acct("amy", 20)]); + assert_eq!(parse_managed(&v).unwrap().get("amy").map(String::as_str), Some("a1")); + // An older account server without the times or the brains. + assert_eq!(parse_accounts(&json!({"users": ["x"]})), vec![acct("x", 0)]); + assert!(parse_managed(&json!({"users": ["x"]})).is_none()); + } +} diff --git a/src/featuremap.rs b/src/featuremap.rs index 4052a96..8e8c920 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -67,6 +67,7 @@ pub const AREAS: &[Area] = &[ area!("phone", "手機頁面"), area!("phonefit", "手機畫面貼齊"), area!("account", "帳號與直接連線"), + area!("server", "伺服器與雲端大腦"), area!("safety", "安全與核准"), area!("sandbox", "安全規則與沙盒"), area!("autonomy", "直接操作、一律放行與自動審核"), diff --git a/src/main.rs b/src/main.rs index f75f0ff..07b3c6a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,7 @@ mod axread; mod axwrite; mod avatar; mod bidi; +mod brains; mod botbrowser; mod browser; mod cloudbox; @@ -390,6 +391,10 @@ fn main() -> eframe::Result<()> { outputs::prune(); // 檢查點 kept content no change has used for a week. checkpoint::prune(); + // `anybot --brains` (deploy/server's `brains`): 大腦管理員 — a cloud brain for every account. + if args.get(1).map(String::as_str) == Some("--brains") { + brains::run(); + } // `anybot --update-box` (make update-box): 更新 Bot 的電腦 from a terminal, by this AnyBot — // or the one running on this data folder (cloudbox::update_box_cli). if args.get(1).map(String::as_str) == Some("--update-box") { diff --git a/src/providers.rs b/src/providers.rs index 0c7d589..a966987 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -265,6 +265,10 @@ pub enum StreamEvent { /// Old step results were set aside from the model's view (their call ids): the chat marks /// them, so the model reads them the same way next turn. Folded(Vec), + /// Earlier thinking no longer held for this conversation was left out (providers:: + /// forget_thinking): the chat lets go of the thinking blocks it keeps too, so the next turn + /// doesn't send them again and lose the turn's own with them. + ThinkingForgotten, /// The model said how much it can read (its "too long" error named it): kept as the bot's /// context size, so it is summarized in time from now on. ContextLimit(u64), @@ -339,6 +343,10 @@ pub struct StepOutput { pub tool_calls: Vec, /// Claude's raw content blocks, kept to replay thinking signatures unchanged. pub blocks: Vec, + /// Earlier thinking blocks no longer held for this conversation were left out of this step + /// (by the API, or taken out to send it again): the turn's history before this step is + /// sent without thinking from now on, or every step would leave them out again. + pub old_thinking_left_out: bool, /// 用量: what this step used, as the provider said (zero when it didn't). pub usage: Usage, } @@ -868,9 +876,18 @@ pub fn run_step(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEven out.text = hant(&out.text); out.thinking = hant(&out.thinking); out.tool_calls = out.tool_calls.into_iter().map(hant_call).collect(); - // Keep Anthropic's `blocks` consistent with `text` and `tool_calls` (never touching `thinking` - // blocks, which carry cryptographic signatures). - for b in out.blocks.iter_mut() { + hant_blocks(&mut out.blocks); + Ok(out) +} + +/// Anthropic's `blocks` put in Traditional like `text` and `tool_calls` — only after the last +/// thinking block: a thinking block's signature binds everything before it as it was written, +/// and a word put in Traditional ahead of one made Claude refuse the next step (400 「Invalid +/// signature in thinking block… bound to a different conversation」). +fn hant_blocks(blocks: &mut [Value]) { + use crate::i18n::hant; + let from = blocks.iter().rposition(|b| matches!(b["type"].as_str(), Some("thinking" | "redacted_thinking"))).map_or(0, |i| i + 1); + for b in blocks.iter_mut().skip(from) { match b["type"].as_str() { Some("text") => { if let Some(t) = b["text"].as_str().map(hant) { @@ -886,7 +903,6 @@ pub fn run_step(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEven _ => {} } } - Ok(out) } /// Steps whose words are for the person to read (a question card, a card, a page, a memory, a @@ -2045,7 +2061,20 @@ fn cache_tail(mut messages: Vec) -> Vec { } -fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { +/// A thinking block is bound to the conversation that produced it: its signature records the +/// system prompt, the tools and everything before it, as sent. Where AnyBot's history no longer +/// reads the same (a step's result set aside, a message left out, words changed), an account the +/// API holds to that refused the whole turn — 400 「Invalid signature in thinking block… bound to +/// a different conversation」. Then the step goes again with `drop_block` (the API leaves such +/// blocks out, the turn goes on without that reasoning), and that address and model get it from +/// then on. Not before: on an account the API doesn't hold to it, setting it would turn the check +/// on, and blocks the model still reads would be left out. Straight to Anthropic only: a gateway +/// may not know the beta (it gets the strip-and-retry in stream_anthropic). +const THINKING_BINDING_BETA: &str = "thinking-binding-controls-2026-08-01"; + +/// The Messages request for this step, and the betas it needs (one `anthropic-beta` header). +fn anthropic_request(req: &ChatRequest) -> (Value, Vec<&'static str>) { + let mut betas = vec![]; let mut body = json!({ "model": req.model, "max_tokens": MAX_OUTPUT_TOKENS_ANTHROPIC, @@ -2062,6 +2091,10 @@ fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Stream } if claude_adaptive(&req.model) { body["thinking"] = json!({"type": "adaptive", "display": "summarized"}); + if NEEDS_BINDING.lock().unwrap_or_else(|e| e.into_inner()).contains(&binding_key(req)) && can_bind(req) { + body["thinking"]["block_binding"] = json!({"prefix_mismatch_behavior": "drop_block"}); + betas.push(THINKING_BINDING_BETA); + } // 思考模式: these models always think; how deeply is `output_config.effort`. if let Some(e) = effort_of(req) { body["output_config"] = json!({"effort": e}); @@ -2076,28 +2109,162 @@ fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Stream body["tools"] = json!(tools); } body["messages"] = json!(cache_tail(anthropic_messages(req))); - let mut r = agent() - .post(&format!("{}/messages", req.base_url)) - .header("Content-Type", "application/json") - .header("x-api-key", &req.api_key) - .header("anthropic-version", ANTHROPIC_VERSION); - if req.kind == ProviderKind::OpenCodeGo { - // Its Anthropic-style door takes the key as a bearer token too. - r = r.header("Authorization", &format!("Bearer {}", req.api_key)).header("x-opencode-session", &opencode_session(req)); - } if claude_fallbacks(&req.model) { body["fallbacks"] = json!("default"); - r = r.header("anthropic-beta", "server-side-fallback-2026-07-01"); + betas.push("server-side-fallback-2026-07-01"); } - // SAND-E0418 turnBackendUnreachable: retryable. - let resp = r.send_json(&body).map_err(|e| Failure::retry(connect_error(req.kind, &e.to_string())))?; - let status = resp.status().as_u16(); - if status >= 400 { + (body, betas) +} + +/// Addresses and models that refused a thinking block as bound elsewhere: sent `drop_block` from +/// then on, while AnyBot runs. +static NEEDS_BINDING: std::sync::LazyLock>> = std::sync::LazyLock::new(Default::default); +/// Anthropic-style addresses and models that refused `thinking.block_binding` (a proxy that doesn't +/// know the beta): not sent there again while AnyBot runs. +static NO_BINDING: std::sync::LazyLock>> = std::sync::LazyLock::new(Default::default); + +/// Whether this step can ask for `drop_block`: Claude with adaptive thinking, straight to +/// Anthropic, at an address that hasn't refused it. +fn can_bind(req: &ChatRequest) -> bool { + req.kind == ProviderKind::Anthropic && claude_adaptive(&req.model) && !NO_BINDING.lock().unwrap_or_else(|e| e.into_inner()).contains(&binding_key(req)) +} + +/// Per address, model and account (the key's hash): one account held to the check doesn't turn +/// it on for another one's bots. +fn binding_key(req: &ChatRequest) -> String { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + req.api_key.hash(&mut h); + format!("{} {} {:x}", req.base_url, req.model, h.finish()) +} + +/// A 400 for the binding control itself (the field or its beta unknown there) — not for a +/// thinking block, whose error names the same field in its advice. +fn binding_refused(status: u16, body: &str) -> bool { + // (A pydantic-style proxy refuses an unknown field with 422.) + matches!(status, 400 | 422) && !body.contains("bound to a different conversation") && (body.contains("block_binding") || body.contains(THINKING_BINDING_BETA)) +} + +/// Thinking blocks the API left out of this step because the history changed under them (or +/// they are another account's: never good again) — not another model's (a fallback model can't +/// read them, the next step's model may). +fn thinking_left_out(req: &ChatRequest, t: &Value) -> bool { + let Some(t) = t.as_array().filter(|t| !t.is_empty()) else { return false }; + log::warn!("AnyBot:{} 這一步沒用上較早的思考區塊:{}", req.model, Value::Array(t.clone()).to_string().chars().take(300).collect::()); + t.iter().any(|x| x["type"] == "thinking_dropped" && x["reason"].as_str().is_some_and(|r| r != "model_binding_mismatch")) +} + +/// The thinking taken out of messages already sent (each turn's words and calls stay as they +/// were): what to do once a step said earlier thinking no longer holds. From the front of the +/// conversation, which the API allows — the next step's blocks still hold. +pub fn forget_thinking(history: &mut [Message]) { + for m in history.iter_mut() { + m.blocks.retain(|b| !matches!(b["type"].as_str(), Some("thinking" | "redacted_thinking"))); + } +} + +/// The refusal `drop_block` is for: a thinking block bound to another conversation (not one whose +/// signature is broken or another account's — those are only stripped). +fn bound_elsewhere(status: u16, body: &str) -> bool { + thinking_refused(status, body) && body.contains("bound to a different conversation") +} + +/// A 400 for a thinking block whose signature doesn't hold here (another conversation, as a +/// gateway without the binding beta still says). +fn thinking_refused(status: u16, body: &str) -> bool { + status == 400 && body.contains("thinking") && (body.contains("Invalid signature") || body.contains("Invalid `signature`")) +} + +/// The messages without any thinking block (each turn's words and calls stay): the one-time +/// recovery when a thinking block is refused. A turn left empty goes, and turns of one side +/// that then meet become one, as the API wants. +fn without_thinking(messages: &Value) -> Value { + let mut out: Vec = vec![]; + for m in messages.as_array().into_iter().flatten() { + let mut m = m.clone(); + if let Some(c) = m["content"].as_array_mut() { + c.retain(|b| !matches!(b["type"].as_str(), Some("thinking" | "redacted_thinking"))); + if c.is_empty() { + continue; + } + } + match out.last_mut() { + Some(last) if last["role"] == m["role"] && last["content"].is_array() && m["content"].is_array() => { + let more = m["content"].as_array().cloned().unwrap_or_default(); + last["content"].as_array_mut().unwrap().extend(more); + } + _ => out.push(m), + } + } + json!(out) +} + +fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Result { + let (mut body, mut betas) = anthropic_request(req); + let post = |body: &Value, betas: &[&str]| { + let mut r = agent() + .post(&format!("{}/messages", req.base_url)) + .header("Content-Type", "application/json") + .header("x-api-key", &req.api_key) + .header("anthropic-version", ANTHROPIC_VERSION); + if req.kind == ProviderKind::OpenCodeGo { + // Its Anthropic-style door takes the key as a bearer token too. + r = r.header("Authorization", &format!("Bearer {}", req.api_key)).header("x-opencode-session", &opencode_session(req)); + } + if !betas.is_empty() { + r = r.header("anthropic-beta", &betas.join(",")); + } + // SAND-E0418 turnBackendUnreachable: retryable. + r.send_json(body).map_err(|e| Failure::retry(connect_error(req.kind, &e.to_string()))) + }; + let mut resp = post(&body, &betas)?; + let mut out_stripped = false; + // Refused for the thinking: the step is sent again with what that calls for — at most once + // for each. + let (mut bound, mut unbound, mut stripped) = (false, false, false); + while resp.status().as_u16() >= 400 { + let status = resp.status().as_u16(); let ra = retry_after_ms(&resp); let text = resp.into_body().read_to_string().unwrap_or_default(); - return Err(http_error(status, &text, ra)); + let sent_binding = body["thinking"]["block_binding"].is_object(); + // A refusal of the control itself: by name — or, right after asking for it, any 4xx that + // isn't about thinking or a limit (a gateway's plain 「Bad Request」, a firewall's 403). + let control_refused = binding_refused(status, &text) || (bound && (400..500).contains(&status) && !matches!(status, 408 | 429) && !thinking_refused(status, &text)); + if !unbound && sent_binding && control_refused { + // An Anthropic-style server that doesn't take `drop_block` (a proxy in front of it): + // without it, and never again to this address. + unbound = true; + log::warn!("AnyBot:{} 不接受 thinking.block_binding({} {}),之後不再送", req.base_url, status, text.chars().take(200).collect::()); + NO_BINDING.lock().unwrap_or_else(|e| e.into_inner()).insert(binding_key(req)); + NEEDS_BINDING.lock().unwrap_or_else(|e| e.into_inner()).remove(&binding_key(req)); + if let Some(t) = body["thinking"].as_object_mut() { + t.remove("block_binding"); + } + betas.retain(|b| *b != THINKING_BINDING_BETA); + // (The thinking it was asked for goes next, if that is still refused.) + } else if !bound && !sent_binding && bound_elsewhere(status, &text) && can_bind(req) { + // Held to the check: ask the API to leave out the blocks that don't hold. Kept for + // this address and model once it answers. + bound = true; + log::warn!("AnyBot:{} 不接受較早的思考內容,改請它略過對不上的思考區塊(drop_block)", req.model); + body["thinking"]["block_binding"] = json!({"prefix_mismatch_behavior": "drop_block"}); + betas.push(THINKING_BINDING_BETA); + } else if !stripped && thinking_refused(status, &text) { + // A thinking block refused anyway (no `drop_block` there): without the thinking — + // the turn goes on, without that reasoning. + stripped = true; + out_stripped = true; + log::warn!("AnyBot:{} 不接受較早的思考內容({}),拿掉思考區塊再送一次", req.model, text.chars().take(200).collect::()); + body["messages"] = without_thinking(&body["messages"]); + } else { + return Err(http_error(status, &text, ra)); + } + resp = post(&body, &betas)?; } - let mut out = StepOutput::default(); + if body["thinking"]["block_binding"].is_object() { + NEEDS_BINDING.lock().unwrap_or_else(|e| e.into_inner()).insert(binding_key(req)); + } + let mut out = StepOutput { old_thinking_left_out: out_stripped, ..Default::default() }; let mut blocks: Vec = vec![]; let mut partial_json: Vec = vec![]; let mut error = None; @@ -2175,6 +2342,7 @@ fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Stream } } "message_start" => { + out.old_thinking_left_out |= thinking_left_out(req, &v["message"]["input_transformations"]); if let Some(u) = v["message"]["usage"].as_object() { let g = |k: &str| u.get(k).and_then(|x| x.as_u64()).unwrap_or(0); out.usage.input = g("input_tokens"); @@ -2184,6 +2352,8 @@ fn stream_anthropic(req: &ChatRequest, cancel: &AtomicBool, send: &dyn Fn(Stream } } "message_delta" => { + // (Said again here after a fallback model took over mid-stream.) + out.old_thinking_left_out |= thinking_left_out(req, &v["input_transformations"]) | thinking_left_out(req, &v["delta"]["input_transformations"]); if let Some(n) = v["usage"]["output_tokens"].as_u64() { out.usage.output = n; } @@ -2634,6 +2804,79 @@ mod tests { assert_eq!(o[3]["role"], "tool"); } + /// A thinking block is bound to the conversation before it, as written. A history that no + /// longer reads the same made Claude refuse the whole turn (400 「Invalid signature in + /// thinking block… bound to a different conversation」, seen 2026-11-23): straight to + /// Anthropic the request asks it to leave such blocks out (`drop_block`, with its beta next + /// to the fallbacks one); a gateway that refuses anyway gets the turn once more without them; + /// and Traditional Chinese no longer rewrites what came before a thinking block. + #[test] + fn thinking_bound_to_another_conversation_no_longer_stops_the_turn() { + let req = |kind, model: &str| ChatRequest { kind, base_url: String::new(), api_key: String::new(), model: model.into(), system: "sys".into(), history: vec![Message::user("hi")], tools: vec![], session: String::new(), effort: String::new() }; + // Not asked for until refused once (on an account the API doesn't hold to the check, + // setting it would turn the check on); then for that address and model from then on. + let mut direct = req(ProviderKind::Anthropic, "claude-opus-5-5"); + direct.base_url = "https://api.example/held".into(); + let (body, betas) = anthropic_request(&direct); + assert_eq!(body["thinking"]["type"], "adaptive"); + assert!(body["thinking"]["block_binding"].is_null()); + assert_eq!(betas, vec!["server-side-fallback-2026-07-01"]); + NEEDS_BINDING.lock().unwrap().insert(binding_key(&direct)); + let (body, betas) = anthropic_request(&direct); + assert_eq!(body["thinking"]["block_binding"]["prefix_mismatch_behavior"], "drop_block"); + assert_eq!(betas, vec![THINKING_BINDING_BETA, "server-side-fallback-2026-07-01"]); + // A gateway's Anthropic door: no beta it may not know; an older Claude: no thinking at all. + let (body, betas) = anthropic_request(&req(ProviderKind::OpenCodeGo, "claude-opus-5-5")); + assert!(body["thinking"]["block_binding"].is_null() && !betas.contains(&THINKING_BINDING_BETA)); + let (body, betas) = anthropic_request(&req(ProviderKind::Anthropic, "claude-haiku-4-5")); + assert!(body["thinking"].is_null() && betas.is_empty()); + + // A proxy in front of Anthropic that doesn't take the control: told apart from a refused + // thinking block (whose advice names the same field), and not sent there again. + assert!(binding_refused(400, r#"{"error":{"message":"thinking.block_binding: Extra inputs are not permitted"}}"#)); + assert!(binding_refused(400, r#"{"error":{"message":"Unexpected value(s) `thinking-binding-controls-2026-08-01` for the `anthropic-beta` header."}}"#)); + let mut proxied = req(ProviderKind::Anthropic, "claude-sonnet-5-5"); + proxied.base_url = "https://proxy.example/v1".into(); + assert!(binding_refused(422, r#"{"detail":[{"type":"extra_forbidden","loc":["body","thinking","block_binding"]}]}"#)); + NEEDS_BINDING.lock().unwrap().insert(binding_key(&proxied)); + NO_BINDING.lock().unwrap().insert(binding_key(&proxied)); + let (body, betas) = anthropic_request(&proxied); + assert!(body["thinking"]["block_binding"].is_null() && betas == vec!["server-side-fallback-2026-07-01"], "{betas:?}"); + assert_eq!(body["thinking"]["type"], "adaptive"); + + // The error as it came, and others that aren't it. + let seen =r#"{"type":"error","error":{"type":"invalid_request_error","message":"messages.9.content.2: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to \"drop_block\"."}}"#; + assert!(thinking_refused(400, seen)); + assert!(thinking_refused(400, "messages.5.content.0: Invalid `signature` in `thinking` block.")); + assert!(!thinking_refused(400, r#"{"error":{"message":"max_tokens: too large"}}"#)); + assert!(!thinking_refused(429, seen)); + + // Without thinking: words and calls stay; a turn left empty goes and its neighbours meet. + let msgs = json!([ + {"role": "user", "content": [{"type": "text", "text": "hi"}]}, + {"role": "assistant", "content": [{"type": "thinking", "thinking": "t", "signature": "s"}, {"type": "text", "text": "看看"}, {"type": "thinking", "thinking": "", "signature": "s2"}, {"type": "tool_use", "id": "c1", "name": "list_dir", "input": {}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "c1", "content": "a.txt"}]}, + {"role": "assistant", "content": [{"type": "redacted_thinking", "data": "x"}]}, + {"role": "user", "content": [{"type": "text", "text": "next"}]}, + ]); + let m = without_thinking(&msgs); + assert!(!m.to_string().contains("thinking"), "{m}"); + assert_eq!(m.as_array().unwrap().len(), 3); + assert_eq!(m[1]["content"].as_array().unwrap().len(), 2); + assert_eq!(m[2]["content"][0]["type"], "tool_result"); + assert_eq!(m[2]["content"][1]["text"], "next"); + + // Traditional Chinese: only after the last thinking block. + let mut blocks = vec![json!({"type": "thinking", "thinking": "", "signature": "s"}), json!({"type": "text", "text": "这里"}), json!({"type": "thinking", "thinking": "", "signature": "s2"}), json!({"type": "text", "text": "这里"})]; + hant_blocks(&mut blocks); + assert_eq!(blocks[1]["text"], "这里", "before a thinking block: as written"); + assert_eq!(blocks[3]["text"], crate::i18n::hant("这里")); + assert_ne!(blocks[3]["text"], "这里"); + let mut plain = vec![json!({"type": "text", "text": "这里"})]; + hant_blocks(&mut plain); + assert_eq!(plain[0]["text"], crate::i18n::hant("这里")); + } + #[test] fn screenshots_reach_the_model_and_old_ones_drop() { let n = crate::computer::KEEP_SCREENSHOTS + 1; @@ -2693,6 +2936,198 @@ mod tests { (format!("http://127.0.0.1:{port}"), rx) } + /// 真的連 Anthropic(要金鑰,花一點點錢;平常不跑)。在自己的終端機: + /// `read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY && cargo test --bin anybot anthropic_live -- --ignored --nocapture` + /// (金鑰不顯示、不存檔;`ANYBOT_LIVE_MODEL` 換模型,預設 claude-opus-5-5)。 + /// 走一遍:連得上、叫工具;思考區塊原樣送回被接受、沒被丟掉;歷史改過(原本那個 400)照樣回答; + /// 帶 drop_block 時 Anthropic 接受,並說它丟掉了對不上的思考。 + #[test] + #[ignore] + fn anthropic_live_thinking_replay_and_recovery() { + let key = std::env::var("ANTHROPIC_API_KEY").expect("先設 ANTHROPIC_API_KEY(read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY)"); + let model = std::env::var("ANYBOT_LIVE_MODEL").unwrap_or_else(|_| "claude-opus-5-5".into()); + let cancel = AtomicBool::new(false); + let tool = json!({"name": "lookup_weather", "description": "Look up today's weather for a city.", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}); + let mut req = ChatRequest { + kind: ProviderKind::Anthropic, + base_url: "https://api.anthropic.com/v1".into(), + api_key: key, + model: model.clone(), + system: "你是簡潔的助理,用繁體中文回答。被要求時一定要用工具。".into(), + history: vec![Message::user("請先想一下要查哪個城市,再用 lookup_weather 查台北今天的天氣,最後用一句話告訴我要不要帶傘。")], + tools: vec![tool], + session: String::new(), + effort: "medium".into(), + }; + let step = |req: &ChatRequest, what: &str| { + let out = run_step(req, &cancel, &|_| {}).unwrap_or_else(|e| panic!("{what}:{e}")); + let kinds: Vec<&str> = out.blocks.iter().filter_map(|b| b["type"].as_str()).collect(); + println!("{what}:文字「{}」 工具 {:?} 區塊 {kinds:?} 丟掉舊思考 {}", out.text.chars().take(60).collect::(), out.tool_calls.iter().map(|c| c.name.clone()).collect::>(), out.old_thinking_left_out); + out + }; + // 1. Connected: the model asks for the tool. + let s1 = step(&req, "1 連線、叫工具"); + let call = s1.tool_calls.first().cloned().expect("沒有叫工具"); + req.history.push(Message { blocks: s1.blocks.clone(), tool_calls: s1.tool_calls.clone(), ..Message::assistant(&s1.text, &format!("Anthropic · {model}")) }); + req.history.push(Message::tool_result(&call.id, &call.name, "台北:午後雷陣雨,降雨機率 70%,28°C")); + // 2. Its blocks back as written, with the result: accepted, nothing left out. + let s2 = step(&req, "2 工具結果送回"); + assert!(!s2.text.trim().is_empty(), "第二步沒有回答"); + assert!(!s2.old_thinking_left_out, "原樣送回的思考不該被丟掉"); + // The answer with its thinking (signed) goes into the history, as a turn keeps it. + req.history.push(Message { blocks: s2.blocks.clone(), ..Message::assistant(&s2.text, &format!("Anthropic · {model}")) }); + req.history.push(Message::user("那明天呢?一句話就好。")); + let signed = req.history.iter().flat_map(|m| m.blocks.iter()).filter(|b| b["type"] == "thinking" && b["signature"].as_str().is_some_and(|s| !s.is_empty())).count(); + println!("歷史裡帶簽章的思考區塊:{signed} 個"); + assert!(signed > 0, "模型兩步都沒寫思考區塊,驗證不到簽章(換個 ANYBOT_LIVE_MODEL 或再跑一次)"); + // 3. Sent back as written: accepted, nothing left out. + let s3 = step(&req, "3 思考原樣送回"); + assert!(!s3.text.trim().is_empty(), "思考原樣送回後沒有回答"); + assert!(!s3.old_thinking_left_out, "原樣送回的思考不該被丟掉"); + // 4. The history before that thinking changed (the bug that stopped the turn): answers. + let mut edited = req.clone(); + edited.history[0] = Message::user("請先想一下要查哪個城市,再用 lookup_weather 查台北今天的天氣,最後用一句話告訴我要不要帶傘。(改過)"); + let s4 = step(&edited, "4 歷史改過"); + assert!(!s4.text.trim().is_empty(), "歷史改過後沒有回答"); + let held = NEEDS_BINDING.lock().unwrap().contains(&binding_key(&edited)); + println!("這個帳號{}被要求檢查({})", if held { "" } else { "沒有" }, if held { "收到 400 後帶 drop_block 重送成功" } else { "對不上的思考照樣讀得到" }); + // 5. drop_block asked for: Anthropic takes it, and says what it left out. + NEEDS_BINDING.lock().unwrap().insert(binding_key(&edited)); + let (body, betas) = anthropic_request(&edited); + assert!(body["thinking"]["block_binding"].is_object() && betas.contains(&THINKING_BINDING_BETA)); + let s5 = step(&edited, "5 帶 drop_block"); + assert!(!s5.text.trim().is_empty(), "帶 drop_block 沒有回答"); + assert!(s5.old_thinking_left_out, "Anthropic 應該說它丟掉了對不上的思考"); + // 6. What the turn does then (forget_thinking): sent without the old thinking, nothing + // left out any more. + let mut after = edited.clone(); + forget_thinking(&mut after.history); + after.history.push(Message { blocks: s5.blocks.clone(), ..Message::assistant(&s5.text, &format!("Anthropic · {model}")) }); + after.history.push(Message::user("謝謝。")); + let s6 = step(&after, "6 忘掉舊思考之後"); + assert!(!s6.text.trim().is_empty(), "忘掉舊思考後沒有回答"); + assert!(!s6.old_thinking_left_out, "忘掉舊思考之後不該再丟"); + println!("全部通過({model})"); + } + + /// A server that answers each request it gets with the next (status, body), and records them. + fn scripted_server(answers: Vec<(u16, &'static str)>) -> (String, std::sync::mpsc::Receiver) { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for (status, body) in answers { + let Ok((mut s, _)) = l.accept() else { return }; + let mut req = Vec::new(); + let mut buf = [0u8; 8192]; + loop { + let n = s.read(&mut buf).unwrap_or(0); + if n == 0 { + break; + } + req.extend_from_slice(&buf[..n]); + let text = String::from_utf8_lossy(&req).to_string(); + if let Some(end) = text.find("\r\n\r\n") { + let len = text[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); + if req.len() >= end + 4 + len { + break; + } + } + } + let _ = tx.send(String::from_utf8_lossy(&req).to_string()); + let kind = if status == 200 { "text/event-stream" } else { "application/json" }; + let _ = s.write_all(format!("HTTP/1.1 {status} X\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()); + } + }); + (format!("http://127.0.0.1:{port}"), rx) + } + + /// The turn that stopped on 2026-11-23 (「錯誤 400:messages.9.content.2: Invalid signature in + /// thinking block. The block is bound to a different conversation…」), played through the + /// real step: straight to Anthropic the request asks for `drop_block`; behind a proxy that + /// refuses the control and then the thinking, the step is sent again without each and goes on. + #[test] + fn a_turn_with_thinking_from_another_conversation_goes_on() { + let cancel = AtomicBool::new(false); + let claude = "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"; + let mut a = Message::assistant("看看", "Anthropic · claude-opus-5-5"); + a.tool_calls = vec![ToolCall { id: "tu1".into(), name: "list_dir".into(), args: "{}".into(), status: ToolStatus::Done }]; + a.blocks = vec![json!({"type": "thinking", "thinking": "", "signature": "s1"}), json!({"type": "text", "text": "看看"}), json!({"type": "thinking", "thinking": "", "signature": "s2"}), json!({"type": "tool_use", "id": "tu1", "name": "list_dir", "input": {}})]; + let history = vec![Message::user("hi"), a, Message::tool_result("tu1", "list_dir", "a.txt"), Message::user("next")]; + let req = |base: &str| ChatRequest { kind: ProviderKind::Anthropic, base_url: format!("{base}/v1"), api_key: "k".into(), model: "claude-opus-5-5".into(), system: "s".into(), history: history.clone(), tools: vec![], session: String::new(), effort: String::new() }; + let flat = |s: String| s.split_whitespace().collect::(); + + let refused_thinking = r#"{"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.2: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to \"drop_block\". That setting requires the thinking-binding-controls-2026-08-01 value in the anthropic-beta header. Content that preceded this block when it was created is missing from this request, starting at `messages.1.content.1`."}}"#; + let dropped = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"input_transformations\":[{\"type\":\"thinking_dropped\",\"path\":\"messages.1.content.2\",\"reason\":\"prefix_binding_mismatch\"}]}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"; + + // Straight to Anthropic, an account held to the check: refused as it came, then the same + // step with drop_block and its beta (the thinking replayed as written) goes on — and that + // address and model get it from then on. + let (base, rx) = scripted_server(vec![(400, refused_thinking), (200, dropped)]); + let out = run_step(&req(&base), &cancel, &|_| {}).unwrap(); + assert_eq!(out.text, "ok"); + assert!(out.old_thinking_left_out, "the API said it left earlier thinking out"); + let (first, second) = (flat(rx.recv().unwrap()), flat(rx.recv().unwrap())); + assert!(!first.contains("block_binding") && first.contains("\"signature\":\"s2\""), "{first}"); + assert!(second.contains("\"block_binding\":{\"prefix_mismatch_behavior\":\"drop_block\"}"), "{second}"); + let beta = second.to_ascii_lowercase().split("anthropic-beta:").nth(1).and_then(|x| x.split("{").next()).unwrap_or("").to_string(); + assert!(beta.contains(THINKING_BINDING_BETA) && beta.contains("server-side-fallback-2026-07-01"), "{second}"); + assert!(second.contains("\"signature\":\"s1\"") && second.contains("\"signature\":\"s2\""), "{second}"); + assert!(anthropic_request(&req(&base)).0["thinking"]["block_binding"].is_object()); + + // A proxy: refuses the thinking, then the control (422), then the thinking again; the + // step goes without the control, then without the thinking, and answers. + let refused_control = r#"{"detail":[{"type":"extra_forbidden","loc":["body","thinking","block_binding"],"msg":"Extra inputs are not permitted"}]}"#; + let (base, rx) = scripted_server(vec![(400, refused_thinking), (422, refused_control), (400, refused_thinking), (200, claude)]); + let out = run_step(&req(&base), &cancel, &|_| {}).unwrap(); + assert_eq!(out.text, "ok"); + assert!(out.old_thinking_left_out, "it was sent without the earlier thinking"); + let sent: Vec = (0..4).map(|_| flat(rx.recv().unwrap())).collect(); + assert!(!sent[0].contains("block_binding") && sent[1].contains("block_binding")); + assert!(!sent[2].contains("block_binding") && !sent[2].contains(THINKING_BINDING_BETA) && sent[2].contains("\"signature\":\"s1\""), "{}", sent[2]); + assert!(!sent[3].contains("\"signature\"") && sent[3].contains("\"type\":\"adaptive\""), "{}", sent[3]); + assert!(sent[3].contains("\"text\":\"看看\"") && sent[3].contains("\"tool_use_id\":\"tu1\""), "words, calls and results stay: {}", sent[3]); + assert!(rx.recv_timeout(std::time::Duration::from_millis(300)).is_err(), "four sends, no more"); + // Not sent the control there again. + assert!(anthropic_request(&req(&base)).0["thinking"]["block_binding"].is_null()); + + // A gateway that answers the control with a plain 「Bad Request」: the step goes on + // without it (then without the thinking), and the address isn't kept as needing it. + let (base, rx) = scripted_server(vec![(400, refused_thinking), (400, r#"{"error":"Bad Request"}"#), (400, refused_thinking), (200, claude)]); + assert_eq!(run_step(&req(&base), &cancel, &|_| {}).unwrap().text, "ok"); + let sent: Vec = (0..4).map(|_| flat(rx.recv().unwrap())).collect(); + assert!(sent[1].contains("block_binding") && !sent[2].contains("block_binding") && !sent[3].contains("\"signature\""), "{sent:?}"); + assert!(anthropic_request(&req(&base)).0["thinking"]["block_binding"].is_null(), "not kept as needing it"); + // A signature that is broken (not bound elsewhere): only stripped — the control isn't + // asked for, so the check isn't turned on for an account the API doesn't hold to it. + let broken = r#"{"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0: Invalid `signature` in `thinking` block."}}"#; + let (base, rx) = scripted_server(vec![(400, broken), (200, claude)]); + assert!(run_step(&req(&base), &cancel, &|_| {}).unwrap().old_thinking_left_out); + let (first, second) = (flat(rx.recv().unwrap()), flat(rx.recv().unwrap())); + assert!(first.contains("\"signature\"") && !second.contains("\"signature\"") && !second.contains("block_binding"), "{second}"); + assert!(anthropic_request(&req(&base)).0["thinking"]["block_binding"].is_null()); + // What counts as left out: not another model's blocks (the next step's model may read + // them), but another account's (never good again). + let r = req(&base); + assert!(!thinking_left_out(&r, &json!([{"type": "thinking_dropped", "path": "messages.1.content.0", "reason": "model_binding_mismatch"}]))); + assert!(thinking_left_out(&r, &json!([{"type": "thinking_dropped", "path": "messages.1.content.0", "reason": "organization_binding_mismatch"}]))); + assert!(!thinking_left_out(&r, &json!([{"type": "thinking_mismatch_allowed", "path": "messages.1.content.0", "reason": "prefix_binding_mismatch"}]))); + assert!(!thinking_left_out(&r, &json!([])) && !thinking_left_out(&r, &Value::Null)); + + // What the turn does then: its history goes without the earlier thinking, words and + // calls as they were. + let mut h = history.clone(); + forget_thinking(&mut h); + assert_eq!(h[1].blocks, vec![json!({"type": "text", "text": "看看"}), json!({"type": "tool_use", "id": "tu1", "name": "list_dir", "input": {}})]); + assert_eq!(h[1].text, history[1].text); + + // Any other 400 is still an error, sent once. + let (base, rx) = scripted_server(vec![(400, r#"{"error":{"message":"max_tokens: too large"}}"#), (200, claude)]); + assert!(run_step(&req(&base), &cancel, &|_| {}).unwrap_err().contains("max_tokens")); + rx.recv().unwrap(); + assert!(rx.recv_timeout(std::time::Duration::from_millis(300)).is_err(), "not sent again"); + } + /// 思考模式 goes out as each service names it; left to the model, nothing is sent; a model /// that refuses the setting is asked again without it, and not sent it a second time. #[test] diff --git a/src/remote.rs b/src/remote.rs index 7c0f1e2..3e0ca8e 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -3368,11 +3368,37 @@ pub struct AccountFind { } pub fn find_account_bots(s: &Settings, password: &str, code: &str) -> AccountFind { - let brain = peers(s).ok().and_then(|hosts| pick_brain(&hosts, &s.host_id)); + find_account_bots_noting(s, password, code, BRAIN_WAIT, &|_| {}) +} + +/// How long a computer that just signed in waits for its cloud brain, on a server that gives +/// every account one: made a few seconds after the sign-up (大腦管理員), up a few seconds later. +pub const BRAIN_WAIT: Duration = Duration::from_secs(90); + +/// As find_account_bots, saying what it waits for. On an account server that gives every account +/// a cloud brain of its own (`brains` in its hello) the brain is waited for — a computer that +/// just signed up used to find none yet and become the brain itself. +pub fn find_account_bots_noting(s: &Settings, password: &str, code: &str, wait: Duration, note: &dyn Fn(&str)) -> AccountFind { + let look = || peers(s).ok().and_then(|hosts| pick_brain(&hosts, &s.host_id)); + let mut brain = look(); + if brain.is_none() && gives_brains(&s.relay_url) { + note("正在等你的雲端大腦開好(第一次約半分鐘)…"); + let start = Instant::now(); + while brain.is_none() && start.elapsed() < wait { + std::thread::sleep(Duration::from_secs(2)); + brain = look(); + } + } let backup = if brain.is_none() { restore(&s.relay_url, &s.relay_user, password, code).ok() } else { None }; AccountFind { brain, backup } } +/// Whether this account server gives every account a cloud brain of its own (its 大腦管理員). +pub fn gives_brains(url: &str) -> bool { + let Ok(mut r) = relay_agent(10, url).get(&format!("{}/api/hello", url.trim_end_matches('/'))).call() else { return false }; + serde_json::from_str::(&r.body_mut().read_to_string().unwrap_or_default()).is_ok_and(|v| v["brains"] == true) +} + /// The brain among the account's AnyBots (relay `hosts` rows), never this one. pub fn pick_brain(hosts: &[Value], me: &str) -> Option<(String, String)> { hosts @@ -3723,16 +3749,17 @@ mod tests { /// {id, same}; one holding none (or an older page) all of it, with the fingerprint. #[test] fn the_state_is_told_as_what_changed() { - let a = json!({"version": 5, "host": "Mac", "models": [1, 2, 3], "bots": [{"id": 1, "name": "甲", "status": ""}, {"id": 2, "name": "乙"}]}); + // (Versions no other test uses: the fingerprints are kept by version for the whole run.) + let a = json!({"version": 905_005, "host": "Mac", "models": [1, 2, 3], "bots": [{"id": 1, "name": "甲", "status": ""}, {"id": 2, "name": "乙"}]}); let full = state_for(a.clone(), "", true); assert!(full["base"].is_null() && full["models"] == json!([1, 2, 3])); let held = full["ssig"].as_str().unwrap().to_string(); let mut b = a.clone(); - b["version"] = json!(6); + b["version"] = json!(905_006); b["bots"][0]["status"] = json!("正在想…"); let part = state_for(b.clone(), &held, true); assert_eq!(part["base"], json!(held)); - assert_eq!(part["version"], 6); + assert_eq!(part["version"], 905_006); assert!(part.get("host").is_none() && part.get("models").is_none(), "unchanged keys left out: {part}"); assert_eq!(part["bots"][0]["status"], "正在想…"); assert_eq!(part["bots"][1], json!({"id": 2, "same": true})); @@ -4138,6 +4165,44 @@ mod tests { format!("http://127.0.0.1:{port}") } + /// Signed up on a server that gives every account a cloud brain: the brain isn't up yet, so the + /// computer waits for it (and says so) instead of becoming the brain itself; it comes up and + /// is the one to show. A server without brains: no wait, the backup as before. + #[test] + fn a_new_account_waits_for_its_cloud_brain() { + let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let n = asked.clone(); + let url = stand_in_relay(6, move |p, _| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay", "brains": true})), + "/relay/host/peers" => { + // Up on the third look. + let i = n.fetch_add(1, Ordering::SeqCst); + let brain = json!({"id": "brain-1", "name": "雲端大腦", "online": true}); + Resp::json(&json!({"hosts": if i >= 2 { vec![brain] } else { vec![] }})) + } + _ => Resp::error(500, "backup asked for"), + }); + let s = Settings { relay_url: url, relay_user: "amy".into(), host_id: "mac-1".into(), host_token: "t".into(), ..Default::default() }; + let said = Arc::new(Mutex::new(String::new())); + let w = said.clone(); + let found = find_account_bots_noting(&s, "pw", "", Duration::from_secs(20), &|t| *w.lock().unwrap() = t.to_string()); + assert_eq!(found.brain, Some(("brain-1".to_string(), "雲端大腦".to_string()))); + assert!(found.backup.is_none(), "not this computer's bots from a backup"); + assert!(said.lock().unwrap().contains("雲端大腦")); + assert_eq!(asked.load(Ordering::SeqCst), 3); + + // No brains here: no wait, straight to the backup. + let url = stand_in_relay(3, |p, _| match p { + "/api/hello" => Resp::json(&json!({"app": "anybot-relay"})), + "/relay/host/peers" => Resp::json(&json!({"hosts": []})), + _ => Resp::error(404, "沒有備份"), + }); + let s = Settings { relay_url: url, ..s }; + let start = Instant::now(); + let found = find_account_bots_noting(&s, "pw", "", Duration::from_secs(20), &|_| panic!("no wait here")); + assert!(found.brain.is_none() && start.elapsed() < Duration::from_secs(5)); + } + /// 連線體檢 (/doctor): each leg timed and said — this ↔ the account server, its download, on to /// the brain; an old server or brain says it can't be timed (not that it's broken); a brain /// that's off, an account server that can't be reached, a slow leg: a ✗ that says where. @@ -4826,6 +4891,26 @@ pub fn pair_block(relay_url: &str, code: &str) -> String { mod account_sync_live { use super::*; + /// On a server that gives every account a cloud brain (deploy/server set up the easy way): + /// what the app does at 「註冊」 — sign up with the invite, then wait for the brain and find + /// it. ANYBOT_RELAY_URL and ANYBOT_RELAY_INVITE (the server's, from its .env). + #[test] + #[ignore] + fn a_new_account_on_a_brains_server_finds_its_cloud_brain() { + let url = std::env::var("ANYBOT_RELAY_URL").expect("ANYBOT_RELAY_URL"); + let invite = std::env::var("ANYBOT_RELAY_INVITE").expect("ANYBOT_RELAY_INVITE"); + assert!(gives_brains(&url), "這台帳號伺服器沒說它會開雲端大腦"); + let (user, pw) = (format!("t{}", crate::httpd::random_hex(4)), "brain-pass-123"); + let s = relay_join(&Settings { host_name: "新的 Mac".into(), ..Default::default() }, &url, &user, pw, true, &invite, "").unwrap(); + let start = Instant::now(); + let said = Mutex::new(String::new()); + let found = find_account_bots_noting(&s, pw, "", BRAIN_WAIT, &|t| *said.lock().unwrap() = t.to_string()); + let (id, name) = found.brain.expect("等不到雲端大腦"); + println!("{user}:{} 秒後找到「{name}」({id});等的時候說:{}", start.elapsed().as_secs(), said.lock().unwrap()); + assert_eq!(name, "雲端大腦"); + assert!(found.backup.is_none()); + } + #[test] #[ignore] fn a_new_computer_gets_the_accounts_bots_after_signing_in() {