ramboweb3's picture
Add ZeroGPU startup guard
3b602b7 verified
Raw History Blame Contribute Delete
13.7 kB
"""Zambo Receipt Verifier β€” verify AI agent execution receipts against the live Zambo ledger.
Paste a zambo.dev receipt URL (https://zambo.dev/run/<uuid>) and this app asks
zambo.dev's own verification endpoint whether the receipt is genuine, then shows
exactly what the ledger says: tool, timestamp, output hash, ledger checks, and
the public anchor. No verdict is ever invented β€” every displayed fact comes from
a real fetch. VERIFIED = the ledger confirmed it. NOT VERIFIED = no record.
"""
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
import gradio as gr
import spaces
# ---------------------------------------------------------------- config
VERIFY_API = "https://zambo.dev/api/receipt" # GET {base}/{uuid}/verify
RECEIPT_PAGE = "https://zambo.dev/run"
RUN_YOUR_OWN = "https://zambo.dev/?src=hf-space"
TIMEOUT = 20
MAX_RETRIES = 5
UUID_RE = re.compile(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
)
LIME = "#b8f53d"
INK = "#0b0d08"
# ------------------------------------------------------- ZeroGPU startup guard
# This Space runs on ZeroGPU hardware, which requires at least one
# @spaces.GPU-decorated function at startup. The verifier is pure CPU
# (urllib calls to the zambo.dev API); this helper is never invoked by the UI.
@spaces.GPU
def _gpu_startup_probe():
return "ok"
CSS = """
body, .gradio-container { background: #0b0d08 !important; }
.gradio-container { max-width: 860px !important; margin: 0 auto; }
.zb-head { text-align: center; padding: 2.2rem 1rem 0.6rem; }
.zb-head h1 { color: #f4f7ec; font-size: 2.1rem; letter-spacing: -0.02em; margin: 0; }
.zb-head h1 .lime { color: #b8f53d; }
.zb-kicker { color: #b8f53d; font-size: 0.78rem; letter-spacing: 0.22em;
text-transform: uppercase; margin-bottom: 0.7rem; }
.zb-sub { color: #9aa08e; font-size: 0.95rem; margin-top: 0.5rem; }
.zb-intro { color: #c9cfbd; font-size: 0.98rem; line-height: 1.6;
background: #12150e; border: 1px solid #232818; border-radius: 14px;
padding: 1rem 1.25rem; margin: 1rem 0 1.4rem; }
.zb-intro strong { color: #f4f7ec; }
.zb-badge { text-align: center; border-radius: 16px; padding: 1.6rem 1rem;
margin: 1.2rem 0; font-size: 1.05rem; line-height: 1.5; }
.zb-badge .big { font-size: 1.9rem; font-weight: 800; letter-spacing: 0.04em; }
.zb-ok { background: #101a08; border: 2px solid #b8f53d;
box-shadow: 0 0 34px rgba(184,245,61,0.16); color: #eef7da; }
.zb-ok .big { color: #b8f53d; }
.zb-no { background: #1c0f0d; border: 2px solid #f0644d; color: #f6dcd4; }
.zb-no .big { color: #f0644d; }
.zb-warn { background: #1d1808; border: 2px solid #e8b93d; color: #f3e6c4; }
.zb-warn .big { color: #e8b93d; }
.zb-details { background: #12150e; border: 1px solid #232818; border-radius: 14px;
padding: 1.1rem 1.3rem; color: #c9cfbd; font-size: 0.95rem;
line-height: 1.75; }
.zb-details h3 { color: #f4f7ec; margin: 0 0 0.4rem; font-size: 1.05rem; }
.zb-details code { background: #0b0d08; border: 1px solid #2c3320; color: #b8f53d;
border-radius: 6px; padding: 0.1rem 0.4rem; font-size: 0.85em;
word-break: break-all; }
.zb-details .chk { color: #b8f53d; }
.zb-cta { text-align: center; margin: 2rem 0 0.5rem; padding: 1.6rem 1rem;
background: linear-gradient(180deg, #141a0b, #0e1208);
border: 1px solid #2c3320; border-radius: 16px; }
.zb-cta h2 { color: #f4f7ec; margin: 0 0 0.5rem; font-size: 1.3rem; }
.zb-cta p { color: #9aa08e; font-size: 0.95rem; margin: 0 0 1rem; }
.zb-foot { text-align: center; color: #6b705f; font-size: 0.8rem;
margin: 1.4rem 0 2rem; }
.zb-note { color: #8a8f7d; font-size: 0.85rem; line-height: 1.6;
border-left: 3px solid #b8f53d; padding-left: 0.9rem; margin: 1rem 0; }
input[type="text"] { background: #12150e !important; color: #f4f7ec !important;
border: 1px solid #2c3320 !important; border-radius: 10px !important; }
button.primary { background: #b8f53d !important; color: #0b0d08 !important;
font-weight: 700 !important; border-radius: 10px !important; }
"""
# ---------------------------------------------------------------- fetch
class ReceiptNotFound(Exception):
pass
class LedgerUnreachable(Exception):
pass
def extract_uuid(text):
"""Return (uuid, error_html). error_html is None on success."""
text = (text or "").strip()
if not text:
return None, (
"That box is empty β€” paste a <b>zambo.dev/run/&lt;receipt-id&gt;</b> "
"URL, or just the receipt ID itself."
)
# If it looks like a URL, the host must be zambo.dev.
if "://" in text or text.lower().startswith("zambo.dev"):
host = urllib.parse.urlparse(
text if "://" in text else "https://" + text
).hostname or ""
if host.lower() not in ("zambo.dev", "www.zambo.dev"):
return None, (
"This checker only verifies <b>zambo.dev</b> receipts β€” "
"that link points somewhere else."
)
m = UUID_RE.search(text)
if not m:
return None, (
"That doesn't look like a receipt link. Paste a full "
"<b>zambo.dev/run/&lt;receipt-id&gt;</b> URL, or just the receipt ID."
)
return m.group(0).lower(), None
def fetch_verification(uuid):
"""Hit zambo.dev's verify endpoint with retries. Returns parsed JSON.
Raises ReceiptNotFound on HTTP 404, LedgerUnreachable when the ledger
never answers after retries.
"""
url = f"{VERIFY_API}/{uuid}/verify"
last_err = None
for attempt in range(MAX_RETRIES):
try:
req = urllib.request.Request(
url, headers={"User-Agent": "zambo-receipt-verifier/1.0 (hf-space)"}
)
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code == 404:
raise ReceiptNotFound()
last_err = e
except Exception as e: # timeouts, truncated bodies, resets β€” retry
last_err = e
time.sleep(1.0 * (attempt + 1))
raise LedgerUnreachable(str(last_err))
# ---------------------------------------------------------------- render
def fmt_ts(iso):
try:
dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
return dt.strftime("%b %d, %Y Β· %H:%M:%S UTC")
except Exception:
return iso
def short_hash(h):
h = h or ""
return h if len(h) <= 26 else h[:13] + "…" + h[-8:]
def badge(kind, big, line):
cls = {"ok": "zb-ok", "no": "zb-no", "warn": "zb-warn"}[kind]
return (
f'<div class="zb-badge {cls}"><div class="big">{big}</div>'
f"<div>{line}</div></div>"
)
def render_verified(d, uuid):
tool = d.get("tool", {}) or {}
tool_name = tool.get("name", "unknown tool")
tool_ver = tool.get("version", "")
checks = d.get("checks", {}) or {}
log_ts = (checks.get("immutable_log_timestamp") or {}).get("timestamp", "")
out_hash = d.get("output_hash", "")
anchor = d.get("anchor", {}) or {}
provenance = d.get("provenance", {}) or {}
check_labels = []
for key in ("signature_valid", "issued_by_zambo_dev",
"chain_valid", "immutable_log_timestamp"):
c = checks.get(key) or {}
if isinstance(c, dict) and c.get("passed"):
check_labels.append(c.get("label", key))
elif c is True:
check_labels.append(key.replace("_", " "))
checks_md = " Β· ".join(f'<span class="chk">βœ“ {c}</span>' for c in check_labels)
anchor_md = ""
if anchor:
ev = anchor.get("event_id", "")
status = anchor.get("status", "")
relays = ", ".join(
r.replace("wss://", "") for r in (anchor.get("relays") or [])
)
pub_at = fmt_ts(anchor.get("published_at", "")) if anchor.get("published_at") else ""
ev_link = (
f'<a href="https://njump.me/{ev}" target="_blank" rel="noopener">'
f"<code>{short_hash(ev)}</code></a>" if ev else "β€”"
)
anchor_md = (
f"- **Public anchor:** {status} β€” event {ev_link}"
+ (f" Β· anchored {pub_at}" if pub_at else "")
+ (f"<br>Relays: <code>{relays}</code>" if relays else "")
)
prov_md = ""
if provenance.get("source"):
prov_md = f"\n- **Data source:** {provenance['source']}"
details = (
f'<div class="zb-details">\n<h3>Receipt <code>{uuid[:8]}</code> β€” '
f"{tool_name} result</h3>\n"
f"- **Tool:** <code>{tool_name}</code>"
+ (f" (v{tool_ver})" if tool_ver else "") + "\n"
f"- **Ran at:** {fmt_ts(log_ts) if log_ts else 'β€”'}\n"
f"- **Output hash:** <code>{out_hash}</code>\n"
f"- **Ledger checks:** {checks_md or 'β€”'}\n"
f"{anchor_md}{prov_md}\n"
f"- **Receipt page:** <a href=\"{RECEIPT_PAGE}/{uuid}\" target=\"_blank\" "
f'rel="noopener">zambo.dev/run/{uuid[:8]}…</a>\n'
f'<div style="margin-top:0.6rem;color:#8a8f7d;font-size:0.85rem;">'
f"Checked live against zambo.dev just now.</div>\n</div>"
)
head = badge(
"ok", "βœ“ VERIFIED",
"This receipt is real. The ledger confirms every field below β€” the hash "
"matches the stored output, and the record is anchored outside Zambo too.",
)
return head, details
def render_not_verified(uuid):
head = badge(
"no", "βœ• NOT VERIFIED",
"zambo.dev has no record of this receipt. Either the link is off, or "
"this receipt doesn't exist β€” double-check the URL and try again.",
)
details = (
'<div class="zb-details">No ledger entry found for '
f"<code>{uuid}</code>. Nothing was confirmed, nothing was denied β€” "
"the receipt simply isn't there.</div>"
)
return head, details
def render_error():
head = badge(
"warn", "⚠ NO VERDICT",
"Couldn't reach the Zambo ledger right now, so no verdict β€” the network "
"flaked, not the receipt. Give it a moment and try again.",
)
return head, ""
def render_bad_input(msg):
return badge("warn", "⚠ CHECK YOUR INPUT", msg), ""
# ---------------------------------------------------------------- app
def verify(text):
uuid, err = extract_uuid(text)
if err:
return render_bad_input(err)
try:
data = fetch_verification(uuid)
except ReceiptNotFound:
return render_not_verified(uuid)
except LedgerUnreachable:
return render_error()
if isinstance(data, dict) and data.get("verified") is True:
return render_verified(data, uuid)
# The ledger answered but did not confirm β€” treat as not verified, honestly.
return render_not_verified(uuid)
HEADER = """
<div class="zb-head">
<div class="zb-kicker">AI agent execution receipts Β· verifiable receipts Β· MCP</div>
<h1>Zambo <span class="lime">Receipt Verifier</span> 🦞</h1>
<div class="zb-sub">Paste a receipt link. Get a straight answer.</div>
</div>
"""
INTRO = """
<div class="zb-intro">
Every Zambo tool call leaves a <strong>verifiable receipt</strong> β€” a public
record of what the agent ran, when it ran, and exactly what came out.
Paste a receipt link below and this app checks it against the <strong>live
Zambo ledger</strong>. If it holds up, you see the proof. If it doesn't,
you'll hear it straight.
</div>
"""
NOTE = """
<div class="zb-note">
<strong>What VERIFIED actually means:</strong> the receipt itself is genuine β€”
the work happened, the hash matches the stored output, and the record is
anchored. It doesn't mean the underlying data is still fresh (a price from
last week is still last week's price).
</div>
"""
CTA = """
<div class="zb-cta">
<h2>Run your own free call</h2>
<p>Every Zambo tool call mints one of these receipts. Free tier: 20 calls per
tool per day, no account, no card. 100+ tools your agent can actually use β€”
with proof attached to every call.</p>
</div>
"""
FOOTER = """
<div class="zb-foot">
Built on the Zambo execution layer Β· Free: 20 calls/tool/day, no account<br>
Verification runs live against zambo.dev β€” nothing here is cached or made up.
</div>
"""
EXAMPLE_URL = "https://zambo.dev/run/a081dbf7-6898-41f4-b7f0-559a08e7a5e6"
def build_demo():
with gr.Blocks(title="Zambo Receipt Verifier β€” verify AI agent execution receipts") as demo:
gr.HTML(HEADER)
gr.HTML(INTRO)
with gr.Row():
inp = gr.Textbox(
label="Receipt URL or receipt ID",
placeholder="https://zambo.dev/run/a081dbf7-6898-41f4-b7f0-559a08e7a5e6",
lines=1,
scale=4,
)
btn = gr.Button("Verify receipt", variant="primary", scale=1)
gr.Examples(
examples=[[EXAMPLE_URL]],
inputs=inp,
label="Try it with a real receipt",
)
badge_out = gr.HTML()
details_out = gr.HTML()
gr.HTML(NOTE)
gr.HTML(CTA)
gr.Button("Run your own free call β†’", link=RUN_YOUR_OWN)
gr.HTML(FOOTER)
btn.click(verify, inputs=inp, outputs=[badge_out, details_out])
inp.submit(verify, inputs=inp, outputs=[badge_out, details_out])
return demo
demo = build_demo()
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
demo.launch(css=CSS, server_name="0.0.0.0", server_port=port)