From 13a0987e53b7665289056aba8d847807bbff7314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:24:52 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20Linux=20=E7=9A=84=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E4=B9=9F=E5=9C=A8=E6=B2=99=E7=9B=92=E8=A3=A1=E8=B7=91=EF=BC=88?= =?UTF-8?q?Landlock=EF=BC=89=EF=BC=9A=E7=A7=81=E5=AF=86=E8=B3=87=E6=96=99?= =?UTF-8?q?=E5=A4=BE=E8=AE=80=E4=B8=8D=E5=88=B0=E4=B9=9F=E5=AF=AB=E4=B8=8D?= =?UTF-8?q?=E5=88=B0=E3=80=81shell=20=E5=95=9F=E5=8B=95=E6=AA=94=E6=94=B9?= =?UTF-8?q?=E4=B8=8D=E4=BA=86=EF=BC=9B=E6=B2=92=E6=9C=89=E6=B2=99=E7=9B=92?= =?UTF-8?q?=E7=9A=84=E9=9B=BB=E8=85=A6=20/doctor=20=E7=85=A7=E5=AF=A6?= =?UTF-8?q?=E8=AA=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - AnyBot 用自己當沙盒(/proc/self/exe __anybot_sandbox … -- /bin/sh -c 指令):套上 Landlock 再變成 shell,互動終端機也包得到。 - Landlock 只能允許:通往私密資料夾的每一層一個個允許、跳過私密的那個;讀到處可以(名字列得出來)、寫除了私密資料夾和啟動檔都可以,跟 macOS 一樣;工作資料夾整個可寫。 - 核心沒有 Landlock:照舊跑、紀錄檔寫一次、/doctor 一行 ✗;Windows 也寫沒有沙盒。 - Linux 被擋時(Permission denied)結果後面附一句說明哪些地方不行。 已驗證:cargo test 588 通過(規劃:私密資料夾、附件只讀、啟動檔只讀、工作資料夾整個可寫、舊核心只用它認得的權限;參數來回);landlock.rs 用 Linux target 做過 cargo check 和 clippy -D warnings(含 Linux 才編的系統呼叫和測試);clippy -D warnings 乾淨。 未驗證:真的 Linux 核心上套上 Landlock(landlock_keeps_a_command_out 在 CI 的 anybot-linux 或一台 Linux 才會跑)、互動終端機在 Linux 上經過沙盒。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 6 +- docs/feature-map/garden.md | 2 +- docs/feature-map/safety.md | 3 +- docs/plan-2026-11-engineering.md | 3 +- src/app/doctor_ui.rs | 2 + src/doctor.rs | 26 ++ src/landlock.rs | 422 +++++++++++++++++++++++++++++++ src/main.rs | 6 + src/tools.rs | 11 +- 9 files changed, 475 insertions(+), 6 deletions(-) create mode 100644 src/landlock.rs diff --git a/FEATURES.md b/FEATURES.md index eee574c..b9323d8 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1035,7 +1035,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 一律允許會記住指令的第一個字。 - git、npm、pnpm、yarn、cargo、brew、pip、pip3、python3、docker、go 這 11 種會記住前兩個字,例如「npm install」。 -### 沙盒(macOS 有提供時) +### 沙盒(macOS 的 sandbox-exec、Linux 的 Landlock) - 所有指令都在沙盒裡跑,下面三種例外(只在你的電腦上;Bot 自己的電腦一律在沙盒裡)。 - 指令碰不到這些地方:AnyBot 的資料、.ssh、.gnupg、Library/Keychains、.aws、.config/gcloud。 @@ -1044,6 +1044,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - `ps`、`top`,單獨或只接 grep、head、awk 這類不讀檔的過濾:它們要系統權限(setuid),沙盒裡一律「Operation not permitted」。 - AppleScript:單獨一條 `osascript -e '…'`(不能跑腳本檔、JavaScript、heredoc),而且不含 do shell script、run script、終端機、keystroke、讀檔、ObjC、祕密資料夾的名字。在沙盒裡 AppleScript 指揮別的 App 一律被拒(-10004)。第一次會先問你,直接操作模式也問,選「一律允許」之後不再問。 - 被沙盒擋下時(setuid 程式、-10004、App 的指令列當掉),結果後面會附一句說明是沙盒擋的、改用什麼,Bot 不會當成電腦壞了一直重試。 +- **Linux**(核心 5.13 以上、有開 Landlock):同樣那些私密資料夾讀不到也寫不到(聊天的附件、技能、.ssh 一樣只能讀),shell 的啟動檔(.bashrc、.profile、.bash_login、~/.config/autostart、~/.config/systemd、.xprofile…)改不了;sudo 這類提高權限的程式不能跑。AnyBot 用自己(`/proc/self/exe`)當沙盒把指令包起來再變成 /bin/sh,所以互動終端機也在沙盒裡。Landlock 只能「允許」、不能「除了這個」,所以和 macOS 不一樣的地方:資料夾裡有哪些名字到處都列得出來(內容讀不到);通往私密資料夾的那幾層(家目錄、~/.config、~/.local、~/.local/share)最上層不能新增檔案或資料夾,它們裡面的其他資料夾照常可以;工作資料夾整個可寫,裡面的 .git/hooks 擋不住。指令失敗出現 Permission denied 時,結果後面附一句「如果是 AnyBot 的指令沙盒擋的…」說明哪些地方不行。 +- 沒有沙盒的電腦照實說,不假裝有:Linux 核心沒有 Landlock(太舊或沒開)時 /doctor 一行「✗ 這台的指令沒有沙盒…」,紀錄檔也寫,指令照樣跑(和以前一樣),只靠上面的安全規則擋;Windows 還沒有沙盒,/doctor 也這樣寫。 ### 在「Bot 的電腦」上 @@ -1507,7 +1509,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 診斷(/doctor) -- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。 +- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);指令有沒有沙盒(macOS 的 sandbox-exec、Linux 的 Landlock 第幾版,沒有就 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。 - 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。 ### 自動審核的固定樣式規則 diff --git a/docs/feature-map/garden.md b/docs/feature-map/garden.md index 96b1be9..9cf642e 100644 --- a/docs/feature-map/garden.md +++ b/docs/feature-map/garden.md @@ -5,7 +5,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 ## 子功能 - 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。 -- 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。 +- 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、指令有沒有沙盒、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。 - 紀錄檔:AnyBot 自己的訊息寫在資料夾的 `logs/anybot-日期.log`(一天一個、留 7 天、一天最多 20 MB),同時照舊印在終端機(伺服器的 `make server-logs` 看得到)。等級用環境變數 ANYBOT_LOG(error、warn、info 預設、debug)。寫進去前先遮掉金鑰、Token、密碼(glpat-、ghp_、sk-、xai-、AKIA、Bearer、JWT、私鑰、名字像 TOKEN/SECRET/PASSWORD 的變數值 → ••••);手機上的步驟細節也一樣遮。 - 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。 - 園丁每日報告(平日 8:44 起):過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index 3742fc7..d0e61a8 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -16,6 +16,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - 安全規則(你的電腦上): - 一律拒絕:sudo、su、rm -rf /、rm -rf ~、mkfs、dd、shutdown、reboot、diskutil erase、chmod -R 777 /。 - 私密檔案不能讀也不能改:AnyBot 自己的資料、.git、.ssh、.gnupg、鑰匙圈、.aws、.env、.pem、.key、id_rsa 這類金鑰、credentials 等。 + - 指令沙盒:macOS 用 sandbox-exec,Linux 用 Landlock(核心 5.13 以上),私密資料夾讀不到也寫不到、shell 啟動檔改不了。Linux 上家目錄、~/.config、~/.local/share 的最上層不能新增東西(裡面的資料夾可以)。沒有沙盒的電腦(舊核心、Windows)/doctor 寫「這台的指令沒有沙盒」。 - 直接做:讀工作資料夾裡的檔案;只用 24 種只看不改的指令(ls、cat、grep、git status…)。 - 先問、可一律允許:改工作資料夾裡的檔案、其他指令、讀工作資料夾以外。 - 每次問:改工作資料夾以外的檔案、含看不出內容的子指令、開互動 shell。 @@ -46,7 +47,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 ## 怎麼操作 - Bot:不能替你按允許,也不能點 AnyBot 的核准按鈕;被拒後不要再試同一件事,也不要換個寫法做。`update_settings` 改不了這些開關(打開「在這台電腦上執行」只有使用者能做)。要你親手做的步驟用 `hand_over_computer`,要你決定的用 `ask_person`([chat](chat.md))。 -- 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。打「/always-approve」後再請它在你的電腦執行 `printf ok`(訊息裡指名你的電腦),不該跳卡片、結果有 ok;用訊息管道傳同一句,照樣要你按;「/always-approve off」後又會問。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`、`cargo test always`。 +- 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。打「/always-approve」後再請它在你的電腦執行 `printf ok`(訊息裡指名你的電腦),不該跳卡片、結果有 ok;用訊息管道傳同一句,照樣要你按;「/always-approve off」後又會問。Linux 上 /doctor 要有「指令沙盒:Linux 的 Landlock」,請 Bot 在你的電腦 `cat ~/.ssh/known_hosts` 可以、`cat` AnyBot 資料夾裡的 state.json 要失敗。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`、`cargo test always`、`cargo test landlock::`(真的套上 Landlock 的那個只在有 Landlock 的 Linux 跑)。 ## 陷阱 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index ad375e7..6cb62c7 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -83,8 +83,9 @@ - 做法:評審可以用只看的工具(讀檔、web_fetch、截圖)查證;同一個「還沒達成」理由連兩次就暫停問;提示加「不要每輪提高標準」。 - 做完:評審用工具讀檔確認的測試;同理由兩次暫停的測試。 -### R6. Linux 的沙盒 ⬜ +### R6. Linux 的沙盒 ✅(真的核心上的測試要在 CI 的 anybot-linux 或一台 Linux 跑:這台 Mac 只驗了規劃和 Linux 的型別檢查) - 做法:Linux 電腦上的指令用 Landlock:寫入只限工作資料夾和 /tmp,私密檔案(protected_dirs)讀寫都擋;核心不支援時照實說(「這台的指令沒有沙盒」),不假裝有。 +- 實際:寫入沒有限在工作資料夾,而是跟 macOS 一樣「除了私密資料夾和 shell 啟動檔都可以」(只限工作資料夾會讓「改我的 ~/.config/xx」做不到,macOS 卻做得到)。Landlock 只能允許,所以通往私密資料夾的那幾層最上層不能新增東西、工作資料夾的 .git/hooks 擋不住。AnyBot 用自己當沙盒(`__anybot_sandbox`),互動終端機也包得到。 - 做完:Linux 上的測試(CI 的 anybot-linux):寫工作資料夾外失敗、讀 ~/.ssh 失敗。 ### R7. 長連線:還在傳就不算斷線、斷線後馬上重連、看得出是哪一段 ✅(帳號伺服器那端要 make update-server) diff --git a/src/app/doctor_ui.rs b/src/app/doctor_ui.rs index 21a2d9e..faa11a4 100644 --- a/src/app/doctor_ui.rs +++ b/src/app/doctor_ui.rs @@ -65,6 +65,8 @@ impl App { } } } + // (Commands for 「你的電腦」 run here, a screen of a brain too.) + lines.push(crate::doctor::sandbox_line()); match crate::doctor::free_mb(&data) { Some(mb) if mb < 2048 => lines.push(bad(format!("磁碟只剩 {mb} MB(快照、模型和 Bot 的電腦都要空間)"))), Some(mb) => lines.push(ok(format!("磁碟還有 {:.1} GB", mb as f64 / 1024.0))), diff --git a/src/doctor.rs b/src/doctor.rs index 426edb2..49ee9ae 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -67,6 +67,20 @@ pub fn ping_tailscale(host: &str) -> Option { None } +/// Whether commands on this computer run in a sandbox, and which. +pub fn sandbox_line() -> Line { + if cfg!(target_os = "macos") { + return if std::path::Path::new("/usr/bin/sandbox-exec").exists() { ok("指令沙盒:macOS 的 sandbox-exec") } else { bad("這台的指令沒有沙盒:找不到 /usr/bin/sandbox-exec") }; + } + if cfg!(target_os = "linux") { + return match crate::landlock::abi() { + Some(v) => ok(format!("指令沙盒:Linux 的 Landlock(第 {v} 版)")), + None => bad(crate::landlock::NONE), + }; + } + bad("這台的指令沒有沙盒(Windows 還沒有):指令讀得到 .ssh 這類私密資料夾,只靠安全規則擋") +} + /// Free space where the data folder is, in MB (None where `df` can't say). pub fn free_mb(dir: &Path) -> Option { let out = std::process::Command::new("df").args(["-Pk"]).arg(dir).output().ok()?; @@ -106,6 +120,18 @@ mod tests { assert_eq!(tailscale_path("no reply"), None); } + #[test] + fn the_sandbox_is_said_as_it_is() { + let l = sandbox_line(); + if cfg!(target_os = "macos") { + assert!(l.ok && l.text.contains("sandbox-exec"), "{l:?}"); + } else if cfg!(target_os = "linux") { + assert_eq!(l.ok, crate::landlock::abi().is_some(), "{l:?}"); + } else { + assert!(!l.ok && l.text.contains("沒有沙盒"), "{l:?}"); + } + } + #[test] fn the_last_crash_and_the_disk() { let d = std::env::temp_dir().join(format!("anybot-doctor-{}", std::process::id())); diff --git a/src/landlock.rs b/src/landlock.rs new file mode 100644 index 0000000..afd4caf --- /dev/null +++ b/src/landlock.rs @@ -0,0 +1,422 @@ +//! Linux 的指令沙盒 (R6). Linux has no sandbox-exec: a command on the person's computer starts +//! through AnyBot itself (`/proc/self/exe __anybot_sandbox … -- /bin/sh -c 指令`), which closes +//! itself in with Landlock and then becomes the shell — the way sandbox-exec wraps it on macOS, so +//! a 互動終端機 (pty.rs copies only the program and its arguments) is closed in too. +//! +//! Landlock only allows; it has no "but not this folder". So what macOS denies is left out of what +//! is allowed: every entry on the way to a protected folder is allowed one by one, the protected +//! one is skipped. Reading: everything but the protected folders (listing names works everywhere, +//! contents don't). Writing: the same, also without the shell startup files; the work folder as a +//! whole. What follows from allowing only: in a folder on the way to a protected one (the home +//! folder, ~/.config, ~/.local/share…) nothing new can be made at its top level (in its other +//! folders it can), and the work folder's .git/hooks stay writable (macOS denies them). +//! A kernel without Landlock (before 5.13, or not turned on) is said as it is (`/doctor`, the +//! log): commands run as they did, without a sandbox, never pretending to have one. + +use std::collections::BTreeMap; +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +/// The first argument that makes AnyBot the sandbox instead of the app. +pub const ARG: &str = "__anybot_sandbox"; + +/// Landlock's file system rights (linux/landlock.h). +pub mod access { + pub const EXECUTE: u64 = 1 << 0; + pub const WRITE_FILE: u64 = 1 << 1; + pub const READ_FILE: u64 = 1 << 2; + pub const READ_DIR: u64 = 1 << 3; + pub const REMOVE_DIR: u64 = 1 << 4; + pub const REMOVE_FILE: u64 = 1 << 5; + pub const MAKE_CHAR: u64 = 1 << 6; + pub const MAKE_DIR: u64 = 1 << 7; + pub const MAKE_REG: u64 = 1 << 8; + pub const MAKE_SOCK: u64 = 1 << 9; + pub const MAKE_FIFO: u64 = 1 << 10; + pub const MAKE_BLOCK: u64 = 1 << 11; + pub const MAKE_SYM: u64 = 1 << 12; + /// Since version 2: moving or linking into another folder (without it, never allowed). + pub const REFER: u64 = 1 << 13; + /// Since version 3. + pub const TRUNCATE: u64 = 1 << 14; + /// Since version 5. + pub const IOCTL_DEV: u64 = 1 << 15; +} +use access::*; + +const READ: u64 = EXECUTE | READ_FILE; +const WRITE: u64 = WRITE_FILE | REMOVE_DIR | REMOVE_FILE | MAKE_CHAR | MAKE_DIR | MAKE_REG | MAKE_SOCK | MAKE_FIFO | MAKE_BLOCK | MAKE_SYM | REFER | TRUNCATE | IOCTL_DEV; +/// The rights a rule on a file (not a folder) may carry. +const FILE_ONLY: u64 = EXECUTE | WRITE_FILE | READ_FILE | TRUNCATE | IOCTL_DEV; + +/// What this kernel's Landlock (its version) can govern. +pub fn handled(abi: u32) -> u64 { + let mut h = (1 << 13) - 1; + if abi >= 2 { + h |= REFER; + } + if abi >= 3 { + h |= TRUNCATE; + } + if abi >= 5 { + h |= IOCTL_DEV; + } + h +} + +/// What a command is kept from. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Spec { + /// Neither read nor written: AnyBot's data, ~/.ssh, ~/.gnupg… + pub hidden: Vec, + /// Inside those, what may still be read (never written): the chat's attachments, skills, ~/.ssh. + pub readable: Vec, + /// Not written: shell startup files… + pub no_write: Vec, + /// The work folder: read and written as a whole. + pub work: PathBuf, +} + +impl Spec { + /// As arguments for the sandbox (`-h`, `-r`, `-w`, `-C`, each with a path). + pub fn to_args(&self) -> Vec { + let mut v = vec![]; + for (flag, paths) in [("-h", &self.hidden), ("-r", &self.readable), ("-w", &self.no_write)] { + for p in paths { + v.push(OsString::from(flag)); + v.push(p.clone().into_os_string()); + } + } + v.push("-C".into()); + v.push(self.work.clone().into_os_string()); + v + } + + /// Read back: the spec, then the program and its arguments (after `--`). + pub fn from_args(args: &[OsString]) -> Result<(Spec, Vec), String> { + let mut s = Spec::default(); + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == "--" { + let rest: Vec = it.cloned().collect(); + if rest.is_empty() { + return Err("沒有要執行的程式".into()); + } + return Ok((s, rest)); + } + let p = PathBuf::from(it.next().ok_or_else(|| format!("{} 後面少了路徑", a.to_string_lossy()))?); + match a.to_str() { + Some("-h") => s.hidden.push(p), + Some("-r") => s.readable.push(p), + Some("-w") => s.no_write.push(p), + Some("-C") => s.work = p, + _ => return Err(format!("看不懂 {}", a.to_string_lossy())), + } + } + Err("少了 --".into()) + } +} + +/// The path as the kernel sees it (links resolved), also for one that isn't there yet. +fn real(p: &Path) -> PathBuf { + if let Ok(r) = std::fs::canonicalize(p) { + return r; + } + match (p.parent(), p.file_name()) { + (Some(parent), Some(name)) if parent != p => real(parent).join(name), + _ => p.to_path_buf(), + } +} + +/// Everything under `dir` but `avoid`: an entry not on the way to an avoided path as a whole, one +/// on the way entry by entry. Links are skipped (what they point to has a path of its own). +fn around(dir: &Path, avoid: &[PathBuf], grant: &mut dyn FnMut(PathBuf, bool)) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + let Ok(t) = e.file_type() else { continue }; + if t.is_symlink() || avoid.contains(&p) { + continue; + } + if t.is_dir() && avoid.iter().any(|a| a.starts_with(&p)) { + around(&p, avoid, grant); + } else { + grant(p, t.is_dir()); + } + } +} + +/// What a sandboxed command may do: (path, rights), each for everything under that path. +pub fn plan(spec: &Spec, abi: u32) -> Vec<(PathBuf, u64)> { + let hidden: Vec = spec.hidden.iter().map(|p| real(p)).collect(); + let work = real(&spec.work); + // (Inside the work folder nothing can be kept from writing: the folder is allowed whole.) + let no_write: Vec = hidden.iter().cloned().chain(spec.no_write.iter().map(|p| real(p)).filter(|p| !p.starts_with(&work))).collect(); + let mut rules: BTreeMap = BTreeMap::new(); + let mut add = |p: PathBuf, r: u64, dir: bool| rules.entry(p).or_insert((0, dir)).0 |= r; + let root = Path::new("/"); + add(root.to_path_buf(), READ_DIR, true); + around(root, &hidden, &mut |p, dir| add(p, READ, dir)); + around(root, &no_write, &mut |p, dir| add(p, WRITE, dir)); + for r in spec.readable.iter().map(|r| real(r)) { + if hidden.iter().any(|h| r.starts_with(h)) && r.exists() { + let dir = r.is_dir(); + add(r, READ, dir); + } + } + if !hidden.iter().any(|h| work.starts_with(h)) && work.is_dir() { + add(work, READ | WRITE, true); + } + let h = handled(abi); + rules.into_iter().map(|(p, (r, dir))| (p, r & h & if dir { u64::MAX } else { FILE_ONLY })).filter(|(_, r)| *r != 0).collect() +} + +/// The program AnyBot is (the sandbox runs as it). In `cargo test` that is the test runner, which +/// can't be the sandbox: commands there run unwrapped unless a test names a real AnyBot. +fn helper() -> Option { + if cfg!(test) { + return std::env::var_os("ANYBOT_TEST_SANDBOX_EXE").map(PathBuf::from); + } + Some(PathBuf::from("/proc/self/exe")) +} + +/// This kernel's Landlock version (None: no Landlock here). Asked once. +pub fn abi() -> Option { + static ABI: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ABI.get_or_init(|| { + let v = sys::abi(); + if cfg!(target_os = "linux") && v.is_none() { + log::warn!("{NONE}"); + } + v + }) +} + +/// What `/doctor` and the log say on a Linux without Landlock. +pub const NONE: &str = "這台的指令沒有沙盒:Linux 核心沒有 Landlock(要 5.13 以上,而且有開:/sys/kernel/security/lsm 裡要有 landlock)。指令照樣能跑,但讀得到 .ssh 這類私密資料夾"; + +/// Commands here run in the Linux sandbox. +pub fn active() -> bool { + cfg!(target_os = "linux") && abi().is_some() && helper().is_some() +} + +/// `/bin/sh -c cmd` inside the sandbox (None: no sandbox here — run it as before). +pub fn wrap(cmd: &str, spec: &Spec) -> Option { + if !active() || spec.hidden.is_empty() { + return None; + } + let mut c = std::process::Command::new(helper()?); + c.arg(ARG).args(spec.to_args()).args(["--", "/bin/sh", "-c", cmd]); + Some(c) +} + +/// After a command failed this way it may have been the sandbox: a word for the bot. +pub const NOTE: &str = "(如果是 AnyBot 的指令沙盒擋的,不是電腦壞了:在 Linux 上指令讀不到也寫不到 AnyBot 的資料和私密資料夾(.ssh、.gnupg、.aws…),改不了 shell 的啟動檔;家目錄、~/.config、~/.local、~/.local/share 這幾層的最上層不能新增檔案或資料夾,但它們裡面的其他資料夾可以。改在工作資料夾裡做,或請使用者自己做。)"; + +/// `anybot __anybot_sandbox … -- program args`: close this process in, then become the program. +/// Anything wrong and the program doesn't run (never without the sandbox it was asked for). +pub fn run_helper(args: &[OsString]) -> ! { + let fail = |e: String| -> ! { + eprintln!("AnyBot 的指令沙盒沒有套上,指令沒有執行:{e}"); + std::process::exit(126) + }; + let (spec, program) = Spec::from_args(args).unwrap_or_else(|e| fail(e)); + let abi = sys::abi().unwrap_or_else(|| fail("這台的 Linux 核心沒有 Landlock".into())); + sys::restrict(&plan(&spec, abi), handled(abi)).unwrap_or_else(|e| fail(e)); + exec(&program[0], &program[1..]) +} + +#[cfg(unix)] +fn exec(program: &OsStr, args: &[OsString]) -> ! { + use std::os::unix::process::CommandExt; + let e = std::process::Command::new(program).args(args).exec(); + eprintln!("無法執行 {}:{e}", program.to_string_lossy()); + std::process::exit(127) +} + +#[cfg(not(unix))] +fn exec(program: &OsStr, _: &[OsString]) -> ! { + eprintln!("無法執行 {}:這台沒有指令沙盒", program.to_string_lossy()); + std::process::exit(126) +} + +#[cfg(target_os = "linux")] +mod sys { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::fs::OpenOptionsExt; + use std::path::PathBuf; + + #[repr(C)] + struct RulesetAttr { + handled_access_fs: u64, + } + + #[repr(C, packed)] + struct PathBeneath { + allowed_access: u64, + parent_fd: i32, + } + + const CREATE_RULESET_VERSION: u32 = 1; + const RULE_PATH_BENEATH: u32 = 1; + + pub fn abi() -> Option { + // SAFETY: asking for the version: no attributes, no memory written. + let v = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, std::ptr::null::(), 0usize, CREATE_RULESET_VERSION) }; + (v > 0).then_some(v as u32) + } + + /// From now on this thread (and what it starts) may do only what `rules` allow. + pub fn restrict(rules: &[(PathBuf, u64)], handled: u64) -> Result<(), String> { + let os = || std::io::Error::last_os_error(); + let attr = RulesetAttr { handled_access_fs: handled }; + // SAFETY: attr lives across the call; the kernel reads size_of bytes of it. + let fd = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, &attr as *const RulesetAttr, std::mem::size_of::(), 0u32) }; + if fd < 0 { + return Err(format!("建立規則失敗:{}", os())); + } + // SAFETY: a new descriptor the kernel just gave us, owned only here. + let ruleset = unsafe { OwnedFd::from_raw_fd(fd as i32) }; + for (p, rights) in rules { + // (Gone since the plan was made: nothing to allow there.) + let Ok(f) = std::fs::OpenOptions::new().read(true).custom_flags(libc::O_PATH | libc::O_CLOEXEC).open(p) else { continue }; + let rule = PathBeneath { allowed_access: *rights, parent_fd: f.as_raw_fd() }; + // SAFETY: rule lives across the call; both descriptors are open. + let r = unsafe { libc::syscall(libc::SYS_landlock_add_rule, ruleset.as_raw_fd(), RULE_PATH_BENEATH, &rule as *const PathBeneath, 0u32) }; + if r < 0 { + return Err(format!("允許「{}」失敗:{}", p.display(), os())); + } + } + // SAFETY: plain prctl and syscall on this thread; the ruleset descriptor is open. + if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 { + return Err(format!("no_new_privs 失敗:{}", os())); + } + if unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset.as_raw_fd(), 0u32) } < 0 { + return Err(format!("套上規則失敗:{}", os())); + } + Ok(()) + } +} + +#[cfg(not(target_os = "linux"))] +mod sys { + pub fn abi() -> Option { + None + } + + pub fn restrict(_: &[(std::path::PathBuf, u64)], _: u64) -> Result<(), String> { + Err("只有 Linux 有 Landlock".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(name: &str) -> PathBuf { + let d = real(&std::env::temp_dir().join(format!("anybot-ll-{name}-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&d); + for sub in ["home/.ssh", "home/.config/gcloud", "home/.config/nvim", "home/Documents", "home/data/attachments", "home/work/.git/hooks"] { + std::fs::create_dir_all(d.join(sub)).unwrap(); + } + for f in ["home/.bashrc", "home/notes.txt", "home/.ssh/id_ed25519", "home/data/state.json"] { + std::fs::write(d.join(f), "x").unwrap(); + } + d + } + + fn rights(rules: &[(PathBuf, u64)], p: &Path) -> Option { + rules.iter().find(|(q, _)| q == p).map(|(_, r)| *r) + } + + /// What is reachable from a rule list (Landlock's way: a rule covers everything under it). + fn may(rules: &[(PathBuf, u64)], p: &Path, want: u64) -> bool { + let got = rules.iter().filter(|(q, _)| p.starts_with(q)).fold(0, |a, (_, r)| a | r); + got & want == want + } + + #[test] + fn the_plan_leaves_out_what_macos_denies() { + let d = tree("plan"); + let h = d.join("home"); + let spec = Spec { hidden: vec![h.join(".ssh"), h.join("data"), h.join(".config/gcloud"), h.join(".gnupg")], readable: vec![h.join("data/attachments"), h.join(".ssh")], no_write: vec![h.join(".bashrc"), h.join("work/.git/hooks")], work: h.join("work") }; + let r = plan(&spec, 5); + // Secrets: neither read nor written; the attachments and ~/.ssh readable only. + assert!(!may(&r, &h.join("data/state.json"), READ_FILE) && !may(&r, &h.join("data/state.json"), WRITE_FILE)); + assert!(!may(&r, &h.join(".config/gcloud/creds"), READ_FILE)); + assert!(may(&r, &h.join("data/attachments/p.png"), READ_FILE) && !may(&r, &h.join("data/attachments/p.png"), WRITE_FILE)); + assert!(may(&r, &h.join(".ssh/id_ed25519"), READ_FILE) && !may(&r, &h.join(".ssh/id_ed25519"), WRITE_FILE)); + // A folder not yet there (~/.gnupg) can't be made: its parent isn't allowed to make things. + assert!(!may(&r, &h, MAKE_DIR)); + // The rest: read and write as before, the startup file read only. + assert!(may(&r, &h.join("Documents/a.txt"), READ_FILE | WRITE_FILE | MAKE_REG)); + assert!(may(&r, &h.join(".config/nvim/init.lua"), READ_FILE | WRITE_FILE)); + assert!(may(&r, &h.join("notes.txt"), READ_FILE | WRITE_FILE)); + assert!(may(&r, &h.join(".bashrc"), READ_FILE) && !may(&r, &h.join(".bashrc"), WRITE_FILE)); + assert!(may(&r, Path::new("/usr/bin/env"), READ_FILE | EXECUTE)); + // The work folder whole (its .git/hooks too: Landlock can't carve inside it). + assert!(may(&r, &h.join("work/new/file.rs"), READ_FILE | WRITE_FILE | MAKE_REG | REMOVE_FILE)); + assert!(may(&r, &h.join("work/.git/index.lock"), MAKE_REG)); + // Names can be listed everywhere; a file's rule carries only file rights. + assert_eq!(rights(&r, Path::new("/")), Some(READ_DIR)); + assert_eq!(rights(&r, &h.join("notes.txt")).map(|x| x & !FILE_ONLY), Some(0)); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn older_kernels_get_only_what_they_know() { + assert_eq!(handled(1), (1 << 13) - 1); + assert_eq!(handled(2) & REFER, REFER); + assert_eq!(handled(4) & (TRUNCATE | IOCTL_DEV), TRUNCATE); + assert_eq!(handled(6) & IOCTL_DEV, IOCTL_DEV); + let d = tree("abi"); + let r = plan(&Spec { hidden: vec![d.join("home/.ssh")], work: d.join("home/work"), ..Default::default() }, 1); + assert!(r.iter().all(|(_, x)| x & !handled(1) == 0), "{r:?}"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn the_spec_goes_through_arguments() { + let s = Spec { hidden: vec!["/h/.ssh".into(), "/h/data".into()], readable: vec!["/h/data/attachments".into()], no_write: vec!["/h/.bashrc".into()], work: "/h/工作區".into() }; + let mut args = s.to_args(); + args.extend(["--", "/bin/sh", "-c", "echo hi"].map(OsString::from)); + let (back, program) = Spec::from_args(&args).unwrap(); + assert_eq!(back, s); + assert_eq!(program, ["/bin/sh", "-c", "echo hi"].map(OsString::from)); + assert!(Spec::from_args(&["-h".into()]).is_err()); + assert!(Spec::from_args(&["-C".into(), "/w".into(), "--".into()]).is_err()); + } + + /// The real thing on a Linux with Landlock (CI's anybot-linux): a thread closed in can't read + /// the secret or write outside, and still works in its folder. + #[cfg(target_os = "linux")] + #[test] + fn landlock_keeps_a_command_out() { + let Some(abi) = sys::abi() else { + eprintln!("這台沒有 Landlock:略過"); + return; + }; + let d = tree("real"); + let h = d.join("home"); + let spec = Spec { hidden: vec![h.join("data")], readable: vec![h.join("data/attachments")], no_write: vec![h.join(".bashrc")], work: h.join("work") }; + std::fs::write(h.join("data/attachments/p.txt"), "photo").unwrap(); + let rules = plan(&spec, abi); + let out = std::thread::spawn(move || { + sys::restrict(&rules, handled(abi)).unwrap(); + let sh = |c: &str| std::process::Command::new("/bin/sh").arg("-c").arg(c).current_dir(&spec.work).output().unwrap(); + let said = |c: &str| String::from_utf8_lossy(&sh(c).stdout).trim().to_string(); + let h = spec.work.parent().unwrap().to_path_buf(); + vec![ + said(&format!("cat '{}' 2>/dev/null || echo HIDDEN", h.join("data/state.json").display())), + said(&format!("cat '{}'", h.join("data/attachments/p.txt").display())), + said(&format!("echo x >> '{}' 2>/dev/null && echo WROTE || echo KEPT", h.join(".bashrc").display())), + said("echo hi > mine.txt && cat mine.txt"), + said(&format!("echo y > '{}' 2>/dev/null && echo WROTE || echo KEPT", h.join("Documents/a.txt").display())), + ] + }) + .join() + .unwrap(); + assert_eq!(out, ["HIDDEN", "photo", "KEPT", "hi", "WROTE"]); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/src/main.rs b/src/main.rs index fb591e7..3e03afc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,7 @@ mod intents; mod i18n; mod i18n_table; mod icons; +mod landlock; mod lantls; mod lock; mod macapps; @@ -319,6 +320,11 @@ const USAGE: &str = "用法: 資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)"; fn main() -> eframe::Result<()> { + // Linux 的指令沙盒 (landlock.rs): AnyBot started as the sandbox around one command — nothing + // of the app, and before reading the arguments as text (a path in them may not be). + if std::env::args_os().nth(1).is_some_and(|a| a == landlock::ARG) { + landlock::run_helper(&std::env::args_os().skip(2).collect::>()); + } let args: Vec = std::env::args().collect(); // Before anything else: no data folder, no window. if matches!(args.get(1).map(String::as_str), Some("--version" | "-V")) { diff --git a/src/tools.rs b/src/tools.rs index cff121c..749b9c1 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -843,7 +843,7 @@ pub fn protected_dirs() -> Vec { fn write_denied_paths(workdir: &Path) -> Vec { let mut v = vec![workdir.join(".git/hooks"), workdir.join(".git/config")]; if let Some(h) = dirs::home_dir() { - for s in [".zshrc", ".zshenv", ".zprofile", ".zlogin", ".bashrc", ".bash_profile", ".profile", "Library/LaunchAgents"] { + for s in [".zshrc", ".zshenv", ".zprofile", ".zlogin", ".bashrc", ".bash_profile", ".bash_login", ".bash_logout", ".profile", "Library/LaunchAgents", ".config/autostart", ".config/systemd", ".xprofile", ".xsessionrc", ".pam_environment"] { v.push(h.join(s)); } } @@ -1134,6 +1134,9 @@ pub const OSASCRIPT_GRANT: &str = "osascript:outside"; /// A word for the bot when a command failed because of the sandbox, not because the program or /// the computer is broken — so it changes course instead of trying the same thing again. pub fn sandbox_note(cmd: &str, out: &str) -> Option<&'static str> { + if crate::landlock::active() { + return (out.contains("Permission denied") || out.contains("Operation not permitted")).then_some(crate::landlock::NOTE); + } sandbox_exec()?; if runs_outside_sandbox(cmd) { return None; @@ -1244,6 +1247,12 @@ pub fn build_command_sealed(cmd: &str, workdir: &Path, protected: &[PathBuf], re c.arg("-p").arg(profile).arg("/bin/sh").arg("-c").arg(cmd); c } + // Linux: Landlock (landlock.rs), the same folders kept out; the bot's own sealed computer + // there never runs commands (sealed_runs_commands). + _ if seal.is_none() => { + let spec = crate::landlock::Spec { hidden: protected.to_vec(), readable: readable.to_vec(), no_write: write_denied_paths(workdir), work: workdir.to_path_buf() }; + crate::landlock::wrap(cmd, &spec).unwrap_or_else(|| shell_of(cmd)) + } _ => shell_of(cmd), }; for k in KEY_ENV_VARS.into_iter().chain(DANGEROUS_ENV_VARS) { From 25bf3f5bd4e297924123e553fcbb8b2542173eca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:28:46 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat:=20/fork=20=E5=88=86=E5=B2=94=EF=BC=9A?= =?UTF-8?q?=E9=80=99=E6=AE=B5=E5=B0=8D=E8=A9=B1=E5=AD=98=E4=B8=80=E4=BB=BD?= =?UTF-8?q?=E5=88=B0=E3=80=8C=E9=81=8E=E5=8E=BB=E7=9A=84=E5=B0=8D=E8=A9=B1?= =?UTF-8?q?=E3=80=8D=EF=BC=8C=E4=B9=8B=E5=BE=8C=E5=90=84=E8=B5=B0=E5=90=84?= =?UTF-8?q?=E7=9A=84=EF=BC=9BAnyBot=20=E7=9A=84=E6=8C=87=E4=BB=A4=E5=8F=AA?= =?UTF-8?q?=E5=9C=A8=E4=B8=80=E5=80=8B=E5=9C=B0=E6=96=B9=E8=AA=8D=E3=80=81?= =?UTF-8?q?=E4=B8=80=E5=80=8B=E5=9C=B0=E6=96=B9=E5=81=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /fork 或 /fork 名字:目前的對話照常繼續,一份「分岔:名字」放進過去的對話最上面;打開它時目前這段自動收進去,兩條路互不影響。Bot 在做事或對話是空的時說原因。 - 不複製整個 Bot(例行任務、訊息管道會重複)。 - 電腦的 send 和手機/螢幕的那條路本來各列一次 /btw、/goal、/plan、/always-approve、/usage、/context、/compact、/doctor,現在都走 app/commands.rs 的 app_command + run_app_command。 - / 清單、手機的指令清單加 /fork。 已驗證:cargo test 590 通過(指令認得出來、不把 /forkx 和路徑當指令;分岔留一份、之後說的不進分岔、打開分岔回到那一點、空的和正在做事時說原因)、clippy -D warnings 乾淨。 未驗證:在真的 App、手機上打 /fork 的樣子。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 9 +- docs/feature-map/chat.md | 4 +- docs/plan-2026-11-engineering.md | 2 +- mobile/index.html | 4 +- src/app.rs | 46 ++------- src/app/chat_ui.rs | 2 +- src/app/commands.rs | 155 +++++++++++++++++++++++++++++++ src/app/remote_ui.rs | 41 +------- 8 files changed, 183 insertions(+), 80 deletions(-) create mode 100644 src/app/commands.rs diff --git a/FEATURES.md b/FEATURES.md index b9323d8..9472438 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 「/」清單只放指令 -- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 +- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact、/fork),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 ### 上線前補上的防護(安全和資源) @@ -1517,6 +1517,13 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 「無需詢問直接允許」「一律詢問」除了用一般的話寫,也可以寫固定樣式:`shell(git *)`、`file(~/Projects/**)`、`connector(gitlab__*)`、`web(domain:example.com)`、`tool(browser_click)`(* 任何字,? 一個字;檔案的 * 只在一層、** 跨資料夾)。 - 樣式在模型之前判斷,每次都一樣,不花模型的錢也不用等:符合「一律詢問」樣式的一定問,模型說允許也沒用(網頁上的字騙不了它);符合允許樣式的直接允許,但如果還有用話寫的「一律詢問」,先讓模型看那幾條;都不符合就照舊把用話寫的規則交給模型。指令要每一段(&&、|、; 分開的)都符合才算允許,有 $()、反引號藏指令的不會被樣式允許。直接操作模式下,「一律詢問」的樣式一樣擋得住。(參考 grok-build 的 Bash(git *) 規則。) +### 分岔(/fork) + +- 「/fork」或「/fork 名字」:把這段對話到現在為止存一份到「過去的對話」最上面,標題「分岔:名字」(沒給名字就用第一句話),聊天裡留一行「已分岔:…」。接著照常在這裡做;想回到分岔那一點走另一條路,從 Bot 選單 › 過去的對話 打開它,目前這段會自動收進過去的對話,兩條路之後互不影響、可以來回切換。參考 grok-build 的 /fork、Claude Code 的 /branch。 +- 不複製整個 Bot:複製的 Bot 會把例行任務跑兩次、訊息管道回兩次。目標、計畫、記憶屬於 Bot,不跟著分岔。 +- Bot 正在做事時不行(「等它做完(或按停止)再 /fork」);對話是空的也不行。電腦、大腦的螢幕、手機打的都算,由大腦做;訊息管道和團隊成員打的不算指令。 +- AnyBot 自己的指令(/btw、/goal、/plan、/always-approve、/usage、/doctor、/context、/compact、/fork)在電腦和手機/螢幕兩條路上由同一個地方認出來、同一個地方做,新增指令只要加一次。 + ### 摘要(/context、/compact) - 對話太長時(到模型可讀的 70%)把較早的內容整理成摘要。摘要照段落寫:使用者要的、已經決定的、做過的事和結果(指令、路徑、網址、數字照原樣)、還沒完成的、注意(試過不行的)。整理得太短(一大段對話不到 200 字)會再要一次。摘要下面由 AnyBot 自己(不是模型)附上使用者最近 12 句原話(每句最多 400 字)和還在跑的背景指令(#編號和指令),這些不會被摘要弄丟。參考 grok-build 的分段摘要和摘要後的提醒。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 302457e..25e6d2c 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -5,7 +5,7 @@ ## 子功能 - 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。 -- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要),打「@」列出其他 Bot。 +- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要)、/fork(分岔:這段對話到這裡為止存一份到「過去的對話」,標題「分岔:…」,之後各走各的),打「@」列出其他 Bot。 - 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。 - 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - 停止:工作中、輸入框空著時,送出鈕變成「停止」。 @@ -23,7 +23,7 @@ - 點側邊欄的 Bot;⌘1–⌘9 切到前九個。 - 輸入框左邊的 +(「輸入框操作」):「附加檔案」「教它一項任務」,下面是換模型(見 [bots](bots.md))。右邊是「開始語音輸入」和送出鈕。 -- Bot 選單(右鍵 Bot,或聊天右上角「更多」):「開始新對話」把目前的對話收進「過去的對話」;「清除聊天記錄」不會再問;「重新啟動這個 Bot」卡住時用,聊天記錄和檔案都保留。 +- Bot 選單(右鍵 Bot,或聊天右上角「更多」):「開始新對話」把目前的對話收進「過去的對話」;/fork 留一份分岔在那裡、目前的照常繼續,打開分岔時目前的會自動收進去;「清除聊天記錄」不會再問;「重新啟動這個 Bot」卡住時用,聊天記錄和檔案都保留。 - 你的最後一則沒有回覆時,下面有「還沒有回覆」和「重新傳送」;被 AnyBot 關掉打斷的回合有「繼續」。 ## 怎麼操作 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 6cb62c7..1ca1da8 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -113,7 +113,7 @@ - 做法:SKILL.md frontmatter:`arguments`(`$ARGUMENTS`、`$1`…)、`allowed-tools`(只能用哪些工具,執行層擋)、`context: fork`(丟給支線做,不佔主對話)。「/技能名 參數」直接帶進去。 - 做完:測試涵蓋三種。 -### M5. /fork 帶著上下文分岔 ⬜ +### M5. /fork 帶著上下文分岔 ✅(分岔存在「過去的對話」,不複製整個 Bot:例行任務、訊息管道會重複;順便把兩份重複的指令分派合成 app/commands.rs 一份) - 做法:`/fork` 把這段對話複製成一個新對話(或新 Bot),之後各走各的。 - 做完:分岔後兩邊互不影響。 diff --git a/mobile/index.html b/mobile/index.html index 75bd540..20a0630 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1656,7 +1656,7 @@ input.addEventListener("keydown", (e) => { input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } }); const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false}; /** AnyBot's own / commands (goal.rs on the brain). */ -const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; +const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; const GOAL_TAG = "[目標]"; /** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name * contains it, then description. None once a space ends the name, or while the bot works. */ @@ -1754,7 +1754,7 @@ async function send() { const memories = b.busy ? undefined : memPicks(); memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); - const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text); + const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/fork(\s|$)/.test(text); if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } // 先顯示: while it works the words aren't in the chat yet — shown at once all the same. const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null; diff --git a/src/app.rs b/src/app.rs index 1fc793d..38676fb 100644 --- a/src/app.rs +++ b/src/app.rs @@ -44,6 +44,8 @@ mod drops_ui; mod memory_ui; mod goal_ui; mod context_ui; +mod commands; +use commands::app_command; mod doctor_ui; mod plan_ui; mod mood_ui; @@ -1426,7 +1428,7 @@ impl App { } // 先顯示: while it works (or the words travel to the brain) they aren't in the chat // yet — the person sees them at once all the same. (A command here draws its own line.) - let local_command = !self.mir.on && (branch::command(&text).is_some() || crate::goal::command(&text).is_some() || crate::plan::command(&text).is_some() || crate::always::command(&text).is_some() || crate::usage::command(&text) || matches!(text.trim(), "/context" | "/compact")); + let local_command = !self.mir.on && app_command(&text).is_some(); if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command { self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now())); } @@ -1456,43 +1458,13 @@ impl App { } // Typed here: this computer is the person's. self.typed_on = Some(String::new()); - // 支線: 「/btw …」 branches the bot off (even while it works: it isn't steering). - if let Some(task) = branch::command(&text) { - self.btw_command(ctx, bot_id, &task, attachments); + // AnyBot's own commands (/btw even while it works: it isn't steering; /goal, /plan, + // /always-approve, /usage, /context, /compact, /fork — commands.rs); anything else takes a + // paused goal up again. + if let Some(cmd) = app_command(&text) { + self.run_app_command(ctx, bot_id, cmd, &text, attachments, picks); return; } - // 目標: 「/goal …」 is AnyBot's, not the bot's; anything else takes a paused goal up again. - if let Some(cmd) = crate::goal::command(&text) { - self.goal_command(ctx, bot_id, cmd, &text, attachments, picks); - return; - } - // 計畫: 「/plan …」 is AnyBot's too. - if let Some(cmd) = crate::plan::command(&text) { - self.plan_command(ctx, bot_id, cmd, &text, attachments, picks); - return; - } - // 一律放行: 「/always-approve」 changes the person's own permissions. - if let Some(cmd) = crate::always::command(&text) { - self.always_command(ctx, bot_id, cmd); - return; - } - // 用量: 「/usage」 — what the models used, a line in this chat. - if crate::usage::command(&text) { - self.usage_note(bot_id); - return; - } - // 對話的長度: 「/context」 how full it is, 「/compact」 fold the older part now. - match text.trim() { - "/context" => { - self.context_note(bot_id); - return; - } - "/compact" => { - self.compact_now(bot_id); - return; - } - _ => {} - } self.goal_heard(bot_id); // While it works, a new message steers the running turn (the original's `turnSteer`: // it doesn't count as a new turn) and reaches the model at its next step. @@ -8560,7 +8532,7 @@ mod tests { let mut bot = app.state.bots[0].clone(); bot.skills = Some(vec!["週報".into()]); let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::>(); - assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact"]); + assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact", "fork"]); assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word"); assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 24a3c3b..28eb00f 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -1134,7 +1134,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool { } /// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs). -pub const SLASH_COMMANDS: [(&str, &str); 8] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要")]; +pub const SLASH_COMMANDS: [(&str, &str); 9] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的")]; /// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone). /// A status of several lines — a retry: the error, what it means, when it tries again — used to diff --git a/src/app/commands.rs b/src/app/commands.rs new file mode 100644 index 0000000..0cd1965 --- /dev/null +++ b/src/app/commands.rs @@ -0,0 +1,155 @@ +// AnyBot's own slash commands (not the bot's): told apart and carried out in one place, whether +// typed here, on a screen of a brain (it sends the words; the brain carries them out) or on the +// phone. They used to be listed twice (send and the remote path), and a new one had to be added +// to both. +// +// 分岔 (/fork, M5): a copy of this conversation goes to 過去的對話 as 「分岔:…」 and the person +// goes on here; opening it later puts this one aside, so the two go their own ways from that point +// (like grok-build's /fork, Claude Code's /branch). A copy of the bot instead would run its +// routines and answer its channels twice. + +use super::*; + +/// One of AnyBot's commands. +pub(super) enum AppCommand { + Btw(String), + Goal(crate::goal::Command), + Plan(crate::plan::Command), + Always(crate::always::Command), + Usage, + Context, + Compact, + Doctor, + Fork(String), +} + +/// A branch's title: 「分岔:」 and the name given, or the conversation's first words. +pub(super) const FORK_PREFIX: &str = "分岔:"; + +/// 「/fork」 or 「/fork 名字」: the name (empty when none), or None. +pub(super) fn fork_command(text: &str) -> Option { + let rest = text.trim_start().strip_prefix("/fork")?; + (rest.is_empty() || rest.starts_with(char::is_whitespace)).then(|| rest.trim().chars().take(40).collect()) +} + +/// The command these words are, if they are one. +pub(super) fn app_command(text: &str) -> Option { + if let Some(task) = branch::command(text) { + return Some(AppCommand::Btw(task)); + } + if let Some(c) = crate::goal::command(text) { + return Some(AppCommand::Goal(c)); + } + if let Some(c) = crate::plan::command(text) { + return Some(AppCommand::Plan(c)); + } + if let Some(c) = crate::always::command(text) { + return Some(AppCommand::Always(c)); + } + if crate::usage::command(text) { + return Some(AppCommand::Usage); + } + if crate::doctor::command(text) { + return Some(AppCommand::Doctor); + } + if let Some(name) = fork_command(text) { + return Some(AppCommand::Fork(name)); + } + match text.trim() { + "/context" => Some(AppCommand::Context), + "/compact" => Some(AppCommand::Compact), + _ => None, + } +} + +impl App { + /// Carry out one of AnyBot's commands for this bot. + pub(super) fn run_app_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: AppCommand, text: &str, attachments: Vec, picks: Option>) { + match cmd { + AppCommand::Btw(task) => self.btw_command(ctx, bot_id, &task, attachments), + AppCommand::Goal(c) => self.goal_command(ctx, bot_id, c, text, attachments, picks), + AppCommand::Plan(c) => self.plan_command(ctx, bot_id, c, text, attachments, picks), + AppCommand::Always(c) => self.always_command(ctx, bot_id, c), + AppCommand::Usage => self.usage_note(bot_id), + AppCommand::Context => self.context_note(bot_id), + AppCommand::Compact => self.compact_now(bot_id), + AppCommand::Doctor => self.doctor_start(bot_id), + AppCommand::Fork(name) => self.fork_now(bot_id, &name), + } + } + + /// 「/fork」: this conversation, as it is now, kept in 過去的對話 too. + pub(super) fn fork_now(&mut self, bot_id: u64, name: &str) { + let Some(b) = self.state.bot(bot_id) else { return }; + if self.streams.contains_key(&bot_id) { + let note = format!("{} 正在做事:等它做完(或按停止)再 /fork。", b.name); + self.goal_note(bot_id, ¬e); + return; + } + let words: Vec<&Message> = b.messages.iter().filter(|m| !m.note).collect(); + if words.is_empty() { + self.goal_note(bot_id, "對話還是空的,沒有東西可以分岔。"); + return; + } + let what = if name.is_empty() { words.iter().find(|m| m.role == Role::User).map(|m| first_line(&m.text, 24)).unwrap_or_else(|| "對話".into()) } else { name.to_string() }; + let title = format!("{FORK_PREFIX}{what}"); + let Some(b) = self.state.bot_mut(bot_id) else { return }; + let mut copy = b.messages.clone(); + // (Like any conversation put aside: its words, not its screenshots in memory.) + copy.iter_mut().for_each(|m| m.images.clear()); + b.threads.insert(0, (title.clone(), copy)); + b.threads.truncate(50); + self.goal_note(bot_id, &format!("已分岔:這段對話到這裡為止存了一份「{title}」。接著在這裡做;要回到這一點走另一條路,從 Bot 的選單 › 過去的對話 打開它(這邊會自動收進過去的對話,不會不見)。")); + self.mark(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_are_told_apart() { + assert!(matches!(app_command("/fork"), Some(AppCommand::Fork(n)) if n.is_empty())); + assert!(matches!(app_command("/fork 試另一個做法"), Some(AppCommand::Fork(n)) if n == "試另一個做法")); + assert!(app_command("/forkx").is_none() && app_command("請 /fork").is_none()); + assert!(matches!(app_command("/btw 查天氣"), Some(AppCommand::Btw(t)) if t == "查天氣")); + assert!(matches!(app_command("/goal 測試通過"), Some(AppCommand::Goal(_)))); + assert!(matches!(app_command(" /compact "), Some(AppCommand::Compact))); + assert!(matches!(app_command("/doctor"), Some(AppCommand::Doctor))); + assert!(app_command("你好").is_none() && app_command("/Users/me/a.txt").is_none()); + } + + #[test] + fn a_fork_keeps_a_copy_and_goes_on_here() { + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-fork.png"))); + // (A bot not shown as working in the sample.) + let id = app.state.bots.iter().find(|b| b.members.is_empty() && !app.streams.contains_key(&b.id)).unwrap().id; + app.state.bot_mut(id).unwrap().messages = vec![Message::user("幫我寫一份報告"), Message::assistant("好,第一版在 report.md", "m")]; + app.run_app_command(&ctx, id, AppCommand::Fork("改寫成表格".into()), "/fork 改寫成表格", vec![], None); + let b = app.state.bot(id).unwrap(); + assert_eq!(b.threads[0].0, "分岔:改寫成表格"); + assert_eq!(b.threads[0].1.len(), 2); + assert!(b.messages.len() == 3 && b.messages[2].note && b.messages[2].text.contains("已分岔"), "{:?}", b.messages.last()); + // The two go their own ways: what is said here doesn't reach the copy. + app.state.bot_mut(id).unwrap().messages.push(Message::user("改用圖表")); + assert_eq!(app.state.bot(id).unwrap().threads[0].1.len(), 2); + // Opening the branch puts this one aside, and comes back at the point it was made. + app.open_thread(id, 0); + let b = app.state.bot(id).unwrap(); + assert_eq!(b.messages.len(), 2); + assert!(b.threads[0].1.iter().any(|m| m.text == "改用圖表")); + // Nothing to fork, or busy: a line says why. + app.state.bot_mut(id).unwrap().messages.clear(); + app.fork_now(id, ""); + assert!(app.state.bot(id).unwrap().messages[0].text.contains("空的")); + app.state.bot_mut(id).unwrap().messages = vec![Message::user("x")]; + let busy = app.state.bots.iter().find(|b| app.streams.contains_key(&b.id)).map(|b| b.id); + if let Some(busy) = busy { + app.state.bot_mut(busy).unwrap().messages.push(Message::user("在做")); + app.fork_now(busy, ""); + assert!(app.state.bot(busy).unwrap().messages.iter().any(|m| m.note && m.text.contains("正在做事"))); + } + } +} diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 1efc019..67d4014 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -535,42 +535,11 @@ impl App { .collect(); // 目標: 「/goal …」 is AnyBot's, not the bot's (owner/admin only); anything else takes a paused goal up again. if !member { - // 支線: 「/btw …」 from the phone or a screen. - if let Some(task) = super::branch::command(&text) { - self.btw_command(ctx, bot, &task, atts); - return; - } - if let Some(cmd) = crate::goal::command(&text) { - self.goal_command(ctx, bot, cmd, &text, atts, memories); - return; - } - if let Some(cmd) = crate::plan::command(&text) { - self.plan_command(ctx, bot, cmd, &text, atts, memories); - return; - } - // 一律放行: the owner's (a teammate's words arrive as 「【名字】…」, never a command). - if let Some(cmd) = crate::always::command(&text) { - self.always_command(ctx, bot, cmd); - return; - } - if crate::usage::command(&text) { - self.usage_note(bot); - return; - } - match text.trim() { - "/context" => { - self.context_note(bot); - return; - } - "/compact" => { - self.compact_now(bot); - return; - } - _ => {} - } - // (From the phone or a screen: the brain checks itself.) - if crate::doctor::command(&text) { - self.doctor_start(bot); + // AnyBot's own commands from the phone or a screen (commands.rs): the owner's + // only (a teammate's words arrive as 「【名字】…」, never a command). A + // /doctor from there: the brain checks itself. + if let Some(cmd) = super::app_command(&text) { + self.run_app_command(ctx, bot, cmd, &text, atts, memories); return; } self.goal_heard(bot); From c596322c3b07f2fa6a399564419e4c22e694bde5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:35:31 +0800 Subject: [PATCH 3/4] =?UTF-8?q?feat:=20=E6=AA=A2=E6=9F=A5=E9=BB=9E?= =?UTF-8?q?=E8=88=87=20/rewind=EF=BC=9ABot=20=E7=94=A8=20edit=5Ffile=20?= =?UTF-8?q?=E6=94=B9=E7=9A=84=E6=AA=94=E6=A1=88=E5=92=8C=E5=B0=8D=E8=A9=B1?= =?UTF-8?q?=E5=8F=AF=E4=BB=A5=E9=80=80=E5=9B=9E=E4=B9=8B=E5=89=8D=E8=AA=AA?= =?UTF-8?q?=E7=9A=84=E6=9F=90=E4=B8=80=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - edit_file 改檔案前先存原本的樣子(沒有這個檔案也記),記在開始那一輪的那句話底下,同一輪同一個檔案只記一次;你的電腦、Bot 自己的電腦(Docker、封閉資料夾)、SSH 電腦都記;存在資料夾的 checkpoints/,同樣內容存一份,一週後清掉。 - /rewind 列出最近 10 句和之後改過幾個檔案;/rewind N 檔案和對話都退回(新的先退,新建的刪掉;那句話放回輸入框;退回前的整段對話收進過去的對話「退回前:…」);/rewind N 檔案、/rewind N 對話 只退一邊。檔案在背景還原,好了一行報告。 - 用指令改的、其他 AnyBot 電腦上的、超過 2 MB 的不在裡面,照實說。 - tools.rs:file_spot、file_now、file_put(box 的路徑檢查抽成 box_guard 共用);Place 可以存檔。 - 背景做完的一行字(later_notes)走同一個地方進聊天。 已驗證:cargo test 593 通過(兩輪改三個檔案:退到第二輪只還原那輪的、退到第一輪全部還原、新建的刪掉、太大的照實說;App 裡 /rewind 清單、編號不存在、退回後只剩 AnyBot 的字、草稿是那句話、退回前收進過去的對話、README 回到中文、INSTALL.md 刪掉)、clippy -D warnings 乾淨。 未驗證:Docker 和 SSH 電腦上的存與還原(走同一個 cat 的路)、真的 App 和手機上打 /rewind。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 11 +- docs/feature-map/chat.md | 2 +- docs/feature-map/files.md | 4 +- docs/plan-2026-11-engineering.md | 2 +- mobile/index.html | 4 +- src/agent.rs | 5 + src/app.rs | 6 +- src/app/chat_ui.rs | 2 +- src/app/commands.rs | 131 ++++++++++++++++ src/checkpoint.rs | 253 +++++++++++++++++++++++++++++++ src/main.rs | 3 + src/tools.rs | 94 +++++++++++- 12 files changed, 501 insertions(+), 16 deletions(-) create mode 100644 src/checkpoint.rs diff --git a/FEATURES.md b/FEATURES.md index 9472438..9920bd7 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 「/」清單只放指令 -- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact、/fork),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 +- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact、/fork、/rewind),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 ### 上線前補上的防護(安全和資源) @@ -1522,7 +1522,14 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 「/fork」或「/fork 名字」:把這段對話到現在為止存一份到「過去的對話」最上面,標題「分岔:名字」(沒給名字就用第一句話),聊天裡留一行「已分岔:…」。接著照常在這裡做;想回到分岔那一點走另一條路,從 Bot 選單 › 過去的對話 打開它,目前這段會自動收進過去的對話,兩條路之後互不影響、可以來回切換。參考 grok-build 的 /fork、Claude Code 的 /branch。 - 不複製整個 Bot:複製的 Bot 會把例行任務跑兩次、訊息管道回兩次。目標、計畫、記憶屬於 Bot,不跟著分岔。 - Bot 正在做事時不行(「等它做完(或按停止)再 /fork」);對話是空的也不行。電腦、大腦的螢幕、手機打的都算,由大腦做;訊息管道和團隊成員打的不算指令。 -- AnyBot 自己的指令(/btw、/goal、/plan、/always-approve、/usage、/doctor、/context、/compact、/fork)在電腦和手機/螢幕兩條路上由同一個地方認出來、同一個地方做,新增指令只要加一次。 +- AnyBot 自己的指令(/btw、/goal、/plan、/always-approve、/usage、/doctor、/context、/compact、/fork、/rewind)在電腦和手機/螢幕兩條路上由同一個地方認出來、同一個地方做,新增指令只要加一次。 + +### 檢查點與退回(/rewind) + +- Bot 用 `edit_file` 改檔案之前,AnyBot 先把那個檔案原本的樣子存起來(還沒有這個檔案也記下來),記在開始那一輪的你那句話底下;同一輪改同一個檔案好幾次只記第一次。在你的電腦、Bot 自己的電腦(Docker 或封閉資料夾)、SSH 電腦上改的都記;存在資料夾的 checkpoints/,一週後清掉,同樣的內容只存一份。參考 Claude Code 的檢查點、grok-build 的 /rewind。 +- 「/rewind」:列出這個對話裡你最近說的 10 句話(最新的在上面),每句寫「之後改過 N 個檔案」。 +- 「/rewind 編號」:檔案和對話都退回那句話之前——那句話之後改的檔案一個個還原(之後才新建的刪掉),新的改動先退,所以每個檔案都回到那句話之前的樣子;對話從那句話起拿掉,那句話放回輸入框(在別台打的照聊天裡寫的再打一次),退回前的整段對話收在過去的對話「退回前:…」,退錯了可以打開拿回來。「/rewind 編號 檔案」只退檔案、「/rewind 編號 對話」只退對話。檔案在背景還原,好了一行列出每個檔案還原了、刪掉了,或為什麼沒還原。 +- 不在檢查點裡的,照實說:用指令改的(shell 的 cat >、sed -i、git、npm…),帳號裡其他 AnyBot 電腦上改的,超過 2 MB 的檔案(退回時說「太大,當時沒有存」)。Bot 正在做事時不能退回(等它做完或按停止)。電腦、大腦的螢幕、手機打的都算,由大腦做。 ### 摘要(/context、/compact) diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 25e6d2c..f1f26d4 100644 --- a/docs/feature-map/chat.md +++ b/docs/feature-map/chat.md @@ -5,7 +5,7 @@ ## 子功能 - 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。 -- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要)、/fork(分岔:這段對話到這裡為止存一份到「過去的對話」,標題「分岔:…」,之後各走各的),打「@」列出其他 Bot。 +- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要)、/fork(分岔:這段對話到這裡為止存一份到「過去的對話」,標題「分岔:…」,之後各走各的)、/rewind(退回:Bot 改的檔案和對話退回之前說的某一句,見 [files](files.md)),打「@」列出其他 Bot。 - 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。 - 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - 停止:工作中、輸入框空著時,送出鈕變成「停止」。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index a752e04..87825e6 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -11,6 +11,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - 工作資料夾:這台電腦是 Bot 設定的「起始資料夾」(沒填就是家目錄);Bot 自己的電腦是它自己的資料夾;SSH 電腦是設定的資料夾或對方的家目錄。 - 交出結果:`send_file` 把檔案放進聊天變成檔案卡片,點一下預覽、可以下載;`open_for_person` 在使用者的螢幕上打開檔案或網址;`publish_site` 把一個 .html 檔或有 index.html 的資料夾發佈成公開網站,回傳網址,同一個名字再發佈就取代。 - 傳到帳號裡另一台裝置是 `send_to_device`(見 [computers](computers.md))。 +- 檢查點:`edit_file` 改檔案前,AnyBot 先把檔案原本的樣子存起來(記在開始那一輪的那句話底下,存一週)。使用者打「/rewind」看可以退回的點,「/rewind 編號」把那句話之後改的檔案還原、對話退回那句話之前,「/rewind 編號 檔案」只退檔案、「/rewind 編號 對話」只退對話。 ## 使用者怎麼到 @@ -23,7 +24,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 ## 怎麼操作 - Bot:先用 `list_dir`、`search`、`read_file` 看清楚再動手,改檔案用 `edit_file`。跑很久的指令讓它進背景,再用 `read_terminal` 的 wait_ms 等,不要一直重查;指令列的 AI 工具用它們的非互動模式(例如 `claude -p "…"`)。一定要看終端機畫面時才用 interactive,用完關掉。每個工具都有 `computer`。交結果用 `send_file`,不要只說檔案在哪;要使用者馬上看到用 `open_for_person`;要公開網址用 `publish_site`(path,name 只用英文字母、數字和 -)。除了 `send_file`,這些都屬於「檔案與指令」能力。結果太長被截(只留開頭和結尾,中間寫「完整內容用 read_result 讀:id=…」)或較早的結果被收起時,用 `read_result`(id、from、chars,一次最多兩萬字)讀完整的,不要為了看完整的再做一次那一步(每個 Bot 都有,完整結果留 7 天)。 -- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`。 +- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`、`cargo test rewind`。請 Bot 改兩個檔案,再打「/rewind」選那一句,兩個檔案要回到原本的內容、那句話回到輸入框。 ## 陷阱 @@ -36,4 +37,5 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - `open_for_person` 不打開程式或指令檔(打開就會執行),改用 `send_file`;AnyBot 在伺服器上時,網址會在使用者正在用的那台電腦打開(不知道是哪台就打不開),檔案打不開,也改用 `send_file`。 - SSH 電腦上的檔案不能直接 `send_file`、`open_for_person` 或 `publish_site`;帳號裡其他電腦的檔案可以 `send_file`(最多 20 MB),但不能打開或發佈。先複製到 Bot 自己的電腦。 - `publish_site`:任何知道網址的人都看得到。每個網站名字第一次會問(工作資料夾外的每次都問);最多 500 個檔案、25 MB;點開頭的檔案、node_modules、機密檔案、指到資料夾外的連結會略過;一定要有 index.html。 +- 檢查點只記 `edit_file` 改的:用 `shell` 改的(cat >、sed -i、git、npm…)不在裡面,帳號裡其他 AnyBot 電腦上的檔案也不在;超過 2 MB 的檔案不存,退回時會說沒辦法還原。要能退回,改檔案就用 `edit_file`。 - 按停止會停掉正在跑的那一步,和這個 Bot 的互動終端機(連同它們啟動的程式);一般的背景指令(例如故意開著的伺服器)會繼續跑。「重新啟動這個 Bot」停掉這個 Bot 的全部背景指令,關掉 App 全部停掉。整個 AnyBot 同時最多 24 個背景指令在跑,滿了新的不會留在背景(會先停掉),用不到的用 stop 關掉。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 1ca1da8..15b47ff 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -97,7 +97,7 @@ ## 軌 M:新機制 -### M1. 檢查點與 /rewind ⬜ +### M1. 檢查點與 /rewind ✅(只記 edit_file 改的,跟 Claude Code 一樣;git stash create 沒做:指令改的東西太多種,退回時會連使用者自己改的一起退) - 做法:每一輪第一次改檔案前,替工作資料夾的檔案(git 專案用 `git stash create`,其他用改之前的副本)存一個檢查點;`/rewind` 列出最近的檢查點,選一個把檔案和對話退回那裡。 - 做完:改了三個檔案後 /rewind,三個檔案回到原本內容。 diff --git a/mobile/index.html b/mobile/index.html index 20a0630..27f39b5 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1656,7 +1656,7 @@ input.addEventListener("keydown", (e) => { input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } }); const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false}; /** AnyBot's own / commands (goal.rs on the brain). */ -const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; +const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "rewind", description: "退回:把 Bot 改的檔案和對話退回之前說的某一句"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}]; const GOAL_TAG = "[目標]"; /** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name * contains it, then description. None once a space ends the name, or while the bot works. */ @@ -1754,7 +1754,7 @@ async function send() { const memories = b.busy ? undefined : memPicks(); memReset(); input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash(); - const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/fork(\s|$)/.test(text); + const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/(fork|rewind)(\s|$)/.test(text); if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; } // 先顯示: while it works the words aren't in the chat yet — shown at once all the same. const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null; diff --git a/src/agent.rs b/src/agent.rs index bc0e923..ff23dbd 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -3290,6 +3290,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< (Ok(()), Ok(t)) => { started(); let ids = tools::RunIds { conversation: bot_id.to_string(), request: call.id.clone() }; + // 檢查點: the file as it was, kept under the person's message that started this turn (/rewind). + if call.name == "edit_file" { + let turn = history.iter().rev().find(|m| m.role == Role::User && !m.note && m.at > 0).map(|m| m.at).unwrap_or(0); + crate::checkpoint::before_edit(bot_id, turn, t, &call.args); + } let (out, ok) = if is_mac && on_device.is_none() { crate::macapps::run(&call.name, &call.args) } else if let (true, Some(host)) = (is_screen || is_web || is_mac, on_device.as_ref()) { diff --git a/src/app.rs b/src/app.rs index 38676fb..d51b4c2 100644 --- a/src/app.rs +++ b/src/app.rs @@ -214,6 +214,8 @@ pub struct App { want_direct: std::cell::Cell, /// 診斷 (/doctor) reports finished on their thread: (the chat it was asked in, the report). doctor_out: Arc>>, + /// Lines for a bot's chat that work on another thread finished (/rewind's files…). + later_notes: Arc>>, /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). #[allow(clippy::type_complexity)] compact_out: Arc)>>>, @@ -496,6 +498,7 @@ impl App { want_direct: Default::default(), strangers: Default::default(), doctor_out: Default::default(), + later_notes: Default::default(), compact_out: Default::default(), managed: if demo { policy::Managed::default() } else { policy::read() }, settings_was_open: false, @@ -5961,6 +5964,7 @@ impl App { // 診斷: a 「/doctor」 that finished; a 「/compact」 too. self.doctor_tick(); self.compact_tick(); + self.later_tick(); // A screen of another AnyBot's brain: its bots work there, not here. if self.mir.on { self.remote_tick(ctx); @@ -8532,7 +8536,7 @@ mod tests { let mut bot = app.state.bots[0].clone(); bot.skills = Some(vec!["週報".into()]); let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::>(); - assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact", "fork"]); + assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact", "fork", "rewind"]); assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word"); assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 28eb00f..7d36438 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -1134,7 +1134,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool { } /// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs). -pub const SLASH_COMMANDS: [(&str, &str); 9] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的")]; +pub const SLASH_COMMANDS: [(&str, &str); 10] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的"), ("rewind", "退回:把 Bot 改的檔案和對話退回之前說的某一句")]; /// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone). /// A status of several lines — a retry: the error, what it means, when it tries again — used to diff --git a/src/app/commands.rs b/src/app/commands.rs index 0cd1965..f5d7ac3 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -21,8 +21,12 @@ pub(super) enum AppCommand { Compact, Doctor, Fork(String), + Rewind(Result), } +/// How many of the person's messages /rewind offers. +const REWIND_POINTS: usize = 10; + /// A branch's title: 「分岔:」 and the name given, or the conversation's first words. pub(super) const FORK_PREFIX: &str = "分岔:"; @@ -55,6 +59,9 @@ pub(super) fn app_command(text: &str) -> Option { if let Some(name) = fork_command(text) { return Some(AppCommand::Fork(name)); } + if let Some(r) = crate::checkpoint::command(text) { + return Some(AppCommand::Rewind(r)); + } match text.trim() { "/context" => Some(AppCommand::Context), "/compact" => Some(AppCommand::Compact), @@ -75,9 +82,88 @@ impl App { AppCommand::Compact => self.compact_now(bot_id), AppCommand::Doctor => self.doctor_start(bot_id), AppCommand::Fork(name) => self.fork_now(bot_id, &name), + AppCommand::Rewind(Err(e)) => self.goal_note(bot_id, &e), + AppCommand::Rewind(Ok(r)) => self.rewind(bot_id, r), } } + /// Lines that work on another thread finished, into their chats. + pub(super) fn later_tick(&mut self) { + let later = std::mem::take(&mut *self.later_notes.lock().unwrap()); + for (bot_id, text) in later { + self.goal_note(bot_id, &text); + self.save_now = true; + } + } + + /// The points 「/rewind」 can go back to: the person's messages in this conversation, newest + /// first (index in the chat, its time, its words). + fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> { + let Some(b) = self.state.bot(bot_id) else { return vec![] }; + b.messages.iter().enumerate().rev().filter(|(_, m)| m.role == Role::User && !m.note && m.at > 0).take(REWIND_POINTS).map(|(i, m)| (i, m.at, m.text.clone())).collect() + } + + /// 「/rewind」 (the points) or 「/rewind N [檔案|對話]」 (back to one). + pub(super) fn rewind(&mut self, bot_id: u64, r: crate::checkpoint::Rewind) { + use crate::checkpoint::Rewind; + let points = self.rewind_points(bot_id); + let kept = crate::checkpoint::entries(bot_id); + let Some(b) = self.state.bot(bot_id) else { return }; + let name = b.name.clone(); + let (n, files, chat) = match r { + Rewind::List => { + if points.is_empty() { + self.goal_note(bot_id, "這個對話還沒有可以退回的點。"); + return; + } + let now = crate::model::now_ms(); + let mut text = format!("可以退回的點(最新的在最上面):退回去會把那句話之後 {name} 用 edit_file 改的檔案還原;用指令(shell、git…)改的不在裡面。"); + for (k, (_, at, words)) in points.iter().enumerate() { + let n = crate::checkpoint::files_since(&kept, *at).len(); + text.push_str(&format!("\n{}. {}「{}」:{}", k + 1, crate::pages::ago(*at, now), first_line(words, 30), if n == 0 { "之後沒有改過檔案".to_string() } else { format!("之後改過 {n} 個檔案") })); + } + text.push_str("\n打「/rewind 編號」檔案和對話都退回那句話之前;「/rewind 編號 檔案」只退檔案;「/rewind 編號 對話」只退對話。"); + self.goal_note(bot_id, &text); + return; + } + Rewind::To { n, files, chat } => (n, files, chat), + }; + if self.streams.contains_key(&bot_id) { + self.goal_note(bot_id, &format!("{name} 正在做事:等它做完(或按停止)再 /rewind。")); + return; + } + let Some((i, at, words)) = points.get(n - 1).cloned() else { + self.goal_note(bot_id, &format!("沒有第 {n} 個點:打 /rewind 看有哪些。")); + return; + }; + if chat { + let Some(b) = self.state.bot_mut(bot_id) else { return }; + // The whole conversation first goes to 過去的對話: a rewind can be taken back. + let mut copy = b.messages.clone(); + copy.iter_mut().for_each(|m| m.images.clear()); + let title = format!("退回前:{}", first_line(&words, 24)); + b.threads.insert(0, (title.clone(), copy)); + b.threads.truncate(50); + b.messages.truncate(i); + b.regen_undo.clear(); + b.draft = words.clone(); + self.drafts.insert(bot_id, words.clone()); + self.goal_note(bot_id, &format!("對話退回到你說「{}」之前,那句話放回輸入框了(在別台打的就照這裡再打一次)。退回前的整段對話收在過去的對話「{title}」。", first_line(&words, 40))); + } + if files { + let out = self.later_notes.clone(); + let repaint = self.repaint_fn(); + self.goal_note(bot_id, "正在還原檔案…"); + std::thread::spawn(move || { + let lines = crate::checkpoint::restore(bot_id, at); + let text = if lines.is_empty() { "檔案:那句話之後沒有用 edit_file 改過檔案,沒有要還原的(用指令改的不在檢查點裡)。".to_string() } else { format!("檔案退回到那句話之前:\n{}", lines.iter().map(|l| format!("- {l}")).collect::>().join("\n")) }; + out.lock().unwrap().push((bot_id, text)); + repaint(); + }); + } + self.mark(); + } + /// 「/fork」: this conversation, as it is now, kept in 過去的對話 too. pub(super) fn fork_now(&mut self, bot_id: u64, name: &str) { let Some(b) = self.state.bot(bot_id) else { return }; @@ -152,4 +238,49 @@ mod tests { assert!(app.state.bot(busy).unwrap().messages.iter().any(|m| m.note && m.text.contains("正在做事"))); } } + + /// 「/rewind」 lists the person's messages with how many files changed after each; going + /// back to one puts the files back, the chat back to before it (its words in the input box, + /// the whole chat in 過去的對話). + #[test] + fn rewind_takes_files_and_chat_back() { + let ctx = egui::Context::default(); + let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-rewind.png"))); + let id = app.state.bots.iter().find(|b| b.members.is_empty() && !app.streams.contains_key(&b.id)).unwrap().id; + let w = std::env::temp_dir().join(format!("anybot-rewind-app-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&w); + std::fs::create_dir_all(&w).unwrap(); + std::fs::write(w.join("README.md"), "中文版").unwrap(); + let t = crate::tools::Target { name: "你的電腦".into(), place: crate::tools::Place::Local { workdir: w.clone() } }; + let said = |text: &str, at: i64| Message { at, ..Message::user(text) }; + app.state.bot_mut(id).unwrap().messages = vec![said("把 README 改成英文", 1_000), Message::assistant("改好了", "m"), said("再加一段安裝說明", 2_000), Message::assistant("加好了", "m")]; + crate::checkpoint::before_edit(id, 1_000, &t, r#"{"path":"README.md"}"#); + std::fs::write(w.join("README.md"), "English").unwrap(); + crate::checkpoint::before_edit(id, 2_000, &t, r#"{"path":"INSTALL.md"}"#); + std::fs::write(w.join("INSTALL.md"), "install").unwrap(); + let run = |app: &mut App, text: &str| { + let cmd = app_command(text).unwrap(); + app.run_app_command(&ctx, id, cmd, text, vec![], None); + }; + run(&mut app, "/rewind"); + let list = app.state.bot(id).unwrap().messages.last().unwrap().text.clone(); + assert!(list.contains("1. ") && list.contains("再加一段安裝說明") && list.contains("之後改過 1 個檔案") && list.contains("把 README 改成英文") && list.contains("之後改過 2 個檔案"), "{list}"); + run(&mut app, "/rewind 9"); + assert!(app.state.bot(id).unwrap().messages.last().unwrap().text.contains("沒有第 9 個")); + run(&mut app, "/rewind 2"); + let b = app.state.bot(id).unwrap(); + assert!(b.messages.iter().all(|m| m.note), "only AnyBot's lines are left: {:?}", b.messages); + assert_eq!(b.draft, "把 README 改成英文"); + assert!(b.threads[0].0.starts_with("退回前:") && b.threads[0].1.len() >= 4); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.later_notes.lock().unwrap().is_empty() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + app.later_tick(); + let report = app.state.bot(id).unwrap().messages.last().unwrap().text.clone(); + assert!(report.contains("README.md") && report.contains("INSTALL.md"), "{report}"); + assert_eq!(std::fs::read_to_string(w.join("README.md")).unwrap(), "中文版"); + assert!(!w.join("INSTALL.md").exists()); + let _ = std::fs::remove_dir_all(&w); + } } diff --git a/src/checkpoint.rs b/src/checkpoint.rs new file mode 100644 index 0000000..d8f7e87 --- /dev/null +++ b/src/checkpoint.rs @@ -0,0 +1,253 @@ +//! 檢查點與 /rewind (M1). Before a bot changes a file with edit_file, what the file was is kept, +//! under the person's message that started that turn (its time). 「/rewind」 lists those messages; +//! 「/rewind N」 puts the files back as they were before the N-th and takes the chat back to just +//! before it; 「/rewind N 檔案」 only the files, 「/rewind N 對話」 only the chat. Like Claude +//! Code's checkpoints: what commands changed (shell, git, npm…) isn't in them, nor files on +//! another AnyBot (裝置連結: that computer's files are its own). Kept a week, in the data folder. + +use crate::tools::{Place, Target}; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// Kept this long. +const KEEP_DAYS: i64 = 7; +/// A file bigger than this isn't kept (it can't be put back; /rewind says so). +pub const MAX_FILE_BYTES: usize = 2 * 1024 * 1024; + +/// One file as it was before a turn changed it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Entry { + /// When it was kept. + pub at: i64, + /// The person's message that started the turn (its `at`). + pub turn: i64, + /// The computer's name, to show. + pub computer: String, + pub place: Place, + pub path: String, + /// Its content before (the name it is kept under); None: the file wasn't there. + pub before: Option, + /// Too big to keep: it can't be put back. + #[serde(default)] + pub too_big: bool, +} + +fn dir() -> PathBuf { + crate::model::State::path().parent().map(|d| d.join("checkpoints")).unwrap_or_else(|| std::env::temp_dir().join("anybot-checkpoints")) +} + +fn log_of(bot: u64) -> PathBuf { + dir().join(format!("bot-{bot}.jsonl")) +} + +fn blob(name: &str) -> PathBuf { + dir().join("blobs").join(name) +} + +/// This bot's kept files, oldest first (a week's). +pub fn entries(bot: u64) -> Vec { + let since = crate::model::now_ms() - KEEP_DAYS * 86_400_000; + std::fs::read_to_string(log_of(bot)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str::(l).ok()).filter(|e| e.at >= since).collect() +} + +fn write_all(bot: u64, list: &[Entry]) -> Result<(), String> { + let text: String = list.iter().filter_map(|e| serde_json::to_string(e).ok()).map(|l| l + "\n").collect(); + std::fs::create_dir_all(dir()).map_err(|e| e.to_string())?; + std::fs::write(log_of(bot), text).map_err(|e| e.to_string()) +} + +/// Before edit_file changes `args`' file on `target` in the turn that `turn` started: keep it as +/// it is now (once per turn and file). Nothing on another AnyBot; a failure only goes to the log. +pub fn before_edit(bot: u64, turn: i64, target: &Target, args: &str) { + if turn == 0 { + return; + } + let path = crate::tools::arg_str(&crate::tools::args_of(args), "path"); + if path.trim().is_empty() { + return; + } + let Some(spot) = crate::tools::file_spot(target, &path) else { return }; + let (place, path) = match spot { + Ok(s) => s, + Err(e) => { + log::info!("檢查點:{path} 找不到位置:{e}"); + return; + } + }; + let mut list = entries(bot); + if list.iter().any(|e| e.turn == turn && e.place == place && e.path == path) { + return; + } + let (before, too_big) = match crate::tools::file_now(&place, &path) { + Ok(None) => (None, false), + Ok(Some(b)) if b.len() > MAX_FILE_BYTES => (None, true), + Ok(Some(b)) => match keep(&b) { + Ok(name) => (Some(name), false), + Err(e) => { + log::warn!("檢查點:存不了 {path}:{e}"); + return; + } + }, + Err(e) => { + log::warn!("檢查點:讀不到 {path}:{e}"); + return; + } + }; + list.push(Entry { at: crate::model::now_ms(), turn, computer: target.name.clone(), place, path, before, too_big }); + if let Err(e) = write_all(bot, &list) { + log::warn!("檢查點:寫不進紀錄:{e}"); + } +} + +/// Keep a file's content under the name of its hash (the same content kept once). +fn keep(bytes: &[u8]) -> Result { + let name: String = ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|x| format!("{x:02x}")).collect(); + let p = blob(&name); + std::fs::create_dir_all(dir().join("blobs")).map_err(|e| e.to_string())?; + // (Written again when already there: its time says it is still in use, for prune.) + std::fs::write(&p, bytes).map_err(|e| e.to_string())?; + Ok(name) +} + +/// The files the turns from `turn` on changed (each file once), to show. +pub fn files_since(list: &[Entry], turn: i64) -> Vec<&Entry> { + let mut seen: Vec<&Entry> = vec![]; + for e in list.iter().filter(|e| e.turn >= turn) { + if !seen.iter().any(|s| s.place == e.place && s.path == e.path) { + seen.push(e); + } + } + seen +} + +/// Put back every file the turns from `turn` on changed, as it was before them (newest change +/// undone first, so each file ends as it was before the first). Those entries are used up. +/// One line per file. +pub fn restore(bot: u64, turn: i64) -> Vec { + let list = entries(bot); + let (undo, keep_list): (Vec, Vec) = list.into_iter().partition(|e| e.turn >= turn); + let mut lines: Vec<(String, String)> = vec![]; + for e in undo.iter().rev() { + let what = if e.computer.is_empty() { e.path.clone() } else { format!("{}({})", e.path, e.computer) }; + let r = if e.too_big { + Err("太大(超過 2 MB),當時沒有存".to_string()) + } else { + match &e.before { + None => crate::tools::file_put(&e.place, &e.path, None).map(|_| "刪掉了(那時還沒有這個檔案)"), + Some(name) => std::fs::read(blob(name)).map_err(|err| format!("存的內容不見了:{err}")).and_then(|b| crate::tools::file_put(&e.place, &e.path, Some(&b))).map(|_| "還原了"), + } + }; + // (Each file is reported once: by the change undone last, the one that counts.) + lines.retain(|l| l.0 != what); + lines.push((what.clone(), match r { + Ok(word) => format!("{what}:{word}"), + Err(err) => format!("{what}:沒有還原,{err}"), + })); + } + if let Err(e) = write_all(bot, &keep_list) { + log::warn!("檢查點:寫不進紀錄:{e}"); + } + lines.into_iter().map(|(_, l)| l).collect() +} + +/// Kept content no entry has used for longer than a week goes (at start). +pub fn prune() { + let Ok(rd) = std::fs::read_dir(dir().join("blobs")) else { return }; + let old = std::time::SystemTime::now() - std::time::Duration::from_secs((KEEP_DAYS as u64 + 1) * 86_400); + for e in rd.flatten() { + if e.metadata().and_then(|m| m.modified()).is_ok_and(|t| t < old) { + let _ = std::fs::remove_file(e.path()); + } + } +} + +/// What 「/rewind …」 asks for. +#[derive(Clone, Debug, PartialEq)] +pub enum Rewind { + /// The list of points. + List, + /// Back to point N (1 = the newest): files, chat, or both. + To { n: usize, files: bool, chat: bool }, +} + +/// 「/rewind」, 「/rewind 2」, 「/rewind 2 檔案」, 「/rewind 2 對話」 (None: not this command; +/// Some(Err) when the words after it can't be read). +pub fn command(text: &str) -> Option> { + let rest = text.trim().strip_prefix("/rewind")?; + if !(rest.is_empty() || rest.starts_with(char::is_whitespace)) { + return None; + } + let mut words = rest.split_whitespace(); + let Some(n) = words.next() else { return Some(Ok(Rewind::List)) }; + let Ok(n) = n.parse::() else { return Some(Err(format!("「{n}」不是編號:先打 /rewind 看有哪些點,再打 /rewind 編號"))) }; + if n == 0 { + return Some(Err("編號從 1 開始".into())); + } + let (files, chat) = match words.next() { + None => (true, true), + Some("檔案" | "files" | "code") => (true, false), + Some("對話" | "chat" | "conversation") => (false, true), + Some(w) => return Some(Err(format!("「{w}」看不懂:後面可以加「檔案」(只退檔案)或「對話」(只退對話),不加就兩個都退"))), + }; + Some(Ok(Rewind::To { n, files, chat })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_words_after_rewind() { + assert_eq!(command("/rewind"), Some(Ok(Rewind::List))); + assert_eq!(command(" /rewind 2 "), Some(Ok(Rewind::To { n: 2, files: true, chat: true }))); + assert_eq!(command("/rewind 1 檔案"), Some(Ok(Rewind::To { n: 1, files: true, chat: false }))); + assert_eq!(command("/rewind 3 對話"), Some(Ok(Rewind::To { n: 3, files: false, chat: true }))); + assert!(matches!(command("/rewind x"), Some(Err(_))) && matches!(command("/rewind 0"), Some(Err(_))) && matches!(command("/rewind 1 全部"), Some(Err(_)))); + assert_eq!(command("/rewinder"), None); + assert_eq!(command("請 /rewind"), None); + } + + /// Three files changed over two turns: going back to the first puts all three back (one that + /// didn't exist goes); going back to the second only what that turn changed. + #[test] + fn rewinding_puts_the_files_back() { + let bot = 900_000 + std::process::id() as u64; + let w = std::env::temp_dir().join(format!("anybot-rewind-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&w); + std::fs::create_dir_all(&w).unwrap(); + let _ = std::fs::remove_file(log_of(bot)); + let t = Target { name: "這台".into(), place: Place::Local { workdir: w.clone() } }; + std::fs::write(w.join("a.txt"), "a0").unwrap(); + std::fs::write(w.join("b.txt"), "b0").unwrap(); + let edit = |turn: i64, f: &str, text: &str| { + before_edit(bot, turn, &t, &serde_json::json!({"path": f, "new_text": text}).to_string()); + std::fs::write(w.join(f), text).unwrap(); + }; + edit(100, "a.txt", "a1"); + edit(100, "a.txt", "a2"); // (the same turn: kept once, as it was before the turn) + edit(100, "new.txt", "n1"); + edit(200, "b.txt", "b1"); + edit(200, "a.txt", "a3"); + assert_eq!(entries(bot).len(), 4); + assert_eq!(files_since(&entries(bot), 100).len(), 3); + assert_eq!(files_since(&entries(bot), 200).len(), 2); + // Back to the second turn: b and a as they were before it. + let lines = restore(bot, 200); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a2"); + assert_eq!(std::fs::read_to_string(w.join("b.txt")).unwrap(), "b0"); + assert_eq!(std::fs::read_to_string(w.join("new.txt")).unwrap(), "n1"); + // Then to the first: everything as it was, the new file gone. + let lines = restore(bot, 100); + assert!(lines.iter().any(|l| l.contains("new.txt") && l.contains("刪掉了")), "{lines:?}"); + assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a0"); + assert!(!w.join("new.txt").exists()); + assert!(entries(bot).is_empty(), "used up"); + // Too big to keep: said, not pretended. + std::fs::write(w.join("big.bin"), vec![b'x'; MAX_FILE_BYTES + 1]).unwrap(); + edit(300, "big.bin", "small"); + assert!(restore(bot, 300)[0].contains("太大")); + let _ = std::fs::remove_file(log_of(bot)); + let _ = std::fs::remove_dir_all(&w); + } +} diff --git a/src/main.rs b/src/main.rs index 3e03afc..3f51aeb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ mod botbrowser; mod browser; mod cloudbox; mod channels; +mod checkpoint; mod computer; mod desktop; mod diagram; @@ -344,6 +345,8 @@ fn main() -> eframe::Result<()> { logfile::init(); // 完整結果 older than a week go. outputs::prune(); + // 檢查點 kept content no change has used for a week. + checkpoint::prune(); // `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/tools.rs b/src/tools.rs index 749b9c1..45ef254 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -132,7 +132,7 @@ pub fn unwrapped_args(args: &str, props: Option<&Value>) -> Option { inner.is_object().then(|| inner.to_string()) } -fn arg_str(v: &Value, k: &str) -> String { +pub(crate) fn arg_str(v: &Value, k: &str) -> String { v.get(k).and_then(Value::as_str).unwrap_or("").to_string() } @@ -1445,7 +1445,7 @@ fn timeout_of(v: &Value) -> u64 { // Here the bot's own computer is a sealed folder, this Mac is the person's computer, and other // computers are reached over SSH. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub enum Place { /// The bot's own computer when Docker isn't there: everything outside `root` in the home /// folder is invisible. @@ -1742,11 +1742,7 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: let (p, path, box_guard) = match place { Place::Box { dir } if name != "shell" => match box_path(std::path::Path::new(dir), &p) { Ok(s) => { - let g = format!( - "base=$(realpath -m -- {base}) && real=$(realpath -m -- {target}) && case \"$real\" in \"$base\"|\"$base\"/*) ;; *) echo '連結指到了你的專屬資料夾以外的地方' >&2; exit 1;; esac; ", - base = sh_quote(dir), - target = sh_quote(&s), - ); + let g = box_guard(dir, &s); (s.clone(), s, g) } Err(e) => return (e, false), @@ -1806,6 +1802,90 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: } } +/// The check in front of a Box file command: the real path (links followed) stays inside the +/// bot's own folder. +fn box_guard(dir: &str, path: &str) -> String { + format!( + "base=$(realpath -m -- {base}) && real=$(realpath -m -- {target}) && case \"$real\" in \"$base\"|\"$base\"/*) ;; *) echo '連結指到了你的專屬資料夾以外的地方' >&2; exit 1;; esac; ", + base = sh_quote(dir), + target = sh_quote(path), + ) +} + +/// 檢查點 (checkpoint.rs): where the file `path` that edit_file names really is on this target — +/// a path here, or one on the box or an SSH computer (None: on another AnyBot, whose files it +/// keeps itself). +pub fn file_spot(target: &Target, path: &str) -> Option> { + Some(match &target.place { + Place::Local { workdir } => Ok((Place::Local { workdir: "/".into() }, resolve(workdir, path).display().to_string())), + Place::Sealed { root } => Ok((Place::Local { workdir: "/".into() }, resolve(root, path).display().to_string())), + Place::Box { dir } => box_path(Path::new(dir), path).map(|p| (target.place.clone(), p)), + Place::Ssh { .. } => Ok((target.place.clone(), path.to_string())), + Place::Device { .. } => return None, + }) +} + +/// What a file is now (None: it isn't there), at a spot from file_spot. +pub fn file_now(place: &Place, path: &str) -> Result>, String> { + match place { + Place::Local { workdir } => { + let p = resolve(workdir, path); + match std::fs::read(&p) { + Ok(b) => Ok(Some(b)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("讀不到 {}:{e}", p.display())), + } + } + Place::Box { dir } | Place::Ssh { dir, .. } => { + if matches!(place, Place::Box { .. }) { + crate::cloudbox::ensure_running()?; + } + let guard = if matches!(place, Place::Box { .. }) { box_guard(dir, path) } else { String::new() }; + let q = sh_quote(path); + let out = remote_capture(place, &format!("{guard}if [ -e {q} ]; then printf Y; cat {q}; else printf N; fi"), None)?; + match out.strip_prefix('Y') { + Some(rest) => Ok(Some(rest.as_bytes().to_vec())), + None if out.starts_with('N') => Ok(None), + None => Err(format!("看不懂 {path} 的狀態")), + } + } + Place::Sealed { .. } | Place::Device { .. } => Err("這台不保留檢查點".into()), + } +} + +/// Put a file back as it was (None: it wasn't there, so it goes), at a spot from file_spot. +pub fn file_put(place: &Place, path: &str, content: Option<&[u8]>) -> Result<(), String> { + match place { + Place::Local { workdir } => { + let p = resolve(workdir, path); + match content { + Some(b) => { + if let Some(d) = p.parent() { + std::fs::create_dir_all(d).map_err(|e| format!("無法建立資料夾:{e}"))?; + } + std::fs::write(&p, b).map_err(|e| format!("寫不進 {}:{e}", p.display())) + } + None => match std::fs::remove_file(&p) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("刪不掉 {}:{e}", p.display())), + _ => Ok(()), + }, + } + } + Place::Box { dir } | Place::Ssh { dir, .. } => { + if matches!(place, Place::Box { .. }) { + crate::cloudbox::ensure_running()?; + } + let guard = if matches!(place, Place::Box { .. }) { box_guard(dir, path) } else { String::new() }; + let q = sh_quote(path); + match content { + Some(b) => remote_capture(place, &format!("{guard}mkdir -p \"$(dirname {q})\" && cat > {q}"), Some(b)).map(|_| ()), + None => remote_capture(place, &format!("{guard}rm -f -- {q}"), None).map(|_| ()), + } + } + Place::Sealed { .. } | Place::Device { .. } => Err("這台不保留檢查點".into()), + } +} + /// Keep a Box file path inside the bot's own folder: relative paths join the bot's dir, and /// a normalised result that lands outside it (`../`, absolute paths to other bots' folders) /// is refused. All bots share one container and one user, so the folder is the only wall. From 9bb9e698a6990240d2c849db046e215902e7f943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:43:52 +0800 Subject: [PATCH 4/4] =?UTF-8?q?feat:=20=E7=9B=A3=E7=9C=8B=EF=BC=9Ashell=20?= =?UTF-8?q?=E5=8A=A0=20monitor=EF=BC=8C=E6=8C=87=E4=BB=A4=E6=AF=8F?= =?UTF-8?q?=E5=8D=B0=E5=87=BA=E6=96=B0=E7=9A=84=E4=B8=80=E8=A1=8C=E5=B0=B1?= =?UTF-8?q?=E5=8F=AB=E9=86=92=20Bot=20=E4=B8=80=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 指令馬上放背景;一秒內印出的併成一次,最多列 20 行,標明「這是指令的輸出,不是使用者說的話」;Bot 閒著就開一輪,在做事就等這輪做完(App::wake)。 - 10 秒超過 200 行、或叫滿 60 次自動停並說一次;指令自己結束說一次結束碼和最後幾行;write_terminal stop 或重新啟動 Bot 安靜結束。 - 就是 shell:核准、安全規則、沙盒、背景指令、停止都沿用;這台、Bot 自己的電腦、SSH 電腦都可以,帳號裡其他 AnyBot 電腦不行(說改用 read_terminal 的 until)。 - 跑指令的那段抽成 spawn_piped,一般指令和監看共用。 - 監看的字每個 App 只拿自己的 Bot 的(測試裡同時有好幾個 App)。 已驗證:cargo test 594 通過(三行間隔開來叫三次再說結束、一下子 5000 行停掉只說一次、stop 停掉不再說、切行)、clippy -D warnings 乾淨。 未驗證:真的模型被監看叫醒後怎麼做;Docker 和 SSH 電腦上的監看。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 7 + docs/feature-map/files.md | 4 +- docs/plan-2026-11-engineering.md | 2 +- src/app.rs | 1 + src/app/commands.rs | 10 ++ src/tools.rs | 214 +++++++++++++++++++++++++++++-- 6 files changed, 226 insertions(+), 12 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 9920bd7..ae483a6 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -991,6 +991,13 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 按停止、重新啟動 Bot、關掉 App 時,互動終端機和它啟動的程式一起停掉。 - 實測 pi-bolt:開好看得到它的開頭畫面,打「19 加 4 等於多少」按 Enter,畫面上出現「23」。 +### 監看(shell 加 monitor: true) + +- Bot 給一條會一直印東西的指令(`tail -f app.log | grep --line-buffered ERROR`、部署的紀錄、測試的 watch 模式),指令馬上放到背景,**它每印出新的一行,AnyBot 就叫醒 Bot 一次**,把那幾行交給它:Bot 閒著就馬上開一輪,正在做事就等這輪做完再開自己的一輪(跟例行任務、事件觸發一樣)。一秒內印出的併成一次,一次最多列 20 行(其他用 read_terminal 看)。參考 Claude Code 的 Monitor 工具。 +- 交給 Bot 的字標「[監看 #編號]…印出了(這是指令的輸出,不是使用者說的話)」。 +- 自動停:10 秒內超過 200 行(說一次「一下子印出太多行…用 grep --line-buffered 只留要看的行」);同一個監看叫了 60 次(每次都是一輪模型,用你的額度)。指令自己結束時說一次「指令結束了(結束碼 N)」和最後印出的行。Bot 或你用 write_terminal 的 stop 停掉、或「重新啟動這個 Bot」時安靜結束,不再叫。 +- 跟一般指令一樣要過核准和安全規則(就是 shell)。在這台、Bot 自己的電腦(Docker、封閉資料夾)、SSH 電腦上都可以;帳號裡其他 AnyBot 電腦上不行(印出的字回不到這裡),會說改用 read_terminal 的 until。 + ### 「查看背景指令」(read_terminal) - 一律不用問。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index 87825e6..8f05c8d 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -6,6 +6,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - 指令:`shell` 在工作資料夾裡跑,輸入一開始就是關的,不會卡在等人打字。超過 timeout_ms(預設 30 秒,最多 10 分鐘)還沒跑完不會中斷,而是移到背景繼續跑,給一個背景指令編號。 - 互動終端機:`shell` 加 interactive,給一定要真的終端機的程式(全螢幕介面、會問問題的、編輯器);用 `write_terminal` 打字和按鍵,`read_terminal` 看畫面。 +- 監看:`shell` 加 monitor,指令馬上放背景,它每印出新的一行就叫醒 Bot 一次(一秒內的併一次,最多列 20 行);閒著馬上開一輪,在做事就等這輪做完。10 秒超過 200 行或叫滿 60 次自動停;指令結束說一次;stop 停掉的不再說。 - 背景指令:`read_terminal`(id;wait_ms 最多 120 秒,等到有新東西又安靜下來;until 等某段字出現);`write_terminal` 加 stop 停掉它和它啟動的所有程式。 - 檔案:`list_dir` 看資料夾;`read_file` 讀(每行有行號,用 offset、limit 分段,檔案最大 8 MB);`search` 找字(結果是「路徑:行號:內容」,有 ripgrep 時可以用正規表示式);`edit_file` 改(old_text 必須剛好出現一次;old_text 留空就是新建或整個覆寫)。 - 工作資料夾:這台電腦是 Bot 設定的「起始資料夾」(沒填就是家目錄);Bot 自己的電腦是它自己的資料夾;SSH 電腦是設定的資料夾或對方的家目錄。 @@ -24,7 +25,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 ## 怎麼操作 - Bot:先用 `list_dir`、`search`、`read_file` 看清楚再動手,改檔案用 `edit_file`。跑很久的指令讓它進背景,再用 `read_terminal` 的 wait_ms 等,不要一直重查;指令列的 AI 工具用它們的非互動模式(例如 `claude -p "…"`)。一定要看終端機畫面時才用 interactive,用完關掉。每個工具都有 `computer`。交結果用 `send_file`,不要只說檔案在哪;要使用者馬上看到用 `open_for_person`;要公開網址用 `publish_site`(path,name 只用英文字母、數字和 -)。除了 `send_file`,這些都屬於「檔案與指令」能力。結果太長被截(只留開頭和結尾,中間寫「完整內容用 read_result 讀:id=…」)或較早的結果被收起時,用 `read_result`(id、from、chars,一次最多兩萬字)讀完整的,不要為了看完整的再做一次那一步(每個 Bot 都有,完整結果留 7 天)。 -- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`、`cargo test rewind`。請 Bot 改兩個檔案,再打「/rewind」選那一句,兩個檔案要回到原本的內容、那句話回到輸入框。 +- 驗證:請 Bot 在它自己的電腦寫一個 report.md 傳給你,聊天要出現檔案卡片,點開看得到內容;請它讀這台電腦工作資料夾外的檔案,要跳出「讀取工作資料夾以外的地方:…」;請它跑 `sleep 40; echo done`,要說已移到背景,再用 `read_terminal` 等到 done。自動測試:`cargo test tools::`、`cargo test pty::`、`cargo test agent::`、`cargo test preview::`、`cargo test app::files_ui::`、`cargo test rewind`、`cargo test a_watched_command`。請 Bot 改兩個檔案,再打「/rewind」選那一句,兩個檔案要回到原本的內容、那句話回到輸入框。 ## 陷阱 @@ -37,5 +38,6 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - `open_for_person` 不打開程式或指令檔(打開就會執行),改用 `send_file`;AnyBot 在伺服器上時,網址會在使用者正在用的那台電腦打開(不知道是哪台就打不開),檔案打不開,也改用 `send_file`。 - SSH 電腦上的檔案不能直接 `send_file`、`open_for_person` 或 `publish_site`;帳號裡其他電腦的檔案可以 `send_file`(最多 20 MB),但不能打開或發佈。先複製到 Bot 自己的電腦。 - `publish_site`:任何知道網址的人都看得到。每個網站名字第一次會問(工作資料夾外的每次都問);最多 500 個檔案、25 MB;點開頭的檔案、node_modules、機密檔案、指到資料夾外的連結會略過;一定要有 index.html。 +- 監看每叫一次就是一輪模型、用使用者的額度:先用 grep --line-buffered 篩到只剩要看的行。帳號裡其他 AnyBot 電腦上不能監看。 - 檢查點只記 `edit_file` 改的:用 `shell` 改的(cat >、sed -i、git、npm…)不在裡面,帳號裡其他 AnyBot 電腦上的檔案也不在;超過 2 MB 的檔案不存,退回時會說沒辦法還原。要能退回,改檔案就用 `edit_file`。 - 按停止會停掉正在跑的那一步,和這個 Bot 的互動終端機(連同它們啟動的程式);一般的背景指令(例如故意開著的伺服器)會繼續跑。「重新啟動這個 Bot」停掉這個 Bot 的全部背景指令,關掉 App 全部停掉。整個 AnyBot 同時最多 24 個背景指令在跑,滿了新的不會留在背景(會先停掉),用不到的用 stop 關掉。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 15b47ff..f105795 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -105,7 +105,7 @@ - 做法:`SessionStart`、`UserPromptSubmit`、`PreToolUse`(回 allow/ask/deny,可以改參數)、`PostToolUse`(可以改 Bot 讀到的結果)、`Stop`(可以叫它繼續)、`Notification`。設定檔放在資料夾的 `hooks/`,或管理員的 policy 位置(MDM 可推);hook 是指令或 HTTP。hook 自己出錯時照常做,紀錄寫清楚。 - 做完:一個 PreToolUse hook 擋 `rm`、一個改參數、一個 Stop hook 讓它多做一輪,都有測試。 -### M3. monitor 工具 ⬜ +### M3. monitor 工具 ✅(做成 shell 的 monitor 參數:核准、安全規則、背景指令、停止都沿用;Bot 在做事時等這輪做完再叫,不插進正在做的那一輪) - 做法:Bot 給一條指令,每輸出一行就變成一則通知/訊息;自動 line-buffered;一次失敗不停;太多行自動停並說明。 - 做完:`tail -f` 一個檔案,寫三行收到三則;一秒寫一千行會自動停。 diff --git a/src/app.rs b/src/app.rs index d51b4c2..4a01efa 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5980,6 +5980,7 @@ impl App { // 會議錄音 turned into text here go to their bot (a brain on a server has no window). self.meetings_poll(ctx); self.tick_routines(ctx); + self.monitor_tick(ctx); self.tick_asks(ctx); self.tick_branches(ctx); self.watchdog(); diff --git a/src/app/commands.rs b/src/app/commands.rs index f5d7ac3..4330a19 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -96,6 +96,16 @@ impl App { } } + /// 監看 (shell with monitor): what watched commands printed wakes their bots — a turn now, + /// or one of its own after the one it is in. + pub(super) fn monitor_tick(&mut self, ctx: &egui::Context) { + let c = ctx.clone(); + crate::tools::set_monitor_repaint(Arc::new(move || c.request_repaint())); + for (bot_id, text) in crate::tools::monitor_take(|b| self.state.bot(b).is_some()) { + self.wake(ctx, bot_id, Message { wake: true, ..Message::user(&text) }); + } + } + /// The points 「/rewind」 can go back to: the person's messages in this conversation, newest /// first (index in the chat, its time, its words). fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> { diff --git a/src/tools.rs b/src/tools.rs index 45ef254..9974057 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -60,7 +60,8 @@ pub fn specs() -> Vec { "parameters": {"type": "object", "properties": { "command": {"type": "string"}, "timeout_ms": {"type": "integer", "description": "How long to wait before moving it to the background (default 30000). Interactive: how long to wait for its first screen (at most 15000)."}, - "interactive": {"type": "boolean", "description": "Run in a real terminal you can see and type into (default false)."}}, "required": ["command"]}}), + "interactive": {"type": "boolean", "description": "Run in a real terminal you can see and type into (default false)."}, + "monitor": {"type": "boolean", "description": "Watch it (監看): it goes to the background at once and every new line it prints wakes you with those lines (a second's lines come together) — e.g. `tail -f app.log | grep --line-buffered ERROR`, a deploy's log, a test watcher. Filter it to the lines that matter: too many lines (over 200 in 10 s) stop it. Stop it with write_terminal stop. Not on another AnyBot of the account."}}, "required": ["command"]}}), json!({"name": "read_terminal", "description": "Look at a background command: its latest output, or a 互動終端機's screen. wait_ms waits (up to 120000) until it shows something new and goes quiet, or until the text in `until` appears, or it ends — instead of checking again and again.", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}, "wait_ms": {"type": "integer"}, "until": {"type": "string", "description": "Return as soon as this text is on the screen / in the output."}}, "required": ["id"]}}), json!({"name": "write_terminal", "description": "Type into a 互動終端機 (a command started with interactive=true): text (each new line presses Enter) and/or keys, then see its screen once it settles (wait_ms, default 4000, up to 120000). close=true sends Ctrl-D. A plain command's input is closed: it can't be typed into.", @@ -1682,6 +1683,7 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: }; match &target.place { Place::Local { workdir } => run(name, args, workdir, cancel, ids), + Place::Device { .. } if name == "shell" && monitor_of(&v) => ("監看不能用在帳號裡的其他 AnyBot 電腦上(它印出的字回不到這裡叫你):改用 read_terminal 的 until 等某段字出現。".into(), false), Place::Device { host, dir } => { // The device runs the tool in the bot's work folder (its own home when unset), and // must answer before the relay gives up at 35 s: long commands move to the @@ -1720,7 +1722,7 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: } if name == "shell" { let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/Users")); - return done(shell(&arg_str(&v, "command"), root, timeout_of(&v), interactive_of(&v), cancel, ids, Some(&home))); + return done(shell(&arg_str(&v, "command"), root, timeout_of(&v), interactive_of(&v), monitor_of(&v), cancel, ids, Some(&home))); } run(name, args, root, cancel, ids) } @@ -1797,6 +1799,9 @@ pub fn run_on(name: &str, args: &str, target: &Target, cancel: &AtomicBool, ids: let tty = name == "shell" && interactive_of(&v); let wrapper = wrapper_for(place, &remote, name == "shell", tty, &job).unwrap_or_default(); let kill = matches!(place, Place::Box { .. }).then(|| crate::cloudbox::exec_kill_argv(&job)); + if name == "shell" && monitor_of(&v) { + return done(start_monitor(build_wrapper_command(&wrapper, &ids.conversation, &ids.request), &remote, ids, kill)); + } done(shell_wrapped(&wrapper, &remote, timeout_of(&v), tty, cancel, ids, kill)) } } @@ -1932,7 +1937,7 @@ pub fn run(name: &str, args: &str, workdir: &Path, cancel: &AtomicBool, ids: &Ru v.get("limit").and_then(Value::as_u64).map(|l| l as usize).unwrap_or(READ_DEFAULT_LINES), ), "edit_file" => edit_file(&resolve(workdir, &arg_str(&v, "path")), &arg_str(&v, "old_text"), &arg_str(&v, "new_text")), - "shell" => shell(&arg_str(&v, "command"), workdir, timeout_of(&v), interactive_of(&v), cancel, ids, None), + "shell" => shell(&arg_str(&v, "command"), workdir, timeout_of(&v), interactive_of(&v), monitor_of(&v), cancel, ids, None), "read_terminal" => read_terminal(v.get("id").and_then(Value::as_u64).unwrap_or(0), v.get("wait_ms").and_then(Value::as_u64).unwrap_or(0), &arg_str(&v, "until")), "write_terminal" if v.get("stop").and_then(Value::as_bool).unwrap_or(false) => stop_terminal(v.get("id").and_then(Value::as_u64).unwrap_or(0)), "write_terminal" => write_terminal(v.get("id").and_then(Value::as_u64).unwrap_or(0), &arg_str(&v, "input"), &keys_of(&v), v.get("close").and_then(Value::as_bool).unwrap_or(false), v.get("wait_ms").and_then(Value::as_u64).unwrap_or(0)), @@ -2140,9 +2145,12 @@ fn edit_file(p: &Path, old: &str, new: &str) -> Result { } } -fn shell(cmd: &str, workdir: &Path, timeout_ms: u64, interactive: bool, cancel: &AtomicBool, ids: &RunIds, seal: Option<&Path>) -> Result { +#[allow(clippy::too_many_arguments)] +fn shell(cmd: &str, workdir: &Path, timeout_ms: u64, interactive: bool, monitor: bool, cancel: &AtomicBool, ids: &RunIds, seal: Option<&Path>) -> Result { let command = build_command_sealed(cmd, workdir, &protected_dirs(), &readable_dirs(), seal, &ids.conversation, &ids.request); - let r = if interactive { run_terminal(command, cmd, first_look_ms(timeout_ms), cancel, ids, None) } else { run_command(command, cmd, timeout_ms, cancel, ids, None) }; + let r = if monitor { + start_monitor(command, cmd, ids, None) + } else if interactive { run_terminal(command, cmd, first_look_ms(timeout_ms), cancel, ids, None) } else { run_command(command, cmd, timeout_ms, cancel, ids, None) }; // (The bot's own sealed computer keeps every command in the sandbox: no hints about outside.) let note = |out: &str| sandbox_note(cmd, out).filter(|_| seal.is_none()).map(|n| format!("{out}\n{n}")).unwrap_or_else(|| out.to_string()); match r { @@ -2167,6 +2175,10 @@ fn first_look_ms(timeout_ms: u64) -> u64 { } /// Whether a shell call asks for a 互動終端機. +fn monitor_of(v: &Value) -> bool { + v.get("monitor").and_then(Value::as_bool).unwrap_or(false) +} + fn interactive_of(v: &Value) -> bool { v.get("interactive").and_then(Value::as_bool).unwrap_or(false) } @@ -2179,11 +2191,12 @@ fn keys_of(v: &Value) -> Vec { } } -fn run_command(mut command: Command, cmd: &str, timeout_ms: u64, cancel: &AtomicBool, ids: &RunIds, kill: Option>) -> Result { +/// Start a plain command: its input closed at once (as if from /dev/null: a program that reads its +/// input to the end — `pi-bolt -p`, `cat`, a script piped to python — goes on instead of waiting +/// forever for words that never come; one that needs typing runs as a 互動終端機), its output and +/// errors gathered in one place as they come (the newest 4 MB). +fn spawn_piped(mut command: Command) -> Result<(std::process::Child, u32, Arc>), String> { let mut child = command.spawn().map_err(|e| format!("無法執行:{e}"))?; - // Its input is closed at once (as if from /dev/null): a program that reads its input to the - // end — `pi-bolt -p`, `cat`, a script piped to python — goes on instead of waiting forever - // for words that never come. One that needs typing runs as a 互動終端機 (interactive). drop(child.stdin.take()); let root = child.id(); let output = Arc::new(Mutex::new(String::new())); @@ -2204,6 +2217,11 @@ fn run_command(mut command: Command, cmd: &str, timeout_ms: u64, cancel: &Atomic } }); } + Ok((child, root, output)) +} + +fn run_command(command: Command, cmd: &str, timeout_ms: u64, cancel: &AtomicBool, ids: &RunIds, kill: Option>) -> Result { + let (mut child, root, output) = spawn_piped(command)?; let start = Instant::now(); loop { if let Ok(Some(status)) = child.try_wait() { @@ -2405,12 +2423,146 @@ fn stop_terminal(id: u64) -> Result { if exit.lock().unwrap().is_some() { return Ok(format!("背景指令 #{id} 本來就結束了。")); } + monitor_quiet(id); kill_tree(root); child.lock().unwrap().kill(); kill_far(&far); Ok(format!("已停止背景指令 #{id}(連同它啟動的程式)。")) } +// ---------- 監看 (shell with monitor, M3) ---------- +// A command watched: it goes to the background at once, and every new line it prints wakes its +// bot with those lines (the lines of one second together, at most MONITOR_BATCH_LINES shown) — +// a turn now when it is idle, a turn of its own after the one it is in (App::wake). Like Claude +// Code's Monitor tool. Too many lines (MONITOR_MAX_LINES in MONITOR_WINDOW) or wakes +// (MONITOR_MAX_WAKES) stop it, said once; its end is said once; a stop (write_terminal, the +// bot restarted) ends it quietly. + +/// Lines shown in one wake (the rest: read_terminal). +pub const MONITOR_BATCH_LINES: usize = 20; +/// More lines than this in MONITOR_WINDOW stop it. +pub const MONITOR_MAX_LINES: usize = 200; +const MONITOR_WINDOW: Duration = Duration::from_secs(10); +/// One watch wakes its bot at most this many times (each wake is a turn of the model). +pub const MONITOR_MAX_WAKES: usize = 60; +/// Lines that come within this are one wake. +const MONITOR_GATHER: Duration = Duration::from_millis(1000); + +fn monitor_out() -> &'static Mutex> { + static O: OnceLock>> = OnceLock::new(); + O.get_or_init(|| Mutex::new(vec![])) +} + +fn monitor_quiet_set() -> &'static Mutex> { + static Q: OnceLock>> = OnceLock::new(); + Q.get_or_init(|| Mutex::new(Default::default())) +} + +/// A watched command stopped on purpose: its end isn't news. +fn monitor_quiet(id: u64) { + monitor_quiet_set().lock().unwrap_or_else(|e| e.into_inner()).insert(id); +} + +static MONITOR_REPAINT: OnceLock> = OnceLock::new(); + +/// How the app is told there is something to wake a bot with (set once at start). +pub fn set_monitor_repaint(f: Arc) { + let _ = MONITOR_REPAINT.set(f); +} + +/// What watched commands said since last time to the bots `mine` takes: (bot, the words to wake +/// it with). The others' stay (a second AnyBot in one process — tests — has bots of its own). +pub fn monitor_take(mine: impl Fn(u64) -> bool) -> Vec<(u64, String)> { + let mut all = monitor_out().lock().unwrap_or_else(|e| e.into_inner()); + let (taken, left): (Vec<_>, Vec<_>) = std::mem::take(&mut *all).into_iter().partition(|(b, _)| mine(*b)); + *all = left; + taken +} + +fn monitor_say(bot: u64, text: String) { + monitor_out().lock().unwrap_or_else(|e| e.into_inner()).push((bot, text)); + if let Some(r) = MONITOR_REPAINT.get() { + r(); + } +} + +/// The new complete lines in `buf` from byte `from` (all of it once the program ended), and where +/// the next read starts. Empty lines are left out. +fn new_lines(buf: &str, from: usize, ended: bool) -> (Vec, usize) { + let rest = buf.get(from..).unwrap_or(""); + let upto = if ended { rest.len() } else { rest.rfind('\n').map(|i| i + 1).unwrap_or(0) }; + let lines = rest[..upto].lines().map(|l| l.trim_end_matches('\r').to_string()).filter(|l| !l.trim().is_empty()).collect(); + (lines, from + upto) +} + +/// Start watching `cmd` for the bot whose conversation `ids` names. +fn start_monitor(command: Command, cmd: &str, ids: &RunIds, kill: Option>) -> Result { + let bot: u64 = ids.conversation.parse().map_err(|_| "監看只能在 Bot 的對話裡用".to_string())?; + if !room_for_terminal() { + return Err(NO_ROOM.into()); + } + let (child, root, output) = spawn_piped(command)?; + let child = Arc::new(Mutex::new(Proc::Std(child))); + let (exit, ended) = (Arc::new(Mutex::new(None)), Arc::new(Mutex::new(None))); + watch_exit(&child, &exit, &ended); + let id = keep_terminal(Terminal { command: cmd.to_string(), io: Io::Pipe(output.clone()), child, exit: exit.clone(), ended, kill, root, conversation: ids.conversation.clone() }); + let shown: String = cmd.chars().take(60).collect(); + std::thread::spawn(move || watch_lines(bot, id, &shown, &output, &exit)); + Ok(format!( + "已開始監看(背景指令 #{id}):它每印出新的一行,AnyBot 就叫你一次(一秒內的一起來,一次最多列 {MONITOR_BATCH_LINES} 行),不用再用 read_terminal 等它。10 秒內超過 {MONITOR_MAX_LINES} 行、或叫了你 {MONITOR_MAX_WAKES} 次會自動停。不需要了就 write_terminal(id={id}, stop=true)。" + )) +} + +fn watch_lines(bot: u64, id: u64, shown: &str, output: &Mutex, exit: &Mutex>) { + let mut from = 0; + let mut recent: std::collections::VecDeque<(Instant, usize)> = Default::default(); + let mut wakes = 0; + let head = |lines: &[String]| { + let mut t: String = lines.iter().take(MONITOR_BATCH_LINES).map(|l| format!("\n{}", l.chars().take(500).collect::())).collect(); + if lines.len() > MONITOR_BATCH_LINES { + t.push_str(&format!("\n(還有 {} 行沒列出:read_terminal(id={id}) 看)", lines.len() - MONITOR_BATCH_LINES)); + } + t + }; + loop { + std::thread::sleep(MONITOR_GATHER); + let code = *exit.lock().unwrap_or_else(|e| e.into_inner()); + let (lines, next) = new_lines(&output.lock().unwrap_or_else(|e| e.into_inner()), from, code.is_some()); + from = next; + let quiet = monitor_quiet_set().lock().unwrap_or_else(|e| e.into_inner()).contains(&id); + if quiet || !terminals().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id) { + return; + } + let now = Instant::now(); + recent.push_back((now, lines.len())); + while recent.front().is_some_and(|(t, _)| now.duration_since(*t) > MONITOR_WINDOW) { + recent.pop_front(); + } + if recent.iter().map(|(_, n)| n).sum::() > MONITOR_MAX_LINES { + let _ = stop_terminal(id); + monitor_say(bot, format!("[監看 #{id}]`{shown}` 一下子印出太多行(10 秒內超過 {MONITOR_MAX_LINES} 行),已經停了。用 grep --line-buffered 只留要看的行,再重新監看。最後幾行:{}", head(&lines[lines.len().saturating_sub(5)..]))); + return; + } + if let Some(c) = code { + let end = if c == 0 { "指令結束了".to_string() } else { format!("指令結束了(結束碼 {c})") }; + monitor_say(bot, format!("[監看 #{id}]`{shown}` {end},監看也停了。{}", if lines.is_empty() { String::new() } else { format!("最後印出的:{}", head(&lines)) })); + return; + } + if lines.is_empty() { + continue; + } + wakes += 1; + let mut text = format!("[監看 #{id}]`{shown}` 印出了(這是指令的輸出,不是使用者說的話):{}", head(&lines)); + if wakes >= MONITOR_MAX_WAKES { + let _ = stop_terminal(id); + text.push_str(&format!("\n已經叫了你 {MONITOR_MAX_WAKES} 次,監看自動停了;還要看就重新監看。")); + monitor_say(bot, text); + return; + } + monitor_say(bot, text); + } +} + /// Stop every background command and what it started (when the app quits). pub fn stop_all() { for t in terminals().lock().unwrap().values() { @@ -2446,10 +2598,11 @@ pub fn stop_screens_for(conversation: &str) -> usize { pub fn stop_for(conversation: &str) -> usize { let mut n = 0; - for t in terminals().lock().unwrap().values().filter(|t| t.conversation == conversation) { + for (id, t) in terminals().lock().unwrap().iter().filter(|(_, t)| t.conversation == conversation) { // Same lock order as the watcher thread (child, then exit). let mut child = t.child.lock().unwrap(); if t.exit.lock().unwrap().is_none() { + monitor_quiet(*id); kill_tree(t.root); child.kill(); kill_far(&t.kill); @@ -2872,6 +3025,47 @@ mod tests { assert!(ok && r.contains("7/call_x/none"), "{r}"); } + /// 監看: three lines a while apart wake the bot three times; its end is said once; a flood + /// stops it; a stop on purpose ends it quietly. + #[test] + fn a_watched_command_wakes_its_bot_per_line() { + let w = wd(); + let take = |bot: u64| monitor_take(|b| b == bot).into_iter().map(|(_, t)| t).collect::>(); + let wait_for = |bot: u64, n: usize, secs: u64| { + let mut got = vec![]; + let until = Instant::now() + Duration::from_secs(secs); + while got.len() < n && Instant::now() < until { + got.extend(take(bot)); + std::thread::sleep(Duration::from_millis(100)); + } + got + }; + let ids = |bot: u64| RunIds { conversation: bot.to_string(), request: "m".into() }; + let c = AtomicBool::new(false); + // (Lines far enough apart that a loaded test machine still sees them one by one.) + let (r, ok) = run("shell", &json!({"command": "for i in 1 2 3; do echo line$i; sleep 3; done", "monitor": true}).to_string(), &w, &c, &ids(81_001)); + assert!(ok && r.contains("已開始監看"), "{r}"); + let got = wait_for(81_001, 4, 25); + assert_eq!(got.len(), 4, "three lines, then its end: {got:?}"); + assert!(got[0].contains("line1") && got[1].contains("line2") && got[2].contains("line3") && got[3].contains("指令結束了"), "{got:?}"); + assert!(got[0].contains("不是使用者說的話") && !got[0].contains("line2")); + // A flood: stopped, said once. + let (r, ok) = run("shell", &json!({"command": "yes hello | head -n 5000; sleep 30", "monitor": true}).to_string(), &w, &c, &ids(81_002)); + assert!(ok, "{r}"); + let got = wait_for(81_002, 1, 10); + assert!(got.len() == 1 && got[0].contains("太多行"), "{got:?}"); + std::thread::sleep(Duration::from_millis(1500)); + assert!(take(81_002).is_empty(), "nothing after it stopped"); + // Stopped on purpose: no word about its end. + let (r, _) = run("shell", &json!({"command": "sleep 30", "monitor": true}).to_string(), &w, &c, &ids(81_003)); + let id: u64 = r.split('#').nth(1).and_then(|s| s.split(')').next()).and_then(|s| s.parse().ok()).expect(&r); + run("write_terminal", &json!({"id": id, "stop": true}).to_string(), &w, &c, &ids(81_003)); + std::thread::sleep(Duration::from_millis(2500)); + assert!(take(81_003).is_empty()); + assert_eq!(new_lines("a\nb\npart", 0, false), (vec!["a".to_string(), "b".to_string()], 4)); + assert_eq!(new_lines("a\nb\npart", 4, true), (vec!["part".to_string()], 8)); + } + #[test] fn sandbox_blocks_protected_folders() { if sandbox_exec().is_none() {