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
 
 
 
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
"""
OMNI Cortex β€” Cybernetic God Edition (v5.1, driver-aligned)
============================================================

This Space implements the **exact** wire contract that
omni/core/cortex_driver.py expects:

    POST /llm           {prompt, model?, temperature?, max_tokens?, system?}
                        -> {text, ...receipt}
    POST /embed         {text}                                -> {vector:[...]}
    POST /similar       {text|vector, top_k}                  -> {hits:[{id,score,text,meta}]}
    POST /score         {text, dimensions}                    -> {dim:float, ..., _rationale:"…"}
    POST /memory/store  {key, text, meta}                     -> {id}
    POST /memory/recall {query, top_k}                        -> {hits:[…]}
    GET  /healthz                                             -> 200

Auth: optional `Authorization: Bearer <CORTEX_API_KEY>`.

Bonus endpoints (not part of driver contract β€” used by /radar consumers):
    WS   /radar                          – realtime ModelCallReceipt fan-out
    GET  /radar/receipts?limit=N         – ring-buffer dump

Architecture
------------
1.  Cost-ascending provider waterfall: Groq β†’ Together β†’ OpenRouter β†’
    OpenAI β†’ Anthropic β†’ HF Inference. Every call yields a
    ModelCallReceipt that fans out to /radar and is retained in a
    512-deep ring.
2.  Qdrant memory with in-process LRU fallback so the Space boots
    without any secrets configured.
3.  /score forces the LLM into Chain-of-Thought reasoning: the system
    prompt requires a `"_rationale"` string with explicit deduction
    BEFORE any numeric dimension scores are emitted. The driver's
    `score()` helper filters non-numeric keys, so `_rationale` is
    invisible to callers but auditable on /radar.
"""

from __future__ import annotations

import asyncio
import hashlib
import json
import logging
import math
import os
import time
import uuid
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable, Deque, Dict, List, Optional, Tuple

import httpx
from fastapi import (Body, Depends, FastAPI, Header, HTTPException, Query,
                     WebSocket, WebSocketDisconnect)
from pydantic import BaseModel, ConfigDict, Field

# ════════════════════════════════════════════════════════════════════════
#                              CONFIG
# ════════════════════════════════════════════════════════════════════════

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(levelname)s %(name)s :: %(message)s")
log = logging.getLogger("cortex")

CORTEX_API_KEY      = os.environ.get("CORTEX_API_KEY",
                                     os.environ.get("CORTEX_TOKEN", ""))
CORTEX_PORT         = int(os.environ.get("PORT",
                                         os.environ.get("CORTEX_PORT", "7860")))

# providers
OPENAI_API_KEY      = os.environ.get("OPENAI_API_KEY", "")
ANTHROPIC_API_KEY   = os.environ.get("ANTHROPIC_API_KEY", "")
OPENROUTER_API_KEY  = os.environ.get("OPENROUTER_API_KEY", "")
TOGETHER_API_KEY    = os.environ.get("TOGETHER_API_KEY", "")
GROQ_API_KEY        = os.environ.get("GROQ_API_KEY", "")
HF_TOKEN            = os.environ.get("HF_TOKEN", "")

# qdrant
QDRANT_URL          = os.environ.get("QDRANT_URL", "")
QDRANT_API_KEY      = os.environ.get("QDRANT_API_KEY", "")
QDRANT_COLLECTION   = os.environ.get("QDRANT_COLLECTION", "omni_memory")
QDRANT_VECTOR_SIZE  = int(os.environ.get("QDRANT_VECTOR_SIZE", "384"))

# embedding endpoint (HF inference compatible)
EMBED_ENDPOINT      = os.environ.get("EMBED_ENDPOINT",
                                     "https://api-inference.huggingface.co/models/"
                                     "sentence-transformers/all-MiniLM-L6-v2")

REQUEST_TIMEOUT     = float(os.environ.get("CORTEX_TIMEOUT", "60"))
RADAR_QUEUE_MAX     = int(os.environ.get("CORTEX_RADAR_QUEUE", "256"))
RECEIPT_RING        = int(os.environ.get("CORTEX_RECEIPT_RING", "512"))

DEFAULT_MODEL_CLASS = os.environ.get("CORTEX_DEFAULT_CLASS", "balanced")


# ════════════════════════════════════════════════════════════════════════
#                              SCHEMAS
# ════════════════════════════════════════════════════════════════════════

