diff --git a/FEATURES.md b/FEATURES.md index d400e38..3251607 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1500,6 +1500,11 @@ 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「再做一次這一步」看完整的:會改東西的步驟重做很危險,答案也可能不一樣,長紀錄的中間就這樣不見了。 + ### 用量(/usage) - 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index b5c5d5d..a752e04 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -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::`。 ## 陷阱 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 281914b..770f99e 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -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 拿到頭尾和檔案路徑,檔案內容完整。 diff --git a/src/agent.rs b/src/agent.rs index 783b16b..282be1e 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -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::>().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 { diff --git a/src/app.rs b/src/app.rs index d6e0c7f..a775bb8 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1711,6 +1711,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 diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 4228885..ff18bc2 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -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(), diff --git a/src/featuremap.rs b/src/featuremap.rs index 79ee0e8..26ac09f 100644 --- a/src/featuremap.rs +++ b/src/featuremap.rs @@ -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(); diff --git a/src/main.rs b/src/main.rs index b29dd8e..c9a83ac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -75,6 +75,7 @@ mod always; mod secrets; mod logfile; mod net; +mod outputs; mod gate; mod usage; #[cfg(test)] @@ -320,6 +321,8 @@ fn main() -> eframe::Result<()> { } // 紀錄檔與當掉報告 (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") { diff --git a/src/outputs.rs b/src/outputs.rs new file mode 100644 index 0000000..58de62f --- /dev/null +++ b/src/outputs.rs @@ -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 { + 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::() + "最後一段"; + 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}"); + } +} diff --git a/src/tools.rs b/src/tools.rs index d295176..2851a77 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -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]