feat: anybot --ask 給腳本用:--json、--bot、--data-dir、--approve、結束碼

工程基礎計畫 E10(grok-build 的 -p 加 JSON 輸出、結束碼)。

- AskOpts::parse:--json、--bot 名字、--data-dir 資料夾、--approve once|reject,選項可以夾在問題的字中間。寫錯時說哪裡錯、結束碼 2。--data-dir 在讀任何東西(紀錄檔、狀態)之前設成 ANYBOT_DATA_DIR。
- ask_cli:--json 時每則訊息一行 JSON(role、text、error、tools、tool_call_id),核准一行 approval、學到技能一行 learned,最後 done(ok、code、steps、secs、timed_out、answer),文字和參數裡的金鑰遮過。Ctrl-C 先停下 Bot、結束碼 130;時間到或這一輪沒有順利 1;順利 0;資料夾裡還沒有 Bot 2(以前什麼都不印就結束)。
- 核准改走 answer()(跟按鈕一樣):以前直接回覆核准卡的頻道,App 操作的核准(刪例行任務這類)在這裡會一直等到時間到。
- 用法說明(anybot -h)、FEATURES.md。

已驗證:cargo test 577 全過、clippy -D warnings 過。新測試:選項在任何位置都讀得到、缺東西時說清楚;結束碼對應。實際跑:隔離的資料夾裡沒有 Bot 時印出提醒、結束碼 2、立刻結束;--json 的 done 那一行格式對。
未驗證:完整一輪的 --json 輸出。手寫的測試狀態檔有 api_key 欄位,除錯版要從鑰匙圈拿保險庫的鑰匙,會在畫面上跳出允許視窗並卡住,所以停在這裡(已記下這個陷阱)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-17 11:58:04 +08:00
parent 6ab56c9ad3
commit 168aae4222
4 changed files with 159 additions and 19 deletions

View File

@ -1554,6 +1554,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- **模型讀到的**:你的「/goal …」後面多一行,說明這是目標、每輪會有另一個模型檢查,所以要用實際的結果證明(指令輸出、測試結果、檔案內容、畫面),需要你做什麼就直接問;「還沒達成」那則後面也提醒它接著做。檢查用的模型讀的是從設定目標那則訊息起的對話(太長就讀最新的約 24000 字;每個工具結果留開頭和結尾,測試的總結通常在最後),並知道已經第幾輪、做了多久,所以條件裡寫「最多 10 輪」也算數。
- **權限不變**:要你核准的步驟照樣停下來等;要放著讓它自己做完,Bot 要開「直接操作」或「自動審核」(Claude Code 也要配 auto mode)。
- **終端機**:`anybot --ask "/goal …"` 會一直做到達成、做不到或暫停才結束(像 `claude -p "/goal …"`),最長 ANYBOT_ASK_SECS 秒(預設 900)。
- **`anybot --ask` 給腳本用**:`--json` 每則訊息一行 JSON(type message/approval/learned/done;done 有 ok、code、steps、secs、timed_out、answer,金鑰遮過);`--bot 名字` 問哪個 Bot;`--data-dir 資料夾`(跟 ANYBOT_DATA_DIR 一樣,在讀任何東西之前就設好);`--approve once` 要核准的自動允許一次(問題卡和「需要處理」照樣略過),不給就自動拒絕。結束碼:0 這一輪順利、1 失敗或時間到、130 Ctrl-C(會先停下 Bot)、2 指令寫錯或資料夾裡還沒有 Bot。核准改走跟按鈕一樣的路:以前 App 操作(刪例行任務這類)的核准在這裡會一直等到時間到。
- 實測(假的 OpenAI 相容模型,獨立的大腦):「兩步」的目標第一輪檢查說還差第二步,AnyBot 自己開第二輪,第二輪後判定達成;永遠沒進展的目標在第 3 輪暫停;要登入的目標判定在等使用者而暫停,回一句「我登入了」後接著做並達成;目標的那幾行沒有出現在任何一次送給模型的內容裡。
- **/always-approve 一律放行**(也可以打 /yolo;像 Claude Code 的 bypassPermissions、Codex 的 --yolo):你打一句就把自己的權限一把全開,不用去設定裡一個個開。
- **打開時做的事**:打開「直接操作」(也就是「在這台電腦上執行」、所有 Bot 的電腦工具),之後所有要等「允許」的卡片都替你按允許,連直接操作還會問的也不問:「一律詢問」規則、付款/傳送/刪除這類點擊、寄信、傳訊息、沙盒外的 AppleScript、打電話、簡訊、在 X 發文、用保險庫的卡片;自動審核也略過(反正都會允許,不用再等一個模型判斷)。打開那一刻你自己的 Bot 正在等的卡片也一起放行。

