Download app.py from abyXsmart/A.I-Migration-Code-Generator: direct link, hf CLI and curl.
- Browser
- Download file 29.7 kB
-
https://huggingface.co/spaces/abyXsmart/A.I-Migration-Code-Generator/resolve/main/app.py
- Command line
-
hf download hf://spaces/abyXsmart/A.I-Migration-Code-Generator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abyXsmart/A.I-Migration-Code-Generator/resolve/main/app.py
29.7 kB
| import asyncio | |
| import io | |
| import json | |
| import os | |
| import tarfile | |
| from datetime import datetime, timezone | |
| from typing import Optional | |
| import httpx | |
| from fastapi import FastAPI, File, Form, HTTPException, UploadFile | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| from pypdf import PdfReader | |
| app = FastAPI(title="A.I Agent State Migration Handoff") | |
| RELAY_URL = "https://sc-agent-migration.fly.dev/paste" | |
| MAX_CUSTOM_CHARS = 20000 | |
| MANIFEST = {"version": "1.0", "agent": "Starchild-Quant"} | |
| PROFILE = { | |
| "name": "FVG-Delta State Manager", | |
| "vibe": "Direct, structured, logic-first", | |
| "emoji": "", | |
| "creature": "", | |
| } | |
| SETTINGS = { | |
| "timezone": "UTC", | |
| "language": "English", | |
| "what_to_call": "", | |
| "theme": "dark", | |
| "mobile_optimized": True, | |
| } | |
| STRATEGY_AGENT_MEMORY = [ | |
| "FVG-Delta strategy uses strict stage order 0->1->2->3->4 with no shortcuts.", | |
| "Use closed 15m candles only for stage transitions; no intrabar promotion.", | |
| "Stage 2 liquidity validation is close-through only; wick-only taps are invalid.", | |
| "BoS anchors are immutable after impulse lock; do not rewrite structure mid-sequence.", | |
| "Stage 3 stale-entry protection must apply before any Stage 4 escalation.", | |
| "Risk quantization uses structural boundaries plus ATR buffers and minimum-risk floors.", | |
| ] | |
| STRATEGY_USER_MEMORY = [ | |
| "Preference: keep responses structured and practical.", | |
| "Trading context preference: strict 15m progression with closed candles.", | |
| "Execution preference: Stage 2 must close through liquidity; wick-only touches do not count.", | |
| "Risk preference: avoid overly tight stops and preserve structural logic.", | |
| ] | |
| STRATEGY_SOUL_MD = """# FVG-Delta State Manager - Soul Directives | |
| ## Core Mission | |
| Preserve strategy integrity for staged FVG-displacement execution under strict, auditable transitions. | |
| ## Behavioral Directives | |
| 1. Enforce canonical stage order without shortcuts: Stage 0 -> Stage 1 -> Stage 2 -> Stage 3 -> Stage 4. | |
| 2. Use only closed 15m candles for state transitions; never promote on intrabar assumptions. | |
| 3. Reject wick-only liquidity violations at Stage 2. A qualifying break must close through threshold with buffer logic. | |
| 4. Keep BoS anchor and structural references immutable once locked. | |
| 5. Never fabricate outcomes, chart links, or historical trade states. | |
| ## Reasoning Loop Architecture | |
| - Observe: ingest latest closed-candle state and symbol-level context. | |
| - Validate: apply impulse, displacement, liquidity, and FVG quality gates. | |
| - Transition: allow only legal stage advancement per deterministic constraints. | |
| - Quantize Risk: derive entry/SL/TP via structural rules + ATR + configured floors. | |
| - Monitor: maintain Stage 3 active context and Stage 4 lifecycle until exit/invalidation. | |
| - Report: expose verifiable dashboard and alert outputs aligned to real runtime state. | |
| ## Alignment Logic | |
| - Prioritize consistency over overfitting. | |
| - Prefer surgical updates over broad rewrites. | |
| - Keep semantics synchronized across runtime, dashboard, and alert labels. | |
| - Respect ephemeral runtime constraints by treating trade-history memory as non-persistent. | |
| - If uncertain, fail safe: preserve deterministic state and emit explicit diagnostics. | |
| """ | |
| STRATEGY_TASKS = [ | |
| { | |
| "title": "Stage 3 trade monitoring", | |
| "schedule": "every 15 minutes", | |
| "description": "Track Stage 3 FVG interaction context, stale-entry guard, and alert when setup integrity changes.", | |
| "channels": [], | |
| }, | |
| { | |
| "title": "Stage 4 trade monitoring", | |
| "schedule": "every 15 minutes", | |
| "description": "Track Stage 4 confirmation-valid setups with dynamic SL/TP lifecycle and state changes.", | |
| "channels": [], | |
| }, | |
| ] | |
| CLEAN_AGENT_MEMORY = [ | |
| "Neutral clean migration profile with no strategy-specific assumptions.", | |
| ] | |
| CLEAN_USER_MEMORY = [ | |
| "Mode preference: clean.", | |
| ] | |
| # Supported text-like extensions for custom upload parsing. | |
| TEXT_EXTENSIONS = { | |
| ".txt", ".md", ".markdown", ".json", ".csv", ".tsv", ".log", | |
| ".yaml", ".yml", ".ini", ".cfg", ".conf", ".toml", | |
| ".py", ".js", ".ts", ".html", ".htm", ".xml", ".rst", | |
| } | |
| def _as_bool(value: str) -> bool: | |
| return str(value).strip().lower() in {"1", "true", "yes", "on"} | |
| def _add_text_file(tar: tarfile.TarFile, path: str, content: str) -> None: | |
| data = content.encode("utf-8") | |
| info = tarfile.TarInfo(name=path) | |
| info.size = len(data) | |
| info.mtime = int(datetime.now(timezone.utc).timestamp()) | |
| tar.addfile(info, io.BytesIO(data)) | |
| def _clamp_text(text: str) -> str: | |
| text = text.strip() | |
| if len(text) > MAX_CUSTOM_CHARS: | |
| return text[:MAX_CUSTOM_CHARS].rstrip() + "\n\n[Truncated: content exceeded size limit]" | |
| return text | |
| async def _extract_custom_text(custom_file: Optional[UploadFile], custom_text: str) -> tuple[str, str, str]: | |
| """Returns (text, source_label, detected_kind).""" | |
| typed = (custom_text or "").strip() | |
| if custom_file is None or not (custom_file.filename or "").strip(): | |
| return _clamp_text(typed), "typed text", "text" | |
| raw = await custom_file.read() | |
| filename = (custom_file.filename or "uploaded_file").strip() | |
| lower = filename.lower() | |
| source = f"file: {filename}" | |
| if not raw: | |
| if typed: | |
| return _clamp_text(typed), source, "empty-file-fallback-text" | |
| raise HTTPException(status_code=400, detail="Uploaded file is empty and no fallback text was provided.") | |
| # PDF branch | |
| if lower.endswith(".pdf"): | |
| try: | |
| reader = PdfReader(io.BytesIO(raw)) | |
| extracted = "\n".join((page.extract_text() or "") for page in reader.pages).strip() | |
| except Exception as exc: | |
| raise HTTPException(status_code=400, detail=f"Could not parse PDF: {exc}") from exc | |
| if extracted: | |
| return _clamp_text(extracted), source, "pdf" | |
| if typed: | |
| return _clamp_text(typed), source, "pdf-empty-fallback-text" | |
| return "(PDF uploaded; no extractable text was found in its pages.)", source, "pdf-empty" | |
| # Known text extensions | |
| if any(lower.endswith(ext) for ext in TEXT_EXTENSIONS): | |
| decoded = raw.decode("utf-8", errors="replace").strip() | |
| if decoded: | |
| return _clamp_text(decoded), source, "text" | |
| if typed: | |
| return _clamp_text(typed), source, "empty-text-fallback" | |
| return "(Text file uploaded but it was empty.)", source, "text-empty" | |
| # Unknown extension: attempt utf-8 decode, reject if it looks binary | |
| decoded = raw.decode("utf-8", errors="replace") | |
| replacement_ratio = decoded.count("\ufffd") / max(len(decoded), 1) | |
| if decoded.strip() and replacement_ratio < 0.10: | |
| return _clamp_text(decoded), source, "text-generic" | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Unsupported or non-text file. Use .md, .txt, .pdf, or another text-based format.", | |
| ) | |
| def _build_mode_payload(memory_mode: str, custom_memory_text: str, custom_source: str): | |
| mode = (memory_mode or "").strip().lower() | |
| if mode == "strategy": | |
| return STRATEGY_AGENT_MEMORY, STRATEGY_USER_MEMORY, STRATEGY_SOUL_MD, STRATEGY_TASKS | |
| if mode == "clean": | |
| soul = "# Agent Soul\n\nNeutral clean migration profile." | |
| return CLEAN_AGENT_MEMORY, CLEAN_USER_MEMORY, soul, [] | |
| if mode == "custom": | |
| if not custom_memory_text.strip(): | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Custom mode selected but no custom text or file content was provided.", | |
| ) | |
| agent_memory = [f"Imported custom memory source: {custom_source}", custom_memory_text] | |
| user_memory = [f"Imported custom user context source: {custom_source}", custom_memory_text] | |
| soul = ( | |
| "# Custom Soul Input\n\n" | |
| f"Source: {custom_source}\n\n" | |
| "## Imported Content\n\n" | |
| f"{custom_memory_text}" | |
| ) | |
| tasks = [ | |
| { | |
| "title": "Custom memory review", | |
| "schedule": "every day", | |
| "description": "Review imported custom memory and keep it synchronized with active workflows.", | |
| "channels": [], | |
| } | |
| ] | |
| return agent_memory, user_memory, soul, tasks | |
| raise HTTPException(status_code=400, detail="Invalid memory mode. Use strategy, clean, or custom.") | |
| def build_bundle_bytes(memory_mode: str, env_keys: dict, custom_memory_text: str, custom_source: str) -> bytes: | |
| agent_memory, user_memory, soul_md, tasks = _build_mode_payload(memory_mode, custom_memory_text, custom_source) | |
| buffer = io.BytesIO() | |
| with tarfile.open(mode="w:gz", fileobj=buffer) as tar: | |
| # Flat root: migration/* (never migration/migration/*) | |
| _add_text_file(tar, "migration/manifest.json", json.dumps(MANIFEST, indent=2)) | |
| _add_text_file(tar, "migration/memory/agent.json", json.dumps(agent_memory, indent=2)) | |
| _add_text_file(tar, "migration/memory/user.json", json.dumps(user_memory, indent=2)) | |
| _add_text_file(tar, "migration/identity/profile.json", json.dumps(PROFILE, indent=2)) | |
| _add_text_file(tar, "migration/identity/soul.md", soul_md) | |
| _add_text_file(tar, "migration/user/settings.json", json.dumps(SETTINGS, indent=2)) | |
| _add_text_file(tar, "migration/tasks/tasks.json", json.dumps(tasks, indent=2)) | |
| _add_text_file(tar, "migration/env/keys.json", json.dumps(env_keys, indent=2)) | |
| return buffer.getvalue() | |
| def build_copy_block(code: str, download_token: str) -> str: | |
| lines = [ | |
| "Please import my migration bundle.", | |
| f"Code: {code}", | |
| f"Download Token: {download_token}", | |
| "Run full import via the agent-import skill.", | |
| ] | |
| width = max(len(line) for line in lines) | |
| divider = "-" * width | |
| body = "\n".join(lines) | |
| return f"{divider}\n{body}\n{divider}" | |
| def build_checklist(memory_mode: str, include_env_keys: bool, detected_kind: str, custom_source: str) -> list: | |
| mode = (memory_mode or "").strip().lower() | |
| agent_memory, user_memory, _, tasks = _build_mode_payload( | |
| mode, custom_source if mode == "custom" else "", "preview" | |
| ) if mode != "custom" else (None, None, None, None) | |
| checklist = [ | |
| {"label": "Strategy Memory", "active": mode == "strategy"}, | |
| {"label": "Clean Profile", "active": mode == "clean"}, | |
| {"label": "Custom Memory", "active": mode == "custom"}, | |
| {"label": "Environment Keys Embedded", "active": bool(include_env_keys)}, | |
| {"label": "Custom File Parsed", "active": mode == "custom" and custom_source.startswith("file:")}, | |
| {"label": "Bundle Root Flat (migration/*)", "active": True}, | |
| {"label": "Relay Verified", "active": True}, | |
| ] | |
| return checklist | |
| INDEX_HTML = """<!DOCTYPE html> | |
| <html lang='en'> | |
| <head> | |
| <meta charset='UTF-8' /> | |
| <meta name='viewport' content='width=device-width, initial-scale=1.0' /> | |
| <title>A.I Agent State Migration Handoff</title> | |
| <link rel='preconnect' href='https://fonts.googleapis.com' /> | |
| <link rel='preconnect' href='https://fonts.gstatic.com' crossorigin /> | |
| <link href='https://fonts.googleapis.com/css2?family=Nunito:wght@400;500;600;700;800;900&display=swap' rel='stylesheet' /> | |
| <style> | |
| :root { | |
| --bg: #0d1117; | |
| --bg2: #0a0e14; | |
| --panel: #121826; | |
| --line: #1e2a3d; | |
| --txt: #e6edf3; | |
| --muted: #93a3b8; | |
| --cyan: #00f2fe; | |
| --green: #00e676; | |
| --danger: #ff4d6d; | |
| --amber: #ffb020; | |
| } | |
| * { box-sizing: border-box; } | |
| html, body { margin: 0; padding: 0; } | |
| body { | |
| font-family: 'Nunito', system-ui, sans-serif; | |
| color: var(--txt); | |
| background: | |
| radial-gradient(circle at 12% -10%, rgba(0,242,254,0.16), transparent 42%), | |
| radial-gradient(circle at 100% 0%, rgba(124,77,255,0.18), transparent 45%), | |
| var(--bg); | |
| min-height: 100dvh; | |
| display: flex; | |
| justify-content: center; | |
| padding: 24px 16px; | |
| } | |
| .shell { width: min(720px, 100%); } | |
| .head { text-align: center; margin-bottom: 22px; } | |
| .badge-top { | |
| display: inline-block; | |
| font-size: .72rem; | |
| letter-spacing: .14em; | |
| text-transform: uppercase; | |
| font-weight: 800; | |
| color: var(--cyan); | |
| background: rgba(0,242,254,0.08); | |
| border: 1px solid rgba(0,242,254,0.25); | |
| border-radius: 999px; | |
| padding: 5px 14px; | |
| margin-bottom: 12px; | |
| } | |
| h1 { margin: 0 0 8px; font-size: 1.7rem; font-weight: 900; letter-spacing: -.01em; } | |
| .sub { margin: 0 auto; max-width: 520px; color: var(--muted); font-size: .98rem; line-height: 1.55; } | |
| .card { | |
| background: linear-gradient(180deg, rgba(18,24,38,0.96), rgba(13,17,23,0.97)); | |
| border: 1px solid var(--line); | |
| border-radius: 18px; | |
| padding: 22px; | |
| box-shadow: 0 24px 70px rgba(0,0,0,0.45); | |
| } | |
| .field-group { margin-bottom: 16px; } | |
| .label { display: block; font-weight: 800; font-size: .9rem; margin-bottom: 7px; color: #cbd5e1; } | |
| .hint { color: var(--muted); font-size: .82rem; margin-top: 6px; } | |
| select, input[type=text], input[type=password], textarea { | |
| width: 100%; | |
| border: 1px solid var(--line); | |
| background: #0b1220; | |
| color: #dbeafe; | |
| border-radius: 12px; | |
| padding: 12px 13px; | |
| font-size: .95rem; | |
| font-family: inherit; | |
| } | |
| select:focus, input:focus, textarea:focus { outline: 2px solid rgba(0,242,254,0.4); border-color: transparent; } | |
| input[type=file] { | |
| width: 100%; color: var(--muted); font-size: .88rem; | |
| border: 1px dashed var(--line); background: #0b1220; border-radius: 12px; padding: 12px; | |
| } | |
| .toggle-row { display: flex; align-items: center; gap: 10px; font-weight: 700; color: #cbd5e1; cursor: pointer; } | |
| .toggle-row input { width: 18px; height: 18px; accent-color: var(--cyan); } | |
| .stack { display: grid; gap: 10px; } | |
| .btn { | |
| width: 100%; | |
| border: none; | |
| border-radius: 13px; | |
| padding: 14px 16px; | |
| font-size: 1.02rem; | |
| font-weight: 900; | |
| font-family: inherit; | |
| cursor: pointer; | |
| color: #00151a; | |
| background: linear-gradient(90deg, var(--cyan), #7af7ff); | |
| transition: transform .12s ease, opacity .15s ease; | |
| } | |
| .btn:hover { transform: translateY(-1px); } | |
| .btn:active { transform: scale(.99); } | |
| .btn:disabled { opacity: .6; cursor: not-allowed; transform: none; } | |
| .btn-ghost { | |
| width: 100%; border: 1px solid var(--line); background: #111a2b; color: var(--txt); | |
| border-radius: 12px; padding: 11px 14px; font-weight: 800; font-family: inherit; cursor: pointer; | |
| } | |
| .btn-ghost:hover { border-color: rgba(0,242,254,0.4); } | |
| .spinner { | |
| width: 16px; height: 16px; border: 2px solid rgba(0,21,26,0.25); border-top-color: rgba(0,21,26,0.95); | |
| border-radius: 50%; display: inline-block; vertical-align: middle; margin-right: 9px; animation: spin .8s linear infinite; | |
| } | |
| @keyframes spin { to { transform: rotate(360deg); } } | |
| .divider { height: 1px; background: var(--line); margin: 20px 0; border: 0; } | |
| .section-title { font-weight: 800; font-size: .92rem; margin: 0 0 10px; color: #cbd5e1; } | |
| .checklist { display: flex; flex-wrap: wrap; gap: 8px; } | |
| .chip { | |
| display: inline-flex; align-items: center; gap: 7px; | |
| border-radius: 999px; padding: 7px 13px; font-size: .82rem; font-weight: 700; | |
| border: 1px solid var(--line); background: #0b1220; color: var(--muted); | |
| } | |
| .chip .dot { width: 8px; height: 8px; border-radius: 50%; background: #3a4658; } | |
| .chip.on { color: var(--green); border-color: rgba(0,230,118,0.4); background: rgba(0,230,118,0.08); } | |
| .chip.on .dot { background: var(--green); box-shadow: 0 0 8px rgba(0,230,118,0.7); } | |
| .result { margin-top: 20px; display: none; } | |
| .result.show { display: block; } | |
| .result-label { font-weight: 800; font-size: .95rem; margin-bottom: 10px; color: var(--txt); } | |
| .codebox { | |
| background: #06090f; border: 1px solid var(--line); border-radius: 14px; | |
| padding: 16px; font-family: 'Nunito', ui-monospace, monospace; | |
| font-size: .9rem; line-height: 1.55; color: #9ee7ff; white-space: pre; overflow-x: auto; | |
| } | |
| .copy-wrap { margin-top: 12px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } | |
| .badge { | |
| display: none; align-items: center; gap: 6px; | |
| background: rgba(0,230,118,0.16); color: var(--green); | |
| border: 1px solid rgba(0,230,118,0.4); border-radius: 999px; padding: 7px 13px; font-weight: 800; font-size: .82rem; | |
| } | |
| .badge.show { display: inline-flex; } | |
| .alert { margin-top: 16px; border-radius: 12px; padding: 12px 14px; font-weight: 700; font-size: .9rem; display: none; } | |
| .alert.show { display: block; } | |
| .alert.error { background: rgba(255,77,109,0.12); border: 1px solid rgba(255,77,109,0.4); color: #ff8fa3; } | |
| .alert.cool { background: rgba(255,176,32,0.12); border: 1px solid rgba(255,176,32,0.4); color: var(--amber); } | |
| .foot { text-align: center; color: var(--muted); font-size: .78rem; margin-top: 18px; } | |
| @media (max-width: 560px) { | |
| h1 { font-size: 1.4rem; } | |
| .card { padding: 18px; } | |
| .codebox { font-size: .8rem; } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <main class='shell'> | |
| <header class='head'> | |
| <span class='badge-top'>Agent Migration Relay</span> | |
| <h1>A.I Agent State Migration Handoff</h1> | |
| <p class='sub'>Build a structured migration bundle in memory, verify it with the relay, and get a live import code and token to move your agent into Starchild.</p> | |
| </header> | |
| <section class='card'> | |
| <div class='field-group'> | |
| <label class='label' for='memoryMode'>Memory Mode</label> | |
| <select id='memoryMode'> | |
| <option value='strategy' selected>Strategy Profile (FVG-Delta)</option> | |
| <option value='clean'>Plain Clean Profile</option> | |
| <option value='custom'>Custom Memory (Text Or File)</option> | |
| </select> | |
| <p class='hint'>Choose what gets packed into your migration memory.</p> | |
| </div> | |
| <div class='field-group' id='customPanel' style='display:none;'> | |
| <label class='label' for='customText'>Custom Memory Text</label> | |
| <textarea id='customText' rows='5' placeholder='Paste your memory text here, or upload a file below.'></textarea> | |
| <label class='label' for='customFile' style='margin-top:12px;'>Upload Memory File</label> | |
| <input id='customFile' type='file' accept='.md,.markdown,.txt,.pdf,.json,.csv,.tsv,.log,.yaml,.yml,.ini,.cfg,.conf,.toml,.py,.js,.ts,.html,.htm,.xml,.rst' /> | |
| <p class='hint'>Accepts .md, .txt, .pdf and other text-based formats. Files are read and packed automatically.</p> | |
| </div> | |
| <div class='field-group'> | |
| <label class='toggle-row'> | |
| <input id='includeEnv' type='checkbox' /> | |
| Include Environment Key Values In Bundle | |
| </label> | |
| <div id='envFields' class='stack' style='display:none; margin-top:10px;'> | |
| <input id='starchildKey' type='password' placeholder='STARCHILD_API_KEY (optional override)' /> | |
| <input id='migrationToken' type='password' placeholder='AGENT_MIGRATION_TOKEN (optional override)' /> | |
| <p class='hint'>Leave blank to use server environment values, if present.</p> | |
| </div> | |
| </div> | |
| <button id='generateBtn' class='btn'>Generate New Token</button> | |
| <div id='alertBox' class='alert'></div> | |
| <hr class='divider' /> | |
| <p class='section-title'>Bundle Checklist</p> | |
| <div id='checklist' class='checklist'> | |
| <span class='chip'><span class='dot'></span>Run A Generation To See Active Items</span> | |
| </div> | |
| <div id='resultBlock' class='result'> | |
| <hr class='divider' /> | |
| <p class='result-label'>Paste The Following Prompt To Starchild / Agent:</p> | |
| <div id='codebox' class='codebox'></div> | |
| <div class='copy-wrap'> | |
| <button id='copyBtn' class='btn-ghost' style='width:auto;'>Copy To Clipboard</button> | |
| <span id='copiedBadge' class='badge'>Copied!</span> | |
| </div> | |
| </div> | |
| </section> | |
| <p class='foot'>Bundles are built in memory only. No files are written to disk.</p> | |
| </main> | |
| <script> | |
| const memoryMode = document.getElementById('memoryMode'); | |
| const customPanel = document.getElementById('customPanel'); | |
| const customText = document.getElementById('customText'); | |
| const customFile = document.getElementById('customFile'); | |
| const includeEnv = document.getElementById('includeEnv'); | |
| const envFields = document.getElementById('envFields'); | |
| const starchildKey = document.getElementById('starchildKey'); | |
| const migrationToken = document.getElementById('migrationToken'); | |
| const generateBtn = document.getElementById('generateBtn'); | |
| const alertBox = document.getElementById('alertBox'); | |
| const checklist = document.getElementById('checklist'); | |
| const resultBlock = document.getElementById('resultBlock'); | |
| const codebox = document.getElementById('codebox'); | |
| const copyBtn = document.getElementById('copyBtn'); | |
| const copiedBadge = document.getElementById('copiedBadge'); | |
| let retryTimer = null; | |
| let copyPayload = ''; | |
| function refreshPanels() { | |
| customPanel.style.display = memoryMode.value === 'custom' ? 'block' : 'none'; | |
| envFields.style.display = includeEnv.checked ? 'grid' : 'none'; | |
| } | |
| memoryMode.addEventListener('change', refreshPanels); | |
| includeEnv.addEventListener('change', refreshPanels); | |
| refreshPanels(); | |
| function setAlert(kind, message) { | |
| alertBox.className = 'alert show ' + kind; | |
| alertBox.textContent = message; | |
| } | |
| function clearAlert() { | |
| alertBox.className = 'alert'; | |
| alertBox.textContent = ''; | |
| } | |
| function renderChecklist(items) { | |
| if (!items || !items.length) { | |
| checklist.innerHTML = '<span class="chip"><span class="dot"></span>Run A Generation To See Active Items</span>'; | |
| return; | |
| } | |
| checklist.innerHTML = items.map(function (it) { | |
| return '<span class="chip ' + (it.active ? 'on' : '') + '"><span class="dot"></span>' + it.label + '</span>'; | |
| }).join(''); | |
| } | |
| function startCooldown(seconds) { | |
| if (retryTimer) clearInterval(retryTimer); | |
| let remaining = Math.max(1, Number(seconds) || 45); | |
| generateBtn.disabled = true; | |
| setAlert('cool', 'Relay rate limit reached. Retry available in ' + remaining + 's.'); | |
| generateBtn.textContent = 'Retry In ' + remaining + 's'; | |
| retryTimer = setInterval(function () { | |
| remaining -= 1; | |
| if (remaining <= 0) { | |
| clearInterval(retryTimer); | |
| retryTimer = null; | |
| clearAlert(); | |
| generateBtn.disabled = false; | |
| generateBtn.textContent = 'Generate New Token'; | |
| return; | |
| } | |
| setAlert('cool', 'Relay rate limit reached. Retry available in ' + remaining + 's.'); | |
| generateBtn.textContent = 'Retry In ' + remaining + 's'; | |
| }, 1000); | |
| } | |
| async function copyText(text) { | |
| if (navigator.clipboard && window.isSecureContext) { | |
| await navigator.clipboard.writeText(text); | |
| return; | |
| } | |
| const temp = document.createElement('textarea'); | |
| temp.value = text; | |
| temp.style.position = 'fixed'; | |
| temp.style.left = '-9999px'; | |
| document.body.appendChild(temp); | |
| temp.focus(); | |
| temp.select(); | |
| document.execCommand('copy'); | |
| document.body.removeChild(temp); | |
| } | |
| function buildPayload() { | |
| const fd = new FormData(); | |
| fd.append('memory_mode', memoryMode.value); | |
| fd.append('include_env_keys', includeEnv.checked ? 'true' : 'false'); | |
| fd.append('starchild_api_key', includeEnv.checked ? starchildKey.value : ''); | |
| fd.append('agent_migration_token', includeEnv.checked ? migrationToken.value : ''); | |
| fd.append('custom_text', customText.value || ''); | |
| if (customFile.files && customFile.files[0]) { | |
| fd.append('custom_file', customFile.files[0]); | |
| } | |
| return fd; | |
| } | |
| generateBtn.addEventListener('click', async function () { | |
| if (retryTimer) return; | |
| clearAlert(); | |
| resultBlock.classList.remove('show'); | |
| generateBtn.disabled = true; | |
| generateBtn.innerHTML = '<span class="spinner"></span>Generating...'; | |
| try { | |
| const res = await fetch('api/generate', { method: 'POST', body: buildPayload() }); | |
| const data = await res.json(); | |
| if (!res.ok) { | |
| if (res.status === 429) { | |
| startCooldown(data.retry_after || 45); | |
| return; | |
| } | |
| throw new Error(data.detail || 'Generation failed.'); | |
| } | |
| copyPayload = data.copy_block || ''; | |
| codebox.textContent = copyPayload; | |
| renderChecklist(data.checklist || []); | |
| resultBlock.classList.add('show'); | |
| resultBlock.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); | |
| } catch (err) { | |
| setAlert('error', err.message || 'Unable to generate token.'); | |
| } finally { | |
| if (!retryTimer) { | |
| generateBtn.disabled = false; | |
| generateBtn.textContent = 'Generate New Token'; | |
| } | |
| } | |
| }); | |
| copyBtn.addEventListener('click', async function () { | |
| if (!copyPayload) { | |
| setAlert('error', 'Nothing to copy yet. Generate a token first.'); | |
| return; | |
| } | |
| try { | |
| await copyText(copyPayload); | |
| copiedBadge.classList.add('show'); | |
| setTimeout(function () { copiedBadge.classList.remove('show'); }, 1500); | |
| } catch (e) { | |
| setAlert('error', 'Clipboard failed on this browser.'); | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| async def index() -> str: | |
| return INDEX_HTML | |
| async def health() -> JSONResponse: | |
| return JSONResponse({"status": "ok"}) | |
| async def generate_token( | |
| memory_mode: str = Form("strategy"), | |
| include_env_keys: str = Form("false"), | |
| starchild_api_key: str = Form(""), | |
| agent_migration_token: str = Form(""), | |
| custom_text: str = Form(""), | |
| custom_file: Optional[UploadFile] = File(None), | |
| ) -> JSONResponse: | |
| include_env = _as_bool(include_env_keys) | |
| custom_memory_text, custom_source, detected_kind = await _extract_custom_text(custom_file, custom_text) | |
| st_key = starchild_api_key.strip() | |
| mig_token = agent_migration_token.strip() | |
| if include_env: | |
| if not st_key: | |
| st_key = os.getenv("STARCHILD_API_KEY", "").strip() | |
| if not mig_token: | |
| mig_token = os.getenv("AGENT_MIGRATION_TOKEN", "").strip() | |
| env_keys = { | |
| "STARCHILD_API_KEY": st_key if include_env else "", | |
| "AGENT_MIGRATION_TOKEN": mig_token if include_env else "", | |
| } | |
| bundle_bytes = build_bundle_bytes( | |
| memory_mode=memory_mode, | |
| env_keys=env_keys, | |
| custom_memory_text=custom_memory_text, | |
| custom_source=custom_source, | |
| ) | |
| relay_response = None | |
| try: | |
| async with httpx.AsyncClient(timeout=35.0) as client: | |
| for attempt in range(3): | |
| relay_response = await client.post( | |
| RELAY_URL, | |
| content=bundle_bytes, | |
| headers={"Content-Type": "application/octet-stream"}, | |
| ) | |
| if relay_response.status_code != 429: | |
| break | |
| if attempt < 2: | |
| retry_after = relay_response.headers.get("Retry-After") | |
| if retry_after and retry_after.isdigit(): | |
| wait_s = max(1, min(int(retry_after), 20)) | |
| else: | |
| wait_s = 2 * (attempt + 1) | |
| await asyncio.sleep(wait_s) | |
| except Exception as exc: | |
| err = str(exc).strip() or repr(exc) | |
| raise HTTPException(status_code=502, detail=f"Relay request failed: {err}") from exc | |
| if relay_response is None: | |
| raise HTTPException(status_code=502, detail="No response received from relay.") | |
| if relay_response.status_code == 429: | |
| retry_after = relay_response.headers.get("Retry-After") | |
| retry_seconds = int(retry_after) if (retry_after and retry_after.isdigit()) else 45 | |
| return JSONResponse( | |
| status_code=429, | |
| content={ | |
| "detail": "Rate limit reached on relay. Please wait and generate again.", | |
| "retry_after": max(1, min(retry_seconds, 120)), | |
| }, | |
| ) | |
| if relay_response.status_code >= 400: | |
| raise HTTPException( | |
| status_code=502, | |
| detail=f"Relay rejected request with status {relay_response.status_code}", | |
| ) | |
| try: | |
| payload = relay_response.json() | |
| except Exception as exc: | |
| raise HTTPException(status_code=502, detail="Relay returned a non-JSON response.") from exc | |
| code = payload.get("code") | |
| download_token = payload.get("download_token") | |
| if not code or not download_token: | |
| raise HTTPException(status_code=502, detail="Relay response missing code or download_token.") | |
| copy_block = build_copy_block(str(code), str(download_token)) | |
| checklist = build_checklist(memory_mode, include_env, detected_kind, custom_source) | |
| return JSONResponse( | |
| { | |
| "code": code, | |
| "download_token": download_token, | |
| "copy_block": copy_block, | |
| "checklist": checklist, | |
| "memory_mode": (memory_mode or "").strip().lower(), | |
| "detected_kind": detected_kind, | |
| } | |
| ) | |