2026-11-17 04:59:21 +00:00
//! 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 < String , String > ,
#[ serde(default, skip_serializing_if = " Option::is_none " ) ]
pub timeout : Option < u64 > ,
}
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 < Hook > ,
}
#[ derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default) ]
pub struct Config {
#[ serde(default) ]
pub hooks : BTreeMap < String , Vec < Group > > ,
}
/// 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 < Config , String > {
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 < Hook > {
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 < i32 > ,
out : String ,
err : String ,
}
fn run_one ( h : & Hook , input : & Value ) -> Result < Ran , String > {
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} " ) ) ? ;
2026-11-17 06:07:48 +00:00
// (On a thread: a hook that never reads its input mustn't hold the turn past its timeout.)
2026-11-17 04:59:21 +00:00
if let Some ( mut si ) = child . stdin . take ( ) {
2026-11-17 06:07:48 +00:00
let text = input . to_string ( ) ;
std ::thread ::spawn ( move | | {
let _ = si . write_all ( text . as_bytes ( ) ) ;
} ) ;
2026-11-17 04:59:21 +00:00
}
let read = | s : Option < Box < dyn Read + Send > > | {
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 < dyn Read + Send > ) ) ;
let err = read ( child . stderr . take ( ) . map ( | s | Box ::new ( s ) as Box < dyn Read + Send > ) ) ;
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 < String > ,
/// 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 < Value > ,
/// For the model: what a hook added.
pub context : String ,
/// PostToolUse: the result the bot reads instead.
pub output : Option < String > ,
/// "continue": false — the whole turn stops, and why.
pub stop : Option < String > ,
}
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 ::< String > ( ) ) ) ,
}
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 < std ::collections ::HashMap < u64 , Hooks > > {
static T : std ::sync ::OnceLock < std ::sync ::Mutex < std ::collections ::HashMap < u64 , Hooks > > > = 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 < Change , String > {
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 < String > {
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 < String , String > {
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 " ) ) ;
2026-11-17 06:07:48 +00:00
// A big event to a hook that never reads it: its timeout still ends it.
let t0 = Instant ::now ( ) ;
assert_eq! ( pre ( & slow , " shell " , json! ( { " command " : " x " . repeat ( 400_000 ) } ) ) , Said ::default ( ) ) ;
assert! ( t0 . elapsed ( ) < Duration ::from_secs ( 4 ) ) ;
2026-11-17 04:59:21 +00:00
}
/// 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 ( ) ) ;
}
}