fix: 獨立審查找到的問題(二):技能的工具限制、連接器登入、檢查點、監看、目標

技能的 allowed-tools(三個會讓限制失效的):
- 用部分名字讀技能時沒有套上限制;靠左寫的清單(- Read)和帶冒號的項目讀成空的;Read(docs/**) 連改檔也放行,而且 docs/../.. 繞得出去。
- 後讀的技能會把限制換掉(現在第一個的限制留著);browser、computer 寫了卻永遠對不上;參數裡的 ' 把後面全吃掉。
連接器登入:
- token 只認名字不認網址:改了網址或同名重加,舊 token 會送到新的地方。現在綁登入時的網址;移除就登出;登出後連線也斷。
- 連接器給的登入位址沒有檢查:可以指到雲端中繼資料、Docker 管理端點,或非網頁的位址。現在都要是網頁位址、過安全規則;resource 不能是別的網站。
- 鑰匙圈一時打不開時,存別的連接器會把其他 token 清空。
檢查點:還原失敗還是把檢查點丟掉;同一個 Bot 另一段對話改的檔案也被退;監看、例行任務的訊息被當成可以退回的點;紀錄檔沒有鎖。
監看:輸出滿 4 MB 之後就再也不叫;印很多又馬上結束的指令被說成「太多行停掉」。
目標:數字在動的進度(還差 7 → 還差 6)被當成同一個理由而暫停;使用者說繼續後,下一輪又跟暫停前比;做不到也撒彩帶;沒有電腦時評審連網頁都不能看。
其他:fork 技能在群組裡被吃掉(群組沒有支線,改在聊天裡做)。

已驗證:cargo test 613 通過(技能、連接器、檢查點、目標各補了斷言)、clippy -D warnings 乾淨。
沒修:Box/SSH 上非 UTF-8 的檔案檢查點會存壞(edit_file 本來就只處理文字);引用訊息再打指令不算指令(原本就這樣);Windows 的管理員 hook 檔位置一般使用者可能寫得進去(沒辦法在這裡驗)。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-17 14:24:12 +08:00
parent 571d07596e
commit 09d782bc32
13 changed files with 154 additions and 45 deletions

View File

@ -1534,11 +1534,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
### Hooks(自己的程式插在 Bot 做事的固定時間點) ### 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…)。 - 格式跟 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)補進這一輪給模型的資訊。 - **SessionStart**:一個對話的第一輪開始前。印出的字(或 additionalContext)補進這一輪給模型的資訊。
- **UserPromptSubmit**:每一輪開始前(有使用者說的話 prompt)。印出的字補進資訊;exit 2 或 decision: block 就不做這一輪,聊天裡說「被 hook 擋下,這一輪沒有做:…」。 - **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】…」。 - **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 可以用它放行。 - **Stop**:Bot 要結束這一輪前(stop_hook_active、last_assistant_message)。decision: block 就叫它照 reason 接著做,一輪最多 3 次;第二次起 stop_hook_active 是 true,hook 可以用它放行。
- **Notification**:AnyBot 通知你的時候(title、message),在背景跑,不等它。 - **Notification**:AnyBot 通知你的時候(title、message),在背景跑,不等它。

View File

@ -44,7 +44,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
- 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。 - 設定 › 權限:「直接操作」的開關「讓 Bot 直接動手,不一個個問你」;「自動審核」的開關「照我寫的規則審核 Bot 的操作」,下面兩張規則卡片,「新增規則」或「刪除」。
- 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。 - 設定 › 電腦 ›「你的電腦」:「在這台電腦上執行」的選單。被管理員鎖住時寫「由你的管理員設定,無法變更」。
- 手機:一樣的卡片和 設定 › 權限([phone](phone.md))。 - 手機:一樣的卡片和 設定 › 權限([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、檔案看不看得懂。
## 怎麼操作 ## 怎麼操作

View File

@ -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() { 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(); 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))); *skill_limit.borrow_mut() = Some((k.name.clone(), crate::skills::tool_rules(k)));
} }
} }

View File

@ -497,7 +497,12 @@ impl App {
match &change { match &change {
crate::mcp::Change::Update { after, .. } => self.mcp_reconnect(&after.name), crate::mcp::Change::Update { after, .. } => self.mcp_reconnect(&after.name),
crate::mcp::Change::Reconnect(n) => self.mcp_reconnect(n), 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()); 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; self.ch.mcp_open = open_next;
if let Some(i) = remove { 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 { if let Some((name, url)) = login {
let note = self.ch.note.clone(); let note = self.ch.note.clone();
std::thread::spawn(move || match crate::mcp_oauth::start(&name, &url) { 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) => { Ok(u) => {
let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&u)); let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&u));
} }

View File

@ -74,7 +74,7 @@ impl App {
/// marked `context: fork` (技能帶參數, M4), which goes to a 支線 as it was typed. /// marked `context: fork` (技能帶參數, M4), which goes to a 支線 as it was typed.
pub(super) fn command_for(&self, bot_id: u64, text: &str) -> Option<AppCommand> { pub(super) fn command_for(&self, bot_id: u64, text: &str) -> Option<AppCommand> {
app_command(text).or_else(|| { 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); 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())) 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). /// first (index in the chat, its time, its words).
fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> { fn rewind_points(&self, bot_id: u64) -> Vec<(usize, i64, String)> {
let Some(b) = self.state.bot(bot_id) else { return vec![] }; 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). /// 「/rewind」 (the points) or 「/rewind N [檔案|對話]」 (back to one).
@ -130,6 +130,8 @@ impl App {
let kept = crate::checkpoint::entries(bot_id); let kept = crate::checkpoint::entries(bot_id);
let Some(b) = self.state.bot(bot_id) else { return }; let Some(b) = self.state.bot(bot_id) else { return };
let name = b.name.clone(); 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 { let (n, files, chat) = match r {
Rewind::List => { Rewind::List => {
if points.is_empty() { if points.is_empty() {
@ -139,7 +141,7 @@ impl App {
let now = crate::model::now_ms(); let now = crate::model::now_ms();
let mut text = format!("可以退回的點(最新的在最上面):退回去會把那句話之後 {name} 用 edit_file 改的檔案還原;用指令(shell、git…)改的不在裡面。"); let mut text = format!("可以退回的點(最新的在最上面):退回去會把那句話之後 {name} 用 edit_file 改的檔案還原;用指令(shell、git…)改的不在裡面。");
for (k, (_, at, words)) in points.iter().enumerate() { 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(&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 編號 對話」只退對話。"); text.push_str("\n打「/rewind 編號」檔案和對話都退回那句話之前;「/rewind 編號 檔案」只退檔案;「/rewind 編號 對話」只退對話。");
@ -175,7 +177,7 @@ impl App {
let repaint = self.repaint_fn(); let repaint = self.repaint_fn();
self.goal_note(bot_id, "正在還原檔案…"); self.goal_note(bot_id, "正在還原檔案…");
std::thread::spawn(move || { 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::<Vec<_>>().join("\n")) }; let text = if lines.is_empty() { "檔案:那句話之後沒有用 edit_file 改過檔案,沒有要還原的(用指令改的不在檢查點裡)。".to_string() } else { format!("檔案退回到那句話之前:\n{}", lines.iter().map(|l| format!("- {l}")).collect::<Vec<_>>().join("\n")) };
out.lock().unwrap().push((bot_id, text)); out.lock().unwrap().push((bot_id, text));
repaint(); repaint();

View File

@ -222,7 +222,8 @@ impl App {
let target = targets.iter().find(|t| t.name == chosen).cloned(); let target = targets.iter().find(|t| t.name == chosen).cloned();
let tools: Vec<serde_json::Value> = match &target { let tools: Vec<serde_json::Value> = 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(), 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 }; let own = ChatRequest { tools, ..own };
// A model of another family when the person has one: a bot's own model grades its own // A model of another family when the person has one: a bot's own model grades its own
@ -285,8 +286,11 @@ impl App {
b.goal = None; b.goal = None;
self.goal_note(bot_id, &note); self.goal_note(bot_id, &note);
self.goal_tell(bot_id, &format!("{name} {title}"), &note); self.goal_tell(bot_id, &format!("{name} {title}"), &note);
// (Met, not 「做不到」.)
if note.starts_with("目標達成") {
self.confetti = Some((bot_id, Instant::now())); self.confetti = Some((bot_id, Instant::now()));
} }
}
Next::Pause { note, title } => { Next::Pause { note, title } => {
self.goal_note(bot_id, &note); self.goal_note(bot_id, &note);
self.goal_tell(bot_id, &format!("{name} {title}"), &note); self.goal_tell(bot_id, &format!("{name} {title}"), &note);

View File

@ -44,6 +44,12 @@ fn blob(name: &str) -> PathBuf {
dir().join("blobs").join(name) 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::Mutex<()>> = std::sync::OnceLock::new();
L.get_or_init(Default::default)
}
/// This bot's kept files, oldest first (a week's). /// This bot's kept files, oldest first (a week's).
pub fn entries(bot: u64) -> Vec<Entry> { pub fn entries(bot: u64) -> Vec<Entry> {
let since = crate::model::now_ms() - KEEP_DAYS * 86_400_000; 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; return;
} }
}; };
let _one = log_lock().lock().unwrap_or_else(|e| e.into_inner());
let mut list = entries(bot); let mut list = entries(bot);
if list.iter().any(|e| e.turn == turn && e.place == place && e.path == path) { if list.iter().any(|e| e.turn == turn && e.place == place && e.path == path) {
return; return;
@ -110,9 +117,9 @@ fn keep(bytes: &[u8]) -> Result<String, String> {
} }
/// The files the turns from `turn` on changed (each file once), to show. /// 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![]; 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) { if !seen.iter().any(|s| s.place == e.place && s.path == e.path) {
seen.push(e); 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 /// 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. /// undone first, so each file ends as it was before the first). Those entries are used up.
/// One line per file. /// One line per file.
pub fn restore(bot: u64, turn: i64) -> Vec<String> { /// 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<String> {
let _one = log_lock().lock().unwrap_or_else(|e| e.into_inner());
let list = entries(bot); let list = entries(bot);
let (undo, keep_list): (Vec<Entry>, Vec<Entry>) = list.into_iter().partition(|e| e.turn >= turn); let (undo, mut keep_list): (Vec<Entry>, Vec<Entry>) = list.into_iter().partition(|e| e.turn >= turn && e.turn <= until);
let mut lines: Vec<(String, String)> = vec![]; let mut lines: Vec<(String, String)> = vec![];
for e in undo.iter().rev() { for e in undo.iter().rev() {
let what = if e.computer.is_empty() { e.path.clone() } else { format!("{}({})", e.path, e.computer) }; 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<String> {
lines.retain(|l| l.0 != what); lines.retain(|l| l.0 != what);
lines.push((what.clone(), match r { lines.push((what.clone(), match r {
Ok(word) => format!("{what}:{word}"), 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) { if let Err(e) = write_all(bot, &keep_list) {
log::warn!("檢查點:寫不進紀錄:{e}"); log::warn!("檢查點:寫不進紀錄:{e}");
} }
@ -229,16 +245,17 @@ mod tests {
edit(200, "b.txt", "b1"); edit(200, "b.txt", "b1");
edit(200, "a.txt", "a3"); edit(200, "a.txt", "a3");
assert_eq!(entries(bot).len(), 4); assert_eq!(entries(bot).len(), 4);
assert_eq!(files_since(&entries(bot), 100).len(), 3); assert_eq!(files_since(&entries(bot), 100, i64::MAX).len(), 3);
assert_eq!(files_since(&entries(bot), 200).len(), 2); 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. // 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!(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("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("b.txt")).unwrap(), "b0");
assert_eq!(std::fs::read_to_string(w.join("new.txt")).unwrap(), "n1"); 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. // 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!(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_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a0");
assert!(!w.join("new.txt").exists()); assert!(!w.join("new.txt").exists());
@ -246,7 +263,7 @@ mod tests {
// Too big to keep: said, not pretended. // Too big to keep: said, not pretended.
std::fs::write(w.join("big.bin"), vec![b'x'; MAX_FILE_BYTES + 1]).unwrap(); std::fs::write(w.join("big.bin"), vec![b'x'; MAX_FILE_BYTES + 1]).unwrap();
edit(300, "big.bin", "small"); 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_file(log_of(bot));
let _ = std::fs::remove_dir_all(&w); let _ = std::fs::remove_dir_all(&w);
} }

View File

@ -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") => { "file" if matches!(name, "read_file" | "edit_file" | "list_dir" | "search" | "write_file") => {
let path = s("path"); let path = s("path");
let home = |p: &str| tools::expand_home(p).display().to_string(); 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" => { "connector" => {
let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() }; let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() };

View File

@ -78,6 +78,8 @@ impl Goal {
pub fn resume(&mut self) { pub fn resume(&mut self) {
self.paused.clear(); self.paused.clear();
self.idle = 0; 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 { if self.turns >= self.until {
self.until = self.turns + TURNS; self.until = self.turns + TURNS;
} }
@ -155,6 +157,11 @@ pub fn same_reason(a: &str, b: &str) -> bool {
let c: Vec<char> = s.chars().filter(|c| !c.is_whitespace() && !c.is_ascii_punctuation() && !",。、;:「」()!?".contains(*c)).collect(); let c: Vec<char> = s.chars().filter(|c| !c.is_whitespace() && !c.is_ascii_punctuation() && !",。、;:「」()!?".contains(*c)).collect();
c.windows(2).map(|w| (w[0], w[1])).collect::<std::collections::HashSet<_>>() c.windows(2).map(|w| (w[0], w[1])).collect::<std::collections::HashSet<_>>()
}; };
// (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::<Vec<_>>();
if numbers(a) != numbers(b) {
return false;
}
let (x, y) = (pairs(a), pairs(b)); let (x, y) = (pairs(a), pairs(b));
if x.is_empty() || y.is_empty() { if x.is_empty() || y.is_empty() {
return false; return false;
@ -376,6 +383,7 @@ mod tests {
assert!(same_reason("還差 2 個測試失敗:goal::tests 的時間格式", "還差2個測試失敗(goal::tests 的時間格式)")); assert!(same_reason("還差 2 個測試失敗:goal::tests 的時間格式", "還差2個測試失敗(goal::tests 的時間格式)"));
assert!(!same_reason("還差 2 個測試失敗", "clippy 還有新的警告")); assert!(!same_reason("還差 2 個測試失敗", "clippy 還有新的警告"));
assert!(!same_reason("", "x")); assert!(!same_reason("", "x"));
assert!(!same_reason("目前只成功送出 3 則貼文,目標是 10 則,還差 7 則;下一步繼續發下一則。", "目前只成功送出 4 則貼文,目標是 10 則,還差 6 則;下一步繼續發下一則。"));
let mut g = Goal::new("所有測試都通過", 0); 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, "還差 2 個測試失敗:時間格式".into()), 1), Next::Again { .. }));
assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::NotYet, "clippy 還有新的警告".into()), 2), Next::Again { .. }), "a different gap: on"); assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::NotYet, "clippy 還有新的警告".into()), 2), Next::Again { .. }), "a different gap: on");

View File

@ -316,6 +316,7 @@ impl Live {
self.oauth = Some(name); self.oauth = Some(name);
return again; return again;
} }
self.oauth = Some(name.clone());
return Err(format!("「{name}」的登入過期了:重新登入(在聊天裡請 Bot 用 manage_connectors 的 login,或 設定 › 整合 › 連接器 按「登入」)。")); return Err(format!("「{name}」的登入過期了:重新登入(在聊天裡請 Bot 用 manage_connectors 的 login,或 設定 › 整合 › 連接器 按「登入」)。"));
} }
} }
@ -392,7 +393,7 @@ fn connect(config: &Server) -> Result<Conn, String> {
let mut headers = s.headers.clone(); let mut headers = s.headers.clone();
// 連接器登入: logged in with OAuth (and no key of its own given): its token. // 連接器登入: 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 !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}")); headers.insert("Authorization".into(), format!("Bearer {t}"));
oauth = Some(s.name.clone()); oauth = Some(s.name.clone());
} }

View File

@ -39,6 +39,9 @@ pub struct Tokens {
pub client_secret: String, pub client_secret: String,
#[serde(default)] #[serde(default)]
pub resource: String, 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 { fn file() -> std::path::PathBuf {
@ -57,12 +60,17 @@ fn read_all() -> HashMap<String, Tokens> {
for t in o.values_mut() { for t in o.values_mut() {
for k in ["access", "refresh", "client_secret"] { for k in ["access", "refresh", "client_secret"] {
if let Some(s) = t[k].as_str().filter(|s| s.starts_with("sealed:")).map(String::from) { 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::<Tokens>(t.clone()).ok().map(|t| (k.clone(), t))).collect()).unwrap_or_default()
} }
fn write_all(all: &HashMap<String, Tokens>) -> Result<(), String> { fn write_all(all: &HashMap<String, Tokens>) -> Result<(), String> {
@ -92,7 +100,7 @@ fn write_all(all: &HashMap<String, Tokens>) -> Result<(), String> {
/// This connector's tokens, if it is logged in. /// This connector's tokens, if it is logged in.
pub fn tokens(server: &str) -> Option<Tokens> { pub fn tokens(server: &str) -> Option<Tokens> {
let _g = store().lock().unwrap_or_else(|e| e.into_inner()); 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<Tokens>) -> Result<(), String> { fn save(server: &str, t: Option<Tokens>) -> 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. /// The access token to send, renewed first when it is about to end.
pub fn bearer(server: &str) -> Option<String> { pub fn bearer(server: &str, url: &str) -> Option<String> {
let t = tokens(server)?; // (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() { 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)); return renew(server).ok().or(Some(t.access));
} }
@ -185,7 +194,17 @@ fn query_pairs(q: &str) -> HashMap<String, String> {
q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (dec(k), dec(v))).collect() 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::<String>()));
}
Ok(())
}
fn get_json(url: &str) -> Result<Value, String> { fn get_json(url: &str) -> Result<Value, String> {
allowed(url)?;
let mut resp = crate::net::agent(HTTP_SECS).get(url).header("Accept", "application/json").call().map_err(|e| format!("連不上 {url}:{e}"))?; 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()) { if !(200..300).contains(&resp.status().as_u16()) {
return Err(format!("{url} 回 HTTP {}", resp.status().as_u16())); return Err(format!("{url} 回 HTTP {}", resp.status().as_u16()));
@ -195,6 +214,7 @@ fn get_json(url: &str) -> Result<Value, String> {
} }
fn post_form(url: &str, form: &[(&str, String)]) -> Result<Value, String> { fn post_form(url: &str, form: &[(&str, String)]) -> Result<Value, String> {
allowed(url)?;
let body: String = form.iter().map(|(k, v)| format!("{}={}", enc(k), enc(v))).collect::<Vec<_>>().join("&"); let body: String = form.iter().map(|(k, v)| format!("{}={}", enc(k), enc(v))).collect::<Vec<_>>().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 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(); let status = resp.status().as_u16();
@ -256,7 +276,8 @@ pub fn discover(mcp_url: &str) -> Result<Endpoints, String> {
tries.push(format!("{o}/.well-known/oauth-protected-resource")); tries.push(format!("{o}/.well-known/oauth-protected-resource"));
let prm = tries.iter().find_map(|u| get_json(u).ok()); 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 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. // The authorization server's metadata (RFC 8414, then OpenID's), path-aware.
let (io, ip) = (origin(&issuer), path_of(&issuer)); let (io, ip) = (origin(&issuer), path_of(&issuer));
let mut meta_tries = vec![]; let mut meta_tries = vec![];
@ -283,12 +304,17 @@ pub fn discover(mcp_url: &str) -> Result<Endpoints, String> {
return Err("這個連接器的登入伺服器不支援 PKCE(S256),AnyBot 不能安全地登入它。".into()); 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 /// Register AnyBot with the authorization server (RFC 7591): its client id (and secret, if it
/// gives one). /// gives one).
fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> { fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> {
allowed(&e.register)?;
let mut resp = crate::net::agent(HTTP_SECS) let mut resp = crate::net::agent(HTTP_SECS)
.post(e.register.as_str()) .post(e.register.as_str())
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
@ -306,6 +332,7 @@ fn register(e: &Endpoints, redirect: &str) -> Result<(String, String), String> {
#[derive(Clone)] #[derive(Clone)]
struct Pending { struct Pending {
server: String, server: String,
url: String,
verifier: String, verifier: String,
redirect: String, redirect: String,
endpoints: Endpoints, endpoints: Endpoints,
@ -368,7 +395,7 @@ pub fn start(server: &str, mcp_url: &str) -> Result<String, String> {
{ {
let mut p = pending().lock().unwrap_or_else(|e| e.into_inner()); let mut p = pending().lock().unwrap_or_else(|e| e.into_inner());
p.retain(|_, x| x.started.elapsed() < LOGIN_WAIT && x.server != server); 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)); std::thread::spawn(move || listen(listener, &state));
Ok(url) Ok(url)
@ -439,7 +466,7 @@ fn finish_query(query: &str) -> Result<String, String> {
form.push(("client_secret", p.client_secret.clone())); form.push(("client_secret", p.client_secret.clone()));
} }
let v = post_form(&p.endpoints.token, &form)?; 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)?)) save(&p.server, Some(tokens_from(&v, &base)?))
})(); })();
finished().lock().unwrap_or_else(|e| e.into_inner()).push((p.server.clone(), r.clone())); 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(); let mut all = read_all();
all.get_mut(&name).unwrap().expires_at = crate::model::now_ms() + 1000; all.get_mut(&name).unwrap().expires_at = crate::model::now_ms() + 1000;
write_all(&all).unwrap(); 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"); assert_eq!(*fake.tokens_given.lock().unwrap(), 2, "one for the code, one renewal");
// The same address again: that login is used up. // 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()); assert!(finish_from_url("http://127.0.0.1:1/callback?code=the-code&state=nope").is_err());

View File

@ -262,7 +262,8 @@ pub fn parse_skill_markdown(text: &str) -> Option<Skill> {
while i < lines.len() { while i < lines.len() {
let line = lines[i]; let line = lines[i];
let trimmed = line.trim(); 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; i += 1;
continue; continue;
} }
@ -274,7 +275,7 @@ pub fn parse_skill_markdown(text: &str) -> Option<Skill> {
let val = raw_val.trim(); let val = raw_val.trim();
// A block list under the key (`allowed-tools:` then ` - Read` lines). // A block list under the key (`allowed-tools:` then ` - Read` lines).
let list_items: Vec<String> = if val.is_empty() { let list_items: Vec<String> = 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 { } else {
vec![] vec![]
}; };
@ -425,7 +426,8 @@ fn split_arguments(args: &str) -> Vec<String> {
match (quote, c) { match (quote, c) {
(Some(q), c) if c == q => quote = None, (Some(q), c) if c == q => quote = None,
(Some(_), c) => cur.push(c), (Some(_), c) => cur.push(c),
(None, '"' | '\'' | '「') => { // (Not ': 「don't stop」 has one.)
(None, '"' | '「') => {
quote = Some(if c == '「' { '」' } else { c }); quote = Some(if c == '「' { '」' } else { c });
any = true; any = true;
} }
@ -526,11 +528,18 @@ pub fn tool_rules(k: &Skill) -> Vec<String> {
let inner = inner.strip_suffix(')').unwrap_or(inner).replace(":*", " *"); let inner = inner.strip_suffix(')').unwrap_or(inner).replace(":*", " *");
match kind.trim() { match kind.trim() {
"Bash" | "shell" => format!("shell({inner})"), "Bash" | "shell" => format!("shell({inner})"),
"Read" | "Write" | "Edit" | "file" => format!("file({inner})"), // (Read(…) is for reading there, not for changing it; WebFetch(…) for
"WebFetch" | "web" => format!("web({inner})"), // 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})"), 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)), 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). /// 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 { 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 { 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. // allowed-tools as rules: Claude Code's names are AnyBot's tools.
let rules = tool_rules(&k); let rules = tool_rules(&k);
assert_eq!(rules, ["tool(read_file)", "shell(git log *)", "shell(git tag *)"]); 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(); let sh = |c: &str| serde_json::json!({"command": c}).to_string();
assert!(skill_allows(&rules, "read_file", r#"{"path":"a"}"#)); 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"))); assert!(skill_allows(&rules, "shell", &sh("git log --oneline")) && skill_allows(&rules, "shell", &sh("git tag v2")));

View File

@ -2538,16 +2538,23 @@ fn watch_lines(bot: u64, id: u64, shown: &str, output: &Mutex<String>, exit: &Mu
while recent.front().is_some_and(|(t, _)| now.duration_since(*t) > MONITOR_WINDOW) { while recent.front().is_some_and(|(t, _)| now.duration_since(*t) > MONITOR_WINDOW) {
recent.pop_front(); recent.pop_front();
} }
if recent.iter().map(|(_, n)| n).sum::<usize>() > MONITOR_MAX_LINES { // (Its own end first: a command that printed a lot and finished wasn't stopped.)
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 let Some(c) = code { if let Some(c) = code {
let end = if c == 0 { "指令結束了".to_string() } else { format!("指令結束了(結束碼 {c})") }; 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)) })); monitor_say(bot, format!("[監看 #{id}]`{shown}` {end},監看也停了。{}", if lines.is_empty() { String::new() } else { format!("最後印出的:{}", head(&lines)) }));
return; 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::<usize>() > 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() { if lines.is_empty() {
continue; continue;
} }