AnyBot/src/goal.rs

451 lines
22 KiB
Rust
Raw Normal View History

//! 目標 (/goal): a condition a bot keeps working toward, turn after turn, until a second model —
//! one that didn't do the work — reads the chat and says it holds. Claude Code's /goal
//! (code.claude.com/docs/en/goal): after every turn a small fast model judges the condition met,
//! not yet met (its reason guides the next turn, which starts by itself) or impossible.
//!
//! The goal lives on the brain, on the bot (`Bot::goal`); screens and the phone show it. The person
//! sets it with 「/goal 條件」, sees it with 「/goal」 and clears it with 「/goal clear」. Nothing
//! here draws or runs anything: the command, the judge's brief and how its answer is read, and
//! the brakes. The window runs it after each turn (app/goal_ui.rs).
//!
//! The brakes are tighter than Claude Code's: one AnyBot turn can be 100 steps on the person's own
//! keys, so a goal stops to ask after [`TURNS`] turns, after [`IDLE_TURNS`] turns that did nothing,
//! and whenever the bot is waiting for the person (a question asked in words ends the turn; going
//! on without the answer would only ask again).
use serde::{Deserialize, Serialize};
use crate::model::{Message, Role};
/// Longest condition (Claude Code: 4,000 characters).
pub const MAX_CONDITION_CHARS: usize = 4_000;
/// Turns a goal runs before it stops to ask; the person's next message gives it as many again
/// (estimated).
pub const TURNS: u32 = 20;
/// Turns in a row that used no tool before it stops: the bot is only talking to the judge.
/// (Claude Code stops after "several turns in a row" without tool use; estimated.)
pub const IDLE_TURNS: u32 = 3;
/// How much of the chat the judge reads, the newest kept (estimated).
const BRIEF_CHARS: usize = 24_000;
/// Each piece of the chat in the judge's brief, at most (estimated).
const TEXT_CHARS: usize = 2_500;
const ARGS_CHARS: usize = 300;
/// A tool's result: its start and its end (where a test run says how it went).
const RESULT_HEAD: usize = 400;
const RESULT_TAIL: usize = 1_100;
/// The tag on AnyBot's 「還沒達成」 that starts the next turn (see app::chat_ui::wake_tag).
pub const TAG: &str = "[目標]";
/// A bot's goal, kept on the bot (it survives restarts; see `pause_all`).
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct Goal {
pub condition: String,
/// When it was set (ms): the time of the person's 「/goal …」 message, where the judge's
/// reading starts.
pub since: i64,
/// Turns judged so far.
#[serde(default)]
pub turns: u32,
/// It stops to ask when `turns` reaches this.
#[serde(default)]
pub until: u32,
/// Turns in a row that used no tool.
#[serde(default)]
pub idle: u32,
/// The judge's newest reason.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
/// Not going on by itself, and why. The person's next message takes it up again.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub paused: String,
}
impl Goal {
pub fn new(condition: &str, since: i64) -> Goal {
Goal { condition: condition.trim().to_string(), since, until: TURNS, ..Default::default() }
}
pub fn active(&self) -> bool {
self.paused.is_empty()
}
/// A turn ended: did it do anything (use a tool)?
pub fn after_turn(&mut self, used_tools: bool) {
self.idle = if used_tools { 0 } else { self.idle + 1 };
}
/// The person wrote: a paused goal goes on, with as many turns again if it had used them up.
pub fn resume(&mut self) {
self.paused.clear();
self.idle = 0;
if self.turns >= self.until {
self.until = self.turns + TURNS;
}
}
}
/// What 「/goal …」 asks for.
#[derive(Debug, PartialEq)]
pub enum Command {
/// 「/goal」: how it stands.
Status,
/// 「/goal clear」 (stop, off, reset, none, cancel, 清除, 取消, 停止).
Clear,
/// 「/goal 條件」: set (or replace) the goal and start on it.
Set(String),
}
/// 「/goal」, 「/goal clear」 or 「/goal 條件」; None for anything else (「/goals」 too).
pub fn command(text: &str) -> Option<Command> {
let rest = text.trim().strip_prefix("/goal")?;
if rest.chars().next().is_some_and(|c| !c.is_whitespace()) {
return None;
}
let arg = rest.trim();
Some(match arg.to_lowercase().as_str() {
"" => Command::Status,
"clear" | "stop" | "off" | "reset" | "none" | "cancel" | "清除" | "取消" | "停止" => Command::Clear,
_ => Command::Set(arg.to_string()),
})
}
/// What the judge said.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Verdict {
Met,
NotYet,
/// The bot is waiting for the person (a question, a sign-in, a decision).
Waiting,
Impossible,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Judged {
Said(Verdict, String),
/// The judge's model didn't answer.
Failed(String),
}
/// The judge's instructions.
pub const JUDGE_SYSTEM: &str = "你是驗收員。使用者給一個 bot 設了目標,bot 剛做完一輪。你只能看下面的對話紀錄(bot 說的話、它用了哪些工具、工具回了什麼),判斷目標現在是不是已經成立。
- 只認對話裡看得到的證據:指令的輸出、測試結果、檔案內容、畫面、網頁內容。bot 自己說「做完了」「應該可以了」不算證據。
- 目標裡有輪數或時間的限制(例如「最多 10 輪」),照紀錄開頭寫的輪數和時間判斷。
- bot 在問使用者問題、等使用者決定,或要使用者做只有他能做的事(登入、付款、給密碼)才能繼續:判 waiting。
- 確定永遠做不到才判 impossible(要的東西不存在、被明確拒絕而且沒有別的路);只是還沒做完、遇到能修的錯誤,都是 not_met。
- reason 一句話,用使用者的語言:met 寫是哪個證據;not_met 寫還差什麼、下一步做什麼;waiting 寫在等使用者什麼;impossible 寫為什麼。
只回一個 JSON,不要別的字:{\"verdict\":\"met|not_met|waiting|impossible\",\"reason\":\"…\"}";
/// The judge's answer, read loosely (a model may wrap the JSON in words or a code fence). An
/// answer that can't be read counts as not yet met: the turn cap still stops it.
pub fn read_verdict(text: &str) -> Judged {
let json = text.find('{').zip(text.rfind('}')).filter(|(a, b)| a < b).and_then(|(a, b)| serde_json::from_str::<serde_json::Value>(&text[a..=b]).ok());
let Some(v) = json else {
let said = clip(&one_line(text), 200);
return Judged::Said(Verdict::NotYet, if said.is_empty() { "(檢查的模型沒有給出結果)".into() } else { said });
};
let verdict = match v["verdict"].as_str().unwrap_or("").trim().to_lowercase().replace([' ', '-'], "_").as_str() {
"met" | "achieved" | "done" | "yes" => Verdict::Met,
"waiting" | "wait" | "ask" | "needs_user" | "need_user" => Verdict::Waiting,
"impossible" | "failed" | "cannot" => Verdict::Impossible,
_ => Verdict::NotYet,
};
Judged::Said(verdict, clip(&one_line(v["reason"].as_str().unwrap_or("")), 300))
}
/// What the judge reads: the goal, how long and how many turns, and the chat since it was set
/// (the newest part when it is long).
pub fn brief(g: &Goal, msgs: &[Message], now: i64) -> String {
let start = msgs.iter().position(|m| m.at >= g.since).unwrap_or(0);
let mut parts: Vec<String> = vec![];
for m in &msgs[start..] {
if m.note || m.interrupted {
continue;
}
match m.role {
_ if m.summary => parts.push(format!("【較早的對話摘要】{}", clip(&m.text, TEXT_CHARS))),
Role::User if m.wake && m.text.starts_with(TAG) => parts.push(format!("【上一次檢查】{}", clip(m.text.trim_start_matches(TAG), TEXT_CHARS))),
Role::User => parts.push(format!("【使用者】{}", clip(&m.text, TEXT_CHARS))),
Role::Assistant => {
if !m.text.trim().is_empty() {
parts.push(format!("【bot】{}", clip(&m.text, TEXT_CHARS)));
}
for c in &m.tool_calls {
parts.push(format!("【bot 用了 {}】{}", c.name, clip(&one_line(&c.args), ARGS_CHARS)));
}
}
Role::Tool => parts.push(format!("【{} 的結果】{}", m.tool_name, head_tail(&m.text, RESULT_HEAD, RESULT_TAIL))),
}
}
let mut chat = parts.join("\n\n");
let n = chat.chars().count();
if n > BRIEF_CHARS {
chat = format!("(前面較早的部分省略)\n…{}", chat.chars().skip(n - BRIEF_CHARS).collect::<String>());
}
format!(
"目標:{}\n\n目標設定了 {},現在是第 {} 輪剛結束。\n\n對話紀錄:\n\n{chat}\n\n目標現在成立了嗎?只回 JSON。",
g.condition,
elapsed(now - g.since),
g.turns + 1
)
}
/// What happens after the judge has spoken.
#[derive(Debug, PartialEq)]
pub enum Next {
/// The goal is over (met, or never can be): clear it and say so.
Over { note: String, title: &'static str },
/// It stops going on by itself and says why (kept: the person's next message goes on).
Pause { note: String, title: &'static str },
/// Another turn, started by this message (AnyBot's, tagged 「[目標]」).
Again { text: String },
}
/// Count the turn and decide what comes next. The goal is changed in place (turns, reason,
/// paused); `Over` means the caller clears it.
pub fn after_verdict(g: &mut Goal, judged: Judged, now: i64) -> Next {
let (verdict, reason) = match judged {
Judged::Said(v, r) => (v, r),
Judged::Failed(e) => {
g.paused = "檢查目標時模型沒有回應".into();
return Next::Pause { note: format!("目標暫停:檢查目標時模型沒有回應({})。傳一句話就接著做。", clip(&one_line(&e), 160)), title: "的目標暫停了" };
}
};
g.turns += 1;
g.reason = reason.clone();
let took = format!("{} 輪 · {}", g.turns, elapsed(now - g.since));
match verdict {
Verdict::Met => Next::Over { note: format!("目標達成:{}\n{reason}({took})", g.condition), title: "達成目標了" },
Verdict::Impossible => Next::Over { note: format!("目標做不到,已清除:{}\n{reason}({took})", g.condition), title: "的目標做不到" },
Verdict::Waiting => {
g.paused = "等你回覆".into();
Next::Pause { note: format!("目標暫停,等你回覆:{reason}"), title: "在等你回覆" }
}
Verdict::NotYet if g.turns >= g.until => {
g.paused = format!("已經做了 {} 輪", g.turns);
Next::Pause { note: format!("目標暫停:已經做了 {} 輪還沒達成。最近一次檢查:{reason}\n傳一句話(例如「繼續」)就再做 {TURNS} 輪;不要了就用 /goal clear。", g.turns), title: "的目標暫停了" }
}
Verdict::NotYet if g.idle >= IDLE_TURNS => {
g.paused = format!("連續 {IDLE_TURNS} 輪沒有動手");
Next::Pause { note: format!("目標暫停:連續 {IDLE_TURNS} 輪都沒有實際動手,看起來卡住了。最近一次檢查:{reason}\n傳一句話就接著做;不要了就用 /goal clear。"), title: "的目標暫停了" }
}
Verdict::NotYet => Next::Again { text: format!("{TAG}還沒達成:{reason}") },
}
}
/// A turn ended badly: the goal stops going on by itself (kept), and the chat says why.
pub fn after_trouble(g: &mut Goal, stopped: bool) -> String {
if stopped {
g.paused = "你按了停止".into();
"目標暫停:你按了停止。傳一句話就接著做;不要了就用 /goal clear。".into()
} else {
g.paused = "這一輪出錯了".into();
"目標暫停:這一輪出錯了。傳一句話就接著做;不要了就用 /goal clear。".into()
}
}
/// AnyBot starting again: a goal that was going on has nothing running it any more (a turn cut
/// off waits for its 「繼續」, a check that was under way is lost). Say so instead of looking busy.
pub fn pause_all<'a>(goals: impl Iterator<Item = &'a mut Goal>) -> bool {
let mut changed = false;
for g in goals.filter(|g| g.active()) {
g.paused = "AnyBot 重新啟動過".into();
changed = true;
}
changed
}
/// What the model reads after the person's 「/goal …」 or AnyBot's 「還沒達成」 (app::group_history).
pub fn context_line(m: &Message) -> Option<String> {
if m.goal.is_empty() {
return None;
}
Some(if m.wake {
format!("〔目標「{}」還沒達成,上面是檢查的理由。接著做,用實際的結果證明進度;需要使用者回答或動手才能繼續,就直接問他。〕", m.goal)
} else {
format!(
"〔使用者用 /goal 設了目標:「{}」。把它做到成立為止。每一輪結束後,會有另一個模型只看這段對話判斷目標達成了沒有,沒達成就會叫你接著做;所以要用實際的結果證明(指令的輸出、測試結果、檔案內容、畫面),不能只說做完了。需要使用者回答或動手才能繼續,就直接問他。真的做不到,就說清楚為什麼。〕",
m.goal
)
})
}
/// 「/goal」 with nothing after it.
pub fn status(g: Option<&Goal>, now: i64) -> String {
let Some(g) = g else { return "沒有設定目標。用「/goal 條件」設一個,例如「/goal 所有測試都通過」。".into() };
let mut s = format!("目前的目標:{}\n已經 {} · 檢查了 {} 輪", g.condition, elapsed(now - g.since), g.turns);
if !g.reason.is_empty() {
s.push_str(&format!("\n最近一次檢查:{}", g.reason));
}
if !g.paused.is_empty() {
s.push_str(&format!("\n已暫停({}):傳一句話就接著做。", g.paused));
}
s
}
/// The one line above the input while there is a goal.
pub fn bar_text(g: &Goal, now: i64) -> String {
if g.active() {
format!("目標進行中 · {} · {} 輪", elapsed(now - g.since), g.turns)
} else {
format!("目標暫停 · {}", g.paused)
}
}
/// 「40 秒」「12 分」「1 小時 5 分」.
pub fn elapsed(ms: i64) -> String {
let s = (ms.max(0) / 1000) as u64;
match s {
0..60 => format!("{s} 秒"),
60..3600 => format!("{} 分", s / 60),
_ if s % 3600 < 60 => format!("{} 小時", s / 3600),
_ => format!("{} 小時 {} 分", s / 3600, s % 3600 / 60),
}
}
fn one_line(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn clip(s: &str, n: usize) -> String {
let s = s.trim();
if s.chars().count() <= n {
return s.to_string();
}
format!("{}…", s.chars().take(n).collect::<String>())
}
fn head_tail(s: &str, head: usize, tail: usize) -> String {
let s = s.trim();
let n = s.chars().count();
if n <= head + tail {
return s.to_string();
}
format!("{}\n…(中間省略 {} 字)…\n{}", s.chars().take(head).collect::<String>(), n - head - tail, s.chars().skip(n - tail).collect::<String>())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::ToolCall;
#[test]
fn the_command_sets_shows_and_clears() {
assert_eq!(command("/goal"), Some(Command::Status));
assert_eq!(command(" /goal "), Some(Command::Status));
assert_eq!(command("/goal clear"), Some(Command::Clear));
assert_eq!(command("/goal STOP"), Some(Command::Clear));
assert_eq!(command("/goal 取消"), Some(Command::Clear));
assert_eq!(command("/goal 所有測試都通過"), Some(Command::Set("所有測試都通過".into())));
assert_eq!(command("/goal\n多行\n條件"), Some(Command::Set("多行\n條件".into())));
// Not the command: another word, or not at the start.
assert_eq!(command("/goals"), None);
assert_eq!(command("/goalkeeper 是誰"), None);
assert_eq!(command("我的 /goal 是"), None);
assert_eq!(command("/pptx 做簡報"), None);
}
#[test]
fn the_judges_answer_is_read_loosely() {
assert_eq!(read_verdict(r#"{"verdict":"met","reason":"npm test 結束碼 0"}"#), Judged::Said(Verdict::Met, "npm test 結束碼 0".into()));
assert_eq!(read_verdict("```json\n{\"verdict\": \"not_met\", \"reason\": \"還有 2 個測試失敗\"}\n```"), Judged::Said(Verdict::NotYet, "還有 2 個測試失敗".into()));
assert_eq!(read_verdict(r#"{"verdict":"waiting","reason":"等使用者登入"}"#), Judged::Said(Verdict::Waiting, "等使用者登入".into()));
assert_eq!(read_verdict(r#"{"verdict":"impossible","reason":"沒有這個檔案"}"#), Judged::Said(Verdict::Impossible, "沒有這個檔案".into()));
// Words without JSON: not yet, with what it said.
assert_eq!(read_verdict("I think it is done"), Judged::Said(Verdict::NotYet, "I think it is done".into()));
assert!(matches!(read_verdict(""), Judged::Said(Verdict::NotYet, r) if !r.is_empty()));
}
#[test]
fn not_yet_goes_again_until_the_brakes() {
let mut g = Goal::new("測試通過", 0);
let not_yet = || Judged::Said(Verdict::NotYet, "還有 1 個失敗".into());
g.after_turn(true);
assert_eq!(after_verdict(&mut g, not_yet(), 60_000), Next::Again { text: "[目標]還沒達成:還有 1 個失敗".into() });
assert_eq!((g.turns, g.reason.as_str(), g.active()), (1, "還有 1 個失敗", true));
// Turns that do nothing: it stops after IDLE_TURNS of them.
for _ in 1..IDLE_TURNS {
g.after_turn(false);
assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Again { .. }));
}
g.after_turn(false);
assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Pause { .. }));
assert!(!g.active());
// The person writes: it goes on.
g.resume();
assert!(g.active() && g.idle == 0);
// The turn cap: stops at `until`, and a message gives it TURNS more.
g.turns = TURNS - 1;
g.after_turn(true);
assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Pause { note, .. } if note.contains(&format!("{TURNS} 輪"))));
g.resume();
assert_eq!(g.until, TURNS * 2);
assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Again { .. }));
}
#[test]
fn met_impossible_waiting_and_a_silent_judge() {
let mut g = Goal::new("測試通過", 0);
assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::Met, "全部通過".into()), 125_000), Next::Over { note, .. } if note.contains("目標達成") && note.contains("全部通過") && note.contains("1 輪 · 2 分")));
let mut g = Goal::new("找到檔案", 0);
assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::Impossible, "不存在".into()), 0), Next::Over { .. }));
let mut g = Goal::new("登入後下載", 0);
assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::Waiting, "等你登入".into()), 0), Next::Pause { .. }));
assert_eq!(g.paused, "等你回覆");
let mut g = Goal::new("x", 0);
assert!(matches!(after_verdict(&mut g, Judged::Failed("timeout".into()), 0), Next::Pause { .. }));
assert_eq!(g.turns, 0, "a check that didn't happen isn't a turn");
let mut g = Goal::new("x", 0);
assert!(after_trouble(&mut g, true).contains("停止") && !g.active());
}
#[test]
fn the_brief_reads_from_the_goal_on_and_keeps_the_newest() {
let old = Message { at: 5, ..Message::user("更早的事") };
let set = Message { at: 10, goal: "測試通過".into(), ..Message::user("/goal 測試通過") };
let call = Message { at: 11, tool_calls: vec![ToolCall { id: "1".into(), name: "shell".into(), args: r#"{"command":"cargo test"}"#.into(), status: Default::default() }], ..Message::assistant("跑測試", "") };
let out = Message { at: 12, ..Message::tool_result("1", "shell", &format!("{}\ntest result: ok. 3 passed", "x".repeat(5000))) };
let note = Message { at: 13, note: true, ..Message::assistant("目標暫停", "") };
let g = Goal::new("測試通過", 10);
let b = brief(&g, &[old, set, call, out, note], 70_010);
assert!(b.starts_with("目標:測試通過"));
assert!(b.contains("1 分") && b.contains("第 1 輪"));
assert!(!b.contains("更早的事"), "before the goal: not read");
assert!(b.contains("【bot 用了 shell】") && b.contains("cargo test"));
assert!(b.contains("test result: ok. 3 passed"), "a result's end is kept");
assert!(b.contains("中間省略"));
assert!(!b.contains("目標暫停"), "AnyBot's own lines aren't evidence");
// Long chats: the newest part.
let many: Vec<Message> = (0..200).map(|i| Message { at: 10 + i, ..Message::assistant(&format!("第{i}步 {}", "y".repeat(400)), "") }).collect();
let b = brief(&g, &many, 0);
assert!(b.contains("第199步") && !b.contains("第0步 ") && b.contains("省略"));
}
#[test]
fn a_restart_pauses_what_was_going_on() {
let mut gs = [Goal::new("a", 0), Goal { paused: "等你回覆".into(), ..Goal::new("b", 0) }];
assert!(pause_all(gs.iter_mut()));
assert_eq!(gs[0].paused, "AnyBot 重新啟動過");
assert_eq!(gs[1].paused, "等你回覆");
assert!(!pause_all(gs.iter_mut()));
}
#[test]
fn times_and_lines() {
assert_eq!(elapsed(40_000), "40 秒");
assert_eq!(elapsed(12 * 60_000 + 5_000), "12 分");
assert_eq!(elapsed(3_600_000), "1 小時");
assert_eq!(elapsed(3_900_000), "1 小時 5 分");
let g = Goal { turns: 3, ..Goal::new("x", 0) };
assert_eq!(bar_text(&g, 120_000), "目標進行中 · 2 分 · 3 輪");
assert!(status(None, 0).contains("沒有設定目標"));
assert!(status(Some(&g), 0).contains("目前的目標:x"));
let set = Message { goal: "x".into(), ..Message::user("/goal x") };
assert!(context_line(&set).unwrap().contains("使用者用 /goal 設了目標"));
let again = Message { goal: "x".into(), wake: true, ..Message::user("[目標]還沒達成:y") };
assert!(context_line(&again).unwrap().contains("還沒達成"));
assert_eq!(context_line(&Message::user("hi")), None);
}
}