原文(日本語に翻訳)
フックイベントにサブエージェント用の agent_id(サブエージェント向け)と agent_type(サブエージェントおよび --agent 向け)を追加
原文(英語)
Added agent_id (for subagents) and agent_type (for subagents and --agent) to hook events
概要
フックイベントに agent_id と agent_type の2つの新フィールドが追加されました。これにより、複数のエージェント・サブエージェントが動作している環境で、どのエージェントからフックが発火したかを正確に識別できます。マルチエージェントシステムのデバッグ、監査ログ、エージェント固有の処理分岐が容易になります。
フィールドの説明
| フィールド | 対象 | 説明 |
|---|---|---|
agent_id | サブエージェント | サブエージェントの一意のID |
agent_type | サブエージェント + --agent | エージェントの種類を示す文字列 |
基本的な使い方
フックスクリプトでこれらのフィールドを受け取る(標準入力からJSONで渡される):
python
#!/usr/bin/env python3
import json
import sys
event = json.load(sys.stdin)
agent_id = event.get("agent_id", "main")
agent_type = event.get("agent_type", "main")
print(f"Agent: {agent_type} (ID: {agent_id})")実践例
エージェント別にログを分ける
python
#!/usr/bin/env python3
# hooks/log-by-agent.py
import json
import sys
from pathlib import Path
from datetime import datetime
event = json.load(sys.stdin)
agent_id = event.get("agent_id", "main")
agent_type = event.get("agent_type", "main")
tool_name = event.get("tool", {}).get("name", "unknown")
log_dir = Path.home() / ".claude" / "agent-logs"
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / f"{agent_type}-{agent_id[:8]}.log"
with open(log_file, "a") as f:
f.write(f"[{datetime.now().isoformat()}] {tool_name}\n")settings.json での設定:
json
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "python3 ~/.claude/hooks/log-by-agent.py"
}
]
}
]
}
}特定エージェントタイプのみに制限をかける
python
#!/usr/bin/env python3
# hooks/restrict-subagent.py
import json
import sys
event = json.load(sys.stdin)
agent_type = event.get("agent_type", "main")
# サブエージェントからのファイル削除を拒否
if agent_type == "subagent":
tool_name = event.get("tool", {}).get("name", "")
if tool_name == "Bash":
command = event.get("tool", {}).get("input", {}).get("command", "")
if "rm -rf" in command:
print(json.dumps({"decision": "deny", "reason": "サブエージェントからのrm -rfは禁止されています"}))
sys.exit(0)
print(json.dumps({"decision": "allow"}))エージェント別の通知
bash
#!/bin/bash
# hooks/notify-agent.sh
EVENT=$(cat)
AGENT_TYPE=$(echo "$EVENT" | jq -r '.agent_type // "main"')
AGENT_ID=$(echo "$EVENT" | jq -r '.agent_id // "main"')
if [ "$AGENT_TYPE" = "subagent" ]; then
osascript -e "display notification \"サブエージェント ${AGENT_ID:0:8} がタスクを完了しました\" with title \"Claude Code\""
fi注意点
agent_idはサブエージェント(Agent toolで起動されたエージェント)にのみ付与されます。メインセッションには付与されませんagent_typeは--agentフラグで起動した場合にも付与されます- フィールドが存在しない場合はメインセッションからのイベントです(後方互換性を保つため)