-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.py
More file actions
539 lines (442 loc) · 17.9 KB
/
Copy pathserver.py
File metadata and controls
539 lines (442 loc) · 17.9 KB
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
"""FastAPI Status Server for CodeFRAME."""
# Standard library imports
import logging
import os
import subprocess
from contextlib import asynccontextmanager
from datetime import datetime, UTC
from enum import Enum
from pathlib import Path
# Third-party imports
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
# Local imports - v2 only (no v1 persistence layer)
from codeframe.workspace import WorkspaceManager
from codeframe.ui.routers import (
# v2 routers only - delegate to codeframe.core modules
batches_v2,
blockers_v2,
checkpoints_v2,
diagnose_v2,
discovery_v2,
environment_v2,
events_v2,
gates_v2,
git_v2,
interactive_sessions_v2,
pr_v2,
prd_v2,
proof_v2,
review_v2,
schedule_v2,
session_chat_ws,
settings_v2,
terminal_ws,
streaming_v2,
tasks_v2,
templates_v2,
workspace_v2,
)
from codeframe.auth import router as auth_router
from codeframe.persistence.database import Database
from codeframe.lib.rate_limiter import (
get_rate_limiter,
rate_limit_exceeded_handler,
)
from codeframe.config.rate_limits import get_rate_limit_config
# ============================================================================
# Configuration and Setup
# ============================================================================
class DeploymentMode(str, Enum):
"""Deployment mode for CodeFRAME."""
SELF_HOSTED = "self_hosted"
HOSTED = "hosted"
def get_deployment_mode() -> DeploymentMode:
"""Get current deployment mode from environment.
Returns:
DeploymentMode.SELF_HOSTED or DeploymentMode.HOSTED
"""
mode = os.getenv("CODEFRAME_DEPLOYMENT_MODE", "self_hosted").lower()
if mode == "hosted":
return DeploymentMode.HOSTED
return DeploymentMode.SELF_HOSTED
def is_hosted_mode() -> bool:
"""Check if running in hosted SaaS mode.
Returns:
True if hosted mode, False if self-hosted
"""
return get_deployment_mode() == DeploymentMode.HOSTED
# Logger setup
logger = logging.getLogger(__name__)
# ============================================================================
# Application Lifespan
# ============================================================================
# Note: Session cleanup removed - v1 persistence layer not used in v2
# If session management is needed, implement in v2 core modules
def _validate_security_config():
"""Validate security configuration at startup.
Raises:
RuntimeError: If security configuration is invalid for the deployment mode
"""
from codeframe.auth.manager import SECRET, DEFAULT_SECRET
deployment_mode = get_deployment_mode()
# In hosted mode, fail fast if using default JWT secret
if deployment_mode == DeploymentMode.HOSTED and SECRET == DEFAULT_SECRET:
raise RuntimeError(
"🚨 SECURITY: AUTH_SECRET must be set in hosted/production mode. "
"Using the default secret compromises all JWT tokens. "
"Set the AUTH_SECRET environment variable to a secure random value."
)
# Log security status
if SECRET == DEFAULT_SECRET:
logger.warning(
"⚠️ Running with default AUTH_SECRET - acceptable for self-hosted development only"
)
else:
logger.info("🔐 AUTH_SECRET configured (custom secret in use)")
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifespan - startup and shutdown."""
# Load environment variables from .env file
from codeframe.core.config import load_environment
load_environment()
# Validate security configuration before starting
_validate_security_config()
# Initialize workspace manager for v2 core
workspace_root_str = os.environ.get(
"WORKSPACE_ROOT", str(Path.cwd() / ".codeframe" / "workspaces")
)
workspace_root = Path(workspace_root_str)
app.state.workspace_manager = WorkspaceManager(workspace_root)
# Initialize global persistent DB (used by interactive_sessions and auth)
db_path = os.environ.get(
"DATABASE_PATH",
str(Path.cwd() / ".codeframe" / "state.db"),
)
db = Database(db_path)
db.initialize()
app.state.db = db
# Log that authentication is now always required
logger.info("🔒 Authentication: ENABLED (always required)")
# Initialize rate limiting
rate_limit_config = get_rate_limit_config()
if rate_limit_config.enabled:
limiter = get_rate_limiter()
if limiter:
app.state.limiter = limiter
logger.info(
f"🚦 Rate limiting: ENABLED "
f"(storage={rate_limit_config.storage}, "
f"standard={rate_limit_config.standard_limit})"
)
else:
logger.info("🚦 Rate limiting: DISABLED")
yield
# Shutdown: nothing to clean up (v2 uses per-workspace databases managed by core)
# ============================================================================
# OpenAPI Tags and Metadata
# ============================================================================
OPENAPI_TAGS = [
{
"name": "health",
"description": "Health check endpoints - verify API availability and get deployment information.",
},
{
"name": "projects",
"description": "Project lifecycle and management - create, read, update, delete projects and access project status, tasks, activity, PRD, and session state.",
},
{
"name": "tasks",
"description": "Task creation, management, and approval workflow - create tasks, approve generated tasks to start development, and manually trigger task assignment.",
},
{
"name": "agents",
"description": "Agent lifecycle and assignment - start/pause/resume agents, assign agents to projects with roles, and manage multi-agent workflows.",
},
{
"name": "blockers",
"description": "Human-in-the-loop blocker management - list, view, and resolve blockers that require human guidance for agents to continue.",
},
{
"name": "checkpoints",
"description": "Project checkpoint and restore functionality - create snapshots of project state and restore to previous checkpoints.",
},
{
"name": "chat",
"description": "Chat and communication endpoints for real-time interaction with agents.",
},
{
"name": "context",
"description": "Context management for agent execution - manage codebase context, file references, and relevant information.",
},
{
"name": "discovery",
"description": "Discovery phase operations - codebase analysis, structure detection, and initial project understanding.",
},
{
"name": "git",
"description": "Git operations - commit, branch, diff, and repository management.",
},
{
"name": "lint",
"description": "Code linting operations - run and manage linting checks.",
},
{
"name": "metrics",
"description": "Metrics and analytics - project progress, agent performance, and quality metrics.",
},
{
"name": "quality_gates",
"description": "Quality gates and checks - run tests, type checking, coverage, and code review gates.",
},
{
"name": "review",
"description": "Code review functionality - trigger and manage AI-powered code reviews.",
},
{
"name": "schedule",
"description": "Task scheduling - view schedule predictions, bottlenecks, and critical path analysis.",
},
{
"name": "session",
"description": "Session management - track session state, progress, and continuity across work sessions.",
},
{
"name": "templates",
"description": "Project and task templates - list, view, and apply reusable templates.",
},
{
"name": "websocket",
"description": "WebSocket connections for real-time updates and event streaming.",
},
{
"name": "auth",
"description": "Authentication and authorization - login, logout, API keys, and session management.",
},
{
"name": "proof-v2",
"description": "PROOF9 quality system — capture requirements from glitches, run proof obligations, manage waivers, and query evidence.",
},
]
OPENAPI_DESCRIPTION = """
# CodeFRAME API
**CodeFRAME** is an AI-powered software development framework that orchestrates multiple agents
to complete programming tasks. This API provides real-time monitoring and control for CodeFRAME projects.
## Overview
The CodeFRAME API enables you to:
- **Create and manage projects** - Initialize projects from git repos, local paths, or start empty
- **Generate and approve tasks** - AI generates implementation tasks from PRDs; approve to start development
- **Monitor agent execution** - Track agents as they work through tasks with real-time WebSocket updates
- **Handle blockers** - Provide human guidance when agents encounter decisions requiring input
- **Review and ship** - Run quality gates, review code changes, and manage the deployment process
## Authentication
All endpoints require authentication. The API supports two authentication methods:
1. **API Key** - Include `X-API-Key` header with your API key
2. **Session Token** - Use JWT token from login endpoint in `Authorization: Bearer <token>` header
## Rate Limiting
The API implements rate limiting to ensure fair usage:
- **Standard endpoints**: Higher request limits for read operations
- **AI endpoints** (agent start, LLM calls): Lower limits due to computational cost
Rate limit headers are included in responses: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
## WebSocket Events
For real-time updates, connect to the WebSocket endpoint. Events include:
- `task_assigned`, `task_completed`, `task_failed`
- `agent_created`, `agent_status`
- `blocker_created`, `blocker_resolved`
- `discovery_starting`, `discovery_completed`
## Error Responses
All errors follow a consistent format:
```json
{
"detail": "Error message describing what went wrong"
}
```
Common HTTP status codes:
- `400` - Bad Request (validation error)
- `401` - Unauthorized (authentication required)
- `403` - Forbidden (insufficient permissions)
- `404` - Not Found (resource doesn't exist)
- `409` - Conflict (duplicate resource or state conflict)
- `422` - Unprocessable Entity (Pydantic validation failure)
- `429` - Too Many Requests (rate limit exceeded)
- `500` - Internal Server Error
"""
# ============================================================================
# FastAPI Application
# ============================================================================
app = FastAPI(
title="CodeFRAME API",
description=OPENAPI_DESCRIPTION,
version="2.0.0",
lifespan=lifespan,
openapi_tags=OPENAPI_TAGS,
contact={
"name": "CodeFRAME Support",
"url": "https://github.com/frankbria/codeframe",
},
license_info={
"name": "MIT",
"identifier": "MIT",
},
)
# ============================================================================
# Rate Limiting Setup
# ============================================================================
# Add rate limiting exception handler
app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler)
# Add rate limiting middleware if enabled
# Initialize limiter immediately so it's available before lifespan runs
rate_limit_config = get_rate_limit_config()
if rate_limit_config.enabled:
limiter = get_rate_limiter()
if limiter:
app.state.limiter = limiter
app.add_middleware(SlowAPIMiddleware)
# ============================================================================
# CORS Middleware
# ============================================================================
# CORS configuration from environment variables
# Get CORS_ALLOWED_ORIGINS from env (comma-separated list)
cors_origins_env = os.environ.get("CORS_ALLOWED_ORIGINS", "")
# Parse comma-separated origins
if cors_origins_env:
allowed_origins = [origin.strip() for origin in cors_origins_env.split(",") if origin.strip()]
else:
# Fallback to development defaults if not configured
allowed_origins = [
"http://localhost:3000", # Next.js dev server
"http://localhost:3001", # Next.js E2E test server
"http://localhost:5173", # Vite dev server
]
# Log CORS configuration for debugging
print("🔒 CORS Configuration:")
print(f" CORS_ALLOWED_ORIGINS env: {cors_origins_env!r}")
print(f" Parsed allowed origins: {allowed_origins}")
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================================================
# Health Check Endpoints
# ============================================================================
@app.get(
"/",
summary="Basic health check",
description="Simple health check endpoint that returns online status. Use /health for detailed information.",
tags=["health"],
)
async def root():
"""Health check endpoint."""
return {"status": "online", "service": "CodeFRAME API"}
@app.get(
"/health",
summary="Detailed health check",
description="Returns comprehensive health information including version, git commit, deployment time, "
"and database connection status. Useful for monitoring and debugging.",
tags=["health"],
)
async def health_check():
"""Detailed health check with deployment info.
Returns:
- status: Service health status
- version: API version from FastAPI app
- commit: Git commit hash (short)
- deployed_at: Server startup timestamp
- database: Database connection status
"""
# Get git commit hash
try:
git_commit = (
subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"],
cwd=Path(__file__).parent.parent.parent,
stderr=subprocess.DEVNULL,
)
.decode()
.strip()
)
except Exception:
git_commit = "unknown"
return {
"status": "healthy",
"service": "CodeFRAME Status Server",
"version": app.version,
"commit": git_commit,
"deployed_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
}
# ============================================================================
# Test-Only Endpoints (for WebSocket integration tests)
# ============================================================================
@app.post("/test/broadcast")
async def test_broadcast(message: dict, project_id: int = None):
"""Trigger a WebSocket broadcast for testing purposes.
This endpoint is only intended for use in integration tests to trigger
broadcasts from the server subprocess. In production, broadcasts are
triggered by actual server-side events.
Args:
message: The message dict to broadcast
project_id: Optional project ID for filtered broadcasts
Returns:
Success confirmation
"""
from codeframe.ui.shared import manager
await manager.broadcast(message, project_id=project_id)
return {"status": "broadcast_sent", "project_id": project_id}
# ============================================================================
# Router Mounting (v2 only)
# ============================================================================
# Authentication router
app.include_router(auth_router.router)
# v2 API routers - all delegate to codeframe.core modules
app.include_router(batches_v2.router) # /api/v2/batches
app.include_router(blockers_v2.router) # /api/v2/blockers
app.include_router(checkpoints_v2.router) # /api/v2/checkpoints
app.include_router(diagnose_v2.router) # /api/v2/tasks/{id}/diagnose
app.include_router(discovery_v2.router) # /api/v2/discovery
app.include_router(environment_v2.router) # /api/v2/env
app.include_router(events_v2.router) # /api/v2/events
app.include_router(gates_v2.router) # /api/v2/gates
app.include_router(git_v2.router) # /api/v2/git
app.include_router(interactive_sessions_v2.router) # /api/v2/sessions
app.include_router(session_chat_ws.router) # /ws/sessions/{id}/chat
app.include_router(terminal_ws.router) # /ws/sessions/{id}/terminal
app.include_router(pr_v2.router) # /api/v2/pr
app.include_router(prd_v2.router) # /api/v2/prd
app.include_router(proof_v2.router) # /api/v2/proof
app.include_router(review_v2.router) # /api/v2/review
app.include_router(schedule_v2.router) # /api/v2/schedule
app.include_router(settings_v2.router) # /api/v2/settings
app.include_router(streaming_v2.router) # /api/v2/tasks/{id}/stream (SSE)
app.include_router(tasks_v2.router) # /api/v2/tasks
app.include_router(templates_v2.router) # /api/v2/templates
app.include_router(workspace_v2.router) # /api/v2/workspaces
# ============================================================================
# Server Startup
# ============================================================================
def run_server(host: str = "0.0.0.0", port: int = 8080):
"""Run the Status Server."""
import uvicorn
uvicorn.run(app, host=host, port=port)
if __name__ == "__main__":
import argparse
# Parse command line arguments
parser = argparse.ArgumentParser(description="CodeFRAME Status Server")
parser.add_argument(
"--host",
type=str,
default=os.environ.get("HOST", "0.0.0.0"),
help="Host to bind to (default: 0.0.0.0 or HOST env var)",
)
parser.add_argument(
"--port",
type=int,
default=int(os.environ.get("BACKEND_PORT", os.environ.get("PORT", "8080"))),
help="Port to bind to (default: 8080 or BACKEND_PORT/PORT env var)",
)
args = parser.parse_args()
run_server(host=args.host, port=args.port)