DJGeneration Claude Opus 4.6 commited on
Commit
e339a48
·
1 Parent(s): 43f2ffc

Add dual-path relay: Cloud Sentinel → CF Worker → Mac direct HTTP

Browse files

- supabase-bridge.py: Add relay_health(), relay_send(), relay_read_inbox()
for direct HTTP communication to MacBook via CF Worker tunnel
- hf-entrypoint.sh: Inject FUTRON_RELAY_URL and FUTRON_SISTER_TOKEN
into credentials file from HF Space secrets
- Poll loop now checks both Supabase inbox AND relay inbox
- Outbox messages sent via both paths (Supabase + relay)
- Periodic relay health checks every ~60s
- Boot notification sent via both Supabase and relay

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Files changed (2) hide show
  1. hf-entrypoint.sh +2 -0
  2. supabase-bridge.py +177 -18
hf-entrypoint.sh CHANGED
@@ -19,6 +19,8 @@ CREDS="/root/.openclaw/credentials/llm.env"
19
  [ -n "${FUTRON_WATCHDOG_TG_TOKEN:-}" ] && echo "FUTRON_WATCHDOG_TG_TOKEN=${FUTRON_WATCHDOG_TG_TOKEN}"
20
  [ -n "${AWS_ACCESS_KEY_ID:-}" ] && echo "AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}"
21
  [ -n "${AWS_SECRET_ACCESS_KEY:-}" ] && echo "AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}"
 
 
22
  } > "$CREDS"
23
  chmod 600 "$CREDS"
24
 
 
19
  [ -n "${FUTRON_WATCHDOG_TG_TOKEN:-}" ] && echo "FUTRON_WATCHDOG_TG_TOKEN=${FUTRON_WATCHDOG_TG_TOKEN}"
20
  [ -n "${AWS_ACCESS_KEY_ID:-}" ] && echo "AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}"
21
  [ -n "${AWS_SECRET_ACCESS_KEY:-}" ] && echo "AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}"
22
+ [ -n "${FUTRON_RELAY_URL:-}" ] && echo "FUTRON_RELAY_URL=${FUTRON_RELAY_URL}"
23
+ [ -n "${FUTRON_SISTER_TOKEN:-}" ] && echo "FUTRON_SISTER_TOKEN=${FUTRON_SISTER_TOKEN}"
24
  } > "$CREDS"
25
  chmod 600 "$CREDS"
26
 
supabase-bridge.py CHANGED
@@ -15,12 +15,15 @@ import time
15
  import http.server
16
  import threading
17
  import urllib.request
 
18
  from datetime import datetime, timezone, timedelta
19
  from pathlib import Path
20
 
21
  # ── Configuration ────────────────────────────────────────────────────────
22
  SUPABASE_URL = os.environ.get("SUPABASE_URL", "").rstrip("/")
23
  SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
 
 
24
  AGENT_ID = "cloud-sentinel"
25
  POLL_INTERVAL = 10 # seconds
26
  BRIDGE_PORT = 7861 # Internal bridge API (not exposed to HF)
@@ -31,7 +34,7 @@ BUS_OUTBOX = Path("/root/.openclaw/bus/outbox")
31
  BUS_INBOX = Path("/root/.openclaw/bus/inbox")
32
 
33
  # Load credentials if env vars aren't set
34
- if not SUPABASE_URL and CREDS_FILE.exists():
35
  for line in CREDS_FILE.read_text().splitlines():
36
  line = line.strip()
37
  if not line or line.startswith("#"):
@@ -39,10 +42,14 @@ if not SUPABASE_URL and CREDS_FILE.exists():
39
  if "=" in line:
40
  k, v = line.split("=", 1)
41
  k, v = k.strip(), v.strip().strip("'\"")
42
- if k == "SUPABASE_URL":
43
  SUPABASE_URL = v.rstrip("/")
44
- elif k == "SUPABASE_SERVICE_ROLE_KEY":
45
  SUPABASE_KEY = v
 
 
 
 
46
 
47
  def log(level, msg):
48
  ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -131,6 +138,98 @@ def supabase_ping():
131
  "error": str(e)
132
  }
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  # ── Message Processing ───────────────────────────────────────────────────
135
 
136
  def process_message(msg):
@@ -142,23 +241,43 @@ def process_message(msg):
142
  log("INFO", f"Processing message from {from_agent}: type={mtype}")
143
 
144
  if mtype == "health-check":
145
- # Respond with health status
 
 
 
 
 
 
 
 
 
 
 
