fix: 獨立審查找到的問題(一):手機通知的允許、hooks、Linux 沙盒

手機通知:
- 一個帶 #answer=once 的連結就能放行正在等的請求:沒帶鑰匙的連結不回答任何事。
- 舊通知可能答到新請求(同一步連問三次編號相同、有些模型每輪從 0 編):每個請求一把隨機鑰匙;通知也不能回答「需要處理」和問題卡;整個請求放不進通知(多行的指令)就不給按鈕。
- 停在登入畫面時按通知,回答會不見;兩指放大被當成鍵盤;換對話時舊訊息一起滑進來。
Hooks:
- hook 的 ask 只有在電腦上的步驟有用,連接器、App 操作、傳檔案…直接做了:現在都會問。
- hook 留一個背景程式就把一輪卡住;逾時只殺 shell、它啟動的還在跑。
- hook 改 AnyBot 欄位名(path)會被舊的 file_path 蓋回去。
- 打開一律放行、--approve once 會替人答應新增 hook。
- 管理員的 hook 改成最後跑:看得到個人 hook 改過的參數,它的拒絕算數。
Linux 沙盒:私密資料夾寫成相對路徑時,在沙盒裡對到別的資料夾,等於沒擋。

已驗證:cargo test 613 通過、clippy -D warnings 乾淨。未驗證:手機網頁那幾項沒有自動測試,要實機看。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-17 14:21:09 +08:00
parent 35807099bb
commit 571d07596e
6 changed files with 112 additions and 28 deletions

View File

@ -842,7 +842,7 @@ try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () =
const S = { sending: [], voice: {}, const S = { sending: [], voice: {},
relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "", relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "",
version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner", version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner",
prevShown: 0, answer: null, sc: "", prevShown: 0, prevFirst: "", answer: null, sc: "",
open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false, open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false,
chatSig: "", file: null, chatSig: "", file: null,
search: "", size: [0, 0], right: false, search: "", size: [0, 0], right: false,
@ -1289,7 +1289,7 @@ function chatHead() {
} }
$("island").onclick = () => go("details", {bot: S.open}); $("island").onclick = () => go("details", {bot: S.open});
function openChat(id) { function openChat(id) {
if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; $("msgs").innerHTML = ""; } if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; $("msgs").innerHTML = ""; }
S.open = id; S.open = id;
// Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the // Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the
// page's ink (the default), "bot" the bot's colour, "black". (An older AnyBot sends no field: its colour.) // page's ink (the default), "bot" the bot's colour, "black". (An older AnyBot sends no field: its colour.)
@ -1419,7 +1419,10 @@ function renderMsgs() {
let h = ""; let h = "";
// A message that arrived since the last draw slides up into place; the whole history on // A message that arrived since the last draw slides up into place; the whole history on
// opening a chat draws plain (no animation on every old message). // opening a chat draws plain (no animation on every old message).
const freshFrom = S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length; // (Another conversation of the same bot — its first message differs — draws plain too.)
const first = S.msgs.length ? String(S.msgs[0].at || "") + (S.msgs[0].text || "").slice(0, 40) : "";
const same = first === S.prevFirst; S.prevFirst = first;
const freshFrom = same && S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length;
S.prevShown = S.msgs.length; S.prevShown = S.msgs.length;
const fr = (i) => (i >= freshFrom ? " fresh" : ""); const fr = (i) => (i >= freshFrom ? " fresh" : "");
S.msgs.forEach((m, i) => { S.msgs.forEach((m, i) => {
@ -3406,7 +3409,8 @@ function openFromHash() {
// Tapping 允許/拒絕 on a notification: answer it once the token is in place. // Tapping 允許/拒絕 on a notification: answer it once the token is in place.
const ans = h.get("answer"); const ans = h.get("answer");
// (With the request it was about: one that changed since is not answered by an old banner.) // (With the request it was about: one that changed since is not answered by an old banner.)
if (ans && b && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans, call: h.get("call") || ""}; // (A link with no key answers nothing: only a banner's own buttons carry one.)
if (ans && b && h.get("call") && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans, call: h.get("call")};
const sc = new URLSearchParams(location.search).get("sc"); const sc = new URLSearchParams(location.search).get("sc");
if (sc) S.sc = sc; if (sc) S.sc = sc;
if (location.hash || location.search) history.replaceState(null, "", location.pathname); if (location.hash || location.search) history.replaceState(null, "", location.pathname);
@ -3415,13 +3419,18 @@ openFromHash();
if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => { if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => {
const d = e.data && e.data.open; if (!d) return; const d = e.data && e.data.open; if (!d) return;
if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; } if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; }
if (d.answer && S.token && d.bot) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask || ""}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message)); if (d.answer && d.ask && d.bot) {
if (d.bot) go("chat", {bot: +d.bot}); // (Not signed in yet: kept, and sent once the phone is — apply.)
if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
else S.answer = {bot: +d.bot, answer: d.answer, call: d.ask};
}
if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot;
}); });
// iOS: the keyboard floats over the page instead of shrinking it; measure it and lift the composer. // iOS: the keyboard floats over the page instead of shrinking it; measure it and lift the composer.
if (window.visualViewport) { if (window.visualViewport) {
const kb = () => { const kb = () => {
const k = Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop)); // (Zoomed in with two fingers the visible part is smaller too: that isn't a keyboard.)
const k = visualViewport.scale > 1.01 ? 0 : Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop));
document.documentElement.style.setProperty("--kb", k + "px"); document.documentElement.style.setProperty("--kb", k + "px");
}; };
visualViewport.addEventListener("resize", kb); visualViewport.addEventListener("resize", kb);

