# /// script
# requires-python = ">=3.11"
# dependencies = ["slack-bolt>=1.20"]
# ///
"""Slack to Claude Code bridge: one Slack thread = one worktree, branch, and session."""
import json
import logging
import os
import re
import signal
import subprocess
import threading
from pathlib import Path
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
log = logging.getLogger("bridge")
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
WORK = Path("/home/agent/work")
STATE_DIR = Path("/root/slack-agent/state") # root only; the agent user can't read it
RUN_AS = ["runuser", "-u", "agent", "--"]
CHILD_ENV = {"HOME": "/home/agent", "LANG": "C.UTF-8",
"PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin")}
REPO = os.environ["AGENT_REPO"]
ALLOWED_USERS = {u for u in os.environ.get("AGENT_ALLOWED_USERS", "").split(",") if u}
ALLOWED_TOOLS = os.environ.get("AGENT_ALLOWED_TOOLS", "Bash(git:*),Bash(gh:*)").split(",")
MAX_PARALLEL = 3
TIMEOUT_S = 3600
SYSTEM_PROMPT = (
"You are a coding agent driven from Slack. Work only in the current git worktree, "
"on its current branch. Implement the request, run the relevant checks, commit, push "
"the branch, and open or update a pull request with gh. NEVER merge a pull request, "
"enable auto-merge, or push to the default branch. Reply for Slack: short, plain "
"text, ending with the pull request link or what blocked you."
)
if not ALLOWED_USERS:
raise SystemExit("Set AGENT_ALLOWED_USERS to a comma-separated list of Slack member IDs")
app = App(token=os.environ["SLACK_BOT_TOKEN"])
BOT_ID = app.client.auth_test()["user_id"]
sem = threading.Semaphore(MAX_PARALLEL)
locks: dict[str, threading.Lock] = {}
seen: set[str] = set()
guard = threading.Lock()
repo_lock = threading.Lock()
def sh(*cmd, cwd=None, timeout=600):
return subprocess.run([*RUN_AS, *cmd], cwd=cwd, env=CHILD_ENV, capture_output=True,
text=True, timeout=timeout, check=True).stdout.strip()
def repo_dir() -> Path:
d = WORK / "repo"
with repo_lock: # threads start in parallel; clone once
if not d.exists():
sh("mkdir", "-p", str(WORK))
sh("gh", "repo", "clone", REPO, str(d))
return d
def state_path(key: str) -> Path:
return STATE_DIR / (key.replace(".", "_") + ".json")
def load_state(key: str) -> dict:
p = state_path(key)
return json.loads(p.read_text()) if p.exists() else {}
def save_state(key: str, st: dict) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
state_path(key).write_text(json.dumps(st))
def ensure_worktree(key: str, st: dict, text: str) -> dict:
if st.get("worktree") and Path(st["worktree"]).exists():
return st
repo = repo_dir()
sh("git", "fetch", "origin", cwd=repo)
base = sh("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=repo)
slug = re.sub(r"[^a-z0-9]+", "-", text.lower())[:30].strip("-") or "task"
thread_id = re.sub(r"[^a-z0-9]+", "-", key.lower()) # unique per Slack thread
branch = f"agent/{slug}-{thread_id}"
wt = WORK / "threads" / key.replace(".", "_")
sh("mkdir", "-p", str(wt.parent))
sh("git", "worktree", "add", "-b", branch, str(wt), base, cwd=repo)
st.update(worktree=str(wt), branch=branch)
save_state(key, st)
return st
def run_claude(prompt: str, st: dict) -> tuple[str, bool]:
cmd = ["claude", "-p", prompt, "--output-format", "json",
"--permission-mode", "acceptEdits",
"--allowedTools", *ALLOWED_TOOLS,
"--append-system-prompt", SYSTEM_PROMPT]
if st.get("session_id"):
cmd += ["--resume", st["session_id"]]
env = {**CHILD_ENV, "CLAUDE_CODE_OAUTH_TOKEN": os.environ["CLAUDE_CODE_OAUTH_TOKEN"]}
# Own process group, so a timeout stops Claude and everything it started.
p = subprocess.Popen([*RUN_AS, *cmd], cwd=st["worktree"], env=env, text=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
start_new_session=True)
try:
stdout, stderr = p.communicate(timeout=TIMEOUT_S)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.communicate()
return f"Timed out after {TIMEOUT_S}s.", False
try:
out = json.loads(stdout)
except json.JSONDecodeError:
return (stderr or stdout or "No output")[-3000:], False
st["session_id"] = out.get("session_id", st.get("session_id"))
return out.get("result") or "(no result)", not out.get("is_error", False)
def thread_context(client, channel, thread_ts, msg_ts, since=None):
"""Thread messages before this one that the agent hasn't seen yet, oldest first."""
try:
kw = dict(channel=channel, ts=thread_ts, limit=200)
if since:
kw["oldest"] = since
msgs = client.conversations_replies(**kw)["messages"]
except Exception as e:
log.warning("thread read failed: %s", e)
return "", since
lines = []
for m in msgs:
# Later messages get their own run, so leave them out of this one.
if float(m["ts"]) >= float(msg_ts) or m.get("user") == BOT_ID:
continue
parts = [m.get("text", "")] + [a.get("text") or a.get("fallback") or ""
for a in m.get("attachments", [])]
body = "\n".join(p for p in parts if p).strip()
if body:
lines.append(f"<{m.get('user') or m.get('bot_id')}> {body}")
return "\n\n".join(lines)[-12000:], msg_ts
def post(client, channel, ts, text):
for i in range(0, max(len(text), 1), 3500):
client.chat_postMessage(channel=channel, thread_ts=ts, text=text[i:i + 3500])
def react(client, channel, ts, add=None, remove=None):
for name, fn in ((remove, client.reactions_remove), (add, client.reactions_add)):
if name:
try:
fn(channel=channel, timestamp=ts, name=name)
except Exception:
pass
def work(client, channel, msg_ts, thread_ts, text):
key = f"{channel}-{thread_ts}"
with guard:
lock = locks.setdefault(key, threading.Lock())
with lock, sem:
react(client, channel, msg_ts, add="eyes")
ok = False
try:
st = ensure_worktree(key, load_state(key), text)
ctx, seen_ts = thread_context(client, channel, thread_ts, msg_ts,
st.get("last_ts"))
prompt = text if not ctx else (
"Slack thread messages you have not seen yet (oldest first):\n" + ctx
+ "\n\nCurrent request from the user:\n" + text)
reply, ok = run_claude(prompt, st)
if ok: # on failure, resend this context with the next request
st["last_ts"] = seen_ts
save_state(key, st)
except Exception as e:
log.exception("run failed")
reply = f"Failed: {e}"
post(client, channel, thread_ts, reply)
react(client, channel, msg_ts, add="white_check_mark" if ok else "x", remove="eyes")
def handle(event, client):
if event.get("bot_id") or event.get("subtype") or event.get("user") not in ALLOWED_USERS:
return
ch, ts = event["channel"], event["ts"]
with guard:
if ts in seen:
return
seen.add(ts)
thread_ts = event.get("thread_ts") or ts
text = re.sub(rf"<@{BOT_ID}>", "", event.get("text", "")).strip()
if text:
key = f"{ch}-{thread_ts}"
if not load_state(key): # so replies count as follow-ups while it sets up
save_state(key, {"accepted": True})
threading.Thread(target=work, args=(client, ch, ts, thread_ts, text),
daemon=True).start()
@app.event("app_mention")
def on_mention(event, client):
handle(event, client)
@app.event("message")
def on_message(event, client):
mentioned = f"<@{BOT_ID}>" in event.get("text", "")
is_dm = event.get("channel_type") == "im"
in_active_thread = bool(event.get("thread_ts")) and bool(
load_state(f"{event['channel']}-{event['thread_ts']}"))
# Channel mentions arrive via app_mention. DMs never do, even with a mention.
if is_dm or (in_active_thread and not mentioned):
handle(event, client)
if __name__ == "__main__":
log.info("bridge up as %s, repo=%s", BOT_ID, REPO)
SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()