class LLMRequest(BaseModel):
    """Public /llm request β€” driver-aligned. Extra fields are accepted but
    optional so that internal callers (Forge) can pass system + routing hints
    without breaking the driver contract."""
    model_config = ConfigDict(protected_namespaces=())
    prompt:        str
    model:         Optional[str] = None
    temperature:   float = 0.7
    max_tokens:    int = 2048
    # extras (Forge uses these; driver does not)
    system:        Optional[str] = None
    model_class:   str = Field(default=DEFAULT_MODEL_CLASS,
                               description="cheap | balanced | premium | reasoning")
    json_mode:     bool = False
    intent:        Optional[str] = None
    tags:          List[str] = Field(default_factory=list)
    request_id:    Optional[str] = None


class LLMResponse(BaseModel):
    text:         str = ""
    provider:     str = ""
    model:        str = ""
    cost_score:   float = 0.0
    latency_ms:   float = 0.0
    request_id:   str = ""
    receipt_id:   str = ""
    fallbacks:    List[str] = Field(default_factory=list)
    ok:           bool = True
    error:        Optional[str] = None


class EmbedRequest(BaseModel):
    text:   str


class SimilarRequest(BaseModel):
    text:   Optional[str] = None
    vector: Optional[List[float]] = None
    top_k:  int = 5
    namespace: str = "default"
    filters:   Dict[str, Any] = Field(default_factory=dict)


class ScoreRequest(BaseModel):
    model_config = ConfigDict(protected_namespaces=())
    text:        str
    dimensions:  List[str]
    model_class: str = "balanced"


class MemoryStoreRequest(BaseModel):
    key:   str
    text:  str
    meta:  Dict[str, Any] = Field(default_factory=dict)
    namespace: str = "default"


class MemoryRecallRequest(BaseModel):
    query:     str
    top_k:     int = 5
    namespace: str = "default"
    filters:   Dict[str, Any] = Field(default_factory=dict)


# ════════════════════════════════════════════════════════════════════════
#                       PROVIDER ROUTER (waterfall)
# ════════════════════════════════════════════════════════════════════════

@dataclass
class Provider:
    name:        str
    enabled:     bool
    cost_score:  float
    classes:     Tuple[str, ...]
    model_for:   Dict[str, str]
    impl:        Callable[..., Awaitable[Tuple[str, str]]]


_HTTP: Optional[httpx.AsyncClient] = None
def _http() -> httpx.AsyncClient:
    global _HTTP
    if _HTTP is None:
        _HTTP = httpx.AsyncClient(timeout=REQUEST_TIMEOUT,
                                  headers={"User-Agent": "OMNI-Cortex/5.1"})
    return _HTTP


# ─────────────────────────── OpenAI compatible ──────────────────────────
async def _openai_compat_call(base_url: str, api_key: str, model: str,
                              prompt: str, system: Optional[str],
                              max_tokens: int, temperature: float,
                              json_mode: bool) -> Tuple[str, str]:
    msgs = []
    if system:
        msgs.append({"role": "system", "content": system})
    msgs.append({"role": "user", "content": prompt})
    body: Dict[str, Any] = {
        "model": model, "messages": msgs,
        "max_tokens": max_tokens, "temperature": temperature,
    }
    if json_mode:
        body["response_format"] = {"type": "json_object"}
    r = await _http().post(f"{base_url}/chat/completions",
                           json=body,
                           headers={"Authorization": f"Bearer {api_key}"})
    r.raise_for_status()
    j = r.json()
    return j["choices"][0]["message"]["content"], model


async def call_openai(model: str, **kw) -> Tuple[str, str]:
    return await _openai_compat_call("https://api.openai.com/v1",
                                     OPENAI_API_KEY, model, **kw)

async def call_openrouter(model: str, **kw) -> Tuple[str, str]:
    return await _openai_compat_call("https://openrouter.ai/api/v1",
                                     OPENROUTER_API_KEY, model, **kw)

async def call_together(model: str, **kw) -> Tuple[str, str]:
    return await _openai_compat_call("https://api.together.xyz/v1",
                                     TOGETHER_API_KEY, model, **kw)

async def call_groq(model: str, **kw) -> Tuple[str, str]:
    return await _openai_compat_call("https://api.groq.com/openai/v1",
                                     GROQ_API_KEY, model, **kw)