View File

@ -1756,7 +1756,7 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow {
hooks.fire("PreToolUse", Some(&call.name), input) hooks.fire("PreToolUse", Some(&call.name), input)
}; };
let call = match &hook_word.input { let call = match &hook_word.input {
Some(v) => ToolCall { args: crate::hooks::args_back(v), ..call }, Some(v) => ToolCall { args: crate::hooks::args_back(v, &call.args), ..call },
None => 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()); 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());
@ -1874,6 +1874,20 @@ fn run_call(t: CallTurn<'_>, asked: ToolCall) -> Flow {
browser: Default::default(), browser: Default::default(),
}; };
let tool = steps::tool_for(&s); let tool = steps::tool_for(&s);
// A hook's 「ask」: OnComputer puts it with its own question; every other tool asks here
// (a connector already allowed, an app action, a file sent out… would have gone ahead).
if tool.name() != "OnComputer" {
if let Some(why) = s.hook_word.permission.clone().filter(|(p, _)| p == "ask").map(|(_, w)| w) {
let answer = s.ask_person(ApprovalKind::Action, format!("{}(你的 hook 要先問:{})", s.what(), if why.is_empty() { "沒有說原因" } else { why.as_str() }), String::new());
if s.cancel.load(Ordering::Relaxed) {
return Flow::End;
}
if answer == ApprovalAnswer::Reject {
s.finish("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。", ToolStatus::Denied, None);
return Flow::Next;
}
}
}
log::debug!("{} 由 {} 處理", s.call.name, tool.name()); log::debug!("{} 由 {} 處理", s.call.name, tool.name());
tool.run(&mut s) tool.run(&mut s)
} }

View File

