diff --git a/FEATURES.md b/FEATURES.md index ffe8bc4..6e28b5e 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1534,11 +1534,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### Hooks(自己的程式插在 Bot 做事的固定時間點) - 格式跟 Claude Code 的 hooks 一樣,寫給它的 hook 直接能用:`{"hooks": {"PreToolUse": [{"matcher": "shell|Bash", "hooks": [{"type": "command", "command": "~/bin/check.sh", "timeout": 30}]}]}}`。hook 是一條指令(事件用 JSON 從它的輸入給它)或 `{"type": "http", "url": "…", "headers": {…}}`(事件 POST 過去,回 JSON)。matcher 是工具名字的正規表示式,AnyBot 的名字和 Claude Code 的都認(shell=Bash、edit_file=Edit/Write、read_file=Read…),空白或 * 是全部;給 hook 的參數同時有 AnyBot 和 Claude Code 的欄位名(path/file_path…)。 -- 放哪裡:使用者的在資料夾的 hooks/hooks.json;管理員的在 /Library/Application Support/AnyBot/hooks.json(Mac,MDM 可以推)、/etc/anybot/hooks.json(Linux)、%ProgramData%\AnyBot\hooks.json(Windows),先跑,AnyBot 裡改不了。每一輪開始時重讀,改了下一輪就生效。 +- 放哪裡:使用者的在資料夾的 hooks/hooks.json;管理員的在 /Library/Application Support/AnyBot/hooks.json(Mac,MDM 可以推)、/etc/anybot/hooks.json(Linux)、%ProgramData%\AnyBot\hooks.json(Windows),AnyBot 裡改不了;它們最後跑,看得到你的 hook 改過的參數,它們的拒絕算數(deny 贏過 ask 贏過 allow)。每一輪開始時重讀,改了下一輪就生效。 - 事件: - **SessionStart**:一個對話的第一輪開始前。印出的字(或 additionalContext)補進這一輪給模型的資訊。 - **UserPromptSubmit**:每一輪開始前(有使用者說的話 prompt)。印出的字補進資訊;exit 2 或 decision: block 就不做這一輪,聊天裡說「被 hook 擋下,這一輪沒有做:…」。 - - **PreToolUse**:每一步執行前(tool_name、tool_input)。exit 2、decision: block 或 permissionDecision: deny:不執行,Bot 讀到「使用者設定的 hook 擋下了這一步。它說:…」;updatedInput:照改過的參數做;ask:一定先問你(卡片寫 hook 的原因);allow:本來要問的就不問——但擋不過 AnyBot 的安全規則,也省不掉付款/傳送/刪除、寄信、傳訊息這類每次都問的。 + - **PreToolUse**:每一步執行前(tool_name、tool_input)。exit 2、decision: block 或 permissionDecision: deny:不執行,Bot 讀到「使用者設定的 hook 擋下了這一步。它說:…」;updatedInput:照改過的參數做;ask:一定先問你(卡片寫 hook 的原因),連接器、App 操作、傳檔案這些不在電腦上跑的步驟也一樣;allow:本來要問的就不問——但擋不過 AnyBot 的安全規則,也省不掉付款/傳送/刪除、寄信、傳訊息這類每次都問的。 - **PostToolUse**:一步順利做完後(加上 tool_response)。updatedToolOutput 換掉 Bot 讀到的結果;additionalContext 或 decision: block 的 reason 接在結果後面「【使用者的 hook】…」。 - **Stop**:Bot 要結束這一輪前(stop_hook_active、last_assistant_message)。decision: block 就叫它照 reason 接著做,一輪最多 3 次;第二次起 stop_hook_active 是 true,hook 可以用它放行。 - **Notification**:AnyBot 通知你的時候(title、message),在背景跑,不等它。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index 8dcf508..05c2637 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -44,7 +44,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。 - 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。 - 手機:一樣的卡片和 設定 › 權限([phone](phone.md))。 -- Hooks:資料夾的 hooks/hooks.json(使用者的);管理員的放 /Library/Application Support/AnyBot/hooks.json(Mac)、/etc/anybot/hooks.json、%ProgramData%\AnyBot\hooks.json,先跑、AnyBot 裡改不了。/doctor 寫有幾個 hook、檔案看不看得懂。 +- Hooks:資料夾的 hooks/hooks.json(使用者的);管理員的放 /Library/Application Support/AnyBot/hooks.json(Mac)、/etc/anybot/hooks.json、%ProgramData%\AnyBot\hooks.json,最後跑(看得到你的 hook 改過的參數)、AnyBot 裡改不了。/doctor 寫有幾個 hook、檔案看不看得懂。 ## 怎麼操作 diff --git a/src/agent/steps.rs b/src/agent/steps.rs index d6bf9c1..ae2c5db 100644 --- a/src/agent/steps.rs +++ b/src/agent/steps.rs @@ -393,7 +393,10 @@ impl TurnTool for AppTool { } 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()) { + // (Found the way the app finds it: its name, else a name that has these words. The + // first skill's limit stays: one loaded after it can't widen it.) + let found = job.skills.iter().find(|k| k.name.to_lowercase() == want).or_else(|| job.skills.iter().find(|k| !want.is_empty() && k.name.to_lowercase().contains(&want))); + if let Some(k) = found.filter(|k| !k.allowed_tools.is_empty() && skill_limit.borrow().is_none()) { *skill_limit.borrow_mut() = Some((k.name.clone(), crate::skills::tool_rules(k))); } } diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index d20f8bd..3372638 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -497,7 +497,12 @@ impl App { match &change { crate::mcp::Change::Update { after, .. } => self.mcp_reconnect(&after.name), crate::mcp::Change::Reconnect(n) => self.mcp_reconnect(n), - crate::mcp::Change::Remove(s) => crate::mcp::forget(&s.name), + crate::mcp::Change::Remove(s) => { + crate::mcp::forget(&s.name); + let _ = crate::mcp_oauth::logout(&s.name); + } + // (Logged out: the link that still carries the token goes too.) + crate::mcp::Change::Logout(n) => self.mcp_reconnect(n), _ => {} } self.ch.mcp_errors.lock().unwrap().retain(|e| Some(&e.0) != waits.as_ref()); @@ -682,11 +687,14 @@ impl App { } self.ch.mcp_open = open_next; if let Some(i) = remove { - self.state.mcp_servers.remove(i); + let gone = self.state.mcp_servers.remove(i); + let _ = crate::mcp_oauth::logout(&gone.name); } if let Some((name, url)) = login { let note = self.ch.note.clone(); std::thread::spawn(move || match crate::mcp_oauth::start(&name, &url) { + // (Windows' `start` reads & in an address as the end of it: the address is shown instead.) + Ok(u) if cfg!(windows) => *note.lock().unwrap() = format!("在瀏覽器打開這個網址登入「{name}」:{u}"), Ok(u) => { let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&u)); } diff --git a/src/app/commands.rs b/src/app/commands.rs index e622a27..9a9dccf 100644 --- a/src/app/commands.rs +++ b/src/app/commands.rs @@ -74,7 +74,7 @@ impl App { /// marked `context: fork` (技能帶參數, M4), which goes to a 支線 as it was typed. pub(super) fn command_for(&self, bot_id: u64, text: &str) -> Option { app_command(text).or_else(|| { - let b = self.state.bot(bot_id)?; + let b = self.state.bot(bot_id).filter(|b| b.members.is_empty())?; let mine = crate::profile::skills_of(b, &self.state.skills); crate::memory::named_skill(text, &mine).filter(|k| k.fork).map(|_| AppCommand::Btw(text.trim().to_string())) }) @@ -120,7 +120,7 @@ impl App { /// first (index in the chat, its time, its words). fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> { let Some(b) = self.state.bot(bot_id) else { return vec![] }; - b.messages.iter().enumerate().rev().filter(|(_, m)| m.role == Role::User && !m.note && m.at > 0).take(REWIND_POINTS).map(|(i, m)| (i, m.at, m.text.clone())).collect() + b.messages.iter().enumerate().rev().filter(|(_, m)| m.role == Role::User && !m.note && !m.wake && m.at > 0).take(REWIND_POINTS).map(|(i, m)| (i, m.at, m.text.clone())).collect() } /// 「/rewind」 (the points) or 「/rewind N [檔案|對話]」 (back to one). @@ -130,6 +130,8 @@ impl App { let kept = crate::checkpoint::entries(bot_id); let Some(b) = self.state.bot(bot_id) else { return }; let name = b.name.clone(); + // (This conversation's turns only: up to its newest message.) + let until = b.messages.iter().map(|m| m.at).max().unwrap_or(0); let (n, files, chat) = match r { Rewind::List => { if points.is_empty() { @@ -139,7 +141,7 @@ impl App { let now = crate::model::now_ms(); let mut text = format!("可以退回的點(最新的在最上面):退回去會把那句話之後 {name} 用 edit_file 改的檔案還原;用指令(shell、git…)改的不在裡面。"); for (k, (_, at, words)) in points.iter().enumerate() { - let n = crate::checkpoint::files_since(&kept, *at).len(); + let n = crate::checkpoint::files_since(&kept, *at, until).len(); text.push_str(&format!("\n{}. {}「{}」:{}", k + 1, crate::pages::ago(*at, now), first_line(words, 30), if n == 0 { "之後沒有改過檔案".to_string() } else { format!("之後改過 {n} 個檔案") })); } text.push_str("\n打「/rewind 編號」檔案和對話都退回那句話之前;「/rewind 編號 檔案」只退檔案;「/rewind 編號 對話」只退對話。"); @@ -175,7 +177,7 @@ impl App { let repaint = self.repaint_fn(); self.goal_note(bot_id, "正在還原檔案…"); std::thread::spawn(move || { - let lines = crate::checkpoint::restore(bot_id, at); + let lines = crate::checkpoint::restore(bot_id, at, until); let text = if lines.is_empty() { "檔案:那句話之後沒有用 edit_file 改過檔案,沒有要還原的(用指令改的不在檢查點裡)。".to_string() } else { format!("檔案退回到那句話之前:\n{}", lines.iter().map(|l| format!("- {l}")).collect::>().join("\n")) }; out.lock().unwrap().push((bot_id, text)); repaint(); diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index ecb30b1..b431450 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -222,7 +222,8 @@ impl App { let target = targets.iter().find(|t| t.name == chosen).cloned(); let tools: Vec = match &target { Some(t) => crate::tools::specs_for(std::slice::from_ref(&t.name), &t.name).into_iter().chain(crate::web::specs_for(&[], "")).filter(|s| goal::JUDGE_TOOLS.contains(&s["name"].as_str().unwrap_or(""))).collect(), - None => vec![], + // (No computer to look at: public pages still.) + None => crate::web::specs_for(&[], "").into_iter().filter(|s| s["name"].as_str() == Some("web_fetch")).collect(), }; let own = ChatRequest { tools, ..own }; // A model of another family when the person has one: a bot's own model grades its own @@ -285,7 +286,10 @@ impl App { b.goal = None; self.goal_note(bot_id, ¬e); self.goal_tell(bot_id, &format!("{name} {title}"), ¬e); - self.confetti = Some((bot_id, Instant::now())); + // (Met, not 「做不到」.) + if note.starts_with("目標達成") { + self.confetti = Some((bot_id, Instant::now())); + } } Next::Pause { note, title } => { self.goal_note(bot_id, ¬e); diff --git a/src/checkpoint.rs b/src/checkpoint.rs index d8f7e87..25ef2d9 100644 --- a/src/checkpoint.rs +++ b/src/checkpoint.rs @@ -44,6 +44,12 @@ fn blob(name: &str) -> PathBuf { dir().join("blobs").join(name) } +/// One at a time on a bot's list (a turn keeping a file while a rewind puts others back). +fn log_lock() -> &'static std::sync::Mutex<()> { + static L: std::sync::OnceLock> = std::sync::OnceLock::new(); + L.get_or_init(Default::default) +} + /// This bot's kept files, oldest first (a week's). pub fn entries(bot: u64) -> Vec { let since = crate::model::now_ms() - KEEP_DAYS * 86_400_000; @@ -74,6 +80,7 @@ pub fn before_edit(bot: u64, turn: i64, target: &Target, args: &str) { return; } }; + let _one = log_lock().lock().unwrap_or_else(|e| e.into_inner()); let mut list = entries(bot); if list.iter().any(|e| e.turn == turn && e.place == place && e.path == path) { return; @@ -110,9 +117,9 @@ fn keep(bytes: &[u8]) -> Result { } /// The files the turns from `turn` on changed (each file once), to show. -pub fn files_since(list: &[Entry], turn: i64) -> Vec<&Entry> { +pub fn files_since(list: &[Entry], turn: i64, until: i64) -> Vec<&Entry> { let mut seen: Vec<&Entry> = vec![]; - for e in list.iter().filter(|e| e.turn >= turn) { + for e in list.iter().filter(|e| e.turn >= turn && e.turn <= until) { if !seen.iter().any(|s| s.place == e.place && s.path == e.path) { seen.push(e); } @@ -123,9 +130,12 @@ pub fn files_since(list: &[Entry], turn: i64) -> Vec<&Entry> { /// Put back every file the turns from `turn` on changed, as it was before them (newest change /// undone first, so each file ends as it was before the first). Those entries are used up. /// One line per file. -pub fn restore(bot: u64, turn: i64) -> Vec { +/// Only this conversation's (turns up to `until`, its newest message): another conversation +/// of the same bot keeps its own. One that couldn't be put back is kept, to try again. +pub fn restore(bot: u64, turn: i64, until: i64) -> Vec { + let _one = log_lock().lock().unwrap_or_else(|e| e.into_inner()); let list = entries(bot); - let (undo, keep_list): (Vec, Vec) = list.into_iter().partition(|e| e.turn >= turn); + let (undo, mut keep_list): (Vec, Vec) = list.into_iter().partition(|e| e.turn >= turn && e.turn <= until); let mut lines: Vec<(String, String)> = vec![]; for e in undo.iter().rev() { let what = if e.computer.is_empty() { e.path.clone() } else { format!("{}({})", e.path, e.computer) }; @@ -141,9 +151,15 @@ pub fn restore(bot: u64, turn: i64) -> Vec { lines.retain(|l| l.0 != what); lines.push((what.clone(), match r { Ok(word) => format!("{what}:{word}"), - Err(err) => format!("{what}:沒有還原,{err}"), + Err(err) => { + if !e.too_big { + keep_list.push(e.clone()); + } + format!("{what}:沒有還原,{err}") + } })); } + keep_list.sort_by_key(|e| e.at); if let Err(e) = write_all(bot, &keep_list) { log::warn!("檢查點:寫不進紀錄:{e}"); } @@ -229,16 +245,17 @@ mod tests { edit(200, "b.txt", "b1"); edit(200, "a.txt", "a3"); assert_eq!(entries(bot).len(), 4); - assert_eq!(files_since(&entries(bot), 100).len(), 3); - assert_eq!(files_since(&entries(bot), 200).len(), 2); + assert_eq!(files_since(&entries(bot), 100, i64::MAX).len(), 3); + assert_eq!(files_since(&entries(bot), 100, 150).len(), 2, "another conversation's later turn isn't this one's"); + assert_eq!(files_since(&entries(bot), 200, i64::MAX).len(), 2); // Back to the second turn: b and a as they were before it. - let lines = restore(bot, 200); + let lines = restore(bot, 200, i64::MAX); assert_eq!(lines.len(), 2, "{lines:?}"); assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a2"); assert_eq!(std::fs::read_to_string(w.join("b.txt")).unwrap(), "b0"); assert_eq!(std::fs::read_to_string(w.join("new.txt")).unwrap(), "n1"); // Then to the first: everything as it was, the new file gone. - let lines = restore(bot, 100); + let lines = restore(bot, 100, i64::MAX); assert!(lines.iter().any(|l| l.contains("new.txt") && l.contains("刪掉了")), "{lines:?}"); assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a0"); assert!(!w.join("new.txt").exists()); @@ -246,7 +263,7 @@ mod tests { // Too big to keep: said, not pretended. std::fs::write(w.join("big.bin"), vec![b'x'; MAX_FILE_BYTES + 1]).unwrap(); edit(300, "big.bin", "small"); - assert!(restore(bot, 300)[0].contains("太大")); + assert!(restore(bot, 300, i64::MAX)[0].contains("太大")); let _ = std::fs::remove_file(log_of(bot)); let _ = std::fs::remove_dir_all(&w); } diff --git a/src/gate.rs b/src/gate.rs index e46c71b..e82b3b0 100644 --- a/src/gate.rs +++ b/src/gate.rs @@ -256,7 +256,8 @@ fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) "file" if matches!(name, "read_file" | "edit_file" | "list_dir" | "search" | "write_file") => { let path = s("path"); let home = |p: &str| tools::expand_home(p).display().to_string(); - !path.is_empty() && (glob(inner, &path, true) || glob(&home(inner), &home(&path), true)) + // (A path that climbs out with `..` is not "under" anything a rule names.) + !path.is_empty() && !path.split(['/', '\\']).any(|c| c == "..") && (glob(inner, &path, true) || glob(&home(inner), &home(&path), true)) } "connector" => { let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() }; diff --git a/src/goal.rs b/src/goal.rs index 0bde03d..44d5984 100644 --- a/src/goal.rs +++ b/src/goal.rs @@ -78,6 +78,8 @@ impl Goal { pub fn resume(&mut self) { self.paused.clear(); self.idle = 0; + // (The person spoke: the next check isn't held against the one before the pause.) + self.reason.clear(); if self.turns >= self.until { self.until = self.turns + TURNS; } @@ -155,6 +157,11 @@ pub fn same_reason(a: &str, b: &str) -> bool { let c: Vec = s.chars().filter(|c| !c.is_whitespace() && !c.is_ascii_punctuation() && !",。、;:「」()!?".contains(*c)).collect(); c.windows(2).map(|w| (w[0], w[1])).collect::>() }; + // (Numbers that moved are progress — 「還差 7 則」 then 「還差 6 則」 — not the same gap.) + let numbers = |s: &str| s.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).map(String::from).collect::>(); + if numbers(a) != numbers(b) { + return false; + } let (x, y) = (pairs(a), pairs(b)); if x.is_empty() || y.is_empty() { return false; @@ -376,6 +383,7 @@ mod tests { assert!(same_reason("還差 2 個測試失敗:goal::tests 的時間格式", "還差2個測試失敗(goal::tests 的時間格式)")); assert!(!same_reason("還差 2 個測試失敗", "clippy 還有新的警告")); assert!(!same_reason("", "x")); + assert!(!same_reason("目前只成功送出 3 則貼文,目標是 10 則,還差 7 則;下一步繼續發下一則。", "目前只成功送出 4 則貼文,目標是 10 則,還差 6 則;下一步繼續發下一則。")); let mut g = Goal::new("所有測試都通過", 0); assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::NotYet, "還差 2 個測試失敗:時間格式".into()), 1), Next::Again { .. })); assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::NotYet, "clippy 還有新的警告".into()), 2), Next::Again { .. }), "a different gap: on"); diff --git a/src/mcp.rs b/src/mcp.rs index 608a418..1405ad3 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -316,6 +316,7 @@ impl Live { self.oauth = Some(name); return again; } + self.oauth = Some(name.clone()); return Err(format!("「{name}」的登入過期了:重新登入(在聊天裡請 Bot 用 manage_connectors 的 login,或 設定 › 整合 › 連接器 按「登入」)。")); } } @@ -392,7 +393,7 @@ fn connect(config: &Server) -> Result { let mut headers = s.headers.clone(); // 連接器登入: logged in with OAuth (and no key of its own given): its token. if !headers.keys().any(|k| k.eq_ignore_ascii_case("authorization")) { - if let Some(t) = crate::mcp_oauth::bearer(&s.name) { + if let Some(t) = crate::mcp_oauth::bearer(&s.name, u) { headers.insert("Authorization".into(), format!("Bearer {t}")); oauth = Some(s.name.clone()); } diff --git a/src/mcp_oauth.rs b/src/mcp_oauth.rs index 81b4f2a..d612618 100644 --- a/src/mcp_oauth.rs +++ b/src/mcp_oauth.rs @@ -39,6 +39,9 @@ pub struct Tokens { pub client_secret: String, #[serde(default)] pub resource: String, + /// The connector's address when it was logged in: the token goes nowhere else. + #[serde(default)] + pub url: String, } fn file() -> std::path::PathBuf { @@ -57,12 +60,17 @@ fn read_all() -> HashMap { for t in o.values_mut() { for k in ["access", "refresh", "client_secret"] { if let Some(s) = t[k].as_str().filter(|s| s.starts_with("sealed:")).map(String::from) { - t[k] = json!(crate::vault_store::open_text(&s).unwrap_or_default()); + // (One that can't be opened now — the keychain is locked — stays sealed: + // it isn't used, and saving another connector's doesn't empty it.) + if let Some(plain) = crate::vault_store::open_text(&s) { + t[k] = json!(plain); + } } } } } - serde_json::from_value(v).unwrap_or_default() + // (Each on its own: one entry that can't be read doesn't lose the others.) + v.as_object().map(|o| o.iter().filter_map(|(k, t)| serde_json::from_value::(t.clone()).ok().map(|t| (k.clone(), t))).collect()).unwrap_or_default() } fn write_all(all: &HashMap) -> Result<(), String> { @@ -92,7 +100,7 @@ fn write_all(all: &HashMap) -> Result<(), String> { /// This connector's tokens, if it is logged in. pub fn tokens(server: &str) -> Option { let _g = store().lock().unwrap_or_else(|e| e.into_inner()); - read_all().remove(server).filter(|t| !t.access.is_empty()) + read_all().remove(server).filter(|t| !t.access.is_empty() && !t.access.starts_with("sealed:")) } fn save(server: &str, t: Option) -> Result<(), String> { @@ -111,8 +119,9 @@ pub fn logout(server: &str) -> Result<(), String> { } /// The access token to send, renewed first when it is about to end. -pub fn bearer(server: &str) -> Option { - let t = tokens(server)?; +pub fn bearer(server: &str, url: &str) -> Option { + // (A connector renamed onto, or pointed at, another address doesn't get this one's token.) + let t = tokens(server).filter(|t| t.url.trim_end_matches('/') == url.trim().trim_end_matches('/'))?; if t.expires_at > 0 && t.expires_at - 60_000 < crate::model::now_ms() && !t.refresh.is_empty() { return renew(server).ok().or(Some(t.access)); } @@ -185,7 +194,17 @@ fn query_pairs(q: &str) -> HashMap { q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (dec(k), dec(v))).collect() } +/// An address a connector (or its login server) named: a web address, and not one the safety +/// rules keep every browser and connector from (cloud metadata, Docker's own). +fn allowed(url: &str) -> Result<(), String> { + if !(url.starts_with("https://") || url.starts_with("http://")) || crate::web::is_forbidden_browser_url(url) { + return Err(format!("這個連接器給的登入位址不能用:{}", url.chars().take(120).collect::())); + } + Ok(()) +} + fn get_json(url: &str) -> Result { + allowed(url)?; let mut resp = crate::net::agent(HTTP_SECS).get(url).header("Accept", "application/json").call().map_err(|e| format!("連不上 {url}:{e}"))?; if !(200..300).contains(&resp.status().as_u16()) { return Err(format!("{url} 回 HTTP {}", resp.status().as_u16())); @@ -195,6 +214,7 @@ fn get_json(url: &str) -> Result { } fn post_form(url: &str, form: &[(&str, String)]) -> Result { + allowed(url)?; let body: String = form.iter().map(|(k, v)| format!("{}={}", enc(k), enc(v))).collect::>().join("&"); let mut resp = crate::net::agent(HTTP_SECS).post(url).header("Content-Type", "application/x-www-form-urlencoded").header("Accept", "application/json").send(body.as_bytes()).map_err(|e| format!("連不上 {url}:{e}"))?; let status = resp.status().as_u16(); @@ -256,7 +276,8 @@ pub fn discover(mcp_url: &str) -> Result { tries.push(format!("{o}/.well-known/oauth-protected-resource")); let prm = tries.iter().find_map(|u| get_json(u).ok()); let issuer = prm.as_ref().and_then(|m| m["authorization_servers"][0].as_str().map(String::from)).unwrap_or_else(|| o.clone()); - let resource = prm.as_ref().and_then(|m| m["resource"].as_str().map(String::from)).unwrap_or_else(|| mcp_url.to_string()); + // (The tokens are for this connector: a resource on another site is not taken from it.) + let resource = prm.as_ref().and_then(|m| m["resource"].as_str().map(String::from)).filter(|r| origin(r) == o).unwrap_or_else(|| mcp_url.to_string()); // The authorization server's metadata (RFC 8414, then OpenID's), path-aware. let (io, ip) = (origin(&issuer), path_of(&issuer)); let mut meta_tries = vec![]; @@ -283,12 +304,17 @@ pub fn discover(mcp_url: &str) -> Result { return Err("這個連接器的登入伺服器不支援 PKCE(S256),AnyBot 不能安全地登入它。".into()); } } - Ok(Endpoints { authorize: s("authorization_endpoint", "/authorize"), token: s("token_endpoint", "/token"), register: s("registration_endpoint", "/register"), scopes, resource }) + let e = Endpoints { authorize: s("authorization_endpoint", "/authorize"), token: s("token_endpoint", "/token"), register: s("registration_endpoint", "/register"), scopes, resource }; + for u in [&e.authorize, &e.token, &e.register] { + allowed(u)?; + } + Ok(e) } /// Register AnyBot with the authorization server (RFC 7591): its client id (and secret, if it /// gives one). fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> { + allowed(&e.register)?; let mut resp = crate::net::agent(HTTP_SECS) .post(e.register.as_str()) .header("Content-Type", "application/json") @@ -306,6 +332,7 @@ fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> { #[derive(Clone)] struct Pending { server: String, + url: String, verifier: String, redirect: String, endpoints: Endpoints, @@ -368,7 +395,7 @@ pub fn start(server: &str, mcp_url: &str) -> Result { { let mut p = pending().lock().unwrap_or_else(|e| e.into_inner()); p.retain(|_, x| x.started.elapsed() < LOGIN_WAIT && x.server != server); - p.insert(state.clone(), Pending { server: server.to_string(), verifier, redirect, endpoints, client_id, client_secret, started: Instant::now() }); + p.insert(state.clone(), Pending { server: server.to_string(), url: mcp_url.trim().to_string(), verifier, redirect, endpoints, client_id, client_secret, started: Instant::now() }); } std::thread::spawn(move || listen(listener, &state)); Ok(url) @@ -439,7 +466,7 @@ fn finish_query(query: &str) -> Result { form.push(("client_secret", p.client_secret.clone())); } let v = post_form(&p.endpoints.token, &form)?; - let base = Tokens { token_endpoint: p.endpoints.token.clone(), client_id: p.client_id.clone(), client_secret: p.client_secret.clone(), resource: p.endpoints.resource.clone(), ..Default::default() }; + let base = Tokens { token_endpoint: p.endpoints.token.clone(), client_id: p.client_id.clone(), client_secret: p.client_secret.clone(), resource: p.endpoints.resource.clone(), url: p.url.clone(), ..Default::default() }; save(&p.server, Some(tokens_from(&v, &base)?)) })(); finished().lock().unwrap_or_else(|e| e.into_inner()).push((p.server.clone(), r.clone())); @@ -589,7 +616,10 @@ pub mod tests { let mut all = read_all(); all.get_mut(&name).unwrap().expires_at = crate::model::now_ms() + 1000; write_all(&all).unwrap(); - assert_eq!(bearer(&name).as_deref(), Some("good-2")); + assert_eq!(bearer(&name, &fake.url).as_deref(), Some("good-2")); + // The connector pointed somewhere else: this token doesn't go there. + assert_eq!(bearer(&name, "https://other.example/mcp"), None); + assert!(allowed("http://169.254.169.254/latest").is_err() && allowed("smb://x/y").is_err() && allowed("https://a.example/t").is_ok()); assert_eq!(*fake.tokens_given.lock().unwrap(), 2, "one for the code, one renewal"); // The same address again: that login is used up. assert!(finish_from_url("http://127.0.0.1:1/callback?code=the-code&state=nope").is_err()); diff --git a/src/skills.rs b/src/skills.rs index 5d5eaac..cd814cc 100644 --- a/src/skills.rs +++ b/src/skills.rs @@ -262,7 +262,8 @@ pub fn parse_skill_markdown(text: &str) -> Option { while i < lines.len() { let line = lines[i]; let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') || line.starts_with(' ') || line.starts_with('\t') { + // (A list's items, indented or not, belong to the key above them.) + if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('-') || line.starts_with(' ') || line.starts_with('\t') { i += 1; continue; } @@ -274,7 +275,7 @@ pub fn parse_skill_markdown(text: &str) -> Option { let val = raw_val.trim(); // A block list under the key (`allowed-tools:` then ` - Read` lines). let list_items: Vec = if val.is_empty() { - lines[i + 1..].iter().take_while(|l| l.starts_with(' ') || l.starts_with('\t') || l.trim().is_empty()).filter_map(|l| l.trim().strip_prefix('-')).map(|x| unquote_yaml(x.trim())).filter(|x| !x.is_empty()).collect() + lines[i + 1..].iter().take_while(|l| l.starts_with(' ') || l.starts_with('\t') || l.starts_with('-') || l.trim().is_empty()).filter_map(|l| l.trim().strip_prefix('-')).map(|x| unquote_yaml(x.trim())).filter(|x| !x.is_empty()).collect() } else { vec![] }; @@ -425,7 +426,8 @@ fn split_arguments(args: &str) -> Vec { match (quote, c) { (Some(q), c) if c == q => quote = None, (Some(_), c) => cur.push(c), - (None, '"' | '\'' | '「') => { + // (Not ': 「don't stop」 has one.) + (None, '"' | '「') => { quote = Some(if c == '「' { '」' } else { c }); any = true; } @@ -526,11 +528,18 @@ pub fn tool_rules(k: &Skill) -> Vec { let inner = inner.strip_suffix(')').unwrap_or(inner).replace(":*", " *"); match kind.trim() { "Bash" | "shell" => format!("shell({inner})"), - "Read" | "Write" | "Edit" | "file" => format!("file({inner})"), - "WebFetch" | "web" => format!("web({inner})"), + // (Read(…) is for reading there, not for changing it; WebFetch(…) for + // reading that site, not for the logged-in browser: skill_allows.) + "Read" => format!("read:file({inner})"), + "Write" | "Edit" | "file" => format!("file({inner})"), + "WebFetch" => format!("fetch:web({inner})"), + "web" => format!("web({inner})"), other => format!("{other}({inner})"), } } + // (The browser and the screen are one tool each to the model, many underneath.) + None if t == "browser" => "tool(browser_*)".to_string(), + None if t == "computer" => "tool(computer_use_*)".to_string(), None => format!("tool({})", anybot_tool(t)), } }) @@ -542,7 +551,17 @@ const ALWAYS_ALLOWED: [&str; 5] = ["use_skill", "read_result", "ask_person", "su /// Whether a tool call is within a loaded skill's allowed-tools (`rules` from tool_rules). pub fn skill_allows(rules: &[String], name: &str, args: &str) -> bool { - ALWAYS_ALLOWED.contains(&name) || matches!(crate::gate::patterns(name, args, rules, &[]), crate::gate::PatternVerdict::Allow(_)) + if ALWAYS_ALLOWED.contains(&name) { + return true; + } + rules.iter().any(|r| { + let (rule, fits) = match r.split_once(':').filter(|(k, _)| matches!(*k, "read" | "fetch")) { + Some(("read", rest)) => (rest, matches!(name, "read_file" | "list_dir" | "search")), + Some((_, rest)) => (rest, name == "web_fetch"), + None => (r.as_str(), true), + }; + fits && matches!(crate::gate::patterns(name, args, &[rule.to_string()], &[]), crate::gate::PatternVerdict::Allow(_)) + }) } fn quote_yaml_if_needed(s: &str) -> String { @@ -1225,6 +1244,15 @@ mod tests { // allowed-tools as rules: Claude Code's names are AnyBot's tools. let rules = tool_rules(&k); assert_eq!(rules, ["tool(read_file)", "shell(git log *)", "shell(git tag *)"]); + // A list at the left edge, an item with a colon; Read(…) reads only, and not past `..`. + let k2 = parse_skill_markdown("---\nname: y\nallowed-tools:\n- Read(docs/**)\n- Bash(git add:*)\n- browser\n---\nhi").unwrap(); + assert_eq!(k2.allowed_tools, ["Read(docs/**)", "Bash(git add:*)", "browser"]); + let r2 = tool_rules(&k2); + let path = |p: &str| serde_json::json!({"path": p}).to_string(); + assert!(skill_allows(&r2, "read_file", &path("docs/a.md")) && !skill_allows(&r2, "edit_file", &path("docs/a.md"))); + assert!(!skill_allows(&r2, "read_file", &path("docs/../../.ssh/config"))); + assert!(skill_allows(&r2, "browser_open", "{}") && skill_allows(&r2, "shell", &serde_json::json!({"command": "git add ."}).to_string())); + assert_eq!(split_arguments("don't stop now"), ["don't", "stop", "now"]); let sh = |c: &str| serde_json::json!({"command": c}).to_string(); assert!(skill_allows(&rules, "read_file", r#"{"path":"a"}"#)); assert!(skill_allows(&rules, "shell", &sh("git log --oneline")) && skill_allows(&rules, "shell", &sh("git tag v2"))); diff --git a/src/tools.rs b/src/tools.rs index 7a25765..f8a918a 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -2538,16 +2538,23 @@ fn watch_lines(bot: u64, id: u64, shown: &str, output: &Mutex, exit: &Mu while recent.front().is_some_and(|(t, _)| now.duration_since(*t) > MONITOR_WINDOW) { recent.pop_front(); } - if recent.iter().map(|(_, n)| n).sum::() > MONITOR_MAX_LINES { - let _ = stop_terminal(id); - monitor_say(bot, format!("[監看 #{id}]`{shown}` 一下子印出太多行(10 秒內超過 {MONITOR_MAX_LINES} 行),已經停了。用 grep --line-buffered 只留要看的行,再重新監看。最後幾行:{}", head(&lines[lines.len().saturating_sub(5)..]))); - return; - } + // (Its own end first: a command that printed a lot and finished wasn't stopped.) if let Some(c) = code { let end = if c == 0 { "指令結束了".to_string() } else { format!("指令結束了(結束碼 {c})") }; monitor_say(bot, format!("[監看 #{id}]`{shown}` {end},監看也停了。{}", if lines.is_empty() { String::new() } else { format!("最後印出的:{}", head(&lines)) })); return; } + // What is kept of its output is full (4 MB): nothing new would be seen from here on. + if output.lock().unwrap_or_else(|e| e.into_inner()).len() >= 3_900_000 { + let _ = stop_terminal(id); + monitor_say(bot, format!("[監看 #{id}]`{shown}` 印出的總量太大(4 MB),監看停了。用 grep --line-buffered 只留要看的行,再重新監看。")); + return; + } + if recent.iter().map(|(_, n)| n).sum::() > MONITOR_MAX_LINES { + let _ = stop_terminal(id); + monitor_say(bot, format!("[監看 #{id}]`{shown}` 一下子印出太多行(10 秒內超過 {MONITOR_MAX_LINES} 行),已經停了。用 grep --line-buffered 只留要看的行,再重新監看。最後幾行:{}", head(&lines[lines.len().saturating_sub(5)..]))); + return; + } if lines.is_empty() { continue; }