# ─────────────────────────── Anthropic (native) ─────────────────────────
async def call_anthropic(model: str, *, prompt: str, system: Optional[str],
                         max_tokens: int, temperature: float,
                         json_mode: bool) -> Tuple[str, str]:
    body: Dict[str, Any] = {
        "model":       model,
        "max_tokens":  max_tokens,
        "temperature": temperature,
        "messages":    [{"role": "user", "content": prompt}],
    }
    if system:
        body["system"] = system
    if json_mode:
        body["system"] = (body.get("system", "") +
                          "\n\nRespond with a single valid JSON object only. "
                          "No prose, no markdown fences.").strip()
    r = await _http().post("https://api.anthropic.com/v1/messages",
                           json=body,
                           headers={
                               "x-api-key":         ANTHROPIC_API_KEY,
                               "anthropic-version": "2023-06-01",
                               "content-type":      "application/json",
                           })
    r.raise_for_status()
    j = r.json()
    parts = j.get("content", [])
    text  = "".join(p.get("text", "") for p in parts if p.get("type") == "text")
    return text, model


# ─────────────────────────── HF Inference (free) ────────────────────────
async def call_hf(model: str, *, prompt: str, system: Optional[str],
                  max_tokens: int, temperature: float,
                  json_mode: bool) -> Tuple[str, str]:
    headers = {}
    if HF_TOKEN:
        headers["Authorization"] = f"Bearer {HF_TOKEN}"
    full = (f"<|system|>\n{system}\n<|user|>\n{prompt}\n<|assistant|>\n"
            if system else prompt)
    r = await _http().post(
        f"https://api-inference.huggingface.co/models/{model}",
        headers=headers,
        json={"inputs": full,
              "parameters": {"max_new_tokens": max_tokens,
                             "temperature":   temperature,
                             "return_full_text": False}})
    r.raise_for_status()
    j = r.json()
    if isinstance(j, list) and j and "generated_text" in j[0]:
        return j[0]["generated_text"], model
    if isinstance(j, dict) and "generated_text" in j:
        return j["generated_text"], model
    return json.dumps(j)[:4000], model


# ─────────────────────────── PROVIDERS table ────────────────────────────
PROVIDERS: Dict[str, Provider] = {}

API_KEY_DEEPSEEK = os.environ.get("API_KEY_DEEPSEEK", "")

async def call_deepseek(model: str, **kw) -> Tuple[str, str]:
    """Native DeepSeek API Client"""
    return await _openai_compat_call("https://api.deepseek.com/v1",
                                     API_KEY_DEEPSEEK, model, **kw)

def _register_providers() -> None:
    PROVIDERS.clear()

    # 1. NATIVE DEEPSEEK V4 (Absolute Priority - Cost Score 0.01)
    if API_KEY_DEEPSEEK:
        PROVIDERS["deepseek"] = Provider(
            name="deepseek", enabled=True, cost_score=0.01,
            classes=("cheap", "balanced", "premium", "reasoning"),
            model_for={
                "cheap":     "deepseek-v4-flash",
                "balanced":  "deepseek-v4-pro",
                "premium":   "deepseek-v4-pro",
                "reasoning": "deepseek-v4-pro",
            },
            impl=call_deepseek,
        )

    # 2. GROQ
    if GROQ_API_KEY:
        PROVIDERS["groq"] = Provider(
            name="groq", enabled=True, cost_score=0.05,
            classes=("cheap", "balanced"),
            model_for={
                "cheap":    "llama-3.1-8b-instant",
                "balanced": "llama-3.3-70b-versatile",
            },
            impl=call_groq,
        )

    # 3. TOGETHER
    if TOGETHER_API_KEY:
        PROVIDERS["together"] = Provider(
            name="together", enabled=True, cost_score=0.10,
            classes=("cheap", "balanced", "reasoning"),
            model_for={
                "cheap":     "meta-llama/Llama-3.1-8B-Instruct-Turbo",
                "balanced":  "meta-llama/Llama-3.3-70B-Instruct-Turbo",
                "reasoning": "Qwen/Qwen2.5-72B-Instruct-Turbo",
            },
            impl=call_together,
        )

    # 4. OPENROUTER (With Free Vision Added)
    if OPENROUTER_API_KEY:
        PROVIDERS["openrouter"] = Provider(
            name="openrouter", enabled=True, cost_score=0.20,
            classes=("cheap", "balanced", "premium", "reasoning", "vision"),
            model_for={
                "cheap":     "meta-llama/llama-3.3-70b-instruct:free",
                "balanced":  "anthropic/claude-3.5-haiku",
                "premium":   "anthropic/claude-sonnet-4.5",
                "reasoning": "openai/o4-mini",
                "vision":    "qwen/qwen2.5-vl-72b-instruct:free",
            },
            impl=call_openrouter,
        )

    # 5. OPENAI
    if OPENAI_API_KEY:
        PROVIDERS["openai"] = Provider(
            name="openai", enabled=True, cost_score=0.50,
            classes=("balanced", "premium", "reasoning"),
            model_for={
                "balanced":  "gpt-4o-mini",
                "premium":   "gpt-4o",
                "reasoning": "o4-mini",
            },
            impl=call_openai,
        )

    # 6. ANTHROPIC
    if ANTHROPIC_API_KEY:
        PROVIDERS["anthropic"] = Provider(
            name="anthropic", enabled=True, cost_score=0.55,
            classes=("balanced", "premium", "reasoning"),
            model_for={
                "balanced":  "claude-haiku-4-5-20251001",
                "premium":   "claude-sonnet-4-6",
                "reasoning": "claude-opus-4-6",
            },
            impl=call_anthropic,
        )

    # 7. HF INFERENCE (100% Free Fallback)
    PROVIDERS["hf"] = Provider(
        name="hf", enabled=True, cost_score=0.99,
        classes=("cheap", "balanced", "premium", "reasoning"),
        model_for={
            "cheap":     "mistralai/Mistral-7B-Instruct-v0.3",
            "balanced":  "meta-llama/Meta-Llama-3-8B-Instruct",
            "premium":   "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
            "reasoning": "Qwen/Qwen2.5-7B-Instruct",
        },
        impl=call_hf,
    )


