AnyBot/src/goal.rs

481 lines
24 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 自己說「做完了」「應該可以了」不算證據。
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
- 最後的「系統統計」是 AnyBot 從工具紀錄算出來的,不是 bot 說的:bot 說的數字(送出幾則、做了幾個)和它對不上時,以系統統計為準,不能判 met。
- 目標裡有輪數或時間的限制(例如「最多 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).
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
/// Sends listed under the judge's 系統統計 (the newest).
const SENDS_LISTED: usize = 20;
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() {
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
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>());
}
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
// What the steps really did, counted from them (evidence.rs): never cut, it is the check.
let t = crate::evidence::tally(&msgs[start..]);
let mut stats = format!("共 {} 步,{} 步失敗或被拒絕;成功送出 {} 次", t.steps, t.failed, t.sent);
for s in t.sends.iter().rev().take(SENDS_LISTED).rev() {
stats.push_str(&format!("\n· {}", clip(s, ARGS_CHARS)));
}
format!(
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
"目標:{}\n\n目標設定了 {},現在是第 {} 輪剛結束。\n\n對話紀錄:\n\n{chat}\n\n【系統統計(AnyBot 從工具紀錄算出,不是 bot 說的)】\n{stats}\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::*;
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
/// The judge reads the bot's words as words, and the system's own count of what was sent.
#[test]
fn the_judge_gets_the_systems_count_not_only_the_bots_word() {
use crate::model::{ToolCall, ToolStatus};
let g = Goal::new("拾日 2 則留言送出", 0);
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
let call = |id: &str, key: &str, st: ToolStatus| ToolCall { id: id.into(), name: "browser_press".into(), args: format!(r#"{{"key":"{key}"}}"#), status: st };
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
let msgs = vec![
Message { at: 1, ..Message::user("發") },
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
Message { at: 2, tool_calls: vec![call("c1", "ctrl+Return", ToolStatus::Done), call("c2", "ctrl+Return", ToolStatus::Failed)], ..Message::assistant("", "") },
Message { sent: "回覆 https://www.threads.com/@a/post/X1 → https://www.threads.com/@shiri.days__/post/Y9".into(), ..Message::tool_result("c1", "browser_press", "已按") },
Message::tool_result("c2", "browser_press", "找不到"),
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
Message { at: 3, ..Message::assistant("拾日:2 則已送出", "") },
];
let b = brief(&g, &msgs, 10);
assert!(b.contains("【bot 的說法(不是證據)】拾日:2 則已送出"), "{b}");
assert!(b.contains("成功送出 1 次") && b.contains("1 步失敗"), "{b}");
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
assert!(b.contains("@shiri.days__/post/Y9"), "the judge sees where it went: {b}");
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
assert!(JUDGE_SYSTEM.contains("以系統統計為準"));
}
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);
}
}