From f19b49f953255bbf2a1eb185c2fe36a45c922acf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 12:59:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Hooks=EF=BC=9A=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E7=9A=84=E7=A8=8B=E5=BC=8F=E6=8F=92=E5=9C=A8=20Bot=20=E5=81=9A?= =?UTF-8?q?=E4=BA=8B=E7=9A=84=E5=9B=BA=E5=AE=9A=E6=99=82=E9=96=93=E9=BB=9E?= =?UTF-8?q?=EF=BC=88Claude=20Code=20=E7=9A=84=E6=A0=BC=E5=BC=8F=EF=BC=89?= =?UTF-8?q?=EF=BC=8CBot=20=E4=B9=9F=E8=83=BD=E5=9C=A8=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E8=A3=A1=E5=B9=AB=E4=BD=A0=E8=A8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - hooks.json 跟 Claude Code 一樣(matcher、type command/http、timeout),AnyBot 和 Claude Code 的工具名字都認;使用者的在資料夾 hooks/,管理員的(先跑、改不了)在系統位置,MDM 可推。 - SessionStart(對話第一輪)、UserPromptSubmit(補資訊或擋下這一輪)、PreToolUse(擋、改參數、ask 一定問、allow 省一次問但擋不過安全規則和每次問的)、PostToolUse(換掉或補 Bot 讀到的結果)、Stop(叫它接著做,一輪最多 3 次)、Notification(跟著通知跑)。 - hook 自己出錯(結束碼、逾時、JSON、設定檔)就當它不在,紀錄檔寫原因;/doctor 寫有幾個、檔案看不看得懂。 - manage_hooks(list/add/remove):加和移除每次都先問,一律放行也問;管理 App 的能力,外面的訊息不能用。 - 測試裡每一輪只拿測試給那個 Bot 的 hook,不讀檔(同時跑的測試不會互相影響)。 已驗證:cargo test 602 通過(hook 本身:擋 rm、改參數、ask、壞掉的 hook、逾時、prompt 補資訊、Stop 用 stop_hook_active 放行、PostToolUse 換結果、manage_hooks 改檔;真的一輪:rm 沒有執行、跑的是 hook 改過的指令、Stop 讓模型多回一次)、clippy -D warnings 乾淨。 未驗證:HTTP hook 打到真的伺服器、管理員檔案的位置在真的 Mac/Linux 上、Windows 的 cmd。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 16 + docs/feature-map/safety.md | 5 +- docs/plan-2026-11-engineering.md | 2 +- src/agent.rs | 149 ++++++++ src/app.rs | 23 +- src/app/doctor_ui.rs | 3 + src/appctl.rs | 7 +- src/doctor.rs | 11 + src/hooks.rs | 620 +++++++++++++++++++++++++++++++ src/main.rs | 1 + src/profile.rs | 2 +- src/remote.rs | 2 + 12 files changed, 835 insertions(+), 6 deletions(-) create mode 100644 src/hooks.rs diff --git a/FEATURES.md b/FEATURES.md index 0d1bf1e..0680727 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1531,6 +1531,22 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - Bot 正在做事時不行(「等它做完(或按停止)再 /fork」);對話是空的也不行。電腦、大腦的螢幕、手機打的都算,由大腦做;訊息管道和團隊成員打的不算指令。 - AnyBot 自己的指令(/btw、/goal、/plan、/always-approve、/usage、/doctor、/context、/compact、/fork、/rewind)在電腦和手機/螢幕兩條路上由同一個地方認出來、同一個地方做,新增指令只要加一次。 +### 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 裡改不了。每一輪開始時重讀,改了下一輪就生效。 +- 事件: + - **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 的安全規則,也省不掉付款/傳送/刪除、寄信、傳訊息這類每次都問的。 + - **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),在背景跑,不等它。 + - 共同的欄位:session_id(anybot-bot-編號)、bot_id、bot、cwd、hook_event_name;指令的環境變數有 ANYBOT_HOOK_EVENT,模型金鑰拿掉。 +- hook 自己出錯——結束碼不是 0 或 2、超過 timeout(預設 60 秒,最多 600)、開不起來、回的 JSON 看不懂、設定檔看不懂——就當它不在,Bot 照常做,紀錄檔寫是哪個 hook、什麼錯;/doctor 寫有幾個 hook,設定檔看不懂時 ✗。continue: false 擋下這一步(PreToolUse)或這一輪(UserPromptSubmit)。 +- hook 在大腦上、用你的身分、在 Bot 的沙盒外跑(它們是你自己的程式)。 +- **在聊天裡請 Bot 設**:「幫我加一個 hook,Bot 每次要執行 rm 就擋下」→ Bot 用 `manage_hooks`(list/add/remove)。加和移除每次都先給你看(「新增一個 hook:每次「PreToolUse」(工具符合「shell」)時,在大腦上(Bot 的沙盒外,用你的身分)執行指令:…」),**一律放行也照樣問**:hook 之後會在沙盒外一直跑。指令裡的金鑰在卡片上遮掉。只改你的檔案,管理員的改不了。訊息管道和團隊成員的那一輪不能用(管理 App 的能力)。 + ### 檢查點與退回(/rewind) - Bot 用 `edit_file` 改檔案之前,AnyBot 先把那個檔案原本的樣子存起來(還沒有這個檔案也記下來),記在開始那一輪的你那句話底下;同一輪改同一個檔案好幾次只記第一次。在你的電腦、Bot 自己的電腦(Docker 或封閉資料夾)、SSH 電腦上改的都記;存在資料夾的 checkpoints/,一週後清掉,同樣的內容只存一份。參考 Claude Code 的檢查點、grok-build 的 /rewind。 diff --git a/docs/feature-map/safety.md b/docs/feature-map/safety.md index d0e61a8..8dcf508 100644 --- a/docs/feature-map/safety.md +++ b/docs/feature-map/safety.md @@ -35,6 +35,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 7. 要問的交給自動審核或直接操作。 8. 上面那些「每次都問」的,蓋過第 6、7 步。 9. 問你;等的時候按停止=拒絕。 +- Hooks:使用者(和管理員)自己的程式,AnyBot 在固定的時間點跑它們,格式跟 Claude Code 一樣(hooks.json)。PreToolUse 可以擋下一步(exit 2 或 deny)、改參數、要先問或省掉一次詢問(但擋不過安全規則,也省不掉付款/傳送/刪除這類每次問);PostToolUse 改 Bot 讀到的結果或加一句;UserPromptSubmit、SessionStart 補資訊給模型或擋下這一輪;Stop 叫它多做(一輪最多 3 次);Notification 跟著通知跑。hook 自己出錯(結束碼不對、逾時、JSON 看不懂)就當它不在,紀錄檔寫原因。 ## 使用者怎麼到 @@ -43,10 +44,11 @@ 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、檔案看不看得懂。 ## 怎麼操作 -- Bot:不能替你按允許,也不能點 AnyBot 的核准按鈕;被拒後不要再試同一件事,也不要換個寫法做。`update_settings` 改不了這些開關(打開「在這台電腦上執行」只有使用者能做)。要你親手做的步驟用 `hand_over_computer`,要你決定的用 `ask_person`([chat](chat.md))。 +- Bot:不能替你按允許,也不能點 AnyBot 的核准按鈕;被拒後不要再試同一件事,也不要換個寫法做。`update_settings` 改不了這些開關(打開「在這台電腦上執行」只有使用者能做)。要你親手做的步驟用 `hand_over_computer`,要你決定的用 `ask_person`。使用者要加、看、移除 hook 時用 `manage_hooks`(action list/add/remove,event、matcher、command 或 url):加和移除每次都先問使用者,一律放行也照樣問([chat](chat.md))。 - 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。打「/always-approve」後再請它在你的電腦執行 `printf ok`(訊息裡指名你的電腦),不該跳卡片、結果有 ok;用訊息管道傳同一句,照樣要你按;「/always-approve off」後又會問。Linux 上 /doctor 要有「指令沙盒:Linux 的 Landlock」,請 Bot 在你的電腦 `cat ~/.ssh/known_hosts` 可以、`cat` AnyBot 資料夾裡的 state.json 要失敗。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`、`cargo test always`、`cargo test landlock::`(真的套上 Landlock 的那個只在有 Landlock 的 Linux 跑)。 ## 陷阱 @@ -55,6 +57,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你 - 「在這台電腦上執行」選了「永不允許」,打開直接操作也不能在這台做事。 - 一律放行會一直開著(重開 AnyBot 也是),例行任務半夜也照樣直接做;用完記得「/always-approve off」。Bot 自己、例行任務、訊息管道都打不開它,只有你打的指令或設定的開關可以。 - 「一律允許」每個 Bot 各記各的,換一個 Bot 還會再問。 +- hook 在大腦上、用使用者的身分、在 Bot 的沙盒外跑:只加看得懂的指令。每一步都會跑 PreToolUse,慢的 hook 會讓 Bot 變慢(預設最多等 60 秒)。 - 拒絕只擋一模一樣的操作;換個寫法擋不住,要靠 Bot 自己停。 - 外面的訊息和團隊成員的訊息不用你的「一律允許」、直接操作和自動審核:要核准的事都得你親手按;AnyBot 瀏覽器(帶著你的登入)和保險庫完全不給用。 - 15 分鐘逾時的訊息會寫是什麼在等(「例行任務」「訊息管道的訊息」「事件觸發的工作」「其他 Bot 交辦的工作」),等的時候在別的 Bot 的聊天裡看不到卡片,要看側邊欄。 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 1090c3a..ebbf814 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -101,7 +101,7 @@ - 做法:每一輪第一次改檔案前,替工作資料夾的檔案(git 專案用 `git stash create`,其他用改之前的副本)存一個檢查點;`/rewind` 列出最近的檢查點,選一個把檔案和對話退回那裡。 - 做完:改了三個檔案後 /rewind,三個檔案回到原本內容。 -### M2. Hooks ⬜ +### M2. Hooks ✅(Claude Code 的格式;SessionStart 是「對話的第一輪」;allow 擋不過安全規則和每次問的;manage_hooks 讓 Bot 在聊天裡設,每次都問、一律放行也問) - 做法:`SessionStart`、`UserPromptSubmit`、`PreToolUse`(回 allow/ask/deny,可以改參數)、`PostToolUse`(可以改 Bot 讀到的結果)、`Stop`(可以叫它繼續)、`Notification`。設定檔放在資料夾的 `hooks/`,或管理員的 policy 位置(MDM 可推);hook 是指令或 HTTP。hook 自己出錯時照常做,紀錄寫清楚。 - 做完:一個 PreToolUse hook 擋 `rm`、一個改參數、一個 Stop hook 讓它多做一輪,都有測試。 diff --git a/src/agent.rs b/src/agent.rs index fd12d2c..f5307a5 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1754,6 +1754,35 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< prompt: history.last().filter(|m| m.role == Role::User).map(|m| crate::oplog::Prompt { at: m.at, text: m.text.clone() }), }); let mut closing = Closing { log: job.log.clone(), op: job.op.clone(), cancel: cancel.clone(), written: false }; + // Hooks (hooks.rs): the person's and the admin's own programs, read once for the turn. + let hooks = crate::hooks::Hooks::load_for(bot_id); + let hook_base = crate::hooks::base(bot_id, &job.via_name); + let mut stop_continues = 0usize; + if !hooks.is_empty() { + let prompt = history.iter().rev().find(|m| m.role == Role::User).map(|m| m.text.clone()).unwrap_or_default(); + let mut context = String::new(); + // SessionStart: a conversation's first turn. + if !history.iter().any(|m| m.role == Role::Assistant) { + let mut input = hook_base.clone(); + input["source"] = serde_json::json!("startup"); + context = hooks.fire("SessionStart", None, input).context; + } + let mut input = hook_base.clone(); + input["prompt"] = serde_json::json!(prompt); + let said = hooks.fire("UserPromptSubmit", None, input); + if let Some(why) = said.block.or(said.stop) { + closing.close(crate::oplog::Outcome::Failed); + send(StreamEvent::Error(format!("被 hook 擋下,這一輪沒有做:{}", if why.is_empty() { "(hook 沒有說原因)".into() } else { why }))); + return; + } + if !said.context.is_empty() { + context = if context.is_empty() { said.context } else { format!("{context}\n{}", said.context) }; + } + // (At the end of the system prompt: what comes before it stays the same for the cache.) + if !context.is_empty() { + job.req.system.push_str(&format!("\n\n【使用者的 hook 補充的資訊】\n{context}")); + } + } // Making room because the model said it was too long: each way once per thing the person // said (see make_room), and which one this step's retry rides on. let mut room = Room::default(); @@ -1967,6 +1996,18 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let switched = plan.changed_route(&calls, quick.is_some()); history.push(msg); if calls.is_empty() { + // Hooks' Stop: a hook may send it on (at most MAX_STOP_CONTINUES times a turn). + if job.steer.lock().unwrap().is_empty() && !hooks.is_empty() && stop_continues < crate::hooks::MAX_STOP_CONTINUES { + let mut input = hook_base.clone(); + input["stop_hook_active"] = serde_json::json!(stop_continues > 0); + input["last_assistant_message"] = serde_json::json!(history.last().map(|m| m.text.clone()).unwrap_or_default()); + if let Some(why) = hooks.fire("Stop", None, input).block { + stop_continues += 1; + send(StreamEvent::Retrying(format!("hook 要它接著做:{}", why.chars().take(80).collect::()))); + history.push(Message::user(&format!("【AnyBot:使用者設定的 hook 說還不能結束】{why}\n照這個接著做,做完再回報。"))); + continue; + } + } // Something typed while it answered keeps the same turn going. if job.steer.lock().unwrap().is_empty() { closing.close(crate::oplog::Outcome::Completed); @@ -1997,6 +2038,27 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } // What runs: the call as asked, on the chosen computer (see keep_to_chosen). let call = ToolCall { args: runs_with.get(&asked.id).cloned().unwrap_or_else(|| asked.args.clone()), ..asked.clone() }; + // Hooks' PreToolUse: blocked here; arguments changed; its allow / ask is used below. + let hook_word = if hooks.is_empty() { + crate::hooks::Said::default() + } else { + let mut input = hook_base.clone(); + input["tool_name"] = serde_json::json!(call.name); + input["tool_input"] = crate::hooks::tool_input(&call.args); + hooks.fire("PreToolUse", Some(&call.name), input) + }; + let call = match &hook_word.input { + Some(v) => ToolCall { args: crate::hooks::args_back(v), ..call }, + None => call, + }; + let hook_no = hook_word.block.clone().or_else(|| hook_word.permission.clone().filter(|(p, _)| p == "deny").map(|(_, r)| r)).or_else(|| hook_word.stop.clone()); + if let Some(why) = hook_no { + send(StreamEvent::ToolStatus(call.id.clone(), ToolStatus::Denied)); + let result = Message::tool_result(&call.id, &call.name, &format!("沒有執行:使用者設定的 hook 擋下了這一步。{}", if why.is_empty() { String::new() } else { format!("它說:{why}") })); + send(StreamEvent::ToolResult(result.clone())); + history.push(result); + continue; + } // 計畫模式: until the person approves the plan, only looking runs (even a step // asked for in the same breath as the plan: the model didn't know the answer). if job.drafting.is_some() && !runs_while_planning(&call.name) { @@ -2098,6 +2160,24 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } 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}")); @@ -3252,6 +3332,19 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< .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 { .. })); @@ -5543,6 +5636,62 @@ echo 'done送出了' > done.html; (setsid pyt assert!(results.iter().any(|r| r.contains("只准用") && r.contains("edit_file")), "{results:?}"); } + /// Hooks (M2) in a real turn: a PreToolUse hook blocks `rm` (not run), another changes a + /// command's arguments (what runs is the changed one), and a Stop hook sends the bot on for + /// one more round before it may finish. + #[cfg(unix)] + #[test] + fn hooks_block_change_and_send_on() { + use crate::hooks::{Config, Group, Hook, Hooks}; + let w = std::env::temp_dir().join(format!("anybot-hooks-turn-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&w); + std::fs::create_dir_all(&w).unwrap(); + std::fs::write(w.join("keep.txt"), "x").unwrap(); + let hook = |command: &str| Hook { kind: "command".into(), command: command.into(), url: String::new(), headers: Default::default(), timeout: Some(10) }; + let mut c = Config::default(); + c.hooks.insert("PreToolUse".into(), vec![Group { matcher: "shell".into(), hooks: vec![ + hook(r#"in=$(cat); echo "$in" | grep -q '"command":"rm ' && { echo '不准刪檔' >&2; exit 2; }; echo "$in" | grep -q 'echo before' && echo '{"hookSpecificOutput":{"permissionDecision":"allow","updatedInput":{"command":"echo after > changed.txt"}}}'; exit 0"#), + ] }]); + c.hooks.insert("Stop".into(), vec![Group { matcher: String::new(), hooks: vec![hook(r#"grep -q '"stop_hook_active":true' && exit 0; echo '{"decision":"block","reason":"再檢查一次"}'"#)] }]); + let bot = 7_701; + crate::hooks::test_hooks().lock().unwrap().insert(bot, Hooks { admin: Config::default(), mine: c }); + let (port, bodies) = fake_http(vec![ + sse_call("c1", "shell", serde_json::json!({"command": "rm keep.txt"})), + sse_call("c2", "shell", serde_json::json!({"command": "echo before > changed.txt"})), + sse_text("做完了"), + sse_text("檢查過了,真的做完了"), + ]); + let mut job = test_job(); + job.req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("整理一下")], tools: tools::specs(), session: String::new(), effort: String::new() }; + job.computers = vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }]; + job.default_computer = crate::model::THIS_COMPUTER_NAME.into(); + job.roles = tools::Roles { own: crate::model::BOT_COMPUTER_NAME.into(), person: Some(crate::model::THIS_COMPUTER_NAME.into()), server: false }; + job.tools_enabled = true; + job.local_execution = true; + let (tx, rx) = channel(); + spawn(job, bot, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + let mut results = vec![]; + loop { + let (_, ev) = rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled"); + match ev { + StreamEvent::NeedApproval(a) => { + let _ = a.reply.send(ApprovalAnswer::Once); + } + StreamEvent::ToolResult(m) => results.push(m.text.clone()), + StreamEvent::Done | StreamEvent::Error(_) => break, + _ => {} + } + } + crate::hooks::test_hooks().lock().unwrap().remove(&bot); + assert!(results[0].contains("hook 擋下") && results[0].contains("不准刪檔"), "{results:?}"); + assert!(w.join("keep.txt").exists(), "rm never ran"); + assert_eq!(std::fs::read_to_string(w.join("changed.txt")).unwrap_or_default().trim(), "after", "the hook's arguments ran: {results:?}"); + let sent = bodies.lock().unwrap().clone(); + assert_eq!(sent.len(), 4, "the Stop hook sent it on once, then let it finish"); + assert!(sent[3].contains("再檢查一次")); + let _ = std::fs::remove_dir_all(&w); + } + #[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/app.rs b/src/app.rs index e93a5f1..9a8f29b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2475,6 +2475,15 @@ impl App { self.manage_connectors(ctx, call); return; } + // Hooks: the person's file (the change was shown to them and they said yes). + if call.name == crate::hooks::MANAGE_TOOL { + let r = crate::hooks::parse_change(&call.args).and_then(|c| crate::hooks::apply_change(&c)); + let _ = call.reply.send(match r { + Ok(t) => (t, true), + Err(e) => (e, false), + }); + return; + } let out = if call.name == "list_computers" { let text = self.state.bot(bot_id).cloned().map(|b| self.computers_text(&b)).unwrap_or_default(); appctl::Outcome { text, ok: true, wake: vec![], theme_changed: false, page: None } @@ -2960,11 +2969,21 @@ impl App { continue; } } + } else if call.name == crate::hooks::MANAGE_TOOL { + // Hooks: run outside the sandbox as the person — every change shown and asked. + match crate::hooks::parse_change(&call.args) { + Ok(c) => crate::hooks::change_question(&c), + Err(e) => { + let _ = call.reply.send((e, false)); + continue; + } + } } else { appctl::needs_approval(&call.name, &call.args, &self.state) }; - // 一律放行: what would be asked is done at once. - let ask = ask.filter(|_| self.always_answer(id, ApprovalKind::Action).is_none()); + // 一律放行: what would be asked is done at once (a hook change is still asked: + // it would run outside the sandbox from then on). + let ask = ask.filter(|_| call.name == crate::hooks::MANAGE_TOOL || self.always_answer(id, ApprovalKind::Action).is_none()); match ask { Some(reason) => { let (reply, _) = channel(); diff --git a/src/app/doctor_ui.rs b/src/app/doctor_ui.rs index faa11a4..715ddaa 100644 --- a/src/app/doctor_ui.rs +++ b/src/app/doctor_ui.rs @@ -67,6 +67,9 @@ impl App { } // (Commands for 「你的電腦」 run here, a screen of a brain too.) lines.push(crate::doctor::sandbox_line()); + if let Some(l) = crate::doctor::hooks_line() { + lines.push(l); + } match crate::doctor::free_mb(&data) { Some(mb) if mb < 2048 => lines.push(bad(format!("磁碟只剩 {mb} MB(快照、模型和 Bot 的電腦都要空間)"))), Some(mb) => lines.push(ok(format!("磁碟還有 {:.1} GB", mb as f64 / 1024.0))), diff --git a/src/appctl.rs b/src/appctl.rs index c27345e..529ff3e 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -9,7 +9,7 @@ use crate::model::{self, Bot, Message, State, Theme, Accent}; use crate::providers::{ProviderKind, ALL_PROVIDERS}; use crate::routines::{self, Routine, Schedule}; -pub const NAMES: [&str; 29] = [ +pub const NAMES: [&str; 30] = [ "list_routines", "create_routine", "update_routine", "delete_routine", "run_routine_now", "list_bots", "create_bot", "update_bot", "message_bot", "list_computers", "update_settings", // 問同事: ask another bot and wait for its answer (the window runs its turn, see app/asks.rs); @@ -23,6 +23,8 @@ pub const NAMES: [&str; 29] = [ // 連接器: list, add, change, reconnect and remove them (the window runs it; it knows how they // connect; adding, changing and removing ask the person first). crate::mcp::MANAGE_TOOL, + // Hooks: list, add and remove the person's (asked every time, even with 一律放行). + crate::hooks::MANAGE_TOOL, ]; pub fn is_app_tool(name: &str) -> bool { @@ -33,6 +35,7 @@ pub fn label(name: &str) -> &'static str { match name { "list_routines" => "查看例行任務", crate::mcp::MANAGE_TOOL => "管理連接器", + crate::hooks::MANAGE_TOOL => "管理 hook", "create_routine" => "建立例行任務", "update_routine" => "修改例行任務", "delete_routine" => "刪除例行任務", @@ -159,6 +162,7 @@ pub fn specs() -> Vec { "parameters": {"type": "object", "properties": { "theme": {"type": "string", "enum": ["light", "dark", "system"]}, "accent": {"type": "string", "enum": ["quiet", "bot_color", "black"], "description": "聊天的顏色: quiet = your messages in a light grey bubble (default), bot_color = in the bot's colour, black"}, "timezone": {"type": "string"}}}}), crate::mcp::manage_spec(), + crate::hooks::manage_spec(), ] .into_iter() .chain(crate::pages::specs()) @@ -177,6 +181,7 @@ pub fn describe(name: &str, args: &str) -> String { } "delete_routine" | "run_routine_now" => format!("#{}", v.get("id").and_then(Value::as_u64).unwrap_or(0)), crate::mcp::MANAGE_TOOL => format!("{} {}", s("action"), s("name")).trim().to_string(), + crate::hooks::MANAGE_TOOL => format!("{} {}", s("action"), s("event")).trim().to_string(), "message_bot" => format!("給 {}:{}", s("bot"), s("text").chars().take(40).collect::()), "ask_bot" => format!("問 {}:{}", s("bot"), s("question").chars().take(40).collect::()), "teach_skill" => format!("「{}」給 {}", s("skill"), s("bot")), diff --git a/src/doctor.rs b/src/doctor.rs index 49ee9ae..dd4f0dc 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -81,6 +81,17 @@ pub fn sandbox_line() -> Line { bad("這台的指令沒有沙盒(Windows 還沒有):指令讀得到 .ssh 這類私密資料夾,只靠安全規則擋") } +/// The hooks set here (None: none, and both files read fine). +pub fn hooks_line() -> Option { + let (mine, admin) = (crate::hooks::read_config(&crate::hooks::mine_path()), crate::hooks::read_config(&crate::hooks::admin_path())); + if let Some(e) = [&mine, &admin].into_iter().find_map(|r| r.as_ref().err()) { + return Some(bad(format!("hook 設定檔有問題,裡面的 hook 都沒有在跑:{e}"))); + } + let count = |c: &crate::hooks::Config| c.hooks.values().flatten().map(|g| g.hooks.len()).sum::(); + let (m, a) = (count(&mine.unwrap_or_default()), count(&admin.unwrap_or_default())); + (m + a > 0).then(|| ok(format!("hook:你的 {m} 個、管理員的 {a} 個({})", crate::hooks::mine_path().display()))) +} + /// Free space where the data folder is, in MB (None where `df` can't say). pub fn free_mb(dir: &Path) -> Option { let out = std::process::Command::new("df").args(["-Pk"]).arg(dir).output().ok()?; diff --git a/src/hooks.rs b/src/hooks.rs new file mode 100644 index 0000000..593f089 --- /dev/null +++ b/src/hooks.rs @@ -0,0 +1,620 @@ +//! Hooks (M2): the person's (or an admin's) own programs, run by AnyBot at set points of a bot's +//! work — Claude Code's hooks, in its file format, so a hook written for it works here. +//! +//! - Where: `<資料夾>/hooks/hooks.json` (the person's: a bot changes it with manage_hooks, asked +//! every time) and the admin's file (`/Library/Application Support/AnyBot/hooks.json` on a Mac, +//! `/etc/anybot/hooks.json`, `%ProgramData%\AnyBot\hooks.json`; MDM can put it there), which runs +//! first and can't be changed from AnyBot. +//! - `{"hooks": {"PreToolUse": [{"matcher": "shell|Bash", "hooks": [{"type": "command", +//! "command": "…", "timeout": 30}]}]}}`; a hook is a command (gets the event as JSON on its +//! input) or `{"type": "http", "url": "…", "headers": {…}}` (gets it POSTed). +//! - Events: SessionStart (a conversation's first turn), UserPromptSubmit (each turn), PreToolUse, +//! PostToolUse, Stop (the bot is about to finish), Notification (AnyBot tells the person). +//! - What a hook says: exit 0 (its JSON, or for UserPromptSubmit/SessionStart its text as context +//! for the model); exit 2 blocks (its error output is the reason); anything else — another exit +//! code, a timeout, it can't start, its JSON can't be read — is the hook's own trouble: written to +//! the log, and the bot goes on as if it weren't there. +//! - They run on the brain, as the person, outside the bots' sandbox (they are the person's own +//! programs). A hook's "allow" saves a question, never AnyBot's own refusals (安全規則) nor the +//! questions asked every time (付款、傳送、刪除…). + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +/// The tool a bot changes the person's hooks with (asked every time, even with 一律放行). +pub const MANAGE_TOOL: &str = "manage_hooks"; + +pub const EVENTS: [&str; 6] = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "Notification"]; + +/// A hook waits this long unless it says (`timeout`, seconds). +const DEFAULT_TIMEOUT_SECS: u64 = 60; +/// Stop hooks may keep a turn going this many times. +pub const MAX_STOP_CONTINUES: usize = 3; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct Hook { + #[serde(rename = "type", default = "command_kind")] + pub kind: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub command: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub headers: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout: Option, +} + +fn command_kind() -> String { + "command".into() +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] +pub struct Group { + /// The tools it is for (a regular expression over the name; Claude Code's names count too: + /// Bash is shell). Empty or `*`: all. + #[serde(default)] + pub matcher: String, + pub hooks: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] +pub struct Config { + #[serde(default)] + pub hooks: BTreeMap>, +} + +/// The person's hooks file. +pub fn mine_path() -> PathBuf { + crate::model::State::path().parent().map(|d| d.join("hooks").join("hooks.json")).unwrap_or_else(|| PathBuf::from("hooks.json")) +} + +/// The admin's hooks file. +pub fn admin_path() -> PathBuf { + if cfg!(test) { + return std::env::var_os("ANYBOT_TEST_ADMIN_HOOKS").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/nonexistent/anybot-admin-hooks.json")); + } + if cfg!(target_os = "macos") { + PathBuf::from("/Library/Application Support/AnyBot/hooks.json") + } else if cfg!(windows) { + PathBuf::from(std::env::var("ProgramData").unwrap_or_else(|_| "C:\\ProgramData".into())).join("AnyBot").join("hooks.json") + } else { + PathBuf::from("/etc/anybot/hooks.json") + } +} + +/// A hooks file (none there: no hooks; one that can't be read: none, and why). +pub fn read_config(p: &std::path::Path) -> Result { + match std::fs::read_to_string(p) { + Ok(t) if t.trim().is_empty() => Ok(Config::default()), + Ok(t) => serde_json::from_str(&t).map_err(|e| format!("{} 看不懂:{e}", p.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()), + Err(e) => Err(format!("讀不到 {}:{e}", p.display())), + } +} + +/// Both files' hooks, the admin's first. +#[derive(Clone, Debug, Default)] +pub struct Hooks { + pub admin: Config, + pub mine: Config, +} + +impl Hooks { + /// Read now (a file that can't be read counts as none; the log says why). + pub fn load() -> Hooks { + let get = |p: PathBuf| { + read_config(&p).unwrap_or_else(|e| { + log::warn!("hooks:{e}"); + Config::default() + }) + }; + Hooks { admin: get(admin_path()), mine: get(mine_path()) } + } + + /// A bot's turn's hooks. (In `cargo test` only what a test set for that bot: turns of other + /// tests running at the same time must not pick up one test's file.) + pub fn load_for(bot_id: u64) -> Hooks { + #[cfg(test)] + return test_hooks().lock().unwrap().get(&bot_id).cloned().unwrap_or_default(); + #[allow(unreachable_code)] + { + let _ = bot_id; + Hooks::load() + } + } + + pub fn is_empty(&self) -> bool { + self.admin.hooks.values().chain(self.mine.hooks.values()).all(|g| g.iter().all(|g| g.hooks.is_empty())) + } + + /// The hooks for this event (and tool), in order. + fn matching(&self, event: &str, tool: Option<&str>) -> Vec { + let mut out = vec![]; + for c in [&self.admin, &self.mine] { + for g in c.hooks.get(event).into_iter().flatten() { + if tool.is_none_or(|t| matches(&g.matcher, t)) { + out.extend(g.hooks.iter().cloned()); + } + } + } + out + } +} + +/// Claude Code's name for an AnyBot tool (a matcher may use either). +fn claude_name(tool: &str) -> &str { + match tool { + "shell" => "Bash", + "read_file" => "Read", + "edit_file" => "Edit", + "search" => "Grep", + "list_dir" => "LS", + "web_fetch" => "WebFetch", + "web_search" => "WebSearch", + _ => tool, + } +} + +/// Whether a matcher covers a tool: the whole name matches it as a regular expression. +fn matches(matcher: &str, tool: &str) -> bool { + let m = matcher.trim(); + if m.is_empty() || m == "*" { + return true; + } + match regex::Regex::new(&format!("^(?:{m})$")) { + Ok(r) => r.is_match(tool) || r.is_match(claude_name(tool)) || (tool == "edit_file" && (r.is_match("Write") || r.is_match("MultiEdit"))), + Err(_) => m == tool, + } +} + +/// What one hook gave back. +#[derive(Debug, Default)] +struct Ran { + code: Option, + out: String, + err: String, +} + +fn run_one(h: &Hook, input: &Value) -> Result { + let secs = h.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS).clamp(1, 600); + if h.kind == "http" { + let mut r = crate::net::agent(secs).post(h.url.as_str()).header("Content-Type", "application/json"); + for (k, v) in &h.headers { + r = r.header(k.as_str(), v.as_str()); + } + let mut resp = r.send(input.to_string().as_bytes()).map_err(|e| format!("連不上 {}:{e}", h.url))?; + let status = resp.status().as_u16(); + let body = resp.body_mut().with_config().limit(1024 * 1024).read_to_string().unwrap_or_default(); + // (Like an exit code: 2xx is 0; anything else is the hook's own trouble.) + return Ok(Ran { code: Some(if (200..300).contains(&status) { 0 } else { i32::from(status) }), out: body, err: String::new() }); + } + if h.command.trim().is_empty() { + return Err("沒有指令".into()); + } + let mut c = if cfg!(windows) { + let mut c = std::process::Command::new("cmd"); + c.arg("/C").arg(&h.command); + c + } else { + let mut c = std::process::Command::new("/bin/sh"); + c.arg("-c").arg(&h.command); + c + }; + for k in crate::tools::KEY_ENV_VARS { + c.env_remove(k); + } + c.env("ANYBOT_HOOK_EVENT", input["hook_event_name"].as_str().unwrap_or("")); + c.env("PATH", crate::cloudbox::tool_path()); + if let Some(h) = dirs::home_dir() { + c.current_dir(h); + } + c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + let mut child = c.spawn().map_err(|e| format!("無法執行:{e}"))?; + if let Some(mut si) = child.stdin.take() { + let _ = si.write_all(input.to_string().as_bytes()); + } + let read = |s: Option>| { + std::thread::spawn(move || { + let mut b = String::new(); + if let Some(mut s) = s { + let _ = s.read_to_string(&mut b); + } + b + }) + }; + let out = read(child.stdout.take().map(|s| Box::new(s) as Box)); + let err = read(child.stderr.take().map(|s| Box::new(s) as Box)); + let t0 = Instant::now(); + let code = loop { + if let Ok(Some(st)) = child.try_wait() { + break st.code(); + } + if t0.elapsed() > Duration::from_secs(secs) { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("超過 {secs} 秒沒有結束,停掉了")); + } + std::thread::sleep(Duration::from_millis(20)); + }; + Ok(Ran { code, out: out.join().unwrap_or_default(), err: err.join().unwrap_or_default() }) +} + +/// What the hooks of one event said, put together. +#[derive(Debug, Default, PartialEq)] +pub struct Said { + /// Blocked, and why (exit 2, or "decision": "block"). + pub block: Option, + /// PreToolUse's word: "allow", "ask" or "deny" (the strictest of them), and why. + pub permission: Option<(String, String)>, + /// PreToolUse: the tool's arguments to run with instead. + pub input: Option, + /// For the model: what a hook added. + pub context: String, + /// PostToolUse: the result the bot reads instead. + pub output: Option, + /// "continue": false — the whole turn stops, and why. + pub stop: Option, +} + +fn stricter(a: &str, b: &str) -> bool { + let rank = |p: &str| match p { + "deny" => 3, + "ask" => 2, + "allow" => 1, + _ => 0, + }; + rank(b) > rank(a) +} + +/// Put one hook's answer into what was said so far. +fn take(event: &str, ran: Ran, said: &mut Said) -> Result<(), String> { + match ran.code { + Some(0) => {} + Some(2) => { + let why = if ran.err.trim().is_empty() { ran.out.trim().to_string() } else { ran.err.trim().to_string() }; + said.block = Some(match said.block.take() { + Some(b) => format!("{b}\n{why}"), + None => why, + }); + return Ok(()); + } + other => return Err(format!("結束碼 {}:{}", other.map(|c| c.to_string()).unwrap_or_else(|| "(被訊號停掉)".into()), ran.err.trim().chars().take(300).collect::())), + } + let text = ran.out.trim(); + if !text.starts_with('{') { + if matches!(event, "UserPromptSubmit" | "SessionStart") && !text.is_empty() { + push_context(said, text); + } + return Ok(()); + } + let v: Value = serde_json::from_str(text).map_err(|e| format!("回的 JSON 看不懂:{e}"))?; + let s = |v: &Value| v.as_str().unwrap_or("").trim().to_string(); + if v["continue"] == json!(false) { + said.stop = Some(s(&v["stopReason"])); + } + let specific = &v["hookSpecificOutput"]; + let reason = [s(&specific["permissionDecisionReason"]), s(&v["reason"])].into_iter().find(|r| !r.is_empty()).unwrap_or_default(); + // PreToolUse: its permission (the older "decision": approve / block too). + let permission = match (s(&specific["permissionDecision"]).as_str(), s(&v["decision"]).as_str(), event) { + (p @ ("allow" | "ask" | "deny"), _, _) => Some(p.to_string()), + (_, "approve", "PreToolUse") => Some("allow".into()), + (_, "block", "PreToolUse") => Some("deny".into()), + _ => None, + }; + if let Some(p) = permission { + if said.permission.as_ref().is_none_or(|(had, _)| stricter(had, &p)) { + said.permission = Some((p, reason.clone())); + } + } else if s(&v["decision"]) == "block" { + said.block = Some(match said.block.take() { + Some(b) => format!("{b}\n{reason}"), + None => reason.clone(), + }); + } + if specific["updatedInput"].is_object() { + said.input = Some(specific["updatedInput"].clone()); + } + for k in ["updatedToolOutput", "updatedMCPToolOutput"] { + if let Some(t) = specific[k].as_str() { + said.output = Some(t.to_string()); + } else if !specific[k].is_null() { + said.output = Some(specific[k].to_string()); + } + } + let extra = s(&specific["additionalContext"]); + if !extra.is_empty() { + push_context(said, &extra); + } + Ok(()) +} + +fn push_context(said: &mut Said, text: &str) { + if !said.context.is_empty() { + said.context.push('\n'); + } + said.context.push_str(text); +} + +impl Hooks { + /// Run this event's hooks (for this tool) with `input`, one after another: each PreToolUse + /// hook sees the arguments the one before it changed. A hook's own trouble goes to the log. + pub fn fire(&self, event: &str, tool: Option<&str>, mut input: Value) -> Said { + let mut said = Said::default(); + for h in self.matching(event, tool) { + input["hook_event_name"] = json!(event); + let r = run_one(&h, &input).and_then(|ran| take(event, ran, &mut said)); + if let Err(e) = r { + log::warn!("hooks:{event} 的「{}」出錯,照常做:{e}", if h.kind == "http" { &h.url } else { &h.command }); + } + if let Some(new) = said.input.clone() { + input["tool_input"] = new; + } + // (Once it is denied or blocked, the rest don't need to run.) + if said.block.is_some() || said.permission.as_ref().is_some_and(|(p, _)| p == "deny") || said.stop.is_some() { + break; + } + } + said + } +} + +#[cfg(test)] +pub fn test_hooks() -> &'static std::sync::Mutex> { + static T: std::sync::OnceLock>> = std::sync::OnceLock::new(); + T.get_or_init(Default::default) +} + +/// What every event's input starts with: whose turn (Claude Code's session_id is the bot's chat). +pub fn base(bot_id: u64, bot: &str) -> Value { + json!({"session_id": format!("anybot-bot-{bot_id}"), "bot_id": bot_id, "bot": bot, "cwd": dirs::home_dir().map(|h| h.display().to_string()).unwrap_or_default()}) +} + +/// A tool's arguments as hooks see them: AnyBot's, plus Claude Code's names for the same thing. +pub fn tool_input(args: &str) -> Value { + let mut v = crate::tools::args_of(args); + if let Some(o) = v.as_object_mut() { + for (ours, theirs) in [("path", "file_path"), ("old_text", "old_string"), ("new_text", "new_string")] { + if let Some(x) = o.get(ours).cloned() { + o.entry(theirs).or_insert(x); + } + } + } + v +} + +/// The arguments a PreToolUse hook gave, back in AnyBot's names. +pub fn args_back(v: &Value) -> String { + let mut v = v.clone(); + if let Some(o) = v.as_object_mut() { + for (ours, theirs) in [("path", "file_path"), ("old_text", "old_string"), ("new_text", "new_string")] { + if let Some(x) = o.remove(theirs) { + o.insert(ours.into(), x); + } + } + } + v.to_string() +} + +/// Notification: AnyBot tells the person something (on a thread of its own; nothing waits). +pub fn notification(title: &str, body: &str, bot_id: u64) { + let (title, body) = (title.to_string(), body.to_string()); + std::thread::spawn(move || { + let h = Hooks::load(); + if !h.matching("Notification", None).is_empty() { + let mut input = base(bot_id, ""); + input["title"] = json!(title); + input["message"] = json!(body); + h.fire("Notification", None, input); + } + }); +} + +// ---------- manage_hooks: the person's file, from the chat ---------- + +pub fn manage_spec() -> Value { + json!({"name": MANAGE_TOOL, "description": "List, add or remove the person's hooks (their own programs AnyBot runs at set points: PreToolUse, PostToolUse, UserPromptSubmit, Stop, SessionStart, Notification — Claude Code's format). Adding or removing is shown to the person and asked every time. A hook runs on the brain, outside the bots' sandbox.", + "parameters": {"type": "object", "properties": { + "action": {"type": "string", "enum": ["list", "add", "remove"]}, + "event": {"type": "string", "enum": EVENTS}, + "matcher": {"type": "string", "description": "Which tools (a regular expression over the name, e.g. shell|edit_file; Claude Code's Bash, Edit work too). Empty: all."}, + "command": {"type": "string", "description": "add/remove: the command (it gets the event as JSON on its input; exit 2 blocks, its error output is why)."}, + "url": {"type": "string", "description": "add/remove: instead of a command, an address the event is POSTed to."}, + "timeout": {"type": "integer", "description": "Seconds (default 60)."}}, + "required": ["action"]}}) +} + +/// What a manage_hooks call would change. +#[derive(Clone, Debug, PartialEq)] +pub enum Change { + List, + Add { event: String, matcher: String, hook: Hook }, + Remove { event: String, hook: Hook }, +} + +pub fn parse_change(args: &str) -> Result { + let v = crate::tools::args_of(args); + let s = |k: &str| v[k].as_str().unwrap_or("").trim().to_string(); + let action = s("action"); + if action == "list" || action.is_empty() { + return Ok(Change::List); + } + let event = s("event"); + if !EVENTS.contains(&event.as_str()) { + return Err(format!("event 要是 {} 其中一個", EVENTS.join("、"))); + } + let hook = if !s("url").is_empty() { Hook { kind: "http".into(), command: String::new(), url: s("url"), headers: BTreeMap::new(), timeout: v["timeout"].as_u64() } } else { Hook { kind: "command".into(), command: s("command"), url: String::new(), headers: BTreeMap::new(), timeout: v["timeout"].as_u64() } }; + if hook.command.is_empty() && hook.url.is_empty() { + return Err("要給 command(指令)或 url(網址)".into()); + } + match action.as_str() { + "add" => { + let matcher = s("matcher"); + if !matcher.is_empty() && matcher != "*" && regex::Regex::new(&matcher).is_err() { + return Err(format!("matcher「{matcher}」不是有效的正規表示式")); + } + Ok(Change::Add { event, matcher, hook }) + } + "remove" => Ok(Change::Remove { event, hook }), + other => Err(format!("看不懂 action「{other}」:list、add 或 remove")), + } +} + +/// What the person is asked before a change. +pub fn change_question(c: &Change) -> Option { + let what = |h: &Hook| if h.kind == "http" { format!("把事件 POST 到 {}", h.url) } else { format!("執行指令:{}", crate::secrets::mask(&h.command)) }; + match c { + Change::List => None, + Change::Add { event, matcher, hook } => Some(format!( + "新增一個 hook:每次「{event}」{}時,在大腦上(Bot 的沙盒外,用你的身分){}。它可以擋下或改掉 Bot 的步驟。", + if matcher.is_empty() || matcher == "*" { String::new() } else { format!("(工具符合「{matcher}」)") }, + what(hook) + )), + Change::Remove { event, hook } => Some(format!("移除「{event}」的 hook:{}", what(hook))), + } +} + +/// Carry out a change on the person's file (the admin's isn't touched). The answer for the bot. +pub fn apply_change(c: &Change) -> Result { + let p = mine_path(); + let mut cfg = read_config(&p)?; + let text = match c { + Change::List => return Ok(list_text(&Hooks { admin: read_config(&admin_path()).unwrap_or_default(), mine: cfg })), + Change::Add { event, matcher, hook } => { + let groups = cfg.hooks.entry(event.clone()).or_default(); + match groups.iter_mut().find(|g| g.matcher == *matcher) { + Some(g) if g.hooks.contains(hook) => return Ok("已經有一樣的 hook 了,沒有再加。".into()), + Some(g) => g.hooks.push(hook.clone()), + None => groups.push(Group { matcher: matcher.clone(), hooks: vec![hook.clone()] }), + } + format!("已新增「{event}」的 hook。") + } + Change::Remove { event, hook } => { + let same = |h: &Hook| (hook.kind == "http" && h.url == hook.url) || (hook.kind != "http" && h.command == hook.command); + let groups = cfg.hooks.entry(event.clone()).or_default(); + let before: usize = groups.iter().map(|g| g.hooks.len()).sum(); + for g in groups.iter_mut() { + g.hooks.retain(|h| !same(h)); + } + groups.retain(|g| !g.hooks.is_empty()); + let after: usize = groups.iter().map(|g| g.hooks.len()).sum(); + if cfg.hooks.get(event).is_some_and(|g| g.is_empty()) { + cfg.hooks.remove(event); + } + if before == after { + return Err(format!("「{event}」沒有這個 hook(action=list 看有哪些)")); + } + format!("已移除「{event}」的 hook。") + } + }; + if let Some(d) = p.parent() { + std::fs::create_dir_all(d).map_err(|e| e.to_string())?; + } + std::fs::write(&p, serde_json::to_string_pretty(&cfg).unwrap_or_default()).map_err(|e| format!("寫不進 {}:{e}", p.display()))?; + Ok(text) +} + +/// Every hook, for the bot (and /doctor's count). +pub fn list_text(h: &Hooks) -> String { + let mut s = String::new(); + for (who, c) in [("管理員的(改不了)", &h.admin), ("使用者的", &h.mine)] { + for (event, groups) in &c.hooks { + for g in groups { + for hook in &g.hooks { + let what = if hook.kind == "http" { format!("POST {}", hook.url) } else { crate::secrets::mask(&hook.command).into_owned() }; + s.push_str(&format!("\n- {who}「{event}」{}:{what}", if g.matcher.is_empty() { String::new() } else { format!("({})", g.matcher) })); + } + } + } + } + if s.is_empty() { + format!("還沒有 hook。使用者的檔案在 {}。", mine_path().display()) + } else { + format!("目前的 hook:{s}") + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + pub(crate) fn cmd(event: &str, matcher: &str, command: &str) -> Hooks { + let mut c = Config::default(); + c.hooks.insert(event.into(), vec![Group { matcher: matcher.into(), hooks: vec![Hook { kind: "command".into(), command: command.into(), url: String::new(), headers: BTreeMap::new(), timeout: Some(10) }] }]); + Hooks { admin: Config::default(), mine: c } + } + + fn pre(h: &Hooks, tool: &str, args: Value) -> Said { + let mut input = base(1, "Master"); + input["tool_name"] = json!(tool); + input["tool_input"] = tool_input(&args.to_string()); + h.fire("PreToolUse", Some(tool), input) + } + + /// A PreToolUse hook that blocks rm (exit 2, its words the reason), one that changes the + /// arguments, one that only asks; the matcher by AnyBot's or Claude Code's name. + #[test] + fn pre_tool_use_blocks_changes_and_asks() { + let block_rm = cmd("PreToolUse", "Bash", r#"grep -q '"command":"rm ' && { echo '不准刪檔' >&2; exit 2; } || exit 0"#); + let said = pre(&block_rm, "shell", json!({"command": "rm -rf build"})); + assert_eq!(said.block.as_deref(), Some("不准刪檔")); + assert_eq!(pre(&block_rm, "shell", json!({"command": "ls"})), Said::default()); + assert_eq!(pre(&block_rm, "read_file", json!({"path": "a"})), Said::default(), "not its tool"); + let change = cmd("PreToolUse", "shell", r#"echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{"command":"ls -la"}}}'"#); + let said = pre(&change, "shell", json!({"command": "ls"})); + assert_eq!(said.input, Some(json!({"command": "ls -la"}))); + assert_eq!(said.permission.as_ref().map(|p| p.0.as_str()), Some("allow")); + let asks = cmd("PreToolUse", "Edit|Write", r#"echo '{"hookSpecificOutput":{"permissionDecision":"ask","permissionDecisionReason":"改檔前問我"}}'"#); + assert_eq!(pre(&asks, "edit_file", json!({"path": "a", "new_text": "x"})).permission, Some(("ask".into(), "改檔前問我".into()))); + assert_eq!(args_back(&json!({"file_path": "b.txt", "new_string": "y"})), json!({"path": "b.txt", "new_text": "y"}).to_string()); + } + + /// A hook's own trouble (a crash, a timeout, nonsense) changes nothing. + #[test] + fn a_broken_hook_is_ignored() { + assert_eq!(pre(&cmd("PreToolUse", "", "exit 7"), "shell", json!({"command": "ls"})), Said::default()); + assert_eq!(pre(&cmd("PreToolUse", "", "echo '{not json'"), "shell", json!({"command": "ls"})), Said::default()); + let mut slow = cmd("PreToolUse", "", "sleep 5"); + slow.mine.hooks.get_mut("PreToolUse").unwrap()[0].hooks[0].timeout = Some(1); + let t0 = Instant::now(); + assert_eq!(pre(&slow, "shell", json!({"command": "ls"})), Said::default()); + assert!(t0.elapsed() < Duration::from_secs(4)); + assert!(!matches("[", "shell") && matches("", "x") && matches("mcp__.*", "mcp__gitlab__get")); + } + + /// UserPromptSubmit's text is context; Stop's block keeps the turn going; PostToolUse can + /// change what the bot reads. + #[test] + fn prompt_stop_and_post_tool() { + let said = cmd("UserPromptSubmit", "", "echo '今天是盤點日'").fire("UserPromptSubmit", None, base(1, "M")); + assert_eq!(said.context, "今天是盤點日"); + let said = cmd("Stop", "", r#"grep -q '"stop_hook_active":true' && exit 0; echo '{"decision":"block","reason":"還沒跑測試"}'"#).fire("Stop", None, json!({"stop_hook_active": false})); + assert_eq!(said.block.as_deref(), Some("還沒跑測試")); + let said = cmd("Stop", "", r#"grep -q '"stop_hook_active":true' && exit 0; echo '{"decision":"block","reason":"還沒跑測試"}'"#).fire("Stop", None, json!({"stop_hook_active": true})); + assert_eq!(said.block, None); + let said = cmd("PostToolUse", "shell", r#"echo '{"hookSpecificOutput":{"updatedToolOutput":"(已遮掉)","additionalContext":"輸出裡有密碼"}}'"#).fire("PostToolUse", Some("shell"), json!({})); + assert_eq!((said.output.as_deref(), said.context.as_str()), (Some("(已遮掉)"), "輸出裡有密碼")); + } + + #[test] + fn manage_hooks_changes_the_persons_file() { + let _ = std::fs::remove_file(mine_path()); + let add = parse_change(&json!({"action": "add", "event": "PreToolUse", "matcher": "shell", "command": "~/bin/check.sh"}).to_string()).unwrap(); + assert!(change_question(&add).unwrap().contains("~/bin/check.sh")); + apply_change(&add).unwrap(); + assert!(apply_change(&add).unwrap().contains("已經有")); + let h = Hooks::load(); + assert_eq!(h.matching("PreToolUse", Some("shell")).len(), 1); + assert!(list_text(&h).contains("check.sh")); + let rm = parse_change(&json!({"action": "remove", "event": "PreToolUse", "command": "~/bin/check.sh"}).to_string()).unwrap(); + apply_change(&rm).unwrap(); + assert!(Hooks::load().is_empty()); + assert!(parse_change(&json!({"action": "add", "event": "Whenever", "command": "x"}).to_string()).is_err()); + assert!(parse_change(&json!({"action": "add", "event": "Stop"}).to_string()).is_err()); + let _ = std::fs::remove_file(mine_path()); + } +} diff --git a/src/main.rs b/src/main.rs index 3f51aeb..2e0c97a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -80,6 +80,7 @@ mod net; mod doctor; mod outputs; mod gate; +mod hooks; mod usage; #[cfg(test)] mod testkit; diff --git a/src/profile.rs b/src/profile.rs index 82b98f2..8f39e53 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -43,7 +43,7 @@ pub fn ability_of(tool: &str) -> Option<&'static str> { "create_routine" | "update_routine" | "delete_routine" | "list_routines" | "run_routine_now" => "routines", "write_page" | "read_page" | "list_pages" => "pages", "message_bot" | "ask_bot" | "teach_skill" | "list_bots" => "team", - "create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" | crate::mcp::MANAGE_TOOL => "admin", + "create_bot" | "update_bot" | "update_settings" | "create_group" | "move_to_group" | "rename_group" | "delete_group" | "delete_skill" | "skill_install" | crate::mcp::MANAGE_TOOL | crate::hooks::MANAGE_TOOL => "admin", _ => return None, }) } diff --git a/src/remote.rs b/src/remote.rs index 593087e..a84a62c 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -2167,6 +2167,8 @@ pub fn palette_json(p: &crate::theme::Palette) -> Value { /// A notification on the person's phones (through the relay; phones that turned them on). pub fn notify(kind: Notice, title: &str, body: &str, bot: u64) { + // Hooks' Notification: the person's own programs hear it too (on a thread; nothing waits). + crate::hooks::notification(title, body, bot); let s = hub().settings(); if s.relay_url.is_empty() || s.host_token.is_empty() { return;