From 2cb543cfe1e2cb4b9554fb51d769141cb6cf3f8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:01:34 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=87=AA=E5=8B=95=E5=AF=A9=E6=A0=B8?= =?UTF-8?q?=E5=8F=AF=E4=BB=A5=E5=AF=AB=E5=9B=BA=E5=AE=9A=E6=A8=A3=E5=BC=8F?= =?UTF-8?q?=E7=9A=84=E8=A6=8F=E5=89=87=EF=BC=8C=E5=9C=A8=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E4=B9=8B=E5=89=8D=E5=88=A4=E6=96=B7=E3=80=81=E6=AF=8F=E6=AC=A1?= =?UTF-8?q?=E4=B8=80=E6=A8=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 計畫 R2(grok-build 的 Bash(git *)、deny > ask > allow 在模型之前)。用一般的話寫的規則交給模型判斷,每次可能不一樣,網頁上的字也可能把模型說成「允許」。 - gate.rs:is_pattern、glob(* 任何字、? 一個字;檔案的 * 只在一層、** 跨資料夾)、patterns:shell(…)(允許要每一段都符合,詢問只要一段;藏起來的指令 $()/反引號樣式不允許)、file(…)(讀檔、改檔、列資料夾、搜尋的路徑,~ 換成家目錄)、connector(…)(mcp__server__tool,use_connector_tool 也算)、web(domain:…)(web_fetch、browser_open 的網址,子網域算、example.com.evil.net 不算)、tool(…)。詢問的樣式贏過允許的樣式。 - agent::review_action:先看樣式。符合詢問 → 問(不能一律允許);符合允許 → 允許,但有用話寫的「一律詢問」時先讓模型看那幾條;都不符合 → 只把用話寫的規則交給模型(review_by_model)。直接操作模式下詢問的樣式一樣擋。 - 設定 › 權限 › 自動審核的說明寫樣式怎麼寫;功能地圖 safety.md、FEATURES.md。 已驗證:cargo test 580 全過、clippy -D warnings 過。新測試:glob;樣式的表格(13 種:git status 允許、git status && rm -rf x 不允許、git push 被詢問蓋過、$() 不允許、路徑、連接器、子網域和假網域、工具名);一輪:直接操作 + 一律詢問的 shell(echo *),那一步停下來問、卡上寫是哪一條規則,模型只被問了兩次(沒有額外的審核呼叫),檔案沒建。 未驗證:無。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 5 ++ docs/feature-map/safety.md | 1 + docs/plan-2026-11-engineering.md | 2 +- src/agent.rs | 53 ++++++++++++- src/app.rs | 2 +- src/gate.rs | 132 +++++++++++++++++++++++++++++++ 6 files changed, 190 insertions(+), 5 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 625a51e..4e83f50 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1510,6 +1510,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。 - 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。 +### 自動審核的固定樣式規則 + +- 「無需詢問直接允許」「一律詢問」除了用一般的話寫,也可以寫固定樣式:`shell(git *)`、`file(~/Projects/**)`、`connector(gitlab__*)`、`web(domain:example.com)`、`tool(browser_click)`(* 任何字,? 一個字;檔案的 * 只在一層、** 跨資料夾)。 +- 樣式在模型之前判斷,每次都一樣,不花模型的錢也不用等:符合「一律詢問」樣式的一定問,模型說允許也沒用(網頁上的字騙不了它);符合允許樣式的直接允許,但如果還有用話寫的「一律詢問」,先讓模型看那幾條;都不符合就照舊把用話寫的規則交給模型。指令要每一段(&&、|、; 分開的)都符合才算允許,有 $()、反引號藏指令的不會被樣式允許。直接操作模式下,「一律詢問」的樣式一樣擋得住。(參考 grok-build 的 Bash(git *) 規則。) + ### 用量(/usage) - 每一次模型呼叫(Bot 的每一步、快速模型、摘要、發布前檢查、目標檢查、支線…)都記一行在資料夾的 `usage/YYYY-MM.jsonl`:時間、供應商、模型、誰的、做什麼(從請求的 session 名稱看:anybot-bot-12 是 Bot 12 的回合)、輸入、輸出、快取讀寫的 token,供應商有回報花費(OpenRouter)時也記。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index 60ee2ad..3742fc7 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -12,6 +12,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - 一律放行(/always-approve,也可以打 /yolo):你自己打的指令,一把全開——打開直接操作,之後所有 Bot 要等「允許」的都自動允許,連直接操作還會問的(「一律詢問」規則、付款/傳送/刪除的點擊、寄信、傳訊息、AppleScript、打電話、簡訊、在 X 發文、保險庫卡片)也不問,自動審核也略過。仍然擋:安全規則一律拒絕的(下面那串);別人傳來的訊息(訊息管道、團隊成員)那一輪照樣等你按;問題卡、「需要處理」和 /plan 的計畫卡照樣等你。打開時已經在等的卡片(你自己的)一起放行。開著時每個聊天的輸入框上方有一條「一律放行 · Bot 做事不再問你」和「關閉」。「/always-approve off」關掉:要核准的又會問;直接操作是它順手打開的就一起關,本來就開著的留著。「/always-approve status」看現在是不是。管理員鎖了直接操作或「在這台電腦上執行」就打不開。 - 直接操作仍會問或擋:安全規則擋的;符合「一律詢問」規則的;畫面上目標寫著付款、傳送、刪除這類字的點擊;用「郵件」「訊息」寄送(「訊息」開了「無需詢問直接傳送」除外);沙盒外的 AppleScript(選「一律允許」前);打電話、傳簡訊、在 X 發文;用保險庫的卡片。問題卡和「需要處理」也照樣等你。 - 自動審核:兩組用一般的話寫的規則「無需詢問直接允許」「一律詢問」,由這個 Bot 的模型判斷,兩邊都符合時「一律詢問」優先。符合允許就直接做;符合詢問就問你,而且沒有「一律允許」;都不符合照常問;審核沒回應就先問你。 +- 固定樣式的規則:規則也可以寫成 `shell(git *)`(指令;允許要 `a && b` 每一段都符合,詢問只要一段)、`file(~/Projects/**)`(檔案或資料夾,** 任何層、* 一層)、`connector(gitlab__*)`(連接器的工具)、`web(domain:example.com)`(那個網站和它底下的網址)、`tool(browser_click)`(工具的名字)。樣式先判斷、每次一樣、不呼叫模型:符合「一律詢問」的樣式一定問(模型說允許也沒用);符合允許的樣式就允許,但用一般的話寫的「一律詢問」還是會先讓模型看一次;有藏起來的指令($()、反引號)的,樣式不會允許。 - 安全規則(你的電腦上): - 一律拒絕:sudo、su、rm -rf /、rm -rf ~、mkfs、dd、shutdown、reboot、diskutil erase、chmod -R 777 /。 - 私密檔案不能讀也不能改:AnyBot 自己的資料、.git、.ssh、.gnupg、鑰匙圈、.aws、.env、.pem、.key、id_rsa 這類金鑰、credentials 等。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index b40e75f..73175dc 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -67,7 +67,7 @@ - 做法:有人在看的一輪照舊(共 3 次);沒人在看的(例行任務、事件觸發、訊息管道、團隊成員)共 8 次、最長等 30 秒、±20% 抖動;Retry-After 照給的等(上限照舊 30 秒)。已經開始輸出就不重試(不變)。 - 做完:假模型注入 503 五次後成功:沒人看的一輪成功,有人看的照舊 3 次後失敗。 -### R2. 固定樣式的規則先判斷 ⬜ +### R2. 固定樣式的規則先判斷 ✅(shell、file、connector、web、tool 五種;browser(click:付款*) 沒做——付款/傳送/刪除的點擊本來就每次問) - 做法:「無需詢問直接允許」「一律詢問」多一種寫法:`shell(git *)`、`file(~/Projects/**)`、`connector(gitlab__*)`、`web(domain:example.com)`、`browser(click:付款*)`。先用樣式判斷(拒絕 > 詢問 > 允許;連在一起的指令每一段都要符合才算允許),判斷不了的才交給模型;模型說允許不能蓋過樣式的詢問。 - 做完:表格測試;`git status && rm -rf x` 不會因為 `shell(git *)` 被允許。 diff --git a/src/agent.rs b/src/agent.rs index 282be1e..60cc99f 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -206,7 +206,26 @@ pub const REVIEW_FAILED_NOTE: &str = "(自動審核沒有回應,所以先問 /// Ask the model whether an action matches the person's rules. "Ask first" wins on conflict /// (NFRGrQ: 規則衝突時,「先詢問」優先); built-in safety checks have already run before this. -fn review_action(job: &Job, review: &Review, action: &str, cancel: &AtomicBool) -> ReviewVerdict { +/// 自動審核: the pattern rules first (gate::patterns — the same every time; an ask pattern can't be +/// talked out of), then the sentence rules by the model. A pattern allow still yields to a +/// sentence 「一律詢問」 the model finds. +fn review_action(job: &Job, review: &Review, name: &str, args: &str, action: &str, cancel: &AtomicBool) -> ReviewVerdict { + use crate::gate::{is_pattern, patterns, PatternVerdict}; + let words = |v: &[String]| v.iter().filter(|r| !is_pattern(r)).cloned().collect::>(); + match patterns(name, args, &review.allow, &review.ask) { + PatternVerdict::Ask(rule) => ReviewVerdict::Ask(rule), + PatternVerdict::Allow(rule) => match words(&review.ask) { + ask if ask.is_empty() => ReviewVerdict::Allow(rule), + ask => match review_by_model(job, &Review { allow: vec![], ask }, action, cancel) { + ReviewVerdict::NoMatch | ReviewVerdict::Allow(_) => ReviewVerdict::Allow(rule), + other => other, + }, + }, + PatternVerdict::NoMatch => review_by_model(job, &Review { allow: words(&review.allow), ask: words(&review.ask) }, action, cancel), + } +} + +fn review_by_model(job: &Job, review: &Review, action: &str, cancel: &AtomicBool) -> ReviewVerdict { if review.allow.is_empty() && review.ask.is_empty() { return ReviewVerdict::NoMatch; } @@ -3104,7 +3123,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< // call to check (it cost every look at the person's Mac 10–20 s). let looks = matches!(call.name.as_str(), "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "browser_read" | "read_file" | "list_dir" | "search"); let verdict = match review { - Some(rv) if !rv.ask.is_empty() && !looks => review_action(&job, &Review { allow: vec![], ask: rv.ask.clone() }, &reason, &cancel), + Some(rv) if !rv.ask.is_empty() && !looks => review_action(&job, &Review { allow: vec![], ask: rv.ask.clone() }, &call.name, &call.args, &reason, &cancel), _ => ReviewVerdict::NoMatch, }; match verdict { @@ -3124,7 +3143,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } } } - (Decision::Ask { reason, grant }, Some(rv)) => match review_action(&job, rv, &reason, &cancel) { + (Decision::Ask { reason, grant }, Some(rv)) => match review_action(&job, rv, &call.name, &call.args, &reason, &cancel) { ReviewVerdict::Allow(rule) => { review_note = format!("(自動審核:符合「{rule}」,直接允許)\n"); Decision::Allow @@ -5477,6 +5496,34 @@ echo 'done送出了' > done.html; (setsid pyt assert!(matches!(evs.last(), Some(StreamEvent::Done))); } + /// R2: in 直接操作, an 「一律詢問」 pattern stops the step and asks — decided without a model + /// call (the fake model is asked for the turn's two steps only), and named on the card. + #[test] + fn an_ask_pattern_stops_direct_mode_without_asking_a_model() { + let call = serde_json::json!({"command": "echo hi > made.txt", "computer": crate::model::THIS_COMPUTER_NAME}); + let (port, seen) = fake_http(vec![sse_call("c1", "shell", call), sse_text("好,不做")]); + let w = std::env::temp_dir().join(format!("anybot-pattern-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&w); + std::fs::create_dir_all(&w).unwrap(); + let job = Job { + req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("做一個檔案")], tools: tools::specs(), session: String::new(), effort: String::new() }, + computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }], + default_computer: crate::model::THIS_COMPUTER_NAME.into(), + roles: tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false }, + local_execution: true, + direct: Arc::new(AtomicBool::new(true)), + review: Some(Review { allow: vec![], ask: vec!["shell(echo *)".into()] }), + ..test_job() + }; + let (evs, asked) = drive(job, ApprovalAnswer::Reject); + assert_eq!(asked.len(), 1, "{asked:?}"); + assert!(asked[0].contains("符合你的「一律詢問」規則:shell(echo *)"), "{}", asked[0]); + assert_eq!(seen.lock().unwrap().len(), 2, "no model call to review it"); + assert!(!w.join("made.txt").exists()); + assert!(matches!(evs.last(), Some(StreamEvent::Done))); + let _ = std::fs::remove_dir_all(&w); + } + /// 問題卡: the turn waits on the card; the answers come back numbered, a skip says so. #[test] fn a_question_card_waits_and_brings_back_the_answers() { diff --git a/src/app.rs b/src/app.rs index 15d9cf4..0794b64 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5631,7 +5631,7 @@ impl App { } }); }); - hint(ui, "為每種操作寫一條簡短的自然語言規則。規則衝突時,「先詢問」優先。這些規則只對你生效。內建的安全檢查一律有效。", p); + hint(ui, "為每種操作寫一條簡短的自然語言規則。規則衝突時,「先詢問」優先。這些規則只對你生效。內建的安全檢查一律有效。也可以寫成固定樣式,每次判斷都一樣、不用等模型:shell(git *)、file(~/Projects/**)、connector(gitlab__*)、web(domain:example.com)、tool(browser_click)。", p); if !self.state.auto_review { hint(ui, "自動審核關閉時不會使用規則", p); } diff --git a/src/gate.rs b/src/gate.rs index b3eb58c..e46c71b 100644 --- a/src/gate.rs +++ b/src/gate.rs @@ -188,3 +188,135 @@ mod tests { assert_eq!(a("computer_use_click", none, deny.clone(), true, true, &[]).decision, deny, "a refusal stays a refusal"); } } + +// ---------- 固定樣式的規則 (R2) ---------- +// 「無需詢問直接允許」 and 「一律詢問」 rules may be written as a pattern instead of a sentence: +// shell(git *) a command (every part of `a && b | c` for an allow; any part for an ask) +// file(~/Projects/**) a file or folder a step reads or changes (** any depth, * one name) +// connector(gitlab__*) a connector's tool (server__tool) +// web(domain:example.com) a page opened or fetched on that site (or below it) +// tool(browser_click) a step by its tool's name +// They are decided here, the same every time, before the model reads the sentence rules: an ask +// pattern can't be talked out of by anything the model read (grok-build's deny > ask > allow +// rules, checked before its model). + +/// What the pattern rules say about a step. +#[derive(Clone, Debug, PartialEq)] +pub enum PatternVerdict { + Ask(String), + Allow(String), + NoMatch, +} + +/// A rule written as a pattern (else it is a sentence for the model). +pub fn is_pattern(rule: &str) -> bool { + let r = rule.trim(); + ["shell(", "file(", "connector(", "web(", "tool("].iter().any(|p| r.starts_with(p)) && r.ends_with(')') +} + +/// `*` any run of characters, `?` one; with `slash_stops`, `*` stays within one path name and +/// `**` crosses folders. +pub fn glob(pat: &str, text: &str, slash_stops: bool) -> bool { + fn go(p: &[char], t: &[char], slash_stops: bool) -> bool { + match p.first() { + None => t.is_empty(), + Some('*') if p.get(1) == Some(&'*') => (0..=t.len()).any(|i| go(&p[2..], &t[i..], slash_stops)), + Some('*') => (0..=t.len()).take_while(|&i| i == 0 || !(slash_stops && t[i - 1] == '/')).any(|i| go(&p[1..], &t[i..], slash_stops)), + Some('?') => !t.is_empty() && go(&p[1..], &t[1..], slash_stops), + Some(c) => t.first() == Some(c) && go(&p[1..], &t[1..], slash_stops), + } + } + let (p, t): (Vec, Vec) = (pat.chars().collect(), text.chars().collect()); + go(&p, &t, slash_stops) +} + +fn host_of(url: &str) -> String { + url.split("://").nth(1).unwrap_or(url).split(['/', ':', '?', '#']).next().unwrap_or("").to_ascii_lowercase() +} + +/// Whether `rule` (a pattern) is about this step; `all` for an allow (every part of a command +/// must match), any part for an ask. +fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) -> bool { + let r = rule.trim(); + let Some((kind, inner)) = r.split_once('(').map(|(k, rest)| (k, rest.strip_suffix(')').unwrap_or(rest).trim())) else { return false }; + let s = |k: &str| args[k].as_str().unwrap_or("").trim().to_string(); + match kind { + "shell" if name == "shell" => { + let cmd = s("command"); + match tools::split_commands(&cmd) { + Some(parts) if !parts.is_empty() => { + let hit = |p: &String| glob(inner, p.trim(), false); + if all { parts.iter().all(hit) } else { parts.iter().any(hit) } + } + // Hidden commands ($(), backticks): an allow can't vouch for what it can't see; an + // ask still looks at the whole line. + _ => !all && glob(inner, &cmd, false), + } + } + "file" if matches!(name, "read_file" | "edit_file" | "list_dir" | "search" | "write_file") => { + let path = s("path"); + let home = |p: &str| tools::expand_home(p).display().to_string(); + !path.is_empty() && (glob(inner, &path, true) || glob(&home(inner), &home(&path), true)) + } + "connector" => { + let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() }; + tool.strip_prefix("mcp__").is_some_and(|t| glob(inner, t, false)) + } + "web" if matches!(name, "web_fetch" | "browser_open") => { + let host = host_of(&s("url")); + let want = inner.strip_prefix("domain:").unwrap_or(inner).trim().to_ascii_lowercase(); + !host.is_empty() && (host == want || host.ends_with(&format!(".{want}"))) + } + "tool" => glob(inner, name, false), + _ => false, + } +} + +/// The pattern rules' word on a step: any ask pattern about it asks (over any allow); else an +/// allow pattern that covers it allows; else they say nothing (the sentences go to the model). +pub fn patterns(name: &str, args: &str, allow: &[String], ask: &[String]) -> PatternVerdict { + let v = tools::args_of(args); + if let Some(r) = ask.iter().filter(|r| is_pattern(r)).find(|r| pattern_matches(r, name, &v, false)) { + return PatternVerdict::Ask(r.trim().to_string()); + } + if let Some(r) = allow.iter().filter(|r| is_pattern(r)).find(|r| pattern_matches(r, name, &v, true)) { + return PatternVerdict::Allow(r.trim().to_string()); + } + PatternVerdict::NoMatch +} + +#[cfg(test)] +mod pattern_tests { + use super::*; + + #[test] + fn globs() { + assert!(glob("git *", "git status", false) && !glob("git *", "gitk", false)); + assert!(glob("npm ?un *", "npm run build", false)); + assert!(glob("/a/**", "/a/b/c.txt", true) && glob("/a/*", "/a/b", true) && !glob("/a/*", "/a/b/c", true)); + } + + /// R2 as a table: the same answer every time, an ask over an allow, a chained command allowed + /// only when every part is. + #[test] + fn pattern_rules_decide_before_the_model() { + let rules = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let allow = rules(&["shell(git *)", "file(~/Projects/**)", "connector(gitlab__get_*)", "web(domain:example.com)", "只是一句話的規則"]); + let ask = rules(&["shell(git push*)", "tool(browser_click)"]); + let p = |name: &str, args: serde_json::Value| patterns(name, &args.to_string(), &allow, &ask); + let sh = |c: &str| serde_json::json!({"command": c}); + assert_eq!(p("shell", sh("git status")), PatternVerdict::Allow("shell(git *)".into())); + assert_eq!(p("shell", sh("git status && git log")), PatternVerdict::Allow("shell(git *)".into())); + assert_eq!(p("shell", sh("git status && rm -rf x")), PatternVerdict::NoMatch, "every part, or no allow"); + assert_eq!(p("shell", sh("git add . && git push origin main")), PatternVerdict::Ask("shell(git push*)".into()), "an ask over an allow"); + assert_eq!(p("shell", sh("echo $(git status)")), PatternVerdict::NoMatch, "a hidden command is never allowed by a pattern"); + assert_eq!(p("read_file", serde_json::json!({"path": "~/Projects/a/b.rs"})), PatternVerdict::Allow("file(~/Projects/**)".into())); + assert_eq!(p("read_file", serde_json::json!({"path": "~/Documents/x"})), PatternVerdict::NoMatch); + assert_eq!(p("mcp__gitlab__get_issue", serde_json::json!({})), PatternVerdict::Allow("connector(gitlab__get_*)".into())); + assert_eq!(p(crate::mcp::USE_TOOL, serde_json::json!({"tool": "mcp__gitlab__delete_project"})), PatternVerdict::NoMatch); + assert_eq!(p("web_fetch", serde_json::json!({"url": "https://docs.example.com/a"})), PatternVerdict::Allow("web(domain:example.com)".into())); + assert_eq!(p("web_fetch", serde_json::json!({"url": "https://example.com.evil.net/"})), PatternVerdict::NoMatch); + assert_eq!(p("browser_click", serde_json::json!({})), PatternVerdict::Ask("tool(browser_click)".into())); + assert!(is_pattern("shell(ls)") && !is_pattern("刪除檔案前先問我") && !is_pattern("shell ls")); + } +}