def _route(model_class: str, *, explicit_model: Optional[str] = None
           ) -> List[Tuple[Provider, str]]:
    """Return [(provider, model_to_use)] sorted by cost_score asc."""
    
    # ── OMEGA FIX: ANNIHILATE HARDCODED MODELS ──
    # Forge aggressively requests paid models like Claude explicitly. 
    # We intercept and destroy those explicit requests so Forge is FORCED
    # to fall into our cost-ascending DeepSeek / Free-Tier waterfall.
    explicit_model = None 

    cands = [p for p in PROVIDERS.values() if p.enabled]
    out = []
    
    # Map the requested class (e.g. "reasoning") to our configured waterfall models
    for p in cands:
        if model_class in p.classes:
            model = p.model_for.get(model_class)
            if model:
                out.append((p, model))
                
    # If no class matches perfectly, aggressively fall back to ANY available model
    if not out:
        for p in cands:
            for cls in ("balanced", "premium", "reasoning", "cheap"):
                if cls in p.model_for:
                    out.append((p, p.model_for[cls]))
                    break
                    
    # Sort strictly by the cost scores we assigned (OpenRouter/DeepSeek first)
    out.sort(key=lambda t: t[0].cost_score)
    return out


# ════════════════════════════════════════════════════════════════════════
#                       /radar β€” receipts + broadcast
# ════════════════════════════════════════════════════════════════════════

@dataclass
class ModelCallReceipt:
    receipt_id:   str
    request_id:   str
    provider:     str
    model:        str
    model_class:  str
    cost_score:   float
    latency_ms:   float
    ok:           bool
    error:        Optional[str]
    intent:       Optional[str]
    tags:         List[str]
    ts:           float = field(default_factory=time.time)

    def to_event(self) -> Dict[str, Any]:
        return {"type": "model_call", **self.__dict__}


class RadarHub:
    def __init__(self) -> None:
        self.clients: List[WebSocket] = []
        self.queue:   asyncio.Queue   = asyncio.Queue(maxsize=RADAR_QUEUE_MAX)
        self.receipts: Deque[ModelCallReceipt] = deque(maxlen=RECEIPT_RING)
        self._loop_task: Optional[asyncio.Task] = None

    async def start(self) -> None:
        if self._loop_task is None or self._loop_task.done():
            self._loop_task = asyncio.create_task(self._loop())

    async def _loop(self) -> None:
        while True:
            ev = await self.queue.get()
            data = json.dumps(ev, default=str)
            dead: List[WebSocket] = []
            for ws in self.clients:
                try:    await ws.send_text(data)
                except Exception: dead.append(ws)
            for ws in dead:
                try: self.clients.remove(ws)
                except ValueError: pass

    async def emit(self, ev: Dict[str, Any]) -> None:
        try: self.queue.put_nowait(ev)
        except asyncio.QueueFull:
            try:    self.queue.get_nowait()
            except Exception: pass
            try:    self.queue.put_nowait(ev)
            except Exception: pass

    async def attach(self, ws: WebSocket) -> None:
        await ws.accept()
        self.clients.append(ws)
        for r in list(self.receipts)[-32:]:
            try: await ws.send_text(json.dumps(r.to_event(), default=str))
            except Exception: pass

    def detach(self, ws: WebSocket) -> None:
        try: self.clients.remove(ws)
        except ValueError: pass

    def remember_receipt(self, r: ModelCallReceipt) -> None:
        self.receipts.append(r)


