1902 lines
94 KiB
Rust
1902 lines
94 KiB
Rust
//! 一步裡的一個工具呼叫 (M7): the tools a turn runs, each a `TurnTool` — whether a call is its
|
||
//! (`takes`) and how it runs (`run`) — in one ordered list, `TOOLS`. The first that takes a call
|
||
//! runs it. The refusals that come before some tools (an action not understood, an ability this
|
||
//! bot doesn't have, a skill's allowed-tools, a stranger's turn) are entries in the same list, in
|
||
//! the same place; the last entry, `OnComputer`, takes whatever is left: a step on one of the
|
||
//! bot's computers, through the gates. (It used to be one function of ~40 `if call.name == …`,
|
||
//! sharing two closures.)
|
||
//!
|
||
//! Every tool ends the same way: `Step::finish` (its status, its result with the notes, any
|
||
//! picture), after `Step::started` when it really ran. What a tool says and what it takes is
|
||
//! still written where it always was (tools.rs, web.rs, appctl.rs…): this is how a turn runs them.
|
||
|
||
use super::*;
|
||
|
||
/// One tool call on its way: the turn's state, the call as it runs, and what every step's end
|
||
/// needs (made by run_call once the checks before any tool have passed).
|
||
pub(super) struct Step<'a> {
|
||
pub job: &'a Job,
|
||
pub bot_id: u64,
|
||
pub send: &'a dyn Fn(StreamEvent),
|
||
pub cancel: &'a Arc<AtomicBool>,
|
||
pub history: &'a mut Vec<Message>,
|
||
pub grants: &'a mut Vec<String>,
|
||
pub said_no: &'a std::cell::Cell<bool>,
|
||
pub refused: &'a std::cell::RefCell<Vec<String>>,
|
||
pub trouble: &'a std::cell::Cell<bool>,
|
||
pub tools_on: &'a mut bool,
|
||
pub local_on: &'a mut bool,
|
||
pub tools_once: &'a mut bool,
|
||
pub local_once: &'a mut bool,
|
||
pub browsers: &'a mut UsedBrowsers,
|
||
pub sent_count: &'a std::cell::Cell<u32>,
|
||
pub hooks: &'a crate::hooks::Hooks,
|
||
pub hook_base: &'a serde_json::Value,
|
||
pub runs: &'a std::cell::RefCell<Vec<(String, bool, String)>>,
|
||
pub step_sent_at: &'a std::cell::Cell<Option<Instant>>,
|
||
pub step_sent: &'a std::cell::Cell<String>,
|
||
pub step_note: &'a std::cell::Cell<String>,
|
||
pub skill_limit: &'a std::cell::RefCell<Option<(String, Vec<String>)>>,
|
||
pub plan_changes: &'a mut u32,
|
||
pub last_sent: &'a std::cell::Cell<Option<Instant>>,
|
||
pub replay: &'a mut Option<Replay>,
|
||
pub plan_go: &'a mut Option<Vec<crate::plan::Step>>,
|
||
pub moved: &'a std::collections::HashMap<String, String>,
|
||
/// The call as it runs (on the chosen computer, with what a hook changed).
|
||
pub call: ToolCall,
|
||
/// The call as 拒絕後停下 knows it.
|
||
pub refused_key: String,
|
||
/// 鬼打牆's warning, put before the result.
|
||
pub repeat_note: String,
|
||
/// What the PreToolUse hooks said (their allow / ask is used by OnComputer).
|
||
pub hook_word: crate::hooks::Said,
|
||
/// Where an AnyBot browser step goes (browser_at: worked out once).
|
||
pub browser: std::cell::OnceCell<Option<Result<(BrowserAt, String), String>>>,
|
||
}
|
||
|
||
impl Step<'_> {
|
||
/// Every step ends the same way: its status, then its result (with the notes) and any
|
||
/// picture, shown and kept.
|
||
pub fn finish(&mut self, output: &str, status: ToolStatus, image: Option<String>) {
|
||
let call = &self.call;
|
||
if status == ToolStatus::Denied && self.said_no.replace(false) {
|
||
self.refused.borrow_mut().push(self.refused_key.clone());
|
||
}
|
||
// A click that changed nothing on the screen is trouble too, though it "worked".
|
||
if matches!(status, ToolStatus::Failed | ToolStatus::Denied) || !self.repeat_note.is_empty() || output.contains(crate::computer::NOOP_TAG) {
|
||
self.trouble.set(true);
|
||
}
|
||
// (A safety rule's no counts as failing too: the same block again and again.)
|
||
let failed = status == ToolStatus::Failed || (status == ToolStatus::Denied && output.starts_with("被安全規則擋下"));
|
||
self.runs.borrow_mut().push((call.name.clone(), failed, output.chars().take(400).collect()));
|
||
// Went out: what the system saw leave the bot's browser, else (other tools) what the
|
||
// step is.
|
||
let sent = self.step_sent.take();
|
||
let sent = if status == ToolStatus::Done { sent } else { String::new() };
|
||
// The system's own lines about the step go after the page's words, outside the part
|
||
// marked as the page's.
|
||
let mut reached = self.step_note.take();
|
||
let sent_at = self.step_sent_at.take();
|
||
if status == ToolStatus::Done && (!sent.is_empty() || (!crate::browser::is_tool(&call.name) && crate::evidence::sends(call))) {
|
||
self.last_sent.set(Some(sent_at.unwrap_or_else(Instant::now)));
|
||
self.sent_count.set(self.sent_count.get() + 1);
|
||
if self.job.target_sends > 0 && self.sent_count.get() == self.job.target_sends {
|
||
reached.push_str(&format!("\n【系統】已達到這一輪的完成條件:送出 {0}/{0} 則。不要再送,收尾回報。", self.job.target_sends));
|
||
}
|
||
}
|
||
self.job.note(crate::oplog::Record::ToolFinished { op: self.job.op.clone(), call_id: call.id.clone(), status: format!("{status:?}").to_lowercase(), at: crate::model::now_ms() });
|
||
(self.send)(StreamEvent::ToolStatus(call.id.clone(), status));
|
||
// Hooks' PostToolUse (after a step that ran): what the bot reads instead, and what a
|
||
// hook adds to it.
|
||
let hooked;
|
||
let output = if status == ToolStatus::Done && !self.hooks.is_empty() {
|
||
let mut input = self.hook_base.clone();
|
||
input["tool_name"] = serde_json::json!(call.name);
|
||
input["tool_input"] = crate::hooks::tool_input(&call.args);
|
||
input["tool_response"] = serde_json::json!(output);
|
||
let said = self.hooks.fire("PostToolUse", Some(&call.name), input);
|
||
let mut t = said.output.unwrap_or_else(|| output.to_string());
|
||
for extra in [said.block, Some(said.context).filter(|c| !c.is_empty())].into_iter().flatten() {
|
||
t.push_str(&format!("\n【使用者的 hook】{extra}"));
|
||
}
|
||
hooked = t;
|
||
hooked.as_str()
|
||
} else {
|
||
output
|
||
};
|
||
let body = noted(self.moved, &call.id, output);
|
||
let body = if status == ToolStatus::Denied { body } else { wrap_untrusted(&call.name, body) };
|
||
let mut result = Message::tool_result(&call.id, &call.name, &format!("{}{body}{reached}", self.repeat_note));
|
||
result.sent = sent;
|
||
result.images.extend(image);
|
||
(self.send)(StreamEvent::ToolResult(result.clone()));
|
||
self.history.push(result);
|
||
}
|
||
|
||
/// About to run, every check passed: the work log hears it first, with the arguments it
|
||
/// runs with and whether it may run again after a crash.
|
||
pub fn started(&self) {
|
||
let call = &self.call;
|
||
self.job.note(crate::oplog::Record::ToolStarted { op: self.job.op.clone(), call_id: call.id.clone(), name: call.name.clone(), args: call.args.clone(), replay: crate::oplog::replay_of(&call.name), at: crate::model::now_ms() });
|
||
(self.send)(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Running));
|
||
}
|
||
|
||
/// What the step is, in the words a question to the person uses.
|
||
pub fn what(&self) -> String {
|
||
let call = &self.call;
|
||
if crate::macapps::is_mac_tool(&call.name) {
|
||
format!("{} {}", crate::macapps::label(&call.name), crate::macapps::describe(&call.name, &call.args))
|
||
} else if computer::is_computer_tool(&call.name) {
|
||
// A control by its number: name it from the app's list the bot last read.
|
||
let named = tools::args_of(&call.args)["ref"].as_str().map(str::trim).filter(|r| !r.is_empty()).and_then(|r| element_named(self.history, r)).map(|e| format!("({e})")).unwrap_or_default();
|
||
format!("{} {}{named}", computer::label(&call.name), computer::describe(&call.name, &call.args))
|
||
} else if web::is_web_tool(&call.name) {
|
||
web::describe(&call.name, &call.args)
|
||
} else {
|
||
tools::describe(&call.name, &call.args)
|
||
}
|
||
}
|
||
|
||
/// Where a web step's AnyBot browser is (None: not a web step), worked out once: whether it
|
||
/// is InBotsBrowser's and where it runs come from the same answer.
|
||
pub fn browser_at(&self) -> Option<&Result<(BrowserAt, String), String>> {
|
||
self.browser.get_or_init(|| web::is_web_tool(&self.call.name).then(|| browser_place(self.job, &self.call.name, &self.call.args))).as_ref()
|
||
}
|
||
|
||
/// Ask the person right away (a pop-up), and wait for the answer.
|
||
pub fn ask_person(&self, kind: ApprovalKind, reason: String, grant: String) -> ApprovalAnswer {
|
||
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 }));
|
||
wait_answer(arx, self.cancel, self.said_no)
|
||
}
|
||
}
|
||
|
||
/// A tool as a turn runs it.
|
||
pub(super) trait TurnTool: Sync {
|
||
/// Its name in the list (the tests read the order by it).
|
||
fn name(&self) -> &'static str;
|
||
/// Whether this call is this one's.
|
||
fn takes(&self, s: &Step<'_>) -> bool;
|
||
/// Run it: the result goes in with Step::finish; Flow::End ends the turn.
|
||
fn run(&self, s: &mut Step<'_>) -> Flow;
|
||
}
|
||
|
||
/// In the order they are asked: the first that takes a call runs it (OnComputer takes all).
|
||
pub(super) static TOOLS: &[&dyn TurnTool] = &[
|
||
&BadAction, &Lacking, &SkillLimit, &ReplaySkill, &FeatureMap, &LookImage, &AppTool, &DemoStep, &WaitAfterSend, &Untrusted, &SentLog, &InBotsBrowser, &Handoff, &KeptResult, &PlanSubmit, &PlanUpdate, &AskCard, &ShowCard, &React, &SendFile, &OpenForPerson, &Phone, &PublishSite, &VaultList, &VaultFill, &ConnectorFind, &Connector, &OnComputer,
|
||
];
|
||
|
||
/// The tool that runs this step.
|
||
pub(super) fn tool_for(s: &Step<'_>) -> &'static dyn TurnTool {
|
||
TOOLS.iter().copied().find(|t| t.takes(s)).unwrap_or(&OnComputer)
|
||
}
|
||
|
||
/// A loaded skill whose allowed-tools leave this call out: (its name, its rules).
|
||
fn skill_outside(s: &Step<'_>) -> Option<(String, Vec<String>)> {
|
||
s.skill_limit.borrow().as_ref().filter(|(_, rules)| !crate::skills::skill_allows(rules, &s.call.name, &s.call.args)).map(|(name, rules)| (name.clone(), rules.clone()))
|
||
}
|
||
|
||
/// A connector's tool this call runs (one of theirs, or through use_connector_tool): its name
|
||
/// and arguments, or why it can't be read.
|
||
fn mcp_step(call: &ToolCall) -> Option<Result<(String, String), String>> {
|
||
if crate::mcp::is_mcp_tool(&call.name) {
|
||
Some(Ok((call.name.clone(), call.args.clone())))
|
||
} else {
|
||
crate::mcp::unwrap_use(&call.name, &call.args)
|
||
}
|
||
}
|
||
|
||
/// A one-tool call whose action wasn't understood (none, unknown): what it takes.
|
||
/// ("No such tool", as it used to say, sent a bot trying other tools in circles.)
|
||
pub(super) struct BadAction;
|
||
|
||
impl TurnTool for BadAction {
|
||
fn name(&self) -> &'static str {
|
||
"BadAction"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::browser::TOOL || s.call.name == computer::TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let call = s.call.clone();
|
||
s.finish(&bad_action(&call.name, &call.args), ToolStatus::Failed, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// Not one of this bot's abilities: it was never offered; say so instead of running it.
|
||
pub(super) struct Lacking;
|
||
|
||
impl TurnTool for Lacking {
|
||
fn name(&self) -> &'static str {
|
||
"Lacking"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
crate::profile::ability_of(&s.call.name).is_some_and(|k| s.job.lacks.iter().any(|l| l == k))
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let Some(k) = crate::profile::ability_of(&s.call.name) else { return Flow::Next };
|
||
s.finish(&crate::profile::lacking_text(k), ToolStatus::Denied, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// A loaded skill's allowed-tools: anything else isn't run this turn.
|
||
pub(super) struct SkillLimit;
|
||
|
||
impl TurnTool for SkillLimit {
|
||
fn name(&self) -> &'static str {
|
||
"SkillLimit"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
skill_outside(s).is_some()
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let Some((skill, rules)) = skill_outside(s) else { return Flow::Next };
|
||
let text = format!("沒有執行:這一輪用的技能「{skill}」只准用 {},「{}」不在裡面。照技能的做法用那些工具做;真的需要別的,先告訴使用者。", rules.join("、"), s.call.name);
|
||
s.finish(&text, ToolStatus::Denied, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// ReplaySkill
|
||
pub(super) struct ReplaySkill;
|
||
|
||
impl TurnTool for ReplaySkill {
|
||
fn name(&self) -> &'static str {
|
||
"ReplaySkill"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == REPLAY_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let call = s.call.clone();
|
||
let v = tools::args_of(&call.args);
|
||
let name = v["name"].as_str().unwrap_or("").trim().to_string();
|
||
let skill = job.skills.iter().find(|k| k.enabled && k.name == name).cloned();
|
||
match skill {
|
||
Some(k) if !k.steps.is_empty() => {
|
||
// 要填: this time's words in the skill's blanks.
|
||
let filled = match crate::memory::fill_blanks(&k.steps, &v["values"]) {
|
||
Ok(f) => f,
|
||
Err(missing) => {
|
||
let example: serde_json::Map<String, serde_json::Value> = missing.iter().map(|m| (m.clone(), serde_json::Value::String("…".into()))).collect();
|
||
s.finish(&format!("「{name}」每次要填:{}。用 values 給每一格這次的內容再重播,例如 {{\"name\": \"{name}\", \"values\": {}}}。", missing.join("、"), serde_json::Value::Object(example)), ToolStatus::Failed, None);
|
||
return Flow::Next;
|
||
}
|
||
};
|
||
// Another computer named for the replay: every step goes there.
|
||
let mut steps: std::collections::VecDeque<_> = filled.into();
|
||
if let Some(c) = v["computer"].as_str().filter(|c| !c.trim().is_empty()) {
|
||
for st in steps.iter_mut() {
|
||
let mut a = tools::args_of(&st.args);
|
||
if a.get("computer").is_some() || computer::is_computer_tool(&st.tool) || web::is_web_tool(&st.tool) || st.tool == "shell" {
|
||
a["computer"] = serde_json::Value::String(c.to_string());
|
||
st.args = a.to_string();
|
||
}
|
||
}
|
||
}
|
||
let total = steps.len();
|
||
s.finish(&format!("開始重播「{name}」,共 {total} 步:AnyBot 會一步一步照做,每一步先在畫面上找到同一個東西,對不上會停下來交給你。"), ToolStatus::Done, None);
|
||
*s.replay = Some(Replay { name, left: steps, total, looked: None });
|
||
}
|
||
Some(_) => s.finish(&format!("「{name}」沒有存可以重播的步驟:用 use_skill 讀出做法,照著自己做。"), ToolStatus::Failed, None),
|
||
None => s.finish(&format!("沒有叫「{name}」的技能。"), ToolStatus::Failed, None),
|
||
}
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 功能地圖: one area of AnyBot's own map (featuremap.rs), read on the brain.
|
||
pub(super) struct FeatureMap;
|
||
|
||
impl TurnTool for FeatureMap {
|
||
fn name(&self) -> &'static str {
|
||
"FeatureMap"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::featuremap::TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let call = s.call.clone();
|
||
s.started();
|
||
match crate::featuremap::read(tools::args_of(&call.args)["topic"].as_str().unwrap_or("")) {
|
||
Ok(text) => s.finish(&text, ToolStatus::Done, None),
|
||
Err(e) => s.finish(&e, ToolStatus::Failed, None),
|
||
}
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 重新看圖: old pictures ride along as a caption only (see with_descriptions);
|
||
/// when the caption is not enough, the bot asks a model that sees pictures for a
|
||
/// fresh, question-shaped look at one of them.
|
||
pub(super) struct LookImage;
|
||
|
||
impl TurnTool for LookImage {
|
||
fn name(&self) -> &'static str {
|
||
"LookImage"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "look_image"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
s.started();
|
||
let v = tools::args_of(&call.args);
|
||
let idx = v["index"].as_u64().unwrap_or(0) as usize;
|
||
let ask = v["question"].as_str().filter(|s| !s.trim().is_empty()).unwrap_or("請仔細描述這張圖片的內容,連圖裡看得見的文字一併寫出來。").to_string();
|
||
let pics: Vec<String> = s.history.iter().rev().flat_map(|m| m.images.iter().rev().cloned()).collect();
|
||
match pics.get(idx) {
|
||
None => s.finish(&format!("對話裡沒有第 {idx} 張圖(最近的往前數只有 {} 張)。", pics.len()), ToolStatus::Failed, None),
|
||
Some(p) => match crate::providers::describe_fresh(p, &ask, &job.req, cancel) {
|
||
Some((d, model)) => s.finish(&format!("「{model}」重新看過這張圖,針對你的問題回報:\n{d}"), ToolStatus::Done, None),
|
||
None => s.finish("沒看完:帳號裡沒有看得懂圖片的模型可用(或它們都失敗了,稍後再試)。", ToolStatus::Failed, None),
|
||
},
|
||
}
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// AppTool
|
||
pub(super) struct AppTool;
|
||
|
||
impl TurnTool for AppTool {
|
||
fn name(&self) -> &'static str {
|
||
"AppTool"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
appctl::is_app_tool(&s.call.name)
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let send = s.send;
|
||
let cancel = s.cancel;
|
||
let said_no = s.said_no;
|
||
let skill_limit = s.skill_limit;
|
||
let call = s.call.clone();
|
||
// App actions run on the window's side, which also asks for deletions.
|
||
s.started();
|
||
let (rtx, rrx) = channel();
|
||
send(StreamEvent::AppAction(AppCall { call_id: call.id.clone(), name: call.name.clone(), args: call.args.clone(), reply: rtx }));
|
||
let (output, ok) = loop {
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
match rrx.recv_timeout(Duration::from_millis(200)) {
|
||
Ok(r) => break r,
|
||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
|
||
Err(_) => break ("App 沒有回應".to_string(), false),
|
||
}
|
||
};
|
||
let denied = !ok && output.contains("拒絕");
|
||
if denied {
|
||
said_no.set(true);
|
||
}
|
||
if ok && call.name == "use_skill" && tools::args_of(&call.args)["file"].as_str().unwrap_or("").trim().is_empty() {
|
||
let want = tools::args_of(&call.args)["name"].as_str().unwrap_or("").trim().to_lowercase();
|
||
if let Some(k) = job.skills.iter().find(|k| k.name.to_lowercase() == want).filter(|k| !k.allowed_tools.is_empty()) {
|
||
*skill_limit.borrow_mut() = Some((k.name.clone(), crate::skills::tool_rules(k)));
|
||
}
|
||
}
|
||
s.finish(&output, if ok { ToolStatus::Done } else if denied { ToolStatus::Denied } else { ToolStatus::Failed }, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// The person's own recording, shown back to the bot: nothing to ask.
|
||
pub(super) struct DemoStep;
|
||
|
||
impl TurnTool for DemoStep {
|
||
fn name(&self) -> &'static str {
|
||
"DemoStep"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "view_demo_step"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let call = s.call.clone();
|
||
s.started();
|
||
let (output, ok, img) = crate::teach::view_step(&job.demos, &call.args);
|
||
s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 間隔從送出算起: wait until `seconds` have passed since the last send — the next
|
||
/// post is opened and typed first, then sent on time (instead of sleeping the whole
|
||
/// interval after each send, then preparing). Stopping ends the wait.
|
||
pub(super) struct WaitAfterSend;
|
||
|
||
impl TurnTool for WaitAfterSend {
|
||
fn name(&self) -> &'static str {
|
||
"WaitAfterSend"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "browser_wait" && tools::args_of(&s.call.args)["after_send"].as_bool() == Some(true)
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let cancel = s.cancel;
|
||
let last_sent = s.last_sent;
|
||
let call = s.call.clone();
|
||
s.started();
|
||
let want = tools::args_of(&call.args)["seconds"].as_f64().unwrap_or(120.0);
|
||
let Some(said) = wait_after_send(last_sent.get(), want, cancel) else { return Flow::End };
|
||
s.finish(&said, ToolStatus::Done, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 別人傳來的訊息: the AnyBot browsers carry the person's logins, and the book is
|
||
/// theirs — not for a stranger's turn (a public page still reads with web_fetch).
|
||
pub(super) struct Untrusted;
|
||
|
||
impl TurnTool for Untrusted {
|
||
fn name(&self) -> &'static str {
|
||
"Untrusted"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
untrusted_refusal(s.job, &s.call.name).is_some()
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let Some(why) = untrusted_refusal(s.job, &s.call.name) else { return Flow::Next };
|
||
s.finish(why, ToolStatus::Denied, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 已送帳本: what this brain saw go out, by account — read here, not on a page.
|
||
pub(super) struct SentLog;
|
||
|
||
impl TurnTool for SentLog {
|
||
fn name(&self) -> &'static str {
|
||
"SentLog"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::browser::SENT_LOG
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let call = s.call.clone();
|
||
s.started();
|
||
let v = tools::args_of(&call.args);
|
||
let days = v["days"].as_i64().unwrap_or(30).clamp(1, crate::publish::KEEP_DAYS);
|
||
let text = crate::publish::log_text(&crate::publish::Ledger::open().all(), v["profile"].as_str().unwrap_or(""), days, crate::model::now_ms(), &job.timezone);
|
||
s.finish(&text, ToolStatus::Done, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// Public web pages need no computer and no permission — and neither does AnyBot's own
|
||
/// browser (like the reference assistant's own browser). A step naming a computer with no
|
||
/// browser there is said so, not run elsewhere.
|
||
pub(super) struct InBotsBrowser;
|
||
|
||
impl TurnTool for InBotsBrowser {
|
||
fn name(&self) -> &'static str {
|
||
"InBotsBrowser"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
match s.browser_at() {
|
||
None => false,
|
||
Some(Err(_)) => true,
|
||
Some(Ok((place, _))) => s.call.name == "web_fetch" || bots_browser(place, &s.call.name, &s.call.args),
|
||
}
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let bot_id = s.bot_id;
|
||
let send = s.send;
|
||
let cancel = s.cancel;
|
||
let said_no = s.said_no;
|
||
let sent_count = s.sent_count;
|
||
let step_sent_at = s.step_sent_at;
|
||
let step_sent = s.step_sent;
|
||
let step_note = s.step_note;
|
||
let call = s.call.clone();
|
||
let (place, on) = match s.browser_at().cloned().unwrap_or_else(|| browser_place(job, &call.name, &call.args)) {
|
||
Ok(x) => x,
|
||
// The step names a computer with no browser there: say so, don't run it elsewhere.
|
||
Err(e) => {
|
||
s.finish(&e, ToolStatus::Failed, None);
|
||
return Flow::Next;
|
||
}
|
||
};
|
||
// 上傳: a file of this computer on its way to a web page is read on the way,
|
||
// like one on its way into the chat (the bot's browser asks nothing else, and
|
||
// any file here could be put on any page). What the person attached for this
|
||
// bot goes as it is. The path is made whole here, so the browser takes the
|
||
// very file that was checked.
|
||
let mut call_args = call.args.clone();
|
||
if call.name == "browser_open" || (call.name == "browser_tabs" && tools::args_of(&call.args)["action"].as_str() == Some("new")) {
|
||
let raw_url = tools::args_of(&call.args)["url"].as_str().unwrap_or("").trim().to_string();
|
||
if !raw_url.is_empty() {
|
||
if let Ok(norm) = web::normalize_url(&raw_url) {
|
||
if web::is_forbidden_browser_url(&norm) {
|
||
s.finish("被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
if !matches!(place, BrowserAt::Box) && web::is_private_browser_url(&norm) {
|
||
if matches!(place, BrowserAt::Here) && job.local_locked {
|
||
s.finish("被安全規則擋下:「在這台電腦上執行」已鎖定,不能開啟本機或內部網路位址。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
let direct = job.direct.load(Ordering::Relaxed);
|
||
let grant = "browser:private".to_string();
|
||
if !direct && !s.grants.contains(&grant) {
|
||
let (atx, arx) = channel();
|
||
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting));
|
||
send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("在瀏覽器開啟本機或內部網路網址:{norm}\n(在 {on} 上)"), grant: grant.clone(), reply: atx, kind: ApprovalKind::Action }));
|
||
match wait_answer(arx, cancel, said_no) {
|
||
ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {}
|
||
ApprovalAnswer::Always(g) => keep_grant(s.grants, g),
|
||
ApprovalAnswer::Reject => {
|
||
s.finish("使用者拒絕了開啟這個內部網址。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if call.name == "browser_upload" {
|
||
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
||
match &place {
|
||
BrowserAt::Here => {
|
||
let here = job.computers.iter().find(|t| matches!(t.place, tools::Place::Local { .. })).cloned().unwrap_or_else(|| tools::Target {
|
||
name: crate::model::THIS_COMPUTER_NAME.into(),
|
||
// (Not one of this bot's computers: nothing on it is "inside".)
|
||
place: tools::Place::Local { workdir: std::env::temp_dir().join("anybot-no-work-folder") },
|
||
});
|
||
let named = match &here.place {
|
||
tools::Place::Local { workdir } => tools::resolve(workdir, &path),
|
||
_ => std::path::PathBuf::from(&path),
|
||
};
|
||
let direct = job.direct.load(Ordering::Relaxed);
|
||
let decision = if crate::attach::is_given(bot_id, &named) {
|
||
Decision::Allow
|
||
} else if job.local_locked {
|
||
Decision::Deny(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能上傳「{}」上的檔案。", here.name))
|
||
} else {
|
||
match tools::decide_file_out(&here, &path, s.grants) {
|
||
Decision::Allow if !direct && !(*s.tools_on && *s.local_on) => Decision::Ask { reason: format!("把「{}」上的檔案上傳到網頁:{}", here.name, named.display()), grant: String::new() },
|
||
Decision::Ask { .. } if direct => Decision::Allow,
|
||
Decision::Ask { grant, .. } => Decision::Ask { reason: format!("把工作資料夾以外的檔案上傳到網頁:{}", named.display()), grant },
|
||
d => d,
|
||
}
|
||
};
|
||
let refused = match decision {
|
||
Decision::Allow => None,
|
||
Decision::Deny(r) => Some(format!("被安全規則擋下:{r}")),
|
||
Decision::Ask { reason, grant } => {
|
||
let (atx, arx) = channel();
|
||
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::Always(g) => {
|
||
keep_grant(s.grants, g);
|
||
None
|
||
}
|
||
ApprovalAnswer::Reject => Some("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string()),
|
||
}
|
||
}
|
||
};
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
if let Some(output) = refused {
|
||
s.finish(&output, ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
let mut v = tools::args_of(&call.args);
|
||
v["path"] = serde_json::Value::String(named.display().to_string());
|
||
call_args = v.to_string();
|
||
}
|
||
BrowserAt::Device(_) => {
|
||
if tools::is_ignored(std::path::Path::new(&path)) {
|
||
s.finish("被安全規則擋下:這個檔案是私密或系統檔案,Bot 不能上傳。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
let direct = job.direct.load(Ordering::Relaxed);
|
||
let grant = format!("upload-device:{on}");
|
||
if !direct && !s.grants.contains(&grant) {
|
||
let (atx, arx) = channel();
|
||
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting));
|
||
send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: format!("把「{on}」上的檔案上傳到網頁:{path}\n(在 {on} 上)"), grant, reply: atx, kind: ApprovalKind::Action }));
|
||
match wait_answer(arx, cancel, said_no) {
|
||
ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => {}
|
||
ApprovalAnswer::Always(g) => keep_grant(s.grants, g),
|
||
ApprovalAnswer::Reject => {
|
||
s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
}
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
}
|
||
}
|
||
BrowserAt::Box => {
|
||
let expanded = crate::cloudbox::box_path(&path);
|
||
let bot_home = crate::cloudbox::bot_dir(if job.home != 0 { job.home } else { bot_id });
|
||
let ok_box = tools::box_path(std::path::Path::new(&bot_home), &expanded)
|
||
.or_else(|_| tools::box_path(std::path::Path::new(crate::cloudbox::BOX_DOWNLOADS), &expanded))
|
||
.or_else(|_| tools::box_path(std::path::Path::new("/tmp"), &expanded));
|
||
match ok_box {
|
||
Ok(clean) => {
|
||
let mut v = tools::args_of(&call.args);
|
||
v["path"] = serde_json::Value::String(clean);
|
||
call_args = v.to_string();
|
||
}
|
||
Err(e) => {
|
||
s.finish(&format!("被安全規則擋下:{e}"), ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// 裝置連結: the AnyBot browser of another computer (its own logins).
|
||
// (On this job's own tabs: another bot may be using the same browser.)
|
||
let run_there = |name: &str, args: &str| -> (String, bool, Option<String>) {
|
||
match &place {
|
||
BrowserAt::Device(host) => match crate::remote::run_on_device(host, name, args, &job.via_name) {
|
||
Ok(v) => (v["text"].as_str().unwrap_or("").to_string(), v["ok"].as_bool().unwrap_or(false), v["image"].as_str().map(String::from)),
|
||
Err(e) => (e, false, None),
|
||
},
|
||
// 每個 Bot 一個螢幕: its own browser, on its own screen.
|
||
BrowserAt::Box => crate::cloudbox::on_screen(&box_screen_of(job, bot_id), || crate::botbrowser::in_box(|| web::run_full(name, args, cancel))),
|
||
BrowserAt::Here => web::run_full(name, args, cancel),
|
||
}
|
||
};
|
||
// 發布關卡 (publish.rs): words about to leave the bot's browser. The book says
|
||
// whether this account already answered this post; the check reads the words;
|
||
// after the step the page is read again for the evidence.
|
||
let gate = match publish_gate(job, &call.name, &call_args, &on, s.history, sent_count.get(), cancel, &|name: &str, args: &str| run_there(name, &with_job(args, &s.browsers.job))) {
|
||
Gate::Refuse(text) => {
|
||
s.finish(&text, ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
g => g,
|
||
};
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
s.started();
|
||
if call.name != "web_fetch" {
|
||
let profile = tools::args_of(&call.args).get("profile").and_then(|p| p.as_str()).unwrap_or("").trim().to_string();
|
||
s.browsers.add(match &place {
|
||
BrowserAt::Here => BotBrowser::Here(profile),
|
||
BrowserAt::Box => BotBrowser::Box(profile),
|
||
BrowserAt::Device(host) => BotBrowser::Device(host.clone(), profile),
|
||
});
|
||
}
|
||
let args = with_job(&call_args, &s.browsers.job);
|
||
let (output, ok, img) = run_there(&call.name, &args);
|
||
if ok {
|
||
step_sent_at.set(Some(Instant::now()));
|
||
let (note, sent) = after_send(&gate, &call, &call_args, &job.via_name, &|name: &str, args: &str| run_there(name, &with_job(args, &s.browsers.job)));
|
||
step_note.set(note);
|
||
step_sent.set(sent);
|
||
}
|
||
// Which computer's browser it was, like every other step.
|
||
let output = if on.is_empty() { output } else { format!("[{on}] {output}") };
|
||
s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 需要處理 (the original's box hand-off): a step only the person can do — signing
|
||
/// in, a captcha, a code from their phone. A card with the computer's live screen
|
||
/// appears in the chat; they take over, do it, and say 「我完成了」 or 「跳過」. A
|
||
/// message typed meanwhile answers it too.
|
||
pub(super) struct Handoff;
|
||
|
||
impl TurnTool for Handoff {
|
||
fn name(&self) -> &'static str {
|
||
"Handoff"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == tools::HANDOFF_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let send = s.send;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
let instruction = tools::args_of(&call.args)["instruction"].as_str().unwrap_or("").trim().to_string();
|
||
let (output, status) = match screen_target(job, &call.args) {
|
||
Err(e) => (e, ToolStatus::Failed),
|
||
Ok(_) if instruction.is_empty() => ("請在 instruction 寫清楚要使用者做什麼。".to_string(), ToolStatus::Failed),
|
||
Ok(t) => {
|
||
let (atx, arx) = channel();
|
||
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting));
|
||
send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: instruction.clone(), grant: t.name.clone(), reply: atx, kind: ApprovalKind::Handoff }));
|
||
let answer = loop {
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
match arx.recv_timeout(Duration::from_millis(200)) {
|
||
Ok(a) => break Some(a),
|
||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||
if !job.steer.lock().unwrap().is_empty() {
|
||
break None;
|
||
}
|
||
}
|
||
Err(_) => break Some(ApprovalAnswer::Reject),
|
||
}
|
||
};
|
||
match answer {
|
||
Some(ApprovalAnswer::Reject) => ("使用者選擇跳過這一步。不要再要求同一件事:沒有它就繼續其餘的工作,做不到的照實說。".to_string(), ToolStatus::Denied),
|
||
Some(_) => (format!("[{}] 使用者按了「我完成了」。先截圖確認畫面,再接著做。", t.name), ToolStatus::Done),
|
||
None => ("使用者沒有按按鈕,而是傳了訊息(就在下面)。照他說的做。".to_string(), ToolStatus::Done),
|
||
}
|
||
}
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 完整結果: part of a long result kept whole (outputs.rs).
|
||
pub(super) struct KeptResult;
|
||
|
||
impl TurnTool for KeptResult {
|
||
fn name(&self) -> &'static str {
|
||
"KeptResult"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::outputs::TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let call = s.call.clone();
|
||
let (output, ok) = crate::outputs::run(&call.args);
|
||
s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 計畫: the plan on a card (a 問題卡 with 開始照計畫做 and 先不要; their own words
|
||
/// are a change); the turn waits. A message typed meanwhile is a change too.
|
||
pub(super) struct PlanSubmit;
|
||
|
||
impl TurnTool for PlanSubmit {
|
||
fn name(&self) -> &'static str {
|
||
"PlanSubmit"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::plan::SUBMIT_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let send = s.send;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
let (output, status) = match (crate::plan::parse_draft(&call.args), job.drafting.as_ref()) {
|
||
(Err(e), _) => (e, ToolStatus::Failed),
|
||
(Ok(_), None) => ("現在不在計畫模式(或計畫已經核准):不用再交計畫,直接照計畫做。".to_string(), ToolStatus::Failed),
|
||
(Ok(draft), Some(d)) => {
|
||
let (atx, arx) = channel();
|
||
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting));
|
||
send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: crate::plan::approval_card(), grant: String::new(), reply: atx, kind: ApprovalKind::Question }));
|
||
let answer = loop {
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
match arx.recv_timeout(Duration::from_millis(200)) {
|
||
Ok(a) => break Some(a),
|
||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||
if !job.steer.lock().unwrap().is_empty() {
|
||
break None;
|
||
}
|
||
}
|
||
Err(_) => break Some(ApprovalAnswer::Reject),
|
||
}
|
||
};
|
||
let decision = match answer {
|
||
Some(ApprovalAnswer::Answered(text)) => crate::plan::decide(&text),
|
||
Some(_) => crate::plan::Decision::NotNow,
|
||
None => crate::plan::Decision::Change(String::new()),
|
||
};
|
||
match decision {
|
||
crate::plan::Decision::Approve => {
|
||
let steps = draft.steps();
|
||
send(StreamEvent::Plan(crate::plan::Event::Approved(steps.clone())));
|
||
let out = crate::plan::approved_result(&steps);
|
||
*s.plan_go = Some(steps);
|
||
(out, ToolStatus::Done)
|
||
}
|
||
crate::plan::Decision::NotNow => {
|
||
send(StreamEvent::Plan(crate::plan::Event::NotNow));
|
||
(crate::plan::NOT_NOW_RESULT.to_string(), ToolStatus::Denied)
|
||
}
|
||
crate::plan::Decision::Change(words) => {
|
||
*s.plan_changes += 1;
|
||
send(StreamEvent::Plan(crate::plan::Event::Changed));
|
||
let out = if words.is_empty() { crate::plan::WROTE_INSTEAD_RESULT.to_string() } else { crate::plan::change_result(&words, d.plan.revisions + *s.plan_changes) };
|
||
(out, ToolStatus::Done)
|
||
}
|
||
}
|
||
}
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 計畫: where it is in the approved plan (the line above the input follows it).
|
||
pub(super) struct PlanUpdate;
|
||
|
||
impl TurnTool for PlanUpdate {
|
||
fn name(&self) -> &'static str {
|
||
"PlanUpdate"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::plan::UPDATE_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let send = s.send;
|
||
let call = s.call.clone();
|
||
let (output, status) = match crate::plan::parse_progress(&call.args) {
|
||
Ok(steps) => {
|
||
let out = crate::plan::progress_result(&steps);
|
||
send(StreamEvent::Plan(crate::plan::Event::Progress(steps)));
|
||
(out, ToolStatus::Done)
|
||
}
|
||
Err(e) => (e, ToolStatus::Failed),
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 問題卡: the questions on a card; the turn waits for the answers. A message typed
|
||
/// meanwhile leaves the card unanswered and is what the bot goes by.
|
||
pub(super) struct AskCard;
|
||
|
||
impl TurnTool for AskCard {
|
||
fn name(&self) -> &'static str {
|
||
"AskCard"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::ask::TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let send = s.send;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
let (output, status) = match crate::ask::parse(&call.args) {
|
||
Err(e) => (e, ToolStatus::Failed),
|
||
Ok(qs) => {
|
||
let (atx, arx) = channel();
|
||
send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Waiting));
|
||
send(StreamEvent::NeedApproval(Approval { call_id: call.id.clone(), tool: call.name.clone(), reason: crate::ask::to_json(&qs), grant: String::new(), reply: atx, kind: ApprovalKind::Question }));
|
||
let answer = loop {
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
match arx.recv_timeout(Duration::from_millis(200)) {
|
||
Ok(a) => break Some(a),
|
||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||
if !job.steer.lock().unwrap().is_empty() {
|
||
break None;
|
||
}
|
||
}
|
||
Err(_) => break Some(ApprovalAnswer::Reject),
|
||
}
|
||
};
|
||
match answer {
|
||
Some(ApprovalAnswer::Answered(text)) => (crate::ask::result(&qs, &crate::ask::answers_of(&text)), ToolStatus::Done),
|
||
Some(_) => (crate::ask::SKIPPED.to_string(), ToolStatus::Denied),
|
||
None => (crate::ask::WROTE_INSTEAD.to_string(), ToolStatus::Done),
|
||
}
|
||
}
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 生活卡片: drawn by the window from the call itself.
|
||
pub(super) struct ShowCard;
|
||
|
||
impl TurnTool for ShowCard {
|
||
fn name(&self) -> &'static str {
|
||
"ShowCard"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "show_card"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
|
||
s.finish("卡片已顯示給使用者。", ToolStatus::Done, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 表情回應: an emoji on the person's latest message (no words needed).
|
||
pub(super) struct React;
|
||
|
||
impl TurnTool for React {
|
||
fn name(&self) -> &'static str {
|
||
"React"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "react"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let send = s.send;
|
||
let call = s.call.clone();
|
||
let emoji: String = tools::args_of(&call.args)["emoji"].as_str().unwrap_or("👍").chars().take(4).collect();
|
||
send(StreamEvent::React(emoji.clone()));
|
||
s.finish(&format!("已在使用者的訊息上按了 {emoji}。"), ToolStatus::Done, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 傳檔案: put a file the bot made into the chat as a card the person can open.
|
||
/// 傳送 (send_to_device): the same file, to another device of the person's account.
|
||
pub(super) struct SendFile;
|
||
|
||
impl TurnTool for SendFile {
|
||
fn name(&self) -> &'static str {
|
||
"SendFile"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "send_file" || s.call.name == "send_to_device"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let bot_id = s.bot_id;
|
||
let send = s.send;
|
||
let call = s.call.clone();
|
||
// (A file on its way out is read on the way first: file_out_refused.)
|
||
if let Some(flow) = file_out_refused(s) {
|
||
return flow;
|
||
}
|
||
s.started();
|
||
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
||
let fetch_tmp = std::env::temp_dir().join(format!("anybot-fetch-{}-{}", std::process::id(), crate::httpd::random_hex(6)));
|
||
let local = match target_for(job, &call.args) {
|
||
// Files ride to the chat only from this bot's own folder on the box.
|
||
Ok(tools::Target { place: tools::Place::Box { dir }, .. }) => match tools::box_path(std::path::Path::new(&dir), &path) {
|
||
Ok(p) => crate::cloudbox::copy_out_from(&dir, &p),
|
||
Err(e) => Err(e),
|
||
},
|
||
Ok(tools::Target { place: tools::Place::Sealed { root }, .. }) => Ok(tools::resolve(&root, &path)),
|
||
Ok(tools::Target { place: tools::Place::Local { workdir }, .. }) => Ok(tools::resolve(&workdir, &path)),
|
||
// Another of the person's computers: it sends the file over, then it is
|
||
// put in the chat like any other.
|
||
Ok(tools::Target { place: tools::Place::Device { host, dir }, .. }) => {
|
||
let args = serde_json::json!({"path": path, "workdir": tools::portable_dir(&dir), "workdir_as_chosen": dir.trim()}).to_string();
|
||
let tmp_dir = fetch_tmp.clone();
|
||
crate::remote::run_on_device(&host, crate::remote::FETCH_FILE, &args, &job.via_name).and_then(|v| {
|
||
let bytes = v["data"].as_str().and_then(|d| base64::engine::general_purpose::STANDARD.decode(d).ok()).ok_or_else(|| v["text"].as_str().unwrap_or("那台電腦沒有把檔案傳過來").to_string())?;
|
||
let safe_name = std::path::Path::new(v["name"].as_str().unwrap_or("檔案"))
|
||
.file_name()
|
||
.map(|n| n.to_string_lossy().to_string())
|
||
.filter(|n| !n.is_empty() && n != "." && n != "..")
|
||
.unwrap_or_else(|| "檔案".into());
|
||
let dst = tmp_dir.join(safe_name);
|
||
let _ = std::fs::create_dir_all(&tmp_dir);
|
||
std::fs::write(&dst, &bytes).map_err(|e| e.to_string())?;
|
||
Ok(dst)
|
||
})
|
||
}
|
||
Ok(_) => Err(format!("這台電腦上的檔案不能直接傳,請先複製到「{}」。", job.roles.own)),
|
||
Err(e) => Err(e),
|
||
};
|
||
// Secrets (SSH keys, the app's own data folder, .env…) never ride into the chat,
|
||
// same rule as read_file/edit_file.
|
||
let local = local.and_then(|p| if tools::is_ignored(&p) || tools::is_ignored(std::path::Path::new(&path)) { Err("這個檔案是機密的,不能傳出去。".to_string()) } else { Ok(p) });
|
||
if call.name == "send_to_device" {
|
||
let to = tools::args_of(&call.args)["to"].as_str().unwrap_or("").to_string();
|
||
let sent = local.and_then(|p| {
|
||
let (id, name) = crate::drops::target_called(&to).ok_or_else(|| {
|
||
let names: Vec<String> = crate::drops::targets().iter().filter_map(|t| t["name"].as_str().map(String::from)).collect();
|
||
if names.is_empty() { "沒有登入帳號,找不到其他裝置。".to_string() } else { format!("帳號裡沒有叫「{to}」的裝置。可以傳到:{}。", names.join("、")) }
|
||
})?;
|
||
let bytes = std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0);
|
||
let from_id = format!("bot-{bot_id}");
|
||
crate::drops::office().add_file(&p, &id, &name, &job.via_name, &from_id)?;
|
||
crate::drops::kick();
|
||
let file = p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||
Ok(if id == crate::drops::PHONE {
|
||
format!("已把「{file}」({})送到手機:使用者會收到通知,在手機 AnyBot 的「傳送到其他裝置」裡下載(保留 7 天)。", crate::attach::human(bytes))
|
||
} else {
|
||
format!("已把「{file}」({})交給大腦傳到「{name}」:它在線上的話馬上會出現在那台的 下載/AnyBot 資料夾並跳通知;沒開機的話,7 天內一開機就會收到。", crate::attach::human(bytes))
|
||
})
|
||
});
|
||
let _ = std::fs::remove_dir_all(&fetch_tmp);
|
||
match sent {
|
||
Ok(out) => s.finish(&out, ToolStatus::Done, None),
|
||
Err(e) => s.finish(&e, ToolStatus::Failed, None),
|
||
}
|
||
return Flow::Next;
|
||
}
|
||
let stored = local.and_then(|p| crate::attach::store(bot_id, &p));
|
||
// (A file fetched from another computer was only parked here on its way.)
|
||
let _ = std::fs::remove_dir_all(&fetch_tmp);
|
||
let (output, ok) = match stored {
|
||
Ok(a) => {
|
||
let out = format!("已把「{}」傳到聊天裡({}),使用者點一下就能預覽。", a.name, crate::attach::human(a.bytes));
|
||
send(StreamEvent::Attach(a));
|
||
(out, true)
|
||
}
|
||
Err(e) => (e, false),
|
||
};
|
||
s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 檔案預覽 / Bot 做的頁面: open what the bot made on the person's screen.
|
||
pub(super) struct OpenForPerson;
|
||
|
||
impl TurnTool for OpenForPerson {
|
||
fn name(&self) -> &'static str {
|
||
"OpenForPerson"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "open_for_person"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let call = s.call.clone();
|
||
// (A file on its way out is read on the way first: file_out_refused.)
|
||
if let Some(flow) = file_out_refused(s) {
|
||
return flow;
|
||
}
|
||
s.started();
|
||
let v = tools::args_of(&call.args);
|
||
let path = v["path"].as_str().unwrap_or("").to_string();
|
||
let web = path.starts_with("http://") || path.starts_with("https://");
|
||
let on_box = match target_for(job, &call.args) {
|
||
Ok(t) => match t.place {
|
||
tools::Place::Box { dir } => Some(tools::box_path(std::path::Path::new(&dir), &path).map(|p| (dir, p))),
|
||
_ => None,
|
||
},
|
||
Err(_) => None,
|
||
};
|
||
// On a server nobody sits at its screen: a link opens in the browser of the
|
||
// computer the person is using; a file is sent into the chat instead.
|
||
let person_now = roles_now(job).person;
|
||
let person_host = person_now.as_ref().and_then(|n| job.computers.iter().find(|t| &t.name == n)).and_then(|t| match &t.place {
|
||
tools::Place::Device { host, .. } => Some(host.clone()),
|
||
_ => None,
|
||
});
|
||
if job.roles.server {
|
||
let (output, ok) = match (&person_host, web) {
|
||
(Some(host), true) => match crate::remote::run_on_device(host, "browser_open", &serde_json::json!({"url": path}).to_string(), &job.via_name) {
|
||
Ok(v) => (format!("[{}] {}", person_now.clone().unwrap_or_default(), v["text"].as_str().unwrap_or("")), v["ok"].as_bool().unwrap_or(false)),
|
||
Err(e) => (e, false),
|
||
},
|
||
(None, true) => ("不知道使用者現在在用哪台電腦,沒辦法打開給他看。把網址直接寫在回覆裡。".to_string(), false),
|
||
(_, false) => ("AnyBot 在伺服器上,檔案沒辦法直接在使用者的螢幕打開。改用 send_file 把檔案傳到聊天裡,使用者點一下就能看。".to_string(), false),
|
||
};
|
||
s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None);
|
||
return Flow::Next;
|
||
}
|
||
let local = match (&on_box, target_for(job, &call.args)) {
|
||
// A web address is the same address on every computer. (It came after the
|
||
// file cases, which turned it into a path inside the work folder.)
|
||
_ if web => Ok(std::path::PathBuf::from(&path)),
|
||
(Some(Ok((dir, p))), _) => crate::cloudbox::copy_out_from(dir, p),
|
||
(Some(Err(e)), _) => Err(e.clone()),
|
||
(None, Ok(tools::Target { place: tools::Place::Sealed { root }, .. })) => Ok(tools::resolve(&root, &path)),
|
||
(None, Ok(tools::Target { place: tools::Place::Local { workdir }, .. })) => Ok(tools::resolve(&workdir, &path)),
|
||
_ => Err(format!("這台電腦上的檔案不能直接打開給使用者看,請先複製到「{}」或這台電腦。", job.roles.own)),
|
||
};
|
||
// Secrets never open on the person's screen either.
|
||
let local = local.and_then(|p| if tools::is_ignored(&p) || tools::is_ignored(std::path::Path::new(&path)) { Err("這個檔案是機密的,不能打開。".to_string()) } else { Ok(p) });
|
||
// Showing is not running: a script or an app would start on the person's
|
||
// computer, outside every sandbox, the moment it is opened.
|
||
let local = local.and_then(|p| {
|
||
if !web && crate::preview::runs_when_opened(&p) {
|
||
Err("這是程式或指令檔,打開就會在使用者的電腦上執行,所以不能用 open_for_person 打開。要給使用者看內容,用 send_file 傳到聊天裡。".to_string())
|
||
} else {
|
||
Ok(p)
|
||
}
|
||
});
|
||
let (output, ok) = match local {
|
||
Ok(p) if p.exists() || web => match crate::preview::system_open(&p).status() {
|
||
Ok(st) if st.success() => (format!("已在使用者的螢幕上打開 {}。", p.display()), true),
|
||
_ => (format!("打不開 {}", p.display()), false),
|
||
},
|
||
Ok(p) => (format!("找不到 {}", p.display()), false),
|
||
Err(e) => (e, false),
|
||
};
|
||
s.finish(&output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 打電話、傳簡訊、在 X 發文: speaks for the person, so asked every single time
|
||
/// (like the original's send tools; no "always").
|
||
pub(super) struct Phone;
|
||
|
||
impl TurnTool for Phone {
|
||
fn name(&self) -> &'static str {
|
||
"Phone"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
crate::phone::is_phone_tool(&s.call.name)
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
let what = crate::phone::describe(&call.name, &call.args);
|
||
let answer = s.ask_person(ApprovalKind::Action, what, String::new());
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
let (output, status) = if answer == ApprovalAnswer::Reject {
|
||
("使用者沒有允許。請不要再試,改問使用者。".to_string(), ToolStatus::Denied)
|
||
} else {
|
||
s.started();
|
||
match crate::phone::run(&call.name, &call.args) {
|
||
(t, true) => (t, ToolStatus::Done),
|
||
(t, false) => (t, ToolStatus::Failed),
|
||
}
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 發布網站: put a page or folder the bot made on the web (asked once per site name).
|
||
pub(super) struct PublishSite;
|
||
|
||
impl TurnTool for PublishSite {
|
||
fn name(&self) -> &'static str {
|
||
"PublishSite"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == "publish_site"
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
let v = tools::args_of(&call.args);
|
||
let path = v["path"].as_str().unwrap_or("").to_string();
|
||
let name = v["name"].as_str().unwrap_or("").trim().to_lowercase();
|
||
let grant = format!("publish:{name}");
|
||
// What goes on the public web is read first, with read_file's walls: a
|
||
// secret never, a sealed bot nothing outside its folder. 「一律允許」 is for a
|
||
// site made in the work folder; from anywhere else (it used to cover any
|
||
// folder on the computer) the person is asked each time.
|
||
let walls = match target_for(job, &call.args) {
|
||
Ok(t) if matches!(t.place, tools::Place::Local { .. }) && job.local_locked => {
|
||
Decision::Deny(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能發布「{}」上的檔案。", t.name))
|
||
}
|
||
Ok(t) => tools::decide_file_out(&t, &path, &[]),
|
||
Err(_) => Decision::Allow,
|
||
};
|
||
if let Decision::Deny(r) = walls {
|
||
s.finish(&format!("被安全規則擋下:{r}"), ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
let outside = matches!(walls, Decision::Ask { .. });
|
||
let grant = if outside { String::new() } else { grant };
|
||
let mut allowed = !outside && s.grants.contains(&grant);
|
||
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::Always(g) => {
|
||
keep_grant(s.grants, g);
|
||
allowed = true;
|
||
}
|
||
ApprovalAnswer::Reject => {}
|
||
}
|
||
}
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
let (output, status) = if !allowed {
|
||
("使用者沒有允許發布。".to_string(), ToolStatus::Denied)
|
||
} else {
|
||
s.started();
|
||
let mut box_tmp: Option<std::path::PathBuf> = None;
|
||
let local = match target_for(job, &call.args) {
|
||
Ok(tools::Target { place: tools::Place::Box { dir }, .. }) => tools::box_path(std::path::Path::new(&dir), &path).and_then(|p| {
|
||
let copied = crate::cloudbox::copy_out_from(&dir, &p)?;
|
||
box_tmp = copied.parent().map(std::path::PathBuf::from);
|
||
Ok(copied)
|
||
}),
|
||
Ok(tools::Target { place: tools::Place::Sealed { root }, .. }) => Ok(tools::resolve(&root, &path)),
|
||
Ok(tools::Target { place: tools::Place::Local { workdir }, .. }) => Ok(tools::resolve(&workdir, &path)),
|
||
Ok(_) => Err(format!("這台電腦上的檔案不能直接發布,請先複製到「{}」。", job.roles.own)),
|
||
Err(e) => Err(e),
|
||
};
|
||
let res = local.and_then(|p| crate::remote::publish_site(&name, &p));
|
||
if let Some(d) = box_tmp {
|
||
let _ = std::fs::remove_dir_all(d);
|
||
}
|
||
match res {
|
||
Ok(url) => (format!("已發布:{url}"), ToolStatus::Done),
|
||
Err(e) => (e, ToolStatus::Failed),
|
||
}
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// 保險庫: the bot sees only metadata; filling asks the person first. A login on a
|
||
/// site it wasn't saved for warns about look-alike sites and can't be "always";
|
||
/// a card is asked every time (like the original's 允許一次 / 拒絕).
|
||
pub(super) struct VaultList;
|
||
|
||
impl TurnTool for VaultList {
|
||
fn name(&self) -> &'static str {
|
||
"VaultList"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::vault::LIST_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let call = s.call.clone();
|
||
let output = crate::vault::list_for_bot(&call.args);
|
||
s.finish(&output, ToolStatus::Done, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// VaultFill
|
||
pub(super) struct VaultFill;
|
||
|
||
impl TurnTool for VaultFill {
|
||
fn name(&self) -> &'static str {
|
||
"VaultFill"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::vault::TOOL || s.call.name == crate::vault::CARD_TOOL || s.call.name == crate::vault::CONTACT_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let bot_id = s.bot_id;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
enum Plan {
|
||
Login(Box<crate::vault::LoginPlan>),
|
||
Card((String, crate::vault_store::Item)),
|
||
Contact((String, crate::vault_store::Item)),
|
||
}
|
||
// An item the vault doesn't have: said before any browser is touched (the
|
||
// answer used to be "no open tab, browser_open first", and the bot went round).
|
||
if let Err(e) = crate::vault::check_ids(&call.name, &call.args) {
|
||
s.finish(&e, ToolStatus::Failed, None);
|
||
return Flow::Next;
|
||
}
|
||
// The fill lands in the same browser browser_* uses: the chosen computer's,
|
||
// the cloud box's, or this one's. The vault store and the person's approval
|
||
// stay on this computer; a chosen computer spends one entry's secret per call.
|
||
let (place, _who) = match browser_place(job, "browser_open", &call.args) {
|
||
Ok(x) => x,
|
||
Err(e) => {
|
||
s.finish(&e, ToolStatus::Failed, None);
|
||
return Flow::Next;
|
||
}
|
||
};
|
||
let v0 = tools::args_of(&call.args);
|
||
let profile = v0["profile"].as_str().unwrap_or("").to_string();
|
||
let tag = s.browsers.job.clone();
|
||
let plan_here = || -> Result<(Plan, String, String), String> {
|
||
if call.name == crate::vault::TOOL {
|
||
crate::vault::plan_login(&call.args).map(|pl| {
|
||
let q = pl.question();
|
||
let grant = if pl.matched { format!("login:{}", pl.host) } else { String::new() };
|
||
(Plan::Login(Box::new(pl)), q, grant)
|
||
})
|
||
} else if call.name == crate::vault::CARD_TOOL {
|
||
crate::vault::plan_card(&call.args).map(|(host, c)| {
|
||
let msg = format!("用保險庫的卡片({} •••• {})在 {host} 填入付款資料(Bot 看不到卡號和安全碼)", c.display_title(), c.last4);
|
||
(Plan::Card((host, c)), msg, String::new())
|
||
})
|
||
} else {
|
||
crate::vault::plan_contact(&call.args).map(|(host, c)| {
|
||
let msg = format!("把保險庫的聯絡資訊「{}」填進 {host} 的表單", c.display_title());
|
||
let grant = format!("contact:{host}");
|
||
(Plan::Contact((host, c)), msg, grant)
|
||
})
|
||
}
|
||
};
|
||
// On a chosen computer the page lives over the relay: read its url there,
|
||
// plan with this computer's vault, fill there only after the person allows.
|
||
let planned: Result<(Plan, String, String), String> = match &place {
|
||
BrowserAt::Device(h) => match crate::remote::run_on_device(h, crate::vault::REMOTE_TOOL, &with_job(&serde_json::json!({"kind": "host", "profile": profile}).to_string(), &tag), &job.via_name)
|
||
.and_then(|r| if r["ok"].as_bool().unwrap_or(false) { Ok(r) } else { Err(r["text"].as_str().unwrap_or("那台電腦的瀏覽器無法使用").to_string()) })
|
||
{
|
||
Ok(t) => {
|
||
let host = t["host"].as_str().unwrap_or("").to_string();
|
||
let url = t["url"].as_str().unwrap_or("").to_string();
|
||
if call.name == crate::vault::TOOL {
|
||
crate::vault::plan_login_on(&host, &v0).map(|pl| {
|
||
let q = pl.question();
|
||
let grant = if pl.matched { format!("login:{}", pl.host) } else { String::new() };
|
||
(Plan::Login(Box::new(pl)), q, grant)
|
||
})
|
||
} else if call.name == crate::vault::CARD_TOOL {
|
||
crate::vault::plan_card_at(&v0, &url).map(|(h, c)| {
|
||
let msg = format!("用保險庫的卡片({} •••• {})在 {h} 填入付款資料(Bot 看不到卡號和安全碼)", c.display_title(), c.last4);
|
||
(Plan::Card((h, c)), msg, String::new())
|
||
})
|
||
} else {
|
||
crate::vault::plan_contact_at(&v0).map(|c| {
|
||
let msg = format!("把保險庫的聯絡資訊「{}」填進 {host} 的表單", c.display_title());
|
||
let grant = format!("contact:{host}");
|
||
(Plan::Contact((host.clone(), c)), msg, grant)
|
||
})
|
||
}
|
||
}
|
||
Err(e) => Err(e),
|
||
}
|
||
// (On this job's own tab, like its other browser steps: planned outside
|
||
// it, every tab looked like another job's — "no open tab".)
|
||
BrowserAt::Box => crate::cloudbox::on_screen(&box_screen_of(job, bot_id), || crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(plan_here))),
|
||
BrowserAt::Here => crate::botbrowser::as_job(&tag, plan_here),
|
||
};
|
||
let (output, status) = match planned {
|
||
Err(e) => (e, ToolStatus::Failed),
|
||
Ok((plan, question, grant)) => {
|
||
let mut allowed = !grant.is_empty() && s.grants.contains(&grant);
|
||
let mut remember_site = false;
|
||
if !allowed {
|
||
match s.ask_person(ApprovalKind::Action, question, grant.clone()) {
|
||
ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true,
|
||
ApprovalAnswer::Always(g) => {
|
||
keep_grant(s.grants, g);
|
||
allowed = true;
|
||
remember_site = true;
|
||
}
|
||
ApprovalAnswer::Reject => {}
|
||
}
|
||
}
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
if !allowed {
|
||
("使用者沒有允許使用保險庫的這個項目。請改問使用者。".to_string(), ToolStatus::Denied)
|
||
} else {
|
||
s.started();
|
||
let submit = tools::args_of(&call.args)["submit"].as_bool().unwrap_or(false);
|
||
let fill_here = || match &plan {
|
||
Plan::Login(pl) => crate::vault::fill_login_with(pl, submit, remember_site),
|
||
Plan::Card((host, _)) => crate::vault::fill_card_on(&call.args, Some(host)),
|
||
Plan::Contact((host, _)) => crate::vault::fill_contact_on(&call.args, Some(host)),
|
||
};
|
||
let r = match (&plan, &place) {
|
||
(Plan::Login(pl), BrowserAt::Device(h)) => remote_vault_login(h, job, &tag, pl, submit, remember_site),
|
||
(Plan::Card((host, c)), BrowserAt::Device(h)) => {
|
||
let a = serde_json::json!({"kind": "form", "values": crate::vault::card_values(c), "site": host, "profile": profile, "https": true}).to_string();
|
||
remote_vault_page(h, job, &with_job(&a, &tag)).and_then(|page| crate::vault::card_fill_text(c, &page))
|
||
}
|
||
(Plan::Contact((host, c)), BrowserAt::Device(h)) => {
|
||
let a = serde_json::json!({"kind": "form", "values": crate::vault::contact_values(c), "site": host, "profile": profile}).to_string();
|
||
remote_vault_page(h, job, &with_job(&a, &tag)).and_then(|page| crate::vault::contact_fill_text(c, &page))
|
||
}
|
||
(_, BrowserAt::Box) => crate::cloudbox::on_screen(&box_screen_of(job, bot_id), || crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(fill_here))),
|
||
(_, BrowserAt::Here) => crate::botbrowser::as_job(&tag, fill_here),
|
||
};
|
||
match r {
|
||
Ok(t) => (t, ToolStatus::Done),
|
||
Err(e) => (e, ToolStatus::Failed),
|
||
}
|
||
}
|
||
}
|
||
};
|
||
s.finish(&output, status, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// Connectors with many tools: finding one is only a look at their list.
|
||
pub(super) struct ConnectorFind;
|
||
|
||
impl TurnTool for ConnectorFind {
|
||
fn name(&self) -> &'static str {
|
||
"ConnectorFind"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
s.call.name == crate::mcp::FIND_TOOL
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let job = s.job;
|
||
let call = s.call.clone();
|
||
if !job.req.tools.iter().any(|t| t["name"].as_str() == Some(crate::mcp::FIND_TOOL)) {
|
||
s.finish("這個回合沒有提供連接器工具。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
s.started();
|
||
let out = crate::mcp::find(&call.args);
|
||
s.finish(&out, ToolStatus::Done, None);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// MCP connectors: asked once per server (or always allowed), like the original's
|
||
/// MCP allow-list; direct mode doesn't ask. A tool run through use_connector_tool
|
||
/// is that tool: the same question, the same call.
|
||
pub(super) struct Connector;
|
||
|
||
impl TurnTool for Connector {
|
||
fn name(&self) -> &'static str {
|
||
"Connector"
|
||
}
|
||
|
||
fn takes(&self, s: &Step<'_>) -> bool {
|
||
mcp_step(&s.call).is_some()
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let Some(step) = mcp_step(&s.call) else { return Flow::Next };
|
||
let job = s.job;
|
||
let cancel = s.cancel;
|
||
if !job.req.tools.iter().any(|t| t["name"].as_str().is_some_and(|n| crate::mcp::is_mcp_tool(n) || n == crate::mcp::USE_TOOL)) {
|
||
s.finish("這個回合沒有提供連接器工具。", ToolStatus::Denied, None);
|
||
return Flow::Next;
|
||
}
|
||
let (mcp_name, mcp_args) = match step {
|
||
Ok(x) => x,
|
||
Err(e) => {
|
||
s.finish(&e, ToolStatus::Failed, None);
|
||
return Flow::Next;
|
||
}
|
||
};
|
||
let (server, tool) = crate::mcp::resolve(&mcp_name).unwrap_or_default();
|
||
let grant = format!("mcp:{server}");
|
||
let args_short: String = mcp_args.chars().take(160).collect();
|
||
let mut allowed = job.direct.load(Ordering::Relaxed) || s.grants.contains(&grant);
|
||
if !allowed {
|
||
match s.ask_person(ApprovalKind::Action, format!("使用連接器「{server}」的工具:{tool} {args_short}"), grant.clone()) {
|
||
ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true,
|
||
ApprovalAnswer::Always(g) => {
|
||
keep_grant(s.grants, g);
|
||
allowed = true;
|
||
}
|
||
ApprovalAnswer::Reject => {}
|
||
}
|
||
}
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
let (output, status, img) = if allowed {
|
||
s.started();
|
||
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)
|
||
};
|
||
s.finish(&output, status, img);
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// Everything else runs on a computer: which one, the switches to use computers and this
|
||
/// one, the safety rules (gate.rs step 6), 自動審核 (step 7), the hook's word, the questions
|
||
/// asked every time (step 8), the screen's lease — then the step itself. It takes every call.
|
||
pub(super) struct OnComputer;
|
||
|
||
impl TurnTool for OnComputer {
|
||
fn name(&self) -> &'static str {
|
||
"OnComputer"
|
||
}
|
||
|
||
fn takes(&self, _s: &Step<'_>) -> bool {
|
||
true
|
||
}
|
||
|
||
fn run(&self, s: &mut Step<'_>) -> Flow {
|
||
let call0 = &s.call;
|
||
let (is_web, is_screen, is_mac) = (web::is_web_tool(&call0.name), computer::is_computer_tool(&call0.name), crate::macapps::is_mac_tool(&call0.name));
|
||
let job = s.job;
|
||
let bot_id = s.bot_id;
|
||
let send = s.send;
|
||
let cancel = s.cancel;
|
||
let refused = s.refused;
|
||
let call = s.call.clone();
|
||
let what = s.what();
|
||
// The person's own apps and everyday browser are on the computer they are using:
|
||
// the one they name, else the one they typed on (else this one, when it is theirs).
|
||
let person_target = || -> Result<tools::Target, String> {
|
||
if names_a_computer(&call.args) {
|
||
return target_for(job, &call.args);
|
||
}
|
||
roles_now(job)
|
||
.person
|
||
.and_then(|n| job.computers.iter().find(|t| t.name == n))
|
||
.cloned()
|
||
.ok_or_else(|| format!("不知道使用者現在在用哪台電腦。請問他要在哪台做(可以用:{})。", job.computers.iter().map(|t| t.name.as_str()).collect::<Vec<_>>().join("、")))
|
||
};
|
||
let target = if is_screen {
|
||
screen_target(job, &call.args)
|
||
} else if is_mac || is_web {
|
||
// (Other browser steps went their own way above; this is the person's own Chrome.)
|
||
person_target()
|
||
} else {
|
||
target_for(job, &call.args)
|
||
};
|
||
let on_box = matches!(target.as_ref().map(|t| &t.place), Ok(tools::Place::Box { .. }));
|
||
// 每個 Bot 一個螢幕: the screen of the bot whose folder this is (a 支線's own).
|
||
let box_screen = match target.as_ref().map(|t| &t.place) {
|
||
Ok(tools::Place::Box { dir }) => box_screen_in(job, bot_id, dir),
|
||
_ => String::new(),
|
||
};
|
||
let on_device = match target.as_ref().map(|t| &t.place) {
|
||
Ok(tools::Place::Device { host, .. }) => Some(host.clone()),
|
||
_ => None,
|
||
};
|
||
// Permission to use computers at all, and this Mac in particular, is asked for
|
||
// when it's needed instead of the step failing quietly.
|
||
let mut gate: Result<(), String> = Ok(());
|
||
// The person just said yes to this very step in a switch's pop-up (it shows the
|
||
// step): no second pop-up for it.
|
||
let mut said_yes = false;
|
||
// 直接操作: like the reference assistant after its one-time setup ("讓 the reference assistant 在你的電腦上開啟檔案和
|
||
// 執行任務。自動審核仍會先檢查所有操作", ENHi8c), nothing is asked except what the
|
||
// safety checks and the person's "一律詢問" rules stop.
|
||
let direct = job.direct.load(Ordering::Relaxed);
|
||
if direct {
|
||
*s.tools_on = true;
|
||
*s.local_on = true;
|
||
}
|
||
if let Ok(t) = &target {
|
||
if !*s.tools_on && !*s.tools_once {
|
||
if refused.borrow().iter().any(|r| r == "gate:tools") {
|
||
gate = Err(REFUSED_ALREADY.into());
|
||
} 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(_) => {
|
||
*s.tools_once = true;
|
||
said_yes = true;
|
||
}
|
||
ApprovalAnswer::Always(_) => {
|
||
*s.tools_on = true;
|
||
said_yes = true;
|
||
}
|
||
ApprovalAnswer::Reject => {
|
||
refused.borrow_mut().push("gate:tools".into());
|
||
gate = Err("使用者沒有允許使用電腦工具。請改用文字回答,或問使用者想怎麼做。".into());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// An admin lock (policy) refuses outright instead of asking.
|
||
if gate.is_ok() && matches!(t.place, tools::Place::Local { .. }) && job.local_locked {
|
||
gate = Err(format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能在「{}」上執行。請改用「{}」。", t.name, job.roles.own));
|
||
}
|
||
if gate.is_ok() && matches!(t.place, tools::Place::Local { .. }) && !*s.local_on && !*s.local_once {
|
||
if refused.borrow().iter().any(|r| r == "gate:local") {
|
||
gate = Err(REFUSED_ALREADY.into());
|
||
} 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(_) => {
|
||
*s.local_once = true;
|
||
said_yes = true;
|
||
}
|
||
ApprovalAnswer::Always(_) => {
|
||
*s.local_on = true;
|
||
said_yes = true;
|
||
}
|
||
ApprovalAnswer::Reject => {
|
||
refused.borrow_mut().push("gate:local".into());
|
||
gate = Err(format!("使用者沒有允許在「{}」上執行。可以改用「{}」,或問使用者。", t.name, job.roles.own));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
// Step 6 (gate.rs): what kind of step it is decides. Can't reach that computer, or
|
||
// the person said no to the pop-up: nothing to ask (reported below).
|
||
let decision = match (&target, &gate) {
|
||
(Ok(t), Ok(())) => {
|
||
let place = if is_screen && on_box { crate::gate::Place::OwnBox } else if on_device.is_some() { crate::gate::Place::Device(&t.name) } else { crate::gate::Place::Elsewhere };
|
||
crate::gate::by_kind(&call.name, &call.args, &what, &job.via_name, t, place, || computer::target_app(&call.name, &call.args), s.grants)
|
||
}
|
||
_ => Decision::Allow,
|
||
};
|
||
// 自動審核: when the rules say yes, continue without asking (JOecNC);
|
||
// when an "always ask" rule matches, stop and ask (Pca/iV).
|
||
let mut review_note = String::new();
|
||
let mut must_ask = false;
|
||
let direct = job.direct.load(Ordering::Relaxed);
|
||
let decision = match (decision, &job.review) {
|
||
// Direct mode: go ahead, unless an "always ask" rule matches.
|
||
(Decision::Ask { reason, grant }, review) if direct => {
|
||
// Only looking (a screenshot, a page or file read) changes nothing, so no
|
||
// "always ask" rule (deleting, paying, posting…) can be about it: no model
|
||
// 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() }, &call.name, &call.args, &reason, cancel),
|
||
_ => ReviewVerdict::NoMatch,
|
||
};
|
||
match verdict {
|
||
ReviewVerdict::Ask(rule) => {
|
||
must_ask = true;
|
||
Decision::Ask { reason: format!("{reason}(符合你的「一律詢問」規則:{rule})"), grant: String::new() }
|
||
}
|
||
// Nobody could check the person's "always ask" rules: ask, never go ahead.
|
||
ReviewVerdict::Failed => {
|
||
must_ask = true;
|
||
Decision::Ask { reason: format!("{reason}{REVIEW_FAILED_NOTE}"), grant: String::new() }
|
||
}
|
||
// (No note on the result: the model doesn't need it, and it was on every step.)
|
||
_ => {
|
||
let _ = grant;
|
||
Decision::Allow
|
||
}
|
||
}
|
||
}
|
||
(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
|
||
}
|
||
ReviewVerdict::Ask(rule) => {
|
||
must_ask = true;
|
||
Decision::Ask { reason: format!("{reason}(符合你的「一律詢問」規則:{rule})"), grant: String::new() }
|
||
}
|
||
ReviewVerdict::NoMatch => Decision::Ask { reason, grant },
|
||
ReviewVerdict::Failed => {
|
||
must_ask = true;
|
||
Decision::Ask { reason: format!("{reason}{REVIEW_FAILED_NOTE}"), grant }
|
||
}
|
||
},
|
||
(d, _) => d,
|
||
};
|
||
// A click or key-submit whose target says money, sending, deleting: asked every
|
||
// time, on every computer (local, remote device, or box), in direct mode too.
|
||
// Harness policy: the model (and anything it read on a page) cannot grant its way past this one.
|
||
let parsed_args = tools::args_of(&call.args);
|
||
// (This computer's latest look is only about steps on this computer: for the box or
|
||
// another computer its numbers name other controls — the chat's latest look does.)
|
||
let here = !on_box && on_device.is_none();
|
||
let sensitive_click = matches!(call.name.as_str(), "computer_use_click" | "computer_use_batch" | "computer_use_menu_click" | "computer_use_typing" | "computer_use_press_key")
|
||
&& here
|
||
.then(|| computer::sensitive_target(&call.name, &parsed_args))
|
||
.flatten()
|
||
.or_else(|| sensitive_in_history(&call.name, &parsed_args, s.history))
|
||
.is_some_and(|l| computer::sensitive_words(&l));
|
||
// Hooks' PreToolUse allow saves a question (never a refusal, nor step 8's); its ask asks.
|
||
let decision = match (s.hook_word.permission.as_ref().map(|(p, r)| (p.as_str(), r.as_str())), decision) {
|
||
(Some(("allow", _)), Decision::Ask { .. }) if !must_ask => Decision::Allow,
|
||
(Some(("ask", why)), Decision::Allow) => {
|
||
must_ask = true;
|
||
Decision::Ask { reason: format!("{what}(你的 hook 要先問:{})", if why.is_empty() { "沒有說原因" } else { why }), grant: String::new() }
|
||
}
|
||
(Some(("ask", why)), Decision::Ask { reason, .. }) => {
|
||
must_ask = true;
|
||
Decision::Ask { reason: format!("{reason}(你的 hook 要先問:{why})"), grant: String::new() }
|
||
}
|
||
(_, d) => d,
|
||
};
|
||
// Step 8 (gate.rs): asked every time, over steps 6 and 7.
|
||
let skip_msg_ask = call.name == crate::macapps::SEND_MESSAGE && s.grants.iter().any(|g| g == "messages:no-ask");
|
||
let on_persons = matches!(target.as_ref().map(|t| &t.place), Ok(tools::Place::Local { .. } | tools::Place::Device { .. }));
|
||
let decision = if gate.is_ok() && target.is_ok() {
|
||
let a = crate::gate::always_ask(&call.name, &parsed_args, &what, &job.via_name, decision, sensitive_click, on_persons, s.grants);
|
||
if a.overridden {
|
||
review_note.clear();
|
||
}
|
||
must_ask |= a.must_ask;
|
||
a.decision
|
||
} else {
|
||
decision
|
||
};
|
||
let approved = match decision {
|
||
_ if gate.is_err() => Err((gate.clone().unwrap_err(), ToolStatus::Denied)),
|
||
_ if target.is_err() => Err((target.clone().err().unwrap_or_default(), ToolStatus::Failed)),
|
||
Decision::Allow => Ok(()),
|
||
// Sending (Messages, mail…), sensitive clicks, outside-sandbox AppleScript, and
|
||
// explicit "always ask" matches still ask even right after enabling a switch.
|
||
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(())
|
||
}
|
||
ApprovalAnswer::Reject => Err(("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".into(), ToolStatus::Denied)),
|
||
}
|
||
}
|
||
};
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
let mut image = None;
|
||
// 螢幕一次給一個: acting on a screen another turn is working (not just looking).
|
||
let busy_screen = match (&approved, &target) {
|
||
(Ok(()), Ok(t)) if is_screen && !only_looks(&call.name) => turn_screen_key(job, bot_id, &t.place).and_then(|k| lease_screen(&mut screen_leases().lock().unwrap(), &k, bot_id, &job.via_name, Instant::now()).err().map(|e| (t.name.clone(), e))),
|
||
_ => None,
|
||
};
|
||
let approved = match busy_screen {
|
||
Some((name, (who, secs))) => Err((
|
||
format!("沒有執行:「{name}」的螢幕現在由「{who}」在操作({secs} 秒前還在用),兩邊一起點會互相打亂。先做不用這個螢幕的部分、改用別台電腦,或晚一點再試:它做完,或停手 {} 秒後就輪到你。", SCREEN_IDLE.as_secs()),
|
||
ToolStatus::Failed,
|
||
)),
|
||
None => approved,
|
||
};
|
||
let (output, status) = match (approved, &target) {
|
||
(Ok(()), Ok(t)) => {
|
||
s.started();
|
||
let ids = tools::RunIds { conversation: bot_id.to_string(), request: call.id.clone() };
|
||
// 檢查點: the file as it was, kept under the person's message that started this turn (/rewind).
|
||
if call.name == "edit_file" {
|
||
let turn = s.history.iter().rev().find(|m| m.role == Role::User && !m.note && m.at > 0).map(|m| m.at).unwrap_or(0);
|
||
crate::checkpoint::before_edit(bot_id, turn, t, &call.args);
|
||
}
|
||
let (out, ok) = if is_mac && on_device.is_none() {
|
||
crate::macapps::run(&call.name, &call.args)
|
||
} else if let (true, Some(host)) = (is_screen || is_web || is_mac, on_device.as_ref()) {
|
||
match crate::remote::run_on_device(host, &call.name, &call.args, &job.via_name) {
|
||
Ok(v) => {
|
||
image = v["image"].as_str().map(String::from);
|
||
(v["text"].as_str().unwrap_or("").to_string(), v["ok"].as_bool().unwrap_or(false))
|
||
}
|
||
Err(e) => (e, false),
|
||
}
|
||
} else if is_screen && on_box {
|
||
match crate::cloudbox::on_screen(&box_screen, || crate::cloudbox::computer_run(&call.name, &tools::args_of(&call.args))) {
|
||
Ok((out, img)) => {
|
||
image = img;
|
||
(out, true)
|
||
}
|
||
Err(e) => (e, false),
|
||
}
|
||
} else if is_screen {
|
||
let (out, ok, img) = computer::run_by(&call.name, &call.args, &job.via_name);
|
||
image = img;
|
||
(out, ok)
|
||
} else if is_web {
|
||
web::run(&call.name, &call.args, cancel)
|
||
} else if on_box {
|
||
// (A window a command opens goes to this turn's screen.)
|
||
crate::cloudbox::on_screen(&box_screen, || tools::run_on(&call.name, &call.args, t, cancel, &ids))
|
||
} else {
|
||
tools::run_on(&call.name, &call.args, t, cancel, &ids)
|
||
};
|
||
(format!("{review_note}[{}] {out}", t.name), if ok { ToolStatus::Done } else { ToolStatus::Failed })
|
||
}
|
||
(Ok(()), Err(e)) => (e.clone(), ToolStatus::Failed),
|
||
(Err(x), _) => x,
|
||
};
|
||
// 給使用者看畫面: the picture goes into the chat for the person (the bot still sees it).
|
||
if call.name == "computer_use_show" {
|
||
if let Some(bytes) = image.as_deref().and_then(|b| base64::engine::general_purpose::STANDARD.decode(b).ok()) {
|
||
// (No time in the name: a brain on a server keeps UTC, and the chat shows when.)
|
||
let name = format!("{} 的畫面.jpg", target.as_ref().map(|t| t.name.as_str()).unwrap_or("電腦"));
|
||
if let Ok(a) = crate::attach::store_bytes(bot_id, &name, &bytes) {
|
||
send(StreamEvent::Attach(a));
|
||
}
|
||
}
|
||
}
|
||
s.finish(&output, status, image);
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Flow::End;
|
||
}
|
||
Flow::Next
|
||
}
|
||
}
|
||
|
||
/// A file on its way out of a computer (into the chat, onto the person's screen) is
|
||
/// read on the way: read_file's walls and read_file's questions, before either
|
||
/// tool below touches it. Both used to run with no check but the secrets list.
|
||
/// (A web address isn't a file.)
|
||
fn file_out_refused(s: &mut Step<'_>) -> Option<Flow> {
|
||
let job = s.job;
|
||
let cancel = s.cancel;
|
||
let call = s.call.clone();
|
||
let what = s.what();
|
||
let path = tools::args_of(&call.args)["path"].as_str().unwrap_or("").to_string();
|
||
let web = call.name == "open_for_person" && (path.starts_with("http://") || path.starts_with("https://"));
|
||
if let (false, Ok(t)) = (web, target_for(job, &call.args)) {
|
||
let direct = job.direct.load(Ordering::Relaxed);
|
||
let local = matches!(t.place, tools::Place::Local { .. });
|
||
let refused: Option<(String, ToolStatus)> = if local && job.local_locked {
|
||
Some((format!("「在這台電腦上執行」設成了永不允許(或被管理員關閉),不能拿「{}」上的檔案。請改用「{}」。", t.name, job.roles.own), ToolStatus::Denied))
|
||
} else {
|
||
let decision = match tools::decide_file_out(&t, &path, s.grants) {
|
||
// Using this computer is switched off: its files are asked for one by one.
|
||
Decision::Allow if local && !direct && !(*s.tools_on && *s.local_on) => {
|
||
Decision::Ask { reason: format!("{}「{}」上的檔案:{what}", if call.name == "send_file" { "把檔案傳到聊天,來自" } else if call.name == "send_to_device" { "把檔案傳到你的另一台裝置,來自" } else { "在你的螢幕上打開" }, t.name), grant: String::new() }
|
||
}
|
||
// 直接操作 goes ahead where reading the file would.
|
||
Decision::Ask { .. } if direct => Decision::Allow,
|
||
d => d,
|
||
};
|
||
match decision {
|
||
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::Always(g) => {
|
||
keep_grant(s.grants, g);
|
||
None
|
||
}
|
||
ApprovalAnswer::Reject => Some(("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string(), ToolStatus::Denied)),
|
||
},
|
||
}
|
||
};
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return Some(Flow::End);
|
||
}
|
||
if let Some((output, status)) = refused {
|
||
s.finish(&output, status, None);
|
||
return Some(Flow::Next);
|
||
}
|
||
}
|
||
None
|
||
}
|