AnyBot/src/smart.rs

204 lines
9.3 KiB
Rust
Raw Normal View History

智慧模式 (/smart): 一问一决定,不是一步一卡 询问和一律放行中间的设定(CLAUDE.md 改善轮迴的第一块:聊天卡顿的主因是一步一卡)。 - 卡片多一个「这轮都准」: 同类操作这一轮只问一次(Job 就是一轮,按构造就是 per-turn; 下一轮会再问)。grant 非空的 Action 卡与连接器卡有这按钮;must-ask(付款/传送/删除的 点击、你的屏幕和 App、保险库、一律询问规则、hook)没有,也不被覆盖。 - 卡片逾时: 你几分钟没回,卡片自己回答——看档案/上网这类先做(步骤结果里写明),敏感操作 自动拒绝并告诉 Bot 别重试。/smart 中途开关都即时(窗口一个 Arc,Job 共享)。 - 审核缓存: 自动审核的模型判决这一轮按(规则,动作)缓存,重复同一步不再每次付 10–20 秒; 审查看不见档案全文时照旧自己问(没动)。 - 开关: /smart(/smart off、status)、设定›权限(滑块调时限,默认 300 秒)、输入列旁图标。 手机/远端只能关不能开(words_loosen + remote setting 只收紧);untrusted 回合永不智慧。 - 锁: 管理员锁住直接操作/本地执行时,智慧模式一起锁。 - feature-map: chat.md / safety.md / autonomy.md / settings.md 同步(featuremap 测试绿)。 已验证: cargo test 全绿 716(含 featuremap::、layout_audit::、approval/tool 锁未动) 未验证: 实机批准卡路径(新按钮、逾时行为)需人类实机点测并签名(CLAUDE.md 审批准则)
2026-11-19 06:59:29 +00:00
//! 智慧模式 (/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.)
//!
//! The person turns it on (「/smart」, the switch in 設定 › 權限), never a bot, a routine, a
//! channel, or a phone on a direct connection (words_loosen covers /smart on). Admin locks on
//! 直接操作/在這台電腦上執行 lock 智慧模式 too. It is off by default.
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、保險庫、你的「一律詢問」規則、問題卡、「需要處理」;安全規則一律拒絕的照樣擋。\n關掉:/smart off,或 設定 › 權限。";
pub const OFF_NOTE: &str = "已關閉智慧模式:要核准的事照樣一件件問你。";
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 = if timeout_secs == 0 {
"卡片逾時:關閉".into()
} else {
format!("卡片逾時:{timeout_secs} 秒沒回,低風險自動放行、敏感操作自動拒絕")
};
if on {
format!("現在是智慧模式:同類操作一輪問一次;{timeout}。關掉用 /smart off。")
} else {
format!("現在沒有智慧模式:要核准的事會一件件問你。{timeout}。打開用 /smart。")
}
}
/// The line above the input while it is on.
pub const BAR: &str = "智慧模式 · 同類操作一輪問一次(敏感操作照樣問)";
/// 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).
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("/smart off"));
assert!(status_note(true, 300).contains("智慧模式") && status_note(true, 300).contains("300 秒"));
assert!(status_note(false, 0).contains("卡片逾時:關閉"));
assert!(BAR.contains("智慧模式"));
}
}