fix: 追進度審查——同一套判斷、只在 Bot 自己的電腦、拒絕外人、卡住的檢查會停掉

- P0:要不要問與實際登記改用同一個 action_of("stop": null、"list": false 不再繞過審批)
- P1:別人傳來的訊息那一輪不能登記;系統指示只在信任的回合提追進度
- P1:檢查只在 Bot 自己的電腦上跑,登記時把電腦寫死(之後換預設電腦不會改到使用者的電腦);登記時也跑使用者的 PreToolUse hook
- P1:一次檢查最多跑 10–60 秒,沒跑完就停掉背景指令、算一次失敗(不再一個個留在背景佔滿名額)
- P2:結束代碼非 0 但有輸出的檢查照樣比對;重開後第一次檢查不會直接判卡住;非回合的模型呼叫讀取逾時維持 300 秒、回合請求用自己的首字等待;分段摘要每段重設看門狗;調整可讀長度時清掉這個模型學到的上限;Anthropic 收起的步驟不再原樣回送完整參數

已驗證: cargo test 756 通過(新增 the_same_reading_of_a_call_on_both_sides、an_error_code_with_output_is_read_and_a_hung_check_is_told、registering_is_decided_as_it_will_be_done),clippy 無新警告;verify-anybot goal.md「追進度」重跑(電腦寫成 Bot 自己的、好了叫醒、追完歸零),另驗指定別台電腦被拒;ctl down 無殘留
未驗證: 真的遠端檢查(SSH 到 GPU 機)與卡住檢查被停掉(要真的機器);手機頁面畫面(沒有 Chrome);新 App 工具與審批需實機測試+人類簽名,不發佈

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-19 23:44:50 +08:00
parent ec8fe4b398
commit f1f43420d2
8 changed files with 211 additions and 43 deletions

View File

