合併: 工程基礎全部完成(太長的結果留完整的、/doctor、anybot --ask 給腳本用)

This commit is contained in:
王性驊 2026-11-17 11:58:12 +08:00
commit 5ff81f7b51
16 changed files with 608 additions and 34 deletions

View File

@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
### 「/」清單只放指令
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。
- 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。
### 上線前補上的防護(安全和資源)
@ -1500,6 +1500,16 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 現在兩端(這台的 tunnel.rs、帳號伺服器的 relay)都以「有沒有收到資料」判斷連線還在;等回答時資料還在進來就繼續等(最多 10 分鐘);長連線一接回,螢幕馬上重新向大腦要資料(以前要等自己的重試時間,最多 20 秒)。
- 設定 › 一般 › 帳戶 › 大腦:狀態下面分段寫「這台 ↔ 帳號伺服器」「帳號伺服器 ↔ 大腦(在線上或不在)」「上次同步的大小、秒數、速度」。帳號伺服器那端的修正要 make update-server 才生效。
### 太長的結果留完整的(read_result)
- 指令輸出、連接器的回答太長時,給模型的只留開頭和結尾各 6000 字,中間寫「…(中間省略 N 個字;完整內容用 read_result 讀:id=r…)…」;完整的存在資料夾的 `outputs/`(一份最多 20 MB、留 7 天,同樣的內容同一個 id)。較早的結果為了騰出空間被收起時也一樣寫 id。
- 每個 Bot 都有 `read_result`(id、從第幾個字、一次最多兩萬字),只是看,計畫模式也能用。以前叫 Bot「再做一次這一步」看完整的:會改東西的步驟重做很危險,答案也可能不一樣,長紀錄的中間就這樣不見了。
### 診斷(/doctor)
- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。
- 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。
### 用量(/usage)
- 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。
@ -1544,6 +1554,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- **模型讀到的**:你的「/goal …」後面多一行,說明這是目標、每輪會有另一個模型檢查,所以要用實際的結果證明(指令輸出、測試結果、檔案內容、畫面),需要你做什麼就直接問;「還沒達成」那則後面也提醒它接著做。檢查用的模型讀的是從設定目標那則訊息起的對話(太長就讀最新的約 24000 字;每個工具結果留開頭和結尾,測試的總結通常在最後),並知道已經第幾輪、做了多久,所以條件裡寫「最多 10 輪」也算數。
- **權限不變**:要你核准的步驟照樣停下來等;要放著讓它自己做完,Bot 要開「直接操作」或「自動審核」(Claude Code 也要配 auto mode)。
- **終端機**:`anybot --ask "/goal …"` 會一直做到達成、做不到或暫停才結束(像 `claude -p "/goal …"`),最長 ANYBOT_ASK_SECS 秒(預設 900)。
- **`anybot --ask` 給腳本用**:`--json` 每則訊息一行 JSON(type message/approval/learned/done;done 有 ok、code、steps、secs、timed_out、answer,金鑰遮過);`--bot 名字` 問哪個 Bot;`--data-dir 資料夾`(跟 ANYBOT_DATA_DIR 一樣,在讀任何東西之前就設好);`--approve once` 要核准的自動允許一次(問題卡和「需要處理」照樣略過),不給就自動拒絕。結束碼:0 這一輪順利、1 失敗或時間到、130 Ctrl-C(會先停下 Bot)、2 指令寫錯或資料夾裡還沒有 Bot。核准改走跟按鈕一樣的路:以前 App 操作(刪例行任務這類)的核准在這裡會一直等到時間到。
- 實測(假的 OpenAI 相容模型,獨立的大腦):「兩步」的目標第一輪檢查說還差第二步,AnyBot 自己開第二輪,第二輪後判定達成;永遠沒進展的目標在第 3 輪暫停;要登入的目標判定在等使用者而暫停,回一句「我登入了」後接著做並達成;目標的那幾行沒有出現在任何一次送給模型的內容裡。
- **/always-approve 一律放行**(也可以打 /yolo;像 Claude Code 的 bypassPermissions、Codex 的 --yolo):你打一句就把自己的權限一把全開,不用去設定裡一個個開。
- **打開時做的事**:打開「直接操作」(也就是「在這台電腦上執行」、所有 Bot 的電腦工具),之後所有要等「允許」的卡片都替你按允許,連直接操作還會問的也不問:「一律詢問」規則、付款/傳送/刪除這類點擊、寄信、傳訊息、沙盒外的 AppleScript、打電話、簡訊、在 X 發文、用保險庫的卡片;自動審核也略過(反正都會允許,不用再等一個模型判斷)。打開那一刻你自己的 Bot 正在等的卡片也一起放行。

View File

@ -5,7 +5,7 @@
## 子功能
- 版面:左邊 Bot 清單(側邊欄拖到比 210 px 窄會收成頭像直欄),右邊聊天。點聊天頂部的 Bot 名稱(「查看對話詳細資訊」)打開右側面板,有「動態」「資料庫」兩頁。
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費),打「@」列出其他 Bot。
- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md)),打「@」列出其他 Bot。
- 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。
- 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。
- 停止:工作中、輸入框空著時,送出鈕變成「停止」。

View File

@ -22,7 +22,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`,這些都屬於「檔案與指令」能力。
- 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::`。
## 陷阱

View File

