File size: 29,682 Bytes
c8524a3
650843d
 
 
 
 
 
 
 
 
 
 
 
c8524a3
 
 
 
650843d
 
c8524a3
 
 
 
 
 
650843d
 
c8524a3
 
 
 
 
 
650843d
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
c8524a3
 
 
650843d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8524a3
 
 
 
 
650843d
c8524a3
 
 
 
 
 
 
650843d
 
c8524a3
 
 
 
 
 
 
 
650843d
c8524a3
 
650843d
 
 
 
 
c8524a3
 
 
 
 
 
 
 
650843d
 
c8524a3
 
 
 
650843d
c8524a3
 
 
 
 
650843d
 
 
 
 
 
 
 
c8524a3
650843d
 
c8524a3
650843d
 
 
c8524a3
650843d
 
 
 
 
c8524a3
650843d
c8524a3
 
650843d
 
 
 
 
 
c8524a3
 
 
 
 
 
 
 
650843d
 
 
 
 
c8524a3
 
650843d
 
c8524a3
650843d
 
 
 
 
 
 
 
 
 
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
c8524a3
 
 
 
 
 
650843d
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
c8524a3
650843d
 
c8524a3
 
 
 
 
 
650843d
 
c8524a3
 
 
 
 
 
 
 
 
 
650843d
 
c8524a3
 
 
650843d
c8524a3
650843d
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
 
 
 
 
 
 
 
 
 
c8524a3
 
 
 
650843d
 
c8524a3
 
 
650843d
 
 
 
 
 
 
 
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
 
c8524a3
650843d
c8524a3
 
 
 
 
 
 
 
 
 
 
 
650843d
c8524a3
650843d
c8524a3
 
 
 
650843d
 
 
c8524a3
 
 
650843d
 
 
c8524a3
 
 
 
 
650843d
 
 
 
 
 
 
 
c8524a3
 
 
 
 
 
 
 
 
 
650843d
 
 
 
 
 
 
 
 
 
 
c8524a3
650843d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8524a3
650843d
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
 
c8524a3
 
 
 
 
 
 
 
 
 
 
 
 
 
650843d
 
 
 
 
 
 
 
 
c8524a3
650843d
 
 
 
c8524a3
650843d
c8524a3
 
650843d
 
 
 
 
c8524a3
 
 
 
650843d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
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>
"""


@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,
        }
    )