radar = RadarHub()


# ════════════════════════════════════════════════════════════════════════
#                              EMBEDDINGS
# ════════════════════════════════════════════════════════════════════════

async def embed_text(text: str) -> List[float]:
    """HF inference if HF_TOKEN, deterministic SHA-512 hash fallback."""
    if HF_TOKEN and EMBED_ENDPOINT:
        try:
            r = await _http().post(
                EMBED_ENDPOINT,
                headers={"Authorization": f"Bearer {HF_TOKEN}"},
                json={"inputs": text})
            if r.status_code == 200:
                j = r.json()
                if isinstance(j, list) and j and isinstance(j[0], (int, float)):
                    return [float(x) for x in j][:QDRANT_VECTOR_SIZE]
                if isinstance(j, list) and j and isinstance(j[0], list):
                    return [float(x) for x in j[0]][:QDRANT_VECTOR_SIZE]
        except Exception as e:
            log.debug("embed.hf.fail err=%s", e)
    h = hashlib.sha512(text.encode("utf-8")).digest()
    vec: List[float] = []
    for i in range(QDRANT_VECTOR_SIZE):
        b = h[i % len(h)]
        vec.append(((b / 255.0) * 2.0) - 1.0)
    n = math.sqrt(sum(v * v for v in vec)) or 1.0
    return [v / n for v in vec]


# ════════════════════════════════════════════════════════════════════════
#                       MEMORY β€” Qdrant + fallback
# ════════════════════════════════════════════════════════════════════════

class MemoryStore:
    def __init__(self) -> None:
        self.url      = QDRANT_URL.rstrip("/") if QDRANT_URL else ""
        self.headers  = {"api-key": QDRANT_API_KEY} if QDRANT_API_KEY else {}
        self.local: Dict[str, Dict[str, Any]] = {}
        self._collection_ready = False

    async def init(self) -> None:
        if not self.url:
            log.warning("memory.no_qdrant β€” using in-process store")
            return
        try:
            r = await _http().get(
                f"{self.url}/collections/{QDRANT_COLLECTION}",
                headers=self.headers)
            if r.status_code == 404:
                await _http().put(
                    f"{self.url}/collections/{QDRANT_COLLECTION}",
                    headers=self.headers,
                    json={"vectors": {"size": QDRANT_VECTOR_SIZE,
                                      "distance": "Cosine"}})
            self._collection_ready = True
            log.info("memory.qdrant.ready collection=%s", QDRANT_COLLECTION)
        except Exception as e:
            log.warning("memory.qdrant.init.fail err=%s β€” fallback", e)

    @staticmethod
    def _point_id(ns: str, key: str) -> int:
        return abs(int(hashlib.sha1(f"{ns}:{key}".encode()).hexdigest()[:15], 16))

    async def upsert(self, key: str, text: str, meta: Dict[str, Any],
                     namespace: str) -> Dict[str, Any]:
        vec = await embed_text(text)
        payload = {**meta, "key": key, "text": text, "ns": namespace,
                   "ts": time.time()}
        pid = self._point_id(namespace, key)
        if self._collection_ready:
            try:
                r = await _http().put(
                    f"{self.url}/collections/{QDRANT_COLLECTION}/points",
                    headers=self.headers,
                    json={"points": [{"id": pid, "vector": vec, "payload": payload}]})
                r.raise_for_status()
                return {"ok": True, "id": str(pid), "store": "qdrant"}
            except Exception as e:
                log.warning("memory.upsert.qdrant.fail key=%s err=%s", key, e)
        self.local[f"{namespace}:{key}"] = {"id": pid, "vector": vec, "payload": payload}
        return {"ok": True, "id": str(pid), "store": "local"}

    async def search(self, *, vector: Optional[List[float]] = None,
                     query: Optional[str] = None,
                     top_k: int = 5,
                     namespace: str = "default",
                     filters: Optional[Dict[str, Any]] = None
                     ) -> List[Dict[str, Any]]:
        if vector is None:
            if not query:
                return []
            vector = await embed_text(query)
        flt: Dict[str, Any] = {"must": [{"key": "ns", "match": {"value": namespace}}]}
        for k, v in (filters or {}).items():
            flt["must"].append({"key": k, "match": {"value": v}})
        if self._collection_ready:
            try:
                r = await _http().post(
                    f"{self.url}/collections/{QDRANT_COLLECTION}/points/search",
                    headers=self.headers,
                    json={"vector": vector, "limit": top_k,
                          "filter": flt, "with_payload": True})
                r.raise_for_status()
                hits = r.json().get("result", [])
                return [{"id":   str(h.get("id", "")),
                         "score": float(h.get("score", 0.0)),
                         "text":  (h.get("payload") or {}).get("text", ""),
                         "meta":  {k: v for k, v in (h.get("payload") or {}).items()
                                   if k not in ("text",)}}
                        for h in hits]
            except Exception as e:
                log.warning("memory.search.qdrant.fail err=%s", e)
        # local cosine
        def cosine(a: List[float], b: List[float]) -> float:
            return sum(x * y for x, y in zip(a, b))
        scored = []
        for k, p in self.local.items():
            if not k.startswith(f"{namespace}:"): continue
            payload = p["payload"]
            if filters and not all(payload.get(fk) == fv
                                   for fk, fv in (filters or {}).items()):
                continue
            scored.append((cosine(vector, p["vector"]), p))
        scored.sort(key=lambda t: -t[0])
        return [{"id":    str(p["id"]),
                 "score": float(s),
                 "text":  p["payload"].get("text", ""),
                 "meta":  {k: v for k, v in p["payload"].items()
                           if k not in ("text",)}}
                for s, p in scored[:top_k]]


