kyrexis-module / kyrexis /api /routes.py
Codexcoder's picture
kyrexis: add kyrexis/api/routes.py
e21793a verified
Raw History Blame Contribute Delete
11.1 kB
# 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()}