Token导航 LogoToken导航TokenDH.com
开发敏感数据github未标认证来源可访问许可证需确认审计提醒

hooks-configuration钩子配置

Agent Skill

hooks-configuration 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,816

周安装

78

GitHub Stars

28

下载量

636
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:hooks-configuration(钩子配置)
来源仓库:https://github.com/laurigates/claude-plugins
仓库路径:skills/hooks-configuration
安装命令:
npx skills add https://github.com/laurigates/claude-plugins --skill hooks-configuration
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/laurigates/claude-plugins --skill hooks-configuration

简介

用于处理 GitHub 仓库、Issue、Pull Request 等协作信息。

  • 适合围绕代码变更、项目状态或团队协作进行整理和操作。
  • 通过 npx skills add 命令从指定仓库安装。
  • 支持 Codex、Claude、Cursor、Gemini CLI,安装方式为 github。
  • hooks-configuration 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Claude Code Hooks Configuration

Expert knowledge for configuring and developing Claude Code hooks to automate workflows and enforce best practices.

When to Use This Skill

Use this skill when...Use something else when...
Configuring hook lifecycle events (PreToolUse, PostToolUse, etc.)Writing general shell scripts unrelated to hooks
Blocking dangerous commands or enforcing patternsSetting up CI/CD pipelines (use CI tooling)
Auto-formatting files after editsConfiguring Claude Code settings unrelated to hooks
Injecting context at session or subagent startWriting standalone automation scripts
Setting up PermissionRequest auto-approve/denyManaging project permissions via settings.json directly
Developing prompt or agent hooks for judgment-based decisionsBuilding MCP servers or custom tool integrations

Core Concepts

What Are Hooks? Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. Unlike relying on Claude to "decide" to run something, hooks provide deterministic, guaranteed execution.

Why Use Hooks?

  • Enforce code formatting automatically
  • Block dangerous commands before execution
  • Inject context at session start
  • Log commands for audit trails
  • Send notifications when tasks complete

Hook Lifecycle Events

EventWhen It FiresKey Use Cases
SessionStartSession begins/resumesEnvironment setup, context loading
SessionEndSession terminatesCleanup, state persistence
UserPromptSubmitUser submits promptInput validation, context injection
PreToolUseBefore tool executionPermission control, blocking dangerous ops
PostToolUseAfter tool completesAuto-formatting, logging, validation
PostToolUseFailureAfter tool execution failsRetry decisions, error handling
PermissionRequestClaude requests permission for a toolAuto approve/deny without user prompt
StopMain agent finishes respondingNotifications, git reminders
SubagentStartSubagent (Task tool) is about to startInput modification, context injection
SubagentStopSubagent finishesPer-task completion evaluation
WorktreeCreateNew git worktree created via EnterWorktreeWorktree setup, dependency install
WorktreeRemoveWorktree removed after session exitsCleanup, uncommitted changes alert
TeammateIdleTeammate in agent team goes idleAssign additional tasks to teammate
TaskCompletedTask in shared task list marked completeValidation gates before task acceptance
PreCompactBefore context compactionTranscript backup
NotificationClaude sends notificationCustom alerts
ConfigChangeClaude Code settings change at runtimeAudit config changes, validation
Stop vs SubagentStop: Stop fires at the session level when the main agent finishes a response turn. SubagentStop fires when an individual subagent (spawned via the Task tool) completes. Use Stop for session-level notifications; use SubagentStop for per-task quality gates.

For full schemas, examples, and timeout recommendations for each event, see .claude/rules/hooks-reference.md.

Configuration

File Locations

Hooks are configured in settings files:

  • ~/.claude/settings.json - User-level (applies everywhere)
  • .claude/settings.json - Project-level (committed to repo)
  • .claude/settings.local.json - Local project (not committed)

Claude Code merges all matching hooks from all files.

Frontmatter Hooks (Skills and Commands)

Hooks can also be defined directly in skill and command frontmatter using the hooks field:

---
name: my-skill
description: A skill with hooks
allowed-tools: Bash, Read
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "echo 'Pre-tool hook from skill'"
          timeout: 10
---

Basic Structure

