Upload 3 files
Browse filesFiles changed (3)
- DockerfileAdded+16
- app.pyAdded+552
- requirements.txtAdded+5
12345678910111213141516FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1
WORKDIR /app
COPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r /app/requirements.txt
COPY app.py /app/app.py
EXPOSE 7860
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552import ioimport jsonimport osimport tarfilefrom datetime import datetime, timezonefrom typing import Optional
import httpxfrom fastapi import FastAPI, File, Form, HTTPException, UploadFilefrom fastapi.responses import HTMLResponse, JSONResponsefrom pypdf import PdfReader
app = FastAPI(title="HF Migration Token Generator")
MANIFEST = {"version": "1.0", "agent": "Starchild-Quant"}PROFILE = {"name": "FVG-Delta State Manager", "version": "5.5"}SETTINGS = {"theme": "dark", "mobile_optimized": True}
STRATEGY_AGENT_MEMORY = { "strategy_name": "FVG-Delta Crypto Signal Engine", "strategy_version": "5.5", "framework": { "engine": "FastAPI scanner loop", "market_scope": "MEXC UST-M", "timeframe": "15m closed candles only", "stage_order": [0, 1, 2, 3, 4], "stage_rules": { "stage_1": "Qualified setup gate requires valid impulse/FVG, liquidity lock, BoS close, no early invalid behavior.", "stage_2": "Liquidity break-and-close gate; wick-only taps do not qualify.", "stage_3": "First valid FVG interaction context with stale-entry guard.", "stage_4": "Opposite-direction confirmation candle validates executable setup with dynamic SL/TP.", }, }, "alpha_signals": { "signal_family": "Displacement + FVG + liquidity sequencing", "filters": [ "Directional dominance and displacement quality", "Range/body quality thresholds", "Swing-noise suppression", "Alternation cap via IMPULSE_MAX_ALTERNATIONS", ], }, "fvg_detection_logic": { "impulse_context": "Require impulse-driven structure before FVG eligibility.", "bos_anchor_policy": "BoS anchor/level remains immutable once impulse lock is established.", "mitigation_rules": "Early mitigation or premature liquidity tap invalidates pre-BoS sequence.", "entry_guard": "Use STAGE3_ENTRY_BUFFER_ATR to avoid stale entry context.", },}
STRATEGY_USER_MEMORY = { "trading_parameters": { "timeframe": "15m", "stage_progression": "strict", "tp_model": "TP1 half-distance to TP2; TP2 max(structural target, RR target)", "sl_model": "FVG/structure boundary + ATR buffer and risk floors", }, "risk_tolerance": { "risk_floor_formula": "max(structural_risk, MIN_STOP_ATR_MULT*ATR, entry*MIN_STOP_PCT/100)", "avoid_tight_stops": True, }, "execution_rules": { "intrabar_decisions": False, "stage_2_policy": "close-through only", "alert_delivery_stages": [3, 4], },}
STRATEGY_SOUL_MD = """# FVG-Delta State Manager — Soul Directives
## Core MissionPreserve strategy integrity for staged FVG-displacement execution under strict, auditable transitions.
## Behavioral Directives1. 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."""
TEXT_EXTENSIONS = { ".txt", ".md", ".markdown", ".json", ".csv", ".log", ".yaml", ".yml", ".ini", ".cfg", ".py", ".js", ".ts", ".html", ".xml",}
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))
async def _extract_custom_text(custom_file: Optional[UploadFile], custom_text: str) -> tuple[str, str]: text = (custom_text or "").strip() source = "typed text"
if custom_file is None: return text, source
raw = await custom_file.read() filename = custom_file.filename or "uploaded_file" lower_name = filename.lower() source = f"file:{filename}"
if lower_name.endswith(".pdf"): try: reader = PdfReader(io.BytesIO(raw)) extracted = "\n".join((page.extract_text() or "") for page in reader.pages).strip() if extracted: return extracted, source if text: return text, source return "(PDF uploaded; no extractable text found in pages)", source except Exception as exc: raise HTTPException(status_code=400, detail=f"Could not parse PDF: {exc}") from exc
if any(lower_name.endswith(ext) for ext in TEXT_EXTENSIONS): decoded = raw.decode("utf-8", errors="replace").strip() if decoded: return decoded, source if text: return text, source return "(Text file uploaded but empty)", source
# fallback: attempt as generic text for other text-like files decoded = raw.decode("utf-8", errors="replace").strip() if decoded: return decoded, source
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.strip().lower()
if mode == "strategy": tasks = { "active_workflows": [ { "workflow": "Stage 3 trade monitoring", "state": "active", "tracking": "FVG interaction context with stale-entry guard", }, { "workflow": "Stage 4 trade monitoring", "state": "active", "tracking": "confirmation-validated setups with dynamic SL/TP lifecycle", }, ], "generated_at_utc": datetime.now(timezone.utc).isoformat(), } return STRATEGY_AGENT_MEMORY, STRATEGY_USER_MEMORY, STRATEGY_SOUL_MD, tasks
if mode == "clean": agent_memory = { "profile": "plain_clean", "description": "Generic migration profile without strategy-specific memory.", "generated_at_utc": datetime.now(timezone.utc).isoformat(), } user_memory = { "preferences": { "mode": "clean", "notes": "No strategy-specific assumptions included.", } } soul = "# Agent Soul\n\nNeutral clean migration profile." tasks = { "active_workflows": [], "generated_at_utc": datetime.now(timezone.utc).isoformat(), } return agent_memory, user_memory, soul, tasks
if mode == "custom": if not custom_memory_text.strip(): raise HTTPException( status_code=400, detail="Custom mode selected but no custom text/file content was provided.", )
agent_memory = { "profile": "custom_imported_memory", "source": custom_source, "custom_memory": custom_memory_text, } user_memory = { "profile": "custom_imported_memory", "source": custom_source, "custom_memory": custom_memory_text, } soul = ( "# Custom Soul Input\n\n" f"Source: {custom_source}\n\n" "## Imported Content\n\n" f"{custom_memory_text}" ) tasks = { "active_workflows": [ { "workflow": "Custom memory migration", "state": "active", "tracking": custom_source, } ], "generated_at_utc": datetime.now(timezone.utc).isoformat(), } 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[str, str], custom_memory_text: str, custom_source: str,) -> bytes: agent_memory, user_memory, soul_md, tasks = _build_mode_payload( memory_mode=memory_mode, custom_memory_text=custom_memory_text, custom_source=custom_source, )
buffer = io.BytesIO() with tarfile.open(mode="w:gz", fileobj=buffer) as tar: _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_handoff_prompt(code: str, download_token: str, memory_mode: str, include_env_keys: bool) -> str: mode = memory_mode.strip().lower() mode_line = { "strategy": "- Mode: strategy memory (FVG profile) included.", "clean": "- Mode: plain clean memory included.", "custom": "- Mode: custom uploaded/typed memory included.", }.get(mode, "- Mode: unknown")
env_line = ( "- Env key values embedded in bundle." if include_env_keys else "- Env key values left empty." )
return ( "---\n" "Tell the user to paste the following prompt into Starchild:\n\n" "Now paste the following prompt to Starchild:\n" "┌──────────────────────────────────────────────────────────────────┐\n" "Please import my migration bundle.\n" f"Code: {code}\n" f"Download token: {download_token}\n" "Run full import via the agent-import skill.\n" "└──────────────────────────────────────────────────────────────────┘\n" "---\n\n" "Checklist:\n" "- Exported: manifest, memory, identity, user settings, tasks, env key schema.\n" f"{mode_line}\n" f"{env_line}\n" "- Bundle root layout: migration/* (no nested migration/migration)." )
@app.get("/", response_class=HTMLResponse)async def index() -> str: return """<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\" /> <title>FVG-Delta Migration Token Dashboard</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;600;700;800&display=swap\" rel=\"stylesheet\" /> <style> :root { --bg:#0d1117; --panel:#121826; --line:#1e2a3d; --txt:#e6edf3; --muted:#94a3b8; --cyan:#00f2fe; --green:#00e676; --danger:#ff4d6d; } * { box-sizing:border-box; } body { margin:0; font-family:'Nunito',sans-serif; background:radial-gradient(circle at top right, rgba(0,242,254,.14), transparent 40%), var(--bg); color:var(--txt); min-height:100dvh; display:flex; align-items:center; justify-content:center; padding:16px; } .wrap { width:min(980px,100%); background:linear-gradient(180deg, rgba(18,24,38,.95), rgba(13,17,23,.97)); border:1px solid var(--line); border-radius:16px; padding:20px; box-shadow:0 20px 60px rgba(0,0,0,.4); } h1 { margin:0 0 8px; font-size:1.4rem; } p { margin:0 0 14px; color:var(--muted); } .grid { display:grid; gap:10px; margin-bottom:12px; } .label { color:#cbd5e1; font-weight:700; display:block; margin-bottom:4px; } .field, select, textarea.input { width:100%; border:1px solid var(--line); background:#0b1220; color:#dbeafe; border-radius:10px; padding:10px; } .btn { width:100%; border:1px solid transparent; border-radius:12px; padding:12px 14px; font-size:1rem; font-weight:800; cursor:pointer; color:#00151a; background:linear-gradient(90deg,var(--cyan),#7af7ff); } .btn:disabled { opacity:.7; cursor:not-allowed; } .spinner { width:16px; height:16px; border:2px solid rgba(0,21,26,.2); border-top-color:rgba(0,21,26,.9); border-radius:50%; display:inline-block; vertical-align:middle; margin-right:8px; animation:spin .8s linear infinite; } @keyframes spin { to { transform:rotate(360deg); } } textarea#output { width:100%; margin-top:14px; min-height:260px; border-radius:12px; border:1px solid var(--line); background:#0b1220; color:#dbeafe; padding:12px; font-size:.94rem; line-height:1.5; resize:vertical; } .copy-row { margin-top:10px; display:flex; gap:10px; align-items:center; flex-wrap:wrap; } .btn-copy { border:1px solid var(--line); border-radius:10px; color:var(--txt); background:#111a2b; font-weight:700; padding:10px 14px; cursor:pointer; } .badge { display:none; background:rgba(0,230,118,.16); color:var(--green); border:1px solid rgba(0,230,118,.35); border-radius:999px; padding:6px 10px; font-weight:700; font-size:.85rem; } .badge.show { display:inline-block; } .error { color:var(--danger); margin-top:8px; min-height:1.2em; } </style></head><body> <main class=\"wrap\"> <h1>FVG-Delta State Migration Handoff</h1> <p>Generate a deterministic in-memory migration bundle and get a live import code/token.</p>
<div class=\"grid\"> <div> <label class=\"label\" for=\"memoryMode\">Memory Mode</label> <select id=\"memoryMode\" class=\"field\"> <option value=\"strategy\" selected>Strategy MEMORY.md profile</option> <option value=\"clean\">Plain clean memory</option> <option value=\"custom\">Custom memory (text or file)</option> </select> </div>
<div id=\"customPanel\" style=\"display:none;\"> <label class=\"label\" for=\"customText\">Custom Text (optional if file is uploaded)</label> <textarea id=\"customText\" class=\"input\" rows=\"6\" placeholder=\"Paste custom memory text here...\"></textarea> <label class=\"label\" for=\"customFile\" style=\"margin-top:8px;\">Upload custom file (.md, .txt, .pdf, and text-related formats)</label> <input id=\"customFile\" class=\"field\" type=\"file\" accept=\".md,.txt,.pdf,.json,.csv,.log,.yaml,.yml,.ini,.cfg,.py,.js,.ts,.html,.xml\" /> </div>
<label style=\"display:flex; gap:8px; align-items:center; color:#cbd5e1; font-weight:700;\"> <input id=\"includeEnv\" type=\"checkbox\" /> Include environment key values in bundle </label>
<div id=\"envFields\" style=\"display:none; gap:8px; grid-template-columns:1fr;\"> <input id=\"starchildKey\" type=\"password\" class=\"field\" placeholder=\"STARCHILD_API_KEY (optional override)\" /> <input id=\"migrationToken\" type=\"password\" class=\"field\" placeholder=\"AGENT_MIGRATION_TOKEN (optional override)\" /> </div> </div>
<button id=\"generateBtn\" class=\"btn\">Generate New Token</button> <textarea id=\"output\" readonly placeholder=\"Generated handoff prompt will appear here...\"></textarea>
<div class=\"copy-row\"> <button id=\"copyBtn\" class=\"btn-copy\">Copy to Clipboard</button> <span id=\"copiedBadge\" class=\"badge\">Copied!</span> </div>
<div id=\"errorBox\" class=\"error\"></div> </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 copyBtn = document.getElementById('copyBtn'); const output = document.getElementById('output'); const copiedBadge = document.getElementById('copiedBadge'); const errorBox = document.getElementById('errorBox');
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 showCopiedBadge() { copiedBadge.classList.add('show'); setTimeout(() => copiedBadge.classList.remove('show'), 1400); }
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); }
generateBtn.addEventListener('click', async () => { errorBox.textContent = ''; generateBtn.disabled = true; generateBtn.innerHTML = '<span class="spinner"></span>Generating...';
try { const formData = new FormData(); formData.append('memory_mode', memoryMode.value); formData.append('include_env_keys', includeEnv.checked ? 'true' : 'false'); formData.append('starchild_api_key', includeEnv.checked ? starchildKey.value : ''); formData.append('agent_migration_token', includeEnv.checked ? migrationToken.value : ''); formData.append('custom_text', customText.value || ''); if (customFile.files && customFile.files[0]) { formData.append('custom_file', customFile.files[0]); }
const res = await fetch('/api/generate', { method: 'POST', body: formData }); const data = await res.json(); if (!res.ok) throw new Error(data.detail || 'Generation failed.'); output.value = data.prompt || ''; } catch (err) { errorBox.textContent = err.message || 'Unable to generate token.'; } finally { generateBtn.disabled = false; generateBtn.textContent = 'Generate New Token'; } });
copyBtn.addEventListener('click', async () => { const text = output.value.trim(); if (!text) { errorBox.textContent = 'Nothing to copy yet. Generate a token first.'; return; } errorBox.textContent = ''; try { await copyText(text); showCopiedBadge(); } catch { errorBox.textContent = 'Clipboard failed on this browser.'; } }); </script></body></html>"""
@app.post("/api/generate")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 = 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, )
try: async with httpx.AsyncClient(timeout=35.0) as client: relay_response = await client.post( "https://sc-agent-migration.fly.dev/paste", content=bundle_bytes, headers={"Content-Type": "application/octet-stream"}, ) 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.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 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")
prompt = build_handoff_prompt( code=str(code), download_token=str(download_token), memory_mode=memory_mode, include_env_keys=include_env, )
return JSONResponse( { "prompt": prompt, "code": code, "download_token": download_token, "memory_mode": memory_mode, } )12345fastapi==0.116.1uvicorn[standard]==0.35.0httpx==0.28.1python-multipart==0.0.20pypdf==5.9.0DockerfileAdded+16
app.pyAdded+552
requirements.txtAdded+5