@ -753,7 +753,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- **追進度(follow_up)**:Bot 啟動要等很久的事(下載、算圖、訓練、部署、別台機器上的工作)後,登記一個很快就跑完的檢查指令(du、tail log、curl 狀態、SSH 一行都可以)、done_when(輸出出現什麼算好了,/…/ 是正規表示式)、可選的 fail_when、then(好了要接著做什麼),就可以結束這一輪。
- 大腦每 every_secs(15–3600,預設 60)秒在那台電腦上跑一次檢查,不叫模型;輸出有變、而且距離上一行超過 10 分鐘,聊天裡記一行「[追進度 #N]「…」還在進行(追了 M 分鐘):最後一行」。
- 好了、出現 fail_when、輸出 15 分鐘(或十次檢查)沒變、超過 give_up_after_mins(預設 180,最多 1440)、或檢查指令連續 3 次失敗,就叫醒 Bot:「[追進度 #N]「…」好了/看起來失敗了/可能卡住了…」,附最後的輸出和 then,告訴它接著怎麼做。
- 登記時,那個檢查指令照 shell 的規則決定要不要問使用者(問的話卡片寫明之後會每 N 秒自動執行),被安全規則擋的不登記;之後不再一次次問。list 看、stop 停;一個 Bot 同時最多 8 個。存在 Bot 身上,重開 AnyBot 照樣追;只有大腦跑,螢幕電腦不跑。
- 檢查只在 Bot 自己的電腦上跑(它會無人看著一再執行,所以不在使用者的電腦上;別台機器從那裡用 SSH 或 curl 看),登記時就把電腦寫死。那個檢查指令照 shell 的規則和使用者的 PreToolUse hook 決定要不要問(問的話卡片寫明之後會每 N 秒自動執行),被安全規則或 hook 擋的不登記;之後不再一次次問。別人傳來的訊息(訊息管道、團隊成員)那一輪不能登記。一次檢查最多跑 every_secs(10–60 秒),沒跑完就停掉、算一次失敗;結束代碼不是 0 但有輸出的照樣比對。list 看、stop 停;一個 Bot 同時最多 8 個。存在 Bot 身上,重開 AnyBot 照樣追;只有大腦跑,螢幕電腦不跑。
- 系統指示要求:要等的事不要 sleep 卡在指令裡、也不要說「我去盯」就結束;「說了就做」的提醒也會叫它用 follow_up。起因:Bot 說「我去盯它跑」之後沒有人叫它回來,使用者只好一直問「好了沒」。
- **主動回報**(系統指示):事情做到一個段落、或追進度叫它回來時,主動用一兩句話回報做到哪、接下來做什麼;發現問題先自己處理。
- **回合結束有三種**:

View File

@ -10,7 +10,7 @@
- `goal-next` 下一輪:沒達成時,系統自己送出一則「[目標]還沒達成:理由」開始下一輪。
- `goal-brake` 煞車:做滿 20 輪先停下來問;連續 3 輪沒有用任何工具(只是在跟評審說話)就停;連續兩輪評審說差的是同一件事(字稍微不同也算)就停,看起來卡住了;Bot 在等使用者回答時停;評審沒有回應時停。使用者傳任何一句話就接著做(滿 20 輪的話再給 20 輪)。
- `goal-done` 達成或做不到:聊天裡留一行結果(花了幾輪),目標清掉。達成、做不到或停下來時,使用者不在電腦前(而且通知開著)會跳通知,手機也收得到。
- `goal-followup` 追進度:Bot 啟動要等很久的事(下載、算圖、訓練、別台機器上的工作)後,登記一個看進度的指令和「看到什麼算好」就結束這一輪,不用你問「好了沒」。大腦定期在那台電腦上跑那個指令(不叫模型):有進展時聊天裡報一行「[追進度 #N]「…」還在進行…」(最多每 10 分鐘一行);好了、失敗、太久沒變化(約 15 分鐘)、超過時間(預設 3 小時)或指令一直失敗,就叫 Bot 回來接著做。登記時那個指令照 `shell` 的規則問你一次,之後不再一次次問。重開 AnyBot 照樣繼續追。
- `goal-followup` 追進度:Bot 啟動要等很久的事(下載、算圖、訓練、別台機器上的工作)後,登記一個看進度的指令和「看到什麼算好」就結束這一輪,不用你問「好了沒」。大腦定期在那台電腦上跑那個指令(不叫模型):有進展時聊天裡報一行「[追進度 #N]「…」還在進行…」(最多每 10 分鐘一行);好了、失敗、太久沒變化(約 15 分鐘)、超過時間(預設 3 小時)或指令一直失敗,就叫 Bot 回來接著做。檢查只在 Bot 自己的電腦上跑(別台用 SSH 或 curl 從那裡看),登記時照 `shell` 的規則和你的 hook 問一次,之後不再一次次問;別人傳來的訊息不能登記。重開 AnyBot 照樣繼續追。
- `goal-restart` 重開:目標存在 Bot 身上,重開 AnyBot 還在;進行中的會先暫停(「AnyBot 重新啟動過」),等使用者一句話才繼續。
## 使用者怎麼到

View File

@ -1158,10 +1158,14 @@ pub fn summarize(base: &ChatRequest, quick: Option<&str>, part: &[Message], canc
let pieces = summary_pieces(part, SUMMARY_PIECE_CHARS);
let mut text: Option<String> = None;
let mut failed = false;
for piece in &pieces {
for (k, piece) in pieces.iter().enumerate() {
if cancel.load(Ordering::Relaxed) {
return None;
}
// (Each piece is a request of its own: the window's wait for a first word starts again.)
if pieces.len() > 1 {
quiet(StreamEvent::Retrying(format!("對話很長了,正在整理成摘要(第 {}/{} 段)…", k + 1, pieces.len())));
}
let got = match &text {
None => ask(piece, ""),
Some(so_far) => ask(&format!("【到目前為止的摘要】\n{so_far}\n\n【接下來的對話】\n{piece}"), "(把接下來的對話併進到目前為止的摘要,照同樣的段落寫一份完整的)"),
@ -1334,10 +1338,11 @@ fn maybe_compact(job: &Job, history: &mut Vec<Message>, percent: u64, cancel: &A
let req = ChatRequest {
..job.req.clone()
};
let quiet = |ev: StreamEvent| {
if matches!(ev, StreamEvent::Alive | StreamEvent::Retrying(_)) {
send(StreamEvent::Alive);
}
// (A retry or the next piece says so — it restarts the window's wait for a first word.)
let quiet = |ev: StreamEvent| match ev {
StreamEvent::Alive => send(StreamEvent::Alive),
StreamEvent::Retrying(w) => send(StreamEvent::Retrying(w)),
_ => {}
};
job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 });
let text = summarize(&req, job.step_model.as_deref(), &history[..cut], cancel, &quiet)?;
@ -1521,10 +1526,11 @@ fn compact_within_turn(job: &Job, history: &mut Vec<Message>, cancel: &AtomicBoo
let (ask, cut) = turn_cut(history)?;
send(StreamEvent::Retrying("對話太長了,正在把這一輪較早的步驟整理成摘要…".into()));
let req = ChatRequest { ..job.req.clone() };
let quiet = |ev: StreamEvent| {
if matches!(ev, StreamEvent::Alive | StreamEvent::Retrying(_)) {
send(StreamEvent::Alive);
}
// (A retry or the next piece says so — it restarts the window's wait for a first word.)
let quiet = |ev: StreamEvent| match ev {
StreamEvent::Alive => send(StreamEvent::Alive),
StreamEvent::Retrying(w) => send(StreamEvent::Retrying(w)),
_ => {}
};
job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 });
let text = summarize(&req, job.step_model.as_deref(), &history[..cut], cancel, &quiet)?;

View File

@ -3118,7 +3118,7 @@ impl App {
self.dirty = true;
continue;
}
if let StreamEvent::AppAction(call) = ev {
if let StreamEvent::AppAction(mut call) = ev {
// 支線: changes no settings — not its own, another bot's or AnyBot's (said at
// once, with no card to allow).
if self.state.bot(id).is_some_and(|b| b.branch_of != 0) && appctl::changes_settings(&call.name, &call.args) {
@ -3151,7 +3151,10 @@ impl App {
// 追進度: its check runs again and again without asking — asked like that
// command with shell, once (a refused one isn't registered).
match self.followup_ask(id, &call.args) {
Ok(ask) => ask,
Ok((ask, args)) => {
call.args = args;
ask
}
Err(e) => {
let _ = call.reply.send((e, false));
continue;
@ -5530,11 +5533,18 @@ impl App {
ui.add(egui::TextEdit::singleline(&mut b.workdir).hint_text(t("在你的電腦上,例如 ~/Documents/專案")).desired_width(ui.available_width()));
});
form_row(ui, "模型可讀長度", p, |ui| {
let before = b.context_tokens;
egui::ComboBox::from_id_salt("ctx_tokens").selected_text(format!("{}K tokens", b.context_tokens / 1000)).width(150.0).show_ui(ui, |ui| {
for t in [32_000u64, 128_000, 200_000, 400_000, 1_000_000] {
ui.selectable_value(&mut b.context_tokens, t, format!("{}K tokens", t / 1000));
}
});
// The person set it: what a model once said it reads (model_limits) no
// longer holds this one back.
if b.context_tokens != before {
let key = b.limit_key();
b.model_limits.remove(&key);
}
ui.label(RichText::new(t("用到 60% 時會把舊對話整理成摘要")).size(FONT_XS).color(p.text3));
});
ui.add_space(2.0);
@ -7554,7 +7564,8 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu
}
ways.push("- 使用者交代的事就做完:不要做到一半停下來問「要我繼續嗎」「要我現在做嗎」,畫面不如預期就自己處理(關掉擋路的視窗、打開要用的 App)再接著做。只有需要使用者親手做、或要先確認會切斷連線、刪除、付款這類事情時才停下來問。".into());
// 追進度 (followup.rs): long things are followed by AnyBot, not by a sleep or a promise.
if b.tools_enabled {
// (Not on a turn from someone other than the person: it can't register one.)
if b.tools_enabled && mcp {
ways.push("- 要等很久的事(下載、算圖、訓練、部署、別台機器上跑的工作):不要用 sleep 卡在指令裡等,也不要說「我去盯」「好了再跟你說」就結束——那樣沒有人會叫你回來。啟動之後用 follow_up 登記一個很快就跑完的檢查指令(看進度的,例如 du、tail log、curl 狀態、SSH 一行)和 done_when(看到什麼算好了),寫上 then(好了要接著做什麼),用一兩句話告訴使用者你在追什麼,然後結束這一輪;AnyBot 會在背景幫你看,好了、失敗、卡住或超時都會叫你回來接著做完。".into());
ways.push("- 主動一點:使用者交代的事情做到一個段落、或追進度叫你回來時,主動用一兩句話回報做到哪、接下來做什麼;發現問題先自己處理,處理完再說,不要等使用者來問「好了沒」。".into());
}

View File

@ -6,32 +6,66 @@ use super::*;
use crate::followup::{self, Verdict};
impl App {
/// Whether registering this follow-up asks the person first: as running its check with
/// `shell` there would (Err: refused — never registered). Listing and stopping don't.
pub(super) fn followup_ask(&self, bot_id: u64, args: &str) -> Result<Option<String>, String> {
let v: serde_json::Value = serde_json::from_str(args).unwrap_or(serde_json::Value::Null);
if v.get("list").is_some() || v.get("stop").is_some() {
return Ok(None);
/// Whether registering this follow-up asks the person first, and the call as it will be
/// done (its computer written in). Err: refused — never registered.
///
/// The check runs again and again with nobody watching, so it runs only on the bot's own
/// computer (another machine is reached from there, by SSH or curl): never on the person's
/// computers, where `shell` has more doors than one decision (在這台電腦上執行, its admin
/// lock, the steps asked every time). The computer is decided now and kept — the bot's
/// chosen computer changing later doesn't move it. Then: as `shell` there would decide it,
/// and the person's PreToolUse hooks; a turn from someone other than the person can't.
pub(super) fn followup_ask(&self, bot_id: u64, args: &str) -> Result<(Option<String>, String), String> {
let mut v: serde_json::Value = serde_json::from_str(args).unwrap_or(serde_json::Value::Null);
if followup::action_of(&v) != followup::Action::Register {
return Ok((None, args.to_string()));
}
let check = v["check"].as_str().unwrap_or("").trim();
if check.is_empty() {
return Ok(None);
if self.strangers.contains(&bot_id) {
return Err("這則訊息是別人傳來的(訊息管道或團隊成員):不能登記追進度。".into());
}
let Some(b) = self.state.bot(bot_id) else { return Err("找不到這個 Bot".into()) };
let (target, name) = self.followup_target(b, v["computer"].as_str().unwrap_or(""))?;
let targets = self.targets_for(b);
let roles = self.roles_for(b, &targets);
let own = roles.own.clone();
let named = v["computer"].as_str().unwrap_or("").trim().to_string();
if !named.is_empty() && named != own {
return Err(format!("追進度的檢查只在你自己的電腦「{own}」上跑(它會無人看著一再執行)。要看別台的進度,從「{own}」用 SSH 或 curl 看,computer 留空。"));
}
let Some(target) = targets.into_iter().find(|t| t.name == own) else {
return Err(format!("你自己的電腦「{own}」現在不能用,沒辦法登記追進度。"));
};
let check = v["check"].as_str().unwrap_or("").trim().to_string();
let every = v["every_secs"].as_u64().unwrap_or(followup::DEFAULT_EVERY_SECS).clamp(followup::MIN_EVERY_SECS, followup::MAX_EVERY_SECS);
match tools::decide_on("shell", &serde_json::json!({"command": check}).to_string(), &target, &b.allow_rules) {
tools::Decision::Allow => Ok(None),
tools::Decision::Ask { reason, .. } => Ok(Some(format!("追進度:之後每 {every} 秒會在「{name}」自動執行這個檢查(不再一次次問你),直到好了或停掉。\n{reason}"))),
let shell_args = serde_json::json!({"command": check}).to_string();
// The person's own PreToolUse hooks, as for a shell step (a block refuses it).
let hooks = crate::hooks::Hooks::load_for(bot_id);
if !hooks.is_empty() {
let mut input = crate::hooks::base(bot_id, &b.name);
input["tool_name"] = serde_json::json!("shell");
input["tool_input"] = crate::hooks::tool_input(&shell_args);
let said = hooks.fire("PreToolUse", Some("shell"), input);
if let Some(why) = said.block.or_else(|| said.permission.filter(|(p, _)| p == "deny").map(|(_, w)| w)) {
return Err(format!("被 hook 擋下:{why}"));
}
}
v["computer"] = serde_json::json!(own);
let args = v.to_string();
match tools::decide_on("shell", &shell_args, &target, &b.allow_rules) {
tools::Decision::Allow => Ok((None, args)),
tools::Decision::Ask { reason, .. } => Ok((Some(format!("追進度:之後每 {every} 秒會在「{own}」自動執行這個檢查(不再一次次問你),直到好了或停掉。\n{reason}")), args)),
tools::Decision::Deny(why) => Err(format!("這個檢查指令不能用:{why}")),
}
}
/// The computer a follow-up runs on: the one it names, or the bot's chosen one.
/// The computer a follow-up runs on (the one written in when it was registered).
fn followup_target(&self, b: &Bot, named: &str) -> Result<(tools::Target, String), String> {
let targets = self.targets_for(b);
let roles = self.roles_for(b, &targets);
let name = if named.trim().is_empty() { Self::chosen_computer(b, &targets, &roles).0 } else { named.trim().to_string() };
// (One registered before the computer was written in: the bot's own.)
let name = if named.trim().is_empty() { roles.own.clone() } else { named.trim().to_string() };
if name != roles.own {
return Err(format!("追進度只在 Bot 自己的電腦上跑,「{name}」不是"));
}
targets.into_iter().find(|t| t.name == name).map(|t| (t, name.clone())).ok_or_else(|| format!("「{name}」現在連不到"))
}
@ -96,6 +130,29 @@ impl App {
mod tests {
use super::*;
/// Registering is asked the way the call will be done, and only for the bot's own computer:
/// a stranger's turn can't, another computer is refused, a null `stop` is a registration
/// (asked like one), and the computer is written in now.
#[test]
fn registering_is_decided_as_it_will_be_done() {
let ctx = egui::Context::default();
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-followup-ask.png")));
let id = app.state.bots[0].id;
let b = app.state.bot(id).unwrap().clone();
let own = app.roles_for(&b, &app.targets_for(&b)).own.clone();
let call = |extra: &str| format!(r#"{{"check":"ls","done_when":"x"{extra}}}"#);
match app.followup_ask(id, &call(r#","stop":null"#)) {
Ok((_, args)) => assert_eq!(serde_json::from_str::<serde_json::Value>(&args).unwrap()["computer"], own.as_str(), "written in"),
Err(e) => assert!(e.contains("不能用") || e.contains("現在不能用"), "{e}"),
}
let other = app.followup_ask(id, &call(r#","computer":"王性驊的Mac mini""#)).unwrap_err();
assert!(other.contains("只在你自己的電腦"), "{other}");
app.strangers.insert(id);
assert!(app.followup_ask(id, &call("")).unwrap_err().contains("別人傳來的"));
// Listing and stopping ask nothing (and change nothing to ask about).
assert!(app.followup_ask(id, r#"{"list":true}"#).unwrap().0.is_none());
}
/// 追進度 end to end on the brain: registered by the tool, a check that moved on is one line
/// in the chat (no model), and the one that says done wakes the bot with what to do next.
#[test]

View File

@ -469,10 +469,11 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
crate::followup::TOOL => {
let now_ms = crate::model::now_ms();
let Some(b) = state.bot(bot_id) else { return err("找不到這個 Bot".into()) };
if v.get("list").and_then(Value::as_bool) == Some(true) {
// (Read the same way the window read it when it decided whether to ask.)
if crate::followup::action_of(&v) == crate::followup::Action::List {
return ok(crate::followup::list_text(&b.follow_ups, now_ms));
}
if let Some(id) = v.get("stop").and_then(Value::as_u64) {
if let crate::followup::Action::Stop(id) = crate::followup::action_of(&v) {
let Some(b) = state.bot_mut(bot_id) else { return err("找不到這個 Bot".into()) };
let before = b.follow_ups.len();
b.follow_ups.retain(|f| f.id != id);

View File

@ -98,11 +98,36 @@ pub fn spec() -> Value {
"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": "Which computer runs the check (as list_computers names it); default: the one you work on."},
"computer": {"type": "string", "description": "Leave empty: checks run on your own computer (they repeat with nobody watching, so never on the person's). Reach other machines from there — an SSH one-liner or curl as the check."},
"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();
@ -186,7 +211,9 @@ pub fn judge(f: &mut FollowUp, got: Result<String, String>, now_ms: i64) -> Verd
if now_ms >= f.until_ms {
return Verdict::OutOfTime;
}
if now_ms - f.last_change_ms >= f.stall_ms() {
// (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 {
@ -196,6 +223,9 @@ pub fn judge(f: &mut FollowUp, got: Result<String, String>, now_ms: i64) -> Verd
}
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("結束代碼") => judge(f, Ok(e), now_ms),
Err(e) => {
f.errors += 1;
if f.errors >= ERRORS_IN_A_ROW {
@ -209,6 +239,12 @@ pub fn judge(f: &mut FollowUp, got: Result<String, String>, now_ms: i64) -> Verd
}
}
/// 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;
@ -293,17 +329,38 @@ pub fn start_check(bot: u64, f: &FollowUp, target: crate::tools::Target, wake: s
if !running().lock().unwrap_or_else(|e| e.into_inner()).insert((bot, f.id)) {
return;
}
let (id, check) = (f.id, f.check.clone());
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": 120_000, "computer": target.name}).to_string();
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 (out, ok) = crate::tools::run_on("shell", &args, &target, &std::sync::atomic::AtomicBool::new(false), &ids);
results().lock().unwrap_or_else(|e| e.into_inner()).push((bot, id, if ok { Ok(out) } else { Err(out) }));
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));
@ -346,12 +403,14 @@ mod tests {
#[test]
fn progress_is_said_now_and_then_and_stillness_reads_as_stuck() {
let mut f = fu(0);
// (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()), 60_000), Verdict::Wait);
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()), REPORT_EVERY_MS + 1), Verdict::Progress("5G".into()));
assert_eq!(judge(&mut f, Ok("6G".into()), REPORT_EVERY_MS + 60_000), Verdict::Wait);
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);
@ -370,6 +429,28 @@ mod tests {
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);
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);

View File

@ -446,6 +446,15 @@ fn first_wait() -> u64 {
FIRST_WAIT.with(|w| w.get()).max(FIRST_RESPONSE_TIMEOUT_SECS)
}
/// How long one read may wait: a turn's request its own first wait (silence after it started is
/// the window's 35 s watchdog's); any other call (a judge, a summary off a turn) 300 s, as before.
fn per_read_secs() -> u64 {
match FIRST_WAIT.with(|w| w.get()) {
0 => 300,
w => w.max(FIRST_RESPONSE_TIMEOUT_SECS),
}
}
/// What a request that got no word at all within its first wait fails with: too much for this
/// model to read in time. Not asked again as it is — made smaller first (agent::make_room).
pub const SLOW_START: &str = "模型讀這麼長的對話,久到還沒開始回答:";
@ -486,7 +495,7 @@ fn agent() -> ureq::Agent {
// a FIN) must end: without a read timeout the lines() loop blocks forever, and every
// such turn leaks a thread and its socket. 5 minutes of total silence is a dead stream —
// or, before the first word, the request's own first wait (read_sse_from tells them apart).
.timeout_per_read(Some(Duration::from_secs(first_wait().min(300))))
.timeout_per_read(Some(Duration::from_secs(per_read_secs())))
.build();
config.into()
}
@ -1771,6 +1780,9 @@ pub(crate) fn written_by(m: &Message, model: &str) -> bool {
}
pub fn anthropic_messages(req: &ChatRequest) -> Vec<Value> {
// (A step whose result was set aside goes rebuilt, its long arguments shortened like every
// provider's, not as its blocks — which carry them whole.)
let folded: std::collections::HashSet<&str> = req.history.iter().filter(|m| m.role == Role::Tool && m.folded).map(|m| m.tool_call_id.as_str()).collect();
let mut messages: Vec<Value> = vec![];
let mut push = |role: &str, blocks: Vec<Value>| {
if blocks.is_empty() {
@ -1818,7 +1830,7 @@ pub fn anthropic_messages(req: &ChatRequest) -> Vec<Value> {
// Its own blocks (thinking with its signature) go back only to the model that wrote
// them: another model refuses a signature that isn't its own — after a switch the
// turn failed. Others get the words and calls rebuilt below.
if !m.blocks.is_empty() && written_by(m, &req.model) {
if !m.blocks.is_empty() && written_by(m, &req.model) && !m.tool_calls.iter().any(|c| folded.contains(c.id.as_str())) {
push("assistant", m.blocks.clone());
} else if !m.error || !m.tool_calls.is_empty() {
let mut b = vec![];