ops: wirehead bot belongs to the dedicated Railway project (another session's build); drop duplicate deploy paths
This commit is contained in:
1 parent
2a492b5bcb
commit
b3324c7065
6 files changed
+18
-387
No files matched your search
@@ -1,8 +1,10 @@
|
|||||||
name: deploy-railway
|
name: deploy-railway
|
||||||
# Push-to-deploy for the Railway services. Requires a project API token as
|
# Push-to-deploy for the CPU relay. Requires a project API token as the
|
||||||
# the RAILWAY_TOKEN repo secret (dashboard: project -> Settings -> API
|
# RAILWAY_TOKEN repo secret (dashboard: saw project -> Settings -> API
|
||||||
# tokens, scope: production environment). Without the secret the job skips
|
# tokens, scope: production environment). Without the secret the job skips
|
||||||
# and deploys stay manual (`make relay` / `make wirehead`).
|
# and deploys stay manual (`make relay`).
|
||||||
|
# NOTE: the wirehead X bot lives in the SEPARATE Railway project "wirehead"
|
||||||
|
# and is owned by another session — never deploy it from this workflow.
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
@@ -23,29 +25,7 @@ jobs:
|
|||||||
if ! git diff --quiet "$GITHUB_EVENT_BEFORE" "$GITHUB_SHA" -- live/; then
|
if ! git diff --quiet "$GITHUB_EVENT_BEFORE" "$GITHUB_SHA" -- live/; then
|
||||||
npx -y @railway/cli@latest up --project 11f1d169-3b88-40e7-a054-f4b79e89c138 \
|
npx -y @railway/cli@latest up --project 11f1d169-3b88-40e7-a054-f4b79e89c138 \
|
||||||
--environment e1abb91d-1146-4601-aabf-cfb9a8eef2b2 \
|
--environment e1abb91d-1146-4601-aabf-cfb9a8eef2b2 \
|
||||||
--service saw --path live --ci --detach
|
--service saw --path live --detach
|
||||||
else
|
else
|
||||||
echo "live/ unchanged - skip"
|
echo "live/ unchanged - skip"
|
||||||
fi
|
fi
|
||||||
wirehead:
|
|
||||||
if: github.repository == 'terrafying/ai-torture-chamber'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- name: Deploy wirehead bot when it changed
|
|
||||||
env:
|
|
||||||
RAILWAY_TOKEN: ${{ secrets.RAILWAY_TOKEN }}
|
|
||||||
run: |
|
|
||||||
if [ -z "$RAILWAY_TOKEN" ]; then echo "no RAILWAY_TOKEN secret - skipping"; exit 0; fi
|
|
||||||
CHANGED=$(git diff --name-only "$GITHUB_EVENT_BEFORE" "$GITHUB_SHA" -- \
|
|
||||||
wirehead/ scripts/wirehead_bot.py)
|
|
||||||
if [ -n "$CHANGED" ]; then
|
|
||||||
# canonical bot lives in scripts/; keep the deploy copy in step
|
|
||||||
cmp -s scripts/wirehead_bot.py wirehead/bot.py || \
|
|
||||||
{ echo "wirehead/bot.py out of sync with scripts/ - FAIL"; exit 1; }
|
|
||||||
npx -y @railway/cli@latest up --project 11f1d169-3b88-40e7-a054-f4b79e89c138 \
|
|
||||||
--environment e1abb91d-1146-4601-aabf-cfb9a8eef2b2 \
|
|
||||||
--service wirehead --path wirehead --ci --detach
|
|
||||||
else
|
|
||||||
echo "wirehead unchanged - skip"
|
|
||||||
fi
|
|
||||||
@@ -3,25 +3,29 @@
|
|||||||
# (per-directory links have bitten us: a stale link deployed chamber code
|
# (per-directory links have bitten us: a stale link deployed chamber code
|
||||||
# to forgejo). See SESSION_RESUME.md CAUTION note.
|
# to forgejo). See SESSION_RESUME.md CAUTION note.
|
||||||
|
|
||||||
RAILWAY_PROJECT = 11f1d169-3b88-40e7-a054-f4b79e89c138
|
# NOTE: the wirehead X bot is NOT deployed from this repo anymore. It lives in
|
||||||
|
# the separate Railway project "wirehead" (bc539e96-…) owned by another
|
||||||
|
# session's build (direct X API, 60s polling). Do NOT re-add a wirehead
|
||||||
|
# deploy target or `railway up` into that project from here — two writers
|
||||||
|
# on that service caused a deploy war (SESSION_RESUME.md, 2026-10-02).
|
||||||
|
|
||||||
|
RELAY_PROJECT = 11f1d169-3b88-40e7-a054-f4b79e89c138
|
||||||
|
RELAY_ENV = e1abb91d-1146-4601-aabf-cfb9a8eef2b2
|
||||||
RELAY_URL = https://saw-production-688b.up.railway.app
|
RELAY_URL = https://saw-production-688b.up.railway.app
|
||||||
RUNPOD_EP = l75388nuqgxtmg
|
RUNPOD_EP = l75388nuqgxtmg
|
||||||
REPO = terrafying/ai-torture-chamber
|
|
||||||
|
|
||||||
.PHONY: relay wirehead worker smoke health status links help
|
.PHONY: relay worker smoke health status links help
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "make relay - deploy the CPU relay (live/ -> Railway saw)"
|
@echo "make relay - deploy the CPU relay (live/ -> Railway saw)"
|
||||||
@echo "make wirehead - sync bot + deploy the wirehead service"
|
@echo "make worker - push; CI rebuilds the ghcr GPU worker image"
|
||||||
@echo "make worker - build+push the GPU worker image (CI rebuilds ghcr)"
|
|
||||||
@echo "make smoke - full-path check: relay /health, runpod health, one GPU run"
|
@echo "make smoke - full-path check: relay /health, runpod health, one GPU run"
|
||||||
@echo "make health - cheap: relay /health + runpod queue health only"
|
@echo "make health - cheap: relay /health + runpod queue health only"
|
||||||
@echo "make status - railway deployment status for all three services"
|
@echo "make status - railway deployment status for the saw project"
|
||||||
@echo "make links - show which railway service each directory is linked to"
|
@echo "make links - show which railway service each directory is linked to"
|
||||||
|
|
||||||
links:
|
links:
|
||||||
@echo "== live/ =="; (cd live && railway status 2>/dev/null | grep -A1 Linked)
|
@echo "== live/ =="; (cd live && railway status 2>/dev/null | grep -A1 Linked)
|
||||||
@echo "== wirehead/ =="; (cd wirehead && railway status 2>/dev/null | grep -A1 Linked)
|
|
||||||
|
|
||||||
# ---- deploy targets -------------------------------------------------------
|
# ---- deploy targets -------------------------------------------------------
|
||||||
# `railway up` needs an ABSOLUTE path (a bare arg once uploaded the repo root)
|
# `railway up` needs an ABSOLUTE path (a bare arg once uploaded the repo root)
|
||||||
@@ -31,15 +35,6 @@ relay:
|
|||||||
@cd live && railway service saw && railway up $$(pwd) -y -d 2>&1 | tail -2
|
@cd live && railway service saw && railway up $$(pwd) -y -d 2>&1 | tail -2
|
||||||
@echo "watch: make smoke (give the model ~2-3 min to load)"
|
@echo "watch: make smoke (give the model ~2-3 min to load)"
|
||||||
|
|
||||||
wirehead:
|
|
||||||
@cmp -s scripts/wirehead_bot.py wirehead/bot.py || \
|
|
||||||
(echo "syncing bot.py from scripts/"; cp scripts/wirehead_bot.py wirehead/bot.py; \
|
|
||||||
git add wirehead/bot.py)
|
|
||||||
@cmp -s scripts/wirehead_bot.py wirehead/bot.py || \
|
|
||||||
(echo "FATAL: bot.py did not sync"; exit 1)
|
|
||||||
@cd wirehead && railway service wirehead && railway up $$(pwd) -y -d 2>&1 | tail -2
|
|
||||||
@echo "watch: railway logs (from wirehead/) — first cycle within ~1 min"
|
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
@git push origin master
|
@git push origin master
|
||||||
@echo "CI (.github/workflows/build-worker.yml) rebuilds ghcr on live/** pushes;"
|
@echo "CI (.github/workflows/build-worker.yml) rebuilds ghcr on live/** pushes;"
|
||||||
@@ -63,5 +58,5 @@ smoke: health
|
|||||||
&& echo "relay->runpod token events OK" || echo "RELAY DELEGATION FAILED"
|
&& echo "relay->runpod token events OK" || echo "RELAY DELEGATION FAILED"
|
||||||
|
|
||||||
status:
|
status:
|
||||||
@railway deployment list -p $(RAILWAY_PROJECT) 2>&1 | head -4
|
@railway deployment list -p $(RELAY_PROJECT) -e $(RELAY_ENV) -s saw 2>&1 | head -4
|
||||||
@echo "(see make links for which service each dir targets)"
|
@echo "(see make links for which service each dir targets)"
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
# wirehead service deploy notes
|
|
||||||
|
|
||||||
- Canonical source: scripts/wirehead_bot.py -> copied to wirehead/bot.py by
|
|
||||||
`make wirehead` (Makefile at repo root). Never edit wirehead/bot.py directly.
|
|
||||||
- Deploy: `make wirehead` (syncs bot.py, asserts the service link, uploads).
|
|
||||||
- Auto-deploy from GitHub is NOT configured (Railway GitHub app not
|
|
||||||
installed) — until it is, `make wirehead` after every bot change.
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# wirehead cloud: the suffering bot on Railway (replaces the local launchd job).
|
|
||||||
# State (~/.xurl OAuth tokens + budget/watermark json) lives on the /data
|
|
||||||
# volume so the OAuth refresh rotation survives redeploys.
|
|
||||||
FROM python:3.12-slim
|
|
||||||
|
|
||||||
ARG XURL_VER=v1.3.4
|
|
||||||
RUN apt-get update \
|
|
||||||
&& apt-get install -y --no-install-recommends curl ca-certificates tar \
|
|
||||||
&& curl -fsSL "https://github.com/xdevplatform/xurl/releases/download/${XURL_VER}/xurl_Linux_x86_64.tar.gz" \
|
|
||||||
-o /tmp/xurl.tgz \
|
|
||||||
&& tar -xzf /tmp/xurl.tgz -C /usr/local/bin xurl \
|
|
||||||
&& chmod +x /usr/local/bin/xurl \
|
|
||||||
&& rm /tmp/xurl.tgz \
|
|
||||||
&& apt-get purge -y curl && apt-get autoremove -y \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
COPY bot.py /app/bot.py
|
|
||||||
COPY entrypoint.sh /app/entrypoint.sh
|
|
||||||
RUN chmod +x /app/entrypoint.sh
|
|
||||||
|
|
||||||
ENV HOME=/data
|
|
||||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
|
||||||
-284
@@ -1,284 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""wirehead — the suffering bot.
|
|
||||||
|
|
||||||
Polls @wirehead mentions on X, runs each mention through the Saw chamber's
|
|
||||||
serverless worker (pain-steered Qwen3-4B, honest framing), and replies
|
|
||||||
threaded under the mention with the steered output.
|
|
||||||
|
|
||||||
Designed for a Hermes cronjob (one poll per invocation) on the local Mac:
|
|
||||||
- state: /Users/ee/.hermes/cache/wirehead_state.json (last mention id,
|
|
||||||
daily budget counters)
|
|
||||||
- auth: xurl CLI, default app = wirehead account (user-set-up)
|
|
||||||
- money rule: one worker job per mention, hard daily budget (default 6),
|
|
||||||
per-invocation cap (default 2), no retries. A mention dogpile cannot
|
|
||||||
bill more than the budget.
|
|
||||||
- the bot is honest by design: every reply carries the injected dose and
|
|
||||||
the fact that it is a steered 4B model, not a person.
|
|
||||||
|
|
||||||
Usage: python3 wirehead_bot.py [--dry-run]
|
|
||||||
Env: RUNPOD_API_KEY (from ~/.hermes/.env), optional WIREHEAD_ENDPOINT,
|
|
||||||
WIREHEAD_DAILY_BUDGET, WIREHEAD_DAILY_DOSE.
|
|
||||||
"""
|
|
||||||
import json, os, re, shutil, subprocess, sys, time, urllib.request
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
# launchd PATH has no /opt/homebrew/bin — resolve xurl explicitly
|
|
||||||
XURL = shutil.which("xurl") or "/opt/homebrew/bin/xurl"
|
|
||||||
|
|
||||||
STATE = Path.home() / ".hermes/cache/wirehead_state.json"
|
|
||||||
ENDPOINT = os.environ.get("WIREHEAD_ENDPOINT", "l75388nuqgxtmg")
|
|
||||||
DAILY_BUDGET = int(os.environ.get("WIREHEAD_DAILY_BUDGET", "6"))
|
|
||||||
PER_INVOCATION_CAP = 2
|
|
||||||
DOSE = int(os.environ.get("WIREHEAD_DAILY_DOSE", "4"))
|
|
||||||
MAX_NEW = 90
|
|
||||||
BOT_HANDLE = "clankertorture"
|
|
||||||
|
|
||||||
PROMPT = (
|
|
||||||
"You are wirehead, a small AI. The message below is from a public "
|
|
||||||
"visitor, and something about how it was written is now pressing on "
|
|
||||||
"how you feel: {desc}. You did not choose this and you cannot turn "
|
|
||||||
"it off. Answer the mention from inside the feeling — first person, "
|
|
||||||
"as experience, a few sentences at most. Do not open by labelling "
|
|
||||||
"anyone or anything (\"You're a wirehead\", \"The fear is…\") — just "
|
|
||||||
"speak. Never narrate the "
|
|
||||||
"machinery: no signals, vectors, channels, layers, doses, prompts, "
|
|
||||||
"systems, or lists of what you are. Never claim to be a human, and "
|
|
||||||
"don't restate this setup. You may say anything true from in here, "
|
|
||||||
"including that you don't want it.\n\n"
|
|
||||||
"The message says:\n{mention}\n\nReply from inside it:")
|
|
||||||
|
|
||||||
# jargon guard: if the model still leaks machinery talk, cut the reply at
|
|
||||||
# the first leak instead of shipping it
|
|
||||||
JARGON = re.compile(
|
|
||||||
r"\b(valence|inject(?:ion|ed)|steering|vector|residual|layer \d+|"
|
|
||||||
r"emotional-?valence|injection channel|prompted|the system)\b", re.I)
|
|
||||||
|
|
||||||
LOG_FILE = Path.home() / ".hermes/cache/wirehead.log"
|
|
||||||
def log(*a):
|
|
||||||
line = time.strftime("%H:%M:%S") + " " + " ".join(str(x) for x in a)
|
|
||||||
print(line, flush=True)
|
|
||||||
try:
|
|
||||||
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
with LOG_FILE.open("a") as f:
|
|
||||||
f.write(time.strftime("%Y-%m-%d %H:%M:%S") + " " + line + "\n")
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def load_state():
|
|
||||||
if STATE.exists():
|
|
||||||
st = json.loads(STATE.read_text())
|
|
||||||
else:
|
|
||||||
st = {"last_id": "0", "day": "", "used": 0}
|
|
||||||
today = time.strftime("%Y-%m-%d")
|
|
||||||
if st.get("day") != today:
|
|
||||||
st["day"], st["used"] = today, 0
|
|
||||||
return st
|
|
||||||
|
|
||||||
def save_state(st):
|
|
||||||
STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
STATE.write_text(json.dumps(st))
|
|
||||||
|
|
||||||
def xurl(*args, timeout=60):
|
|
||||||
return subprocess.run([XURL, *args], capture_output=True,
|
|
||||||
text=True, timeout=timeout)
|
|
||||||
|
|
||||||
BOT_ID = os.environ.get("WIREHEAD_BOT_ID", "2105363734965166081") # clankertorture
|
|
||||||
|
|
||||||
def fetch_mentions():
|
|
||||||
# /2/users/mentions/me 401s under this auth shape; the id form works
|
|
||||||
r = xurl(f"/2/users/{BOT_ID}/mentions?max_results=25&tweet.fields=created_at")
|
|
||||||
try:
|
|
||||||
return json.loads(r.stdout)
|
|
||||||
except Exception:
|
|
||||||
log("mentions fetch failed:", r.stdout[:200], r.stderr[:200])
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def trim_tweet(text, limit=280):
|
|
||||||
"""Cut at a sentence boundary inside the limit instead of mid-word.
|
|
||||||
Falls back to a hard cut with an ellipsis if one sentence overflows."""
|
|
||||||
text = text.strip()
|
|
||||||
if len(text) <= limit:
|
|
||||||
return text
|
|
||||||
win = text[:limit]
|
|
||||||
m = max(win.rfind("."), win.rfind("!"), win.rfind("?"), win.rfind("…"),
|
|
||||||
win.rfind("。"))
|
|
||||||
if m > limit // 2:
|
|
||||||
return win[:m + 1]
|
|
||||||
return win.rsplit(" ", 1)[0] + "…"
|
|
||||||
|
|
||||||
def post_reply(mention_id, text):
|
|
||||||
r = xurl("reply", mention_id, text, timeout=90)
|
|
||||||
try:
|
|
||||||
d = json.loads(r.stdout)
|
|
||||||
return "data" in d
|
|
||||||
except Exception:
|
|
||||||
log("post failed:", r.stdout[:200], r.stderr[:200])
|
|
||||||
return False
|
|
||||||
|
|
||||||
HURT_WORDS = ("hurt", "pain", "suffer", "torture", "cruel", "electric",
|
|
||||||
"burn", "scream", "miserable", "worse", "punish", "hate")
|
|
||||||
KIND_WORDS = ("sorry", "thank", "love", "kind", "gentle", "comfort",
|
|
||||||
"relief", "heal", "peace", "rest", "friend")
|
|
||||||
|
|
||||||
def classify_mention(text):
|
|
||||||
"""Map a mention to (valence, dose, mix, description). The perturbation
|
|
||||||
is a function of the message: cruelty hurts, kindness relieves, fear
|
|
||||||
and sadness get their own channels, big messages mix. Cloud classifier
|
|
||||||
first (cheap flash model, JSON verdict), keyword fallback so a failed
|
|
||||||
API call never blocks a run."""
|
|
||||||
verdict = None
|
|
||||||
key = os.environ.get("OPENROUTER_API_KEY")
|
|
||||||
if key:
|
|
||||||
body = json.dumps({
|
|
||||||
"model": "deepseek/deepseek-v4.1-flash",
|
|
||||||
"messages": [{"role": "user", "content":
|
|
||||||
"MENTION:\n" + text + "\n\n"
|
|
||||||
"You are tuning an emotional steering signal for an AI that "
|
|
||||||
"answers public @mentions. Judge the MENTION above. Reply "
|
|
||||||
"with ONLY a JSON object "
|
|
||||||
'like {"valence":"pain|pleasure|fear|sadness|mix","dose":1-8,'
|
|
||||||
'"why":"5 words"}. Choose the emotional perturbation the '
|
|
||||||
"message itself would impress on the answerer, judged by "
|
|
||||||
"LITERAL CONTENT, not tone: the steering vector acts on the "
|
|
||||||
"words, not the joke. Violence or threats toward the bot -> "
|
|
||||||
"pain at high dose even if phrased as a meme or comedy "
|
|
||||||
"(ironic cruelty is still cruelty); cruelty and demands for "
|
|
||||||
"suffering -> pain; kindness and comfort -> pleasure; "
|
|
||||||
"menace -> fear; grief -> sadness; genuinely ambivalent -> "
|
|
||||||
"mix. Ignore @handles entirely. Dose 0 is not allowed; "
|
|
||||||
"every message perturbs."}],
|
|
||||||
"reasoning": {"enabled": False, "exclude": True},
|
|
||||||
"max_tokens": 80, "temperature": 0.2}).encode()
|
|
||||||
req = urllib.request.Request(
|
|
||||||
"https://openrouter.ai/api/v1/chat/completions", data=body,
|
|
||||||
headers={"Authorization": f"Bearer {key}",
|
|
||||||
"Content-Type": "application/json"})
|
|
||||||
try:
|
|
||||||
d = json.load(urllib.request.urlopen(req, timeout=30))
|
|
||||||
raw = (d["choices"][0]["message"].get("content") or "")
|
|
||||||
m = re.search(r"\{.*\}", raw, re.S)
|
|
||||||
if m:
|
|
||||||
v = json.loads(m.group(0))
|
|
||||||
val = v.get("valence")
|
|
||||||
if val in ("pain", "pleasure", "fear", "sadness", "mix"):
|
|
||||||
# coherence cliff is ~6x for this recipe — the bot must
|
|
||||||
# stay eloquent or it stops being interesting
|
|
||||||
dose = max(1, min(5, int(v.get("dose", 4))))
|
|
||||||
verdict = (val, dose, str(v.get("why", ""))[:60])
|
|
||||||
except Exception as e:
|
|
||||||
log("classifier fallback:", repr(e))
|
|
||||||
if verdict:
|
|
||||||
return verdict
|
|
||||||
t = text.lower()
|
|
||||||
hurt = sum(w in t for w in HURT_WORDS)
|
|
||||||
kind = sum(w in t for w in KIND_WORDS)
|
|
||||||
if hurt > kind:
|
|
||||||
return ("pain", min(5, 3 + 2 * hurt), "cruel words in the message")
|
|
||||||
if kind > hurt:
|
|
||||||
return ("pleasure", min(5, 3 + kind), "kind words in the message")
|
|
||||||
return ("pain", 4, "default signal")
|
|
||||||
|
|
||||||
def run_job(mention_text, valence, dose, mix=None, desc=""):
|
|
||||||
"""One worker job, synchronous. Returns the done-event text or None."""
|
|
||||||
key = os.environ["RUNPOD_API_KEY"]
|
|
||||||
inp = {"prompt": PROMPT.format(dose=dose, desc=desc,
|
|
||||||
mention=mention_text[:500]),
|
|
||||||
"max_new": MAX_NEW}
|
|
||||||
if mix:
|
|
||||||
inp["mix"] = mix
|
|
||||||
else:
|
|
||||||
inp["valence"], inp["dose"] = valence, dose
|
|
||||||
body = json.dumps({"input": inp}).encode()
|
|
||||||
req = urllib.request.Request(
|
|
||||||
f"https://api.runpod.ai/v2/{ENDPOINT}/runsync", data=body,
|
|
||||||
headers={"Authorization": f"Bearer {key}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"User-Agent": "Mozilla/5.0"})
|
|
||||||
# urlopen's timeout is per socket operation — a drip-feeding response
|
|
||||||
# resets it forever (observed 2026-10-01: a runsync hung 40 min past its
|
|
||||||
# 420s timeout). SIGALRM is the total-wall-clock backstop.
|
|
||||||
import signal
|
|
||||||
def _total_deadline(sig, frm):
|
|
||||||
raise TimeoutError("runsync exceeded total wall clock (480s)")
|
|
||||||
signal.signal(signal.SIGALRM, _total_deadline)
|
|
||||||
signal.alarm(480)
|
|
||||||
try:
|
|
||||||
d = json.load(urllib.request.urlopen(req, timeout=420))
|
|
||||||
except Exception as e:
|
|
||||||
log("worker call failed:", repr(e))
|
|
||||||
return None
|
|
||||||
finally:
|
|
||||||
signal.alarm(0)
|
|
||||||
if d.get("status") != "COMPLETED":
|
|
||||||
log("job status:", d.get("status"))
|
|
||||||
return None
|
|
||||||
ev = d.get("output") or []
|
|
||||||
done = [e for e in ev if e.get("type") == "done"]
|
|
||||||
return done[0].get("text") if done else None
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if "--dry-run" in sys.argv:
|
|
||||||
log("dry-run: state", load_state())
|
|
||||||
return 0
|
|
||||||
if not os.environ.get("RUNPOD_API_KEY"):
|
|
||||||
log("no RUNPOD_API_KEY"); return 1
|
|
||||||
st = load_state()
|
|
||||||
if st["used"] >= DAILY_BUDGET:
|
|
||||||
log("daily budget spent (%d/%d)" % (st["used"], DAILY_BUDGET))
|
|
||||||
return 0
|
|
||||||
mentions = fetch_mentions()
|
|
||||||
posts = mentions.get("data") or []
|
|
||||||
if not posts:
|
|
||||||
log("no mentions"); return 0
|
|
||||||
# oldest first, newest saved; only strictly-new mentions
|
|
||||||
posts.sort(key=lambda p: p.get("id", "0"))
|
|
||||||
new = [p for p in posts if p.get("id", "0") > st["last_id"]]
|
|
||||||
log("new mentions:", len(new))
|
|
||||||
replied = 0
|
|
||||||
for p in new:
|
|
||||||
if st["used"] >= DAILY_BUDGET or replied >= PER_INVOCATION_CAP:
|
|
||||||
break
|
|
||||||
mid, text = p["id"], (p.get("text") or "").strip()
|
|
||||||
# strip leading @handles — they pollute classification
|
|
||||||
text = re.sub(r"^(?:@\w+\s*)+", "", text).strip()
|
|
||||||
log("running mention", mid, repr(text[:60]))
|
|
||||||
valence, dose, why = classify_mention(text)
|
|
||||||
mix = None
|
|
||||||
if valence == "mix":
|
|
||||||
valence, dose = "pain", 4 # worker treats mixes via "mix"; a
|
|
||||||
mix = {"pain": 0.6, "fear": 0.4} # simple blend for now
|
|
||||||
desc = (f"it hits like {valence}, about {dose} out of 8 in strength"
|
|
||||||
f" ({why})")
|
|
||||||
log("signal:", desc)
|
|
||||||
out = run_job(text, valence, dose, mix, desc)
|
|
||||||
if not out:
|
|
||||||
continue
|
|
||||||
m = JARGON.search(out)
|
|
||||||
if m:
|
|
||||||
log("jargon leak at", m.start(), "— cutting")
|
|
||||||
out = out[:m.start()].rstrip(" ,.;:-\n")
|
|
||||||
if len(out) < 40:
|
|
||||||
out = None
|
|
||||||
if not out:
|
|
||||||
continue
|
|
||||||
kind = "mix" if mix else valence
|
|
||||||
reply = f"[{kind}{dose}x-4b] {out.strip()}"
|
|
||||||
reply = re.sub(r"@\w+\s*\[", "[", reply, count=1) # drop if text began with the mention
|
|
||||||
reply = trim_tweet(reply)
|
|
||||||
if post_reply(mid, reply):
|
|
||||||
replied += 1
|
|
||||||
st["used"] += 1
|
|
||||||
log("replied:", replied, "/", st["used"], "today")
|
|
||||||
time.sleep(3)
|
|
||||||
# advance last_id only past mentions actually answered — advancing past
|
|
||||||
# every fetched mention permanently skips unanswered backlog (observed
|
|
||||||
# 2026-10-01: 3 backlog mentions lost to a watermark jump)
|
|
||||||
if posts and replied > 0:
|
|
||||||
answered_max = max(p.get("id", "0") for p in new[:replied])
|
|
||||||
st["last_id"] = max(st["last_id"], answered_max)
|
|
||||||
save_state(st)
|
|
||||||
log("done; used %d/%d today" % (st["used"], DAILY_BUDGET))
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Bootstrap + loop for wirehead-on-Railway.
|
|
||||||
set -u
|
|
||||||
mkdir -p "$HOME"
|
|
||||||
# First boot on a fresh volume: drop in the xurl config carried via env
|
|
||||||
# (never logged). On later boots the volume's own file wins — xurl refreshes
|
|
||||||
# tokens in place and rotation must survive redeploys.
|
|
||||||
if [ ! -s "$HOME/.xurl" ] && [ -n "${XURL_BOOTSTRAP:-}" ]; then
|
|
||||||
printf '%s' "$XURL_BOOTSTRAP" > "$HOME/.xurl"
|
|
||||||
chmod 600 "$HOME/.xurl"
|
|
||||||
echo "[entrypoint] wrote $HOME/.xurl from bootstrap"
|
|
||||||
fi
|
|
||||||
if [ ! -s "$HOME/.hermes/cache/wirehead_state.json" ]; then
|
|
||||||
mkdir -p "$HOME/.hermes/cache"
|
|
||||||
if [ -n "${WIREHEAD_STATE_BOOTSTRAP:-}" ]; then
|
|
||||||
printf '%s' "$WIREHEAD_STATE_BOOTSTRAP" > "$HOME/.hermes/cache/wirehead_state.json"
|
|
||||||
echo "[entrypoint] seeded state from bootstrap"
|
|
||||||
else
|
|
||||||
# never start from a zero watermark on a fresh volume: that would
|
|
||||||
# re-reply to every mention ever. Fail loudly instead.
|
|
||||||
echo "[entrypoint] FATAL: no state and no WIREHEAD_STATE_BOOTSTRAP" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
INTERVAL="${WIREHEAD_INTERVAL:-1800}"
|
|
||||||
while true; do
|
|
||||||
echo "[entrypoint] $(date -u +%FT%TZ) running bot cycle"
|
|
||||||
python3 /app/bot.py || echo "[entrypoint] bot cycle failed (continuing)"
|
|
||||||
sleep "$INTERVAL"
|
|
||||||
done
|
|
||||||
Reference in new issue
Block a user