diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 183c1be..5ec9f7a 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -121,7 +121,7 @@ - 做法:MCP 的 OAuth(PKCE+動態註冊),在大腦上跑,手機或電腦開瀏覽器完成登入,Token 存保險庫。 - 做完:對一個測試用的 OAuth MCP 伺服器登入成功。 -### M7. 拆開 agent::spawn、Tool trait 🚧(spawn 已經從 1797 行拆到 373 行、行為不變(937ca5c);Tool trait 還沒做:一個工具呼叫的 1400 行在 run_call,約 40 個 `if call.name == …` 共用 finish/started 兩個閉包和十幾個區域變數,要先改成一個 StepCx 物件帶 finish/started 方法,再把每一塊搬成 trait 的實作。這一步要再整段改寫一次,跟拆 spawn 分開做比較安全) +### M7. 拆開 agent::spawn、Tool trait ✅(spawn 1797 → 373 行;一個工具呼叫的 1400 行拆成 src/agent/steps.rs 的 28 個 TurnTool,照原本的順序排在 TOOLS 裡,第一個 takes 的就 run;原本夾在中間的拒絕(看不懂的動作、沒有這個能力、技能的 allowed-tools、別人傳來的訊息)也是清單裡的一項,位置不變;最後一項 OnComputer 收下其他的。run_call 剩 146 行。工具的說明(spec)還是寫在各自的模組,trait 管的是一輪怎麼跑它們) - 做法:E9 之後,把工具執行改成一個 `Tool` trait(參數型別、說明、是否只看、執行),`spawn` 不再用一長串 if 分派。 - 做完:行為不變,`agent.rs` 的 `spawn` 小於 500 行。 diff --git a/src/agent.rs b/src/agent.rs index cdc8a32..b8e9ce1 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -474,7 +474,7 @@ impl Drop for UsedBrowsers { } } -#[derive(Debug)] +#[derive(Debug, Clone)] enum BrowserAt { Here, Box, @@ -1683,6 +1683,8 @@ fn route_of(name: &str) -> &'static str { } } +mod steps; + /// What one tool call left the turn to do. enum Flow { /// On to the next call. @@ -1725,8 +1727,9 @@ struct CallTurn<'a> { moved: &'a std::collections::HashMap, } -/// One tool call of a step, start to end (M7: moved out of spawn, unchanged): checked, asked -/// about, run, and its result in the chat. +/// One tool call of a step: the checks before any tool (the same click twice, a hook's no, the +/// plan not approved yet, 鬼打牆, the same failure, refused already), then the tool that takes +/// it (steps.rs) runs it. fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { #[allow(unused_mut)] let CallTurn { job, bot_id, send, cancel, mut history, mut grants, said_no, refused, trouble, mut tools_on, mut local_on, mut tools_once, mut local_once, mut browsers, sent_count, hooks, hook_base, runs, mut tried, step_sent_at, step_sent, step_note, skill_limit, mut previous, mut plan_changes, last_sent, runs_with, mut replay, mut plan_go, moved } = t; @@ -1835,1330 +1838,44 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow { history.push(result); return Flow::Next; } - // Every step ends the same way: its status, then its result (with the notes) and - // any picture, shown and kept. - let finish = |history: &mut Vec, output: &str, status: ToolStatus, image: Option| { - if status == ToolStatus::Denied && said_no.replace(false) { - refused.borrow_mut().push(refused_key.clone()); - } - // A click that changed nothing on the screen is trouble too, though it "worked". - if matches!(status, ToolStatus::Failed | ToolStatus::Denied) || !repeat_note.is_empty() || output.contains(crate::computer::NOOP_TAG) { - 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("被安全規則擋下")); - 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 = 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 = step_note.take(); - let sent_at = step_sent_at.take(); - if status == ToolStatus::Done && (!sent.is_empty() || (!crate::browser::is_tool(&call.name) && crate::evidence::sends(&call))) { - last_sent.set(Some(sent_at.unwrap_or_else(Instant::now))); - sent_count.set(sent_count.get() + 1); - if job.target_sends > 0 && sent_count.get() == job.target_sends { - reached.push_str(&format!("\n【系統】已達到這一輪的完成條件:送出 {0}/{0} 則。不要再送,收尾回報。", job.target_sends)); - } - } - job.note(crate::oplog::Record::ToolFinished { op: job.op.clone(), call_id: call.id.clone(), status: format!("{status:?}").to_lowercase(), at: crate::model::now_ms() }); - 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 && !hooks.is_empty() { - let mut input = 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 = 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(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!("{repeat_note}{body}{reached}")); - result.sent = sent; - result.images.extend(image); - send(StreamEvent::ToolResult(result.clone())); - history.push(result); + // The tool that takes this call runs it (steps.rs: the list, in the order they are asked). + let mut s = steps::Step { + job, + bot_id, + send, + cancel, + history, + grants, + said_no, + refused, + trouble, + tools_on, + local_on, + tools_once, + local_once, + browsers, + sent_count, + hooks, + hook_base, + runs, + step_sent_at, + step_sent, + step_note, + skill_limit, + plan_changes, + last_sent, + replay, + plan_go, + moved, + call, + refused_key, + repeat_note, + hook_word, + browser: Default::default(), }; - // 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. - let started = || { - job.note(crate::oplog::Record::ToolStarted { op: 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() }); - send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Running)); - }; - // 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.) - if call.name == crate::browser::TOOL || call.name == computer::TOOL { - finish(history, &bad_action(&call.name, &call.args), ToolStatus::Failed, None); - return Flow::Next; - } - // Not one of this bot's abilities: it was never offered; say so instead of running it. - if let Some(k) = crate::profile::ability_of(&call.name).filter(|k| job.lacks.iter().any(|l| l == k)) { - finish(history, &crate::profile::lacking_text(k), ToolStatus::Denied, None); - return Flow::Next; - } - // A loaded skill's allowed-tools: anything else isn't run this turn. - let outside = skill_limit.borrow().as_ref().filter(|(_, rules)| !crate::skills::skill_allows(rules, &call.name, &call.args)).map(|(name, rules)| (name.clone(), rules.clone())); - if let Some((skill, rules)) = outside { - let text = format!("沒有執行:這一輪用的技能「{skill}」只准用 {},「{}」不在裡面。照技能的做法用那些工具做;真的需要別的,先告訴使用者。", rules.join("、"), call.name); - finish(history, &text, ToolStatus::Denied, None); - return Flow::Next; - } - if call.name == REPLAY_TOOL { - 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 = missing.iter().map(|m| (m.clone(), serde_json::Value::String("…".into()))).collect(); - finish(history, &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(); - finish(history, &format!("開始重播「{name}」,共 {total} 步:AnyBot 會一步一步照做,每一步先在畫面上找到同一個東西,對不上會停下來交給你。"), ToolStatus::Done, None); - *replay = Some(Replay { name, left: steps, total, looked: None }); - } - Some(_) => finish(history, &format!("「{name}」沒有存可以重播的步驟:用 use_skill 讀出做法,照著自己做。"), ToolStatus::Failed, None), - None => finish(history, &format!("沒有叫「{name}」的技能。"), ToolStatus::Failed, None), - } - return Flow::Next; - } - // 功能地圖: one area of AnyBot's own map (featuremap.rs), read on the brain. - if call.name == crate::featuremap::TOOL { - started(); - match crate::featuremap::read(tools::args_of(&call.args)["topic"].as_str().unwrap_or("")) { - Ok(text) => finish(history, &text, ToolStatus::Done, None), - Err(e) => finish(history, &e, ToolStatus::Failed, None), - } - return 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. - if call.name == "look_image" { - 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 = history.iter().rev().flat_map(|m| m.images.iter().rev().cloned()).collect(); - match pics.get(idx) { - None => finish(history, &format!("對話裡沒有第 {idx} 張圖(最近的往前數只有 {} 張)。", pics.len()), ToolStatus::Failed, None), - Some(p) => match crate::providers::describe_fresh(p, &ask, &job.req, cancel) { - Some((d, model)) => finish(history, &format!("「{model}」重新看過這張圖,針對你的問題回報:\n{d}"), ToolStatus::Done, None), - None => finish(history, "沒看完:帳號裡沒有看得懂圖片的模型可用(或它們都失敗了,稍後再試)。", ToolStatus::Failed, None), - }, - } - return Flow::Next; - } - if appctl::is_app_tool(&call.name) { - // App actions run on the window's side, which also asks for deletions. - 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))); - } - } - finish(history, &output, if ok { ToolStatus::Done } else if denied { ToolStatus::Denied } else { ToolStatus::Failed }, None); - return Flow::Next; - } - // The person's own recording, shown back to the bot: nothing to ask. - if call.name == "view_demo_step" { - started(); - let (output, ok, img) = crate::teach::view_step(&job.demos, &call.args); - finish(history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img); - return 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. - if call.name == "browser_wait" && tools::args_of(&call.args)["after_send"].as_bool() == Some(true) { - 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 }; - finish(history, &said, ToolStatus::Done, None); - return 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). - if let Some(why) = untrusted_refusal(job, &call.name) { - finish(history, why, ToolStatus::Denied, None); - return Flow::Next; - } - // 已送帳本: what this brain saw go out, by account — read here, not on a page. - if call.name == crate::browser::SENT_LOG { - 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); - finish(history, &text, ToolStatus::Done, None); - return 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). - let at = web::is_web_tool(&call.name).then(|| browser_place(job, &call.name, &call.args)); - // The step names a computer with no browser there: say so, don't run it elsewhere. - if let Some(Err(e)) = at { - finish(history, &e, ToolStatus::Failed, None); - return Flow::Next; - } - if let Some(Ok((place, on))) = at.filter(|r| r.as_ref().map(|(place, _)| call.name == "web_fetch" || bots_browser(place, &call.name, &call.args)).unwrap_or(false)) { - // 上傳: 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) { - finish(history, "被安全規則擋下:禁止在瀏覽器開啟雲端中繼資料(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 { - finish(history, "被安全規則擋下:「在這台電腦上執行」已鎖定,不能開啟本機或內部網路位址。", ToolStatus::Denied, None); - return Flow::Next; - } - let direct = job.direct.load(Ordering::Relaxed); - let grant = "browser:private".to_string(); - if !direct && !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(grants, g), - ApprovalAnswer::Reject => { - finish(history, "使用者拒絕了開啟這個內部網址。", 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, grants) { - Decision::Allow if !direct && !(*tools_on && *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(grants, g); - None - } - ApprovalAnswer::Reject => Some("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string()), - } - } - }; - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - if let Some(output) = refused { - finish(history, &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)) { - finish(history, "被安全規則擋下:這個檔案是私密或系統檔案,Bot 不能上傳。", ToolStatus::Denied, None); - return Flow::Next; - } - let direct = job.direct.load(Ordering::Relaxed); - let grant = format!("upload-device:{on}"); - if !direct && !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(grants, g), - ApprovalAnswer::Reject => { - finish(history, "使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", 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) => { - finish(history, &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) { - 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, history, sent_count.get(), cancel, &|name: &str, args: &str| run_there(name, &with_job(args, &browsers.job))) { - Gate::Refuse(text) => { - finish(history, &text, ToolStatus::Denied, None); - return Flow::Next; - } - g => g, - }; - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - 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(); - 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, &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, &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}") }; - finish(history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img); - return Flow::Next; - } - let is_web = web::is_web_tool(&call.name); - let is_screen = computer::is_computer_tool(&call.name); - let is_mac = crate::macapps::is_mac_tool(&call.name); - let what = if is_mac { - format!("{} {}", crate::macapps::label(&call.name), crate::macapps::describe(&call.name, &call.args)) - } else if is_screen { - // 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(history, r)).map(|e| format!("({e})")).unwrap_or_default(); - format!("{} {}{named}", computer::label(&call.name), computer::describe(&call.name, &call.args)) - } else if is_web { - web::describe(&call.name, &call.args) - } else { - tools::describe(&call.name, &call.args) - }; - // Ask the person right away (a pop-up), and wait for the answer. - let ask_person = |kind: ApprovalKind, reason: String, grant: String| -> ApprovalAnswer { - 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, grant, reply: atx, kind })); - wait_answer(arx, cancel, said_no) - }; - // 需要處理 (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. - if call.name == tools::HANDOFF_TOOL { - 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), - } - } - }; - finish(history, &output, status, None); - return Flow::Next; - } - // 完整結果: part of a long result kept whole (outputs.rs). - if call.name == crate::outputs::TOOL { - let (output, ok) = crate::outputs::run(&call.args); - finish(history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None); - return 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. - if call.name == crate::plan::SUBMIT_TOOL { - 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); - *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) => { - *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 + *plan_changes) }; - (out, ToolStatus::Done) - } - } - } - }; - finish(history, &output, status, None); - return Flow::Next; - } - // 計畫: where it is in the approved plan (the line above the input follows it). - if call.name == crate::plan::UPDATE_TOOL { - 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), - }; - finish(history, &output, status, None); - return 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. - if call.name == crate::ask::TOOL { - 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), - } - } - }; - finish(history, &output, status, None); - return Flow::Next; - } - // 生活卡片: drawn by the window from the call itself. - if call.name == "show_card" { - finish(history, "卡片已顯示給使用者。", ToolStatus::Done, None); - return Flow::Next; - } - // 表情回應: an emoji on the person's latest message (no words needed). - if call.name == "react" { - let emoji: String = tools::args_of(&call.args)["emoji"].as_str().unwrap_or("👍").chars().take(4).collect(); - send(StreamEvent::React(emoji.clone())); - finish(history, &format!("已在使用者的訊息上按了 {emoji}。"), ToolStatus::Done, None); - return 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.) - if call.name == "send_file" || call.name == "open_for_person" || call.name == "send_to_device" { - 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, grants) { - // Using this computer is switched off: its files are asked for one by one. - Decision::Allow if local && !direct && !(*tools_on && *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 ask_person(ApprovalKind::Action, format!("{reason}\n(在 {} 上)", t.name), grant) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => None, - ApprovalAnswer::Always(g) => { - keep_grant(grants, g); - None - } - ApprovalAnswer::Reject => Some(("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string(), ToolStatus::Denied)), - }, - } - }; - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - if let Some((output, status)) = refused { - finish(history, &output, status, None); - return 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. - if call.name == "send_file" || call.name == "send_to_device" { - 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 = 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) => finish(history, &out, ToolStatus::Done, None), - Err(e) => finish(history, &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), - }; - finish(history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None); - return Flow::Next; - } - // 檔案預覽 / Bot 做的頁面: open what the bot made on the person's screen. - if call.name == "open_for_person" { - 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), - }; - finish(history, &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), - }; - finish(history, &output, if ok { ToolStatus::Done } else { ToolStatus::Failed }, None); - return Flow::Next; - } - // 打電話、傳簡訊、在 X 發文: speaks for the person, so asked every single time - // (like the original's send tools; no "always"). - if crate::phone::is_phone_tool(&call.name) { - let what = crate::phone::describe(&call.name, &call.args); - let answer = 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 { - started(); - match crate::phone::run(&call.name, &call.args) { - (t, true) => (t, ToolStatus::Done), - (t, false) => (t, ToolStatus::Failed), - } - }; - finish(history, &output, status, None); - return Flow::Next; - } - // 發布網站: put a page or folder the bot made on the web (asked once per site name). - if call.name == "publish_site" { - 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 { - finish(history, &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 && grants.contains(&grant); - if !allowed { - let from = if outside { "(在工作資料夾以外)" } else { "" }; - match ask_person(ApprovalKind::Action, format!("把 {path}{from} 發布成公開網站「{name}」(任何知道網址的人都看得到)"), grant.clone()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true, - ApprovalAnswer::Always(g) => { - keep_grant(grants, g); - allowed = true; - } - ApprovalAnswer::Reject => {} - } - } - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - let (output, status) = if !allowed { - ("使用者沒有允許發布。".to_string(), ToolStatus::Denied) - } else { - started(); - let mut box_tmp: Option = 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), - } - }; - finish(history, &output, status, None); - return 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 允許一次 / 拒絕). - if call.name == crate::vault::LIST_TOOL { - let output = crate::vault::list_for_bot(&call.args); - finish(history, &output, ToolStatus::Done, None); - return Flow::Next; - } - if call.name == crate::vault::TOOL || call.name == crate::vault::CARD_TOOL || call.name == crate::vault::CONTACT_TOOL { - enum Plan { - Login(Box), - 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) { - finish(history, &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) => { - finish(history, &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 = 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() && grants.contains(&grant); - let mut remember_site = false; - if !allowed { - match ask_person(ApprovalKind::Action, question, grant.clone()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true, - ApprovalAnswer::Always(g) => { - keep_grant(grants, g); - allowed = true; - remember_site = true; - } - ApprovalAnswer::Reject => {} - } - } - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - if !allowed { - ("使用者沒有允許使用保險庫的這個項目。請改問使用者。".to_string(), ToolStatus::Denied) - } else { - 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), - } - } - } - }; - finish(history, &output, status, None); - return Flow::Next; - } - // Connectors with many tools: finding one is only a look at their list. - if call.name == crate::mcp::FIND_TOOL { - if !job.req.tools.iter().any(|t| t["name"].as_str() == Some(crate::mcp::FIND_TOOL)) { - finish(history, "這個回合沒有提供連接器工具。", ToolStatus::Denied, None); - return Flow::Next; - } - started(); - let out = crate::mcp::find(&call.args); - finish(history, &out, ToolStatus::Done, None); - return 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. - let mcp_step = 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) }; - if let Some(step) = mcp_step { - 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)) { - finish(history, "這個回合沒有提供連接器工具。", ToolStatus::Denied, None); - return Flow::Next; - } - let (mcp_name, mcp_args) = match step { - Ok(x) => x, - Err(e) => { - finish(history, &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) || grants.contains(&grant); - if !allowed { - match ask_person(ApprovalKind::Action, format!("使用連接器「{server}」的工具:{tool} {args_short}"), grant.clone()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => allowed = true, - ApprovalAnswer::Always(g) => { - keep_grant(grants, g); - allowed = true; - } - ApprovalAnswer::Reject => {} - } - } - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - let (output, status, img) = if allowed { - 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) - }; - finish(history, &output, status, img); - return Flow::Next; - } - // 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 { - 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::>().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 { - *tools_on = true; - *local_on = true; - } - if let Ok(t) = &target { - if !*tools_on && !*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 ask_person(ApprovalKind::EnableTools, reason, "tools:on".into()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => { - *tools_once = true; - said_yes = true; - } - ApprovalAnswer::Always(_) => { - *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 { .. }) && !*local_on && !*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 ask_person(ApprovalKind::EnableThisComputer, reason, "local:on".into()) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => { - *local_once = true; - said_yes = true; - } - ApprovalAnswer::Always(_) => { - *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), 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, 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 (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 && 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, 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 ask_person(ApprovalKind::Action, reason, grant) { - ApprovalAnswer::Once | ApprovalAnswer::Answered(_) => Ok(()), - ApprovalAnswer::Always(g) => { - keep_grant(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)) => { - 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 = 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)); - } - } - } - finish(history, &output, status, image); - if cancel.load(Ordering::Relaxed) { - return Flow::End; - } - Flow::Next + let tool = steps::tool_for(&s); + log::debug!("{} 由 {} 處理", s.call.name, tool.name()); + tool.run(&mut s) } pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc, ctx: eframe::egui::Context) { @@ -5746,6 +4463,50 @@ echo 'done送出了' > done.html; (setsid pyt let _ = std::fs::remove_dir_all(&w); } + /// M7: each kind of call goes to its tool, in the list's order; the refusals sit where they + /// did (a stranger's turn can't use the browser, but web_fetch still reads a public page); + /// what no tool takes runs on a computer. + #[test] + fn each_call_finds_its_tool() { + use std::cell::{Cell, RefCell}; + let names: Vec<&str> = steps::TOOLS.iter().map(|t| t.name()).collect(); + assert_eq!(names.last(), Some(&"OnComputer")); + assert_eq!(names.iter().collect::>().len(), names.len(), "{names:?}"); + let pos = |n: &str| names.iter().position(|x| *x == n).unwrap(); + assert!(pos("Lacking") < pos("AppTool") && pos("Untrusted") < pos("SentLog") && pos("Untrusted") > pos("WaitAfterSend")); + let which = |job: &Job, name: &str, args: serde_json::Value| -> &'static str { + let (mut history, mut grants, mut browsers) = (vec![], vec![], UsedBrowsers::new("t", 1, false)); + let (mut b1, mut b2, mut b3, mut b4, mut changes, mut replay, mut plan_go) = (false, false, false, false, 0u32, None, None); + let (said_no, refused, trouble, sent, runs) = (Cell::new(false), RefCell::new(vec![]), Cell::new(false), Cell::new(0), RefCell::new(vec![])); + let (at, s1, s2, limit, last) = (Cell::new(None), Cell::new(String::new()), Cell::new(String::new()), RefCell::new(None), Cell::new(None)); + let (hooks, base, moved, cancel) = (crate::hooks::Hooks::default(), serde_json::Value::Null, std::collections::HashMap::new(), Arc::new(AtomicBool::new(false))); + let send = |_: StreamEvent| {}; + let s = steps::Step { + job, bot_id: 1, send: &send, cancel: &cancel, history: &mut history, grants: &mut grants, said_no: &said_no, refused: &refused, trouble: &trouble, + tools_on: &mut b1, local_on: &mut b2, tools_once: &mut b3, local_once: &mut b4, browsers: &mut browsers, sent_count: &sent, hooks: &hooks, hook_base: &base, + runs: &runs, step_sent_at: &at, step_sent: &s1, step_note: &s2, skill_limit: &limit, plan_changes: &mut changes, last_sent: &last, replay: &mut replay, + plan_go: &mut plan_go, moved: &moved, call: ToolCall { id: "c".into(), name: name.into(), args: args.to_string(), status: ToolStatus::Running }, + refused_key: String::new(), repeat_note: String::new(), hook_word: Default::default(), browser: Default::default(), + }; + steps::tool_for(&s).name() + }; + let job = test_job(); + assert_eq!(which(&job, computer::TOOL, serde_json::json!({})), "BadAction"); + assert_eq!(which(&job, "look_image", serde_json::json!({"index": 0})), "LookImage"); + assert_eq!(which(&job, "use_skill", serde_json::json!({"name": "x"})), "AppTool"); + assert_eq!(which(&job, crate::ask::TOOL, serde_json::json!({})), "AskCard"); + assert_eq!(which(&job, crate::outputs::TOOL, serde_json::json!({})), "KeptResult"); + assert_eq!(which(&job, "send_to_device", serde_json::json!({})), "SendFile"); + assert_eq!(which(&job, "web_fetch", serde_json::json!({"url": "https://example.com"})), "InBotsBrowser"); + assert_eq!(which(&job, "mcp__gitlab__get_issue", serde_json::json!({})), "Connector"); + assert_eq!(which(&job, "shell", serde_json::json!({"command": "ls"})), "OnComputer"); + let stranger = Job { untrusted: true, ..test_job() }; + assert_eq!(which(&stranger, "browser_open", serde_json::json!({"url": "https://example.com"})), "Untrusted"); + assert_eq!(which(&stranger, "web_fetch", serde_json::json!({"url": "https://example.com"})), "InBotsBrowser"); + let lacking = Job { lacks: vec!["admin".into()], ..test_job() }; + assert_eq!(which(&lacking, "create_bot", serde_json::json!({})), "Lacking"); + } + #[test] fn a_verdict_is_clear_or_the_review_failed() { assert!(matches!(parse_verdict(r#"{"verdict":"ask","rule":"刪除前先問"}"#), ReviewVerdict::Ask(r) if r == "刪除前先問")); diff --git a/src/agent/steps.rs b/src/agent/steps.rs new file mode 100644 index 0000000..d6bf9c1 --- /dev/null +++ b/src/agent/steps.rs @@ -0,0 +1,1901 @@ +//! 一步裡的一個工具呼叫 (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, + pub history: &'a mut Vec, + pub grants: &'a mut Vec, + pub said_no: &'a std::cell::Cell, + pub refused: &'a std::cell::RefCell>, + pub trouble: &'a std::cell::Cell, + 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, + pub hooks: &'a crate::hooks::Hooks, + pub hook_base: &'a serde_json::Value, + pub runs: &'a std::cell::RefCell>, + pub step_sent_at: &'a std::cell::Cell>, + pub step_sent: &'a std::cell::Cell, + pub step_note: &'a std::cell::Cell, + pub skill_limit: &'a std::cell::RefCell)>>, + pub plan_changes: &'a mut u32, + pub last_sent: &'a std::cell::Cell>, + pub replay: &'a mut Option, + pub plan_go: &'a mut Option>, + pub moved: &'a std::collections::HashMap, + /// 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>>, +} + +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) { + 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)> { + 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> { + 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 = 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 = 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) { + 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 = 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 = 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), + 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 { + 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::>().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 { + 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 +}