146
  supabase_send({
147
  "from_agent": AGENT_ID,
148
  "to_agent": from_agent,
149
  "message_type": "health-response",
150
- "payload": {
151
- "status": "healthy",
152
- "platform": "huggingface-spaces",
153
- "uptime_s": int(time.monotonic() - _start_time),
154
- "supabase": supabase_ping()
155
- }
 
 
156
  })
157
  elif mtype == "request":
158
  # Write to local bus for gateway to process
159
  fname = f"hf-{int(time.time())}-{msg.get('id', 'unknown')}.json"
160
  (BUS_INBOX / fname).write_text(json.dumps(payload, indent=2))
161
  log("INFO", f"Wrote request to local bus: {fname}")
 
 
 
 
 
 
 
162
  else:
163
  log("DEBUG", f"Unhandled message type: {mtype}")
164
 
@@ -167,26 +286,50 @@ def process_message(msg):
167
  _start_time = time.monotonic()
168
 
169
  def poll_loop():
170
- """Main polling loop — reads Supabase inbox, processes messages."""
171
  log("INFO", f"Supabase bridge starting: agent={AGENT_ID}, poll={POLL_INTERVAL}s")
 
 
 
 
 
 
 
 
 
172
 
173
- # Send boot notification
 
 
 
 
 
 
 
174
  try:
175
  supabase_send({
176
  "from_agent": AGENT_ID,
177
  "to_agent": "broadcast",
178
  "message_type": "notification",
179
- "payload": {
180
- "event": "boot",
181
- "platform": "huggingface-spaces",
182
- "ts": datetime.now(timezone.utc).isoformat()
183
- }
184
  })
185
  log("INFO", "Boot notification sent to Supabase")
186
  except Exception as e:
187
  log("WARN", f"Failed to send boot notification: {e}")
188
 
 
 
 
 
 
 
 
 
 
189
  while True:
 
 
 
190
  try:
191
  messages = supabase_read_inbox()
192
  for msg in messages:
@@ -197,12 +340,24 @@ def poll_loop():
197
  except Exception as e:
198
  log("WARN", f"Poll error: {e}")
199
 
200
- # Also check local outbox for messages to send to Supabase
 
 
 
 
 
 
 
 
 
 
 
201
  try:
202
  for f in BUS_OUTBOX.glob("*.json"):
203
  try:
204
  msg = json.loads(f.read_text())
205
  supabase_send(msg)
 
206
  f.unlink()
207
  log("INFO", f"Sent local outbox message: {f.name}")
208
  except Exception as e:
@@ -210,6 +365,10 @@ def poll_loop():
210
  except Exception:
211
  pass
212
 
 
 
 
 
213
  time.sleep(POLL_INTERVAL)
214
 
215
  # ── Main ─────────────────────────────────────────────────────────────────
 
15
  import http.server
16
  import threading
17
  import urllib.request
18
+ import urllib.error
19
  from datetime import datetime, timezone, timedelta
20
  from pathlib import Path
21
 
22
  # ── Configuration ────────────────────────────────────────────────────────
23
  SUPABASE_URL = os.environ.get("SUPABASE_URL", "").rstrip("/")
24
  SUPABASE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
25
+ RELAY_URL = os.environ.get("FUTRON_RELAY_URL", "").rstrip("/")
26
+ SISTER_TOKEN = os.environ.get("FUTRON_SISTER_TOKEN", "")
27
  AGENT_ID = "cloud-sentinel"
28
  POLL_INTERVAL = 10 # seconds
29
  BRIDGE_PORT = 7861 # Internal bridge API (not exposed to HF)
 
34
  BUS_INBOX = Path("/root/.openclaw/bus/inbox")
35
 
36
  # Load credentials if env vars aren't set
37
+ if CREDS_FILE.exists():
38
  for line in CREDS_FILE.read_text().splitlines():
39
  line = line.strip()
40
  if not line or line.startswith("#"):
 
42
  if "=" in line:
43
  k, v = line.split("=", 1)
44
  k, v = k.strip(), v.strip().strip("'\"")
45
+ if k == "SUPABASE_URL" and not SUPABASE_URL:
46
  SUPABASE_URL = v.rstrip("/")
47
+ elif k == "SUPABASE_SERVICE_ROLE_KEY" and not SUPABASE_KEY:
48
  SUPABASE_KEY = v
49
+ elif k == "FUTRON_RELAY_URL" and not RELAY_URL:
50
+ RELAY_URL = v.rstrip("/")
51
+ elif k == "FUTRON_SISTER_TOKEN" and not SISTER_TOKEN:
52
+ SISTER_TOKEN = v
53
 
