// 目標 (/goal) in the window: 「/goal …」 typed to this brain (here, on one of its screens, on the // phone), the check after each turn, and the line above the input. What a goal is, how it is // judged and when it stops: goal.rs. // // The loop: a turn ends (settle) → its goal, if one is going, is checked by a second model on a // thread of its own (goal_tick → goal_judge) → the verdict comes back as StreamEvent::Goal // (goal_verdict) → not yet: AnyBot's 「[目標]還沒達成:…」 wakes the bot for another turn; met, // impossible or paused: a line in the chat (a note, never sent to the model) and, when the // person is away, a notification. Only a brain does this: a screen's turns run on its brain. use super::*; use crate::goal::{self, Command, Goal, Judged, Next}; /// The judge's answer, after up to JUDGE_LOOKS rounds of looking for itself with the read-only /// tools (anything else it asks for is refused, not run). pub(super) fn judge_with_looks(req: &ChatRequest, target: Option<&crate::tools::Target>, bot_id: u64, cancel: &AtomicBool) -> Result { let mut req = req.clone(); for round in 0..=goal::JUDGE_LOOKS { if round == goal::JUDGE_LOOKS { // Out of looks: it says now, without tools. req.tools.clear(); req.history.push(Message::user("查證的次數用完了。現在只回 JSON。")); } let out = providers::run_step(&req, cancel, &|_| {})?; if out.tool_calls.is_empty() { return Ok(out.text); } req.history.push(Message { tool_calls: out.tool_calls.clone(), blocks: out.blocks.clone(), ..Message::assistant(&out.text, &req.model) }); for c in &out.tool_calls { let (text, _) = match (c.name.as_str(), target) { ("web_fetch", _) => crate::web::run("web_fetch", &c.args, cancel), // (Only what a bot may read without asking: inside the work folder, never a secret.) (n, Some(t)) if goal::JUDGE_TOOLS.contains(&n) && !matches!(crate::tools::decide_on(n, &c.args, t, &[]), crate::tools::Decision::Allow) => ("檢查目標時只能看工作資料夾裡、不是私密的檔案;這個不能看。".to_string(), false), (n, Some(t)) if goal::JUDGE_TOOLS.contains(&n) => crate::tools::run_on(n, &c.args, t, cancel, &crate::tools::RunIds { conversation: bot_id.to_string(), request: format!("judge-{}", c.id) }), _ => (format!("檢查目標時不能用「{}」:只能用 {}。", c.name, goal::JUDGE_TOOLS.join("、")), false), }; req.history.push(Message::tool_result(&c.id, &c.name, &crate::tools::head_tail(&text))); } } Err("檢查目標時一直在查證,沒有給答案".into()) } impl App { /// 「/goal …」: show, clear, or set the goal and start on it. pub(super) fn goal_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: Command, text: &str, attachments: Vec, picks: Option>) { let now = crate::model::now_ms(); let Some(b) = self.state.bot(bot_id) else { return }; match cmd { Command::Status => { let s = goal::status(b.goal.as_ref(), now); self.goal_note(bot_id, &s); } Command::Clear => { let s = match self.state.bot_mut(bot_id).and_then(|b| b.goal.take()) { Some(g) => format!("已清除目標:{}", g.condition), None => "沒有設定目標。".into(), }; self.goal_checking.remove(&bot_id); self.goal_note(bot_id, &s); } Command::Set(cond) => { if !b.members.is_empty() { self.goal_note(bot_id, "群組聊天還不能設目標。"); return; } if cond.chars().count() > goal::MAX_CONDITION_CHARS { self.goal_note(bot_id, &format!("目標太長了(最多 {} 字)。", goal::MAX_CONDITION_CHARS)); return; } self.goal_checking.remove(&bot_id); if self.streams.contains_key(&bot_id) { // Working: the running turn hears it at its next step, and its end is the // first one checked. if let Some(b) = self.state.bot_mut(bot_id) { b.goal = Some(Goal::new(&cond, now)); } self.queue_steer(bot_id, text.trim().to_string(), attachments); } else { let m = Message { goal: cond.clone(), ..person_message(&self.state, bot_id, text.trim(), attachments, picks) }; if let Some(b) = self.state.bot_mut(bot_id) { b.goal = Some(Goal::new(&cond, m.at)); b.messages.push(m); } self.start_reply(ctx, bot_id); } } } self.dirty = true; self.save_now = true; } /// The person wrote to the bot (not 「/goal」): a paused goal goes on with this turn. pub(super) fn goal_heard(&mut self, bot_id: u64) { if let Some(g) = self.state.bot_mut(bot_id).and_then(|b| b.goal.as_mut()) { g.resume(); } } /// 清除目標 above the input: on a screen the brain clears it, as if typed there. pub(super) fn goal_clear(&mut self, ctx: &egui::Context, bot_id: u64) { if self.mir.on { self.mirror_send(bot_id, "/goal clear".into(), vec![], None); return; } self.goal_command(ctx, bot_id, Command::Clear, "/goal clear", vec![], None); } /// AnyBot's own line in the chat. While the bot works, its newest message is the one the /// words stream into, so the line goes just before it. pub(super) fn goal_note(&mut self, bot_id: u64, text: &str) { let streaming = self.streams.contains_key(&bot_id); let selected = self.state.selected; if let Some(b) = self.state.bot_mut(bot_id) { let m = Message { note: true, ..Message::assistant(text, "") }; let at = note_index(&b.messages, streaming); b.messages.insert(at, m); if bot_id != selected { b.unread = true; } } self.dirty = true; } /// Tell the person how the goal stands, the way a finished turn is told (only when away). fn goal_tell(&self, bot_id: u64, title: &str, note: &str) { if self.demo || !(self.away() && self.state.notify) { return; } let body = first_line(¬e.replace('\n', " "), 120); if !self.headless { notify::banner_for(title, &body, true, Some(bot_id)); } crate::remote::notify(crate::remote::Notice::Done, title, &body, bot_id); } /// 清除聊天記錄 / 開始新對話: the goal goes with the chat it was set in (Claude Code's /clear /// removes it too). Before the turn is stopped, so stopping doesn't leave a 「目標暫停」 line /// in the new chat. pub(super) fn goal_drop(&mut self, bot_id: u64) { if let Some(b) = self.state.bot_mut(bot_id) { b.goal = None; // 計畫 too: it was about that chat. b.plan = None; } self.goal_checking.remove(&bot_id); self.goal_due.retain(|(id, _)| *id != bot_id); } /// 停止 pressed between two turns of a goal (the check is reading the chat; nothing is /// running to stop): the goal pauses, or the next turn would start a moment later anyway. pub(super) fn goal_stop(&mut self, bot_id: u64) { if self.streams.contains_key(&bot_id) || !self.goal_pending(bot_id) { return; } self.goal_checking.remove(&bot_id); self.goal_due.retain(|(id, _)| *id != bot_id); let Some(g) = self.state.bot_mut(bot_id).and_then(|b| b.goal.as_mut()).filter(|g| g.active()) else { return }; let note = goal::after_trouble(g, true); self.goal_note(bot_id, ¬e); self.save_now = true; } /// A turn of this bot's goal has ended and its check hasn't spoken yet. pub(super) fn goal_pending(&self, bot_id: u64) -> bool { self.goal_checking.contains(&bot_id) || self.goal_due.iter().any(|(id, _)| *id == bot_id) } /// Turns that ended since the last frame: check the ones working toward a goal. pub(super) fn goal_tick(&mut self, ctx: &egui::Context) { for (bot_id, outcome) in std::mem::take(&mut self.goal_due) { // Another turn is on its way (typed meanwhile, the next group member): its end is // the one checked. if self.streams.contains_key(&bot_id) || self.pending_turns.iter().any(|(id, _)| *id == bot_id) || self.group_next.contains(&bot_id) { continue; } let Some(b) = self.state.bot_mut(bot_id) else { continue }; let Some(g) = b.goal.as_mut().filter(|g| g.active()) else { continue }; match outcome { TurnOutcome::Success => { let start = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0); g.after_turn(b.messages[start..].iter().any(|m| m.role == Role::Assistant && !m.tool_calls.is_empty())); let g = g.clone(); self.goal_judge(ctx, bot_id, g); } TurnOutcome::Cancelled | TurnOutcome::Error => { let note = goal::after_trouble(g, outcome == TurnOutcome::Cancelled); let title = format!("{} 的目標暫停了", b.name); self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &title, ¬e); } } self.dirty = true; } } /// Ask the bot's quick model (or its own, as its 執行步驟用的模型 setting says) whether the /// goal holds, on a thread; the answer comes back as StreamEvent::Goal. fn goal_judge(&mut self, ctx: &egui::Context, bot_id: u64, g: Goal) { let Some(b) = self.state.bot(bot_id) else { return }; let ps = self.state.provider(b.provider); let model = match b.step_model.trim() { "off" => b.model.clone(), "" => b.provider.quick_model(&b.model).map(String::from).unwrap_or_else(|| b.model.clone()), m => m.to_string(), }; let own = 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, system: goal::JUDGE_SYSTEM.into(), history: vec![Message::user(&goal::brief(&g, &b.messages, crate::model::now_ms()))], tools: vec![], session: format!("anybot-goal-{bot_id}"), effort: String::new(), }; // It may look for itself (R5): read files and folders where the bot works, read public // pages — nothing that changes anything. let targets = self.targets_for(b); let roles = self.roles_for(b, &targets); let (chosen, _) = Self::chosen_computer(b, &targets, &roles); let target = targets.iter().find(|t| t.name == chosen).cloned(); let tools: Vec = match &target { Some(t) => crate::tools::specs_for(std::slice::from_ref(&t.name), &t.name).into_iter().chain(crate::web::specs_for(&[], "")).filter(|s| goal::JUDGE_TOOLS.contains(&s["name"].as_str().unwrap_or(""))).collect(), None => vec![], }; let own = ChatRequest { tools, ..own }; // A model of another family when the person has one: a bot's own model grades its own // work too kindly (pstack's judges are from a different family). Its own, if that fails. let mut tries: Vec = self.judge_elsewhere(b.provider).map(|(kind, base_url, api_key, model)| ChatRequest { kind, base_url, api_key, model, ..own.clone() }).into_iter().collect(); tries.push(own); self.goal_checking.insert(bot_id); let (tx, ctx) = (self.tx.clone(), ctx.clone()); std::thread::spawn(move || { let cancel = AtomicBool::new(false); let mut judged = Judged::Failed("沒有可以檢查的模型".into()); for req in &tries { match judge_with_looks(req, target.as_ref(), bot_id, &cancel) { Ok(text) => { judged = goal::read_verdict(&text); break; } Err(e) => { log::warn!("AnyBot:用 {} 檢查目標沒有回應:{e}", req.model); judged = Judged::Failed(e); } } } log::info!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}"); let _ = tx.send((bot_id, 0, StreamEvent::Goal(g.since, judged))); ctx.request_repaint(); }); } /// Another provider the person has set up, for judging a bot's goal: (kind, base url, key, /// model). Not a local Ollama model (small ones judge poorly), not the bot's own provider. pub(super) fn judge_elsewhere(&self, own: ProviderKind) -> Option<(ProviderKind, String, String, String)> { providers::ALL_PROVIDERS.into_iter().filter(|k| *k != own && *k != ProviderKind::Ollama).find_map(|kind| { let ps = self.state.provider(kind); let key = providers::resolve_key_for(kind, &ps.api_key, &ps.base_url); let usable = if kind == ProviderKind::Custom { !ps.base_url.trim().is_empty() } else { !kind.needs_key() || !key.is_empty() }; if !usable || (kind.needs_key() && key.is_empty()) { return None; } let model = if ps.default_model.trim().is_empty() { kind.suggested_model().to_string() } else { ps.default_model.trim().to_string() }; Some((kind, providers::resolve_base(kind, &ps.base_url), key, model)) }) } /// The check has spoken: another turn, or a line saying it is over or paused. pub(super) fn goal_verdict(&mut self, ctx: &egui::Context, bot_id: u64, since: i64, judged: Judged) { self.goal_checking.remove(&bot_id); // The person already started another turn: its end is checked instead. if self.streams.contains_key(&bot_id) { return; } let Some(b) = self.state.bot_mut(bot_id) else { return }; let name = b.name.clone(); // Cleared, set again or stopped while it was being checked. let Some(g) = b.goal.as_mut().filter(|g| g.since == since && g.active()) else { return }; let next = goal::after_verdict(g, judged, crate::model::now_ms()); let condition = g.condition.clone(); match next { Next::Over { note, title } => { b.goal = None; self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &format!("{name} {title}"), ¬e); self.confetti = Some((bot_id, Instant::now())); } Next::Pause { note, title } => { self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &format!("{name} {title}"), ¬e); } Next::Again { text } => self.wake(ctx, bot_id, Message { wake: true, goal: condition, ..Message::user(&text) }), } self.dirty = true; self.save_now = true; } /// The line above the input while there is a goal: how it stands (the goal and the newest /// check on hover) and 清除目標. The words end in … before the button on a narrow window. pub(super) fn goal_bar(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) { let Some(g) = bot.goal.as_ref() else { return }; let p = self.pal; let now = crate::model::now_ms(); let text = if g.active() && self.goal_checking.contains(&bot.id) { t("目標 · 正在檢查有沒有達成…") } else { goal::bar_text(g, now) }; let mut tip = format!("{}{}", t("目標:"), g.condition); if !g.reason.is_empty() { tip.push_str(&format!("\n\n{}{}", t("最近一次檢查:"), g.reason)); } let col = if g.active() { p.text2 } else { p.text3 }; let mut clear = false; ui.horizontal(|ui| { ui.add_space(14.0); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.add_space(10.0); clear = small_button(ui, "清除目標", p).clicked(); ui.with_layout(Layout::left_to_right(Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 6.0; let (r, _) = ui.allocate_exact_size(vec2(13.0, 14.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Target, if g.active() { p.accent } else { col }); ui.add(egui::Label::new(RichText::new(&text).size(FONT_XS).color(col)).truncate().selectable(false)).on_hover_text(&tip); }); }); }); ui.add_space(2.0); if clear { self.goal_clear(ctx, bot.id); } if g.active() { // The minutes count on. ctx.request_repaint_after(std::time::Duration::from_secs(30)); } } /// A goal's line in the chat (AnyBot's, not the bot's): small, in the middle. pub(super) fn goal_note_row(&self, ui: &mut egui::Ui, m: &Message) { let p = self.pal; ui.add_space(2.0); ui.vertical_centered(|ui| { let w = message_max_width(ui.available_width()); ui.set_max_width(w); Frame::new().fill(p.hover).corner_radius(R_M).inner_margin(Margin::symmetric(12, 7)).show(ui, |ui| { ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = 6.0; let (r, _) = ui.allocate_exact_size(vec2(13.0, 16.0), egui::Sense::hover()); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Target, p.text3); ui.add(egui::Label::new(RichText::new(&m.text).size(FONT_SM).line_height(Some(18.0)).color(p.text2)).wrap()); }); }); }); ui.add_space(10.0); } } /// Where AnyBot's own line goes in a chat. At the end — but never between a step and its result /// or after the reply being written (while the bot works, the newest message is the one its /// words stream into), and above a 「繼續」 card, which has to stay the newest thing to be pressed. pub(super) fn note_index(msgs: &[Message], streaming: bool) -> usize { let mut i = msgs.len(); if streaming { while i > 0 && msgs[i - 1].role == Role::Tool { i -= 1; } i = i.saturating_sub(1); } else if msgs.last().is_some_and(|m| m.interrupted) { i -= 1; } i } #[cfg(test)] mod tests { use super::*; /// R5: the judge looks for itself (a file where the bot works) before it answers; a step /// that would change something is refused, not run. #[test] fn the_judge_looks_for_itself_read_only() { use crate::testkit::{Fake, Reply}; let w = std::env::temp_dir().join(format!("anybot-judge-{}", std::process::id())); let _ = std::fs::remove_dir_all(&w); std::fs::create_dir_all(&w).unwrap(); std::fs::write(w.join("report.txt"), "全部 340 個測試通過").unwrap(); let fake = Fake::openai(vec![ Reply::call("j1", "read_file", serde_json::json!({"path": "report.txt"})), Reply::call("j2", "shell", serde_json::json!({"command": "touch made.txt"})), Reply::text(r#"{"verdict":"met","reason":"report.txt 寫全部通過"}"#), ]); let t = crate::tools::Target { name: "這台".into(), place: crate::tools::Place::Local { workdir: w.clone() } }; let req = ChatRequest { kind: crate::providers::ProviderKind::Custom, base_url: fake.base(), api_key: String::new(), model: "m".into(), system: goal::JUDGE_SYSTEM.into(), history: vec![Message::user("目標:所有測試都通過")], tools: vec![], session: String::new(), effort: String::new() }; let text = judge_with_looks(&req, Some(&t), 1, &AtomicBool::new(false)).unwrap(); assert!(text.contains("\"met\""), "{text}"); let bodies = fake.bodies.lock().unwrap().clone(); assert!(bodies[1].to_string().contains("全部 340 個測試通過"), "the file it read went back to it"); assert!(bodies[2].to_string().contains("檢查目標時不能用「shell」"), "refused"); assert!(!w.join("made.txt").exists(), "nothing was changed"); // A secret, or a file outside the work folder: not read for the judge. std::fs::write(w.join(".env"), "KEY=top-secret").unwrap(); let fake = Fake::openai(vec![ Reply::call("j1", "read_file", serde_json::json!({"path": ".env"})), Reply::call("j2", "read_file", serde_json::json!({"path": "/etc/hosts"})), Reply::text(r#"{"verdict":"not_met","reason":"看不到"}"#), ]); let req = ChatRequest { base_url: fake.base(), ..req }; judge_with_looks(&req, Some(&t), 1, &AtomicBool::new(false)).unwrap(); let bodies = fake.bodies.lock().unwrap().clone(); assert!(!bodies.iter().any(|b| b.to_string().contains("top-secret")) && bodies[1].to_string().contains("不能看") && bodies[2].to_string().contains("不能看"), "{bodies:?}"); let _ = std::fs::remove_dir_all(&w); } #[test] fn a_note_never_splits_a_step_from_its_result() { let user = Message::user("做事"); let step = Message { tool_calls: vec![crate::model::ToolCall { id: "1".into(), name: "shell".into(), args: "{}".into(), status: Default::default() }], ..Message::assistant("", "") }; let result = Message::tool_result("1", "shell", "ok"); let reply = Message::assistant("好了", ""); // Idle: at the end. assert_eq!(note_index(&[user.clone(), reply.clone()], false), 2); assert_eq!(note_index(&[], false), 0); // Working: before the reply being written… assert_eq!(note_index(&[user.clone(), reply.clone()], true), 1); // …and before a step whose result is the newest message. assert_eq!(note_index(&[user.clone(), step.clone(), result.clone()], true), 1); assert_eq!(note_index(&[], true), 0); // A 「繼續」 card stays the newest thing. let card = Message { interrupted: true, ..Message::assistant("被中斷了", "") }; assert_eq!(note_index(&[user, step, result, card], false), 3); } }