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 = """
A.I Agent State Migration Handoff
Agent Migration Relay
A.I Agent State Migration Handoff
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.
Choose what gets packed into your migration memory.
Bundle Checklist
Run A Generation To See Active Items
Paste The Following Prompt To Starchild / Agent:
Copied!
"""
@app.get("/", response_class=HTMLResponse)
async def index() -> str:
return INDEX_HTML
@app.get("/health")
async def health() -> JSONResponse:
return JSONResponse({"status": "ok"})
@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, 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,
}
)