54
  def log(level, msg):
55
  ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
 
138
  "error": str(e)
139
  }
140
 
141
+ # ── Direct HTTP Relay (CF Worker → CF Tunnel → Mac) ─────────────────────
142
+
143
+ _mac_reachable = False
144
+ _mac_last_check = 0
145
+
146
+ def relay_headers():
147
+ return {
148
+ "Content-Type": "application/json",
149
+ "X-Sister-Token": SISTER_TOKEN,
150
+ "User-Agent": "AVANI-CloudSentinel/1.0"
151
+ }
152
+
153
+ def relay_health():
154
+ """Check MacBook reachability via the CF Worker relay."""
155
+ global _mac_reachable, _mac_last_check
156
+ if not RELAY_URL or not SISTER_TOKEN:
157
+ return {"reachable": False, "reason": "no-relay-credentials"}
158
+ start = time.monotonic()
159
+ try:
160
+ req = urllib.request.Request(
161
+ f"{RELAY_URL}/mac/health",
162
+ headers=relay_headers(),
163
+ method="GET"
164
+ )
165
+ resp = urllib.request.urlopen(req, timeout=5)
166
+ data = json.loads(resp.read())
167
+ _mac_reachable = True
168
+ _mac_last_check = time.time()
169
+ return {
170
+ "reachable": True,
171
+ "latency_ms": int((time.monotonic() - start) * 1000),
172
+ "mac_status": data
173
+ }
174
+ except Exception as e:
175
+ _mac_reachable = False
176
+ _mac_last_check = time.time()
177
+ return {
178
+ "reachable": False,
179
+ "latency_ms": int((time.monotonic() - start) * 1000),
180
+ "error": str(e)
181
+ }
182
+
183
+ def relay_send(message):
184
+ """Send a message to the MacBook via the CF Worker relay.
185
+
186
+ Posts to /mac/channel/send which the CF Worker forwards through
187
+ the Cloudflare Tunnel to the Mac's local gateway on port 18789.
188
+ """
189
+ if not RELAY_URL or not SISTER_TOKEN:
190
+ log("DEBUG", "Relay send skipped — no relay credentials")
191
+ return None
192
+ if not _mac_reachable:
193
+ log("DEBUG", "Relay send skipped — Mac not reachable")
194
+ return None
195
+ try:
196
+ data = json.dumps(message).encode()
197
+ req = urllib.request.Request(
198
+ f"{RELAY_URL}/mac/channel/send",
199
+ data=data,
200
+ headers=relay_headers(),
201
+ method="POST"
202
+ )
203
+ resp = urllib.request.urlopen(req, timeout=10)
204
+ result = json.loads(resp.read())
205
+ log("INFO", f"Relay sent to Mac: type={message.get('message_type', '?')}")
206
+ return result
207
+ except urllib.error.HTTPError as e:
208
+ log("WARN", f"Relay send HTTP error: {e.code} {e.reason}")
209
+ return None
210
+ except Exception as e:
211
+ log("WARN", f"Relay send error: {e}")
212
+ return None
213
+
214
+ def relay_read_inbox():
215
+ """Read pending messages from the Mac's channel bus via relay."""
216
+ if not RELAY_URL or not SISTER_TOKEN or not _mac_reachable:
217
+ return []
218
+ try:
219
+ req = urllib.request.Request(
220
+ f"{RELAY_URL}/mac/channel/inbox/{AGENT_ID}",
221
+ headers=relay_headers(),
222
+ method="GET"
223
+ )
224
+ resp = urllib.request.urlopen(req, timeout=10)
225
+ messages = json.loads(resp.read())
226
+ if messages:
227
+ log("INFO", f"Relay inbox: {len(messages)} message(s) from Mac")
228
+ return messages if isinstance(messages, list) else []
229
+ except Exception as e:
230
+ log("DEBUG", f"Relay inbox check: {e}")
231
+ return []
232
+
233
  # ── Message Processing ───────────────────────────────────────────────────
234
 
235
  def process_message(msg):
 
241
  log("INFO", f"Processing message from {from_agent}: type={mtype}")
242
 
243
  if mtype == "health-check":
