Add contributor guide and project usage docs

This commit is contained in:
2026-02-16 22:48:05 +09:00
parent 1e552f8c46
commit 87482efd6d
16 changed files with 671 additions and 1 deletions

View File

@@ -0,0 +1,3 @@
"""LazyEnter - Slack을 통한 Claude Code 원격 제어 브릿지."""
__version__ = "0.1.0"

View File

@@ -0,0 +1,12 @@
"""CLI 엔트리포인트."""
from lazy_enter.bridge import Bridge
def main() -> None:
bridge = Bridge()
bridge.run()
if __name__ == "__main__":
main()

109
src/lazy_enter/bridge.py Normal file
View File

@@ -0,0 +1,109 @@
"""Bridge Agent - Slack과 PTY 프로세스를 연결하는 핵심 중계 로직."""
from __future__ import annotations
import logging
import threading
import time
from lazy_enter.config import Config
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.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.pty and self.pty.is_alive:
self.pty.send(text)
logger.info("입력 전달: %s", text)
else:
self.slack.send_message(channel, ":warning: 실행 중인 세션이 없습니다.")
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 Code 세션을 시작한다."""
if self.pty and self.pty.is_alive:
self.slack.send_message(
channel, ":information_source: 이미 세션이 실행 중입니다."
)
return
self._channel = channel
self.pty = PtyManager(self.config.default_shell)
self.pty.start()
self._running = True
self._output_thread = threading.Thread(target=self._poll_output, daemon=True)
self._output_thread.start()
self.slack.send_message(channel, ":rocket: Claude Code 세션이 시작되었습니다.")
def _stop_session(self, channel: str) -> None:
"""Claude Code 세션을 종료한다."""
self._running = False
if self.pty:
self.pty.stop()
self.pty = None
self.slack.send_message(channel, ":stop_sign: 세션이 종료되었습니다.")
def _poll_output(self) -> None:
"""PTY 출력을 주기적으로 읽어 Slack으로 전송한다."""
buffer = ""
while self._running and self.pty and self.pty.is_alive:
output = self.pty.read_output(timeout=self.config.pty_read_timeout)
if output:
buffer += output
if buffer:
# 메시지 길이 제한 적용
message = buffer[: self.config.max_message_length]
if len(buffer) > self.config.max_message_length:
message += "\n... (truncated)"
self.slack.send_message(self._channel, f"```\n{message}\n```")
buffer = ""
time.sleep(self.config.output_buffer_interval)
if not self._running:
return
# 프로세스가 예기치 않게 종료된 경우
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()

27
src/lazy_enter/config.py Normal file
View File

@@ -0,0 +1,27 @@
"""환경 변수 및 설정 관리."""
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
default_shell: str = os.getenv("DEFAULT_SHELL", "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"))

60
src/lazy_enter/hooks.py Normal file
View 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()

View File

@@ -0,0 +1,56 @@
"""pexpect 기반 PTY 프로세스 관리."""
from __future__ import annotations
import logging
import pexpect
logger = logging.getLogger(__name__)
class PtyManager:
"""가상 터미널에서 CLI 프로세스를 생성하고 입출력을 제어한다."""
def __init__(self, command: str = "claude") -> None:
self.command = command
self._process: pexpect.spawn | None = None
@property
def is_alive(self) -> bool:
return self._process is not None and self._process.isalive()
def start(self) -> None:
"""프로세스를 시작한다."""
logger.info("프로세스 시작: %s", self.command)
self._process = pexpect.spawn(
self.command,
encoding="utf-8",
timeout=None,
)
def send(self, text: str) -> None:
"""프로세스에 텍스트 입력을 전달한다."""
if not self.is_alive:
raise RuntimeError("프로세스가 실행 중이 아닙니다.")
assert self._process is not None
logger.debug("입력 전송: %s", text)
self._process.sendline(text)
def read_output(self, timeout: int = 5) -> str:
"""프로세스의 출력을 읽는다."""
if not self.is_alive:
raise RuntimeError("프로세스가 실행 중이 아닙니다.")
assert self._process is not None
try:
self._process.expect(pexpect.TIMEOUT, timeout=timeout)
except pexpect.TIMEOUT:
pass
return self._process.before or ""
def stop(self) -> None:
"""프로세스를 종료한다."""
if self._process is not None:
logger.info("프로세스 종료")
self._process.close(force=True)
self._process = None

View File

@@ -0,0 +1,108 @@
"""Slack Socket Mode 이벤트 핸들링."""
from __future__ import annotations
import logging
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(self.app, config.slack_app_token)
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 핸들러를 시작한다."""
logger.info("Slack Socket Mode 시작")
self._handler.start()
def stop(self) -> None:
"""Socket Mode 핸들러를 종료한다."""
logger.info("Slack Socket Mode 종료")
self._handler.close()