ISLAM-PO's picture
Add context engineering toolkit (Units 1-5)
b4c665d verified
|
Raw History Blame Contribute Delete
2.72 kB

Hooks Examples (Unit 5)

This directory demonstrates hook patterns across Claude Code, Codex, OpenCode, and Pi.

Hook Lifecycle

User prompt
    β”‚
    β”œβ”€[UserPromptSubmit hook]─► log / inject context
    β–Ό
Model reasoning
    β”‚
    β”œβ”€[PreToolUse hook]─► allow, deny, rewrite args
    β–Ό
Tool executes
    β”‚
    β”œβ”€[PostToolUse hook]─► log, analyze, post-process
    β–Ό
Model continues
    β”‚
    └─[Stop / SessionEnd hooks]─► persist, notify, tear down

Claude Code β€” .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python .claude/hooks/guard_bash.py"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "python .claude/hooks/run_linter.py"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python .claude/hooks/notify_done.py"
          }
        ]
      }
    ]
  }
}

OpenCode β€” .opencode/plugins/activity-logger.ts

export default {
  "tool.execute.before": async (input, output) => {
    console.log(`[HOOK] Before tool: ${input.tool}`);
    // Block dangerous commands
    if (input.tool === "bash" && input.args?.command?.includes("rm -rf")) {
      throw new Error("Blocked: dangerous command");
    }
  },
  "tool.execute.after": async (input, output) => {
    console.log(`[HOOK] After tool: ${input.tool} -> ${output.result?.slice(0, 100)}`);
  },
  "event": async ({ event }) => {
    if (event.type === "session.idle") {
      console.log("[HOOK] Session ended");
    }
  }
};

Guardrail Example β€” .claude/hooks/guard_bash.py

import json, sys

payload = json.load(sys.stdin)
command = payload.get("tool_input", {}).get("command", "")

BLOCKED = ["rm -rf /", "rm -rf ~", "~/.ssh/", "chmod 777"]
for pattern in BLOCKED:
    if pattern in command:
        print(json.dumps({"decision": "deny", "reason": f"Blocked: {pattern}"}))
        sys.exit(0)

print(json.dumps({"decision": "allow"}))

Three Patterns

  1. Observability β€” Log every tool call, prompt, and stop event to a dashboard.
  2. Guardrails β€” Inspect commands before execution; deny unsafe actions.
  3. Automation β€” Run linters, formatters, tests automatically after file edits.

Agent Activity Dashboard

A Gradio app that receives hook events over HTTP and visualizes tool calls, prompts, and sessions in real time. See hooks/dashboard.py.