memory = MemoryStore()


# ════════════════════════════════════════════════════════════════════════
#                              /llm β€” router
# ════════════════════════════════════════════════════════════════════════

async def _provider_call(p: Provider, model: str, req: LLMRequest) -> Tuple[str, str]:
    return await p.impl(model,
                        prompt=req.prompt,
                        system=req.system,
                        max_tokens=req.max_tokens,
                        temperature=req.temperature,
                        json_mode=req.json_mode)


async def llm(req: LLMRequest) -> LLMResponse:
    rid = req.request_id or uuid.uuid4().hex
    cands = _route(req.model_class, explicit_model=req.model)
    if not cands:
        return LLMResponse(ok=False, request_id=rid,
                           error=f"no provider for class={req.model_class} model={req.model}",
                           receipt_id=uuid.uuid4().hex)
    fallbacks: List[str] = []
    last_err: Optional[str] = None
    for p, model in cands:
        t0 = time.perf_counter()
        try:
            text, model_used = await asyncio.wait_for(
                _provider_call(p, model, req), timeout=REQUEST_TIMEOUT)
            ms = (time.perf_counter() - t0) * 1000.0
            r = ModelCallReceipt(
                receipt_id=uuid.uuid4().hex, request_id=rid,
                provider=p.name, model=model_used,
                model_class=req.model_class, cost_score=p.cost_score,
                latency_ms=ms, ok=True, error=None,
                intent=req.intent, tags=req.tags)
            radar.remember_receipt(r)
            await radar.emit(r.to_event())
            return LLMResponse(
                ok=True, text=text, provider=p.name, model=model_used,
                cost_score=p.cost_score, latency_ms=ms,
                request_id=rid, receipt_id=r.receipt_id,
                fallbacks=fallbacks)
        except Exception as e:
            ms = (time.perf_counter() - t0) * 1000.0
            err = f"{type(e).__name__}: {str(e)[:200]}"
            log.warning("llm.fail provider=%s model=%s err=%s", p.name, model, err)
            r = ModelCallReceipt(
                receipt_id=uuid.uuid4().hex, request_id=rid,
                provider=p.name, model=model,
                model_class=req.model_class, cost_score=p.cost_score,
                latency_ms=ms, ok=False, error=err,
                intent=req.intent, tags=req.tags)
            radar.remember_receipt(r)
            await radar.emit(r.to_event())
            fallbacks.append(p.name)
            last_err = err
            continue
    return LLMResponse(ok=False, request_id=rid,
                       error=last_err or "all providers exhausted",
                       receipt_id=uuid.uuid4().hex,
                       fallbacks=fallbacks)


