AnyBot/src/smart.rs

210 lines
9.9 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.

//! 智慧模式 (/smart): the middle setting between 詢問 every step and 一律放行.
//!
//! It rides on top of the existing gates (gate.rs) — it changes nothing about what is refused,
//! what is asked, or the order they are checked in. It adds two things, and only to a question
//! the gates already decided to ask (never to a refusal, a 問題卡, a 需要處理, a hook's ask,
//! a step a 一律詢問 rule named, a sensitive click, sending, outside-sandbox AppleScript —
//! the things 「直接操作」 still asks too, marked `must_ask` in the loop):
//!
//! - 這輪都准: answering a card with Scope(grant) remembers that grant for the rest of the
//! turn (Job is one turn, so the memory is per-turn by construction; a new turn asks again).
//! It is the plan-card in miniature: one decision per category per turn, not per step.
//! - 卡片逾時: a question nobody answers answers itself after a while — by the step's tier.
//! Safe/Work steps go ahead (the person is away, the step is low-risk, the note says so in
//! the step's result); Sensitive steps are refused (a check that goes unanswered, blocks).
//!
//! The tier is rules alone (no model), the same every time:
//! - Safe: looking (screenshots, reads, web) — changes nothing.
//! - Work: the bot's own work (commands, files in its folders, its browser, a connector call).
//! - Sensitive: anything on the person's own computer with hands (clicks, keys), sending from
//! the person's apps, the vault, filling a login/card, publishing. (The must_ask paths above
//! never reach the timeout at all; this tier covers what's left.)
//!
//! It is always on: the person asked for bots that keep going, and nothing it does reaches past
//! the gates above. Only an admin's lock on 直接操作/在這台電腦上執行 keeps it off (it grants the
//! same ground). 「/smart off」 and the old switch say so instead of turning it off; the card
//! timeout (設定 › 權限) stays the person's to set, from 30 seconds up.
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
/// What 「/smart …」 asks for.
#[derive(Debug, PartialEq)]
pub enum Command {
On,
Off,
Status,
}
/// 「/smart」, with 「off」 or 「status」; None for anything else.
pub fn command(text: &str) -> Option<Command> {
let t = text.trim();
let rest = t.strip_prefix("/smart").or_else(|| t.strip_prefix("/yolo-soft"))?;
if rest.chars().next().is_some_and(|c| !c.is_whitespace()) {
return None;
}
Some(match rest.trim().to_lowercase().as_str() {
"" | "on" | "開" | "打開" | "開啟" => Command::On,
"off" | "stop" | "關" | "關閉" | "關掉" | "取消" | "停止" => Command::Off,
_ => Command::Status,
})
}
pub const ON_NOTE: &str = "智慧模式一直開著:Bot 要問你的事,同一類這一輪只問一次(按「這輪都准」後同類直接做);你幾分鐘沒回的卡片,低風險的直接做(步驟裡會寫),敏感操作的自動拒絕。\n仍然會問、會擋:付款/傳送/刪除的點擊、寄信傳訊息、你的螢幕和 App、保險庫、你的「一律詢問」規則、問題卡、「需要處理」;安全規則一律拒絕的照樣擋。";
/// What 「/smart off」 (and an old phone's switch) is told: it stays on.
pub const OFF_NOTE: &str = "智慧模式一直開著,不能關:它只讓同一類操作一輪問一次、沒人回的卡片自己處理,付款、傳送、刪除、你的螢幕和 App 照樣問你。卡片要等久一點,到 設定 › 權限 把「卡片等多久」調長。";
/// The shortest card timeout (設定 › 權限): 0 used to mean 「never answers itself」 — off by
/// another name.
pub const MIN_TIMEOUT_SECS: u64 = 30;
pub const LOCKED_NOTE: &str = "沒辦法打開智慧模式:「直接操作」或「在這台電腦上執行」被你的管理員鎖住了。";
/// What 「/smart status」 says. `timeout_secs`: 0 is the card timeout off.
pub fn status_note(on: bool, timeout_secs: u64) -> String {
let timeout = format!("卡片逾時:{} 秒沒回,低風險自動放行、敏感操作自動拒絕", timeout_secs.max(MIN_TIMEOUT_SECS));
if on {
format!("智慧模式一直開著:同類操作一輪問一次;{timeout}。")
} else {
format!("智慧模式被你的管理員關掉了:要核准的事會一件件問你。{timeout}。")
}
}
/// How risky a step is, for what an unanswered card answers itself with.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Tier {
/// Looking only: a screenshot, a read, a page fetched.
Safe,
/// The bot's own work: commands, its files, its browser, a connector.
Work,
/// The person's computer with hands, their apps sending, the vault, a login, publishing.
Sensitive,
}
/// The step's tier. `on_persons`: it runs on the person's own computer or another of their
/// devices (not the bot's box). Rules alone — no model, the same every time.
pub fn tier(name: &str, on_persons: bool) -> Tier {
use crate::{computer, macapps, web};
if matches!(name, "publish_site" | "browser_fill_login" | "browser_fill_card" | "browser_fill_contact") {
return Tier::Sensitive;
}
if name == crate::vault::LIST_TOOL {
return Tier::Safe;
}
if macapps::is_mac_tool(name) {
// Reading an app is looking; writing or sending from it is the person's.
return if macapps::is_send(name) || macapps::is_write(name) { Tier::Sensitive } else { Tier::Safe };
}
if computer::is_computer_tool(name) {
if !on_persons {
return Tier::Work;
}
return if computer::NAMES[..3].contains(&name) { Tier::Safe } else { Tier::Sensitive };
}
if web::is_web_tool(name) {
return Tier::Safe;
}
Tier::Work
}
/// The turn's part of 智慧模式, on the Job (a Job is one turn, so what it remembers is per-turn).
#[derive(Default)]
pub struct Smart {
/// The mode; the window can switch it mid-turn (the App and every live stream share one Arc).
pub on: Arc<AtomicBool>,
/// How long a question may wait before it answers itself (Duration::ZERO: never).
pub timeout: Duration,
/// 「這輪都准」: the grants the person widened to this turn.
pub scopes: std::cell::RefCell<Vec<String>>,
/// 自動審核: the reviewer's verdicts this turn, so the same step never pays for a model
/// call twice (keyed by exactly the words the reviewer reads).
pub reviews: std::cell::RefCell<std::collections::HashMap<String, crate::agent::ReviewVerdict>>,
}
impl Smart {
/// Off, and never turns on (tests, untrusted turns).
/// 開著,用預設逾時。
#[cfg(test)]
pub fn on(timeout: Duration) -> Smart {
Self { on: Arc::new(AtomicBool::new(true)), timeout, scopes: std::cell::RefCell::new(vec![]), reviews: std::cell::RefCell::new(std::collections::HashMap::new()) }
}
pub fn off() -> Smart {
Smart::default()
}
pub fn new(on: Arc<AtomicBool>, timeout: Duration) -> Smart {
Smart { on, timeout, scopes: Default::default(), reviews: Default::default() }
}
pub fn active(&self) -> bool {
self.on.load(std::sync::atomic::Ordering::Relaxed)
}
/// Whether this turn already has a 「這輪都准」 for that grant.
pub fn scoped(&self, grant: &str) -> bool {
!grant.is_empty() && self.scopes.borrow().iter().any(|g| g == grant)
}
pub fn scope(&self, grant: &str) {
if !grant.is_empty() && !self.scoped(grant) {
self.scopes.borrow_mut().push(grant.to_string());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_command_and_its_words() {
assert_eq!(command("/smart"), Some(Command::On));
assert_eq!(command(" /smart on "), Some(Command::On));
assert_eq!(command("/smart 打開"), Some(Command::On));
assert_eq!(command("/smart off"), Some(Command::Off));
assert_eq!(command("/smart 關掉"), Some(Command::Off));
assert_eq!(command("/smart status"), Some(Command::Status));
assert_eq!(command("/smartx"), None);
assert_eq!(command("請 /smart"), None);
}
/// The tier table: what a step's risk is, by kind and where it lands.
#[test]
fn tiers_by_kind_and_place() {
assert_eq!(tier("computer_use_screenshot", true), Tier::Safe, "looking at the person's screen");
assert_eq!(tier("computer_use_click", true), Tier::Sensitive, "hands on the person's screen");
assert_eq!(tier("computer_use_click", false), Tier::Work, "its own desktop");
assert_eq!(tier("mac_send_message", false), Tier::Sensitive, "a message from the person's Messages");
assert_eq!(tier("mac_read_notes", false), Tier::Safe, "reading an app is looking");
assert_eq!(tier("browser_fill_login", false), Tier::Sensitive);
assert_eq!(tier("vault_list", false), Tier::Safe);
assert_eq!(tier("publish_site", false), Tier::Sensitive);
assert_eq!(tier("web_fetch", false), Tier::Safe);
assert_eq!(tier("shell", false), Tier::Work);
assert_eq!(tier("edit_file", false), Tier::Work);
assert_eq!(tier("mcp__gitlab__get_issue", false), Tier::Work);
}
#[test]
fn scopes_are_per_turn_words() {
let s = Smart::off();
assert!(!s.scoped("edit_file"));
s.scope("edit_file");
s.scope("");
assert!(s.scoped("edit_file") && !s.scoped(""), "an empty grant is nothing to remember");
assert!(!s.active());
}
#[test]
fn the_notes_say_what_stays_asked() {
assert!(ON_NOTE.contains("這輪都准") && ON_NOTE.contains("仍然會問") && ON_NOTE.contains("一直開著"));
assert!(OFF_NOTE.contains("不能關") && OFF_NOTE.contains("照樣問你"));
assert!(status_note(true, 300).contains("一直開著") && status_note(true, 300).contains("300 秒"));
assert!(status_note(true, 0).contains("30 秒"), "0 is no longer 「never」");
assert!(status_note(false, 300).contains("管理員"));
}
}