@ -5,6 +5,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「
## 子功能
- 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。
- 診斷(/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 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。

View File

@ -50,11 +50,11 @@
- 做法:safety.md 的「每一步的關卡順序」九步,從 `agent::spawn` 抽成 `gate::decide(…) -> Gate`(輸入:工具、參數、電腦、開關、規則;輸出:直接做/問/拒絕和理由),一張表格式測試涵蓋每一步。`spawn` 只呼叫它。
- 做完:表格測試涵蓋九步和直接操作、一律放行、陌生人訊息;行為不變(舊測試全過)。
### E10. 無頭模式可以寫腳本 ⬜
- 做法:`anybot --ask` 加 `--json`(每個事件一行 JSON)、`--bot 名稱`、`--data-dir`、`--approve once|reject`;結束碼 0 成功、1 失敗、130 被中斷。
### E10. 無頭模式可以寫腳本 ✅
- 做法:`anybot --ask` 加 `--json`(每則訊息一行 JSON,還有 approval、learned、done)、`--bot 名稱`、`--data-dir`、`--approve once|reject`;結束碼 0 成功、1 失敗或時間到、130 Ctrl-C、2 指令寫錯或還沒有 Bot。核准改走 answer(),App 操作的核准卡不再一直等到時間到。
- 做完:`anybot --ask --json …` 的輸出能被 `jq` 讀;測試涵蓋結束碼。
### E11. `/doctor` 診斷 ⬜
### E11. `/doctor` 診斷 ✅
- 做法:聊天打 `/doctor`(或 設定 › 更新):版本、資料夾、這台↔帳號伺服器(延遲、走 Tailscale 中繼還是直連、下載速度)、帳號伺服器↔大腦(在不在線)、模型供應商(金鑰、連得到)、Bot 的電腦、連接器、磁碟、上次當掉。一條一條 ✓/✗ 加原因。
- 做完:每一項都有測試;把「連不到大腦」那天的情況跑一次要說得出是哪一段。
@ -71,7 +71,7 @@
- 做法:「無需詢問直接允許」「一律詢問」多一種寫法:`shell(git *)`、`file(~/Projects/**)`、`connector(gitlab__*)`、`web(domain:example.com)`、`browser(click:付款*)`。先用樣式判斷(拒絕 > 詢問 > 允許;連在一起的指令每一段都要符合才算允許),判斷不了的才交給模型;模型說允許不能蓋過樣式的詢問。
- 做完:表格測試;`git status && rm -rf x` 不會因為 `shell(git *)` 被允許。
### R3. 太長的結果存成檔案 ⬜
### R3. 太長的結果存成檔案 ✅(存在資料夾的 outputs/,用 read_result 讀;Bot 的沙盒讀不到 AnyBot 的資料夾,所以不是普通檔案)
- 做法:指令輸出、連接器結果、網頁內容超過上限時,完整內容存到 Bot 的資料夾 `outputs/`,截短的那份寫「完整內容在 …」;舊結果收起時也一樣(不再叫 Bot「再跑一次」)。
- 做完:一個 50 萬字的輸出,Bot 拿到頭尾和檔案路徑,檔案內容完整。

View File

@ -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: "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: "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\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)\s*$/i.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;

View File

