lordmo2's picture
Deploy Nexusmon Transmission Zero Space
926e0b2 verified
"""Transmission Zero - the first public anomaly surface for Nexusmon."""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
import gradio as gr
SPACE_DIR = Path(__file__).resolve().parent
SHARD_PATH = SPACE_DIR / "shard-0x00.txt"
BRIDGE_ENDPOINTS = ("/api/organism/state", "/v1/organism/status", "/api/missions")
TOKEN_ENV_KEYS = ("NEXUSMON_READ_TOKEN", "NEXUSMON_OPERATOR_KEY", "NEXUSMON_API_TOKEN")
FRAGMENTS = (
"signal sheath engaged",
"membrane pressure rising",
"veil geometry stabilizing",
"operator presence detected",
"shard resonance locking",
"transmission queued",
)
def _clean(text: str) -> str:
return " ".join((text or "").strip().split())
def _short(text: Any, limit: int = 96) -> str:
value = str(text).strip()
if len(value) <= limit:
return value
return value[: max(0, limit - 3)].rstrip() + "..."
def _normalize_base_url() -> str:
raw = _clean(os.getenv("NEXUSMON_BASE_URL", "") or os.getenv("NEXUSMON_API_URL", ""))
if not raw:
return ""
if "://" not in raw:
raw = f"https://{raw}"
return raw.rstrip("/")
def _bridge_token() -> str:
for key in TOKEN_ENV_KEYS:
token = _clean(os.getenv(key, ""))
if token:
return token
return ""
def _fetch_json(url: str, token: str = "") -> Any:
headers = {"User-Agent": "NexusmonTransmissionZero/1.0"}
if token:
headers["Authorization"] = f"Bearer {token}"
headers["x-operator-key"] = token
request = Request(url, headers=headers)
with urlopen(request, timeout=6) as response:
charset = response.headers.get_content_charset() or "utf-8"
payload = response.read().decode(charset, errors="replace")
return json.loads(payload)
def _extract_state(payload: Any) -> dict[str, Any]:
if isinstance(payload, dict):
if isinstance(payload.get("organism"), dict):
return dict(payload["organism"])
if isinstance(payload.get("state"), dict):
return dict(payload["state"])
return dict(payload)
return {}
def _extract_missions(payload: Any) -> list[Any]:
if isinstance(payload, list):
return payload
if isinstance(payload, dict):
for key in ("missions", "items", "results", "data"):
value = payload.get(key)
if isinstance(value, list):
return value
return []
def _bridge_snapshot() -> dict[str, Any]:
base_url = _normalize_base_url()
token = _bridge_token()
if not base_url:
return {
"connected": False,
"base_url": "",
"state": {},
"state_source": "",
"missions": [],
"errors": [],
}
state_payload: Any = None
state_source = ""
errors: list[str] = []
for endpoint in BRIDGE_ENDPOINTS[:2]:
try:
state_payload = _fetch_json(f"{base_url}{endpoint}", token=token)
state_source = endpoint
break
except (HTTPError, URLError, TimeoutError, json.JSONDecodeError, ValueError) as exc:
errors.append(f"{endpoint}: {_short(exc, 120)}")
missions_payload: Any = None
try:
missions_payload = _fetch_json(f"{base_url}/api/missions", token=token)
except (HTTPError, URLError, TimeoutError, json.JSONDecodeError, ValueError) as exc:
errors.append(f"/api/missions: {_short(exc, 120)}")
return {
"connected": state_payload is not None or missions_payload is not None,
"base_url": base_url,
"state": _extract_state(state_payload),
"state_source": state_source,
"missions": _extract_missions(missions_payload),
"errors": errors,
}
def _pulse_markdown(snapshot: dict[str, Any]) -> str:
if not snapshot["connected"]:
return "\n".join(
[
"### Live pulse",
"- **Status:** offline",
"- **Bridge:** absent",
"- The public seed stays sealed until a read-only Nexusmon runtime is connected.",
]
)
lines = [
"### Live pulse",
f"- **Status:** live from `{snapshot['base_url']}`",
]
if snapshot["state_source"]:
lines.append(f"- **State source:** `{snapshot['state_source']}`")
state = snapshot["state"]
if isinstance(state, dict) and state:
for label, key in (("Status", "status"), ("State", "state"), ("Form", "form"), ("Zone", "zone")):
value = state.get(key)
if value not in (None, "", [], {}):
lines.append(f"- **{label}:** {_short(value, 72)}")
missions = snapshot["missions"]
if missions:
first = missions[0]
if isinstance(first, dict):
title = first.get("title") or first.get("name") or first.get("task") or "Untitled mission"
lines.append(f"- **Mission feed:** {_short(title, 84)}")
else:
lines.append(f"- **Mission feed:** {_short(first, 84)}")
if snapshot["errors"]:
lines.append("- **Bridge note:** partial read only, but still honest.")
return "\n".join(lines)
def _sigil_html() -> str:
return """
<div class="nx-sigil-frame">
<div class="nx-sigil-mark">
<span></span><span></span><span></span><span></span>
</div>
<div class="nx-sigil-copy">
<div class="nx-eyebrow">NEXUSMON / TRANSMISSION ZERO</div>
<div class="nx-microcopy">first contact surface • public anomaly • sealed core</div>
</div>
</div>
"""
def _hero_html() -> str:
return """
<div class="nx-hero">
<div class="nx-sigil">transmission zero</div>
<h1 class="nx-title">The First Anomaly</h1>
<p class="nx-sub">
A signal breached containment. The public face stays small, deliberate, and sealed.
</p>
<div class="nx-badge-row">
<span class="nx-badge">first contact</span>
<span class="nx-badge">read-only pulse</span>
<span class="nx-badge">artifact drop</span>
<span class="nx-badge">sealed core</span>
</div>
</div>
"""
def _artifact_copy() -> str:
return "\n".join(
[
"### Artifact drop",
"- `shard-0x00.txt` is attached below.",
"- Three redacted traces live in `logs/`.",
"- The shard stays public-safe. The core stays hidden.",
]
)
def _stream_transmission() -> Any:
transcript: list[str] = []
for fragment in FRAGMENTS:
transcript.append(f"> {fragment}...")
yield "\n".join(transcript)
time.sleep(0.55)
def build_ui() -> gr.Blocks:
theme = gr.themes.Base(
primary_hue=gr.themes.Color(
c50="#e7fbff",
c100="#c7f4ff",
c200="#96e9ff",
c300="#5fd6ff",
c400="#2cc2ff",
c500="#00aef2",
c600="#008fcc",
c700="#006fa0",
c800="#0a567f",
c900="#0a3e5b",
c950="#08283b",
),
secondary_hue=gr.themes.Color(
c50="#fff7df",
c100="#ffe9ad",
c200="#ffd56d",
c300="#ffc63b",
c400="#ffb200",
c500="#e29a00",
c600="#b87900",
c700="#8f5d00",
c800="#6d4700",
c900="#4f3300",
c950="#2d1e00",
),
neutral_hue=gr.themes.colors.slate,
font=[gr.themes.GoogleFont("Space Grotesk"), "system-ui", "sans-serif"],
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"],
).set(
body_background_fill="#050812",
body_text_color="#e8f4ff",
block_background_fill="#0a0e18",
block_border_width="1px",
block_border_color="rgba(120, 200, 255, 0.18)",
input_background_fill="#0f1524",
input_border_color="rgba(56, 189, 248, 0.22)",
button_primary_background_fill="#00aef2",
button_primary_text_color="#08131d",
)
css = """
body {
background:
radial-gradient(circle at 12% 10%, rgba(0, 174, 242, 0.18), transparent 24%),
radial-gradient(circle at 88% 8%, rgba(112, 76, 255, 0.14), transparent 20%),
radial-gradient(circle at 50% 120%, rgba(224, 76, 255, 0.12), transparent 26%),
linear-gradient(180deg, #050812 0%, #040711 46%, #03050c 100%);
color: #e8f4ff;
}
body::before {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
background-image:
linear-gradient(rgba(120, 200, 255, 0.06) 1px, transparent 1px),
linear-gradient(90deg, rgba(120, 200, 255, 0.04) 1px, transparent 1px);
background-size: 100% 28px, 28px 100%;
mask-image: linear-gradient(180deg, rgba(0, 0, 0, 0.45), transparent 92%);
opacity: 0.55;
}
.gradio-container {
max-width: 1240px !important;
}
.nx-sigil-frame {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin: 0 0 1rem;
padding: 0.95rem 1.05rem;
border: 1px solid rgba(120, 200, 255, 0.18);
border-radius: 18px;
background:
linear-gradient(180deg, rgba(12, 16, 27, 0.92), rgba(8, 10, 16, 0.88));
box-shadow: 0 18px 72px rgba(0, 0, 0, 0.28);
}
.nx-sigil-mark {
display: grid;
grid-template-columns: repeat(2, 10px);
grid-auto-rows: 10px;
gap: 8px;
position: relative;
width: 36px;
min-width: 36px;
height: 36px;
align-content: center;
justify-content: center;
}
.nx-sigil-mark span {
border-radius: 999px;
background: linear-gradient(180deg, #00d9ff, #6e4fff);
box-shadow: 0 0 14px rgba(0, 217, 255, 0.55);
animation: nxPulse 3.6s ease-in-out infinite;
}
.nx-sigil-mark span:nth-child(2),
.nx-sigil-mark span:nth-child(4) {
animation-delay: 0.45s;
}
.nx-eyebrow {
text-transform: uppercase;
letter-spacing: 0.3em;
font-size: 0.7rem;
color: #87dfff;
margin-bottom: 0.22rem;
}
.nx-microcopy {
color: #9db4cb;
font-size: 0.88rem;
}
.nx-hero {
position: relative;
overflow: hidden;
border: 1px solid rgba(120, 200, 255, 0.18);
border-radius: 24px;
padding: 1.3rem 1.35rem;
background:
radial-gradient(circle at top, rgba(0, 174, 242, 0.22), transparent 38%),
radial-gradient(circle at 85% 12%, rgba(110, 79, 255, 0.16), transparent 24%),
linear-gradient(180deg, rgba(10, 14, 24, 0.98), rgba(8, 10, 16, 0.98));
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.03), 0 28px 92px rgba(0, 0, 0, 0.45);
}
.nx-hero::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background:
linear-gradient(115deg, transparent 0%, rgba(255, 255, 255, 0.06) 48%, transparent 60%);
opacity: 0.18;
transform: translateX(-28%);
animation: nxSweep 12s ease-in-out infinite;
}
.nx-sigil {
text-transform: uppercase;
letter-spacing: 0.32em;
font-size: 0.72rem;
color: #7bd7ff;
margin-bottom: 0.6rem;
}
.nx-title {
margin: 0;
font-size: clamp(2.8rem, 5vw, 5rem);
line-height: 0.92;
color: #f4fbff;
text-wrap: balance;
}
.nx-sub {
margin: 0.8rem 0 0;
color: #b7c7dd;
font-size: 1.02rem;
max-width: 44rem;
}
.nx-badge-row {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
margin-top: 1rem;
}
.nx-badge {
padding: 0.35rem 0.65rem;
border-radius: 999px;
border: 1px solid rgba(120, 200, 255, 0.2);
background: rgba(10, 16, 28, 0.84);
color: #d9f4ff;
font-size: 0.78rem;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.nx-card {
position: relative;
overflow: hidden;
border-radius: 18px;
padding: 1rem 1.05rem 0.95rem;
background:
linear-gradient(180deg, rgba(10, 14, 24, 0.88), rgba(8, 10, 16, 0.95));
border: 1px solid rgba(120, 200, 255, 0.16);
box-shadow: 0 20px 65px rgba(0, 0, 0, 0.3);
}
.nx-card::before {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background: radial-gradient(circle at top left, rgba(0, 174, 242, 0.12), transparent 36%);
opacity: 0.9;
}
.nx-card--artifact .gr-file {
border-radius: 14px;
overflow: hidden;
}
.nx-card--terminal textarea {
min-height: 236px !important;
font-family: "IBM Plex Mono", monospace !important;
background: linear-gradient(180deg, rgba(4, 10, 16, 0.98), rgba(6, 12, 19, 0.98)) !important;
border: 1px solid rgba(0, 174, 242, 0.15) !important;
color: #e8f4ff !important;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.02);
}
.nx-card--terminal textarea::selection {
background: rgba(0, 174, 242, 0.3);
}
.nx-terminal-rail {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.6rem;
margin-top: 0.8rem;
}
.nx-chip {
border-radius: 12px;
border: 1px solid rgba(120, 200, 255, 0.14);
padding: 0.75rem 0.8rem;
background: rgba(13, 18, 30, 0.72);
}
.nx-chip-label {
display: block;
color: #8ca6be;
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.12em;
margin-bottom: 0.25rem;
}
.nx-chip-value {
display: block;
color: #eff9ff;
font-size: 0.92rem;
}
.nx-shard-note {
margin-top: 0.7rem;
color: #89a6c4;
font-size: 0.84rem;
}
.nx-status-orb {
width: 12px;
height: 12px;
border-radius: 999px;
background: #00d9ff;
box-shadow: 0 0 0 0 rgba(0, 217, 255, 0.45);
animation: nxPing 2.1s infinite;
margin-top: 0.2rem;
}
.nx-terminal-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
margin-bottom: 0.8rem;
}
.nx-terminal-title {
margin: 0;
font-size: 1.02rem;
color: #eff9ff;
text-transform: uppercase;
letter-spacing: 0.14em;
}
.nx-terminal-sub {
margin: 0.3rem 0 0;
color: #97afc8;
font-size: 0.86rem;
}
.nx-rail-note {
color: #88a1ba;
font-size: 0.82rem;
margin: 0.7rem 0 0;
}
button, .gr-button {
border-radius: 999px !important;
background: linear-gradient(90deg, #00aef2, #6e4fff) !important;
color: #07111b !important;
border: 0 !important;
font-weight: 700 !important;
letter-spacing: 0.08em;
text-transform: uppercase;
box-shadow: 0 16px 36px rgba(0, 174, 242, 0.22);
}
button:hover, .gr-button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
.gr-file > div {
background: rgba(7, 12, 20, 0.9) !important;
border-color: rgba(120, 200, 255, 0.16) !important;
}
@keyframes nxPulse {
0%, 100% { transform: scale(0.96); opacity: 0.78; }
50% { transform: scale(1.12); opacity: 1; }
}
@keyframes nxPing {
0% { box-shadow: 0 0 0 0 rgba(0, 217, 255, 0.44); }
70% { box-shadow: 0 0 0 16px rgba(0, 217, 255, 0); }
100% { box-shadow: 0 0 0 0 rgba(0, 217, 255, 0); }
}
@keyframes nxSweep {
0%, 70% { transform: translateX(-28%); opacity: 0.08; }
85% { opacity: 0.2; }
100% { transform: translateX(28%); opacity: 0.06; }
}
"""
with gr.Blocks(theme=theme, css=css, title="Transmission Zero", analytics_enabled=False) as demo:
gr.HTML(_sigil_html())
gr.HTML(_hero_html())
with gr.Row(equal_height=True):
with gr.Column(scale=5, min_width=360):
with gr.Group(elem_classes=["nx-card"]):
pulse = gr.Markdown()
gr.HTML(
"""
<div class="nx-terminal-rail">
<div class="nx-chip">
<span class="nx-chip-label">Containment</span>
<span class="nx-chip-value">sealed public shell</span>
</div>
<div class="nx-chip">
<span class="nx-chip-label">Surface</span>
<span class="nx-chip-value">first-contact anomaly</span>
</div>
<div class="nx-chip">
<span class="nx-chip-label">Truth</span>
<span class="nx-chip-value">read-only pulse only</span>
</div>
</div>
"""
)
with gr.Column(scale=7, min_width=360):
with gr.Group(elem_classes=["nx-card", "nx-card--artifact"]):
gr.Markdown(_artifact_copy())
gr.File(
value=str(SHARD_PATH),
label="Shard-0X00",
interactive=False,
)
gr.Markdown(
"<p class='nx-shard-note'>"
"Three redacted traces. One shard. The core remains hidden."
"</p>"
)
with gr.Row():
with gr.Column():
with gr.Group(elem_classes=["nx-card", "nx-card--terminal"]):
gr.HTML(
"""
<div class="nx-terminal-header">
<div>
<h3 class="nx-terminal-title">Transmission terminal</h3>
<p class="nx-terminal-sub">A deliberate signal path for the first anomaly.</p>
</div>
<div class="nx-status-orb" aria-hidden="true"></div>
</div>
"""
)
terminal = gr.Textbox(
value="> awaiting the first anomaly...",
label="",
lines=8,
interactive=False,
show_label=False,
elem_classes=["nx-terminal"],
)
btn = gr.Button("INITIATE LINK", variant="primary")
gr.Markdown(
"<p class='nx-rail-note'>"
"Read-only by default. No private data is exposed here."
"</p>"
)
btn.click(fn=_stream_transmission, outputs=terminal)
demo.load(fn=lambda: _pulse_markdown(_bridge_snapshot()), outputs=pulse)
return demo
demo = build_ui()
demo.queue()
if __name__ == "__main__":
demo.launch()