diff --git a/src/agent.rs b/src/agent.rs index 2f275f0..a6f6642 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -57,6 +57,9 @@ pub struct Job { pub tools_enabled: bool, /// 直接操作 mode; the window can switch it on mid-turn ("全部允許"). pub direct: Arc, + /// 智慧模式 (/smart): the turn's scope grants, the reviewer's cache, the card timeout + /// (see smart.rs; off by default — `Smart::off()`). + pub smart: crate::smart::Smart, /// 在這台電腦上執行 is locked off by an admin policy: refuse, don't ask. pub local_locked: bool, pub grants: Vec, @@ -192,6 +195,7 @@ pub struct Review { pub ask: Vec, } +#[derive(Clone)] pub enum ReviewVerdict { Allow(String), Ask(String), @@ -229,6 +233,22 @@ fn review_by_model(job: &Job, review: &Review, action: &str, cancel: &AtomicBool if review.allow.is_empty() && review.ask.is_empty() { return ReviewVerdict::NoMatch; } + // The reviewer cache: the same words the reviewer would read get the same verdict, paid for + // once per turn (a repeated step shouldn't pay 10–20 s of a model every time; 智慧模式 ships + // with it, and it serves any turn where the same step comes back). A failed review is not + // cached: it is a check that broke, and the next step may find it well. + let key = format!("{}\u{1}{}", review.allow.join("\u{2}"), review.ask.join("\u{2}")) + "\u{1}" + action; + if let Some(v) = job.smart.reviews.borrow().get(&key) { + return v.clone(); + } + let v = review_by_model_now(job, review, action, cancel); + if !matches!(v, ReviewVerdict::Failed) { + job.smart.reviews.borrow_mut().insert(key, v.clone()); + } + v +} + +fn review_by_model_now(job: &Job, review: &Review, action: &str, cancel: &AtomicBool) -> ReviewVerdict { // A file's contents in the arguments would fill the reviewer's context. The ends are enough // to match a sentence rule; a yes that only saw them still asks (steps::reviewed). let action = steps::for_reviewer(action); @@ -2403,6 +2423,7 @@ mod tests { via_name: String::new(), tools_enabled: true, direct: Arc::new(AtomicBool::new(false)), + smart: crate::smart::Smart::off(), local_locked: false, steer: Arc::new(Mutex::new(vec![])), review: None, @@ -2790,6 +2811,7 @@ mod tests { local_execution: true, tools_enabled: true, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), skills: vec![skill], ..test_job() }; @@ -2910,6 +2932,7 @@ mod tests { local_execution: true, tools_enabled: true, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), via: "Custom · main".into(), ..test_job() }; @@ -2987,6 +3010,7 @@ mod tests { local_execution: true, tools_enabled: true, direct: Arc::new(AtomicBool::new(false)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3174,6 +3198,7 @@ mod tests { local_execution: true, tools_enabled: true, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), grants: if granted { vec![tools::OSASCRIPT_GRANT.into()] } else { vec![] }, ..test_job() }; @@ -3260,6 +3285,7 @@ mod tests { roles: tools::Roles { own, person: None, server: true }, local_execution: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3309,6 +3335,7 @@ mod tests { roles: tools::Roles { own: own.into(), person: None, server: true }, local_execution: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3371,6 +3398,7 @@ printf 'a,b\n1,2\n' > report.csv && printf 'hello box' > '/tmp/anybot-up/上傳 roles: tools::Roles { own: own.into(), person: None, server: true }, local_execution: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3421,6 +3449,7 @@ printf 'a,b\n1,2\n' > report.csv && printf 'hello box' > '/tmp/anybot-up/上傳 roles: tools::Roles { own: own.into(), person: None, server: true }, local_execution: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3463,6 +3492,7 @@ printf 'a,b\n1,2\n' > report.csv && printf 'hello box' > '/tmp/anybot-up/上傳 roles: tools::Roles { own: own.into(), person: None, server: true }, local_execution: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3567,6 +3597,7 @@ echo 'done送出了' > done.html; (setsid pyt roles: tools::Roles { own: own.into(), person: None, server: true }, local_execution: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), ..test_job() }; let (tx, rx) = channel(); @@ -3958,6 +3989,7 @@ echo 'done送出了' > done.html; (setsid pyt via_name: "Bot".into(), tools_enabled: true, direct: Arc::new(AtomicBool::new(false)), + smart: crate::smart::Smart::off(), local_locked: false, steer: Arc::new(Mutex::new(vec![])), review: None, @@ -4047,6 +4079,7 @@ echo 'done送出了' > done.html; (setsid pyt via_name: "Bot".into(), tools_enabled: true, direct: Arc::new(AtomicBool::new(false)), + smart: crate::smart::Smart::off(), local_locked: false, steer, review: None, @@ -4135,6 +4168,7 @@ echo 'done送出了' > done.html; (setsid pyt close_browsers: true, tools_enabled: false, direct: Arc::new(AtomicBool::new(false)), + smart: crate::smart::Smart::off(), local_locked: false, grants: vec![], context_tokens: DEFAULT_CONTEXT_TOKENS, @@ -4363,6 +4397,7 @@ echo 'done送出了' > done.html; (setsid pyt close_browsers: true, tools_enabled: false, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), local_locked: false, grants: vec![], context_tokens: DEFAULT_CONTEXT_TOKENS, @@ -4626,6 +4661,7 @@ echo 'done送出了' > done.html; (setsid pyt 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 }, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), review: Some(Review { allow: vec![], ask: vec!["刪除或修改任何檔案前先問我".into()] }), ..test_job() }; @@ -4651,6 +4687,7 @@ echo 'done送出了' > done.html; (setsid pyt 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 }, direct: Arc::new(AtomicBool::new(true)), + smart: crate::smart::Smart::off(), review: Some(Review { allow: vec![], ask: vec!["刪除或修改任何檔案前先問我".into()] }), ..test_job() }; @@ -4680,6 +4717,7 @@ echo 'done送出了' > done.html; (setsid pyt 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)), + smart: crate::smart::Smart::off(), review: Some(Review { allow: vec![], ask: vec!["shell(echo *)".into()] }), ..test_job() }; @@ -4711,6 +4749,7 @@ echo 'done送出了' > done.html; (setsid pyt 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: crate::mcp::specs(), session: String::new(), effort: String::new() }, direct: Arc::new(AtomicBool::new(direct)), + smart: crate::smart::Smart::off(), review, grants: grants.iter().map(|g| g.to_string()).collect(), ..test_job() @@ -4841,6 +4880,7 @@ echo 'done送出了' > done.html; (setsid pyt computers: vec![tools::Target { name: "筆電".into(), place: tools::Place::Device { host: "h-test".into(), dir: String::new() } }], default_computer: "筆電".into(), direct: Arc::new(AtomicBool::new(direct)), + smart: crate::smart::Smart::off(), review, grants: grants.iter().map(|g| g.to_string()).collect(), ..test_job() @@ -5283,6 +5323,7 @@ echo 'done送出了' > done.html; (setsid pyt 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)), + smart: crate::smart::Smart::off(), drafting: Some(Drafting { plan, tools: every, system: "你是 Bot。".into() }), ..test_job() }; diff --git a/src/agent/steps.rs b/src/agent/steps.rs index 732d478..ed5d4fe 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -150,6 +150,48 @@ impl Step<'_> { (self.send)(StreamEvent::NeedApproval(Approval { call_id: self.call.id.clone(), tool: self.call.name.clone(), reason, grant, reply: atx, kind })); wait_answer(arx, self.cancel, self.said_no) } + + /// Ask with 智慧模式's extras (see smart.rs): the card understands 「這輪都准」 (Scope), and a + /// card nobody answers answers itself after the turn's timeout — a Safe/Work step goes ahead + /// (the step's result says so), a Sensitive one is refused. Outside 智慧模式 (or on an + /// untrusted turn) it is the plain question. Returns (the answer, the auto-answer's note). + pub fn ask_smart(&self, reason: String, grant: String, tier: crate::smart::Tier) -> (ApprovalAnswer, Option) { + if self.job.untrusted || !self.job.smart.active() { + return (self.ask_person(ApprovalKind::Action, reason, grant), None); + } + let (atx, arx) = channel(); + (self.send)(StreamEvent::ToolStatus(self.call.id.clone(), ToolStatus::Waiting)); + (self.send)(StreamEvent::NeedApproval(Approval { call_id: self.call.id.clone(), tool: self.call.name.clone(), reason, grant, reply: atx, kind: ApprovalKind::Action })); + let limit = self.job.smart.timeout; + let start = Instant::now(); + loop { + if self.cancel.load(Ordering::Relaxed) { + return (ApprovalAnswer::Reject, None); + } + match arx.recv_timeout(std::time::Duration::from_millis(200)) { + Ok(a) => { + self.said_no.set(a == ApprovalAnswer::Reject); + return (a, None); + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return (ApprovalAnswer::Reject, None), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + if !limit.is_zero() && start.elapsed() >= limit { + let secs = limit.as_secs(); + return match tier { + crate::smart::Tier::Sensitive => ( + ApprovalAnswer::Reject, + Some(format!("{secs} 秒沒有人回應,這是敏感操作,智慧模式已自動拒絕。不要再試同一件事;告訴使用者你卡在哪裡、需要他允許什麼。")), + ), + _ => ( + ApprovalAnswer::Once, + Some(format!("(智慧模式:{secs} 秒沒有人回應,這不是敏感操作,先做了;使用者可以在「顯示步驟」看到這一步。)")), + ), + }; + } + } + } + } + } } /// A tool as a turn runs it. @@ -645,7 +687,7 @@ impl TurnTool for InBotsBrowser { review_note = note; if let Decision::Ask { reason, grant } = decision { match s.ask_person(ApprovalKind::Action, format!("{reason}{on_line}"), grant) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {} + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => {} ApprovalAnswer::Always(g) => keep_grant(s.grants, g), ApprovalAnswer::Reject => { s.finish("使用者拒絕了開啟這個內部網址。", ToolStatus::Denied, None); @@ -684,7 +726,7 @@ impl TurnTool for InBotsBrowser { send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("{reason}\n(在 {} 上)", here.name), grant, reply: atx, kind: ApprovalKind::Action })); match wait_answer(arx, cancel, said_no) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => None, + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => None, ApprovalAnswer::Always(g) => { keep_grant(s.grants, g); None @@ -720,7 +762,7 @@ impl TurnTool for InBotsBrowser { send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting)); send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("{reason}\n(在 {on} 上)"), grant, reply: atx, kind: ApprovalKind::Action })); match wait_answer(arx, cancel, said_no) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {} + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => {} ApprovalAnswer::Always(g) => keep_grant(s.grants, g), ApprovalAnswer::Reject => { s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None); @@ -1329,7 +1371,7 @@ impl TurnTool for PublishSite { if !allowed { let from = if outside { "(在工作資料夾以外)" } else { "" }; match s.ask_person(ApprovalKind::Action, format!("把 {path}{from} 發布成公開網站「{name}」(任何知道網址的人都看得到)"), grant.clone()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true, + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => allowed = true, ApprovalAnswer::Always(g) => { keep_grant(s.grants, g); allowed = true; @@ -1495,7 +1537,7 @@ impl TurnTool for VaultFill { let mut remember_site = false; if !allowed { match s.ask_person(ApprovalKind::Action, question, grant.clone()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true, + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => allowed = true, ApprovalAnswer::Always(g) => { keep_grant(s.grants, g); allowed = true; @@ -1718,17 +1760,44 @@ impl TurnTool for Connector { }; let hook_ask = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, why)| why); let (decision, note) = connector_decision(job, s.grants, &mcp_name, &mcp_args, hook_ask.as_deref(), cancel); + let mut auto_no: Option = None; let allowed = match decision { Decision::Allow => true, Decision::Deny(_) => false, - Decision::Ask { reason, grant } => match s.ask_person(ApprovalKind::Action, reason, grant) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => true, - ApprovalAnswer::Always(g) => { - keep_grant(s.grants, g); + Decision::Ask { reason, grant } => { + // 智慧模式: 「這輪都准」 covers this connector for the rest of the turn. + if s.job.smart.active() && s.job.smart.scoped(&grant) { + s.step_note.set("(智慧模式:你這一輪已准過這個連接器,這一步直接做。)".into()); true + } else { + let (answer, auto) = if hook_ask.is_some() { + // A hook's ask is a must-ask: 智慧模式 never answers it by itself. + (s.ask_person(ApprovalKind::Action, reason, grant), None) + } else { + s.ask_smart(reason, grant, crate::smart::Tier::Work) + }; + match answer { + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => { + if let Some(note) = auto { + s.step_note.set(note); + } + true + } + ApprovalAnswer::Scope(g) => { + s.job.smart.scope(&g); + true + } + ApprovalAnswer::Always(g) => { + keep_grant(s.grants, g); + true + } + ApprovalAnswer::Reject => { + auto_no = auto; + false + } + } } - ApprovalAnswer::Reject => false, - }, + } }; if cancel.load(Ordering::Relaxed) { return Flow::End; @@ -1742,7 +1811,7 @@ impl TurnTool for Connector { let (o, ok, img) = crate::mcp::call_until(&mcp_name, &mcp_args, cancel); (o, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img) } else { - ("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string(), ToolStatus::Denied, None) + (auto_no.unwrap_or_else(|| "使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string()), ToolStatus::Denied, None) }; s.finish(&output, status, img); Flow::Next @@ -1824,7 +1893,7 @@ impl TurnTool for OnComputer { } else { let reason = format!("讓 {} 使用電腦工具:{}\n(在 {} 上)", job.via_name, what, t.name); match s.ask_person(ApprovalKind::EnableTools, reason, "tools:on".into()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => { + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => { *s.tools_once = true; said_yes = true; } @@ -1849,7 +1918,7 @@ impl TurnTool for OnComputer { } else { let reason = format!("在「{}」上執行任務,而不只是在它自己的電腦上:{}{what}", t.name, if is_web { format!("{} ", web::label(&call.name)) } else { String::new() }); match s.ask_person(ApprovalKind::EnableThisComputer, reason, "local:on".into()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => { + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => { *s.local_once = true; said_yes = true; } @@ -1930,15 +1999,42 @@ impl TurnTool for OnComputer { Decision::Ask { .. } if said_yes && !must_ask && !(is_mac && crate::macapps::is_send(&call.name) && !skip_msg_ask) && !sensitive_click => Ok(()), Decision::Deny(r) => Err((format!("被安全規則擋下:{r}"), ToolStatus::Denied)), Decision::Ask { reason, grant } => { - let machine = target.as_ref().map(|t| t.name.clone()).unwrap_or_default(); - let reason = format!("{reason}\n(在 {machine} 上)"); - match s.ask_person(ApprovalKind::Action, reason, grant) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => Ok(()), - ApprovalAnswer::Always(g) => { - keep_grant(s.grants, g); - Ok(()) + // 智慧模式: a 「這輪都准」 for this kind from earlier this turn covers it (only a + // question the gates chose to ask — never a must-ask: a sensitive click, a send, + // your 「一律詢問」 rule, a hook's ask). + if !must_ask && s.job.smart.active() && s.job.smart.scoped(&grant) { + s.step_note.set("(智慧模式:你這一輪已准過這類操作,這一步直接做。)".into()); + Ok(()) + } else { + let machine = target.as_ref().map(|t| t.name.clone()).unwrap_or_default(); + let reason = format!("{reason}\n(在 {machine} 上)"); + // Must-asks (a sensitive click, a send, your 「一律詢問」 rule, a hook's ask) get + // the plain question: 智慧模式 never answers one of those by itself. + let (answer, auto) = if must_ask { + (s.ask_person(ApprovalKind::Action, reason, grant), None) + } else { + s.ask_smart(reason, grant, crate::smart::tier(&call.name, on_persons)) + }; + match answer { + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => { + if let Some(note) = auto { + s.step_note.set(note); + } + Ok(()) + } + ApprovalAnswer::Scope(g) => { + s.job.smart.scope(&g); + Ok(()) + } + ApprovalAnswer::Always(g) => { + keep_grant(s.grants, g); + Ok(()) + } + ApprovalAnswer::Reject => Err(( + auto.unwrap_or_else(|| "使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".into()), + ToolStatus::Denied, + )), } - ApprovalAnswer::Reject => Err(("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".into(), ToolStatus::Denied)), } } }; @@ -2050,7 +2146,7 @@ fn file_out_refused(s: &mut Step<'_>) -> Option { Decision::Allow => None, Decision::Deny(r) => Some((format!("被安全規則擋下:{r}"), ToolStatus::Denied)), Decision::Ask { reason, grant } => match s.ask_person(ApprovalKind::Action, format!("{reason}\n(在 {} 上)", t.name), grant) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => None, + ApprovalAnswer::Once | ApprovalAnswer::Answered(_) | ApprovalAnswer::Scope(_) => None, ApprovalAnswer::Always(g) => { keep_grant(s.grants, g); None diff --git a/src/app.rs b/src/app.rs index 917fa49..881c32a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -147,6 +147,9 @@ pub fn set_doc_folders(v: Vec) { pub struct App { state: State, + /// 智慧模式 (/smart): one switch for every live turn — a turn reads it at each step, so + /// 「/smart」 works mid-turn (and 設定's switch too). See smart.rs. + pub smart_flag: Arc, pal: Palette, /// The shell inputs `pal` was last built from (主題、底色、強調色、對比、密度): when the /// state's differ, the next frame builds the shell again — whatever changed them. @@ -468,8 +471,10 @@ impl App { } crate::routines::set_person_timezone(&state.timezone); let (tx, rx) = channel(); + let smart0 = state.smart_mode; let mut app = App { state, + smart_flag: Arc::new(AtomicBool::new(smart0)), pal: LIGHT, shell_applied: None, demo, @@ -1927,6 +1932,10 @@ impl App { local_locked: !self.managed.local.allows() || self.state.local_never, tools_enabled: !untrusted && b.tools_enabled, direct, + // 智慧模式: the window's switch (shared — 「/smart」 works mid-turn), the card timeout, + // and this turn's 「這輪都准」 (per-turn by construction: a Job is one turn). + // An untrusted turn (a stranger's message) is never in 智慧模式. + smart: if untrusted { crate::smart::Smart::off() } else { crate::smart::Smart::new(self.smart_flag.clone(), std::time::Duration::from_secs(self.state.smart_timeout_secs)) }, grants: if untrusted { Vec::new() } else { @@ -2699,6 +2708,7 @@ impl App { Goal, Plan, Always, + Smart, } struct Shown { mode: Mode, @@ -2733,6 +2743,10 @@ impl App { let more = t("用 /always-approve 打開的。安全規則一律拒絕的(sudo、rm -rf /、金鑰檔…)照樣擋;別人傳來的訊息照樣等你按;問題卡和「需要處理」照樣等你。"); shown.push(Shown { mode: Mode::Always, icon: Icon::Zap, col: p.danger, count: String::new(), line: t(crate::always::BAR), more, end: "關閉一律放行" }); } + if self.smart_flag.load(Ordering::Relaxed) { + let more = t("用 /smart 打開的。同一類操作這一輪只問一次(按「這輪都准」後同類直接做);幾分鐘沒回的卡片,低風險自動放行、敏感操作自動拒絕。安全規則一律拒絕的照樣攝;付款、傳送、刪除的點擊、你的螢幕和 App、保險庫照樣問。"); + shown.push(Shown { mode: Mode::Smart, icon: Icon::Sparkle, col: p.accent, count: String::new(), line: t(crate::smart::BAR), more, end: "關閉智慧模式" }); + } if shown.is_empty() { return 0.0; } @@ -2775,6 +2789,7 @@ impl App { self.mirror_send(bot.id, "/always-approve off".into(), vec![], None); } Some(Mode::Always) => self.always_command(ctx, bot.id, crate::always::Command::Off), + Some(Mode::Smart) => self.smart_command(ctx, bot.id, crate::smart::Command::Off), None => {} } used @@ -2784,6 +2799,40 @@ impl App { (self.state.local_execution || self.state.direct_mode && self.managed.direct.allows()) && self.managed.local.allows() } + /// 智慧模式 (/smart): the window's switch; every live turn reads it, so it works mid-turn. + /// Admin locks on 直接操作/在這台電腦上執行 lock this too (it grants the same ground). + fn smart_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: crate::smart::Command) { + let _ = bot_id; + match cmd { + crate::smart::Command::On => { + if !self.managed.direct.allows() || !self.managed.local.allows() { + self.goal_note(bot_id, crate::smart::LOCKED_NOTE); + return; + } + if self.smart_flag.swap(true, Ordering::Relaxed) { + self.goal_note(bot_id, "智慧模式本來就是開的。"); + } else { + self.state.smart_mode = true; + self.state.save(); + self.goal_note(bot_id, crate::smart::ON_NOTE); + } + } + crate::smart::Command::Off => { + if self.smart_flag.swap(false, Ordering::Relaxed) { + self.state.smart_mode = false; + self.state.save(); + self.goal_note(bot_id, crate::smart::OFF_NOTE); + } else { + self.goal_note(bot_id, "智慧模式本來就是關的。"); + } + } + crate::smart::Command::Status => { + self.goal_note(bot_id, &crate::smart::status_note(self.smart_flag.load(Ordering::Relaxed), self.state.smart_timeout_secs)); + } + } + ctx.request_repaint(); + } + fn enable_direct_mode(&mut self) { if !self.managed.direct.allows() || !self.managed.local.allows() { self.notice = Some("「直接操作」已由管理員關閉,沒辦法打開。".into()); @@ -2829,7 +2878,7 @@ impl App { fn answer(&mut self, ctx: &egui::Context, bot_id: u64, answer: ApprovalAnswer) { if self.mir.on { let (a, text) = match &answer { - ApprovalAnswer::Once => ("once", ""), + ApprovalAnswer::Once | ApprovalAnswer::Scope(_) => ("once", ""), ApprovalAnswer::Always(_) => ("always", ""), ApprovalAnswer::Reject => ("reject", ""), ApprovalAnswer::Answered(text) => ("answered", text.as_str()), @@ -4076,6 +4125,12 @@ impl App { answer = Some(ApprovalAnswer::Always(grant.clone())); } } + // 智慧模式: the middle yes — this kind, this turn only (see smart.rs). + if kind == ApprovalKind::Action && !grant.is_empty() && self.smart_flag.load(Ordering::Relaxed) { + if ui.button(t("這輪都准")).on_hover_text(format!("這一輪之內{}這類操作都不再問你;下一輪會再問。(智慧模式)", grant_label(&grant))).clicked() { + answer = Some(ApprovalAnswer::Scope(grant.clone())); + } + } if ui.button(t("拒絕")).clicked() { answer = Some(ApprovalAnswer::Reject); } @@ -5948,6 +6003,35 @@ impl App { } hint(ui, "仍會擋下:危險指令(sudo、格式化…)、密碼和金鑰檔、AnyBot 自己的資料,以及你在「自動審核」寫的「一律詢問」規則(預設:刪除檔案、付款、用你的帳號發文或傳訊息)。macOS 第一次讓 AnyBot 控制瀏覽器時還是會自己問一次,按「好」就行。", p); }); + // 智慧模式: the middle setting — one decision per kind per turn, cards that answer themselves. + section(ui, "智慧模式", p); + setting_card(ui, p, |ui| { + let allowed = self.managed.direct.allows() && self.managed.local.allows(); + let mut on = self.smart_flag.load(Ordering::Relaxed); + let mut flip = None; + ui.horizontal(|ui| { + ui.label(RichText::new(t("同類操作一輪只問一次,卡片逾時自動回答")).size(FONT_BASE).color(p.text)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if ui.add_enabled(allowed, computers_ui::toggle(&mut on)).changed() { + flip = Some(on); + } + }); + }); + if !allowed { + crate::icons::label(ui, crate::icons::Icon::Lock, &t("由你的管理員設定,無法變更"), 12.0, p.danger); + } + let mut secs = self.state.smart_timeout_secs; + ui.add_enabled(allowed, egui::Slider::new(&mut secs, 0..=1800).step_by(30.0).suffix(" 秒").text(t("卡片等多久就自動回答"))); + if secs != self.state.smart_timeout_secs { + self.state.smart_timeout_secs = secs; + self.state.save(); + } + hint(ui, "也可以在任何聊天打 /smart(關掉打 /smart off)。按「這輪都准」後同類操作這一輪直接做,下一輪會再問;卡片超過上面那個時間沒回,看檔案、上網這類先做(步驟裡會寫),付款、傳送、刪除的點擊、你的螢幕和 App、保險庫這類自動拒絕。安全規則一律拒絕的照樣攝;問題卡和「需要處理」照樣等你。", p); + if let Some(on) = flip { + let id = self.state.selected; + self.smart_command(ctx, id, if on { crate::smart::Command::On } else { crate::smart::Command::Off }); + } + }); // 一律放行: the same switch as 「/always-approve」 in a chat. section(ui, "一律放行", p); setting_card(ui, p, |ui| { @@ -9294,7 +9378,7 @@ mod tests { let mut bot = app.state.bots[0].clone(); bot.skills = Some(vec!["週報".into()]); let names = |l: Vec<(String, String)>| l.into_iter().map(|x| x.0).collect::>(); - assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "usage", "doctor", "context", "compact", "fork", "rewind"]); + assert_eq!(names(app.slash_list("/", &bot)), vec!["goal", "plan", "btw", "always-approve", "smart", "usage", "doctor", "context", "compact", "fork", "rewind"]); assert_eq!(names(app.slash_list("/週", &bot)), vec!["週報"], "its own, by the word"); assert_eq!(names(app.slash_list("/b", &bot)), vec!["btw"]); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 282ca13..bf83ed9 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -1135,7 +1135,7 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool { } /// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs). -pub const SLASH_COMMANDS: [(&str, &str); 10] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的"), ("rewind", "退回:把 Bot 改的檔案和對話退回之前說的某一句")]; +pub const SLASH_COMMANDS: [(&str, &str); 11] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)"), ("plan", "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"), ("btw", "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"), ("always-approve", "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"), ("smart", "智慧模式:同類操作一輪只問一次,卡片逾時自動回答(/smart off 關閉)"), ("usage", "用量:最近一天和一週,各 Bot、各模型用了多少 token"), ("doctor", "診斷:檢查這台電腦的連線、大腦、模型服務、Bot 的電腦、連接器、磁碟"), ("context", "這個對話用了模型可讀的多少"), ("compact", "現在就把較早的對話整理成摘要"), ("fork", "分岔:這段對話存一份到過去的對話,之後各走各的"), ("rewind", "退回:把 Bot 改的檔案和對話退回之前說的某一句")]; /// What the bot is doing, in the one line beside its face (and on a colleague's card, the phone). /// A status of several lines — a retry: the error, what it means, when it tries again — used to diff --git a/src/app/commands.rs b/src/app/commands.rs index 23591d4..fc56a90 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -16,6 +16,7 @@ pub(super) enum AppCommand { Goal(crate::goal::Command), Plan(crate::plan::Command), Always(crate::always::Command), + Smart(crate::smart::Command), Usage, Context, Compact, @@ -33,6 +34,10 @@ impl AppCommand { match self { AppCommand::Always(crate::always::Command::On) => true, AppCommand::Always(crate::always::Command::Off | crate::always::Command::Status) => false, + // 智慧模式 loosens the asking too (per-turn grants, cards answering themselves): + // a phone on a direct connection can turn it off, never on. + AppCommand::Smart(crate::smart::Command::On) => true, + AppCommand::Smart(crate::smart::Command::Off | crate::smart::Command::Status) => false, AppCommand::Btw(_) | AppCommand::Goal(_) | AppCommand::Plan(_) | AppCommand::Usage | AppCommand::Context | AppCommand::Compact | AppCommand::Doctor | AppCommand::Fork(_) | AppCommand::Rewind(_) => false, } } @@ -69,6 +74,9 @@ pub(super) fn app_command(text: &str) -> Option { if let Some(c) = crate::always::command(text) { return Some(AppCommand::Always(c)); } + if let Some(c) = crate::smart::command(text) { + return Some(AppCommand::Smart(c)); + } if crate::usage::command(text) { return Some(AppCommand::Usage); } @@ -106,6 +114,7 @@ impl App { AppCommand::Goal(c) => self.goal_command(ctx, bot_id, c, text, attachments, picks), AppCommand::Plan(c) => self.plan_command(ctx, bot_id, c, text, attachments, picks), AppCommand::Always(c) => self.always_command(ctx, bot_id, c), + AppCommand::Smart(c) => self.smart_command(ctx, bot_id, c), AppCommand::Usage => self.usage_note(bot_id), AppCommand::Context => self.context_note(bot_id), AppCommand::Compact => self.compact_now(bot_id), diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 2f20ff0..bc7b0c7 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -1568,6 +1568,17 @@ impl App { self.disable_direct_mode() } } + // 智慧模式: a phone may only tighten it — turning it on is typed at the computer + // (same rule as 「/smart」 words, which remote.rs refuses before they arrive). + "smart_mode" => { + if v.as_bool().unwrap_or(false) { + return fail("智慧模式只能在電腦上打開"); + } + if self.smart_flag.swap(false, Ordering::Relaxed) { + self.state.smart_mode = false; + self.mark(); + } + } "auto_review" => self.state.auto_review = v.as_bool().unwrap_or(false), "notify" => self.state.notify = v.as_bool().unwrap_or(true), "rule_add" | "rule_remove" => { @@ -1867,6 +1878,7 @@ impl App { }, "timezone": st.timezone, "notify": st.notify, "language": st.language, "direct_mode": st.direct_mode, "direct_locked": !self.managed.direct.allows() || !self.managed.local.allows(), + "smart_mode": st.smart_mode, "auto_review": st.auto_review, "allow_rules": st.review_allow_rules, "ask_rules": st.review_ask_rules, "providers": crate::providers::ALL_PROVIDERS.iter().map(|&k| { let ps = st.provider(k); diff --git a/src/main.rs b/src/main.rs index 6797210..0f7c14a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -76,6 +76,7 @@ mod garden; mod goal; mod plan; mod always; +mod smart; mod secrets; mod logfile; mod net; diff --git a/src/model.rs b/src/model.rs index 6911dfc..26804a1 100644 --- a/src/model.rs +++ b/src/model.rs @@ -706,6 +706,14 @@ pub struct State { /// "always ask" rules stop the bot. #[serde(default)] pub direct_mode: bool, + /// 智慧模式 (/smart): asked questions get 「這輪都准」 (one decision per kind per turn) and + /// unanswered cards answer themselves by tier (low-risk goes ahead, sensitive refuses). + /// See smart.rs. + #[serde(default)] + pub smart_mode: bool, + /// How long a 智慧模式 question may go unanswered before it answers itself (0: never). + #[serde(default = "default_smart_timeout")] + pub smart_timeout_secs: u64, /// 一律放行 (/always-approve): every request that would wait for 允許 is answered yes by /// itself (the person's own turns; refusals, questions and someone else's messages excepted). /// See always.rs. @@ -820,6 +828,11 @@ fn first_routine_id() -> u64 { 1 } +/// 智慧模式's card timeout, 5 minutes by default (0 turns it off). +fn default_smart_timeout() -> u64 { + 300 +} + fn default_shell_tone() -> f32 { 1.0 } @@ -1259,6 +1272,8 @@ impl State { notify: true, alert_sound: true, direct_mode: false, + smart_mode: false, + smart_timeout_secs: default_smart_timeout(), always_approve: false, direct_before_always: false, auto_update_when_away: true, diff --git a/src/providers.rs b/src/providers.rs index 8d2c505..bb49b39 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -315,6 +315,9 @@ pub struct AppCall { pub enum ApprovalAnswer { Once, Always(String), + /// 智慧模式 「這輪都准」: allow this, and remember the grant for the rest of this turn only + /// (see smart.rs; the phone never sends it — widening, even per-turn, is typed at the computer). + Scope(String), Reject, /// 問題卡: what the person answered, a JSON list with one string per question. Answered(String), diff --git a/src/smart.rs b/src/smart.rs new file mode 100644 index 0000000..f2d1a96 --- /dev/null +++ b/src/smart.rs @@ -0,0 +1,203 @@ +//! 智慧模式 (/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 { + 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, + /// 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>, + /// 自動審核: 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>, +} + +impl Smart { + /// Off, and never turns on (tests, untrusted turns). + pub fn off() -> Smart { + Smart::default() + } + + pub fn new(on: Arc, 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("智慧模式")); + } +}