forked from anthropics/claude-plugins-official
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpretooluse.py
More file actions
executable file
·71 lines (56 loc) · 2.18 KB
/
pretooluse.py
File metadata and controls
executable file
·71 lines (56 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python3
"""PreToolUse hook executor for hookify plugin.
This script is called by Claude Code before any tool executes.
It reads .claude/hookify.*.local.md files and evaluates rules.
"""
import os
import sys
import json
# Add plugin root to Python path for imports
PLUGIN_ROOT = os.environ.get('CLAUDE_PLUGIN_ROOT')
if PLUGIN_ROOT and PLUGIN_ROOT not in sys.path:
sys.path.insert(0, PLUGIN_ROOT)
try:
from core.config_loader import load_rules
from core.rule_engine import RuleEngine
except ImportError as e:
# If imports fail, allow operation and log error
error_msg = {"systemMessage": f"Hookify import error: {e}"}
print(json.dumps(error_msg), file=sys.stdout)
sys.exit(0)
def main():
"""Main entry point for PreToolUse hook."""
try:
# Read input from stdin
input_data = json.load(sys.stdin)
# Determine event type for filtering.
# For PreToolUse, we use tool_name to determine "bash" vs "file" event.
# Default to a sentinel ('pretooluse') so load_rules filters out rules
# declared for other hook events (notably 'stop'). Passing event=None
# bypasses filtering in load_rules and lets stop-event rules fire on
# every PreToolUse, which can deadlock tool loading when a stop rule's
# conditions also match arbitrary PreToolUse input.
tool_name = input_data.get('tool_name', '')
event = 'pretooluse'
if tool_name == 'Bash':
event = 'bash'
elif tool_name in ['Edit', 'Write', 'MultiEdit']:
event = 'file'
# Load rules
rules = load_rules(event=event)
# Evaluate rules
engine = RuleEngine()
result = engine.evaluate_rules(rules, input_data)
# Always output JSON (even if empty)
print(json.dumps(result), file=sys.stdout)
except Exception as e:
# On any error, allow the operation and log
error_output = {
"systemMessage": f"Hookify error: {str(e)}"
}
print(json.dumps(error_output), file=sys.stdout)
finally:
# ALWAYS exit 0 - never block operations due to hook errors
sys.exit(0)
if __name__ == '__main__':
main()