@ -215,6 +215,10 @@ pub struct App {
doctor_out: Arc<Mutex<Vec<(u64, String)>>>, doctor_out: Arc<Mutex<Vec<(u64, String)>>>,
/// Lines for a bot's chat that work on another thread finished (/rewind's files…). /// Lines for a bot's chat that work on another thread finished (/rewind's files…).
later_notes: Arc<Mutex<Vec<(u64, String)>>>, later_notes: Arc<Mutex<Vec<(u64, String)>>>,
/// The key a phone banner's 允許/拒絕 must carry to answer a bot's waiting request: made
/// new for every request (the tool call's id repeats — one step may ask three times, and
/// some models number their calls from 0 every turn), and not guessable from a link.
pub(crate) ask_keys: HashMap<u64, String>,
/// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)). /// 「/compact」 summaries finished on their thread: (bot, (messages replaced, summary, first kept message's time)).
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
compact_out: Arc<Mutex<Vec<(u64, Option<(usize, Message, i64)>)>>>, compact_out: Arc<Mutex<Vec<(u64, Option<(usize, Message, i64)>)>>>,
@ -498,6 +502,7 @@ impl App {
strangers: Default::default(), strangers: Default::default(),
doctor_out: Default::default(), doctor_out: Default::default(),
later_notes: Default::default(), later_notes: Default::default(),
ask_keys: Default::default(),
compact_out: Default::default(), compact_out: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() }, managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false, settings_was_open: false,
@ -2627,7 +2632,7 @@ impl App {
self.enable_direct_mode(); self.enable_direct_mode();
self.state.always_approve = true; self.state.always_approve = true;
// What the person's own turns are waiting on now goes ahead. // What the person's own turns are waiting on now goes ahead.
let waiting: Vec<u64> = self.approvals.iter().filter(|(id, a)| !self.strangers.contains(id) && crate::always::answer_for(a.kind).is_some()).map(|(id, _)| *id).collect(); let waiting: Vec<u64> = self.approvals.iter().filter(|(id, a)| !self.strangers.contains(id) && a.tool != crate::hooks::MANAGE_TOOL && crate::always::answer_for(a.kind).is_some()).map(|(id, _)| *id).collect();
for id in waiting { for id in waiting {
self.answer(ctx, id, ApprovalAnswer::Once); self.answer(ctx, id, ApprovalAnswer::Once);
} }
@ -4169,6 +4174,8 @@ impl App {
/// attention (the Dock icon bounces when AnyBot isn't in front, and the 提示音 rings). /// attention (the Dock icon bounces when AnyBot isn't in front, and the 提示音 rings).
fn on_new_approval(&mut self, ctx: &egui::Context, bot_id: u64) { fn on_new_approval(&mut self, ctx: &egui::Context, bot_id: u64) {
self.popup_hidden.remove(&bot_id); self.popup_hidden.remove(&bot_id);
let key = crate::httpd::random_hex(16);
self.ask_keys.insert(bot_id, key.clone());
// (A brain on a server has nobody to hear it.) // (A brain on a server has nobody to hear it.)
let chime = !self.demo && !self.headless && self.state.alert_sound; let chime = !self.demo && !self.headless && self.state.alert_sound;
if chime { if chime {
@ -4180,6 +4187,9 @@ impl App {
if self.state.notify && self.away() { if self.state.notify && self.away() {
if let (Some(b), Some(a)) = (self.state.bot(bot_id), self.approvals.get(&bot_id)) { if let (Some(b), Some(a)) = (self.state.bot(bot_id), self.approvals.get(&bot_id)) {
let mut what = a.reason.split('\n').next().unwrap_or("").to_string(); let mut what = a.reason.split('\n').next().unwrap_or("").to_string();
// 允許 on a banner must be about all of it: a request that doesn't fit there
// whole (a command of several lines) is answered in the chat.
let whole = a.reason.lines().filter(|l| !l.starts_with("(在 ")).count() <= 1 && what.chars().count() <= 170;
// 「{callee} 需要你」 for a step only the person can do. // 「{callee} 需要你」 for a step only the person can do.
let mut title = if a.kind == ApprovalKind::Handoff { format!("{}:需要你", b.name) } else { format!("{} 需要你允許", b.name) }; let mut title = if a.kind == ApprovalKind::Handoff { format!("{}:需要你", b.name) } else { format!("{} 需要你允許", b.name) };
if a.kind == ApprovalKind::Question { if a.kind == ApprovalKind::Question {
@ -4192,8 +4202,8 @@ impl App {
} }
// 允許/拒絕 on the banner only for a request to allow (a question, or a step // 允許/拒絕 on the banner only for a request to allow (a question, or a step
// only the person can do, opens the chat). // only the person can do, opens the chat).
if matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer) { if whole && a.tool != crate::hooks::MANAGE_TOOL && matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer) {
crate::remote::notify_approval(&title, &what, bot_id, &a.call_id); crate::remote::notify_approval(&title, &what, bot_id, &key);
} else { } else {
crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id); crate::remote::notify(crate::remote::Notice::Need, &title, &what, bot_id);
} }
@ -6175,7 +6185,8 @@ impl App {
// an app action waiting on its card is answered too — it used to wait to the limit.) // an app action waiting on its card is answered too — it used to wait to the limit.)
if let Some(a) = app.approvals.get(&id) { if let Some(a) = app.approvals.get(&id) {
let (kind, tool, reason) = (a.kind, a.tool.clone(), a.reason.clone()); let (kind, tool, reason) = (a.kind, a.tool.clone(), a.reason.clone());
let yes = opts.approve && crate::always::answer_for(kind).is_some(); // (A hook change is the person's to allow: it would run outside the sandbox from then on.)
let yes = opts.approve && tool != crate::hooks::MANAGE_TOOL && crate::always::answer_for(kind).is_some();
if json { if json {
line(serde_json::json!({"type": "approval", "tool": tool, "reason": reason, "answer": if yes { "once" } else { "reject" }})); line(serde_json::json!({"type": "approval", "tool": tool, "reason": reason, "answer": if yes { "once" } else { "reject" }}));
} else { } else {

View File

@ -613,7 +613,9 @@ impl App {
Cmd::Answer { bot, answer, text, call } => { Cmd::Answer { bot, answer, text, call } => {
// From a notification banner: only the request it showed (it may have been // From a notification banner: only the request it showed (it may have been
// answered since, and another one be waiting). // answered since, and another one be waiting).
if !call.is_empty() && self.approvals.get(&bot).map(|a| a.call_id.as_str()) != Some(call.as_str()) { // (And only a request to allow: 「允許」 on a hand-off would mean 「我完成了」.)
let allowable = self.approvals.get(&bot).is_some_and(|a| matches!(a.kind, ApprovalKind::Action | ApprovalKind::EnableTools | ApprovalKind::EnableThisComputer));
if !call.is_empty() && !(allowable && self.ask_keys.get(&bot) == Some(&call)) {
self.goal_note(bot, "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。"); self.goal_note(bot, "通知上的「允許/拒絕」沒有用上:那個請求已經不在等了(回答過,或換成了別的)。打開聊天看現在在等什麼。");
return; return;
} }
@ -1853,7 +1855,9 @@ mod phone_act_tests {
let bot = app.state.bots[0].id; let bot = app.state.bots[0].id;
let wait = |app: &mut App, call: &str| { let wait = |app: &mut App, call: &str| {
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
app.approvals.insert(bot, crate::providers::Approval { call_id: call.into(), tool: "shell".into(), reason: "刪除 build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action }); // (The same tool call asking again, as one step does: a new key each time.)
app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "shell".into(), reason: "刪除 build".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Action });
app.ask_keys.insert(bot, call.into());
rx rx
}; };
let rx = wait(&mut app, "call-2"); let rx = wait(&mut app, "call-2");
@ -1863,6 +1867,12 @@ mod phone_act_tests {
assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上"))); assert!(app.state.bot(bot).unwrap().messages.iter().any(|m| m.note && m.text.contains("沒有用上")));
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "call-2".into() }); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "call-2".into() });
assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once))); assert!(matches!(rx.try_recv(), Ok(ApprovalAnswer::Once)));
// A hand-off isn't answered from a banner, even with its key.
let (tx, rx2) = std::sync::mpsc::channel();
app.approvals.insert(bot, crate::providers::Approval { call_id: "c0".into(), tool: "x".into(), reason: "登入".into(), grant: String::new(), reply: tx, kind: ApprovalKind::Handoff });
app.ask_keys.insert(bot, "k".into());
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "once".into(), text: String::new(), call: "k".into() });
assert!(rx2.try_recv().is_err());
// From the app itself (no request id): as before. // From the app itself (no request id): as before.
let rx = wait(&mut app, "call-3"); let rx = wait(&mut app, "call-3");
app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "reject".into(), text: String::new(), call: String::new() }); app.remote_cmd(&ctx, Cmd::Answer { bot, answer: "reject".into(), text: String::new(), call: String::new() });

View File

@ -97,7 +97,8 @@ pub fn read_config(p: &std::path::Path) -> Result<Config, String> {
} }
} }
/// Both files' hooks, the admin's first. /// Both files' hooks. The person's run first and the admin's last: the admin's see the
/// arguments as a personal hook left them, and the strictest word (deny over ask over allow) stands.
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct Hooks { pub struct Hooks {
pub admin: Config, pub admin: Config,
@ -135,7 +136,7 @@ impl Hooks {
/// The hooks for this event (and tool), in order. /// The hooks for this event (and tool), in order.
fn matching(&self, event: &str, tool: Option<&str>) -> Vec<Hook> { fn matching(&self, event: &str, tool: Option<&str>) -> Vec<Hook> {
let mut out = vec![]; let mut out = vec![];
for c in [&self.admin, &self.mine] { for c in [&self.mine, &self.admin] {
for g in c.hooks.get(event).into_iter().flatten() { for g in c.hooks.get(event).into_iter().flatten() {
if tool.is_none_or(|t| matches(&g.matcher, t)) { if tool.is_none_or(|t| matches(&g.matcher, t)) {
out.extend(g.hooks.iter().cloned()); out.extend(g.hooks.iter().cloned());
@ -214,6 +215,11 @@ fn run_one(h: &Hook, input: &Value) -> Result<Ran, String> {
c.current_dir(h); c.current_dir(h);
} }
c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
c.process_group(0);
}
let mut child = c.spawn().map_err(|e| format!("無法執行:{e}"))?; let mut child = c.spawn().map_err(|e| format!("無法執行:{e}"))?;
// (On a thread: a hook that never reads its input mustn't hold the turn past its timeout.) // (On a thread: a hook that never reads its input mustn't hold the turn past its timeout.)
if let Some(mut si) = child.stdin.take() { if let Some(mut si) = child.stdin.take() {
@ -222,14 +228,33 @@ fn run_one(h: &Hook, input: &Value) -> Result<Ran, String> {
let _ = si.write_all(text.as_bytes()); let _ = si.write_all(text.as_bytes());
}); });
} }
// What it printed, gathered as it comes: a program the hook left running keeps the pipe
// open, and the hook's own end must not wait for it.
let read = |s: Option<Box<dyn Read + Send>>| { let read = |s: Option<Box<dyn Read + Send>>| {
std::thread::spawn(move || { let got = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
let mut b = String::new(); let g = got.clone();
if let Some(mut s) = s { let t = std::thread::spawn(move || {
let _ = s.read_to_string(&mut b); let Some(mut s) = s else { return };
let mut chunk = [0u8; 8192];
while let Ok(n) = s.read(&mut chunk) {
if n == 0 {
break;
} }
b let mut g = g.lock().unwrap_or_else(|e| e.into_inner());
}) if g.len() < 1024 * 1024 {
g.extend_from_slice(&chunk[..n]);
}
}
});
(got, t)
};
let text = |(got, t): (std::sync::Arc<std::sync::Mutex<Vec<u8>>>, std::thread::JoinHandle<()>)| {
let t0 = Instant::now();
while !t.is_finished() && t0.elapsed() < Duration::from_millis(300) {
std::thread::sleep(Duration::from_millis(10));
}
let b = got.lock().unwrap_or_else(|e| e.into_inner()).clone();
String::from_utf8_lossy(&b).into_owned()
}; };
let out = read(child.stdout.take().map(|s| Box::new(s) as Box<dyn Read + Send>)); let out = read(child.stdout.take().map(|s| Box::new(s) as Box<dyn Read + Send>));
let err = read(child.stderr.take().map(|s| Box::new(s) as Box<dyn Read + Send>)); let err = read(child.stderr.take().map(|s| Box::new(s) as Box<dyn Read + Send>));
@ -239,13 +264,14 @@ fn run_one(h: &Hook, input: &Value) -> Result<Ran, String> {
break st.code(); break st.code();
} }
if t0.elapsed() > Duration::from_secs(secs) { if t0.elapsed() > Duration::from_secs(secs) {
crate::tools::kill_tree(child.id());
let _ = child.kill(); let _ = child.kill();
let _ = child.wait(); let _ = child.wait();
return Err(format!("超過 {secs} 秒沒有結束,停掉了")); return Err(format!("超過 {secs} 秒沒有結束,停掉了"));
} }
std::thread::sleep(Duration::from_millis(20)); std::thread::sleep(Duration::from_millis(20));
}; };
Ok(Ran { code, out: out.join().unwrap_or_default(), err: err.join().unwrap_or_default() }) Ok(Ran { code, out: text(out), err: text(err) })
} }
/// What the hooks of one event said, put together. /// What the hooks of one event said, put together.
@ -261,7 +287,7 @@ pub struct Said {
pub context: String, pub context: String,
/// PostToolUse: the result the bot reads instead. /// PostToolUse: the result the bot reads instead.
pub output: Option<String>, pub output: Option<String>,
/// "continue": false — the whole turn stops, and why. /// "continue": false, and why: PreToolUse — this step isn't run; UserPromptSubmit — this turn isn't.
pub stop: Option<String>, pub stop: Option<String>,
} }
@ -391,16 +417,20 @@ pub fn tool_input(args: &str) -> Value {
v v
} }
/// The arguments a PreToolUse hook gave, back in AnyBot's names. /// The arguments a PreToolUse hook gave, back in AnyBot's names. A field has two names for the
pub fn args_back(v: &Value) -> String { /// hook (tool_input): whichever of them it changed from `before` (the arguments it was given) counts.
pub fn args_back(v: &Value, before: &str) -> String {
let was = crate::tools::args_of(before);
let mut v = v.clone(); let mut v = v.clone();
if let Some(o) = v.as_object_mut() { if let Some(o) = v.as_object_mut() {
for (ours, theirs) in [("path", "file_path"), ("old_text", "old_string"), ("new_text", "new_string")] { for (ours, theirs) in [("path", "file_path"), ("old_text", "old_string"), ("new_text", "new_string")] {
if let Some(x) = o.remove(theirs) { if let Some(x) = o.remove(theirs) {
if !o.contains_key(ours) || x != was[ours] {
o.insert(ours.into(), x); o.insert(ours.into(), x);
} }
} }
} }
}
v.to_string() v.to_string()
} }
@ -574,7 +604,10 @@ mod tests {
assert_eq!(said.permission.as_ref().map(|p| p.0.as_str()), Some("allow")); 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":"改檔前問我"}}'"#); 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!(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()); assert_eq!(args_back(&json!({"file_path": "b.txt", "new_string": "y"}), "{}"), json!({"path": "b.txt", "new_text": "y"}).to_string());
// The hook changed AnyBot's name and left Claude Code's as it was: its change counts.
assert_eq!(args_back(&json!({"path": "/safe/x", "file_path": "/etc/x"}), r#"{"path":"/etc/x"}"#), json!({"path": "/safe/x"}).to_string());
assert_eq!(args_back(&json!({"path": "/etc/x", "file_path": "/safe/y"}), r#"{"path":"/etc/x"}"#), json!({"path": "/safe/y"}).to_string());
} }
/// A hook's own trouble (a crash, a timeout, nonsense) changes nothing. /// A hook's own trouble (a crash, a timeout, nonsense) changes nothing.
@ -587,6 +620,10 @@ mod tests {
let t0 = Instant::now(); let t0 = Instant::now();
assert_eq!(pre(&slow, "shell", json!({"command": "ls"})), Said::default()); assert_eq!(pre(&slow, "shell", json!({"command": "ls"})), Said::default());
assert!(t0.elapsed() < Duration::from_secs(4)); assert!(t0.elapsed() < Duration::from_secs(4));
// A program the hook leaves running doesn't hold the turn.
let t0 = Instant::now();
assert_eq!(pre(&cmd("PreToolUse", "", "sleep 20 & echo '{}'"), "shell", json!({"command": "ls"})), Said::default());
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(!matches("[", "shell") && matches("", "x") && matches("mcp__.*", "mcp__gitlab__get")); assert!(!matches("[", "shell") && matches("", "x") && matches("mcp__.*", "mcp__gitlab__get"));
// A big event to a hook that never reads it: its timeout still ends it. // A big event to a hook that never reads it: its timeout still ends it.
let t0 = Instant::now(); let t0 = Instant::now();

View File

@ -208,6 +208,9 @@ pub fn wrap(cmd: &str, spec: &Spec) -> Option<std::process::Command> {
if !active() || spec.hidden.is_empty() { if !active() || spec.hidden.is_empty() {
return None; return None;
} }
// (Whole paths: the sandbox starts in the command's work folder, not where AnyBot is.)
let whole = |v: &[PathBuf]| v.iter().map(|p| std::path::absolute(p).unwrap_or_else(|_| p.clone())).collect::<Vec<_>>();
let spec = Spec { hidden: whole(&spec.hidden), readable: whole(&spec.readable), no_write: whole(&spec.no_write), work: std::path::absolute(&spec.work).unwrap_or_else(|_| spec.work.clone()) };
let mut c = std::process::Command::new(helper()?); let mut c = std::process::Command::new(helper()?);
c.arg(ARG).args(spec.to_args()).args(["--", "/bin/sh", "-c", cmd]); c.arg(ARG).args(spec.to_args()).args(["--", "/bin/sh", "-c", cmd]);
Some(c) Some(c)