View File

@ -50,8 +50,8 @@
- 做法:safety.md 的「每一步的關卡順序」九步,從 `agent::spawn` 抽成 `gate::decide(…) -> Gate`(輸入:工具、參數、電腦、開關、規則;輸出:直接做/問/拒絕和理由),一張表格式測試涵蓋每一步。`spawn` 只呼叫它。
- 做完:表格測試涵蓋九步和直接操作、一律放行、陌生人訊息;行為不變(舊測試全過)。
### E10. 無頭模式可以寫腳本 ⬜
- 做法:`anybot --ask` 加 `--json`(每個事件一行 JSON)、`--bot 名稱`、`--data-dir`、`--approve once|reject`;結束碼 0 成功、1 失敗、130 被中斷。
### E10. 無頭模式可以寫腳本 ✅
- 做法:`anybot --ask` 加 `--json`(每則訊息一行 JSON,還有 approval、learned、done)、`--bot 名稱`、`--data-dir`、`--approve once|reject`;結束碼 0 成功、1 失敗或時間到、130 Ctrl-C、2 指令寫錯或還沒有 Bot。核准改走 answer(),App 操作的核准卡不再一直等到時間到。
- 做完:`anybot --ask --json …` 的輸出能被 `jq` 讀;測試涵蓋結束碼。
### E11. `/doctor` 診斷 ✅

View File

