보안 리뷰 지적 반영. 꼬리(<usage>·agentId)를 문자열 어디서든 지우면 본문 속 FIX 가 함께 사라질 수 있었다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
137 lines
5.6 KiB
Python
137 lines
5.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Outlook 초안 생성·수정·발송 전에 view-mou-watchdog 검토 통과를 요구하는 PreToolUse 훅.
|
|
|
|
통과 조건: 가장 최근 view-mou-watchdog 결과(동기 결과 또는 백그라운드 task-notification)가 'WATCHDOG: PASS' 이고,
|
|
그 PASS 이후에 아직 다른 Outlook 초안 도구 호출이 없다 (검토 한 번에 초안 한 번).
|
|
"""
|
|
import json
|
|
import re
|
|
import sys
|
|
|
|
AGENT = "view-mou-watchdog"
|
|
OUTLOOK_PREFIX = "mcp__claude_ai_Microsoft_365__outlook_"
|
|
GATED = ("create_draft", "create_reply_draft", "create_reply_all_draft", "update_draft", "send_draft", "send_mail", "forward_mail")
|
|
|
|
|
|
def deny(reason):
|
|
print(json.dumps({
|
|
"hookSpecificOutput": {
|
|
"hookEventName": "PreToolUse",
|
|
"permissionDecision": "deny",
|
|
"permissionDecisionReason": reason,
|
|
}
|
|
}, ensure_ascii=False))
|
|
sys.exit(0)
|
|
|
|
|
|
def is_gated(name):
|
|
return name.startswith(OUTLOOK_PREFIX) and name[len(OUTLOOK_PREFIX):] in GATED
|
|
|
|
|
|
def result_text(item):
|
|
c = item.get("content")
|
|
if isinstance(c, str):
|
|
return c
|
|
if isinstance(c, list):
|
|
return "\n".join((x.get("text") or "") for x in c if isinstance(x, dict))
|
|
return ""
|
|
|
|
|
|
def verdict(text):
|
|
# 판정은 결과의 마지막 비어 있지 않은 줄이 정확히 "WATCHDOG: PASS" 일 때만 인정한다 (본문 중간 인용·FIX 혼재 차단)
|
|
# 백그라운드 알림은 <result> 뒤에 <usage>·</task-notification> 이 붙으므로 <result> 본문만 본다
|
|
text = text.replace("\\n", "\n")
|
|
# FIX 가 원문 어디에든 있으면 통과시키지 않는다 (꼬리 제거·<result> 추출 전에 검사)
|
|
if "WATCHDOG: FIX" in text:
|
|
return False
|
|
# 백그라운드 알림은 마지막 <result> 블록만 본다
|
|
blocks = re.findall(r"<result>(.*?)</result>", text, re.S)
|
|
if blocks:
|
|
text = blocks[-1]
|
|
# 동기 결과는 판정 뒤에 하네스 꼬리(agentId: … 줄 + <usage>…</usage>)가 붙는다. 문자열 끝에 붙은 꼬리만 뗀다
|
|
text = re.sub(r"\n\s*agentId:[^\n]*\s*(<usage>.*?</usage>)?\s*$", "", text, flags=re.S)
|
|
lines = [l.strip() for l in text.splitlines() if l.strip()]
|
|
if not lines:
|
|
return False
|
|
last = re.sub(r"[`*_<>/]|result", "", lines[-1]).strip()
|
|
return last == "WATCHDOG: PASS"
|
|
|
|
|
|
def main():
|
|
payload = json.load(sys.stdin)
|
|
if not is_gated(payload.get("tool_name", "")):
|
|
sys.exit(0)
|
|
|
|
rows = []
|
|
with open(payload["transcript_path"], encoding="utf-8") as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line:
|
|
try:
|
|
rows.append(json.loads(line))
|
|
except json.JSONDecodeError:
|
|
continue
|
|
|
|
# 검토 1회(PASS) = 초안 도구 1회. 백그라운드 검토 결과는 task-notification 으로 도착한다
|
|
watchdog_ids = set()
|
|
passed = False
|
|
for r in rows:
|
|
if not isinstance(r, dict):
|
|
continue
|
|
if r.get("isSidechain"):
|
|
continue
|
|
# 요청 사본 행은 앞선 도구 호출을 다시 담고 있어 순서를 흐트러뜨린다. 건너뛴다
|
|
if r.get("type") == "api-request-blob":
|
|
continue
|
|
# 최신 Claude Code 는 백그라운드 결과(task-notification)를 attachment.queued_command 로 기록한다
|
|
att = r.get("attachment") or {}
|
|
if att.get("type") == "queued_command":
|
|
prompt = att.get("prompt") or ""
|
|
if "<task-notification>" in prompt:
|
|
m = re.search(r"<tool-use-id>([^<]+)</tool-use-id>", prompt)
|
|
if m and m.group(1) in watchdog_ids:
|
|
passed = verdict(prompt)
|
|
continue
|
|
c = (r.get("message") or {}).get("content") if isinstance(r, dict) else None
|
|
if isinstance(c, str):
|
|
if "<task-notification>" in c:
|
|
m = re.search(r"<tool-use-id>([^<]+)</tool-use-id>", c)
|
|
if m and m.group(1) in watchdog_ids:
|
|
passed = verdict(c)
|
|
continue
|
|
if not isinstance(c, list):
|
|
continue
|
|
for x in c:
|
|
if not isinstance(x, dict):
|
|
continue
|
|
if x.get("type") == "tool_use":
|
|
inp = x.get("input") or {}
|
|
# 에이전트 정의가 아직 로드되지 않은 세션에서는 general-purpose 에 정의 파일을 넘기고 description 에 이름을 단다
|
|
if x.get("name") in ("Agent", "Task") and (
|
|
inp.get("subagent_type") == AGENT or AGENT in (inp.get("description") or "")
|
|
):
|
|
watchdog_ids.add(x.get("id"))
|
|
elif is_gated(x.get("name", "")):
|
|
passed = False
|
|
elif x.get("type") == "tool_result" and x.get("tool_use_id") in watchdog_ids:
|
|
text = result_text(x)
|
|
if "WATCHDOG:" in text:
|
|
passed = verdict(text)
|
|
|
|
if not passed:
|
|
deny(
|
|
"view-mou-watchdog 검토가 통과되지 않았습니다. 메일 초안을 만들거나 고치기 전에 "
|
|
"Agent(subagent_type='view-mou-watchdog')에 초안 전문과 근거 위치를 넘겨 검토받고, "
|
|
"'WATCHDOG: PASS'가 나온 뒤 다시 시도하세요. FIX면 정정한 초안으로 다시 검토받으세요."
|
|
)
|
|
sys.exit(0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except SystemExit:
|
|
raise
|
|
except Exception as e: # 훅이 깨지면 막는 쪽으로 (fail-closed)
|
|
deny(f"watchdog 게이트 훅 오류로 초안 도구를 막았습니다: {type(e).__name__}: {e}")
|