Complete all 37 items: frontend UI, backend stubs, infrastructure, docs, tests
Frontend (items 1-10):
- WebSocket streaming integration with useWebSocket hook
- Admin Dashboard UI (status, voices, agents, governance tabs)
- Voice playback UI (TTS/STT integration)
- Settings/Preferences page (conversation style, sliders)
- Responsive/mobile layout (breakpoints at 480px, 768px)
- Dark/light theme with CSS variables and localStorage
- Error handling & loading states (retry, empty state, disabled input)
- Authentication UI (login page, Bearer token, logout)
- Head visualization improvements (active/speaking states, animations)
- Consequence/Ethics dashboard (lessons, consequences, insights tabs)
Backend stubs (items 11-21):
- Tool connectors: DocsConnector (text/md/PDF), DBConnector (SQLite/Postgres), CodeRunnerConnector (Python/JS/Bash/Ruby sandboxed)
- STT adapter: WhisperSTTAdapter, AzureSTTAdapter
- Multi-modal interface adapters: Visual, Haptic, Gesture, Biometric
- SSE streaming endpoint (/v1/sessions/{id}/stream/sse)
- Multi-tenant support (X-Tenant-ID header, tenant CRUD)
- Plugin marketplace/registry (register, install, list)
- Backup/restore endpoints
- Versioned API negotiation (Accept-Version header, deprecation)
Infrastructure (items 22-26):
- docker-compose.yml (API + Postgres + Redis + frontend)
- .env.example with all configurable vars
- gunicorn.conf.py production ASGI config
- Prometheus metrics collector and /metrics endpoint
- Structured JSON logging configuration
Documentation (items 27-29):
- Architecture docs with module layout and subsystem descriptions
- Quickstart guide with setup, API tour, and test instructions
Tests (items 30-32):
- Integration tests: 25 end-to-end API tests
- Frontend tests: 10 Vitest tests for hooks (useTheme, useAuth)
- Load/performance tests: latency and throughput benchmarks
- Connector tests: 16 tests for Docs, DB, CodeRunner
- Multi-modal adapter tests: 9 tests
- Metrics collector tests: 5 tests
- STT adapter tests: 2 tests
511 Python tests passing, 10 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 11:34:21 +00:00
|
|
|
"""FastAPI application factory for FusionAGI Dvādaśa API.
|
|
|
|
|
|
|
|
|
|
Includes versioned API negotiation, metrics, and CORS support."""
|
2026-02-09 21:51:42 -08:00
|
|
|
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
Complete all 37 items: frontend UI, backend stubs, infrastructure, docs, tests
Frontend (items 1-10):
- WebSocket streaming integration with useWebSocket hook
- Admin Dashboard UI (status, voices, agents, governance tabs)
- Voice playback UI (TTS/STT integration)
- Settings/Preferences page (conversation style, sliders)
- Responsive/mobile layout (breakpoints at 480px, 768px)
- Dark/light theme with CSS variables and localStorage
- Error handling & loading states (retry, empty state, disabled input)
- Authentication UI (login page, Bearer token, logout)
- Head visualization improvements (active/speaking states, animations)
- Consequence/Ethics dashboard (lessons, consequences, insights tabs)
Backend stubs (items 11-21):
- Tool connectors: DocsConnector (text/md/PDF), DBConnector (SQLite/Postgres), CodeRunnerConnector (Python/JS/Bash/Ruby sandboxed)
- STT adapter: WhisperSTTAdapter, AzureSTTAdapter
- Multi-modal interface adapters: Visual, Haptic, Gesture, Biometric
- SSE streaming endpoint (/v1/sessions/{id}/stream/sse)
- Multi-tenant support (X-Tenant-ID header, tenant CRUD)
- Plugin marketplace/registry (register, install, list)
- Backup/restore endpoints
- Versioned API negotiation (Accept-Version header, deprecation)
Infrastructure (items 22-26):
- docker-compose.yml (API + Postgres + Redis + frontend)
- .env.example with all configurable vars
- gunicorn.conf.py production ASGI config
- Prometheus metrics collector and /metrics endpoint
- Structured JSON logging configuration
Documentation (items 27-29):
- Architecture docs with module layout and subsystem descriptions
- Quickstart guide with setup, API tour, and test instructions
Tests (items 30-32):
- Integration tests: 25 end-to-end API tests
- Frontend tests: 10 Vitest tests for hooks (useTheme, useAuth)
- Load/performance tests: latency and throughput benchmarks
- Connector tests: 16 tests for Docs, DB, CodeRunner
- Multi-modal adapter tests: 9 tests
- Metrics collector tests: 5 tests
- STT adapter tests: 2 tests
511 Python tests passing, 10 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 11:34:21 +00:00
|
|
|
import json
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
import os
|
|
|
|
|
import time
|
|
|
|
|
from collections import defaultdict
|
|
|
|
|
from contextlib import asynccontextmanager
|
2026-02-09 21:51:42 -08:00
|
|
|
from typing import Any
|
|
|
|
|
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
from fusionagi._logger import logger
|
2026-02-09 21:51:42 -08:00
|
|
|
from fusionagi.api.dependencies import SessionStore, default_orchestrator, set_app_state
|
Complete all 37 items: frontend UI, backend stubs, infrastructure, docs, tests
Frontend (items 1-10):
- WebSocket streaming integration with useWebSocket hook
- Admin Dashboard UI (status, voices, agents, governance tabs)
- Voice playback UI (TTS/STT integration)
- Settings/Preferences page (conversation style, sliders)
- Responsive/mobile layout (breakpoints at 480px, 768px)
- Dark/light theme with CSS variables and localStorage
- Error handling & loading states (retry, empty state, disabled input)
- Authentication UI (login page, Bearer token, logout)
- Head visualization improvements (active/speaking states, animations)
- Consequence/Ethics dashboard (lessons, consequences, insights tabs)
Backend stubs (items 11-21):
- Tool connectors: DocsConnector (text/md/PDF), DBConnector (SQLite/Postgres), CodeRunnerConnector (Python/JS/Bash/Ruby sandboxed)
- STT adapter: WhisperSTTAdapter, AzureSTTAdapter
- Multi-modal interface adapters: Visual, Haptic, Gesture, Biometric
- SSE streaming endpoint (/v1/sessions/{id}/stream/sse)
- Multi-tenant support (X-Tenant-ID header, tenant CRUD)
- Plugin marketplace/registry (register, install, list)
- Backup/restore endpoints
- Versioned API negotiation (Accept-Version header, deprecation)
Infrastructure (items 22-26):
- docker-compose.yml (API + Postgres + Redis + frontend)
- .env.example with all configurable vars
- gunicorn.conf.py production ASGI config
- Prometheus metrics collector and /metrics endpoint
- Structured JSON logging configuration
Documentation (items 27-29):
- Architecture docs with module layout and subsystem descriptions
- Quickstart guide with setup, API tour, and test instructions
Tests (items 30-32):
- Integration tests: 25 end-to-end API tests
- Frontend tests: 10 Vitest tests for hooks (useTheme, useAuth)
- Load/performance tests: latency and throughput benchmarks
- Connector tests: 16 tests for Docs, DB, CodeRunner
- Multi-modal adapter tests: 9 tests
- Metrics collector tests: 5 tests
- STT adapter tests: 2 tests
511 Python tests passing, 10 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 11:34:21 +00:00
|
|
|
from fusionagi.api.metrics import get_metrics, metrics_enabled
|
|
|
|
|
|
|
|
|
|
API_VERSION = "1"
|
|
|
|
|
SUPPORTED_VERSIONS = ["1"]
|
|
|
|
|
DEPRECATED_VERSIONS: list[str] = []
|
2026-02-09 21:51:42 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_app(
|
|
|
|
|
adapter: Any = None,
|
|
|
|
|
cors_origins: list[str] | None = None,
|
|
|
|
|
) -> Any:
|
|
|
|
|
"""Create FastAPI app with Dvādaśa routes.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
adapter: Optional LLMAdapter for head/Witness LLM calls.
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
cors_origins: Optional list of CORS allowed origins.
|
2026-02-09 21:51:42 -08:00
|
|
|
"""
|
|
|
|
|
try:
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
from fastapi import FastAPI, Request, Response
|
|
|
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
2026-02-09 21:51:42 -08:00
|
|
|
except ImportError as e:
|
|
|
|
|
raise ImportError("Install with: pip install fusionagi[api]") from e
|
|
|
|
|
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
# --- Lifespan (replaces deprecated on_event) ---
|
|
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(application: FastAPI): # type: ignore[type-arg]
|
|
|
|
|
"""Startup / shutdown lifecycle."""
|
|
|
|
|
adapter_inner = getattr(application.state, "llm_adapter", None)
|
|
|
|
|
orch, bus = default_orchestrator(adapter_inner)
|
|
|
|
|
store = SessionStore()
|
|
|
|
|
set_app_state(orch, bus, store)
|
|
|
|
|
application.state._dvadasa_ready = True
|
|
|
|
|
logger.info("FusionAGI Dvādaśa API started")
|
|
|
|
|
yield
|
|
|
|
|
logger.info("FusionAGI Dvādaśa API shutdown")
|
|
|
|
|
|
2026-02-09 21:51:42 -08:00
|
|
|
app = FastAPI(
|
|
|
|
|
title="FusionAGI Dvādaśa API",
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
description=(
|
|
|
|
|
"12-headed multi-agent orchestration API.\n\n"
|
|
|
|
|
"## Authentication\n"
|
|
|
|
|
"Set `FUSIONAGI_API_KEY` to require Bearer token auth on all `/v1/` routes.\n\n"
|
|
|
|
|
"## Rate Limiting\n"
|
|
|
|
|
"Default: 120 requests/minute per client IP. "
|
|
|
|
|
"Configure via `FUSIONAGI_RATE_LIMIT` (requests) and "
|
|
|
|
|
"`FUSIONAGI_RATE_WINDOW` (seconds) env vars."
|
|
|
|
|
),
|
2026-02-09 21:51:42 -08:00
|
|
|
version="0.1.0",
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
lifespan=lifespan,
|
2026-02-09 21:51:42 -08:00
|
|
|
)
|
|
|
|
|
app.state.llm_adapter = adapter
|
|
|
|
|
from fusionagi.api.dependencies import set_default_adapter
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
|
2026-02-09 21:51:42 -08:00
|
|
|
set_default_adapter(adapter)
|
|
|
|
|
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
# --- Auth middleware ---
|
|
|
|
|
api_key = os.environ.get("FUSIONAGI_API_KEY")
|
|
|
|
|
|
|
|
|
|
class AuthMiddleware(BaseHTTPMiddleware):
|
|
|
|
|
"""Bearer token authentication for /v1/ routes."""
|
|
|
|
|
|
|
|
|
|
async def dispatch(self, request: Request, call_next: Any) -> Response:
|
|
|
|
|
if api_key and request.url.path.startswith("/v1/"):
|
|
|
|
|
auth = request.headers.get("authorization", "")
|
|
|
|
|
if not auth.startswith("Bearer ") or auth[7:].strip() != api_key:
|
|
|
|
|
return Response(
|
|
|
|
|
content='{"detail":"Invalid or missing API key"}',
|
|
|
|
|
status_code=401,
|
|
|
|
|
media_type="application/json",
|
|
|
|
|
)
|
|
|
|
|
return await call_next(request) # type: ignore[no-any-return]
|
|
|
|
|
|
|
|
|
|
app.add_middleware(AuthMiddleware)
|
|
|
|
|
|
|
|
|
|
# --- Rate limiting middleware ---
|
|
|
|
|
rate_limit = int(os.environ.get("FUSIONAGI_RATE_LIMIT", "120"))
|
|
|
|
|
rate_window = float(os.environ.get("FUSIONAGI_RATE_WINDOW", "60"))
|
|
|
|
|
_buckets: dict[str, list[float]] = defaultdict(list)
|
|
|
|
|
|
|
|
|
|
class RateLimitMiddleware(BaseHTTPMiddleware):
|
Next-level improvements: 15 items across backend, frontend, and testing
Backend:
- SQLiteStateBackend: persistent task/trace storage with SQLite
- InMemoryStateBackend: in-memory impl of StateBackend interface
- Redis cache backend (CacheBackend ABC + MemoryCacheBackend + RedisCacheBackend)
- OpenAI adapter: async acomplete() with retry logic
- Per-tenant + per-IP rate limiting in middleware
Frontend:
- State management: useStore + useAppState (zero-dep, context + reducer)
- React Router integration: URL-based navigation (usePageNavigation)
- WebSocket streaming: sendPrompt + StreamCallbacks for token-by-token updates
- File preview: inline image/text/binary preview with expand/collapse
- Sparkline charts + MetricCard + BarChart for dashboard visualization
- Push notifications hook (useNotifications) with browser Notification API
- i18n system: 6 locales (en, es, fr, de, ja, zh) with interpolation
- 6 new Storybook stories (ChatMessage, Skeleton, Markdown, SearchFilter, Toast, FilePreview)
Testing:
- Playwright E2E config + 6 browser specs (desktop + mobile)
- 18 new Python tests (SQLiteStateBackend, InMemoryStateBackend, cache backends)
570 Python tests + 45 frontend tests = 615 total, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:17:14 +00:00
|
|
|
"""Per-tenant + per-IP sliding window rate limiter (advisory mode).
|
2026-04-28 08:58:15 +00:00
|
|
|
|
Next-level improvements: 15 items across backend, frontend, and testing
Backend:
- SQLiteStateBackend: persistent task/trace storage with SQLite
- InMemoryStateBackend: in-memory impl of StateBackend interface
- Redis cache backend (CacheBackend ABC + MemoryCacheBackend + RedisCacheBackend)
- OpenAI adapter: async acomplete() with retry logic
- Per-tenant + per-IP rate limiting in middleware
Frontend:
- State management: useStore + useAppState (zero-dep, context + reducer)
- React Router integration: URL-based navigation (usePageNavigation)
- WebSocket streaming: sendPrompt + StreamCallbacks for token-by-token updates
- File preview: inline image/text/binary preview with expand/collapse
- Sparkline charts + MetricCard + BarChart for dashboard visualization
- Push notifications hook (useNotifications) with browser Notification API
- i18n system: 6 locales (en, es, fr, de, ja, zh) with interpolation
- 6 new Storybook stories (ChatMessage, Skeleton, Markdown, SearchFilter, Toast, FilePreview)
Testing:
- Playwright E2E config + 6 browser specs (desktop + mobile)
- 18 new Python tests (SQLiteStateBackend, InMemoryStateBackend, cache backends)
570 Python tests + 45 frontend tests = 615 total, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:17:14 +00:00
|
|
|
Tracks both IP-level and tenant-level request rates. Logs exceedances
|
|
|
|
|
but allows requests through (advisory governance).
|
2026-04-28 08:58:15 +00:00
|
|
|
"""
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
|
|
|
|
|
async def dispatch(self, request: Request, call_next: Any) -> Response:
|
|
|
|
|
client_ip = request.client.host if request.client else "unknown"
|
Next-level improvements: 15 items across backend, frontend, and testing
Backend:
- SQLiteStateBackend: persistent task/trace storage with SQLite
- InMemoryStateBackend: in-memory impl of StateBackend interface
- Redis cache backend (CacheBackend ABC + MemoryCacheBackend + RedisCacheBackend)
- OpenAI adapter: async acomplete() with retry logic
- Per-tenant + per-IP rate limiting in middleware
Frontend:
- State management: useStore + useAppState (zero-dep, context + reducer)
- React Router integration: URL-based navigation (usePageNavigation)
- WebSocket streaming: sendPrompt + StreamCallbacks for token-by-token updates
- File preview: inline image/text/binary preview with expand/collapse
- Sparkline charts + MetricCard + BarChart for dashboard visualization
- Push notifications hook (useNotifications) with browser Notification API
- i18n system: 6 locales (en, es, fr, de, ja, zh) with interpolation
- 6 new Storybook stories (ChatMessage, Skeleton, Markdown, SearchFilter, Toast, FilePreview)
Testing:
- Playwright E2E config + 6 browser specs (desktop + mobile)
- 18 new Python tests (SQLiteStateBackend, InMemoryStateBackend, cache backends)
570 Python tests + 45 frontend tests = 615 total, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:17:14 +00:00
|
|
|
tenant_id = request.headers.get("x-tenant-id", "default")
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
now = time.monotonic()
|
|
|
|
|
cutoff = now - rate_window
|
Next-level improvements: 15 items across backend, frontend, and testing
Backend:
- SQLiteStateBackend: persistent task/trace storage with SQLite
- InMemoryStateBackend: in-memory impl of StateBackend interface
- Redis cache backend (CacheBackend ABC + MemoryCacheBackend + RedisCacheBackend)
- OpenAI adapter: async acomplete() with retry logic
- Per-tenant + per-IP rate limiting in middleware
Frontend:
- State management: useStore + useAppState (zero-dep, context + reducer)
- React Router integration: URL-based navigation (usePageNavigation)
- WebSocket streaming: sendPrompt + StreamCallbacks for token-by-token updates
- File preview: inline image/text/binary preview with expand/collapse
- Sparkline charts + MetricCard + BarChart for dashboard visualization
- Push notifications hook (useNotifications) with browser Notification API
- i18n system: 6 locales (en, es, fr, de, ja, zh) with interpolation
- 6 new Storybook stories (ChatMessage, Skeleton, Markdown, SearchFilter, Toast, FilePreview)
Testing:
- Playwright E2E config + 6 browser specs (desktop + mobile)
- 18 new Python tests (SQLiteStateBackend, InMemoryStateBackend, cache backends)
570 Python tests + 45 frontend tests = 615 total, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:17:14 +00:00
|
|
|
|
|
|
|
|
# Per-IP tracking
|
|
|
|
|
ip_key = f"ip:{client_ip}"
|
|
|
|
|
_buckets[ip_key] = [t for t in _buckets[ip_key] if t > cutoff]
|
|
|
|
|
if len(_buckets[ip_key]) >= rate_limit:
|
2026-04-28 08:58:15 +00:00
|
|
|
logger.info(
|
Next-level improvements: 15 items across backend, frontend, and testing
Backend:
- SQLiteStateBackend: persistent task/trace storage with SQLite
- InMemoryStateBackend: in-memory impl of StateBackend interface
- Redis cache backend (CacheBackend ABC + MemoryCacheBackend + RedisCacheBackend)
- OpenAI adapter: async acomplete() with retry logic
- Per-tenant + per-IP rate limiting in middleware
Frontend:
- State management: useStore + useAppState (zero-dep, context + reducer)
- React Router integration: URL-based navigation (usePageNavigation)
- WebSocket streaming: sendPrompt + StreamCallbacks for token-by-token updates
- File preview: inline image/text/binary preview with expand/collapse
- Sparkline charts + MetricCard + BarChart for dashboard visualization
- Push notifications hook (useNotifications) with browser Notification API
- i18n system: 6 locales (en, es, fr, de, ja, zh) with interpolation
- 6 new Storybook stories (ChatMessage, Skeleton, Markdown, SearchFilter, Toast, FilePreview)
Testing:
- Playwright E2E config + 6 browser specs (desktop + mobile)
- 18 new Python tests (SQLiteStateBackend, InMemoryStateBackend, cache backends)
570 Python tests + 45 frontend tests = 615 total, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:17:14 +00:00
|
|
|
"API rate limit advisory: IP limit exceeded (proceeding)",
|
|
|
|
|
extra={"client_ip": client_ip, "count": len(_buckets[ip_key]), "limit": rate_limit},
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
)
|
Next-level improvements: 15 items across backend, frontend, and testing
Backend:
- SQLiteStateBackend: persistent task/trace storage with SQLite
- InMemoryStateBackend: in-memory impl of StateBackend interface
- Redis cache backend (CacheBackend ABC + MemoryCacheBackend + RedisCacheBackend)
- OpenAI adapter: async acomplete() with retry logic
- Per-tenant + per-IP rate limiting in middleware
Frontend:
- State management: useStore + useAppState (zero-dep, context + reducer)
- React Router integration: URL-based navigation (usePageNavigation)
- WebSocket streaming: sendPrompt + StreamCallbacks for token-by-token updates
- File preview: inline image/text/binary preview with expand/collapse
- Sparkline charts + MetricCard + BarChart for dashboard visualization
- Push notifications hook (useNotifications) with browser Notification API
- i18n system: 6 locales (en, es, fr, de, ja, zh) with interpolation
- 6 new Storybook stories (ChatMessage, Skeleton, Markdown, SearchFilter, Toast, FilePreview)
Testing:
- Playwright E2E config + 6 browser specs (desktop + mobile)
- 18 new Python tests (SQLiteStateBackend, InMemoryStateBackend, cache backends)
570 Python tests + 45 frontend tests = 615 total, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:17:14 +00:00
|
|
|
|
|
|
|
|
# Per-tenant tracking (separate quota)
|
|
|
|
|
tenant_key = f"tenant:{tenant_id}"
|
|
|
|
|
tenant_limit = rate_limit * 5 # tenants get 5x the per-IP limit
|
|
|
|
|
_buckets[tenant_key] = [t for t in _buckets[tenant_key] if t > cutoff]
|
|
|
|
|
if len(_buckets[tenant_key]) >= tenant_limit:
|
|
|
|
|
logger.info(
|
|
|
|
|
"API rate limit advisory: tenant limit exceeded (proceeding)",
|
|
|
|
|
extra={"tenant_id": tenant_id, "count": len(_buckets[tenant_key]), "limit": tenant_limit},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
_buckets[ip_key].append(now)
|
|
|
|
|
_buckets[tenant_key].append(now)
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
return await call_next(request) # type: ignore[no-any-return]
|
|
|
|
|
|
|
|
|
|
app.add_middleware(RateLimitMiddleware)
|
|
|
|
|
|
Complete all 37 items: frontend UI, backend stubs, infrastructure, docs, tests
Frontend (items 1-10):
- WebSocket streaming integration with useWebSocket hook
- Admin Dashboard UI (status, voices, agents, governance tabs)
- Voice playback UI (TTS/STT integration)
- Settings/Preferences page (conversation style, sliders)
- Responsive/mobile layout (breakpoints at 480px, 768px)
- Dark/light theme with CSS variables and localStorage
- Error handling & loading states (retry, empty state, disabled input)
- Authentication UI (login page, Bearer token, logout)
- Head visualization improvements (active/speaking states, animations)
- Consequence/Ethics dashboard (lessons, consequences, insights tabs)
Backend stubs (items 11-21):
- Tool connectors: DocsConnector (text/md/PDF), DBConnector (SQLite/Postgres), CodeRunnerConnector (Python/JS/Bash/Ruby sandboxed)
- STT adapter: WhisperSTTAdapter, AzureSTTAdapter
- Multi-modal interface adapters: Visual, Haptic, Gesture, Biometric
- SSE streaming endpoint (/v1/sessions/{id}/stream/sse)
- Multi-tenant support (X-Tenant-ID header, tenant CRUD)
- Plugin marketplace/registry (register, install, list)
- Backup/restore endpoints
- Versioned API negotiation (Accept-Version header, deprecation)
Infrastructure (items 22-26):
- docker-compose.yml (API + Postgres + Redis + frontend)
- .env.example with all configurable vars
- gunicorn.conf.py production ASGI config
- Prometheus metrics collector and /metrics endpoint
- Structured JSON logging configuration
Documentation (items 27-29):
- Architecture docs with module layout and subsystem descriptions
- Quickstart guide with setup, API tour, and test instructions
Tests (items 30-32):
- Integration tests: 25 end-to-end API tests
- Frontend tests: 10 Vitest tests for hooks (useTheme, useAuth)
- Load/performance tests: latency and throughput benchmarks
- Connector tests: 16 tests for Docs, DB, CodeRunner
- Multi-modal adapter tests: 9 tests
- Metrics collector tests: 5 tests
- STT adapter tests: 2 tests
511 Python tests passing, 10 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 11:34:21 +00:00
|
|
|
# --- Version negotiation middleware ---
|
|
|
|
|
class VersionMiddleware(BaseHTTPMiddleware):
|
|
|
|
|
"""API version negotiation via Accept-Version header.
|
|
|
|
|
|
|
|
|
|
Adds X-API-Version and deprecation warnings to responses.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
async def dispatch(self, request: Request, call_next: Any) -> Response:
|
|
|
|
|
requested = request.headers.get("accept-version", API_VERSION)
|
|
|
|
|
if requested not in SUPPORTED_VERSIONS:
|
|
|
|
|
return Response(
|
|
|
|
|
content=json.dumps({
|
|
|
|
|
"detail": f"Unsupported API version: {requested}",
|
|
|
|
|
"supported_versions": SUPPORTED_VERSIONS,
|
|
|
|
|
}),
|
|
|
|
|
status_code=400,
|
|
|
|
|
media_type="application/json",
|
|
|
|
|
)
|
|
|
|
|
response = await call_next(request)
|
|
|
|
|
response.headers["X-API-Version"] = requested
|
|
|
|
|
if requested in DEPRECATED_VERSIONS:
|
|
|
|
|
response.headers["Deprecation"] = "true"
|
|
|
|
|
response.headers["Sunset"] = "2026-12-31"
|
|
|
|
|
return response # type: ignore[no-any-return]
|
|
|
|
|
|
|
|
|
|
app.add_middleware(VersionMiddleware)
|
|
|
|
|
|
|
|
|
|
# --- Metrics middleware ---
|
|
|
|
|
if metrics_enabled():
|
|
|
|
|
class MetricsMiddleware(BaseHTTPMiddleware):
|
|
|
|
|
async def dispatch(self, request: Request, call_next: Any) -> Response:
|
|
|
|
|
m = get_metrics()
|
|
|
|
|
m.inc("http_requests_total", labels={"method": request.method, "path": request.url.path})
|
|
|
|
|
start = time.monotonic()
|
|
|
|
|
response = await call_next(request)
|
|
|
|
|
duration = time.monotonic() - start
|
|
|
|
|
m.observe("http_request_duration_seconds", duration, labels={"path": request.url.path})
|
|
|
|
|
m.inc("http_responses_total", labels={"status": str(response.status_code)})
|
|
|
|
|
return response # type: ignore[no-any-return]
|
|
|
|
|
|
|
|
|
|
app.add_middleware(MetricsMiddleware)
|
|
|
|
|
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
# --- Routes ---
|
|
|
|
|
from fusionagi.api.routes import router as api_router
|
2026-02-09 21:51:42 -08:00
|
|
|
|
|
|
|
|
app.include_router(api_router, prefix="/v1", tags=["dvadasa"])
|
|
|
|
|
|
Complete all 37 items: frontend UI, backend stubs, infrastructure, docs, tests
Frontend (items 1-10):
- WebSocket streaming integration with useWebSocket hook
- Admin Dashboard UI (status, voices, agents, governance tabs)
- Voice playback UI (TTS/STT integration)
- Settings/Preferences page (conversation style, sliders)
- Responsive/mobile layout (breakpoints at 480px, 768px)
- Dark/light theme with CSS variables and localStorage
- Error handling & loading states (retry, empty state, disabled input)
- Authentication UI (login page, Bearer token, logout)
- Head visualization improvements (active/speaking states, animations)
- Consequence/Ethics dashboard (lessons, consequences, insights tabs)
Backend stubs (items 11-21):
- Tool connectors: DocsConnector (text/md/PDF), DBConnector (SQLite/Postgres), CodeRunnerConnector (Python/JS/Bash/Ruby sandboxed)
- STT adapter: WhisperSTTAdapter, AzureSTTAdapter
- Multi-modal interface adapters: Visual, Haptic, Gesture, Biometric
- SSE streaming endpoint (/v1/sessions/{id}/stream/sse)
- Multi-tenant support (X-Tenant-ID header, tenant CRUD)
- Plugin marketplace/registry (register, install, list)
- Backup/restore endpoints
- Versioned API negotiation (Accept-Version header, deprecation)
Infrastructure (items 22-26):
- docker-compose.yml (API + Postgres + Redis + frontend)
- .env.example with all configurable vars
- gunicorn.conf.py production ASGI config
- Prometheus metrics collector and /metrics endpoint
- Structured JSON logging configuration
Documentation (items 27-29):
- Architecture docs with module layout and subsystem descriptions
- Quickstart guide with setup, API tour, and test instructions
Tests (items 30-32):
- Integration tests: 25 end-to-end API tests
- Frontend tests: 10 Vitest tests for hooks (useTheme, useAuth)
- Load/performance tests: latency and throughput benchmarks
- Connector tests: 16 tests for Docs, DB, CodeRunner
- Multi-modal adapter tests: 9 tests
- Metrics collector tests: 5 tests
- STT adapter tests: 2 tests
511 Python tests passing, 10 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 11:34:21 +00:00
|
|
|
# Metrics endpoint
|
|
|
|
|
if metrics_enabled():
|
|
|
|
|
@app.get("/metrics", tags=["monitoring"])
|
|
|
|
|
def metrics_endpoint() -> dict[str, Any]:
|
|
|
|
|
return get_metrics().snapshot()
|
|
|
|
|
|
Full optimization: 38 improvements across frontend, backend, infrastructure, and docs
Frontend (17 items):
- Virtualized message list with batch loading
- CSS split with skeleton, drawer, search filter, message action styles
- Code splitting via React.lazy + Suspense for Admin/Ethics/Settings pages
- Skeleton loading components (Skeleton, SkeletonCard, SkeletonGrid)
- Debounced search/filter component (SearchFilter)
- Error boundary with fallback UI
- Keyboard shortcuts (Ctrl+K search, Ctrl+Enter send, Escape dismiss)
- Page transition animations (fade-in)
- PWA support (manifest.json + service worker)
- WebSocket auto-reconnect with exponential backoff (10 retries)
- Chat history persistence to localStorage (500 msg limit)
- Message edit/delete on hover
- Copy-to-clipboard on code blocks
- Mobile drawer (bottom-sheet for consensus panel)
- File upload support
- User preferences sync to backend
Testing (8 items):
- Component tests: Toast, Markdown, ChatMessage, Avatar, ErrorBoundary, Skeleton
- Hook tests: useChatHistory
- E2E smoke tests (5 tests)
- Accessibility audit utility
Backend (12 items):
- Vector memory with cosine similarity search
- TTS/STT adapter factory wiring
- Geometry kernel with orphan detection
- Tenant registry with CRUD operations
- Response cache with TTL
- Connection pool (async)
- Background task queue
- Health check endpoints (/health, /ready)
- Request tracing middleware (X-Request-ID)
- API key rotation mechanism
- Environment-based config (settings.py)
- API route documentation improvements
Infrastructure (4 items):
- Grafana dashboard template
- Database migration system
- Storybook configuration
Documentation (3 items):
- ADR-001: Advisory Governance Model
- ADR-002: Twelve-Head Architecture
- ADR-003: Consequence Engine
552 Python tests + 45 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-05-02 03:08:08 +00:00
|
|
|
# Health check endpoints (no auth required)
|
|
|
|
|
_start_time = time.time()
|
|
|
|
|
|
|
|
|
|
@app.get("/health", tags=["monitoring"])
|
|
|
|
|
def health_check() -> dict[str, Any]:
|
|
|
|
|
"""Basic health check for load balancer probes."""
|
|
|
|
|
return {"status": "healthy", "uptime_seconds": round(time.time() - _start_time, 1)}
|
|
|
|
|
|
|
|
|
|
@app.get("/ready", tags=["monitoring"])
|
|
|
|
|
def readiness_check() -> dict[str, Any]:
|
|
|
|
|
"""Readiness probe. Returns 503 if not initialized."""
|
|
|
|
|
ready = getattr(app.state, "_dvadasa_ready", False)
|
|
|
|
|
if not ready:
|
|
|
|
|
from starlette.responses import JSONResponse
|
|
|
|
|
return JSONResponse( # type: ignore[return-value]
|
|
|
|
|
content={"status": "not_ready"},
|
|
|
|
|
status_code=503,
|
|
|
|
|
)
|
|
|
|
|
return {"status": "ready", "uptime_seconds": round(time.time() - _start_time, 1)}
|
|
|
|
|
|
Complete all 37 items: frontend UI, backend stubs, infrastructure, docs, tests
Frontend (items 1-10):
- WebSocket streaming integration with useWebSocket hook
- Admin Dashboard UI (status, voices, agents, governance tabs)
- Voice playback UI (TTS/STT integration)
- Settings/Preferences page (conversation style, sliders)
- Responsive/mobile layout (breakpoints at 480px, 768px)
- Dark/light theme with CSS variables and localStorage
- Error handling & loading states (retry, empty state, disabled input)
- Authentication UI (login page, Bearer token, logout)
- Head visualization improvements (active/speaking states, animations)
- Consequence/Ethics dashboard (lessons, consequences, insights tabs)
Backend stubs (items 11-21):
- Tool connectors: DocsConnector (text/md/PDF), DBConnector (SQLite/Postgres), CodeRunnerConnector (Python/JS/Bash/Ruby sandboxed)
- STT adapter: WhisperSTTAdapter, AzureSTTAdapter
- Multi-modal interface adapters: Visual, Haptic, Gesture, Biometric
- SSE streaming endpoint (/v1/sessions/{id}/stream/sse)
- Multi-tenant support (X-Tenant-ID header, tenant CRUD)
- Plugin marketplace/registry (register, install, list)
- Backup/restore endpoints
- Versioned API negotiation (Accept-Version header, deprecation)
Infrastructure (items 22-26):
- docker-compose.yml (API + Postgres + Redis + frontend)
- .env.example with all configurable vars
- gunicorn.conf.py production ASGI config
- Prometheus metrics collector and /metrics endpoint
- Structured JSON logging configuration
Documentation (items 27-29):
- Architecture docs with module layout and subsystem descriptions
- Quickstart guide with setup, API tour, and test instructions
Tests (items 30-32):
- Integration tests: 25 end-to-end API tests
- Frontend tests: 10 Vitest tests for hooks (useTheme, useAuth)
- Load/performance tests: latency and throughput benchmarks
- Connector tests: 16 tests for Docs, DB, CodeRunner
- Multi-modal adapter tests: 9 tests
- Metrics collector tests: 5 tests
- STT adapter tests: 2 tests
511 Python tests passing, 10 frontend tests passing, 0 ruff errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 11:34:21 +00:00
|
|
|
# Version info endpoint
|
|
|
|
|
@app.get("/version", tags=["meta"])
|
|
|
|
|
def version_info() -> dict[str, Any]:
|
|
|
|
|
return {
|
|
|
|
|
"current_version": API_VERSION,
|
|
|
|
|
"supported_versions": SUPPORTED_VERSIONS,
|
|
|
|
|
"deprecated_versions": DEPRECATED_VERSIONS,
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-09 21:51:42 -08:00
|
|
|
if cors_origins is not None:
|
|
|
|
|
try:
|
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
|
2026-02-09 21:51:42 -08:00
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=cors_origins,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
|
|
|
|
except ImportError:
|
feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed:
1. Merged PR #2 (starlette/httpx deps)
2. Fixed async race condition in multimodal_ui.py
3. Wired TTSAdapter (ElevenLabs, Azure) in API routes
4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim)
5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY)
6. Added async adapter interface (acomplete/acomplete_structured)
7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings)
8. Liquid Neural Networks (continuous-time adaptive weights)
9. Quantum-AI Hybrid compute backend (simulator + optimization)
10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols)
11. Consciousness Engineering (formal self-model with introspection)
12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness)
13. GPU integration tests for TensorFlow backend
14. Multi-stage production Dockerfile
15. Gitea CI/CD pipeline (lint, test matrix, Docker build)
16. API rate limiting middleware (per-IP sliding window)
17. OpenAPI docs cleanup (auth + rate limiting descriptions)
18. Benchmarking suite (decomposition, multi-path, recomposition, e2e)
19. Plugin system (head registry for custom heads)
427 tests passing, 0 ruff errors, 0 mypy errors.
Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
2026-04-28 08:32:05 +00:00
|
|
|
pass
|
2026-02-09 21:51:42 -08:00
|
|
|
|
|
|
|
|
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Default app instance for uvicorn/gunicorn
|
|
|
|
|
app = create_app()
|