@ -1006,7 +1006,9 @@ const FOLD_HEAD_CHARS: usize = 200;
/// What the model reads in place of an old, long result.
pub fn folded_text(text: &str) -> String {
let head: String = text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(FOLD_HEAD_CHARS).collect();
format!("(這一步較早的結果已收起,只留開頭;需要完整內容就再做一次這一步){head}…")
// 完整結果: kept whole (the same text, the same id, turn after turn), read with read_result.
let id = crate::outputs::keep(text);
format!("(這一步較早的結果已收起,只留開頭;完整內容用 {} 讀:id={id}){head}…", crate::outputs::TOOL)
}
/// The first, free way to make room: old steps' long results (a page's text, a command's output,
@ -1353,7 +1355,7 @@ pub const QUICK_TROUBLE_MAX: usize = 2;
fn only_looks(name: &str) -> bool {
matches!(
name,
"computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "computer_use_check_permissions" | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_find" | "browser_table" | "browser_tabs" | "browser_wait" | "browser_sent_log" | "anybot_guide" | "web_fetch" | "read_file" | "list_dir" | "search" | "read_terminal" | "list_computers" | "list_bots" | "list_routines" | "read_page" | "use_skill" | "react" | "show_card" | "search_documents" | "search_memory"
"computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "computer_use_check_permissions" | crate::outputs::TOOL | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_find" | "browser_table" | "browser_tabs" | "browser_wait" | "browser_sent_log" | "anybot_guide" | "web_fetch" | "read_file" | "list_dir" | "search" | "read_terminal" | "list_computers" | "list_bots" | "list_routines" | "read_page" | "use_skill" | "react" | "show_card" | "search_documents" | "search_memory"
)
}
@ -2403,6 +2405,12 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
finish(&mut history, &output, status, None);
continue;
}
// 完整結果: part of a long result kept whole (outputs.rs).
if call.name == crate::outputs::TOOL {
let (output, ok) = crate::outputs::run(&call.args);
finish(&mut history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None);
continue;
}
// 計畫: the plan on a card (a 問題卡 with 開始照計畫做 and 先不要; their own words
// are a change); the turn waits. A message typed meanwhile is a change too.
if call.name == crate::plan::SUBMIT_TOOL {

View File

@ -43,6 +43,7 @@ mod voice_ui;
mod drops_ui;
mod memory_ui;
mod goal_ui;
mod doctor_ui;
mod plan_ui;
mod mood_ui;
mod profile_ui;
@ -208,6 +209,8 @@ pub struct App {
popup_hidden: std::collections::HashSet<u64>,
/// "全部允許,之後直接操作" was clicked in a request.
want_direct: std::cell::Cell<bool>,
/// 診斷 (/doctor) reports finished on their thread: (the chat it was asked in, the report).
doctor_out: Arc<Mutex<Vec<(u64, String)>>>,
/// Bots whose running turn came from someone else's message (a channel, a teammate):
/// 一律放行 doesn't answer for them.
strangers: std::collections::HashSet<u64>,
@ -486,6 +489,7 @@ impl App {
popup_hidden: Default::default(),
want_direct: Default::default(),
strangers: Default::default(),
doctor_out: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false,
exe_built: crate::version::exe_modified(),
@ -1402,6 +1406,13 @@ impl App {
if text.trim().is_empty() && !self.has_pending_attachments(bot_id) {
return;
}
// 診斷: 「/doctor」 checks this computer — here even on a screen of a brain, and above
// all when the brain can't be reached.
if crate::doctor::command(&text) {
self.drafts.insert(bot_id, String::new());
self.doctor_start(bot_id);
return;
}
// A screen that can't reach its brain: say so, and keep the quote, the files and the
// memories picked (they used to be used up, leaving only the words to send again).
if self.mir.on && !self.mir.online {
@ -1711,6 +1722,8 @@ impl App {
}
// 功能地圖: AnyBot's own map, one area at a time (every bot; nothing in it is private).
tool_specs.push(crate::featuremap::spec());
// 完整結果: the rest of a long result (every bot: its own steps' results).
tool_specs.push(crate::outputs::spec());
tool_specs.push(serde_json::json!({"name": "react", "description": "Put an emoji reaction on the person's latest message, like a friend would (e.g. ❤️ for thanks or good news, 👍 for OK, 😂 for a joke, 🎉 for a win, 👀 when you'll look into it). Use it now and then where it fits; you can still answer in words.",
"parameters": {"type": "object", "properties": {"emoji": {"type": "string", "description": "One emoji"}}, "required": ["emoji"]}}));
// 傳送: a file from a computer the bot works on to another device of the account
@ -5956,6 +5969,8 @@ impl App {
if !self.demo {
self.tell_crashes();
}
// 診斷: a 「/doctor」 that finished.
self.doctor_tick();
// A screen of another AnyBot's brain: its bots work there, not here.
if self.mir.on {
self.remote_tick(ctx);
@ -6094,7 +6109,13 @@ impl App {
/// with no window, refuses every approval (and says so), and prints the turn's steps. Run it
/// with ANYBOT_DATA_DIR pointing at a copy of the data folder. It doesn't connect to the
/// account, channels or routines.
pub fn ask_cli(ctx: &egui::Context, text: &str) -> ! {
/// `anybot --ask …`: one question to a bot, its whole turn (and a goal's turns) waited out,
/// what happened printed — as text for a person, or (`--json`) one JSON object a line for a
/// script. Exit code: 0 the turn went well, 1 it failed or ran out of time, 130 stopped with
/// Ctrl-C, 2 the command itself was wrong.
pub fn ask_cli(ctx: &egui::Context, opts: AskOpts) -> ! {
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
let _ = ctrlc::set_handler(|| INTERRUPTED.store(true, Ordering::SeqCst));
let mut app = App::new(ctx, None);
app.headless = true;
app.asking = true;
@ -6103,17 +6124,45 @@ impl App {
for (name, why) in crate::mcp::sync(&app.state.mcp_servers) {
log::warn!("連接器「{name}」連不上:{why}");
}
let id = app.state.primary_bot;
let id = match opts.bot.as_deref() {
None => app.state.primary_bot,
Some(want) => match app.state.bots.iter().find(|b| b.name == want).or_else(|| app.state.bots.iter().find(|b| b.name.eq_ignore_ascii_case(want))) {
Some(b) => b.id,
None => {
eprintln!("沒有叫「{want}」的 Bot(有:{})", app.state.bots.iter().map(|b| b.name.as_str()).collect::<Vec<_>>().join("、"));
std::process::exit(2);
}
},
};
if app.state.bot(id).is_none() {
eprintln!("這個資料夾還沒有 Bot:先打開 AnyBot 建立一個,或用 anybot setup。");
std::process::exit(2);
}
let json = opts.json;
let line = |v: serde_json::Value| println!("{v}");
let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0);
app.drafts.insert(id, text.to_string());
app.drafts.insert(id, opts.text.clone());
app.send(ctx, id);
let t0 = Instant::now();
let limit = std::env::var("ANYBOT_ASK_SECS").ok().and_then(|v| v.parse().ok()).unwrap_or(900u64);
// 「/goal …」: on to the end, as Claude Code's `claude -p "/goal …"` does — turn, check, turn.
while (app.streams.contains_key(&id) || app.goal_pending(id)) && t0.elapsed().as_secs() < limit {
if let Some(a) = app.approvals.remove(&id) {
println!(" ⚠️ 要求核准(自動拒絕):{} — {}", a.tool, a.reason);
let _ = a.reply.send(ApprovalAnswer::Reject);
if INTERRUPTED.load(Ordering::SeqCst) {
app.stop(id);
break;
}
// Nobody to press a button: --approve once allows what would be asked (a question
// card or a hand-off is skipped either way); without it, refused. (Through answer():
// an app action waiting on its card is answered too — it used to wait to the limit.)
if let Some(a) = app.approvals.get(&id) {
let (kind, tool, reason) = (a.kind, a.tool.clone(), a.reason.clone());
let yes = opts.approve && crate::always::answer_for(kind).is_some();
if json {
line(serde_json::json!({"type": "approval", "tool": tool, "reason": reason, "answer": if yes { "once" } else { "reject" }}));
} else {
println!(" ⚠️ 要求核准({}):{tool} — {reason}", if yes { "自動允許" } else { "自動拒絕" });
}
app.answer(ctx, id, if yes { ApprovalAnswer::Once } else { ApprovalAnswer::Reject });
}
app.drain_events(ctx);
app.goal_tick(ctx);
@ -6121,19 +6170,23 @@ impl App {
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
std::thread::sleep(std::time::Duration::from_millis(100));
}
let timed_out = app.streams.contains_key(&id) && !INTERRUPTED.load(Ordering::SeqCst);
let secs = t0.elapsed().as_secs();
// 自己進化 comes after the turn: wait for it when the turn was long enough to learn from.
let turn_msgs = app.state.bot(id).and_then(|b| b.messages.get(start..)).map(|m| m.to_vec()).unwrap_or_default();
if crate::memory::worth_learning(&turn_msgs) {
if !INTERRUPTED.load(Ordering::SeqCst) && crate::memory::worth_learning(&turn_msgs) {
let before = app.state.skills.clone();
let t1 = Instant::now();
while app.state.skills == before && t1.elapsed().as_secs() < 180 {
app.drain_events(ctx);
std::thread::sleep(std::time::Duration::from_millis(200));
}
match app.state.skills.iter().find(|k| !before.contains(k)) {
Some(k) => println!("📚 學到({} 秒):{} — {}\n{}\n", t1.elapsed().as_secs(), k.name, k.description, k.instructions),
None => println!("📚 這次沒有存技能({} 秒)", t1.elapsed().as_secs()),
let learned = app.state.skills.iter().find(|k| !before.contains(k));
match (json, learned) {
(true, Some(k)) => line(serde_json::json!({"type": "learned", "skill": k.name, "description": k.description})),
(true, None) => {}
(false, Some(k)) => println!("📚 學到({} 秒):{} — {}\n{}\n", t1.elapsed().as_secs(), k.name, k.description, k.instructions),
(false, None) => println!("📚 這次沒有存技能({} 秒)", t1.elapsed().as_secs()),
}
}
// The chat can shrink (compaction) between the snapshot and now: slice safely.
@ -6145,6 +6198,17 @@ impl App {
let full = std::env::var("ANYBOT_ASK_FULL").is_ok();
let mut steps = 0;
for m in &msgs {
steps += m.tool_calls.len();
if json {
let role = match m.role {
Role::User => "user",
Role::Assistant if m.note => "note",
Role::Assistant => "assistant",
Role::Tool => "tool",
};
line(serde_json::json!({"type": "message", "role": role, "text": crate::secrets::mask(&m.text), "error": m.error, "tools": m.tool_calls.iter().map(|c| serde_json::json!({"id": c.id, "name": c.name, "args": crate::secrets::mask(&c.args)})).collect::<Vec<_>>(), "tool_call_id": m.tool_call_id}));
continue;
}
match m.role {
Role::User => println!("👤 {}", m.text),
Role::Assistant => {
@ -6152,16 +6216,22 @@ impl App {
println!("🤖 {}", if full || m.tool_calls.is_empty() { m.text.clone() } else { clip(&m.text, 300) });
}
for c in &m.tool_calls {
steps += 1;
println!(" 🔧 {} {}", c.name, clip(&c.args, 200));
}
}
Role::Tool => println!(" ↳ {}{}", if m.images.is_empty() { "" } else { "[附截圖] " }, clip(&m.text, if full { 4000 } else { 400 })),
}
}
println!("—— {steps} 個工具步驟,{secs} 秒");
let outcome = app.state.bot(id).and_then(|b| b.last_turn.as_ref()).map(|t| t.outcome);
let code = ask_exit_code(INTERRUPTED.load(Ordering::SeqCst), timed_out, outcome);
let answer = msgs.iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()).map(|m| m.text.clone()).unwrap_or_default();
if json {
line(serde_json::json!({"type": "done", "ok": code == 0, "code": code, "steps": steps, "secs": secs, "timed_out": timed_out, "answer": crate::secrets::mask(&answer)}));
} else {
println!("—— {steps} 個工具步驟,{secs} 秒{}", if timed_out { "(時間到了,還沒做完)" } else { "" });
}
app.state.save();
std::process::exit(0)
std::process::exit(code)
}
pub fn serve(ctx: &egui::Context) -> ! {
@ -6625,6 +6695,59 @@ fn carried_in_view(messages: &[Message]) -> std::collections::HashSet<String> {
/// A message of the person's, with the memories they picked under the composer (`None`: they
/// didn't look; AnyBot chooses at the start of the turn).
/// What `anybot --ask` was told (main parses it before anything else, for --data-dir).
#[derive(Debug, PartialEq, Default)]
pub struct AskOpts {
pub text: String,
/// One JSON object a line instead of text for a person.
pub json: bool,
/// The bot asked, by name (the main bot when not given).
pub bot: Option<String>,
/// A data folder of its own (ANYBOT_DATA_DIR).
pub data_dir: Option<String>,
/// What would be asked is allowed once (`--approve once`); refused otherwise.
pub approve: bool,
}
impl AskOpts {
/// The words after `--ask`: options first or mixed in, the rest is the question.
pub fn parse(args: &[String]) -> Result<AskOpts, String> {
let mut o = AskOpts::default();
let mut words = vec![];
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--json" => o.json = true,
"--bot" => o.bot = Some(it.next().ok_or("--bot 後面要接 Bot 的名字")?.clone()),
"--data-dir" => o.data_dir = Some(it.next().ok_or("--data-dir 後面要接資料夾")?.clone()),
"--approve" => match it.next().map(String::as_str) {
Some("once") => o.approve = true,
Some("reject") => o.approve = false,
_ => return Err("--approve 後面要接 once 或 reject".into()),
},
w => words.push(w.to_string()),
}
}
o.text = words.join(" ");
if o.text.trim().is_empty() {
return Err("要問什麼?例如:anybot --ask --json --bot 小幫手 今天天氣如何".into());
}
Ok(o)
}
}
/// `anybot --ask`'s exit code: 130 stopped with Ctrl-C, 1 out of time or the turn didn't go
/// well, 0 it did.
pub fn ask_exit_code(interrupted: bool, timed_out: bool, outcome: Option<crate::model::TurnOutcome>) -> i32 {
if interrupted {
130
} else if timed_out || outcome != Some(crate::model::TurnOutcome::Success) {
1
} else {
0
}
}
fn person_message(st: &State, bot_id: u64, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) -> Message {
let mut m = Message { attachments, ..Message::user(text) };
if let Some(p) = picks {
@ -7946,6 +8069,52 @@ mod tests {
assert_eq!(app.state.bot(id).unwrap().name, name);
}
/// E10: `anybot --ask` reads its options anywhere among the words, and says by its exit
/// code how the turn went.
#[test]
fn ask_options_and_exit_codes() {
let a = |v: &[&str]| super::AskOpts::parse(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>());
let o = a(&["--json", "--bot", "小幫手", "今天", "--approve", "once", "天氣如何", "--data-dir", "/tmp/x"]).unwrap();
assert_eq!(o, super::AskOpts { text: "今天 天氣如何".into(), json: true, bot: Some("小幫手".into()), data_dir: Some("/tmp/x".into()), approve: true });
assert!(a(&["--json"]).unwrap_err().contains("要問什麼"));
assert!(a(&["--bot"]).unwrap_err().contains("--bot"));
assert!(a(&["--approve", "always", "x"]).unwrap_err().contains("once 或 reject"));
use crate::model::TurnOutcome::*;
assert_eq!(super::ask_exit_code(false, false, Some(Success)), 0);
assert_eq!(super::ask_exit_code(false, false, Some(Error)), 1);
assert_eq!(super::ask_exit_code(false, true, Some(Success)), 1, "out of time");
assert_eq!(super::ask_exit_code(false, false, None), 1);
assert_eq!(super::ask_exit_code(true, false, Some(Cancelled)), 130);
}
/// 診斷: 「/doctor」 says it is checking, then one report: each finding ✓ or ✗ (the model
/// services are this test's fake one; no account, no bots' computer in a test).
#[test]
fn doctor_reports_each_finding() {
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-doctor.png")));
let fake = crate::testkit::Fake::openai(vec![]);
app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = fake.base();
for b in app.state.bots.iter_mut() {
b.provider = crate::providers::ProviderKind::Custom;
}
let id = app.state.bots[0].id;
app.drafts.insert(id, "/doctor".into());
app.send(&ctx, id);
assert!(app.state.bot(id).unwrap().messages.last().is_some_and(|m| m.note && m.text.starts_with("診斷中")));
let mut report = String::new();
for _ in 0..200 {
app.doctor_tick();
if let Some(m) = app.state.bot(id).unwrap().messages.last().filter(|m| m.text.starts_with("診斷(/doctor)")) {
report = m.text.clone();
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(report.contains("✓ AnyBot ") && report.contains("✓ 沒有登入帳號") && report.contains("模型服務 ") && report.contains("Bot 的電腦:"), "{report}");
assert!(report.lines().last().is_some_and(|l| l == "全部正常。" || l.starts_with("有 ")), "{report}");
}
/// 一律放行: before it, a command on this computer waits for 允許; after 「/always-approve」 the
/// person's own turn runs it with no card at all; a stranger's message still waits; 「off」
/// puts asking back (and 直接操作 off again, as it was before).
@ -8326,7 +8495,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::<Vec<_>>();
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage"]);
assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor"]);
assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word");
assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]);
}

View File

@ -176,6 +176,7 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> String {
"send_to_device" => "正在傳到你的另一台裝置".into(),
"publish_site" => "正在發布網站".into(),
"show_card" => "正在整理成卡片".into(),
"read_result" => "正在看完整的結果".into(),
"submit_plan" => "正在交計畫給你看".into(),
"update_plan" => "正在更新計畫進度".into(),
"react" => "正在按表情".into(),
@ -1133,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); 5] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token")];
pub const SLASH_COMMANDS: [(&str, &str); 6] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、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

123
src/app/doctor_ui.rs Normal file
View File

@ -0,0 +1,123 @@
// 診斷 (/doctor) in the window: what this computer can tell about itself, gathered now (the
// settings and states the window has) and on a thread (the checks that go over the network: each
// model service the bots use, how Tailscale reaches the account server), then said in one line of
// AnyBot's in the chat — on a screen of a brain, whose chats are the brain's, as a notice. What
// each line says and how: doctor.rs.
use super::*;
use crate::doctor::{bad, ok, Line};
impl App {
/// 「/doctor」: gather, check on a thread, tell (doctor_tick).
pub(super) fn doctor_start(&mut self, bot_id: u64) {
let mut lines: Vec<Line> = vec![];
let data = State::path().parent().map(|p| p.to_path_buf()).unwrap_or_default();
lines.push(ok(format!("AnyBot {};資料夾 {}", crate::version::full(crate::version::exe_modified()), data.display())));
lines.push(ok(format!("紀錄檔 {}", crate::logfile::dir().join(format!("anybot-{}.log", chrono::Local::now().format("%Y-%m-%d"))).display())));
// The account server and the brain.
let s = self.state.remote.clone();
if s.relay_url.is_empty() {
lines.push(ok("沒有登入帳號(只在這台用)"));
} else {
let status = crate::remote::hub().relay_status();
if status == "已連線" {
lines.push(ok(format!("這台 ↔ 帳號伺服器({}):已連線", s.relay_url)));
} else {
lines.push(bad(format!("這台 ↔ 帳號伺服器({}):{}", s.relay_url, if status.is_empty() { "沒有連線" } else { status.as_str() })));
}
}
if !s.brain_id.is_empty() {
match self.rm.peers.lock().unwrap().iter().find(|(id, _, _)| *id == s.brain_id).map(|x| x.2) {
Some(true) => lines.push(ok(format!("帳號伺服器 ↔ 大腦「{}」:在線上", s.brain_name))),
Some(false) => lines.push(bad(format!("帳號伺服器 ↔ 大腦「{}」:不在線上(大腦那台的 AnyBot 沒開、沒網路,或正在重新啟動)", s.brain_name))),
None => {}
}
if self.mir.on {
if self.mir.online {
lines.push(ok(format!("大腦「{}」:連得到", s.brain_name)));
} else {
lines.push(bad(format!("大腦「{}」:{}", s.brain_name, self.mir.reason)));
}
}
if let Some((at, bytes, ms)) = *self.mir.last_sync.lock().unwrap() {
let slow = bytes >= 1_000_000 && ms > 0 && bytes * 1000 / ms < 300_000;
let words = super::mirror_ui::sync_words(at, bytes, ms);
lines.push(if slow { bad(format!("{words}:線很慢")) } else { ok(words) });
}
}
// The bots' computer and the connectors (a screen's are the brain's).
if self.mir.on {
lines.push(ok("Bot 的電腦、連接器、模型服務在大腦上(到大腦那台打 /doctor 看)"));
} else {
let run = crate::cloudbox::run_state();
if crate::cloudbox::available() {
lines.push(ok(format!("Bot 的電腦:{}", run.label())));
} else {
lines.push(bad(format!("Bot 的電腦:{}(指令改在封閉的資料夾裡跑,沒有桌面)", run.label())));
}
let status = crate::mcp::status();
let errors = self.ch.mcp_errors.lock().unwrap().clone();
for m in self.state.mcp_servers.iter().filter(|m| m.enabled) {
match (status.get(&m.name), errors.iter().find(|e| e.0 == m.name)) {
(Some(n), _) => lines.push(ok(format!("連接器「{}」:已連上,{n} 個工具", m.name))),
(None, Some((_, e))) => lines.push(bad(format!("連接器「{}」:{e}", m.name))),
(None, None) => lines.push(bad(format!("連接器「{}」:還沒連上", m.name))),
}
}
}
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))),
None => {}
}
if let Some((when, at)) = crate::doctor::last_crash(&crate::logfile::dir()) {
lines.push(bad(format!("上次內部出錯:{when},在 {at}(報告在紀錄檔資料夾)")));
}
// Over the network, on a thread: the model services the bots use (here, not on a screen),
// and how Tailscale reaches the account server.
let mut services: Vec<(String, crate::providers::ProviderKind, String, String)> = vec![];
if !self.mir.on {
for kind in ALL_PROVIDERS.into_iter().filter(|k| self.state.bots.iter().any(|b| b.provider == *k)) {
let ps = self.state.provider(kind);
services.push((kind.label().to_string(), kind, providers::resolve_base(kind, &ps.base_url), providers::resolve_key_for(kind, &ps.api_key, &ps.base_url)));
}
}
let ts_host = crate::doctor::tailscale_host(&s.relay_url);
let out = self.doctor_out.clone();
let repaint = self.repaint_fn();
if self.mir.on {
self.notice = Some("診斷中:正在檢查連線…".into());
} else {
self.goal_note(bot_id, "診斷中:正在檢查連線和模型服務…");
}
std::thread::spawn(move || {
if let Some(host) = ts_host {
if let Some(l) = crate::doctor::ping_tailscale(&host) {
lines.push(l);
}
}
for (name, kind, base, key) in services {
match providers::list_models(kind, &base, &key) {
Ok(m) => lines.push(ok(format!("模型服務 {name}:連得到({} 個模型)", m.len()))),
Err(e) => lines.push(bad(format!("模型服務 {name}:{}", e.chars().take(160).collect::<String>()))),
}
}
out.lock().unwrap().push((bot_id, crate::doctor::report(&lines)));
repaint();
});
self.dirty = true;
}
/// A finished 「/doctor」: its report in the chat it was asked in (a notice on a screen).
pub(super) fn doctor_tick(&mut self) {
let done: Vec<(u64, String)> = std::mem::take(&mut *self.doctor_out.lock().unwrap());
for (bot_id, text) in done {
if self.mir.on {
self.notice = Some(text);
} else {
self.goal_note(bot_id, &text);
}
self.dirty = true;
}
}
}

View File

@ -32,7 +32,7 @@ pub struct RemoteUi {
join_rx: Option<Receiver<Result<(Settings, remote::AccountFind), String>>>,
restore_rx: Option<Receiver<Result<Vec<u8>, String>>>,
busy: Arc<AtomicBool>,
peers: Arc<Mutex<Vec<(String, String, bool)>>>,
pub(super) peers: Arc<Mutex<Vec<(String, String, bool)>>>,
last_seen_mark: Option<Instant>,
peers_at: Option<Instant>,
/// 團隊: (user, role) shared with, loaded from the relay; the form to add one.
@ -557,6 +557,11 @@ impl App {
self.usage_note(bot);
return;
}
// (From the phone or a screen: the brain checks itself.)
if crate::doctor::command(&text) {
self.doctor_start(bot);
return;
}
self.goal_heard(bot);
}
if self.streams.contains_key(&bot) {

123
src/doctor.rs Normal file
View File

@ -0,0 +1,123 @@
//! 診斷 (/doctor): what this computer's AnyBot can find out about itself, one line each, ✓ or ✗
//! with the reason — the version and folders, this computer ↔ the account server (and whether
//! Tailscale goes direct or through one of its relays), the account server ↔ the brain, the last
//! sync's speed, each model service the bots use, the bots' computer, the connectors, the disk,
//! the last crash. On a screen of a brain it is this computer that is checked (where a problem
//! usually is). The checks that go over the network run on a thread of their own. Like
//! grok-build's /doctor; `make doctor` checks the build tools instead.
use std::path::Path;
/// 「/doctor」 (nothing after it).
pub fn command(text: &str) -> bool {
text.trim() == "/doctor"
}
/// One finding: fine or not, and what it says.
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
pub ok: bool,
pub text: String,
}
pub fn ok(t: impl Into<String>) -> Line {
Line { ok: true, text: t.into() }
}
pub fn bad(t: impl Into<String>) -> Line {
Line { ok: false, text: t.into() }
}
/// The report: a title line, then each finding with ✓ or ✗, and a last line counting the ✗.
pub fn report(lines: &[Line]) -> String {
let bad = lines.iter().filter(|l| !l.ok).count();
let mut s = String::from("診斷(/doctor):這台電腦的 AnyBot");
for l in lines {
s.push_str(&format!("\n{} {}", if l.ok { "✓" } else { "✗" }, l.text));
}
s.push_str(&if bad == 0 { "\n全部正常。".to_string() } else { format!("\n有 {bad} 項要看一下(✗)。") });
s
}
/// The Tailscale name in an account server's address (…​.ts.net), if it is one.
pub fn tailscale_host(url: &str) -> Option<String> {
let host = url.split("://").nth(1)?.split(['/', ':']).next()?.to_string();
host.ends_with(".ts.net").then_some(host)
}
/// What `tailscale ping` said, in words: direct, or through which relay (much slower).
pub fn tailscale_path(ping: &str) -> Option<Line> {
let line = ping.lines().find(|l| l.contains("pong from"))?;
if let Some(relay) = line.split("via DERP(").nth(1).and_then(|r| r.split(')').next()) {
let ms = line.split(" in ").nth(1).unwrap_or("").trim().to_string();
return Some(bad(format!("Tailscale 沒有直連,走它在「{relay}」的中繼({ms}):大份資料會很慢。兩台通常在同一個網路卻連不直,多半是中間擋了 UDP(Tailscale 直連用 41641)")));
}
Some(ok(format!("Tailscale 直連({})", line.split("pong from").nth(1).unwrap_or("").trim())))
}
/// Ask Tailscale how it reaches `host` (None when Tailscale isn't here).
pub fn ping_tailscale(host: &str) -> Option<Line> {
for bin in ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale"] {
let out = std::process::Command::new(bin).args(["ping", "-c", "1", "--timeout", "5s", host]).output();
if let Ok(o) = out {
let text = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
return tailscale_path(&text).or_else(|| Some(bad(format!("Tailscale 找不到 {host}:{}", text.lines().next().unwrap_or("沒有回應")))));
}
}
None
}
/// Free space where the data folder is, in MB (None where `df` can't say).
pub fn free_mb(dir: &Path) -> Option<u64> {
let out = std::process::Command::new("df").args(["-Pk"]).arg(dir).output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
text.lines().nth(1)?.split_whitespace().nth(3)?.parse::<u64>().ok().map(|kb| kb / 1024)
}
/// The newest crash report in `logs`: (when, where) from its file.
pub fn last_crash(logs: &Path) -> Option<(String, String)> {
let mut reports: Vec<std::path::PathBuf> = std::fs::read_dir(logs).ok()?.flatten().map(|e| e.path()).filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("crash-"))).collect();
reports.sort();
let text = std::fs::read_to_string(reports.last()?).ok()?;
let field = |k: &str| text.lines().find_map(|l| l.strip_prefix(k)).unwrap_or("").trim().to_string();
Some((field("時間:"), field("位置:")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_report_counts_what_is_wrong() {
let r = report(&[ok("版本 v1"), bad("模型服務 xAI:金鑰不對")]);
assert!(r.contains("✓ 版本 v1\n✗ 模型服務 xAI:金鑰不對") && r.ends_with("有 1 項要看一下(✗)。"), "{r}");
assert!(report(&[ok("a")]).ends_with("全部正常。"));
assert!(command(" /doctor ") && !command("/doctor x"));
}
#[test]
fn tailscale_says_direct_or_through_which_relay() {
assert_eq!(tailscale_host("https://nobledesktop.tailbcc3a6.ts.net:8443").as_deref(), Some("nobledesktop.tailbcc3a6.ts.net"));
assert_eq!(tailscale_host("https://example.com"), None);
let relayed = tailscale_path("pong from nobledesktop (100.82.106.34) via DERP(hkg) in 63ms\n").unwrap();
assert!(!relayed.ok && relayed.text.contains("「hkg」") && relayed.text.contains("63ms") && relayed.text.contains("41641"), "{relayed:?}");
let direct = tailscale_path("pong from nobledesktop (100.82.106.34) via 10.184.27.181:41641 in 4ms").unwrap();
assert!(direct.ok && direct.text.contains("10.184.27.181:41641"), "{direct:?}");
assert_eq!(tailscale_path("no reply"), None);
}
#[test]
fn the_last_crash_and_the_disk() {
let d = std::env::temp_dir().join(format!("anybot-doctor-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
assert_eq!(last_crash(&d), None);
std::fs::write(d.join("crash-20261101-000000.000.seen.txt"), "時間:舊的\n位置:a.rs:1\n").unwrap();
std::fs::write(d.join("crash-20261117-104200.000.txt"), "時間:2026-11-17 10:42:00\n位置:src/app.rs:12\n").unwrap();
assert_eq!(last_crash(&d), Some(("2026-11-17 10:42:00".into(), "src/app.rs:12".into())));
if cfg!(unix) {
assert!(free_mb(&d).is_some_and(|mb| mb > 0));
}
let _ = std::fs::remove_dir_all(&d);
}
}

View File

@ -109,7 +109,7 @@ mod tests {
all.extend(names(&crate::phone::specs()));
all.extend(names(&crate::vault::specs_for(&crate::vault::Offer { login: true, card: true, contact: true })));
all.push(crate::ask::spec()["name"].as_str().unwrap().to_string());
all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL].map(String::from));
all.extend([crate::plan::SUBMIT_TOOL, crate::plan::UPDATE_TOOL, crate::outputs::TOOL].map(String::from));
all.push(crate::teach::view_step_spec()["name"].as_str().unwrap().to_string());
all.extend([crate::mcp::FIND_TOOL, crate::mcp::USE_TOOL, crate::agent::REPLAY_TOOL, crate::tools::HANDOFF_TOOL, "show_card", "react", "send_to_device", "send_file", "open_for_person", "publish_site", TOOL].map(String::from));
all.sort();

View File

@ -75,6 +75,8 @@ mod always;
mod secrets;
mod logfile;
mod net;
mod doctor;
mod outputs;
mod gate;
mod usage;
#[cfg(test)]
@ -302,7 +304,12 @@ impl eframe::App for Busy {
const USAGE: &str = "用法:
anybot 打開 AnyBot 視窗
anybot --serve 不開視窗,讓 Bot 繼續工作、接手機
anybot --ask 問題… 問第一個 Bot 一句,印出回答(測試用)
anybot --ask 問題… 問一個 Bot 一句,印出這一輪(給人看)
--json 一行一個 JSON(給腳本:message、approval、learned、done)
--bot 名字 問哪個 Bot(預設主要 Bot)
--data-dir 資料夾 用另一個資料夾(像 ANYBOT_DATA_DIR)
--approve once 要核准的自動允許一次(預設自動拒絕)
結束碼:0 這一輪順利、1 失敗或時間到、130 按了 Ctrl-C、2 指令寫錯
anybot setup … 在沒有螢幕的機器上設定
anybot --install-skill 來源 安裝技能(GitHub 網址、owner/repo/path、SKILL.md 網址或本機資料夾)
anybot --update-box 更新 Bot 的電腦(同 設定 › 電腦 › 更新;AnyBot 開著就請它做)
@ -318,8 +325,19 @@ fn main() -> eframe::Result<()> {
println!("AnyBot {}", version::full(version::exe_modified()));
return Ok(());
}
// `anybot --ask … --data-dir X`: that folder for everything (set before anything reads it).
let ask = (args.get(1).map(String::as_str) == Some("--ask")).then(|| app::AskOpts::parse(&args[2..]));
if let Some(Err(e)) = &ask {
eprintln!("{e}");
std::process::exit(2);
}
if let Some(Ok(app::AskOpts { data_dir: Some(d), .. })) = &ask {
std::env::set_var("ANYBOT_DATA_DIR", d);
}
// 紀錄檔與當掉報告 (logfile.rs): logs/ in the data folder, and a report if anything panics.
logfile::init();
// 完整結果 older than a week go.
outputs::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") {
@ -415,11 +433,10 @@ fn main() -> eframe::Result<()> {
std::process::exit(setup::run(&args[2..]));
}
// Everything below uses the data folder (the chats, the work log): one AnyBot at a time.
if args.get(1).map(String::as_str) == Some("--ask") {
let text = args[2..].join(" ");
if let Some(Ok(opts)) = ask {
let ctx = egui::Context::default();
let _folder = take_folder_or_exit();
app::App::ask_cli(&ctx, &text);
app::App::ask_cli(&ctx, opts);
}
// No window: keep the bots working and answer the phone (always-on Mac or server).
if args.iter().any(|a| a == "--serve") {

113
src/outputs.rs Normal file
View File

@ -0,0 +1,113 @@
//! 完整結果: a step's result that is too long for the chat (a command's output, a connector's
//! answer) keeps its start and its end for the model, and the whole of it is kept here, in the
//! data folder's `outputs/`, by an id made from its content. The note in the middle says the id,
//! and the bot reads any part with `read_result`. An older result set aside to make room
//! (agent::folded_text) points here too. Before, the bot was told to do the step again to see the
//! rest — wrong for a step that changes something or answers differently the second time, and
//! the middle of a long log was simply gone. Like grok-build saving big MCP results to a file.
//!
//! Kept LIFE_DAYS days; one result at most KEEP_MAX_BYTES.
use serde_json::{json, Value};
use std::path::PathBuf;
/// The tool the bot reads a kept result with.
pub const TOOL: &str = "read_result";
/// Days a kept result stays.
pub const LIFE_DAYS: u64 = 7;
/// The most of one result kept (a 2 GB log isn't copied whole).
pub const KEEP_MAX_BYTES: usize = 20 * 1024 * 1024;
/// The most `read_result` gives at once.
pub const READ_MAX_CHARS: usize = 20_000;
fn dir() -> PathBuf {
crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("outputs")
}
/// Keep the whole text; its id (the same text always gets the same id: keeping it again is free).
pub fn keep(text: &str) -> String {
let id = format!("r{}", &crate::httpd::sha256_hex(text)[..12]);
let path = dir().join(format!("{id}.txt"));
if !path.exists() {
let _ = std::fs::create_dir_all(dir());
let mut end = text.len().min(KEEP_MAX_BYTES);
while !text.is_char_boundary(end) {
end -= 1;
}
let _ = crate::httpd::write_private(&path, &text.as_bytes()[..end]);
}
id
}
/// What the middle of a shortened result says.
pub fn note(left_out: usize, id: &str) -> String {
format!("…(中間省略 {left_out} 個字;完整內容用 {TOOL} 讀:id={id})…")
}
/// Part of a kept result: from the `from`-th character, at most `chars` of them.
pub fn read(id: &str, from: usize, chars: usize) -> Result<String, String> {
let id = id.trim();
if !id.starts_with('r') || id.len() != 13 || !id[1..].chars().all(|c| c.is_ascii_hexdigit()) {
return Err(format!("id「{id}」不對:用結果裡寫的那個(像 r1a2b3c4d5e6f)。"));
}
let text = std::fs::read_to_string(dir().join(format!("{id}.txt"))).map_err(|_| format!("找不到 {id}:可能超過 {LIFE_DAYS} 天被清掉了,要的話再做一次那一步。"))?;
let total = text.chars().count();
if from >= total {
return Err(format!("{id} 只有 {total} 個字,從第 {from} 個字開始沒有內容了。"));
}
let chars = chars.clamp(1, READ_MAX_CHARS);
let part: String = text.chars().skip(from).take(chars).collect();
let end = from + part.chars().count();
let more = if end < total { format!("(還有 {} 個字:from={end} 接著讀)", total - end) } else { "(到結尾了)".into() };
Ok(format!("[{id}] 第 {from}–{end} 個字,共 {total} 個字{more}\n{part}"))
}
/// Results older than LIFE_DAYS go (at start).
pub fn prune() {
let life = std::time::Duration::from_secs(LIFE_DAYS * 86_400);
for e in std::fs::read_dir(dir()).into_iter().flatten().flatten() {
if e.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > life) {
let _ = std::fs::remove_file(e.path());
}
}
}
pub fn spec() -> Value {
json!({"name": TOOL,
"description": "Read the whole of a long step result that was shortened (its middle left out) or set aside earlier to make room. Give the id the result names (read_result id=…), where to start (a character offset; 0 is the beginning) and how much (at most 20,000 characters at a time). Use it instead of doing a step again just to see the rest.",
"parameters": {"type": "object", "properties": {
"id": {"type": "string", "description": "The id in the shortened result, e.g. r1a2b3c4d5e6f."},
"from": {"type": "integer", "description": "Character offset to start at (default 0)."},
"chars": {"type": "integer", "description": "How many characters (default and at most 20000)."}},
"required": ["id"]}})
}
/// `read_result`'s answer for the bot.
pub fn run(args: &str) -> (String, bool) {
let v: Value = serde_json::from_str(args).unwrap_or(Value::Null);
match read(v["id"].as_str().unwrap_or(""), v["from"].as_u64().unwrap_or(0) as usize, v["chars"].as_u64().unwrap_or(READ_MAX_CHARS as u64) as usize) {
Ok(t) => (t, true),
Err(e) => (e, false),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_kept_result_is_read_back_in_parts() {
let text: String = (0..30_000).map(|i| char::from(b'a' + (i % 26) as u8)).collect::<String>() + "最後一段";
let id = keep(&text);
assert_eq!(keep(&text), id, "the same text, the same id");
let first = read(&id, 0, 100).unwrap();
assert!(first.contains("第 0–100 個字,共 30004 個字") && first.contains("from=100 接著讀"), "{first}");
let last = read(&id, 29_990, 50).unwrap();
assert!(last.ends_with("最後一段") && last.contains("到結尾了"), "{last}");
assert!(read(&id, 40_000, 10).unwrap_err().contains("只有 30004 個字"));
assert!(read("../../etc/passwd", 0, 10).is_err() && read("rzzzzzzzzzzzz", 0, 10).is_err());
assert!(read("r000000000000", 0, 10).unwrap_err().contains("找不到"));
let (out, ok) = run(&json!({"id": id, "from": 26}).to_string());
assert!(ok && out.contains("\nabcd"), "{out}");
}
}

View File

@ -75,6 +75,7 @@ pub fn label(name: &str) -> &'static str {
match name {
HANDOFF_TOOL => "請你接手電腦",
crate::ask::TOOL => "問你",
crate::outputs::TOOL => "看完整的結果",
crate::plan::SUBMIT_TOOL => "交計畫給你核准",
crate::plan::UPDATE_TOOL => "更新計畫進度",
"list_dir" => "查看資料夾",
@ -1411,7 +1412,9 @@ pub fn head_tail(s: &str) -> String {
}
let head: String = s.chars().take(OUTPUT_HEAD_CHARS).collect();
let tail: String = s.chars().skip(n - OUTPUT_TAIL_CHARS).collect();
format!("{head}\n…(中間省略 {} 個字)…\n{tail}", n - OUTPUT_HEAD_CHARS - OUTPUT_TAIL_CHARS)
// 完整結果: the whole is kept, and the note says how to read the middle (outputs.rs).
let id = crate::outputs::keep(s);
format!("{head}\n{}\n{tail}", crate::outputs::note(n - OUTPUT_HEAD_CHARS - OUTPUT_TAIL_CHARS, &id))
}
fn timeout_of(v: &Value) -> u64 {
@ -2746,7 +2749,7 @@ mod tests {
fn head_tail_trims_middle() {
let s = "a".repeat(OUTPUT_HEAD_CHARS) + &"b".repeat(5000) + &"c".repeat(OUTPUT_TAIL_CHARS);
let t = head_tail(&s);
assert!(t.contains("中間省略 5000 個字"));
assert!(t.contains("中間省略 5000 個字;完整內容用 read_result 讀"));
}
#[test]