{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "your-command-here",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Matcher Patterns

  • Exact match: "Bash" - matches exactly "Bash" tool
  • Regex patterns: "Edit|Write" - matches either tool
  • Wildcards: "Notebook.*" - matches tools starting with "Notebook"
  • All tools: "*" - matches everything
  • MCP tools: "mcp__server__tool" - targets MCP server tools

Input/Output Schema Summary

Hooks receive JSON via stdin with common fields (session_id, transcript_path, cwd, permission_mode, hook_event_name). Event-specific fields include tool_name and tool_input for PreToolUse, plus tool_response for PostToolUse, and subagent_type/subagent_prompt for SubagentStart.

Exit codes: 0 = allow, 2 = block (stderr shown to Claude), other = non-blocking error.

JSON responses vary by event: PreToolUse uses hookSpecificOutput with permissionDecision; Stop/SubagentStop use decision/reason; SubagentStart uses updatedPrompt; SessionStart uses hookSpecificOutput with additionalContext.

For detailed hook schemas and examples, see REFERENCE.md.

Common Hook Patterns

Block Dangerous Commands (PreToolUse)

#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

# Block rm -rf /
if echo "$COMMAND" | grep -Eq 'rm\s+(-rf|-fr)\s+/'; then
    echo "BLOCKED: Refusing to run destructive command on root" >&2
    exit 2
fi

exit 0

Auto-Format After Edits (PostToolUse)

#!/bin/bash
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [[ "$FILE" == *.py ]]; then
    ruff format "$FILE" 2>/dev/null
    ruff check --fix "$FILE" 2>/dev/null
elif [[ "$FILE" == *.ts ]] || [[ "$FILE" == *.tsx ]]; then
    prettier --write "$FILE" 2>/dev/null
fi

exit 0

Remind About Built-in Tools (PreToolUse)

#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

if echo "$COMMAND" | grep -Eq '^\s*cat\s+[^|><]'; then
    echo "REMINDER: Use the Read tool instead of 'cat'" >&2
    exit 2
fi

exit 0

Load Context at Session Start (SessionStart)

#!/bin/bash
GIT_STATUS=$(git status --short 2>/dev/null | head -5)
BRANCH=$(git branch --show-current 2>/dev/null)

CONTEXT="Current branch: $BRANCH\nPending changes:\n$GIT_STATUS"
jq -n --arg ctx "$CONTEXT" '{
  "hookSpecificOutput": {
    "hookEventName": "SessionStart",
    "additionalContext": $ctx
  }
}'

For additional patterns (subagent injection, desktop notifications, audit logging, auto-approve, worktree setup, task gating), see REFERENCE.md.

Prompt-Based and Agent-Based Hooks

In addition to command hooks, Claude Code supports LLM-powered hooks for decisions requiring judgment.

Hook Types

TypeHow It WorksDefault TimeoutUse When
commandRuns a shell command, reads stdin, returns exit code600sDeterministic rules (regex, field checks)
httpSends hook data to an HTTPS endpoint, reads JSON response30sRemote/centralized policy enforcement
promptSingle-turn LLM call (Haiku), returns {ok: true/false}30sJudgment on hook input data alone
agentMulti-turn subagent with tool access, returns {ok: true/false}60sVerification needing file/tool access

Additional Hook Handler Fields

  • async: true: Fire-and-forget for command hooks (non-blocking, exit code ignored)
  • once: true: Run only once per session; subsequent triggers are skipped

Supported Events

Prompt and agent hooks work on: PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, Stop, SubagentStop, TaskCompleted, UserPromptSubmit.

All other events (SessionStart, SessionEnd, PreCompact, etc.) support only command hooks.

CLAUDE_ENV_FILE (SessionStart)

SessionStart hooks can write environment variables that persist for the session via CLAUDE_ENV_FILE:

if [ -n "$CLAUDE_ENV_FILE" ]; then
  echo "NODE_ENV=development" >> "$CLAUDE_ENV_FILE"
fi
Note: Prefer command hooks over agent hooks when the logic is deterministic. For example, test verification is better as a bash script than an agent hook -- it eliminates LLM latency on every invocation.

For prompt, agent, and HTTP hook configuration examples, see REFERENCE.md.

For the full decision guide on when to use each hook type, see .claude/rules/prompt-agent-hooks.md.

Handling Blocked Commands

When a PreToolUse hook blocks a command:

SituationAction
Hook suggests alternativeUse the suggested tool/approach
Alternative won't workAsk user to run command manually
User says "proceed"Still blocked - explain and provide command for manual execution

Critical: User permission does NOT bypass hooks. Retrying a blocked command will fail again.

When command is legitimately needed:

  1. Explain why the command is required
  2. Describe alternatives considered and why they won't work
  3. Provide exact command for user to run manually
  4. Let user decide

Best Practices

Script Development:

  1. Always read input from stdin with cat
  2. Use jq for JSON parsing
  3. Quote all variables to prevent injection
  4. Exit with code 2 to block, 0 to allow
  5. Write blocking messages to stderr
  6. Keep hooks fast (< 5 seconds)

Configuration:

  1. Use $CLAUDE_PROJECT_DIR for portable paths
  2. Set explicit timeouts (default: 10 minutes / 600s as of 2.1.50)
  3. Use specific matchers over wildcards
  4. Test hooks manually before enabling

Security:

  1. Validate all inputs
  2. Use absolute paths
  3. Avoid touching .env or .git/ directly
  4. Review hook code before deployment

Debugging

Verify hook registration:

/hooks

Enable debug logging:

claude --debug

Test hooks manually:

echo '{"tool_input": {"command": "cat file.txt"}}' | bash your-hook.sh
echo $?  # Check exit code

Available Hooks in This Plugin

  • bash-antipatterns.sh: Detects when Claude uses shell commands instead of built-in tools (cat, grep, sed, timeout, etc.)

See hooks/README.md for full documentation.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.47%
按下载量换算226

Claude

30.69%
按下载量换算195

Cursor

19.93%
按下载量换算127

Gemini CLI

9.04%
按下载量换算57

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills