Compare commits
9 Commits
1e552f8c46
...
feat/tmux-
| Author | SHA1 | Date | |
|---|---|---|---|
| 119dd9a486 | |||
| b83929fac2 | |||
| e616bebdb9 | |||
| 8f8e63f56f | |||
| df377cf2df | |||
| 906022555a | |||
| ebe7902362 | |||
| 582c19bb50 | |||
| 87482efd6d |
20
.env.example
Normal file
20
.env.example
Normal file
@@ -0,0 +1,20 @@
|
||||
# Slack App 설정
|
||||
SLACK_BOT_TOKEN=xoxb-your-bot-token
|
||||
SLACK_APP_TOKEN=xapp-your-app-token
|
||||
|
||||
# 보안: 허가된 사용자/채널만 명령 수락
|
||||
SLACK_ALLOWED_USER_ID=U0XXXXXXXXX
|
||||
SLACK_ALLOWED_CHANNEL_ID=C0XXXXXXXXX
|
||||
|
||||
# PTY / tmux 연결 설정
|
||||
TMUX_SESSION_NAME=claude
|
||||
PTY_READ_TIMEOUT=5
|
||||
|
||||
# 출력 버퍼 설정
|
||||
OUTPUT_BUFFER_INTERVAL=2.0
|
||||
MAX_MESSAGE_LENGTH=3000
|
||||
|
||||
# 상태 보고 / 재연결 설정
|
||||
RECONNECT_DELAY_SECONDS=5.0
|
||||
OUTPUT_IDLE_REPORT_SECONDS=120
|
||||
INPUT_IDLE_REPORT_SECONDS=300
|
||||
44
AGENTS.md
Normal file
44
AGENTS.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Organization
|
||||
This project uses a `src/` layout:
|
||||
- `src/lazy_enter/`: application code (`bridge.py`, `slack_handler.py`, `pty_manager.py`, `config.py`, `hooks.py`)
|
||||
- `tests/`: `pytest` test suite (`test_*.py` files)
|
||||
- `pyproject.toml`: packaging, lint, type-check, and test configuration
|
||||
- `.env.example`: environment variable template for local setup
|
||||
|
||||
Use module boundaries intentionally: `bridge.py` orchestrates flow, while Slack, PTY, config, and hook parsing stay in their dedicated modules.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
- `pip install -e .`: install the package in editable mode for local development.
|
||||
- `python -m lazy_enter` or `lazy-enter`: run the bridge locally.
|
||||
- `pytest`: run all tests.
|
||||
- `pytest tests/test_hooks.py -v`: run one test file with verbose output.
|
||||
- `ruff check src/ tests/`: lint imports and code quality rules.
|
||||
- `ruff format src/ tests/`: apply standard formatting.
|
||||
- `mypy src/`: run strict static type checks.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
Target runtime is Python 3.10+ with 4-space indentation and type hints on public functions.
|
||||
Follow `ruff` rules (`E`, `F`, `I`, `N`, `W`, `UP`) and keep imports sorted.
|
||||
Naming patterns:
|
||||
- modules/files: `snake_case.py`
|
||||
- functions/variables: `snake_case`
|
||||
- classes: `PascalCase`
|
||||
- constants/env keys: `UPPER_SNAKE_CASE`
|
||||
|
||||
## Testing Guidelines
|
||||
Use `pytest` with tests under `tests/` and names matching `test_*.py` (configured in `pyproject.toml`).
|
||||
Prefer focused unit tests per module (see `tests/test_hooks.py`, `tests/test_config.py`).
|
||||
For bug fixes, add or update a regression test in the matching test file before finalizing.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
Current git history is minimal (`Initial commit`), so enforce clear conventions now:
|
||||
- Commit messages: imperative, concise subject (e.g., `Add Slack user/channel guard`).
|
||||
- Keep commits scoped to one logical change.
|
||||
- PRs should include: problem summary, what changed, test evidence (`pytest`, `ruff`, `mypy`), and linked issue/context.
|
||||
- Include screenshots or log snippets when behavior changes are user-visible (for example, Slack message formatting).
|
||||
|
||||
## Security & Configuration Tips
|
||||
Do not commit secrets. Copy `.env.example` to `.env` locally.
|
||||
Restrict Slack access with `SLACK_ALLOWED_USER_ID` and `SLACK_ALLOWED_CHANNEL_ID` before running in shared workspaces.
|
||||
55
CLAUDE.md
Normal file
55
CLAUDE.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
LazyEnter("소파에서 엔터나 치자")는 로컬 PC의 Claude Code CLI 세션을 Slack으로 중계하여, 모바일에서 승인(y/n) 및 명령을 원격 수행하는 브릿지 시스템이다. Slack Socket Mode를 사용하므로 공인 IP나 방화벽 설정이 불필요하다.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Slack App (모바일/데스크톱)
|
||||
↕ Socket Mode
|
||||
SlackHandler ← Bridge → PtyManager
|
||||
↑ ↕
|
||||
Config pexpect (claude 프로세스)
|
||||
↑
|
||||
CLI Hooks (hooks.py)
|
||||
```
|
||||
|
||||
- **Bridge** (`bridge.py`): 핵심 중계기. SlackHandler와 PtyManager를 연결하고 출력 폴링 스레드를 관리
|
||||
- **SlackHandler** (`slack_handler.py`): slack_bolt 기반 Socket Mode 이벤트 수신/메시지 전송
|
||||
- **PtyManager** (`pty_manager.py`): pexpect로 가상 터미널 프로세스 생성·입출력 제어
|
||||
- **Config** (`config.py`): python-dotenv 기반 환경 변수 관리
|
||||
- **Hooks** (`hooks.py`): Claude Code `/hooks` 이벤트를 파싱하여 Slack 알림 전송 (승인 대기, 작업 완료)
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# 의존성 설치
|
||||
pip install -e .
|
||||
|
||||
# 실행
|
||||
lazy-enter
|
||||
# 또는
|
||||
python -m lazy_enter
|
||||
|
||||
# 테스트
|
||||
pytest
|
||||
pytest tests/test_hooks.py -v # 단일 파일
|
||||
pytest tests/test_hooks.py::test_parse_hook_event_valid -v # 단일 테스트
|
||||
|
||||
# 린트
|
||||
ruff check src/ tests/
|
||||
ruff format src/ tests/
|
||||
|
||||
# 타입 체크
|
||||
mypy src/
|
||||
```
|
||||
|
||||
## Key Conventions
|
||||
|
||||
- `src/` 레이아웃 사용 (`src/lazy_enter/`)
|
||||
- 환경 변수는 `.env` 파일로 관리 (`.env.example` 참조)
|
||||
- 보안: `SLACK_ALLOWED_USER_ID`, `SLACK_ALLOWED_CHANNEL_ID`로 접근 제한 필수
|
||||
94
README.md
94
README.md
@@ -1,3 +1,95 @@
|
||||
# LazyEnter
|
||||
|
||||
소파에서 엔터나 치자
|
||||
소파에서 엔터나 치자.
|
||||
로컬 PC의 Claude Code CLI 세션을 Slack Socket Mode로 중계해 모바일에서도 원격으로 입력/승인을 처리하는 브릿지입니다.
|
||||
|
||||
## 동작 방식
|
||||
|
||||
1. 로컬에서 Claude를 tmux 세션으로 미리 실행 (`tmux new -s claude claude`)
|
||||
2. Slack에서 `/start-claude` 실행
|
||||
3. 브릿지가 기존 tmux 세션에 연결해 pane 출력/입력을 중계
|
||||
4. Slack 채널 메시지가 CLI 입력으로 전달됨
|
||||
5. CLI 출력이 Slack으로 다시 전송됨
|
||||
6. `/stop-claude`로 브릿지 연결 해제 (tmux 세션은 유지)
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
```bash
|
||||
git clone <repo-url>
|
||||
cd LazyEnter
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
`.env` 파일을 생성하고 값을 채우세요:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
필수 환경 변수:
|
||||
- `SLACK_BOT_TOKEN`
|
||||
- `SLACK_APP_TOKEN`
|
||||
- `SLACK_ALLOWED_USER_ID`
|
||||
- `SLACK_ALLOWED_CHANNEL_ID`
|
||||
|
||||
선택 환경 변수:
|
||||
- `TMUX_SESSION_NAME` (기본: `claude`)
|
||||
- `PTY_READ_TIMEOUT` (기본: `5`)
|
||||
- `OUTPUT_BUFFER_INTERVAL` (기본: `2.0`)
|
||||
- `MAX_MESSAGE_LENGTH` (기본: `3000`)
|
||||
- `RECONNECT_DELAY_SECONDS` (기본: `5.0`, Socket Mode 재연결 대기 시간)
|
||||
- `OUTPUT_IDLE_REPORT_SECONDS` (기본: `120`, 출력 정지 보고 임계값)
|
||||
- `INPUT_IDLE_REPORT_SECONDS` (기본: `300`, 입력 정지 보고 임계값)
|
||||
|
||||
`SLACK_ALLOWED_USER_ID`, `SLACK_ALLOWED_CHANNEL_ID`가 비어 있으면 실행이 중단됩니다.
|
||||
|
||||
## Slack 앱 설정
|
||||
|
||||
- Socket Mode 활성화
|
||||
- Bot Token Scopes에 `chat:write`, `commands` 추가
|
||||
- Slash Commands 생성:
|
||||
- `/start-claude`
|
||||
- `/stop-claude`
|
||||
- 앱을 워크스페이스에 설치 후 토큰을 `.env`에 반영
|
||||
|
||||
## 실행
|
||||
|
||||
먼저 로컬에서 Claude tmux 세션을 실행:
|
||||
|
||||
```bash
|
||||
tmux new -s claude claude
|
||||
```
|
||||
|
||||
그 다음 브릿지 실행:
|
||||
|
||||
```bash
|
||||
lazy-enter
|
||||
# 또는
|
||||
python -m lazy_enter
|
||||
```
|
||||
|
||||
실행 후 Slack의 허용된 채널에서:
|
||||
- `/start-claude`: 기존 세션에 연결
|
||||
- 일반 메시지 전송: Claude CLI로 입력 전달
|
||||
- `/stop-claude`: 브릿지 연결 해제 (세션 유지)
|
||||
|
||||
## 테스트 및 품질 점검
|
||||
|
||||
```bash
|
||||
pytest
|
||||
ruff check src/ tests/
|
||||
ruff format src/ tests/
|
||||
mypy src/
|
||||
```
|
||||
|
||||
## hooks 알림 사용 (선택)
|
||||
|
||||
`hooks.py`는 JSON 이벤트를 받아 Slack 알림 문구로 변환합니다.
|
||||
|
||||
```bash
|
||||
echo '{"type":"prompt","tool":"Bash"}' | python -m lazy_enter.hooks
|
||||
```
|
||||
|
||||
`SLACK_ALLOWED_CHANNEL_ID`가 설정된 경우 해당 채널로 알림을 보냅니다.
|
||||
|
||||
41
pyproject.toml
Normal file
41
pyproject.toml
Normal file
@@ -0,0 +1,41 @@
|
||||
[project]
|
||||
name = "lazy-enter"
|
||||
version = "0.1.0"
|
||||
description = "소파에서 엔터나 치자 - Slack을 통한 Claude Code 원격 제어 브릿지"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.10"
|
||||
authors = [
|
||||
{ name = "jihoson", email = "kiparang7th@gmail.com" },
|
||||
]
|
||||
dependencies = [
|
||||
"slack-bolt>=1.21.0",
|
||||
"slack-sdk>=3.33.0",
|
||||
"python-dotenv>=1.0.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
lazy-enter = "lazy_enter.__main__:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/lazy_enter"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["src"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py310"
|
||||
src = ["src", "tests"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "N", "W", "UP"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
mypy_path = "src"
|
||||
strict = true
|
||||
3
src/lazy_enter/__init__.py
Normal file
3
src/lazy_enter/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
"""LazyEnter - Slack을 통한 Claude Code 원격 제어 브릿지."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
22
src/lazy_enter/__main__.py
Normal file
22
src/lazy_enter/__main__.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""CLI 엔트리포인트."""
|
||||
|
||||
import sys
|
||||
|
||||
from lazy_enter.bridge import Bridge
|
||||
from lazy_enter.config import Config
|
||||
|
||||
|
||||
def main() -> None:
|
||||
config = Config()
|
||||
try:
|
||||
config.validate_required_settings()
|
||||
except ValueError as exc:
|
||||
print(f"[LazyEnter] 설정 오류: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
bridge = Bridge(config)
|
||||
bridge.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
185
src/lazy_enter/bridge.py
Normal file
185
src/lazy_enter/bridge.py
Normal file
@@ -0,0 +1,185 @@
|
||||
"""Bridge Agent - Slack과 PTY 프로세스를 연결하는 핵심 중계 로직."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
|
||||
from lazy_enter.config import Config
|
||||
from lazy_enter.output_filter import clean_terminal_output
|
||||
from lazy_enter.pty_manager import PtyManager
|
||||
from lazy_enter.slack_handler import SlackHandler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Bridge:
|
||||
"""Slack ↔ CLI 프로세스 간의 중계기."""
|
||||
|
||||
def __init__(self, config: Config | None = None) -> None:
|
||||
self.config = config or Config()
|
||||
self.slack = SlackHandler(self.config)
|
||||
self.pty: PtyManager | None = None
|
||||
self._output_thread: threading.Thread | None = None
|
||||
self._running = False
|
||||
self._channel: str = self.config.allowed_channel_id
|
||||
self._last_sent_output: str = ""
|
||||
self._last_input_at = time.monotonic()
|
||||
self._last_output_at = time.monotonic()
|
||||
self._input_idle_reported = False
|
||||
self._output_idle_reported = False
|
||||
|
||||
self.slack.on_message(self._handle_message)
|
||||
self.slack.on_command(self._handle_command)
|
||||
|
||||
def _handle_message(self, text: str, channel: str) -> None:
|
||||
"""Slack 메시지를 PTY 프로세스로 전달한다."""
|
||||
if self._is_blocked_input(text):
|
||||
self.slack.send_message(
|
||||
channel, ":no_entry: 차단된 명령 패턴이 감지되었습니다."
|
||||
)
|
||||
return
|
||||
|
||||
if self.pty and self.pty.is_alive:
|
||||
self.pty.send(text)
|
||||
self._last_input_at = time.monotonic()
|
||||
self._input_idle_reported = False
|
||||
logger.info("입력 전달: %s", text)
|
||||
else:
|
||||
self.slack.send_message(channel, ":warning: 연결된 세션이 없습니다.")
|
||||
|
||||
@staticmethod
|
||||
def _is_blocked_input(text: str) -> bool:
|
||||
"""치명적 쉘 명령 패턴을 단순 차단한다."""
|
||||
normalized = re.sub(r"\s+", " ", text.lower()).strip()
|
||||
blocked_patterns = (
|
||||
"rm -rf /",
|
||||
"rm -rf /*",
|
||||
"mkfs",
|
||||
":(){:|:&};:",
|
||||
"shutdown -h",
|
||||
"reboot",
|
||||
"poweroff",
|
||||
)
|
||||
return any(pattern in normalized for pattern in blocked_patterns)
|
||||
|
||||
def _handle_command(self, command: str, channel: str) -> None:
|
||||
"""슬래시 커맨드를 처리한다."""
|
||||
if command == "start":
|
||||
self._start_session(channel)
|
||||
elif command == "stop":
|
||||
self._stop_session(channel)
|
||||
|
||||
def _start_session(self, channel: str) -> None:
|
||||
"""기존 Claude tmux 세션에 연결한다."""
|
||||
if self.pty and self.pty.is_alive:
|
||||
self.slack.send_message(
|
||||
channel, ":information_source: 이미 세션에 연결되어 있습니다."
|
||||
)
|
||||
return
|
||||
|
||||
self._channel = channel
|
||||
self._last_sent_output = ""
|
||||
self.pty = PtyManager(self.config.tmux_session_name)
|
||||
try:
|
||||
self.pty.start()
|
||||
except RuntimeError as exc:
|
||||
self.pty = None
|
||||
self.slack.send_message(channel, f":warning: {exc}")
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._last_input_at = time.monotonic()
|
||||
self._last_output_at = time.monotonic()
|
||||
self._input_idle_reported = False
|
||||
self._output_idle_reported = False
|
||||
self._output_thread = threading.Thread(target=self._poll_output, daemon=True)
|
||||
self._output_thread.start()
|
||||
|
||||
self.slack.send_message(channel, ":link: Claude 세션에 연결되었습니다.")
|
||||
|
||||
def _stop_session(self, channel: str) -> None:
|
||||
"""브릿지 연결만 해제한다."""
|
||||
self._running = False
|
||||
if self.pty:
|
||||
self.pty.stop()
|
||||
self.pty = None
|
||||
self._last_sent_output = ""
|
||||
self.slack.send_message(channel, ":electric_plug: 세션 연결이 해제되었습니다.")
|
||||
|
||||
def _poll_output(self) -> None:
|
||||
"""PTY 출력을 주기적으로 읽어 Slack으로 전송한다."""
|
||||
buffer = ""
|
||||
while self._running and self.pty and self.pty.is_alive:
|
||||
now = time.monotonic()
|
||||
output = self.pty.read_output(timeout=self.config.pty_read_timeout)
|
||||
if output:
|
||||
cleaned = clean_terminal_output(output)
|
||||
if cleaned:
|
||||
buffer += f"{cleaned}\n"
|
||||
self._last_output_at = now
|
||||
self._output_idle_reported = False
|
||||
|
||||
if buffer:
|
||||
# 메시지 길이 제한 적용
|
||||
message = buffer[: self.config.max_message_length].rstrip()
|
||||
if len(buffer) > self.config.max_message_length:
|
||||
message += "\n... (truncated)"
|
||||
if message and message != self._last_sent_output:
|
||||
self.slack.send_message(self._channel, f"```\n{message}\n```")
|
||||
self._last_sent_output = message
|
||||
buffer = ""
|
||||
|
||||
output_idle = now - self._last_output_at
|
||||
if (
|
||||
self.config.output_idle_report_seconds > 0
|
||||
and not self._output_idle_reported
|
||||
and output_idle >= self.config.output_idle_report_seconds
|
||||
):
|
||||
self.slack.send_message(
|
||||
self._channel,
|
||||
(
|
||||
f":hourglass_flowing_sand: 출력이 {int(output_idle)}초 동안 "
|
||||
"없습니다. 세션 상태를 확인해주세요."
|
||||
),
|
||||
)
|
||||
self._output_idle_reported = True
|
||||
|
||||
input_idle = now - self._last_input_at
|
||||
if (
|
||||
self.config.input_idle_report_seconds > 0
|
||||
and not self._input_idle_reported
|
||||
and input_idle >= self.config.input_idle_report_seconds
|
||||
):
|
||||
self.slack.send_message(
|
||||
self._channel,
|
||||
f":information_source: 입력이 {int(input_idle)}초 동안 없습니다.",
|
||||
)
|
||||
self._input_idle_reported = True
|
||||
|
||||
time.sleep(self.config.output_buffer_interval)
|
||||
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
# attach 프로세스가 예기치 않게 종료된 경우
|
||||
self.slack.send_message(self._channel, ":warning: 세션 연결이 종료되었습니다.")
|
||||
|
||||
def run(self) -> None:
|
||||
"""브릿지를 시작한다."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
|
||||
)
|
||||
logger.info("LazyEnter Bridge 시작")
|
||||
try:
|
||||
self.slack.start()
|
||||
except KeyboardInterrupt:
|
||||
logger.info("종료 신호 수신")
|
||||
finally:
|
||||
self._running = False
|
||||
if self.pty:
|
||||
self.pty.stop()
|
||||
self.slack.stop()
|
||||
50
src/lazy_enter/config.py
Normal file
50
src/lazy_enter/config.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""환경 변수 및 설정 관리."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class Config:
|
||||
"""앱 전체 설정을 담당하는 클래스."""
|
||||
|
||||
# Slack
|
||||
slack_bot_token: str = os.getenv("SLACK_BOT_TOKEN", "")
|
||||
slack_app_token: str = os.getenv("SLACK_APP_TOKEN", "")
|
||||
allowed_user_id: str = os.getenv("SLACK_ALLOWED_USER_ID", "")
|
||||
allowed_channel_id: str = os.getenv("SLACK_ALLOWED_CHANNEL_ID", "")
|
||||
|
||||
# PTY / tmux attach
|
||||
tmux_session_name: str = os.getenv("TMUX_SESSION_NAME", "claude")
|
||||
pty_read_timeout: int = int(os.getenv("PTY_READ_TIMEOUT", "5"))
|
||||
|
||||
# Buffer
|
||||
output_buffer_interval: float = float(os.getenv("OUTPUT_BUFFER_INTERVAL", "2.0"))
|
||||
max_message_length: int = int(os.getenv("MAX_MESSAGE_LENGTH", "3000"))
|
||||
|
||||
# Status reporting / reconnect
|
||||
reconnect_delay_seconds: float = float(os.getenv("RECONNECT_DELAY_SECONDS", "5.0"))
|
||||
output_idle_report_seconds: int = int(
|
||||
os.getenv("OUTPUT_IDLE_REPORT_SECONDS", "120")
|
||||
)
|
||||
input_idle_report_seconds: int = int(os.getenv("INPUT_IDLE_REPORT_SECONDS", "300"))
|
||||
|
||||
def validate_required_settings(self) -> None:
|
||||
"""필수 설정값 누락 여부를 검증한다."""
|
||||
missing: list[str] = []
|
||||
if not self.slack_bot_token:
|
||||
missing.append("SLACK_BOT_TOKEN")
|
||||
if not self.slack_app_token:
|
||||
missing.append("SLACK_APP_TOKEN")
|
||||
if not self.allowed_user_id:
|
||||
missing.append("SLACK_ALLOWED_USER_ID")
|
||||
if not self.allowed_channel_id:
|
||||
missing.append("SLACK_ALLOWED_CHANNEL_ID")
|
||||
|
||||
if missing:
|
||||
joined = ", ".join(missing)
|
||||
raise ValueError(f"필수 환경 변수가 누락되었습니다: {joined}")
|
||||
60
src/lazy_enter/hooks.py
Normal file
60
src/lazy_enter/hooks.py
Normal file
@@ -0,0 +1,60 @@
|
||||
"""Claude Code hooks 연동 - 상태 알림 서비스."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from lazy_enter.config import Config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def parse_hook_event(raw: str) -> dict:
|
||||
"""훅 이벤트 JSON을 파싱한다."""
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("훅 이벤트 파싱 실패: %s", raw)
|
||||
return {}
|
||||
|
||||
|
||||
def format_notification(event: dict) -> str | None:
|
||||
"""훅 이벤트를 슬랙 알림 메시지로 변환한다.
|
||||
|
||||
Returns:
|
||||
포맷된 메시지 문자열. 알림이 불필요한 이벤트면 None.
|
||||
"""
|
||||
event_type = event.get("type", "")
|
||||
|
||||
if event_type == "prompt":
|
||||
tool = event.get("tool", "unknown")
|
||||
return f":bell: *[승인 대기 중]* `{tool}` 실행을 승인해주세요. (y/n)"
|
||||
|
||||
if event_type == "completion":
|
||||
summary = event.get("summary", "작업이 완료되었습니다.")
|
||||
return f":white_check_mark: *[완료]* {summary}"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def hook_main() -> None:
|
||||
"""hooks 스크립트로 직접 실행될 때의 엔트리포인트.
|
||||
|
||||
stdin으로 전달된 이벤트를 파싱하여 Slack으로 전송한다.
|
||||
"""
|
||||
from lazy_enter.slack_handler import SlackHandler
|
||||
|
||||
config = Config()
|
||||
raw = sys.stdin.read()
|
||||
event = parse_hook_event(raw)
|
||||
message = format_notification(event)
|
||||
|
||||
if message and config.allowed_channel_id:
|
||||
slack = SlackHandler(config)
|
||||
slack.send_message(config.allowed_channel_id, message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
hook_main()
|
||||
32
src/lazy_enter/output_filter.py
Normal file
32
src/lazy_enter/output_filter.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""PTY 출력에서 터미널 제어 시퀀스를 제거한다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
# ANSI CSI / OSC / DCS / 단일 ESC 시퀀스를 폭넓게 제거한다.
|
||||
_ANSI_ESCAPE_RE = re.compile(
|
||||
r"(?:\x1B\[[0-?]*[ -/]*[@-~])"
|
||||
r"|(?:\x1B\][^\x1B\x07]*(?:\x07|\x1B\\))"
|
||||
r"|(?:\x1BP[^\x1B]*(?:\x1B\\))"
|
||||
r"|(?:\x1B[@-_])"
|
||||
)
|
||||
|
||||
# ESC 문자가 유실된 상태로 남는 CSI 토큰(예: [38;2;153;153;153m) 제거.
|
||||
_BROKEN_CSI_RE = re.compile(r"\[(?:[0-9;<=>?]|(?:\d+;))*\d*[A-Za-z]")
|
||||
|
||||
# C0 제어문자 중 개행/탭/캐리지리턴을 제외하고 제거.
|
||||
_CONTROL_RE = re.compile(r"[\x00-\x08\x0B-\x1F\x7F]")
|
||||
|
||||
|
||||
def clean_terminal_output(text: str) -> str:
|
||||
"""Slack 전송용 텍스트를 정리한다."""
|
||||
cleaned = _ANSI_ESCAPE_RE.sub("", text)
|
||||
cleaned = _BROKEN_CSI_RE.sub("", cleaned)
|
||||
cleaned = cleaned.replace("\r", "")
|
||||
cleaned = _CONTROL_RE.sub("", cleaned)
|
||||
|
||||
# 제어 코드 제거 후 남는 빈 줄을 축소한다.
|
||||
lines = [line.rstrip() for line in cleaned.splitlines()]
|
||||
compact = "\n".join(lines).strip()
|
||||
return compact
|
||||
105
src/lazy_enter/pty_manager.py
Normal file
105
src/lazy_enter/pty_manager.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""기존 tmux 세션의 pane을 캡처/입력하여 CLI 입출력을 중계한다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PtyManager:
|
||||
"""기존 tmux 세션의 pane을 읽고 입력을 보낸다."""
|
||||
|
||||
def __init__(self, session_name: str = "claude") -> None:
|
||||
self.session_name = session_name
|
||||
self._connected = False
|
||||
self._last_capture: list[str] = []
|
||||
|
||||
@property
|
||||
def is_alive(self) -> bool:
|
||||
return self._connected and self._session_exists()
|
||||
|
||||
def _run_tmux(self, args: list[str]) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
["tmux", *args],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def _session_exists(self) -> bool:
|
||||
return self._run_tmux(["has-session", "-t", self.session_name]).returncode == 0
|
||||
|
||||
def _ensure_session_exists(self) -> None:
|
||||
"""대상 tmux 세션 존재 여부를 검증한다."""
|
||||
result = self._run_tmux(["has-session", "-t", self.session_name])
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
"tmux 세션이 없습니다. 먼저 실행하세요: "
|
||||
f"tmux new -s {self.session_name} claude"
|
||||
)
|
||||
|
||||
def _capture_lines(self) -> list[str]:
|
||||
"""pane의 최근 출력 스냅샷을 줄 단위로 가져온다."""
|
||||
result = self._run_tmux(
|
||||
["capture-pane", "-p", "-t", self.session_name, "-S", "-200"]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
return result.stdout.splitlines()
|
||||
|
||||
@staticmethod
|
||||
def _diff_lines(previous: list[str], current: list[str]) -> list[str]:
|
||||
"""이전 스냅샷 대비 새로 추가된 줄만 계산한다."""
|
||||
if not previous:
|
||||
return []
|
||||
|
||||
prefix = 0
|
||||
for prev, curr in zip(previous, current):
|
||||
if prev != curr:
|
||||
break
|
||||
prefix += 1
|
||||
|
||||
if prefix > 0:
|
||||
return current[prefix:]
|
||||
|
||||
# 화면 스크롤/리프레시로 앞부분이 달라진 경우 tail overlap으로 보정.
|
||||
max_overlap = min(len(previous), len(current))
|
||||
for overlap in range(max_overlap, 0, -1):
|
||||
if previous[-overlap:] == current[:overlap]:
|
||||
return current[overlap:]
|
||||
return current
|
||||
|
||||
def start(self) -> None:
|
||||
"""기존 tmux 세션에 연결한다."""
|
||||
self._ensure_session_exists()
|
||||
logger.info("tmux 세션 연결: %s", self.session_name)
|
||||
self._connected = True
|
||||
self._last_capture = self._capture_lines()
|
||||
|
||||
def send(self, text: str) -> None:
|
||||
"""세션에 텍스트 입력을 전달한다."""
|
||||
if not self.is_alive:
|
||||
raise RuntimeError("프로세스가 실행 중이 아닙니다.")
|
||||
logger.debug("입력 전송: %s", text)
|
||||
result = self._run_tmux(["send-keys", "-t", self.session_name, text, "C-m"])
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError("tmux 입력 전송에 실패했습니다.")
|
||||
|
||||
def read_output(self, timeout: int = 5) -> str:
|
||||
"""세션 pane 출력을 읽는다."""
|
||||
_ = timeout
|
||||
if not self.is_alive:
|
||||
raise RuntimeError("프로세스가 실행 중이 아닙니다.")
|
||||
current = self._capture_lines()
|
||||
delta_lines = self._diff_lines(self._last_capture, current)
|
||||
self._last_capture = current
|
||||
return "\n".join(delta_lines).strip()
|
||||
|
||||
def stop(self) -> None:
|
||||
"""브릿지 연결만 종료한다(원격 세션은 유지)."""
|
||||
if self._connected:
|
||||
logger.info("tmux 세션 연결 해제")
|
||||
self._connected = False
|
||||
self._last_capture = []
|
||||
130
src/lazy_enter/slack_handler.py
Normal file
130
src/lazy_enter/slack_handler.py
Normal file
@@ -0,0 +1,130 @@
|
||||
"""Slack Socket Mode 이벤트 핸들링."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from slack_bolt import App
|
||||
from slack_bolt.adapter.socket_mode import SocketModeHandler
|
||||
from slack_sdk import WebClient
|
||||
|
||||
from lazy_enter.config import Config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SlackHandler:
|
||||
"""Slack 앱과의 통신을 담당한다."""
|
||||
|
||||
def __init__(self, config: Config) -> None:
|
||||
self.config = config
|
||||
self.app = App(token=config.slack_bot_token)
|
||||
self._handler: SocketModeHandler | None = None
|
||||
self._stop_requested = False
|
||||
self._on_message_callback: callable | None = None
|
||||
self._on_command_callback: callable | None = None
|
||||
|
||||
self._register_listeners()
|
||||
|
||||
@property
|
||||
def client(self) -> WebClient:
|
||||
return self.app.client
|
||||
|
||||
def _is_authorized(self, user_id: str, channel_id: str) -> bool:
|
||||
"""허가된 사용자·채널인지 확인한다."""
|
||||
if self.config.allowed_user_id and user_id != self.config.allowed_user_id:
|
||||
return False
|
||||
if (
|
||||
self.config.allowed_channel_id
|
||||
and channel_id != self.config.allowed_channel_id
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
def _register_listeners(self) -> None:
|
||||
"""Slack 이벤트 리스너를 등록한다."""
|
||||
|
||||
@self.app.event("message")
|
||||
def handle_message(event: dict, say: callable) -> None:
|
||||
user_id = event.get("user", "")
|
||||
channel_id = event.get("channel", "")
|
||||
text = event.get("text", "")
|
||||
|
||||
if not self._is_authorized(user_id, channel_id):
|
||||
return
|
||||
|
||||
if self._on_message_callback:
|
||||
self._on_message_callback(text, channel_id)
|
||||
|
||||
@self.app.command("/start-claude")
|
||||
def handle_start(ack: callable, body: dict) -> None:
|
||||
ack()
|
||||
user_id = body.get("user_id", "")
|
||||
channel_id = body.get("channel_id", "")
|
||||
|
||||
if not self._is_authorized(user_id, channel_id):
|
||||
return
|
||||
|
||||
if self._on_command_callback:
|
||||
self._on_command_callback("start", channel_id)
|
||||
|
||||
@self.app.command("/stop-claude")
|
||||
def handle_stop(ack: callable, body: dict) -> None:
|
||||
ack()
|
||||
user_id = body.get("user_id", "")
|
||||
channel_id = body.get("channel_id", "")
|
||||
|
||||
if not self._is_authorized(user_id, channel_id):
|
||||
return
|
||||
|
||||
if self._on_command_callback:
|
||||
self._on_command_callback("stop", channel_id)
|
||||
|
||||
def on_message(self, callback: callable) -> None:
|
||||
"""메시지 수신 콜백을 등록한다."""
|
||||
self._on_message_callback = callback
|
||||
|
||||
def on_command(self, callback: callable) -> None:
|
||||
"""슬래시 커맨드 콜백을 등록한다."""
|
||||
self._on_command_callback = callback
|
||||
|
||||
def send_message(
|
||||
self, channel: str, text: str, thread_ts: str | None = None
|
||||
) -> None:
|
||||
"""슬랙 채널에 메시지를 전송한다."""
|
||||
self.client.chat_postMessage(
|
||||
channel=channel,
|
||||
text=text,
|
||||
thread_ts=thread_ts,
|
||||
)
|
||||
|
||||
def start(self) -> None:
|
||||
"""Socket Mode 핸들러를 시작한다. 연결이 끊기면 재연결한다."""
|
||||
self._stop_requested = False
|
||||
logger.info("Slack Socket Mode 시작")
|
||||
|
||||
while not self._stop_requested:
|
||||
try:
|
||||
self._handler = SocketModeHandler(self.app, self.config.slack_app_token)
|
||||
self._handler.start()
|
||||
except Exception:
|
||||
if self._stop_requested:
|
||||
break
|
||||
logger.exception("Socket Mode 연결이 종료되었습니다.")
|
||||
|
||||
if self._stop_requested:
|
||||
break
|
||||
|
||||
logger.warning(
|
||||
"Socket Mode 재연결 시도 (%s초 후)",
|
||||
self.config.reconnect_delay_seconds,
|
||||
)
|
||||
time.sleep(self.config.reconnect_delay_seconds)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Socket Mode 핸들러를 종료한다."""
|
||||
logger.info("Slack Socket Mode 종료")
|
||||
self._stop_requested = True
|
||||
if self._handler is not None:
|
||||
self._handler.close()
|
||||
0
tests/__init__.py
Normal file
0
tests/__init__.py
Normal file
37
tests/test_config.py
Normal file
37
tests/test_config.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""Config 테스트."""
|
||||
|
||||
import pytest
|
||||
|
||||
from lazy_enter.config import Config
|
||||
|
||||
|
||||
def test_config_defaults():
|
||||
config = Config()
|
||||
assert config.tmux_session_name == "claude"
|
||||
assert config.pty_read_timeout == 5
|
||||
assert config.output_buffer_interval == 2.0
|
||||
assert config.max_message_length == 3000
|
||||
assert config.reconnect_delay_seconds == 5.0
|
||||
assert config.output_idle_report_seconds == 120
|
||||
assert config.input_idle_report_seconds == 300
|
||||
|
||||
|
||||
def test_validate_required_settings_missing() -> None:
|
||||
config = Config()
|
||||
config.slack_bot_token = ""
|
||||
config.slack_app_token = ""
|
||||
config.allowed_user_id = ""
|
||||
config.allowed_channel_id = ""
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
config.validate_required_settings()
|
||||
|
||||
|
||||
def test_validate_required_settings_ok() -> None:
|
||||
config = Config()
|
||||
config.slack_bot_token = "xoxb-test"
|
||||
config.slack_app_token = "xapp-test"
|
||||
config.allowed_user_id = "U000"
|
||||
config.allowed_channel_id = "C000"
|
||||
|
||||
config.validate_required_settings()
|
||||
34
tests/test_hooks.py
Normal file
34
tests/test_hooks.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""hooks 모듈 테스트."""
|
||||
|
||||
from lazy_enter.hooks import format_notification, parse_hook_event
|
||||
|
||||
|
||||
def test_parse_hook_event_valid():
|
||||
raw = '{"type": "prompt", "tool": "Bash"}'
|
||||
event = parse_hook_event(raw)
|
||||
assert event["type"] == "prompt"
|
||||
assert event["tool"] == "Bash"
|
||||
|
||||
|
||||
def test_parse_hook_event_invalid():
|
||||
event = parse_hook_event("not json")
|
||||
assert event == {}
|
||||
|
||||
|
||||
def test_format_notification_prompt():
|
||||
event = {"type": "prompt", "tool": "Bash"}
|
||||
msg = format_notification(event)
|
||||
assert msg is not None
|
||||
assert "승인 대기 중" in msg
|
||||
|
||||
|
||||
def test_format_notification_completion():
|
||||
event = {"type": "completion", "summary": "리팩토링 완료"}
|
||||
msg = format_notification(event)
|
||||
assert msg is not None
|
||||
assert "완료" in msg
|
||||
|
||||
|
||||
def test_format_notification_unknown():
|
||||
event = {"type": "unknown"}
|
||||
assert format_notification(event) is None
|
||||
18
tests/test_output_filter.py
Normal file
18
tests/test_output_filter.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""output_filter 모듈 테스트."""
|
||||
|
||||
from lazy_enter.output_filter import clean_terminal_output
|
||||
|
||||
|
||||
def test_clean_terminal_output_removes_ansi_sequences():
|
||||
raw = "\x1b[?2004h\x1b[38;2;153;153;153mClaude Code\x1b[39m"
|
||||
assert clean_terminal_output(raw) == "Claude Code"
|
||||
|
||||
|
||||
def test_clean_terminal_output_removes_broken_csi_tokens():
|
||||
raw = "[?2004h[38;2;153;153;153mhello[39m"
|
||||
assert clean_terminal_output(raw) == "hello"
|
||||
|
||||
|
||||
def test_clean_terminal_output_preserves_plain_text():
|
||||
raw = "line1\nline2"
|
||||
assert clean_terminal_output(raw) == "line1\nline2"
|
||||
103
tests/test_pty_manager.py
Normal file
103
tests/test_pty_manager.py
Normal file
@@ -0,0 +1,103 @@
|
||||
"""PtyManager 테스트."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
|
||||
from lazy_enter.pty_manager import PtyManager
|
||||
|
||||
|
||||
@dataclass
|
||||
class Result:
|
||||
returncode: int
|
||||
stdout: str = ""
|
||||
|
||||
|
||||
def test_initial_state():
|
||||
pty = PtyManager("claude")
|
||||
assert not pty.is_alive
|
||||
|
||||
|
||||
def test_start_raises_when_tmux_session_missing(monkeypatch: pytest.MonkeyPatch):
|
||||
def fake_run(
|
||||
cmd: Sequence[str],
|
||||
check: bool,
|
||||
capture_output: bool,
|
||||
text: bool,
|
||||
):
|
||||
assert list(cmd) == ["tmux", "has-session", "-t", "claude"]
|
||||
assert check is False
|
||||
assert capture_output is True
|
||||
assert text is True
|
||||
|
||||
return Result(returncode=1)
|
||||
|
||||
monkeypatch.setattr("lazy_enter.pty_manager.subprocess.run", fake_run)
|
||||
|
||||
pty = PtyManager("claude")
|
||||
with pytest.raises(RuntimeError):
|
||||
pty.start()
|
||||
|
||||
|
||||
def test_start_send_read_and_stop(monkeypatch: pytest.MonkeyPatch):
|
||||
calls: list[list[str]] = []
|
||||
|
||||
def fake_run(
|
||||
cmd: Sequence[str],
|
||||
check: bool,
|
||||
capture_output: bool,
|
||||
text: bool,
|
||||
):
|
||||
calls.append(list(cmd))
|
||||
assert check is False
|
||||
assert capture_output is True
|
||||
assert text is True
|
||||
|
||||
if cmd[:4] == ["tmux", "has-session", "-t", "claude"]:
|
||||
return Result(returncode=0)
|
||||
if cmd[:7] == ["tmux", "capture-pane", "-p", "-t", "claude", "-S", "-200"]:
|
||||
# 첫 캡처는 baseline, 두 번째 캡처에서 한 줄 증가.
|
||||
if calls.count(list(cmd)) == 1:
|
||||
return Result(returncode=0, stdout="line1\nline2\n")
|
||||
return Result(returncode=0, stdout="line1\nline2\nline3\n")
|
||||
if cmd[:6] == ["tmux", "send-keys", "-t", "claude", "hello", "C-m"]:
|
||||
return Result(returncode=0)
|
||||
return Result(returncode=1)
|
||||
|
||||
monkeypatch.setattr("lazy_enter.pty_manager.subprocess.run", fake_run)
|
||||
|
||||
pty = PtyManager("claude")
|
||||
pty.start()
|
||||
assert pty.is_alive
|
||||
|
||||
pty.send("hello")
|
||||
assert pty.read_output() == "line3"
|
||||
|
||||
pty.stop()
|
||||
assert not pty.is_alive
|
||||
|
||||
|
||||
def test_read_output_returns_empty_when_unchanged(monkeypatch: pytest.MonkeyPatch):
|
||||
def fake_run(
|
||||
cmd: Sequence[str],
|
||||
check: bool,
|
||||
capture_output: bool,
|
||||
text: bool,
|
||||
):
|
||||
assert check is False
|
||||
assert capture_output is True
|
||||
assert text is True
|
||||
if cmd[:4] == ["tmux", "has-session", "-t", "claude"]:
|
||||
return Result(returncode=0)
|
||||
if cmd[:7] == ["tmux", "capture-pane", "-p", "-t", "claude", "-S", "-200"]:
|
||||
return Result(returncode=0, stdout="same\n")
|
||||
return Result(returncode=1)
|
||||
|
||||
monkeypatch.setattr("lazy_enter.pty_manager.subprocess.run", fake_run)
|
||||
|
||||
pty = PtyManager("claude")
|
||||
pty.start()
|
||||
assert pty.read_output() == ""
|
||||
Reference in New Issue
Block a user