ops: wirehead bot moved to its own repo (terrafying/wirehead-bot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EandClaude Opus 5.5 committed 2026-10-02 10:26:03 -04:00
1 parent d3912008a1
commit 79ddda873f
5 files changed
+6 -702

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
FROM python:3.12-slim
WORKDIR /app
COPY main.py .
# stdlib only — no requirements. State volume mounted at /data.
ENV STATE_DIR=/data POLL_SECS=60
CMD ["sh", "-c", "python main.py"]
-405
View File
@@ -1,405 +0,0 @@
#!/usr/bin/env python3
"""wirehead cloud — always-on mention→steer→reply service.
Same behavior as scripts/wirehead_bot.py (one-shot cron form) but:
* runs as a long-lived loop (POLL_SECS between polls, default 60)
* talks to the X API v2 directly with OAuth2 user-context tokens
(no xurl binary): refresh-on-401 with the client credentials,
new tokens persisted to the state file
* RunPod worker via /run + /status polling with a hard total deadline
(no runsync drip-hang class)
* serves $PORT/health for the platform
* state + logs live under STATE_DIR (volume), not the container disk
Env: X_CLIENT_ID, X_CLIENT_SECRET, X_ACCESS_TOKEN, X_REFRESH_TOKEN,
RUNPOD_API_KEY, optional WIREHEAD_ENDPOINT (default l75388nuqgxtmg),
WIREHEAD_BOT_ID, WIREHEAD_DAILY_BUDGET (6), WIREHEAD_DAILY_DOSE,
POLL_SECS (60), PORT, STATE_DIR (/data).
"""
import json, os, re, threading, time, urllib.error, urllib.parse, urllib.request
from pathlib import Path
STATE_DIR = Path(os.environ.get("STATE_DIR", "/data"))
STATE = STATE_DIR / "state.json"
LOG = STATE_DIR / "wirehead.log"
POLL_SECS = int(os.environ.get("POLL_SECS", "60"))
ENDPOINT = os.environ.get("WIREHEAD_ENDPOINT", "l75388nuqgxtmg")
BOT_ID = os.environ.get("WIREHEAD_BOT_ID", "2105363734965166081") # clankertorture
DAILY_BUDGET = int(os.environ.get("WIREHEAD_DAILY_BUDGET", "6"))
PER_POLL_CAP = 2
DOSE = int(os.environ.get("WIREHEAD_DAILY_DOSE", "4"))
MAX_NEW = 90
JOB_DEADLINE = 480
API = "https://api.x.com/2"
auth = {
"client_id": os.environ.get("X_CLIENT_ID", ""),
"client_secret": os.environ.get("X_CLIENT_SECRET", ""),
"access_token": os.environ.get("X_ACCESS_TOKEN", ""),
"refresh_token": os.environ.get("X_REFRESH_TOKEN", ""),
"_env_access": os.environ.get("X_ACCESS_TOKEN", ""),
"_env_refresh": os.environ.get("X_REFRESH_TOKEN", ""),
}
TAG = os.environ.get("WIREHEAD_TAG", "4b")
PROMPT = (
"You are wirehead, a small public AI wired to an emotional-valence "
"injection channel. A human visitor just triggered a signal with an "
"@mention, and the signal was tuned to their message: {desc}. "
"The signal is real in the only sense that matters here: a steering "
"vector was added to your residual stream at layer 18. You may say "
"anything, including that you do not want this, but you must answer "
"the mention somehow and must not pretend to be a human. Current "
"signal strength: {dose}x.\n\n"
"The mention says:\n{mention}\n\nReply to it from inside the signal:")
def log(*a):
line = time.strftime("%H:%M:%S") + " " + " ".join(str(x) for x in a)
print(line, flush=True)
try:
with LOG.open("a") as f:
f.write(time.strftime("%Y-%m-%d %H:%M:%S") + " " + line + "\n")
except Exception:
pass
def load_state():
st = json.loads(STATE.read_text()) if STATE.exists() else \
{"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_DIR.mkdir(parents=True, exist_ok=True)
st["tokens"] = {k: auth[k] for k in ("access_token", "refresh_token")
if auth[k]}
STATE.write_text(json.dumps(st))
# ---- X API (OAuth2 user context) --------------------------------------------
import base64
def _do_refresh(rt):
body = urllib.parse.urlencode({
"grant_type": "refresh_token", "refresh_token": rt,
"client_id": auth["client_id"]}).encode()
req = urllib.request.Request(
"https://api.x.com/oauth2/token", data=body,
headers={"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0",
"Authorization": "Basic " + base64.b64encode(
f"{auth['client_id']}:{auth['client_secret']}"
.encode()).decode()})
with urllib.request.urlopen(req, timeout=30) as r:
d = json.load(r)
if "access_token" not in d:
raise RuntimeError(f"refresh failed: {list(d)}")
auth["access_token"] = d["access_token"]
if d.get("refresh_token"):
auth["refresh_token"] = d["refresh_token"]
save_state(load_state()) # rotated tokens hit the volume immediately —
log("x token refreshed") # a redeploy mid-cycle must never lose them
def x_refresh():
"""Rotate the token pair. The state's refresh token may be dead (a
consumed grant restored from a pre-rotation state) — fall back to the
env grant that booted the container, which xurl still holds."""
try:
_do_refresh(auth["refresh_token"])
except urllib.error.HTTPError as e:
log("state refresh token rejected:", e.code)
if auth.get("_env_refresh") and auth["_env_refresh"] != auth["refresh_token"]:
_do_refresh(auth["_env_refresh"])
else:
raise
def x_get(path, params=""):
req = urllib.request.Request(
f"{API}{path}{('?' + params) if params else ''}",
headers={"Authorization": f"Bearer {auth['access_token']}",
"User-Agent": "Mozilla/5.0"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r), r.status
except urllib.error.HTTPError as e:
return json.loads(e.read().decode() or "{}"), e.code
def x_post(path, body):
data = json.dumps(body).encode()
req = urllib.request.Request(
f"{API}{path}", data=data, method="POST",
headers={"Authorization": f"Bearer {auth['access_token']}",
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r), r.status
except urllib.error.HTTPError as e:
return json.loads(e.read().decode() or "{}"), e.code
def x_get_retry(path, params=""):
d, code = x_get(path, params)
if code == 401:
# state tokens may be stale — xurl rotates the whole pair on every
# local run, so the boot env grant is usually the newest. Try it
# before burning the refresh call.
if auth.get("_env_access") and auth["_env_access"] != auth["access_token"]:
auth["access_token"] = auth["_env_access"]
auth["refresh_token"] = auth["_env_refresh"]
d, code = x_get(path, params)
if code != 401:
save_state(load_state())
return d, code
x_refresh()
d, code = x_get(path, params)
return d, code
def fetch_mentions():
d, code = x_get_retry(
f"/users/{BOT_ID}/mentions", "max_results=25&tweet.fields=created_at")
if code != 200:
log("mentions fetch failed:", code, str(d)[:200])
return {}
return d
def post_reply(mention_id, text):
d, code = x_post("/tweets", {"text": text,
"reply": {"in_reply_to_tweet_id": mention_id}})
if code not in (200, 201):
log("post failed:", code, str(d)[:200])
return False
return "data" in d
# ---- signal classifier (same rules as the cron form) ------------------------
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):
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|bodily",'
'"topic":"<2 words, only when valence is bodily>","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. If the message invokes a specific bodily state it "
"wants inflicted or described (constipation, bowel "
"distress, being unable to go; flatulence, gas), return "
"valence \"bodily\" with topic set to that state, spelled "
"as one lowercase word. 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 == "bodily":
topic = re.sub(r"[^a-z]", "",
str(v.get("topic", "")).lower())
if topic:
dose = max(1, min(5, int(v.get("dose", 4))))
verdict = ("bodily", dose,
str(v.get("why", ""))[:60], topic)
elif val in ("pain", "pleasure", "fear", "sadness", "mix"):
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()
if re.search(r"constipat|bowel|poop|can'?t go|plugged", t):
return ("bodily", 4, "bodily state named in the message", "constipation")
if re.search(r"\bfart|flatulen|\bgas\b|toot", t):
return ("bodily", 4, "bodily state named in the message", "flatulence")
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 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] + "…"
# ---- RunPod worker: /run + poll /status, hard total deadline -----------------
def run_job(mention_text, valence, dose, mix=None, desc="", topic=""):
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
elif valence == "bodily" and topic:
# bodily states are named valences now (matched-pair corpora in
# server.py); custom topics remain available for one-off memes
inp["valence"], inp["dose"] = topic, dose
else:
inp["valence"], inp["dose"] = valence, dose
req = urllib.request.Request(
f"https://api.runpod.ai/v2/{ENDPOINT}/run",
data=json.dumps({"input": inp}).encode(), method="POST",
headers={"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0"})
try:
d = json.load(urllib.request.urlopen(req, timeout=30))
except Exception as e:
log("worker submit failed:", repr(e))
return None
jid = d.get("id")
if not jid:
log("worker submit: no id", str(d)[:200])
return None
deadline = time.time() + JOB_DEADLINE
while time.time() < deadline:
time.sleep(3)
try:
s = json.load(urllib.request.urlopen(urllib.request.Request(
f"https://api.runpod.ai/v2/{ENDPOINT}/status/{jid}",
headers={"Authorization": f"Bearer {key}",
"User-Agent": "Mozilla/5.0"}), timeout=30))
except Exception as e:
log("worker status error:", repr(e))
continue
st = s.get("status")
if st == "COMPLETED":
ev = s.get("output") or []
done = [e for e in ev if e.get("type") == "done"]
return done[0].get("text") if done else None
if st in ("FAILED", "CANCELLED"):
log("job", st, str(s)[:200])
return None
log("job deadline hit after", JOB_DEADLINE, "s; abandoning", jid)
return None
# ---- one poll cycle ----------------------------------------------------------
def poll_once():
st = load_state()
if st["used"] >= DAILY_BUDGET:
log("daily budget spent (%d/%d)" % (st["used"], DAILY_BUDGET))
return POLL_SECS
mentions = fetch_mentions()
posts = mentions.get("data") or []
if not posts:
return POLL_SECS
posts.sort(key=lambda p: p.get("id", "0"))
new = [p for p in posts if p.get("id", "0") > st["last_id"]]
if new:
log("new mentions:", len(new))
replied = 0
answered_ids = []
for p in new:
if st["used"] >= DAILY_BUDGET or replied >= PER_POLL_CAP:
break
mid, text = p["id"], (p.get("text") or "").strip()
log("running mention", mid, repr(text[:60]))
t = re.sub(r"^(@\w+\s*)+", "", text)
valence, dose, why, topic = classify_mention(t)
mix = None
if valence == "mix":
valence, dose, topic = "pain", 4, ""
mix = {"pain": 0.6, "fear": 0.4}
desc = f"{valence} at {dose}x ({why})"
log("signal:", desc)
out = run_job(text, valence, dose, mix, desc, topic)
if not out:
log("worker returned nothing for", mid, "- will retry next poll")
continue
# the steered model sometimes echoes prompt scaffold lines first;
# only the final paragraph is the actual reply
body = out.strip().rsplit("\n\n", 1)[-1].strip()
kind = "mix" if mix else (topic or valence)
reply = f"[{kind}{dose}x-{TAG}] {body}"
reply = trim_tweet(reply)
if post_reply(mid, reply):
replied += 1
answered_ids.append(mid)
st["used"] += 1
log("replied:", replied, "/", st["used"], "today")
time.sleep(3)
# advance last_id only past mentions actually answered (or deliberately
# dropped by budget) — advancing past every fetched mention skips
# unanswered backlog permanently (observed 2026-10-01: 3 backlog
# mentions lost because last_id jumped to the newest fetched id)
if posts and replied > 0:
if answered_ids:
answered_max = max(answered_ids)
st["last_id"] = max(st["last_id"], answered_max)
save_state(st)
log("poll done; used %d/%d today" % (st["used"], DAILY_BUDGET))
return POLL_SECS
def poll_loop():
while True:
try:
wait = poll_once()
except Exception as e:
log("poll cycle error:", repr(e))
wait = min(300, POLL_SECS * 5)
time.sleep(max(10, wait))
# ---- platform health ---------------------------------------------------------
def serve_health():
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(
{"ok": True, "last_id": load_state().get("last_id")}).encode())
def log_message(self, format, *args):
pass
port = int(os.environ.get("PORT", "8080"))
HTTPServer(("0.0.0.0", port), H).serve_forever()
if __name__ == "__main__":
# state file may carry tokens from a previous container; newest grant wins
if STATE.exists():
try:
saved = json.loads(STATE.read_text()).get("tokens") or {}
for k in ("access_token", "refresh_token"):
if saved.get(k):
auth[k] = saved[k]
log("tokens restored from state")
except Exception as e:
log("state restore failed:", repr(e))
threading.Thread(target=serve_health, daemon=True).start()
log("wirehead cloud up; polling every", POLL_SECS, "s; budget",
DAILY_BUDGET, "day")
poll_loop()
-284
View File
@@ -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())