File size: 11,097 Bytes
e21793a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# kyrexis/api/routes.py
"""
Kyrexis AI API Endpoints β€” Complete REST API (spec section 8)

All endpoints live under /api/v1/kyrexis/*. The system is lazy: the
first call to POST /initialize boots every subsystem; every other
endpoint returns 503 until then (matching the spec).
"""

from __future__ import annotations

import time
from typing import Any, Dict, List, Optional

import numpy as np
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

router = APIRouter(prefix="/api/v1/kyrexis", tags=["kyrexis"])

# ── Global subsystem instances (lazy singleton per process) ──────────────
kyrexis_core = None
skills_engine = None
messenger_integration = None
photonic_display = None
particle_detector = None
progression_scaling = None
INITIALIZED_AT = None


# ── Request models ────────────────────────────────────────────────────────
class ComputeIn(BaseModel):
    data: List[float]


class MessengerSendIn(BaseModel):
    recipient_id: str
    message: str


class PulseIn(BaseModel):
    power: float = 1.0


class SkillIn(BaseModel):
    parameters: Dict[str, Any] = Field(default_factory=dict)


# ── Lifecycle ─────────────────────────────────────────────────────────────
@router.post("/initialize")
async def initialize_kyrexis() -> Dict[str, Any]:
    """Initialize the full Kyrexis AI system (idempotent)."""
    global kyrexis_core, skills_engine, messenger_integration
    global photonic_display, particle_detector, progression_scaling, INITIALIZED_AT

    if kyrexis_core is None:
        from kyrexis.core import KyrexisCore
        from kyrexis.quantum_skills import QuantumSkillsEngine

        kyrexis_core = KyrexisCore()
        kyrexis_core.initialize()
        skills_engine = QuantumSkillsEngine(kyrexis_core)

    if messenger_integration is None:
        from kyrexis.messenger_integration import KyrexisMessengerIntegration

        messenger_integration = KyrexisMessengerIntegration()
        messenger_integration.initialize(kyrexis_core)

    if photonic_display is None:
        from kyrexis.photonic_display import LaserCrystalPhotonicDisplay

        photonic_display = LaserCrystalPhotonicDisplay()
        photonic_display.initialize()

    if particle_detector is None:
        from kyrexis.particle_detector import ParticlePairDetector

        particle_detector = ParticlePairDetector()
        particle_detector.initialize()

    if progression_scaling is None:
        from kyrexis.progression_scaling import ProgressionScalingEngine

        progression_scaling = ProgressionScalingEngine()

    INITIALIZED_AT = time.time()
    return {
        "status": "initialized",
        "kyrexis": kyrexis_core.get_state(),
        "messenger": messenger_integration.get_status(),
        "photonic": photonic_display.get_display_state(),
        "particle": particle_detector.get_detector_state(),
        "progression": progression_scaling.get_progression_status(),
    }


# ── Core ──────────────────────────────────────────────────────────────────
@router.get("/status")
async def get_kyrexis_status() -> Dict[str, Any]:
    """Kyrexis AI core state."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    return kyrexis_core.get_state()


@router.get("/quantum/state")
async def get_quantum_state() -> Dict[str, Any]:
    """Quantum state snapshot."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    return {
        "qubits": kyrexis_core.state.quantum_qubits,
        "fidelity": kyrexis_core.state.fidelity,
        "coherence": kyrexis_core.state.coherence,
        "entanglement_pairs": kyrexis_core.state.entanglement_pairs,
    }


@router.post("/quantum/compute")
async def quantum_compute(body: ComputeIn) -> Dict[str, Any]:
    """Apply the quantum-superposition simulation to a vector."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    result = kyrexis_core.quantum_compute(np.array(body.data, dtype=float))
    return {"result": result.tolist()}


@router.post("/predict")
async def predict_future(body: Dict[str, Any]) -> Dict[str, Any]:
    """20-year forward projection (33.5% CAGR)."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    current = float(body.get("current_value", 1.0))
    years = int(body.get("years", 20))
    return kyrexis_core.predict_future(current, years)


@router.post("/self-improve")
async def self_improve() -> Dict[str, Any]:
    """Run one exponential-intelligence improvement cycle."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    return kyrexis_core.self_improve()


# ── Skills engine ─────────────────────────────────────────────────────────
@router.get("/skills")
async def get_skills() -> Dict[str, Any]:
    """All quantum skills + cooldowns."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    return skills_engine.get_skill_status()