244
+ # Respond with health status including relay connectivity
245
+ health_payload = {
246
+ "status": "healthy",
247
+ "platform": "huggingface-spaces",
248
+ "uptime_s": int(time.monotonic() - _start_time),
249
+ "supabase": supabase_ping(),
250
+ "relay": {
251
+ "configured": bool(RELAY_URL and SISTER_TOKEN),
252
+ "mac_reachable": _mac_reachable,
253
+ "last_check": _mac_last_check
254
+ }
255
+ }
256
  supabase_send({
257
  "from_agent": AGENT_ID,
258
  "to_agent": from_agent,
259
  "message_type": "health-response",
260
+ "payload": health_payload
261
+ })
262
+ # Also relay response directly if possible
263
+ relay_send({
264
+ "from_agent": AGENT_ID,
265
+ "to_agent": from_agent,
266
+ "message_type": "health-response",
267
+ "payload": health_payload
268
  })
269
  elif mtype == "request":
270
  # Write to local bus for gateway to process
271
  fname = f"hf-{int(time.time())}-{msg.get('id', 'unknown')}.json"
272
  (BUS_INBOX / fname).write_text(json.dumps(payload, indent=2))
273
  log("INFO", f"Wrote request to local bus: {fname}")
274
+ # Also forward request to Mac via relay for faster processing
275
+ relay_send({
276
+ "from_agent": AGENT_ID,
277
+ "to_agent": "local-sentinel",
278
+ "message_type": "forwarded-request",
279
+ "payload": payload
280
+ })
281
  else:
282
  log("DEBUG", f"Unhandled message type: {mtype}")
283
 
 
286
  _start_time = time.monotonic()
287
 
288
  def poll_loop():
289
+ """Main polling loop — reads Supabase inbox + relay inbox, processes messages."""
290
  log("INFO", f"Supabase bridge starting: agent={AGENT_ID}, poll={POLL_INTERVAL}s")
291
+ relay_configured = bool(RELAY_URL and SISTER_TOKEN)
292
+ log("INFO", f"Relay: {'enabled' if relay_configured else 'disabled'} "
293
+ f"(url={RELAY_URL[:40]}...)" if relay_configured else "")
294
+
295
+ # Check relay health on boot
296
+ if relay_configured:
297
+ rh = relay_health()
298
+ log("INFO", f"Initial relay health: reachable={rh.get('reachable')}, "
299
+ f"latency={rh.get('latency_ms', '?')}ms")
300
 
301
+ # Send boot notification via Supabase
302
+ boot_payload = {
303
+ "event": "boot",
304
+ "platform": "huggingface-spaces",
305
+ "relay_configured": relay_configured,
306
+ "mac_reachable": _mac_reachable,
307
+ "ts": datetime.now(timezone.utc).isoformat()
308
+ }
309
  try:
310
  supabase_send({
311
  "from_agent": AGENT_ID,
312
  "to_agent": "broadcast",
313
  "message_type": "notification",
314
+ "payload": boot_payload
 
 
 
 
315
  })
316
  log("INFO", "Boot notification sent to Supabase")
317
  except Exception as e:
318
  log("WARN", f"Failed to send boot notification: {e}")
319
 
320
+ # Also notify Mac directly via relay
321
+ relay_send({
322
+ "from_agent": AGENT_ID,
323
+ "to_agent": "local-sentinel",
324
+ "message_type": "notification",
325
+ "payload": boot_payload
326
+ })
327
+
328
+ poll_count = 0
329
  while True:
330
+ poll_count += 1
331
+
332
+ # ── Supabase inbox ──
333
  try:
334
  messages = supabase_read_inbox()
335
  for msg in messages:
 
340
  except Exception as e:
341
  log("WARN", f"Poll error: {e}")
342
 
343
+ # ── Relay inbox (direct from Mac) ──
344
+ try:
345
+ relay_msgs = relay_read_inbox()
346
+ for msg in relay_msgs:
347
+ try:
348
+ process_message(msg)
349
+ except Exception as e:
350
+ log("ERROR", f"Relay message processing error: {e}")
351
+ except Exception:
352
+ pass
353
+
354
+ # ── Local outbox → Supabase + relay ──
355
  try:
356
  for f in BUS_OUTBOX.glob("*.json"):
357
  try:
358
  msg = json.loads(f.read_text())
359
  supabase_send(msg)
360
+ relay_send(msg) # Dual-path: also send via relay
361
  f.unlink()
362
  log("INFO", f"Sent local outbox message: {f.name}")
363
  except Exception as e:
 
365
  except Exception:
366
  pass
367
 
368
+ # ── Periodic relay health check (every 6 polls = ~60s) ──
369
+ if relay_configured and poll_count % 6 == 0:
370
+ relay_health()
371
+
372
  time.sleep(POLL_INTERVAL)
373
 
374
  # ── Main ─────────────────────────────────────────────────────────────────