@ -6109,7 +6109,13 @@ impl App {
/// with no window, refuses every approval (and says so), and prints the turn's steps. Run it
/// with ANYBOT_DATA_DIR pointing at a copy of the data folder. It doesn't connect to the
/// account, channels or routines.
pub fn ask_cli(ctx: &egui::Context, text: &str) -> ! {
/// `anybot --ask …`: one question to a bot, its whole turn (and a goal's turns) waited out,
/// what happened printed — as text for a person, or (`--json`) one JSON object a line for a
/// script. Exit code: 0 the turn went well, 1 it failed or ran out of time, 130 stopped with
/// Ctrl-C, 2 the command itself was wrong.
pub fn ask_cli(ctx: &egui::Context, opts: AskOpts) -> ! {
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
let _ = ctrlc::set_handler(|| INTERRUPTED.store(true, Ordering::SeqCst));
let mut app = App::new(ctx, None);
app.headless = true;
app.asking = true;
@ -6118,17 +6124,45 @@ impl App {
for (name, why) in crate::mcp::sync(&app.state.mcp_servers) {
log::warn!("連接器「{name}」連不上:{why}");
}
let id = app.state.primary_bot;
let id = match opts.bot.as_deref() {
None => app.state.primary_bot,
Some(want) => match app.state.bots.iter().find(|b| b.name == want).or_else(|| app.state.bots.iter().find(|b| b.name.eq_ignore_ascii_case(want))) {
Some(b) => b.id,
None => {
eprintln!("沒有叫「{want}」的 Bot(有:{})", app.state.bots.iter().map(|b| b.name.as_str()).collect::<Vec<_>>().join("、"));
std::process::exit(2);
}
},
};
if app.state.bot(id).is_none() {
eprintln!("這個資料夾還沒有 Bot:先打開 AnyBot 建立一個,或用 anybot setup。");
std::process::exit(2);
}
let json = opts.json;
let line = |v: serde_json::Value| println!("{v}");
let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0);
app.drafts.insert(id, text.to_string());
app.drafts.insert(id, opts.text.clone());
app.send(ctx, id);
let t0 = Instant::now();
let limit = std::env::var("ANYBOT_ASK_SECS").ok().and_then(|v| v.parse().ok()).unwrap_or(900u64);
// 「/goal …」: on to the end, as Claude Code's `claude -p "/goal …"` does — turn, check, turn.
while (app.streams.contains_key(&id) || app.goal_pending(id)) && t0.elapsed().as_secs() < limit {
if let Some(a) = app.approvals.remove(&id) {
println!(" ⚠️ 要求核准(自動拒絕):{} — {}", a.tool, a.reason);
let _ = a.reply.send(ApprovalAnswer::Reject);
if INTERRUPTED.load(Ordering::SeqCst) {
app.stop(id);
break;
}
// Nobody to press a button: --approve once allows what would be asked (a question
// card or a hand-off is skipped either way); without it, refused. (Through answer():
// an app action waiting on its card is answered too — it used to wait to the limit.)
if let Some(a) = app.approvals.get(&id) {
let (kind, tool, reason) = (a.kind, a.tool.clone(), a.reason.clone());
let yes = opts.approve && crate::always::answer_for(kind).is_some();
if json {
line(serde_json::json!({"type": "approval", "tool": tool, "reason": reason, "answer": if yes { "once" } else { "reject" }}));
} else {
println!(" ⚠️ 要求核准({}):{tool} — {reason}", if yes { "自動允許" } else { "自動拒絕" });
}
app.answer(ctx, id, if yes { ApprovalAnswer::Once } else { ApprovalAnswer::Reject });
}
app.drain_events(ctx);
app.goal_tick(ctx);
@ -6136,19 +6170,23 @@ impl App {
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
std::thread::sleep(std::time::Duration::from_millis(100));
}
let timed_out = app.streams.contains_key(&id) && !INTERRUPTED.load(Ordering::SeqCst);
let secs = t0.elapsed().as_secs();
// 自己進化 comes after the turn: wait for it when the turn was long enough to learn from.
let turn_msgs = app.state.bot(id).and_then(|b| b.messages.get(start..)).map(|m| m.to_vec()).unwrap_or_default();
if crate::memory::worth_learning(&turn_msgs) {
if !INTERRUPTED.load(Ordering::SeqCst) && crate::memory::worth_learning(&turn_msgs) {
let before = app.state.skills.clone();
let t1 = Instant::now();
while app.state.skills == before && t1.elapsed().as_secs() < 180 {
app.drain_events(ctx);
std::thread::sleep(std::time::Duration::from_millis(200));
}
match app.state.skills.iter().find(|k| !before.contains(k)) {
Some(k) => println!("📚 學到({} 秒):{} — {}\n{}\n", t1.elapsed().as_secs(), k.name, k.description, k.instructions),
None => println!("📚 這次沒有存技能({} 秒)", t1.elapsed().as_secs()),
let learned = app.state.skills.iter().find(|k| !before.contains(k));
match (json, learned) {
(true, Some(k)) => line(serde_json::json!({"type": "learned", "skill": k.name, "description": k.description})),
(true, None) => {}
(false, Some(k)) => println!("📚 學到({} 秒):{} — {}\n{}\n", t1.elapsed().as_secs(), k.name, k.description, k.instructions),
(false, None) => println!("📚 這次沒有存技能({} 秒)", t1.elapsed().as_secs()),
}
}
// The chat can shrink (compaction) between the snapshot and now: slice safely.
@ -6160,6 +6198,17 @@ impl App {
let full = std::env::var("ANYBOT_ASK_FULL").is_ok();
let mut steps = 0;
for m in &msgs {
steps += m.tool_calls.len();
if json {
let role = match m.role {
Role::User => "user",
Role::Assistant if m.note => "note",
Role::Assistant => "assistant",
Role::Tool => "tool",
};
line(serde_json::json!({"type": "message", "role": role, "text": crate::secrets::mask(&m.text), "error": m.error, "tools": m.tool_calls.iter().map(|c| serde_json::json!({"id": c.id, "name": c.name, "args": crate::secrets::mask(&c.args)})).collect::<Vec<_>>(), "tool_call_id": m.tool_call_id}));
continue;
}
match m.role {
Role::User => println!("👤 {}", m.text),
Role::Assistant => {
@ -6167,16 +6216,22 @@ impl App {
println!("🤖 {}", if full || m.tool_calls.is_empty() { m.text.clone() } else { clip(&m.text, 300) });
}
for c in &m.tool_calls {
steps += 1;
println!(" 🔧 {} {}", c.name, clip(&c.args, 200));
}
}
Role::Tool => println!(" ↳ {}{}", if m.images.is_empty() { "" } else { "[附截圖] " }, clip(&m.text, if full { 4000 } else { 400 })),
}
}
println!("—— {steps} 個工具步驟,{secs} 秒");
let outcome = app.state.bot(id).and_then(|b| b.last_turn.as_ref()).map(|t| t.outcome);
let code = ask_exit_code(INTERRUPTED.load(Ordering::SeqCst), timed_out, outcome);
let answer = msgs.iter().rev().find(|m| m.role == Role::Assistant && !m.note && !m.text.trim().is_empty()).map(|m| m.text.clone()).unwrap_or_default();
if json {
line(serde_json::json!({"type": "done", "ok": code == 0, "code": code, "steps": steps, "secs": secs, "timed_out": timed_out, "answer": crate::secrets::mask(&answer)}));
} else {
println!("—— {steps} 個工具步驟,{secs} 秒{}", if timed_out { "(時間到了,還沒做完)" } else { "" });
}
app.state.save();
std::process::exit(0)
std::process::exit(code)
}
pub fn serve(ctx: &egui::Context) -> ! {
@ -6640,6 +6695,59 @@ fn carried_in_view(messages: &[Message]) -> std::collections::HashSet<String> {
/// A message of the person's, with the memories they picked under the composer (`None`: they
/// didn't look; AnyBot chooses at the start of the turn).
/// What `anybot --ask` was told (main parses it before anything else, for --data-dir).
#[derive(Debug, PartialEq, Default)]
pub struct AskOpts {
pub text: String,
/// One JSON object a line instead of text for a person.
pub json: bool,
/// The bot asked, by name (the main bot when not given).
pub bot: Option<String>,
/// A data folder of its own (ANYBOT_DATA_DIR).
pub data_dir: Option<String>,
/// What would be asked is allowed once (`--approve once`); refused otherwise.
pub approve: bool,
}
impl AskOpts {
/// The words after `--ask`: options first or mixed in, the rest is the question.
pub fn parse(args: &[String]) -> Result<AskOpts, String> {
let mut o = AskOpts::default();
let mut words = vec![];
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--json" => o.json = true,
"--bot" => o.bot = Some(it.next().ok_or("--bot 後面要接 Bot 的名字")?.clone()),
"--data-dir" => o.data_dir = Some(it.next().ok_or("--data-dir 後面要接資料夾")?.clone()),
"--approve" => match it.next().map(String::as_str) {
Some("once") => o.approve = true,
Some("reject") => o.approve = false,
_ => return Err("--approve 後面要接 once 或 reject".into()),
},
w => words.push(w.to_string()),
}
}
o.text = words.join(" ");
if o.text.trim().is_empty() {
return Err("要問什麼?例如:anybot --ask --json --bot 小幫手 今天天氣如何".into());
}
Ok(o)
}
}
/// `anybot --ask`'s exit code: 130 stopped with Ctrl-C, 1 out of time or the turn didn't go
/// well, 0 it did.
pub fn ask_exit_code(interrupted: bool, timed_out: bool, outcome: Option<crate::model::TurnOutcome>) -> i32 {
if interrupted {
130
} else if timed_out || outcome != Some(crate::model::TurnOutcome::Success) {
1
} else {
0
}
}
fn person_message(st: &State, bot_id: u64, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) -> Message {
let mut m = Message { attachments, ..Message::user(text) };
if let Some(p) = picks {
@ -7961,6 +8069,24 @@ mod tests {
assert_eq!(app.state.bot(id).unwrap().name, name);
}
/// E10: `anybot --ask` reads its options anywhere among the words, and says by its exit
/// code how the turn went.
#[test]
fn ask_options_and_exit_codes() {
let a = |v: &[&str]| super::AskOpts::parse(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>());
let o = a(&["--json", "--bot", "小幫手", "今天", "--approve", "once", "天氣如何", "--data-dir", "/tmp/x"]).unwrap();
assert_eq!(o, super::AskOpts { text: "今天 天氣如何".into(), json: true, bot: Some("小幫手".into()), data_dir: Some("/tmp/x".into()), approve: true });
assert!(a(&["--json"]).unwrap_err().contains("要問什麼"));
assert!(a(&["--bot"]).unwrap_err().contains("--bot"));
assert!(a(&["--approve", "always", "x"]).unwrap_err().contains("once 或 reject"));
use crate::model::TurnOutcome::*;
assert_eq!(super::ask_exit_code(false, false, Some(Success)), 0);
assert_eq!(super::ask_exit_code(false, false, Some(Error)), 1);
assert_eq!(super::ask_exit_code(false, true, Some(Success)), 1, "out of time");
assert_eq!(super::ask_exit_code(false, false, None), 1);
assert_eq!(super::ask_exit_code(true, false, Some(Cancelled)), 130);
}
/// 診斷: 「/doctor」 says it is checking, then one report: each finding ✓ or ✗ (the model
/// services are this test's fake one; no account, no bots' computer in a test).
#[test]

View File

@ -304,7 +304,12 @@ impl eframe::App for Busy {
const USAGE: &str = "用法:
anybot 打開 AnyBot 視窗
anybot --serve 不開視窗,讓 Bot 繼續工作、接手機
anybot --ask 問題… 問第一個 Bot 一句,印出回答(測試用)
anybot --ask 問題… 問一個 Bot 一句,印出這一輪(給人看)
--json 一行一個 JSON(給腳本:message、approval、learned、done)
--bot 名字 問哪個 Bot(預設主要 Bot)
--data-dir 資料夾 用另一個資料夾(像 ANYBOT_DATA_DIR)
--approve once 要核准的自動允許一次(預設自動拒絕)
結束碼:0 這一輪順利、1 失敗或時間到、130 按了 Ctrl-C、2 指令寫錯
anybot setup … 在沒有螢幕的機器上設定
anybot --install-skill 來源 安裝技能(GitHub 網址、owner/repo/path、SKILL.md 網址或本機資料夾)
anybot --update-box 更新 Bot 的電腦(同 設定 › 電腦 › 更新;AnyBot 開著就請它做)
@ -320,6 +325,15 @@ fn main() -> eframe::Result<()> {
println!("AnyBot {}", version::full(version::exe_modified()));
return Ok(());
}
// `anybot --ask … --data-dir X`: that folder for everything (set before anything reads it).
let ask = (args.get(1).map(String::as_str) == Some("--ask")).then(|| app::AskOpts::parse(&args[2..]));
if let Some(Err(e)) = &ask {
eprintln!("{e}");
std::process::exit(2);
}
if let Some(Ok(app::AskOpts { data_dir: Some(d), .. })) = &ask {
std::env::set_var("ANYBOT_DATA_DIR", d);
}
// 紀錄檔與當掉報告 (logfile.rs): logs/ in the data folder, and a report if anything panics.
logfile::init();
// 完整結果 older than a week go.
@ -419,11 +433,10 @@ fn main() -> eframe::Result<()> {
std::process::exit(setup::run(&args[2..]));
}
// Everything below uses the data folder (the chats, the work log): one AnyBot at a time.
if args.get(1).map(String::as_str) == Some("--ask") {
let text = args[2..].join(" ");
if let Some(Ok(opts)) = ask {
let ctx = egui::Context::default();
let _folder = take_folder_or_exit();
app::App::ask_cli(&ctx, &text);
app::App::ask_cli(&ctx, opts);
}
// No window: keep the bots working and answer the phone (always-on Mac or server).
if args.iter().any(|a| a == "--serve") {