diff --git a/FEATURES.md b/FEATURES.md index 4e83f50..5e896b8 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -487,7 +487,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ### 「/」清單只放指令 -- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 +- 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/plan、/btw、/always-approve、/usage、/doctor、/context、/compact),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 ### 上線前補上的防護(安全和資源) @@ -1515,6 +1515,11 @@ 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 *) 規則。) +### 摘要(/context、/compact) + +- 對話太長時(到模型可讀的 70%)把較早的內容整理成摘要。摘要照段落寫:使用者要的、已經決定的、做過的事和結果(指令、路徑、網址、數字照原樣)、還沒完成的、注意(試過不行的)。整理得太短(一大段對話不到 200 字)會再要一次。摘要下面由 AnyBot 自己(不是模型)附上使用者最近 12 句原話(每句最多 400 字)和還在跑的背景指令(#編號和指令),這些不會被摘要弄丟。參考 grok-build 的分段摘要和摘要後的提醒。 +- 「/context」:這個對話(模型看得到的部分)約幾 token、模型可讀多少、幾 %。「/compact」:現在就整理(Bot 在做事時不行),在背景用快速模型做,好了留一行「已整理:較早的 N 則訊息換成一段摘要」。 + ### 用量(/usage) - 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。 diff --git a/docs/feature-map/chat.md b/docs/feature-map/chat.md index 23779a6..302457e 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)),打「@」列出其他 Bot。 +- 輸入框:Enter 送出、Shift+Enter 換行(在「1. 」「- 」這種清單裡會自動接下一項);輸入框空著按 ↑ 找回上一則;每個 Bot 的草稿各存一份,重開也在。打「/」列出 /goal、/plan、/btw、/always-approve(一律放行,見 [safety](safety.md))、/usage(用量:最近一天和一週、各 Bot 和各模型用了多少 token,模型服務有回報才有;有回報花費的才寫花費)、/doctor(診斷,見 [garden](garden.md))、/context(這個對話用了模型可讀的多少)、/compact(現在就把較早的對話整理成摘要),打「@」列出其他 Bot。 - 記憶小卡片:打字停一下,輸入框上方出現「帶入記憶」一列,見 [memory](memory.md)。 - 插話:Bot 工作中照樣打字送出,不另開一輪,Bot 下一步就讀到(附檔一起進去);輸入框下方寫「已排入「…」,Bot 會在下一步看到」。這一輪剛好結束、來不及讀的,自動變成下一輪。 - 停止:工作中、輸入框空著時,送出鈕變成「停止」。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 73175dc..627969e 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -75,7 +75,7 @@ - 做法:指令輸出、連接器結果、網頁內容超過上限時,完整內容存到 Bot 的資料夾 `outputs/`,截短的那份寫「完整內容在 …」;舊結果收起時也一樣(不再叫 Bot「再跑一次」)。 - 做完:一個 50 萬字的輸出,Bot 拿到頭尾和檔案路徑,檔案內容完整。 -### R4. 摘要的品質、手動 /compact、/context ⬜ +### R4. 摘要的品質、手動 /compact、/context ✅(計畫進度本來就每一輪在系統指示裡,摘要不另外寫) - 做法:摘要用分段的提示(目標、做了什麼、檔案、未完成、使用者原話全留);摘要太短就重做一次;摘要後提醒還在跑的背景指令和計畫進度。`/compact` 現在就整理,`/context` 看用了多少。 - 做完:測試涵蓋太短重做、背景指令提醒。 diff --git a/mobile/index.html b/mobile/index.html index 1f863e4..75bd540 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: "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: "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)\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); 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 60cc99f..bc0e923 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -960,7 +960,7 @@ pub fn estimate_tokens(s: &str) -> u64 { ascii / 4 + other } -fn history_tokens(system: &str, h: &[Message]) -> u64 { +pub fn history_tokens(system: &str, h: &[Message]) -> u64 { // Pictures as they are sent: a step's screenshot only while it is one of the newest // KEEP_SCREENSHOTS (older ones go as a note, see providers::kept_images); counting every one // of a fifty-step task made compaction come early and shrink results the bot still needed. @@ -1052,6 +1052,86 @@ pub fn fold_results(history: &mut [Message]) -> Vec { /// (fold_results); only if that isn't enough, fold older messages into one summary, written by /// the quick model when the bot has one (it is a tidy-up, not thinking). `percent` 0: the model /// itself said the chat is too long — do both. Returns how many messages the summary replaced. +/// 摘要 (R4): what the summary is asked to keep, in sections, so the model after it can go on +/// without the original (grok-build's sectioned compaction prompt). +const SUMMARY_SYSTEM: &str = "你負責把一段對話整理成摘要,讓接著做的模型不看原文也能接下去。照下面的段落寫,每段用條列,沒有內容的段落寫「(無)」,不要加入對話裡沒有的東西: +## 使用者要的 +(目標、偏好、限制) +## 已經決定的 +## 做過的事和結果 +(成功和失敗的都寫;指令、檔案路徑、網址、數字照原樣) +## 還沒完成的 +(下一步做什麼) +## 注意 +(試過不行的做法、不要再做的事)"; + +/// A summary shorter than this (of a long stretch) is asked for once more. +const SUMMARY_MIN_CHARS: usize = 200; +/// The person's own words kept word for word under a summary: the newest this many, each clipped. +const SUMMARY_PERSON_WORDS: usize = 12; +const SUMMARY_PERSON_CHARS: usize = 400; + +thread_local! { + /// The bot whose turn runs on this thread (its background commands are named under a summary). + static TURN_BOT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The summary of `part` by the quick model (the bot's own when it has none): the sections, a +/// second try when it came back too short, then the person's own words as they wrote them and +/// the background commands still running (both from AnyBot, not the model: they can't be lost). +pub fn summarize(base: &ChatRequest, quick: Option<&str>, part: &[Message], cancel: &AtomicBool, quiet: &dyn Fn(StreamEvent)) -> Option { + let flat = flatten(part); + let ask = |extra: &str| { + let req = ChatRequest { + system: SUMMARY_SYSTEM.into(), + history: vec![Message::user(&format!("請整理下面這段對話:{extra}\n\n{flat}"))], + tools: vec![], + model: quick.map(String::from).unwrap_or_else(|| base.model.clone()), + effort: String::new(), + ..base.clone() + }; + providers::run_step(&req, cancel, quiet).ok().map(|o| o.text.trim().to_string()) + }; + let mut text = ask("")?; + if text.chars().count() < SUMMARY_MIN_CHARS && flat.chars().count() > SUMMARY_MIN_CHARS * 10 && !cancel.load(Ordering::Relaxed) { + if let Some(again) = ask("(上一次整理得太短,請照段落寫完整)").filter(|t| t.chars().count() > text.chars().count()) { + text = again; + } + } + if text.is_empty() || cancel.load(Ordering::Relaxed) { + return None; + } + Some(with_what_must_stay(&text, part, TURN_BOT.with(|b| b.get()))) +} + +/// The bot whose summaries this thread writes (its background commands are named under them). +pub fn set_turn_bot(bot: u64) { + TURN_BOT.with(|b| b.set(bot)); +} + +/// Under a summary: the person's own words (the newest, word for word) and the bot's background +/// commands still running. +pub fn with_what_must_stay(summary: &str, part: &[Message], bot: u64) -> String { + let mut out = summary.to_string(); + let said: Vec = part.iter().filter(|m| m.role == Role::User && !m.wake && !m.summary && !m.text.trim().is_empty()).map(|m| m.text.trim().chars().take(SUMMARY_PERSON_CHARS).collect::()).collect(); + if !said.is_empty() { + out.push_str("\n\n## 使用者的原話(最近的,照原文)"); + for w in said.iter().skip(said.len().saturating_sub(SUMMARY_PERSON_WORDS)) { + out.push_str(&format!("\n- 「{}」", w.replace('\n', " "))); + } + } + if bot != 0 { + let running = tools::running_for(&bot.to_string()); + if !running.is_empty() { + out.push_str("\n\n## 還在跑的背景指令(用 read_terminal 看)"); + for (id, cmd) in running { + out.push_str(&format!("\n- #{id}:{}", cmd.chars().take(120).collect::())); + } + } + } + out +} + fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option { // (The tools' descriptions go with every request too: ~12 000 tokens for a bot with all.) let tools = tools_tokens(&job.req.tools); @@ -1071,11 +1151,6 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A let cut = compaction_cut(history)?; send(StreamEvent::Retrying("對話很長了,正在把較早的內容整理成摘要…".into())); let req = ChatRequest { - system: "你負責把一段對話整理成摘要,讓之後的對話能接著進行。請用條列寫下:使用者的目標與偏好、已經做出的決定、重要的事實與數字、提到的檔案路徑與指令結果、還沒完成的事。不要加入對話裡沒有的內容。".into(), - history: vec![Message::user(&format!("請整理下面這段對話:\n\n{}", flatten(&history[..cut])))], - tools: vec![], - model: job.step_model.clone().unwrap_or_else(|| job.req.model.clone()), - effort: String::new(), ..job.req.clone() }; let quiet = |ev: StreamEvent| { @@ -1084,11 +1159,8 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A } }; job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 }); - let out = providers::run_step(&req, cancel, &quiet).ok()?; - if out.text.trim().is_empty() || cancel.load(Ordering::Relaxed) { - return None; - } - let summary = Message { role: Role::Assistant, text: out.text.trim().to_string(), summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() }; + let text = summarize(&req, job.step_model.as_deref(), &history[..cut], cancel, &quiet)?; + let summary = Message { role: Role::Assistant, text, summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() }; // The window shows the chat unfiltered (group chats drop some messages on the way here); // the timestamp of the first kept message is the landmark it can find the cut by. let boundary = history[cut].at; @@ -1243,25 +1315,15 @@ fn turn_cut(h: &[Message]) -> Option<(usize, usize)> { fn compact_within_turn(job: &Job, history: &mut Vec, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option { let (ask, cut) = turn_cut(history)?; send(StreamEvent::Retrying("對話太長了,正在把這一輪較早的步驟整理成摘要…".into())); - let req = ChatRequest { - system: "你負責把一段對話整理成摘要,讓之後的對話能接著進行。請用條列寫下:使用者的目標與偏好、已經做出的決定、已經完成的步驟和結果(哪些成功、哪些失敗)、重要的事實與數字、提到的檔案路徑與網址、還沒完成的事。不要加入對話裡沒有的內容。".into(), - history: vec![Message::user(&format!("請整理下面這段對話:\n\n{}", flatten(&history[..cut])))], - tools: vec![], - model: job.step_model.clone().unwrap_or_else(|| job.req.model.clone()), - effort: String::new(), - ..job.req.clone() - }; + let req = ChatRequest { ..job.req.clone() }; let quiet = |ev: StreamEvent| { if matches!(ev, StreamEvent::Alive | StreamEvent::Retrying(_)) { send(StreamEvent::Alive); } }; job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 }); - let out = providers::run_step(&req, cancel, &quiet).ok()?; - if out.text.trim().is_empty() || cancel.load(Ordering::Relaxed) { - return None; - } - let summary = Message { role: Role::Assistant, text: out.text.trim().to_string(), summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() }; + let text = summarize(&req, job.step_model.as_deref(), &history[..cut], cancel, &quiet)?; + let summary = Message { role: Role::Assistant, text, summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() }; let request = history[ask].clone(); history.splice(..cut, [summary, request]); Some(cut) @@ -1626,6 +1688,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let _screens = ScreensBack(bot_id); let mut job = job; crate::providers::set_patient(job.unattended); + TURN_BOT.with(|b| b.set(bot_id)); let send = |ev: StreamEvent| { let _ = tx.send((bot_id, ev)); ctx.request_repaint(); @@ -5524,6 +5587,26 @@ echo 'done送出了' > done.html; (setsid pyt let _ = std::fs::remove_dir_all(&w); } + /// R4: a summary that comes back too short is asked for once more; under it, the person's + /// own words as they wrote them (the newest) — from AnyBot, so they can't be lost. + #[test] + fn a_summary_keeps_the_persons_words_and_is_not_too_short() { + use crate::testkit::{Fake, Reply}; + let long = "## 使用者要的\n- 把部落格搬到新主機\n".repeat(20); + let fake = Fake::openai(vec![Reply::text("太短"), Reply::text(&long)]); + let req = ChatRequest { kind: ProviderKind::Custom, base_url: fake.base(), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![], tools: vec![], session: String::new(), effort: String::new() }; + let mut part = vec![]; + for i in 0..30 { + part.push(Message::user(&format!("第 {i} 件事:請把這個資料夾裡的檔案整理好,留下最新的版本,其他移到封存。"))); + part.push(Message::assistant(&format!("好,第 {i} 件做完了,移了 3 個檔案到封存。"), "m")); + } + let out = summarize(&req, None, &part, &AtomicBool::new(false), &|_| {}).unwrap(); + assert!(out.starts_with("## 使用者要的"), "the longer, second answer: {out}"); + assert_eq!(fake.requests(), 2); + assert!(out.contains("## 使用者的原話(最近的,照原文)") && out.contains("「第 29 件事") && !out.contains("「第 17 件事"), "the newest 12: {out}"); + assert_eq!(fake.bodies.lock().unwrap()[0]["messages"][0]["content"].as_str().map(|s| s.contains("## 還沒完成的")), Some(true), "the sections are asked for"); + } + /// 問題卡: the turn waits on the card; the answers come back numbered, a skip says so. #[test] fn a_question_card_waits_and_brings_back_the_answers() { @@ -5683,7 +5766,7 @@ echo 'done送出了' > done.html; (setsid pyt /// step is asked again (with the summary), instead of the turn failing. #[test] fn an_overflow_folds_the_chat_and_asks_again() { - let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), sse_text("摘要:問過六個問題"), sse_text("好了")]); + let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), sse_text(&format!("摘要:問過六個問題。{}", "(這段摘要夠長,不會被要求再寫一次)".repeat(12))), sse_text("好了")]); let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: long_chat(), tools: vec![], session: String::new(), effort: String::new() }, ..test_job() }; let (evs, _) = drive(job, ApprovalAnswer::Reject); assert!(matches!(evs.last(), Some(StreamEvent::Done)), "{:?}", evs.iter().filter_map(|e| if let StreamEvent::Error(e) = e { Some(e.clone()) } else { None }).collect::>()); @@ -5694,7 +5777,8 @@ echo 'done送出了' > done.html; (setsid pyt assert_eq!(texts, vec!["好了"]); let seen = seen.lock().unwrap(); assert_eq!(seen.len(), 3); - assert!(seen[2].contains("摘要:問過六個問題") && !seen[2].contains("第 0 個問題"), "{}", seen[2]); + // The folded answers are gone; the person's own words stay, word for word, under the summary. + assert!(seen[2].contains("摘要:問過六個問題") && !seen[2].contains("第 0 個回答") && seen[2].contains("## 使用者的原話") && seen[2].contains("「第 0 個問題」"), "{}", seen[2]); } /// jenny-Host, 2026-11-14 18:10: one screenshot took a request to a gateway that reads it as @@ -5730,7 +5814,7 @@ echo 'done送出了' > done.html; (setsid pyt /// earlier steps are summarized inside it — the request stays, the newest steps stay. #[test] fn a_long_turn_with_one_request_is_summarized_inside_itself() { - let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), (400, OVERFLOW_BODY.into()), sse_text("摘要:前面的步驟做完了"), sse_text("完成")]); + let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), (400, OVERFLOW_BODY.into()), sse_text(&format!("摘要:前面的步驟做完了。{}", "(這段摘要夠長,不會被要求再寫一次)".repeat(12))), sse_text("完成")]); let mut history = vec![Message::user("把十件事做完")]; for i in 0..10 { let call = ToolCall { id: format!("c{i}"), name: "shell".into(), args: serde_json::json!({"command": format!("echo step-{i}")}).to_string(), status: ToolStatus::Done }; diff --git a/src/app.rs b/src/app.rs index 0794b64..1fc793d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -43,6 +43,7 @@ mod voice_ui; mod drops_ui; mod memory_ui; mod goal_ui; +mod context_ui; mod doctor_ui; mod plan_ui; mod mood_ui; @@ -211,6 +212,9 @@ 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>>, + /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). + #[allow(clippy::type_complexity)] + compact_out: Arc)>>>, /// Bots whose running turn came from someone else's message (a channel, a teammate): /// 一律放行 doesn't answer for them. strangers: std::collections::HashSet, @@ -490,6 +494,7 @@ impl App { want_direct: Default::default(), strangers: Default::default(), doctor_out: Default::default(), + compact_out: Default::default(), managed: if demo { policy::Managed::default() } else { policy::read() }, settings_was_open: false, exe_built: crate::version::exe_modified(), @@ -1421,7 +1426,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)); + 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")); 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())); } @@ -1476,6 +1481,18 @@ impl App { 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. @@ -5969,8 +5986,9 @@ impl App { if !self.demo { self.tell_crashes(); } - // 診斷: a 「/doctor」 that finished. + // 診斷: a 「/doctor」 that finished; a 「/compact」 too. self.doctor_tick(); + self.compact_tick(); // A screen of another AnyBot's brain: its bots work there, not here. if self.mir.on { self.remote_tick(ctx); @@ -8069,6 +8087,53 @@ mod tests { assert_eq!(app.state.bot(id).unwrap().name, name); } + /// R4: 「/context」 says how full the chat is; 「/compact」 folds the older part into a summary + /// now (the person's words kept under it) and says so — the chat stays whole, the model reads + /// from the summary on. + #[test] + fn context_and_compact_from_the_chat() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-compact.png"))); + let fake = crate::testkit::Fake::openai(vec![crate::testkit::Reply::text(&"## 使用者要的\n- 整理資料夾\n".repeat(30))]); + app.state.provider_mut(crate::providers::ProviderKind::Custom).base_url = fake.base(); + let id = app.state.bots[0].id; + { + let b = app.state.bot_mut(id).unwrap(); + b.provider = crate::providers::ProviderKind::Custom; + b.model = "m".into(); + b.step_model = "off".into(); + b.messages.clear(); + for i in 0..20 { + b.messages.push(Message { at: 1_000 + i * 2, ..Message::user(&format!("第 {i} 個問題")) }); + b.messages.push(Message { at: 1_001 + i * 2, ..Message::assistant(&format!("第 {i} 個回答"), "m") }); + } + } + let say = |app: &mut super::App, t: &str| { + app.drafts.insert(id, t.into()); + app.send(&ctx, id); + }; + say(&mut app, "/context"); + assert!(app.state.bot(id).unwrap().messages.last().is_some_and(|m| m.note && m.text.contains("token") && m.text.contains("/compact"))); + let before = app.state.bot(id).unwrap().messages.len(); + say(&mut app, "/compact"); + let mut done = false; + for _ in 0..200 { + app.compact_tick(); + if app.state.bot(id).unwrap().messages.iter().any(|m| m.note && m.text.starts_with("已整理")) { + done = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + assert!(done, "the summary came back"); + let b = app.state.bot(id).unwrap(); + let s = b.messages.iter().find(|m| m.summary).expect("a summary in the chat"); + assert!(s.text.starts_with("## 使用者要的") && s.text.contains("## 使用者的原話") && s.text.contains("「第"), "{}", s.text); + // (Nothing leaves the chat: the model reads from the summary on.) + let view = b.messages.len() - crate::model::model_view_start(&b.messages); + assert!(b.messages.len() > before && view < before / 2, "the model's view got short ({view} of {})", b.messages.len()); + } + /// E10: `anybot --ask` reads its options anywhere among the words, and says by its exit /// code how the turn went. #[test] @@ -8495,7 +8560,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"]); + 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!["週報"], "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 6bd52e9..24a3c3b 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); 6] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟")]; +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", "現在就把較早的對話整理成摘要")]; /// 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/context_ui.rs b/src/app/context_ui.rs new file mode 100644 index 0000000..ae76f38 --- /dev/null +++ b/src/app/context_ui.rs @@ -0,0 +1,86 @@ +// 對話的長度 (R4): 「/context」 says how much of what the model can read this chat uses, and +// 「/compact」 folds its older part into a summary now (on a thread, by the quick model), the same +// way a turn does it at COMPACT_THRESHOLD_PERCENT (agent::summarize). + +use super::*; + +impl App { + /// 「/context」: a line in this chat. + pub(super) fn context_note(&mut self, bot_id: u64) { + let Some(b) = self.state.bot(bot_id) else { return }; + let start = crate::model::model_view_start(&b.messages); + let used = agent::history_tokens("", &b.messages[start..]); + let limit = b.context_tokens.max(4_000); + let text = format!( + "這個對話(模型看得到的部分)約 {} token,{} 可讀 {} token,約 {}%(系統指示和工具說明另外大約幾千到一萬多 token)。到 {}% 會自動把較早的內容整理成摘要;要現在整理打 /compact。", + used, + b.model, + limit, + used * 100 / limit, + agent::COMPACT_THRESHOLD_PERCENT + ); + self.goal_note(bot_id, &text); + self.dirty = true; + } + + /// 「/compact」: the older part of this chat into a summary now (compact_tick takes it in). + pub(super) fn compact_now(&mut self, bot_id: u64) { + let Some(b) = self.state.bot(bot_id).cloned() else { return }; + if self.streams.contains_key(&bot_id) { + self.goal_note(bot_id, &format!("{} 正在做事:等它做完再 /compact(太長時它自己也會整理)。", b.name)); + return; + } + let start = crate::model::model_view_start(&b.messages); + let view: Vec = b.messages[start..].iter().filter(|m| !m.note).cloned().collect(); + let Some(cut) = agent::compaction_cut(&view) else { + self.goal_note(bot_id, "對話還很短,不用整理。"); + return; + }; + let ps = self.state.provider(b.provider); + let req = ChatRequest { + kind: b.provider, + base_url: providers::resolve_base(b.provider, &ps.base_url), + api_key: providers::resolve_key_for(b.provider, &ps.api_key, &ps.base_url), + model: b.model.clone(), + system: String::new(), + history: vec![], + tools: vec![], + session: format!("anybot-bot-{bot_id}"), + effort: String::new(), + }; + let quick = match b.step_model.trim() { + "off" => None, + "" => b.provider.quick_model(&b.model).map(String::from), + m if m == b.model => None, + m => Some(m.to_string()), + }; + self.goal_note(bot_id, "正在把較早的對話整理成摘要…"); + let (out, repaint) = (self.compact_out.clone(), self.repaint_fn()); + std::thread::spawn(move || { + agent::set_turn_bot(bot_id); + let cancel = AtomicBool::new(false); + let got = agent::summarize(&req, quick.as_deref(), &view[..cut], &cancel, &|_| {}); + out.lock().unwrap().push((bot_id, got.map(|text| (cut, Message { role: Role::Assistant, text, summary: true, via: b.model.clone(), at: crate::model::now_ms(), ..Default::default() }, view[cut].at)))); + repaint(); + }); + self.dirty = true; + } + + /// A finished 「/compact」: the summary takes the older part's place (as a turn's does). + pub(super) fn compact_tick(&mut self) { + let done = std::mem::take(&mut *self.compact_out.lock().unwrap()); + for (bot_id, got) in done { + match got { + Some((n, summary, boundary)) => { + if let Some(b) = self.state.bot_mut(bot_id) { + crate::model::fold_in(&mut b.messages, n, summary, boundary); + } + self.goal_note(bot_id, &format!("已整理:較早的 {n} 則訊息換成一段摘要(你說過的話照原文留在摘要下面)。")); + } + None => self.goal_note(bot_id, "沒有整理成:模型沒有回應,稍後再試。"), + } + self.dirty = true; + self.save_now = true; + } + } +} diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index e1ef3ce..1efc019 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -557,6 +557,17 @@ impl App { 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); diff --git a/src/tools.rs b/src/tools.rs index 2851a77..cff121c 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -1394,6 +1394,14 @@ fn room_for_terminal() -> bool { const NO_ROOM: &str = "背景已經有太多指令在跑了,這個沒有留在背景(已停掉)。先看看哪些不用了:對它們用 write_terminal 的 stop: true 停掉,再試一次。"; +/// A bot's background commands still running: (id, command). +pub fn running_for(conversation: &str) -> Vec<(u64, String)> { + let t = terminals().lock().unwrap_or_else(|e| e.into_inner()); + let mut v: Vec<(u64, String)> = t.iter().filter(|(_, x)| x.conversation == conversation && x.exit.lock().map(|e| e.is_none()).unwrap_or(false)).map(|(id, x)| (*id, x.command.clone())).collect(); + v.sort(); + v +} + fn terminals() -> &'static Mutex> { static T: OnceLock>> = OnceLock::new(); T.get_or_init(|| Mutex::new(HashMap::new()))