check-mail.sh 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/bin/bash
  2. # hooks/check-mail.sh
  3. # PreToolUse hook - checks for unread inter-session mail
  4. # Runs on every tool call. Silent when inbox is empty.
  5. # Matcher: * (all tools)
  6. #
  7. # Configuration in .claude/settings.json or .claude/settings.local.json:
  8. # {
  9. # "hooks": {
  10. # "PreToolUse": [{
  11. # "matcher": "*",
  12. # "hooks": ["bash hooks/check-mail.sh"]
  13. # }]
  14. # }
  15. # }
  16. MAIL_DB="$HOME/.claude/mail.db"
  17. COOLDOWN_FILE="/tmp/agentmail_check_$$"
  18. COOLDOWN_SECONDS=10
  19. # Skip if disabled for this project
  20. [ -f ".claude/agentmail.disable" ] && exit 0
  21. # Skip if no database exists yet
  22. [ -f "$MAIL_DB" ] || exit 0
  23. # Cooldown: skip if checked recently (within COOLDOWN_SECONDS)
  24. if [ -f "$COOLDOWN_FILE" ]; then
  25. last_check=$(stat -c %Y "$COOLDOWN_FILE" 2>/dev/null || stat -f %m "$COOLDOWN_FILE" 2>/dev/null || echo 0)
  26. now=$(date +%s)
  27. if [ $((now - last_check)) -lt $COOLDOWN_SECONDS ]; then
  28. exit 0
  29. fi
  30. fi
  31. touch "$COOLDOWN_FILE"
  32. PROJECT=$(basename "$PWD" | sed "s/'/''/g")
  33. # Single fast query - count unread
  34. UNREAD=$(sqlite3 "$MAIL_DB" "SELECT COUNT(*) FROM messages WHERE to_project='${PROJECT}' AND read=0;" 2>/dev/null)
  35. # Silent exit if no mail
  36. [ "${UNREAD:-0}" -eq 0 ] && exit 0
  37. # Check for urgent messages
  38. URGENT=$(sqlite3 "$MAIL_DB" "SELECT COUNT(*) FROM messages WHERE to_project='${PROJECT}' AND read=0 AND priority='urgent';" 2>/dev/null)
  39. # Show notification with preview of first 3 messages
  40. echo ""
  41. if [ "${URGENT:-0}" -gt 0 ]; then
  42. echo "=== URGENT MAIL: ${UNREAD} unread (${URGENT} urgent) ==="
  43. else
  44. echo "=== MAIL: ${UNREAD} unread message(s) ==="
  45. fi
  46. sqlite3 -separator ' ' "$MAIL_DB" \
  47. "SELECT ' ' || CASE WHEN priority='urgent' THEN '[!] ' ELSE '' END || 'From: ' || from_project || ' | ' || subject FROM messages WHERE to_project='${PROJECT}' AND read=0 ORDER BY priority DESC, timestamp DESC LIMIT 3;" 2>/dev/null
  48. if [ "$UNREAD" -gt 3 ]; then
  49. echo " ... and $((UNREAD - 3)) more"
  50. fi
  51. echo "Use /mail to read messages."
  52. echo "==="