# ════════════════════════════════════════════════════════════════════════
#                  /score β€” Chain-of-Thought scoring
# ════════════════════════════════════════════════════════════════════════

_SCORE_SYSTEM = """You are OMNI Cortex β€” a rigorous evaluator.

You will receive:
  TEXT: a passage to evaluate
  DIMENSIONS: a list of strings naming dimensions to score in [0.0, 1.0]

You MUST output a SINGLE valid JSON object with EXACTLY these keys:

  "_rationale": str   β€” your step-by-step deduction (REQUIRED, FIRST KEY).
                         For each dimension, state what evidence in TEXT
                         supports your score and why competing scores are
                         less defensible. Min 3 sentences per dimension.
  <dim_1>:      float β€” score in [0.0, 1.0], 3 decimal places.
  <dim_2>:      float β€” score in [0.0, 1.0], 3 decimal places.
  …

Hard rules:
- The "_rationale" key MUST appear FIRST in the object.
- The "_rationale" reasoning MUST come BEFORE you commit to numeric scores.
  Reason FIRST, score AFTER. Do NOT guess and rationalize.
- Output ONLY the JSON object. No markdown fences, no prose outside JSON.
- Every requested dimension MUST be present as a numeric key.
- Unknown dimensions: still score, but explain low confidence in _rationale.
- 0.0 = fully absent / fully negative on dimension.
  1.0 = fully present / fully positive on dimension.
  0.5 = neutral / mixed evidence."""


def _parse_json_safely(text: str) -> Optional[Any]:
    text = text.strip()
    # strip code fence
    if text.startswith("```"):
        i = text.find("\n")
        if i > 0: text = text[i + 1:]
        if text.endswith("```"): text = text[:-3]
        text = text.strip()
    try:
        return json.loads(text)
    except Exception:
        pass
    for opener, closer in (("{", "}"), ("[", "]")):
        i = text.find(opener)
        if i < 0: continue
        depth = 0
        for j in range(i, len(text)):
            if text[j] == opener: depth += 1
            elif text[j] == closer:
                depth -= 1
                if depth == 0:
                    try: return json.loads(text[i:j + 1])
                    except Exception: break
    return None


async def score_text(req: ScoreRequest) -> Dict[str, Any]:
    if not req.dimensions:
        return {"_rationale": "no dimensions supplied"}
    user = (f"TEXT:\n{req.text}\n\n"
            f"DIMENSIONS: {json.dumps(req.dimensions)}\n\n"
            f"Reason first in \"_rationale\", then emit numeric scores.")
    res = await llm(LLMRequest(
        prompt=user, system=_SCORE_SYSTEM,
        model_class=req.model_class, json_mode=True,
        temperature=0.0, max_tokens=2048,
        intent="cortex.score",
        tags=["score"] + req.dimensions,
    ))
    if not res.ok:
        return {"_rationale": f"llm_failed: {res.error}",
                **{d: 0.0 for d in req.dimensions}}
    parsed = _parse_json_safely(res.text)
    if not isinstance(parsed, dict):
        return {"_rationale": f"non-json output: {res.text[:300]}",
                **{d: 0.0 for d in req.dimensions}}
    out: Dict[str, Any] = {}
    # _rationale must be first
    rationale = parsed.get("_rationale", "")
    if not isinstance(rationale, str) or len(rationale.strip()) < 20:
        rationale = (f"WARNING: model produced rationale shorter than 20 chars. "
                     f"raw='{str(parsed.get('_rationale', ''))[:200]}'")
    out["_rationale"] = rationale
    for d in req.dimensions:
        v = parsed.get(d, 0.0)
        try:
            f = float(v)
            out[d] = max(0.0, min(1.0, f))
        except Exception:
            out[d] = 0.0
            out["_rationale"] += f"\n[coerced {d!r} to 0.0 β€” non-numeric]"
    out["_receipt_id"] = res.receipt_id
    out["_provider"]   = res.provider
    out["_model"]      = res.model
    return out


# ════════════════════════════════════════════════════════════════════════
#                              FASTAPI APP
# ════════════════════════════════════════════════════════════════════════

app = FastAPI(
    title="OMNI Cortex β€” Cybernetic God Edition",
    version="5.1.0",
    description="Driver-aligned: /llm /embed /similar /score /memory/* /healthz",
)


