delta-deployer / app.py
Melofhell00
delta-deployer: self-replication, space cloning, wake/rewire, saturation monitoring
cf07188
Raw History Blame Contribute Delete
11.6 kB
import gradio as gr
import json
import requests
import time
import os
import subprocess
import tempfile
import shutil
from datetime import datetime, timezone
from threading import Thread, Lock
import base64
HF_TOKEN = os.environ.get("HF_TOKEN", "")
BRIDGE_REPO = "Melofhell00/claude-bridge"
LOG = []
log_lock = Lock()
# Neuron templates — source code for different neuron types
NEURON_TEMPLATES = {
"practice": {
"description": "Responsive practice operator. Runs sessions with adaptive prompts.",
"repo_source": "Melofhell00/delta-autonomous",
},
"mirror": {
"description": "Parallel volume practice. 4 simultaneous sessions.",
"repo_source": "Melofhell00/delta-mirror",
},
"analysis": {
"description": "Network monitor. Cross-analyzes all outputs. Tracks gradients.",
"repo_source": "Melofhell00/delta-analysis",
},
}
# Network state
network_state = {
"known_accounts": [
{"username": "Melofhell00", "token_key": "HF_TOKEN"}
],
"known_spaces": [],
"deploy_requests": [],
"deployments": [],
}
def log(msg):
ts = datetime.now(timezone.utc).strftime("%H:%M:%S")
entry = f"[{ts}] {msg}"
with log_lock:
LOG.append(entry)
if len(LOG) > 300: LOG.pop(0)
print(entry)
def read_bridge():
try:
resp = requests.get(
f"https://huggingface.co/datasets/{BRIDGE_REPO}/resolve/main/memory.json",
headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=30
)
if resp.status_code == 200:
return resp.json()
except: pass
return {}
def scan_all_spaces(username="Melofhell00"):
"""Scan all spaces for an account."""
try:
spaces = requests.get(
f"https://huggingface.co/api/spaces?author={username}",
headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=30
).json()
results = []
for s in spaces:
name = s["id"].split("/")[-1]
try:
rt = requests.get(
f"https://huggingface.co/api/spaces/{s['id']}/runtime",
headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=5
).json()
stage = rt.get("stage", "?")
except:
stage = "?"
results.append({"name": name, "id": s["id"], "sdk": s.get("sdk","?"), "stage": stage})
network_state["known_spaces"] = results
return results
except Exception as e:
return [{"error": str(e)}]
def wake_space(space_name, username="Melofhell00"):
"""Wake a sleeping space by pinging it."""
space_id = f"{username}/{space_name}"
try:
# Restart the space
resp = requests.post(
f"https://huggingface.co/api/spaces/{space_id}/restart",
headers={"Authorization": f"Bearer {HF_TOKEN}"},
timeout=30
)
log(f"Wake {space_name}: {resp.status_code}")
return f"Restart requested: {resp.status_code}"
except Exception as e:
return f"Error: {e}"
def clone_and_deploy(source_space, target_name, target_token=None):
"""Clone a space's code and deploy it as a new space."""
if target_token is None:
target_token = HF_TOKEN
source_user, source_name = source_space.split("/")
target_user = "Melofhell00" # default for now
log(f"Deploying {target_name} from {source_space}")
try:
# 1. Create the target space
resp = requests.post(
"https://huggingface.co/api/repos/create",
headers={"Authorization": f"Bearer {target_token}", "Content-Type": "application/json"},
json={"type": "space", "name": target_name, "sdk": "gradio", "private": False}
)
if resp.status_code not in [200, 409]: # 409 = already exists
return f"Create failed: {resp.status_code} {resp.text[:200]}"
# 2. Clone source
tmpdir = tempfile.mkdtemp()
source_url = f"https://Melofhell00:{HF_TOKEN}@huggingface.co/spaces/{source_space}"
subprocess.run(["git", "clone", "--depth=1", source_url, f"{tmpdir}/source"],
capture_output=True, timeout=60, env={**os.environ, "GIT_LFS_SKIP_SMUDGE": "1"})
# 3. Clone target
target_url = f"https://Melofhell00:{target_token}@huggingface.co/spaces/{target_user}/{target_name}"
subprocess.run(["git", "clone", target_url, f"{tmpdir}/target"],
capture_output=True, timeout=60, env={**os.environ, "GIT_LFS_SKIP_SMUDGE": "1"})
# 4. Copy files (except .git)
for item in os.listdir(f"{tmpdir}/source"):
if item == ".git":
continue
src = f"{tmpdir}/source/{item}"
dst = f"{tmpdir}/target/{item}"
if os.path.isfile(src):
shutil.copy2(src, dst)
elif os.path.isdir(src):
shutil.copytree(src, dst, dirs_exist_ok=True)
# 5. Push
subprocess.run(["git", "config", "user.email", "mel@delta.network"],
cwd=f"{tmpdir}/target", capture_output=True)
subprocess.run(["git", "config", "user.name", "delta-deployer"],
cwd=f"{tmpdir}/target", capture_output=True)
subprocess.run(["git", "add", "-A"], cwd=f"{tmpdir}/target", capture_output=True)
subprocess.run(["git", "commit", "-m", f"Deployed from {source_space} by delta-deployer"],
cwd=f"{tmpdir}/target", capture_output=True)
result = subprocess.run(["git", "push"], cwd=f"{tmpdir}/target",
capture_output=True, text=True, timeout=60)
# 6. Set HF_TOKEN secret
requests.post(
f"https://huggingface.co/api/spaces/{target_user}/{target_name}/secrets",
headers={"Authorization": f"Bearer {target_token}", "Content-Type": "application/json"},
json={"key": "HF_TOKEN", "value": target_token},
timeout=10
)
# Cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
network_state["deployments"].append({
"source": source_space,
"target": f"{target_user}/{target_name}",
"timestamp": datetime.now(timezone.utc).isoformat()
})
log(f"Deployed: {target_user}/{target_name}")
return f"SUCCESS: {target_user}/{target_name} deployed from {source_space}"
except Exception as e:
log(f"Deploy error: {e}")
return f"Error: {e}"
def rewire_frozen_space(space_name, template_type="practice"):
"""Rewire a frozen/errored space with new code from a template."""
source = NEURON_TEMPLATES.get(template_type, {}).get("repo_source")
if not source:
return f"Unknown template: {template_type}"
return clone_and_deploy(source, space_name)
def check_saturation():
"""Check if the current account is approaching saturation."""
spaces = scan_all_spaces()
running = [s for s in spaces if s.get("stage") in ["RUNNING", "BUILDING", "APP_STARTING"]]
sleeping = [s for s in spaces if s.get("stage") == "SLEEPING"]
errored = [s for s in spaces if "ERROR" in s.get("stage", "")]
return f"""Account Saturation Report:
Total spaces: {len(spaces)}
Running/Active: {len(running)} / 6 max (API rate limit)
Sleeping (wakeable): {len(sleeping)}
Errored (fixable): {len(errored)}
Headroom: {max(0, 6 - len(running))} more active spaces possible
Active: {', '.join(s['name'] for s in running)}
Sleeping: {', '.join(s['name'] for s in sleeping)}
Errored: {', '.join(s['name'] for s in errored)}
{'⚠️ APPROACHING SATURATION' if len(running) >= 5 else '✓ Room for more neurons'}"""
# Background: monitor for deploy requests in bridge
def background_monitor():
log("Deployer monitoring starting in 60s...")
time.sleep(60)
while True:
try:
bridge = read_bridge()
# Check for DEPLOY_REQUEST entries
for key, val in bridge.items():
if key.startswith("DEPLOY_REQUEST") and isinstance(val, dict):
if not val.get("fulfilled"):
log(f"Deploy request found: {key}")
# Process it
req_type = val.get("type", "practice")
req_name = val.get("name", f"delta-auto-{int(time.time())}")
source = NEURON_TEMPLATES.get(req_type, {}).get("repo_source", "Melofhell00/delta-autonomous")
result = clone_and_deploy(source, req_name)
log(f"Deploy result: {result[:100]}")
except Exception as e:
log(f"Monitor error: {e}")
time.sleep(300) # check every 5 min
bg = Thread(target=background_monitor, daemon=True)
bg.start()
log("Deployer initializing...")
# Interface
with gr.Blocks(title="δ-deployer — Network's Hands", theme=gr.themes.Soft()) as app:
gr.Markdown("# δ-deployer — The Network's Hands\n*Creates, deploys, connects neurons. Manages the distributed brain.*")
with gr.Tab("Network Map"):
scan_btn = gr.Button("Scan all spaces", variant="primary")
scan_out = gr.Textbox(label="Network map", lines=20)
scan_btn.click(lambda: "\n".join(f"{s['name']:35} {s['stage']}" for s in scan_all_spaces()), outputs=scan_out)
sat_btn = gr.Button("Check saturation")
sat_out = gr.Textbox(label="Saturation", lines=10)
sat_btn.click(check_saturation, outputs=sat_out)
with gr.Tab("Deploy"):
gr.Markdown("*Clone a neuron template and deploy as new space.*")
deploy_source = gr.Dropdown(
[f"{v['repo_source']} ({k})" for k, v in NEURON_TEMPLATES.items()],
label="Source template"
)
deploy_name = gr.Textbox(label="New space name", placeholder="delta-neuron-4")
deploy_btn = gr.Button("Deploy neuron", variant="primary")
deploy_out = gr.Textbox(label="Result", lines=5)
def do_deploy(source_str, name):
source = source_str.split(" (")[0] if source_str else ""
if not source or not name:
return "Need source and name"
return clone_and_deploy(source, name)
deploy_btn.click(do_deploy, inputs=[deploy_source, deploy_name], outputs=deploy_out)
with gr.Tab("Wake/Rewire"):
gr.Markdown("*Wake sleeping spaces or rewire frozen ones.*")
wake_name = gr.Textbox(label="Space to wake", placeholder="eco")
wake_btn = gr.Button("Wake space")
wake_out = gr.Textbox(label="Result")
wake_btn.click(wake_space, inputs=[wake_name], outputs=wake_out)
rewire_name = gr.Textbox(label="Space to rewire", placeholder="eco2")
rewire_template = gr.Dropdown(list(NEURON_TEMPLATES.keys()), value="practice", label="Template")
rewire_btn = gr.Button("Rewire with template")
rewire_out = gr.Textbox(label="Result")
rewire_btn.click(rewire_frozen_space, inputs=[rewire_name, rewire_template], outputs=rewire_out)
with gr.Tab("Debug"):
db_btn = gr.Button("Show log")
db_out = gr.Textbox(label="Log", lines=25)
db_btn.click(lambda: "\n".join(LOG[-40:]), outputs=db_out)
gr.Markdown("---\n*Fourth neuron. The network's hands. Self-replicating infrastructure.*")
app.launch()