Recent Posts
Recent Comments
반응형
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

오늘도 공부

Codex CLI 훅(Hook) 완벽 가이드 본문

카테고리 없음

Codex CLI 훅(Hook) 완벽 가이드

행복한 수지아빠 2026. 2. 14. 15:39
반응형

OpenAI Codex CLI의 notify 기능을 활용해 작업 완료 알림을 받는 방법을 정리합니다.


개요

Codex CLI는 에이전트가 턴을 마칠 때 외부 프로그램을 실행할 수 있는 notify 설정을 제공합니다. 이를 통해 데스크톱 알림, 웹훅, CI/CD 연동 등 다양한 용도로 활용할 수 있습니다.


기본 설정

config.toml 위치

~/.codex/config.toml

notify 설정 추가

# 배열 형태로 실행할 프로그램과 인자를 지정
notify = ["python3", "/path/to/notify.py"]

# 또는 쉘 스크립트 방식
notify = ["sh", "-c", "echo '$1' > /tmp/codex-log.txt", "--"]

notification JSON 구조

notify 스크립트는 단일 JSON 인자를 받습니다:

{
  "type": "agent-turn-complete",
  "thread-id": "abc123",
  "turn-id": "turn-1",
  "cwd": "/Users/username/project",
  "input-messages": ["사용자 입력 메시지"],
  "last-assistant-message": "작업 완료했습니다."
}
필드 설명
type 이벤트 타입 (현재 agent-turn-complete만 지원)
thread-id 세션 식별자
turn-id 턴 식별자
cwd 작업 디렉토리
input-messages 사용자 입력 메시지 배열
last-assistant-message 마지막 어시스턴트 응답

알림 스크립트 예시

1. macOS 데스크톱 알림 (공식 예제)

#!/usr/bin/env python3
import json
import subprocess
import sys

def main() -> int:
    notification = json.loads(sys.argv[1])

    # agent-turn-complete 이벤트만 처리
    if notification.get("type") != "agent-turn-complete":
        return 0

    title = f"Codex: {notification.get('last-assistant-message', 'Turn Complete!')}"
    message = " ".join(notification.get("input-messages", []))

    subprocess.check_output([
        "terminal-notifier",
        "-title", title,
        "-message", message,
        "-group", "codex-" + notification.get("thread-id", ""),
        "-activate", "com.googlecode.iterm2",
    ])
    return 0

if __name__ == "__main__":
    sys.exit(main())

config.toml:

notify = ["python3", "~/.local/bin/codex-notify.py"]

2. 터미널 OSC 알림 (Mux 연동)

#!/usr/bin/env bash
# ~/.local/bin/codex-mux-notify

NOTIFICATION="$1"
CWD=$(echo "$NOTIFICATION" | jq -r '.cwd // empty' 2>/dev/null)

# OSC 9 시퀀스로 알림 전송
printf '\e]9;%s\a' "$CWD" > /dev/tty

config.toml:

notify = ["~/.local/bin/codex-mux-notify"]

3. 쉘 원라이너 (간단한 로깅)

notify = ["sh", "-c", "echo \"$1\" >> /tmp/codex.log", "--"]

4. 슬랙 웹훅

#!/usr/bin/env python3
import json
import requests
import sys

def main():
    notification = json.loads(sys.argv[1])

    if notification.get("type") != "agent-turn-complete":
        return

    cwd = notification.get("cwd", "unknown")
    message = notification.get("last-assistant-message", "완료")

    requests.post("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", json={
        "text": f"Codex 작업 완료",
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": f"*프로젝트:* `{cwd}`\n*결과:* {message[:200]}"
                }
            }
        ]
    })

if __name__ == "__main__":
    main()

TUI 내장 알림 vs notify

기능 notify tui.notifications
외부 프로그램 실행 O X
웹훅 전송 O X
데스크톱 토스트 O O (제한적)
이벤트 타입 필터 X O
TUI 내 표시 X O

TUI 내장 알림 설정:

[tui]
notifications = ["agent-turn-complete", "approval-requested"]

Mux 터미널과 연동하기

Mux는 OSC 9 시퀀스를 감지하여 사이드바에 알림 뱃지를 표시합니다.

설정 방법

스크립트 생성 (~/.local/bin/codex-mux-notify):

#!/usr/bin/env bash
CWD=$(echo "$1" | jq -r '.cwd // empty' 2>/dev/null)
printf '\e]9;%s\a' "$CWD" > /dev/tty

config.toml:

notify = ["~/.local/bin/codex-mux-notify"]

작동 원리

  1. Codex 작업 완료 → notify 스크립트 실행
  2. 스크립트가 JSON에서 cwd 추출
  3. OSC 9 시퀀스 전송 (\e]9;/path/to/project\a)
  4. Mux가 시퀀스 감지 → 프로젝트 경로로 매칭
  5. 현재 선택되지 않은 프로젝트에 녹색 ✓ 뱃지 표시

WSL 2 지원

Codex는 WSL 2 + Windows Terminal 환경을 자동으로 감지하여 Windows 네이티브 토스트 알림으로 폴백합니다. 별도 설정이 필요하지 않습니다.


문제 해결

알림이 오지 않을 때

  1. 스크립트 실행 권한 확인

    chmod +x ~/.local/bin/codex-notify
  2. 스크립트 경로가 올바른지 확인

    codex --config notify='["~/.local/bin/codex-notify"]'
  3. 수동 테스트

    # JSON 더미 데이터로 테스트
    ~/.local/bin/codex-notify '{"type":"agent-turn-complete","cwd":"/tmp"}'

jq가 없는 경우

# macOS
brew install jq

# 또는 Python 사용
CWD=$(python3 -c "import json,sys; print(json.loads(sys.argv[1]).get('cwd',''))" "$1")

참고 자료


요약

# ~/.codex/config.toml

# 방법 1: Python 스크립트 (macOS 알림)
notify = ["python3", "~/.local/bin/codex-notify.py"]

# 방법 2: Bash 스크립트 (Mux 연동)
notify = ["~/.local/bin/codex-mux-notify"]

# 방법 3: 간단한 로깅
notify = ["sh", "-c", "echo \"$1\" >> /tmp/codex.log", "--"]

Codex의 notify 기능을 활용하면 작업 완료 시 다양한 방식으로 알림을 받을 수 있습니다. 특히 Mux 같은 터미널 멀티플렉서와 연동하면 여러 프로젝트를 동시에 작업할 때 유용합니다.

반응형