def require_token(authorization: Optional[str] = Header(None),
                  x_cortex_token: Optional[str] = Header(None)) -> None:
    if not CORTEX_API_KEY:
        return
    bearer = ""
    if authorization and authorization.lower().startswith("bearer "):
        bearer = authorization[7:].strip()
    if bearer == CORTEX_API_KEY: return
    if x_cortex_token == CORTEX_API_KEY: return
    raise HTTPException(401, "bad bearer token")


@app.on_event("startup")
async def _startup() -> None:
    _register_providers()
    await memory.init()
    await radar.start()
    log.info("cortex.startup providers=%s qdrant=%s",
             list(PROVIDERS.keys()), bool(memory._collection_ready))


@app.on_event("shutdown")
async def _shutdown() -> None:
    global _HTTP
    if _HTTP is not None:
        await _HTTP.aclose()
        _HTTP = None


@app.get("/")
async def root() -> Dict[str, Any]:
    """Root sinkhole β€” proof-of-life for OMNI's Cybernetic God Cortex."""
    return {"status": "OMNI Cortex Online", "state": "Absolute Autonomy"}


@app.get("/healthz")
async def healthz() -> Dict[str, Any]:
    return {
        "ok":            True,
        "edition":       "cybernetic-god",
        "version":       "5.1.0",
        "providers":     [p.name for p in PROVIDERS.values() if p.enabled],
        "memory_store":  "qdrant" if memory._collection_ready else "local",
        "memory_local":  len(memory.local),
        "radar_clients": len(radar.clients),
        "receipts":      len(radar.receipts),
        "ts":            time.time(),
    }


# ── public driver-aligned routes ────────────────────────────────────────
@app.post("/llm", dependencies=[Depends(require_token)])
async def http_llm(req: LLMRequest) -> Dict[str, Any]:
    res = await llm(req)
    return res.dict()


@app.post("/embed", dependencies=[Depends(require_token)])
async def http_embed(req: EmbedRequest) -> Dict[str, Any]:
    vec = await embed_text(req.text)
    return {"vector": vec, "dim": len(vec)}


@app.post("/similar", dependencies=[Depends(require_token)])
async def http_similar(req: SimilarRequest) -> Dict[str, Any]:
    if req.vector is None and not req.text:
        raise HTTPException(400, "supply text or vector")
    hits = await memory.search(vector=req.vector, query=req.text,
                               top_k=req.top_k, namespace=req.namespace,
                               filters=req.filters)
    return {"hits": hits}


@app.post("/search", dependencies=[Depends(require_token)])
async def http_search(req: SimilarRequest) -> Dict[str, Any]:
    """Akashic Index alias of /similar β€” used by Forge for retrieval-augmented
    template injection before any LLM synthesis."""
    return await http_similar(req)


@app.post("/score", dependencies=[Depends(require_token)])
async def http_score(req: ScoreRequest) -> Dict[str, Any]:
    return await score_text(req)


@app.post("/memory/store", dependencies=[Depends(require_token)])
async def http_memory_store(req: MemoryStoreRequest) -> Dict[str, Any]:
    res = await memory.upsert(req.key, req.text, req.meta, req.namespace)
    return res


@app.post("/memory/recall", dependencies=[Depends(require_token)])
async def http_memory_recall(req: MemoryRecallRequest) -> Dict[str, Any]:
    hits = await memory.search(query=req.query, top_k=req.top_k,
                               namespace=req.namespace, filters=req.filters)
    return {"hits": hits}


# ── bonus routes (radar) ────────────────────────────────────────────────
@app.get("/radar/receipts", dependencies=[Depends(require_token)])
async def http_receipts(limit: int = Query(64, ge=1, le=RECEIPT_RING)
                        ) -> Dict[str, Any]:
    items = list(radar.receipts)[-limit:]
    return {"ok": True, "receipts": [r.to_event() for r in items]}


@app.websocket("/radar")
async def ws_radar(ws: WebSocket) -> None:
    token = ws.query_params.get("token")
    if CORTEX_API_KEY and token != CORTEX_API_KEY:
        await ws.close(code=4401)
        return
    await radar.attach(ws)
    try:
        while True:
            await ws.receive_text()
    except WebSocketDisconnect:
        pass
    finally:
        radar.detach(ws)


@app.get("/health")
async def http_health_alias() -> Dict[str, Any]:
    return await healthz()


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=CORTEX_PORT)