> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sailresearch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Run a background coding agent on Sail

> Run Claude Code or Codex in a private, always-on Sailbox with the subscription you already have, and give it tasks from Slack.

Give your coding agent [one prompt](#copy-agent-prompt-recommended) to set up Claude Code or Codex in a private [devbox](https://docs.sailresearch.com/sailboxes-devboxes). It signs in with the subscription you already have, runs in the cloud, and you can reach it from anywhere.

**Once you're finished, you'll have:**

* An always-on Sailbox running Claude Code, Codex, or both, signed in with your Claude or ChatGPT subscription.
* Optionally, a Slack bot that takes a task in a thread, works on its own branch, and replies with a pull request.

**Why run it on Sail?**

* The agent keeps working even when your laptop is closed.
* You [pay for the CPU, memory, and disk the Sailbox actually uses](https://docs.sailresearch.com/sailboxes-pricing.md).
* The devbox is private, so only you can use the logins stored on it. The Slack bridge connects out over Socket Mode, so the Sailbox needs no public URL.

## Copy agent prompt (recommended):

Share this page with your coding agent or paste the prompt below.

```text theme={null}
Follow https://docs.sailresearch.com/background-coding-agent to set up a private
Sail devbox running Claude Code and/or Codex, signed in with my existing
subscription, not an API key. Ask me which agents I want and whether to add the
Slack bridge. If I want Slack, ask for the GitHub repo, the bot name, and my
Slack member ID. Stop and tell me exactly what to open whenever I need to sign
in or approve something. Never set ANTHROPIC_API_KEY or OPENAI_API_KEY, print a
credential, or make the devbox shared. Test that each agent answers a one-line
prompt and, for Slack, that a small task in a thread gets a pull request link.
Tell me what you tested and what still needs a check.
```

## Manual steps

### 1. Install the Sail CLI and sign in

You'll need a Mac or Linux machine, an SSH key, and a Claude Pro or Max subscription, a ChatGPT Plus, Pro, or Business subscription, or both.

```bash theme={null}
curl -fsSL https://cli.sailresearch.com/install.sh | sh
sail auth login
```

`sail auth login` opens your browser. A private devbox needs a login tied to your own account, not an organization service key. If you don't have an SSH key, create one with `ssh-keygen -t ed25519`.

### 2. Create the devbox

Pick the agents you want with `--with`:

```bash theme={null}
sail box devbox up my-agent --with claude,codex
sail box auto-sleep <sailbox-id> never
```

`up` creates a private Sailbox from the [devbox image](https://docs.sailresearch.com/sailbox-sdk-images.md), installs the agents, adds an SSH shortcut such as `my-agent.sail`, and prints the Sailbox ID. Setting [auto-sleep](https://docs.sailresearch.com/sailboxes-autosleep) to `never` keeps the agent available while you're away. It's billed while it runs.

### 3. Sign in with your subscription

Open a shell on the devbox with `sail box shell <sailbox-id>`. Sign-in pages it opens appear in your local browser.

For Claude Code, create a long-lived token. Sign in when the browser opens and paste the code back.

```bash theme={null}
claude setup-token
```

Save the token in a file only you can read, and load it now and in every new shell:

```bash theme={null}
install -m 600 /dev/null ~/.agent.env
echo 'export CLAUDE_CODE_OAUTH_TOKEN=<token>' >> ~/.agent.env
echo '. ~/.agent.env' >> ~/.bashrc
. ~/.agent.env
```

For Codex, sign in with your ChatGPT account:

```bash theme={null}
codex login --device-auth
```

Don't set `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` on the devbox. Either one switches the agent to API billing instead of your subscription.

Check that each agent answers:

```bash theme={null}
claude -p "Reply with OK"
codex exec "Reply with OK"
```

### 4. Start a session that keeps running

Start the agent in tmux, so it keeps working after you disconnect:

```bash theme={null}
tmux new -s agent
claude
```

Reattach later with `tmux attach -t agent`. To work in your editor instead, see [connect](https://docs.sailresearch.com/sailboxes-devboxes#connect).

## Connect Slack (optional)

The bridge listens for mentions over Socket Mode and runs Claude Code headlessly for each request. Every Slack thread gets its own git worktree, branch, and Claude session, so several threads can run at once. Replies in the same thread continue the same session. The agent opens pull requests and never merges them.

### 1. Create the Slack app

At [api.slack.com/apps](https://api.slack.com/apps), choose **Create New App**, then **From a manifest**, and paste this. Change the name if you like.

```json theme={null}
{
  "display_information": { "name": "coding-agent" },
  "features": {
    "app_home": {
      "messages_tab_enabled": true,
      "messages_tab_read_only_enabled": false
    },
    "bot_user": { "display_name": "coding-agent", "always_online": true }
  },
  "oauth_config": {
    "scopes": {
      "bot": [
        "app_mentions:read",
        "chat:write",
        "reactions:write",
        "channels:history",
        "groups:history",
        "im:history",
        "im:read",
        "im:write"
      ]
    }
  },
  "settings": {
    "event_subscriptions": {
      "bot_events": [
        "app_mention",
        "message.channels",
        "message.groups",
        "message.im"
      ]
    },
    "interactivity": { "is_enabled": false },
    "org_deploy_enabled": false,
    "socket_mode_enabled": true
  }
}
```

Install the app in your workspace. Under **Basic Information**, create an app-level token with the `connections:write` scope. Invite the bot to a test channel, and copy your Slack member ID from your profile.

### 2. Give the agent its own user

The bridge runs as root and starts Claude as a separate `agent` user. The agent can't read the Slack tokens or the bridge's state. On the devbox, as root:

```bash theme={null}
useradd --create-home --shell /bin/bash agent
runuser -u agent -- gh auth login --web
runuser -u agent -- git config --global user.name "Coding agent"
runuser -u agent -- git config --global user.email "<your-email>"
install -d -m 700 /root/slack-agent
```

Create `/root/slack-agent/.env` with mode `0600`:

| Variable | What to enter |
| - | - |
| `SLACK_BOT_TOKEN` | The bot token (`xoxb-`) from **OAuth & Permissions** |
| `SLACK_APP_TOKEN` | The app-level token (`xapp-`) with `connections:write` |
| `CLAUDE_CODE_OAUTH_TOKEN` | The token from `claude setup-token` |
| `AGENT_REPO` | The GitHub repository, as `owner/name` |
| `AGENT_ALLOWED_USERS` | Comma-separated Slack member IDs. The bot ignores everyone else. |
| `AGENT_ALLOWED_TOOLS` | The commands the agent may run, for example `"Bash(git:*),Bash(gh:*)"` |

Quote any value that contains parentheses, as in the example above. The file is loaded by the shell, and an unquoted parenthesis breaks it.

### 3. Add the bridge

> [accordion] Save the bridge as /root/slack-agent/bridge.py
>
> ```python bridge.py theme={null}
> # /// 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()
> ```

The bridge passes the agent only its Claude token and a minimal environment. It reads earlier messages in the thread before each run, so the agent knows what a follow-up refers to.

### 4. Start it and test from Slack

Run the bridge in tmux with a restart loop, so it comes back after a crash:

```bash theme={null}
tmux new-session -d -s bridge 'set -a; . /root/slack-agent/.env; set +a; while true; do uv run /root/slack-agent/bridge.py; sleep 5; done'
```

Check `tmux attach -t bridge` for `bridge up as`, then test from Slack:

1. Mention the bot in the test channel with a small task. It reacts with 👀 while it works, then replies in the thread with a pull request link and ✅.
2. Reply in the same thread without a mention, for example "also update the README". It should continue on the same branch.
3. Ask the bot something from an account that isn't in `AGENT_ALLOWED_USERS`. It should stay silent.
