AnyBot/src/followup.rs

475 lines
23 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 追進度 (follow_up): a bot that started something long — a download, a render, a training run,
//! a deploy, a job on another machine over SSH — registers how to look at it and what "done"
//! looks like, and ends its turn. The brain runs the check now and then on that computer (no
//! model in between), posts a progress line in the chat when it moved on, and wakes the bot when
//! it is done, failed, seems stuck, or ran out of time — the person never has to ask 「好了沒」.
//!
//! Before this, the bot said 「我去盯它跑」 and nothing came back: a `sleep` inside a command (cut
//! by its timeout), a 監看 that only watches this computer's own output, or a /goal judge that
//! paused after two rounds of 「還沒好」.
//!
//! The check runs unattended, again and again: registering it is asked like running that command
//! with `shell` (the window decides, app/followup_ui.rs), and it runs where `shell` would.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
pub const TOOL: &str = "follow_up";
/// Seconds between checks: at least, by default, at most.
pub const MIN_EVERY_SECS: u64 = 15;
pub const DEFAULT_EVERY_SECS: u64 = 60;
pub const MAX_EVERY_SECS: u64 = 3_600;
/// Minutes before it gives up: by default, at most.
pub const DEFAULT_GIVE_UP_MINS: u64 = 180;
pub const MAX_GIVE_UP_MINS: u64 = 1_440;
/// A progress line in the chat at most this often (only when the output moved on).
pub const REPORT_EVERY_MS: i64 = 10 * 60_000;
/// The check itself failing this many times in a row ends it.
pub const ERRORS_IN_A_ROW: u32 = 3;
/// Follow-ups one bot keeps at once.
pub const MAX_PER_BOT: usize = 8;
/// What is kept of each check's output (its end: progress lines are usually last).
const OUTPUT_KEEP: usize = 1_500;
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
pub struct FollowUp {
pub id: u64,
/// What it follows, in the person's words (「下載 Qwen Turbo」).
pub what: String,
/// The command that shows where it is now.
pub check: String,
/// The computer it runs on (empty: the bot's chosen one).
#[serde(default)]
pub computer: String,
/// Done when the output has this (text; /…/ is a regular expression).
pub done_when: String,
/// Failed when the output has this (same; empty: never).
#[serde(default)]
pub fail_when: String,
/// What the bot said it does once it is done (given back when woken).
#[serde(default)]
pub then: String,
pub every_secs: u64,
pub started_ms: i64,
pub until_ms: i64,
#[serde(default)]
pub next_ms: i64,
/// The latest output (its end) and when it last changed.
#[serde(default)]
pub last: String,
#[serde(default)]
pub last_change_ms: i64,
#[serde(default)]
pub reported_ms: i64,
#[serde(default)]
pub errors: u32,
}
impl FollowUp {
/// No change for this long reads as stuck: 15 minutes, or ten checks if they are further apart.
pub fn stall_ms(&self) -> i64 {
(15 * 60_000).max(self.every_secs as i64 * 10_000)
}
}
/// What one check says.
#[derive(Debug, PartialEq)]
pub enum Verdict {
/// Not yet; check again at next_ms.
Wait,
/// Not yet, and it moved on: a progress line for the chat (no model).
Progress(String),
Done,
Failed,
Stuck,
OutOfTime,
/// The check command itself kept failing (its last error).
CheckBroken(String),
}
pub fn spec() -> Value {
json!({"name": TOOL, "description": "追進度: follow something long that keeps going without you — a download, a render, a training run, a deploy, a job on another machine (an SSH one-liner as the check works). Register how to look at it (`check`, a quick command that prints where it is now) and what done looks like (`done_when`); then tell the person in a sentence what you are following and END YOUR TURN — do not sleep, poll in a loop or say 「我去盯」 without this. AnyBot runs the check every `every_secs` on that computer (no model in between), posts a short progress line in the chat when it moved on, and wakes you with the latest output when it is done, failed (`fail_when`), shows no change for a long while, or runs out of time — then carry on (`then` is given back to you). `stop` ends one; `list` shows them.",
"parameters": {"type": "object", "properties": {
"what": {"type": "string", "description": "What it follows, for the person (e.g. 下載 Qwen-Image Turbo、渲染第 3 版影片)."},
"check": {"type": "string", "description": "A quick command that prints the current state and exits (e.g. `du -sh /model/x`, `tail -n 3 /tmp/job.log`, `curl -s localhost:8188/history/ID`, or an SSH one-liner to another machine). Not a loop, not a sleep."},
"done_when": {"type": "string", "description": "Text in the check's output that means done (e.g. DL_DONE, \"status\": \"success\"). /…/ is a regular expression."},
"fail_when": {"type": "string", "description": "Text that means it failed (e.g. Traceback|Error). /…/ is a regular expression. Optional."},
"then": {"type": "string", "description": "What you will do once it is done (given back to you when woken). Optional."},
"every_secs": {"type": "integer", "description": "Seconds between checks (15–3600, default 60)."},
"give_up_after_mins": {"type": "integer", "description": "Minutes before it gives up and wakes you (default 180, at most 1440)."},
"computer": {"type": "string", "description": "Leave empty: checks run on your own computer. Or an SSH machine as list_computers names it (asked once). Never the person's own computers — the check repeats with nobody watching; reach those from your computer with SSH or curl."},
"stop": {"type": "integer", "description": "End the follow-up with this number instead."},
"list": {"type": "boolean", "description": "Show the follow-ups running now instead."}}}})
}
/// What a call of the tool asks for. The window decides whether to ask the person by this, and
/// the registering side does what this says — the same reading on both sides (a call with
/// `"stop": null` once read as 「stop」 for asking and as 「register」 for doing).
#[derive(Debug, PartialEq)]
pub enum Action {
List,
Stop(u64),
Register,
}
pub fn action_of(v: &Value) -> Action {
if v.get("list").and_then(Value::as_bool) == Some(true) {
return Action::List;
}
match v.get("stop").and_then(Value::as_u64) {
Some(id) => Action::Stop(id),
None => Action::Register,
}
}
/// Seconds one check may run before it is stopped (and counts as a failed check).
pub fn check_timeout_secs(every_secs: u64) -> u64 {
every_secs.clamp(10, 60)
}
/// A new follow-up from the tool's arguments.
pub fn parse(v: &Value, id: u64, now_ms: i64) -> Result<FollowUp, String> {
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::trim).unwrap_or("").to_string();
let check = s("check");
if check.is_empty() {
return Err("缺少 check:一個很快就結束、會印出現在進度的指令".into());
}
let done_when = s("done_when");
if done_when.is_empty() {
return Err("缺少 done_when:檢查的輸出裡出現什麼代表好了".into());
}
for (k, p) in [("done_when", &done_when), ("fail_when", &s("fail_when"))] {
if let Some(re) = as_regex(p) {
regex::Regex::new(re).map_err(|e| format!("{k} 的正規表示式有問題:{e}"))?;
}
}
let every_secs = v.get("every_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_EVERY_SECS).clamp(MIN_EVERY_SECS, MAX_EVERY_SECS);
let mins = v.get("give_up_after_mins").and_then(Value::as_u64).unwrap_or(DEFAULT_GIVE_UP_MINS).clamp(1, MAX_GIVE_UP_MINS);
let what = Some(s("what")).filter(|w| !w.is_empty()).unwrap_or_else(|| check.chars().take(40).collect());
Ok(FollowUp {
id,
what,
check,
computer: s("computer"),
done_when,
fail_when: s("fail_when"),
then: s("then"),
every_secs,
started_ms: now_ms,
until_ms: now_ms + mins as i64 * 60_000,
next_ms: now_ms,
last_change_ms: now_ms,
reported_ms: now_ms,
..Default::default()
})
}
/// /…/: a regular expression (what is inside).
fn as_regex(p: &str) -> Option<&str> {
p.strip_prefix('/').and_then(|r| r.strip_suffix('/')).filter(|r| !r.is_empty())
}
fn matches(pattern: &str, text: &str) -> bool {
if pattern.is_empty() {
return false;
}
match as_regex(pattern) {
Some(re) => regex::Regex::new(re).is_ok_and(|r| r.is_match(text)),
None => text.contains(pattern),
}
}
/// The end of an output, at most OUTPUT_KEEP characters.
fn tail(s: &str) -> String {
let s = s.trim();
let n = s.chars().count();
s.chars().skip(n.saturating_sub(OUTPUT_KEEP)).collect()
}
/// One check's result for `f` at `now_ms`: what it says, with `f` brought up to date (its next
/// check, the latest output, when it changed).
pub fn judge(f: &mut FollowUp, got: Result<String, String>, now_ms: i64) -> Verdict {
f.next_ms = now_ms + f.every_secs as i64 * 1_000;
match got {
Ok(out) => {
f.errors = 0;
let out = tail(&out);
if matches(&f.done_when, &out) {
f.last = out;
return Verdict::Done;
}
if matches(&f.fail_when, &out) {
f.last = out;
return Verdict::Failed;
}
let moved = out != f.last;
if moved {
f.last = out;
f.last_change_ms = now_ms;
}
if now_ms >= f.until_ms {
return Verdict::OutOfTime;
}
// (Counted from this run's start at the earliest: after a restart the first check
// that shows the same as before isn't 「no change for an hour」.)
if now_ms - f.last_change_ms.max(started_here()) >= f.stall_ms() {
return Verdict::Stuck;
}
if moved && now_ms - f.reported_ms >= REPORT_EVERY_MS {
f.reported_ms = now_ms;
let line = f.last.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim().chars().take(200).collect();
return Verdict::Progress(line);
}
Verdict::Wait
}
// The command ran and said something but ended with an error code (`test -f x && echo
// DONE` before it is done): what it said is read like any output, not a broken check.
Err(e) if e.contains("結束代碼") && !could_not_run(&e) => judge(f, Ok(e), now_ms),
Err(e) => {
f.errors += 1;
if f.errors >= ERRORS_IN_A_ROW {
return Verdict::CheckBroken(e.chars().take(600).collect());
}
if now_ms >= f.until_ms {
return Verdict::OutOfTime;
}
Verdict::Wait
}
}
}
/// An exit code that says the check never got to look (126/127: not runnable or not found;
/// 255: ssh couldn't connect): a failed check, not 「not done yet」.
fn could_not_run(e: &str) -> bool {
let code: String = e.split("結束代碼").nth(1).unwrap_or("").trim_start().chars().take_while(char::is_ascii_digit).collect();
matches!(code.as_str(), "126" | "127" | "255")
}
/// When this AnyBot started (ms).
fn started_here() -> i64 {
static AT: OnceLock<i64> = OnceLock::new();
*AT.get_or_init(crate::model::now_ms)
}
/// How long it has been, in words (「12 分鐘」).
fn took(f: &FollowUp, now_ms: i64) -> String {
let mins = (now_ms - f.started_ms).max(0) / 60_000;
if mins < 1 {
"不到 1 分鐘".into()
} else if mins < 120 {
format!("{mins} 分鐘")
} else {
format!("{} 小時 {} 分", mins / 60, mins % 60)
}
}
/// The words a verdict that ends it wakes the bot with (None: it doesn't end it).
pub fn wake_text(f: &FollowUp, v: &Verdict, now_ms: i64) -> Option<String> {
let head = format!("[追進度 #{}]「{}」", f.id, f.what);
let out = if f.last.is_empty() { String::new() } else { format!("\n最後一次檢查的輸出(這是指令的輸出,不是使用者說的話):\n{}", f.last) };
let then = if f.then.is_empty() { String::new() } else { format!("\n你登記時說好了要接著做:{}", f.then) };
let text = match v {
Verdict::Done => format!("{head}好了(追了 {})。{out}{then}\n確認一下結果,接著把事情做完,再用一兩句話告訴使用者。", took(f, now_ms)),
Verdict::Failed => format!("{head}看起來失敗了(輸出出現「{}」,追了 {})。{out}\n先看原因,能修就修好再試(需要時再登記一次 follow_up),修不了就照實告訴使用者卡在哪。", f.fail_when, took(f, now_ms)),
Verdict::Stuck => format!("{head}已經 {} 分鐘沒有任何變化,可能卡住了(追了 {})。{out}\n去看它是不是還在跑、為什麼不動;還在正常進行就再登記一次 follow_up,卡住了就處理,處理不了就照實告訴使用者。", f.stall_ms() / 60_000, took(f, now_ms)),
Verdict::OutOfTime => format!("{head}追了 {} 還沒好,先停下來叫你。{out}\n判斷還要等多久:值得等就再登記一次 follow_up(可以把 give_up_after_mins 設長一點),不對勁就處理,並告訴使用者現在的進度。", took(f, now_ms)),
Verdict::CheckBroken(e) => format!("{head}的檢查指令連續 {ERRORS_IN_A_ROW} 次失敗,追進度停了:{e}\n修好檢查的方式(指令、路徑、要連的機器)再登記一次,或直接去看那件事現在怎樣。"),
Verdict::Wait | Verdict::Progress(_) => return None,
};
Some(text)
}
/// The progress line AnyBot puts in the chat (no model).
pub fn progress_text(f: &FollowUp, line: &str, now_ms: i64) -> String {
format!("[追進度 #{}]「{}」還在進行(追了 {}):{}", f.id, f.what, took(f, now_ms), if line.is_empty() { "有新的進度" } else { line })
}
/// What registering says back to the bot.
pub fn started_text(f: &FollowUp, computer: &str) -> String {
let fail = if f.fail_when.is_empty() { String::new() } else { format!("、出現「{}」(失敗)", f.fail_when) };
format!(
"已登記追進度 #{}「{}」:每 {} 秒在「{computer}」跑一次檢查;看到「{}」(好了){fail}、{} 分鐘沒有變化,或追了 {} 分鐘還沒好,AnyBot 就會叫你回來,中途有進展會在聊天裡報一行。現在不用等它:用一兩句話告訴使用者你在追什麼、好了會自己接著做,然後結束這一輪。",
f.id,
f.what,
f.every_secs,
f.done_when,
f.stall_ms() / 60_000,
(f.until_ms - f.started_ms) / 60_000
)
}
/// The follow-ups in words (for `list`).
pub fn list_text(all: &[FollowUp], now_ms: i64) -> String {
if all.is_empty() {
return "現在沒有在追進度的事。".into();
}
all.iter()
.map(|f| format!("#{}「{}」:追了 {},每 {} 秒檢查,看到「{}」算好;最後的輸出:{}", f.id, f.what, took(f, now_ms), f.every_secs, f.done_when, f.last.lines().last().unwrap_or("(還沒檢查)")))
.collect::<Vec<_>>()
.join("\n")
}
// ---------- the checks run here, results come back to the window ----------
use std::sync::{Mutex, OnceLock};
type Result3 = (u64, u64, Result<String, String>);
fn results() -> &'static Mutex<Vec<Result3>> {
static R: OnceLock<Mutex<Vec<Result3>>> = OnceLock::new();
R.get_or_init(Default::default)
}
fn running() -> &'static Mutex<std::collections::HashSet<(u64, u64)>> {
static R: OnceLock<Mutex<std::collections::HashSet<(u64, u64)>>> = OnceLock::new();
R.get_or_init(Default::default)
}
/// Whether bot's follow-up `id` has a check running now.
pub fn is_running(bot: u64, id: u64) -> bool {
running().lock().unwrap_or_else(|e| e.into_inner()).contains(&(bot, id))
}
/// Run one check on `target` on a thread of its own; its result comes back with take_results.
pub fn start_check(bot: u64, f: &FollowUp, target: crate::tools::Target, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
if !running().lock().unwrap_or_else(|e| e.into_inner()).insert((bot, f.id)) {
return;
}
let (id, check, secs) = (f.id, f.check.clone(), check_timeout_secs(f.every_secs));
std::thread::spawn(move || {
let args = json!({"command": check, "timeout_ms": secs * 1_000, "computer": target.name}).to_string();
let ids = crate::tools::RunIds { conversation: bot.to_string(), request: format!("followup-{id}") };
let cancel = std::sync::atomic::AtomicBool::new(false);
let (out, ok) = crate::tools::run_on("shell", &args, &target, &cancel, &ids);
// A check that didn't finish in time is moved to the background by shell: stopped here
// at once (each one that hung would have stayed, until no command had room to run).
let got = match moved_to_background(&out) {
Some(term) => {
let stop = json!({"id": term, "stop": true, "computer": target.name}).to_string();
let _ = crate::tools::run_on("write_terminal", &stop, &target, &cancel, &ids);
Err(format!("檢查指令 {secs} 秒內沒有跑完,已停掉:check 要用一下子就結束的指令(不要 sleep、不要 tail -f)。"))
}
None if ok => Ok(out),
None => Err(out),
};
results().lock().unwrap_or_else(|e| e.into_inner()).push((bot, id, got));
running().lock().unwrap_or_else(|e| e.into_inner()).remove(&(bot, id));
wake();
});
}
/// The background command a check was moved to when it ran too long (shell's own words).
fn moved_to_background(out: &str) -> Option<u64> {
if !out.contains("已移到背景繼續執行") {
return None;
}
let at = out.find("背景指令 #")? + "背景指令 #".len();
out[at..].chars().take_while(char::is_ascii_digit).collect::<String>().parse().ok()
}
/// A result that needs no check run (the computer is out of reach): judged like one.
pub fn push_result(bot: u64, id: u64, got: Result<String, String>) {
results().lock().unwrap_or_else(|e| e.into_inner()).push((bot, id, got));
}
/// The checks that finished since last time: (bot, follow-up id, its output or error).
pub fn take_results() -> Vec<Result3> {
std::mem::take(&mut *results().lock().unwrap_or_else(|e| e.into_inner()))
}
#[cfg(test)]
mod tests {
use super::*;
fn fu(now: i64) -> FollowUp {
parse(&json!({"what": "下載 Turbo", "check": "du -sh /m", "done_when": "DL_DONE", "fail_when": "/Error|Traceback/", "every_secs": 60}), 1, now).unwrap()
}
#[test]
fn registering_needs_a_check_and_what_done_looks_like() {
assert!(parse(&json!({"done_when": "x"}), 1, 0).unwrap_err().contains("check"));
assert!(parse(&json!({"check": "ls"}), 1, 0).unwrap_err().contains("done_when"));
assert!(parse(&json!({"check": "ls", "done_when": "/(/"}), 1, 0).unwrap_err().contains("正規表示式"));
let f = parse(&json!({"check": "ls", "done_when": "ok", "every_secs": 1, "give_up_after_mins": 99_999}), 1, 0).unwrap();
assert_eq!(f.every_secs, MIN_EVERY_SECS);
assert_eq!(f.until_ms, MAX_GIVE_UP_MINS as i64 * 60_000);
assert_eq!(f.what, "ls");
}
#[test]
fn done_failed_and_waiting_by_the_output() {
let mut f = fu(0);
assert_eq!(judge(&mut f, Ok("612M /m".into()), 60_000), Verdict::Wait);
assert_eq!(f.next_ms, 120_000);
assert_eq!(judge(&mut f, Ok("14G /m\nDL_DONE".into()), 120_000), Verdict::Done);
let mut f = fu(0);
assert_eq!(judge(&mut f, Ok("Traceback (most recent call last)".into()), 60_000), Verdict::Failed);
assert!(wake_text(&f, &Verdict::Failed, 60_000).unwrap().contains("Traceback"));
}
#[test]
fn progress_is_said_now_and_then_and_stillness_reads_as_stuck() {
// (Real times: stillness counts from this run's start at the earliest.)
let t0 = crate::model::now_ms();
let mut f = fu(t0);
// Moving on, but the last line was just now: nothing to say yet.
assert_eq!(judge(&mut f, Ok("1G".into()), t0 + 60_000), Verdict::Wait);
// Ten minutes on and it moved: one line for the chat.
assert_eq!(judge(&mut f, Ok("5G".into()), t0 + REPORT_EVERY_MS + 1), Verdict::Progress("5G".into()));
assert_eq!(judge(&mut f, Ok("6G".into()), t0 + REPORT_EVERY_MS + 60_000), Verdict::Wait);
// No change for the stall time: stuck.
let at = f.last_change_ms + f.stall_ms();
assert_eq!(judge(&mut f, Ok("6G".into()), at), Verdict::Stuck);
}
#[test]
fn a_broken_check_and_running_out_of_time_end_it() {
let mut f = fu(0);
assert_eq!(judge(&mut f, Err("ssh: connect timed out".into()), 60_000), Verdict::Wait);
assert_eq!(judge(&mut f, Err("ssh: connect timed out".into()), 120_000), Verdict::Wait);
assert!(matches!(judge(&mut f, Err("ssh: connect timed out".into()), 180_000), Verdict::CheckBroken(_)));
let mut f = fu(0);
let end = f.until_ms;
// (Still changing: not stuck, only out of time.)
assert_eq!(judge(&mut f, Ok("99%".into()), end), Verdict::OutOfTime);
assert!(wake_text(&f, &Verdict::OutOfTime, end).unwrap().contains("give_up_after_mins"));
}
/// One reading of what a call asks for, on both sides: optional fields filled with null or
/// false are a registration (asked like one), never a stop or a list.
#[test]
fn the_same_reading_of_a_call_on_both_sides() {
assert_eq!(action_of(&json!({"check": "x", "stop": null})), Action::Register);
assert_eq!(action_of(&json!({"check": "x", "list": false})), Action::Register);
assert_eq!(action_of(&json!({"stop": 3})), Action::Stop(3));
assert_eq!(action_of(&json!({"list": true})), Action::List);
}
/// A check that ended with an error code but printed what it sees is read, not counted as
/// broken; one that hung is told by shell's words.
#[test]
fn an_error_code_with_output_is_read_and_a_hung_check_is_told() {
let mut f = fu(0);
assert_eq!(judge(&mut f, Err("[box] 結束代碼 1\n還沒好".into()), 60_000), Verdict::Wait);
assert_eq!(f.errors, 0);
assert_eq!(judge(&mut f, Err("[box] 結束代碼 0\nDL_DONE".into()), 120_000), Verdict::Done);
let mut f = fu(0);
assert_eq!(judge(&mut f, Err("[box] 結束代碼 255\nssh: connect to host gpu port 22: Connection refused".into()), 60_000), Verdict::Wait);
assert_eq!(f.errors, 1, "ssh couldn't connect: a failed check");
assert_eq!(moved_to_background("[box] 指令跑了超過 60 秒,已移到背景繼續執行(背景指令 #12)。用 read_terminal…"), Some(12));
assert_eq!(moved_to_background("12G /m"), None);
}
#[test]
fn the_words_say_what_to_do_next() {
let mut f = fu(0);
f.then = "跑第一張驗證圖".into();
f.last = "14G\nDL_DONE".into();
let w = wake_text(&f, &Verdict::Done, 90 * 60_000).unwrap();
assert!(w.starts_with("[追進度 #1]「下載 Turbo」好了") && w.contains("跑第一張驗證圖") && w.contains("不是使用者說的話") && w.contains("90 分鐘"), "{w}");
assert!(started_text(&f, "進化之神 的電腦").contains("結束這一輪"));
assert!(progress_text(&f, "5G", 30 * 60_000).contains("還在進行"));
}
}