@router.post("/skills/{skill_id}")
async def execute_skill(skill_id: str, body: SkillIn) -> Dict[str, Any]:
    """Execute a quantum skill by id."""
    if kyrexis_core is None:
        raise HTTPException(status_code=503, detail="Kyrexis not initialized")
    result = skills_engine.execute_skill(skill_id, body.parameters)
    if "error" in result:
        raise HTTPException(status_code=400, detail=result["error"])
    return result


# ── Messenger ─────────────────────────────────────────────────────────────
@router.post("/messenger/webhook")
async def messenger_webhook(payload: Dict[str, Any]) -> Dict[str, Any]:
    """Handle a Messenger webhook payload."""
    if messenger_integration is None:
        raise HTTPException(status_code=503, detail="Messenger not initialized")
    return messenger_integration.handle_webhook(payload)


@router.post("/messenger/send")
async def messenger_send(body: MessengerSendIn) -> Dict[str, Any]:
    """Send a message via Messenger."""
    if messenger_integration is None:
        raise HTTPException(status_code=503, detail="Messenger not initialized")
    result = messenger_integration.send_message(body.recipient_id, body.message)
    return {"status": "sent", "result": result}


# ── Photonic display ──────────────────────────────────────────────────────
@router.get("/photonic/display")
async def get_photonic_display() -> Dict[str, Any]:
    """Photonic display system state."""
    if photonic_display is None:
        raise HTTPException(status_code=503, detail="Photonic display not initialized")
    return photonic_display.get_display_state()


@router.post("/photonic/pulse")
async def generate_photonic_pulse(body: PulseIn) -> Dict[str, Any]:
    """Generate a 775 nm laser pulse (simulated)."""
    if photonic_display is None:
        raise HTTPException(status_code=503, detail="Photonic display not initialized")
    pulse = photonic_display.generate_laser_pulse(body.power)
    return {"pulse": pulse}


# ── Particle detector ─────────────────────────────────────────────────────
@router.get("/particle/state")
async def get_particle_state() -> Dict[str, Any]:
    """Particle detector state."""
    if particle_detector is None:
        raise HTTPException(status_code=503, detail="Particle detector not initialized")
    return particle_detector.get_detector_state()


@router.post("/particle/detect")
async def detect_particle_pair() -> Dict[str, Any]:
    """Detect a particle pair and verify entanglement."""
    if particle_detector is None:
        raise HTTPException(status_code=503, detail="Particle detector not initialized")
    rng = np.random.default_rng()
    photon_state = rng.standard_normal(4) + 1j * rng.standard_normal(4)
    pair = particle_detector.detect_particle_pair(photon_state)
    verification = particle_detector.verify_entanglement(pair)
    return {
        "pair": {
            "id": pair.id,
            "correlation": pair.correlation,
            "fidelity": pair.fidelity,
            "entanglement": pair.entanglement,
        },
        "verification": verification,
    }


# ── Progression scaling ───────────────────────────────────────────────────
@router.get("/progression/status")
async def get_progression_status() -> Dict[str, Any]:
    """20-year progression status."""
    if progression_scaling is None:
        raise HTTPException(status_code=503, detail="Progression scaling not initialized")
    return progression_scaling.get_progression_status()


@router.get("/progression/{year}")
async def get_progression_at_year(year: int) -> Dict[str, Any]:
    """Progression at a specific year (1-20)."""
    if progression_scaling is None:
        raise HTTPException(status_code=503, detail="Progression scaling not initialized")
    if year < 1 or year > 20:
        raise HTTPException(status_code=400, detail="Year must be between 1 and 20")
    return progression_scaling.get_progression_at_year(year)


@router.post("/progression/project")
async def progression_project(body: Dict[str, Any]) -> Dict[str, Any]:
    """Project a value across 20 years with x4 scaling."""
    if progression_scaling is None:
        raise HTTPException(status_code=503, detail="Progression scaling not initialized")
    current = float(body.get("current_value", 1.0))
    return progression_scaling.calculate_20_year_projection(current)


# ── Universal agent network ───────────────────────────────────────────────
@router.get("/agents")
async def get_agents() -> Dict[str, Any]:
    """Universal Agent Network status."""
    from kyrexis.agents import network

    return network.status()


@router.post("/agents/sync")
async def sync_agents() -> Dict[str, Any]:
    """Run the network sync protocol (simulated updates)."""
    from kyrexis.agents import network

    if not network.network_online:
        network.activate()
    return {"sync": network.sync()}