-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
2045 lines (1681 loc) · 66.5 KB
/
Copy pathapi.py
File metadata and controls
2045 lines (1681 loc) · 66.5 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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""REST API Server - FastAPI based API service for Agent-Loop
Provides HTTP endpoints to interact with the Agent-Loop system.
Production-grade with API versioning, logging, error handling, and more.
"""
import asyncio
import json
import os
import sys
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
import bleach
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Header, Depends, Request, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, Response, JSONResponse
from starlette.middleware.gzip import GZipMiddleware
from pydantic import BaseModel, field_validator
from pydantic import ValidationInfo
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))
from agent.state_manager import StateManager
from agent.task_selector import TaskSelector
from agent.session_manager import SessionManager
from agent.git_helper import GitHelper
from agent.metrics import get_prometheus_metrics, get_metrics_content_type, get_metrics_collector
from agent.logging_ import configure_logging, get_logger
from agent.exceptions import (
AgentLoopError,
ConfigError,
ConfigValidationError,
TaskExecutionError,
ProviderError,
NotificationError,
SessionError,
StateError,
ErrorCode,
)
# Configure structured logging
log_level = os.environ.get("LOG_LEVEL", "INFO")
log_file = os.environ.get("LOG_FILE", "")
json_output = bool(log_file)
configure_logging(log_level=log_level, log_file=log_file, json_output=json_output)
logger = get_logger(__name__)
# ========== Unified Error Response ==========
def create_error_response(
error_code: ErrorCode,
message: str,
status_code: int = 500,
detail: Optional[str] = None,
) -> JSONResponse:
"""Create a standardized JSON error response.
Args:
error_code: The error code enum value
message: Human-readable error message
status_code: HTTP status code
detail: Additional details about the error
Returns:
JSONResponse with standardized error format
"""
error_dict: Dict[str, Any] = {
"error_code": error_code.value,
"message": message,
"timestamp": datetime.now().isoformat(),
}
if detail:
error_dict["detail"] = detail
return JSONResponse(
status_code=status_code,
content=error_dict,
)
def handle_agent_error(error: Exception) -> JSONResponse:
"""Convert AgentLoopError to standardized JSON response.
Args:
error: The exception to handle
Returns:
JSONResponse with standardized error format
"""
if isinstance(error, AgentLoopError):
# Map error codes to HTTP status codes
status_code = 500
if isinstance(error, (ConfigValidationError, StateError)):
status_code = 400
elif isinstance(error, (SessionError, StateError)):
status_code = 404
return create_error_response(
error_code=error.error_code,
message=error.message,
status_code=status_code,
detail=error.detail,
)
# For non-AgentLoopError exceptions, create a generic error response
return create_error_response(
error_code=ErrorCode.E9001,
message=str(error),
status_code=500,
detail=type(error).__name__,
)
# ========== Rate Limiter ==========
limiter = Limiter(key_func=get_remote_address)
def load_rate_limit_config() -> Dict[str, Any]:
"""Load rate limit configuration from config
Returns:
Dict with rate limit settings
"""
try:
state_manager = StateManager()
config = state_manager.load_config()
rate_limit = config.get("rate_limit", {})
return {
"enabled": rate_limit.get("enabled", True),
"default_limit": rate_limit.get("default_limit", "100/minute"),
"endpoints": rate_limit.get("endpoints", {})
}
except Exception:
return {
"enabled": True,
"default_limit": "100/minute",
"endpoints": {}
}
app = FastAPI(
title="Agent-Loop API",
description="""## Production-Grade REST API for Agent-Loop
This API provides comprehensive endpoints for managing the Agent-Loop autonomous agent system.
### Features
- **Task Management**: Create, read, update, delete, and bulk operations on tasks
- **Session Management**: View session history and stats
- **Agent Control**: Run agent, pause/resume execution
- **Real-time Events**: WebSocket streaming for agent events
- **Health Monitoring**: System health checks with dependency verification
- **Metrics**: Prometheus-compatible metrics endpoint
### Authentication
Use the `X-API-Key` header for API key authentication (when enabled in config).
### Versioning
- Current version: **v1** (prefix: `/api/v1`)
- Legacy routes (without version prefix) are redirected to v1
""",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
)
# Add GZip compression middleware
app.add_middleware(GZipMiddleware, minimum_size=1000)
# Add rate limiter to app state
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# ========== Global Exception Handler ==========
class APIException(Exception):
"""Base API exception with structured error response"""
def __init__(self, message: str, status_code: int = 500, error_code: str = "E0000", detail: Optional[str] = None):
self.message = message
self.status_code = status_code
self.error_code = error_code
self.detail = detail
super().__init__(message)
@app.exception_handler(APIException)
async def api_exception_handler(request: Request, exc: APIException) -> JSONResponse:
"""Handle custom API exceptions with structured error response"""
error_response: Dict[str, Any] = {
"error_code": exc.error_code,
"message": exc.message,
"timestamp": datetime.now().isoformat(),
}
if exc.detail:
error_response["detail"] = exc.detail
return JSONResponse(status_code=exc.status_code, content=error_response)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""Global exception handler for unhandled errors"""
logger.error(f"Unhandled exception: {type(exc).__name__}: {exc}")
# Check if it's already an AgentLoopError handled elsewhere
if isinstance(exc, AgentLoopError):
return handle_agent_error(exc)
error_response: Dict[str, Any] = {
"error_code": "E9001",
"message": "Internal server error",
"timestamp": datetime.now().isoformat(),
"detail": str(exc) if os.environ.get("DEBUG") else "An unexpected error occurred"
}
return JSONResponse(status_code=500, content=error_response)
# ========== Request/Response Logging Middleware ==========
@app.middleware("http")
async def log_requests(request: Request, call_next):
"""Log all requests with method, path, status, duration, and request_id"""
request_id = str(uuid.uuid4())
request.state.request_id = request_id
start_time = time.time()
# Log incoming request
logger.info(
f"Request started",
extra={
"request_id": request_id,
"method": request.method,
"path": request.url.path,
"client_host": request.client.host if request.client else None,
}
)
# Process request
try:
response = await call_next(request)
except Exception as e:
logger.error(
f"Request failed",
extra={
"request_id": request_id,
"method": request.method,
"path": request.url.path,
"error": str(e),
}
)
raise
# Calculate duration
duration_ms = (time.time() - start_time) * 1000
# Log response
logger.info(
f"Request completed",
extra={
"request_id": request_id,
"method": request.method,
"path": request.url.path,
"status_code": response.status_code,
"duration_ms": round(duration_ms, 2),
}
)
# Add request_id to response headers
response.headers["X-Request-ID"] = request_id
return response
def load_cors_config() -> Dict[str, Any]:
"""Load CORS configuration from config
Returns:
Dict with CORS settings
"""
try:
state_manager = StateManager()
config = state_manager.load_config()
cors = config.get("cors", {})
return {
"enabled": cors.get("enabled", True),
"allow_origins": cors.get("allow_origins", []), # Empty means same-origin only
"allow_credentials": cors.get("allow_credentials", False),
"allow_methods": cors.get("allow_methods", ["GET", "POST", "PATCH", "DELETE"]),
"allow_headers": cors.get("allow_headers", ["*"]),
}
except Exception:
# Default: strict same-origin only
return {
"enabled": True,
"allow_origins": [],
"allow_credentials": False,
"allow_methods": ["GET", "POST", "PATCH", "DELETE"],
"allow_headers": ["*"],
}
# Add CORS middleware
cors_config = load_cors_config()
if cors_config["enabled"]:
# If allow_origins is empty, only allow same-origin requests
allow_origins = cors_config["allow_origins"] if cors_config["allow_origins"] else ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=allow_origins,
allow_credentials=cors_config["allow_credentials"],
allow_methods=cors_config["allow_methods"],
allow_headers=cors_config["allow_headers"],
)
logger.info(f"CORS enabled with origins: {allow_origins}")
else:
logger.info("CORS disabled")
# ========== API Versioning ==========
# Create v1 router with /api/v1 prefix
api_v1_router = FastAPI(
title="Agent-Loop API v1",
description="Version 1 of the Agent-Loop REST API",
version="1.0.0",
)
# Global agent state for pause/resume
_agent_paused = False
_agent_instance = None
# Legacy route redirects - redirect old paths to new v1 paths
@app.get("/tasks", tags=["Redirect"])
async def redirect_tasks(request: Request):
"""Redirect /tasks to /api/v1/tasks"""
from fastapi.responses import RedirectResponse
# Preserve query parameters
query = request.url.query
new_url = f"/api/v1/tasks?{query}" if query else "/api/v1/tasks"
return RedirectResponse(url=new_url, status_code=301)
@app.get("/sessions", tags=["Redirect"])
async def redirect_sessions(request: Request):
"""Redirect /sessions to /api/v1/sessions"""
from fastapi.responses import RedirectResponse
# Preserve query parameters
query = request.url.query
new_url = f"/api/v1/sessions?{query}" if query else "/api/v1/sessions"
return RedirectResponse(url=new_url, status_code=301)
@app.get("/status", tags=["Redirect"])
async def redirect_status():
"""Redirect /status to /api/v1/status"""
from fastapi.responses import RedirectResponse
return RedirectResponse(url="/api/v1/status", status_code=301)
@app.get("/run", tags=["Redirect"])
async def redirect_run():
"""Redirect /run to /api/v1/run"""
from fastapi.responses import RedirectResponse
return RedirectResponse(url="/api/v1/run", status_code=301)
# Global state
_agent_instance = None
# ========== API Key Authentication ==========
# Security: Track authentication attempts for monitoring
_auth_attempts: Dict[str, int] = {}
def load_api_keys() -> tuple[bool, List[str]]:
"""Load API keys from config
Returns:
Tuple of (enabled, keys)
"""
try:
state_manager = StateManager()
config = state_manager.load_config()
api_keys_config = config.get("api_keys", {})
enabled = api_keys_config.get("enabled", False)
keys = api_keys_config.get("keys", [])
return enabled, keys
except Exception:
# Default to disabled for security - require explicit enable
return False, []
def get_api_key(x_api_key: str = Header(None, description="API key for authentication")) -> str:
"""Validate API key from request header
Args:
x_api_key: API key from X-API-Key header
Returns:
The validated API key
Raises:
HTTPException: If API key is invalid or missing
Security: Uses unified error response to prevent endpoint enumeration.
Both missing and invalid key return 401 to avoid revealing whether
the endpoint requires authentication or if the key is invalid.
"""
enabled, valid_keys = load_api_keys()
# If API key authentication is not enabled, require explicit opt-in
# For security, we default to requiring auth unless explicitly disabled
if not enabled:
# When disabled, still require a placeholder to prevent accidental exposure
# but accept any non-empty value to allow easier testing
if x_api_key:
return x_api_key
# If explicitly disabled, allow access (legacy behavior for backward compatibility)
return "no-auth"
# Security: Unified error response - don't reveal if endpoint exists
# Both missing key and invalid key return 401 to prevent enumeration
if not x_api_key:
raise HTTPException(
status_code=401,
detail="Authentication required"
)
# Check if API key is valid (constant-time comparison not needed for API keys)
if x_api_key not in valid_keys:
# Log failed attempt for security monitoring (don't include the key)
logger.warning(f"Invalid API key attempt from authentication")
raise HTTPException(
status_code=401,
detail="Authentication required"
)
return x_api_key
# ========== WebSocket Manager ==========
class ConnectionManager:
"""Manages WebSocket connections for real-time event streaming"""
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
"""Accept a new WebSocket connection"""
await websocket.accept()
self.active_connections.append(websocket)
logger.info(f"WebSocket client connected. Total connections: {len(self.active_connections)}")
def disconnect(self, websocket: WebSocket):
"""Remove a WebSocket connection"""
if websocket in self.active_connections:
self.active_connections.remove(websocket)
logger.info(f"WebSocket client disconnected. Total connections: {len(self.active_connections)}")
async def send_message(self, message: Dict[str, Any]):
"""Send a message to all connected clients"""
if not self.active_connections:
return
message_json = json.dumps(message, ensure_ascii=False)
# Send to all active connections
disconnected = []
for connection in self.active_connections:
try:
await connection.send_text(message_json)
except Exception as e:
logger.warning(f"Failed to send to WebSocket: {e}")
disconnected.append(connection)
# Clean up disconnected clients
for conn in disconnected:
self.disconnect(conn)
async def broadcast(self, event_type: str, data: Dict[str, Any]):
"""Broadcast an event to all connected clients"""
message = {
"type": event_type,
"timestamp": datetime.now().isoformat(),
"data": data
}
await self.send_message(message)
# Global WebSocket manager
ws_manager = ConnectionManager()
# ========== Event Pusher ==========
class EventPusher:
"""Singleton class to push events to WebSocket clients"""
_instance = None
_ws_manager: Optional[ConnectionManager] = None
@classmethod
def get_instance(cls) -> "EventPusher":
"""Get the singleton instance"""
if cls._instance is None:
cls._instance = cls()
return cls._instance
@classmethod
def set_ws_manager(cls, manager: ConnectionManager):
"""Set the WebSocket manager"""
cls._ws_manager = manager
async def push_status(self, status: str, message: str, data: Optional[Dict[str, Any]] = None):
"""Push agent status update"""
if self._ws_manager:
await self._ws_manager.broadcast("status", {
"status": status,
"message": message,
"data": data or {}
})
async def push_task_progress(self, task_id: str, progress: str, details: Optional[Dict[str, Any]] = None):
"""Push task progress update"""
if self._ws_manager:
await self._ws_manager.broadcast("task_progress", {
"task_id": task_id,
"progress": progress,
"details": details or {}
})
async def push_log(self, level: str, message: str, source: Optional[str] = None):
"""Push log message"""
if self._ws_manager:
await self._ws_manager.broadcast("log", {
"level": level,
"message": message,
"source": source
})
async def push_iteration(self, iteration: int, total: int, task: Optional[str] = None):
"""Push iteration update"""
if self._ws_manager:
await self._ws_manager.broadcast("iteration", {
"current": iteration,
"total": total,
"task": task
})
# Initialize EventPusher with ws_manager
EventPusher.set_ws_manager(ws_manager)
# ========== Request/Response Models ==========
# Input validation constants
MAX_TASK_NAME_LENGTH = 200
MAX_DESCRIPTION_LENGTH = 2000
MAX_ID_LENGTH = 50
# Whitelist for allowed characters in task names (alphanumeric, dash, underscore, space)
VALID_TASK_NAME_PATTERN = r'^[\w\s\-]+$'
class TaskCreate(BaseModel):
"""Task creation request model with input validation"""
id: Optional[str] = None
name: str
description: Optional[str] = None
priority: Optional[int] = 99
depends_on: Optional[List[str]] = None
@field_validator('name')
@classmethod
def validate_name(cls, v: str, info: ValidationInfo) -> str:
"""Validate and sanitize task name"""
if not v or not v.strip():
raise ValueError("Task name cannot be empty")
# Check length
if len(v) > MAX_TASK_NAME_LENGTH:
raise ValueError(f"Task name cannot exceed {MAX_TASK_NAME_LENGTH} characters")
# Check for valid characters (alphanumeric, dash, underscore, space)
import re
if not re.match(VALID_TASK_NAME_PATTERN, v):
raise ValueError("Task name can only contain letters, numbers, spaces, dashes, and underscores")
# Strip and return sanitized name
return v.strip()
@field_validator('description')
@classmethod
def validate_description(cls, v: Optional[str], info: ValidationInfo) -> Optional[str]:
"""Validate and sanitize task description"""
if v is None:
return None
# Check length
if len(v) > MAX_DESCRIPTION_LENGTH:
raise ValueError(f"Description cannot exceed {MAX_DESCRIPTION_LENGTH} characters")
# Strip and return
return v.strip()
@field_validator('id')
@classmethod
def validate_id(cls, v: Optional[str], info: ValidationInfo) -> Optional[str]:
"""Validate task ID format"""
if v is None:
return None
if len(v) > MAX_ID_LENGTH:
raise ValueError(f"Task ID cannot exceed {MAX_ID_LENGTH} characters")
# Only allow alphanumeric, dash, underscore
import re
if not re.match(r'^[\w\-]+$', v):
raise ValueError("Task ID can only contain letters, numbers, dashes, and underscores")
return v.strip()
@field_validator('priority')
@classmethod
def validate_priority(cls, v: Optional[int], info: ValidationInfo) -> Optional[int]:
"""Validate priority value"""
if v is None:
return 99
if not isinstance(v, int):
raise ValueError("Priority must be an integer")
if v < 1 or v > 99:
raise ValueError("Priority must be between 1 and 99")
return v
@field_validator('depends_on')
@classmethod
def validate_depends_on(cls, v: Optional[List[str]], info: ValidationInfo) -> Optional[List[str]]:
"""Validate depends_on field"""
if v is None:
return None
if not isinstance(v, list):
raise ValueError("depends_on must be a list")
# Check for empty strings and duplicates
seen = set()
for dep_id in v:
if not dep_id or not dep_id.strip():
raise ValueError("depends_on cannot contain empty IDs")
if dep_id in seen:
raise ValueError(f"Duplicate dependency: {dep_id}")
seen.add(dep_id)
return v
class TaskResponse(BaseModel):
"""Task response model"""
id: str
name: str
description: str
priority: int
status: str
passes: bool
created_at: str
updated_at: str
verify_command: Optional[str] = None
context_files: Optional[List[str]] = None
depends_on: Optional[List[str]] = None
class TaskUpdate(BaseModel):
"""Task update request model with validation"""
priority: Optional[int] = None
status: Optional[str] = None
passes: Optional[bool] = None
@field_validator('status')
@classmethod
def validate_status(cls, v: Optional[str], info: ValidationInfo) -> Optional[str]:
"""Validate status value"""
if v is None:
return v
valid_statuses = {"pending", "completed", "failed", "in_progress"}
if v not in valid_statuses:
raise ValueError(f"Status must be one of: {', '.join(valid_statuses)}")
return v
@field_validator('priority')
@classmethod
def validate_priority(cls, v: Optional[int], info: ValidationInfo) -> Optional[int]:
"""Validate priority value"""
if v is None:
return v
if not isinstance(v, int):
raise ValueError("Priority must be an integer")
if v < 1 or v > 99:
raise ValueError("Priority must be between 1 and 99")
return v
class StatusResponse(BaseModel):
"""Agent status response model"""
project_name: str
project_type: str
test_command: str
git_branch: str
has_changes: bool
tasks_completed: int
tasks_total: int
tasks_pending: int
current_session: Optional[Dict[str, Any]]
error_count: int
class SessionResponse(BaseModel):
"""Session history response model"""
total_sessions: int
completed_sessions: int
sessions: List[Dict[str, Any]]
class PaginatedTaskResponse(BaseModel):
"""Paginated task list response"""
items: List[TaskResponse]
page: int
per_page: int
total: int
total_pages: int
class PaginatedSessionResponse(BaseModel):
"""Paginated session list response"""
items: List[Dict[str, Any]]
page: int
per_page: int
total: int
total_pages: int
class SessionStatsResponse(BaseModel):
"""Session statistics response"""
summary: Dict[str, Any]
duration: Dict[str, Any]
errors: Dict[str, int]
tags: Dict[str, int]
trends: Dict[str, List[Dict[str, Any]]]
archive_info: Dict[str, Any]
class TaskDeleteResponse(BaseModel):
"""Task deletion response"""
success: bool
message: str
task_id: str
deleted_archived: bool = False
class BulkTaskOperation(BaseModel):
"""Bulk task operation request"""
operations: List[Dict[str, Any]]
class BulkTaskResponse(BaseModel):
"""Bulk task operation response"""
success: bool
created: int
updated: int
deleted: int
errors: List[Dict[str, str]]
class AgentControlResponse(BaseModel):
"""Agent control response"""
success: bool
message: str
state: str
class HealthCheckResponse(BaseModel):
"""Enhanced health check response"""
status: str
service: str
timestamp: str
dependencies: Dict[str, Any]
class RunRequest(BaseModel):
"""Agent run request model"""
iterations: Optional[int] = 10
class RunResponse(BaseModel):
"""Agent run response model"""
success: bool
message: str
iterations: int
completed: int
errors: int
class LogLevelRequest(BaseModel):
"""Request model for changing log level"""
level: str
lock: bool = False
class LogLevelResponse(BaseModel):
"""Response model for log level change"""
success: bool
current_level: str
locked: bool
message: str
# ========== XSS Sanitization ==========
def sanitize_for_html(text: str) -> str:
"""Sanitize text for safe HTML output
Args:
text: Input text to sanitize
Returns:
Sanitized text safe for HTML display
"""
if not text:
return ""
# Use bleach to strip dangerous HTML tags
return bleach.clean(text, tags=[], strip=True)
def sanitize_task_response(task: Dict[str, Any]) -> Dict[str, Any]:
"""Sanitize task data for safe API response
Args:
task: Task dictionary
Returns:
Sanitized task dictionary
"""
sanitized = task.copy()
# Sanitize string fields that might be displayed in HTML
for field in ['name', 'description', 'verify_command']:
if field in sanitized and sanitized[field]:
sanitized[field] = sanitize_for_html(str(sanitized[field]))
return sanitized
# ========== API Endpoints ==========
@app.get("/status", response_model=StatusResponse)
@app.get("/api/v1/status", response_model=StatusResponse, tags=["Status"])
@limiter.limit("60/minute")
def get_status(request: Request, api_key: str = Depends(get_api_key)) -> StatusResponse:
"""Get current Agent status including project info, git status, and task statistics.
Returns:
- Project name and type
- Git branch and changes status
- Task counts (completed, pending, total)
- Current session info
- Error count
"""
try:
state_manager = StateManager()
git_helper = GitHelper()
task_selector = TaskSelector(state_manager)
# Get config
config = state_manager.load_config()
# Get state
state = state_manager.load_state()
# Get task stats
completed = task_selector.get_completed_count()
total = task_selector.get_total_count()
pending = task_selector.get_pending_count()
return StatusResponse(
project_name=config.get("project_name", "N/A"),
project_type=config.get("project_type", "N/A"),
test_command=config.get("test_command", "N/A"),
git_branch=git_helper.get_current_branch() or "N/A",
has_changes=git_helper.has_changes(),
tasks_completed=completed,
tasks_total=total,
tasks_pending=pending,
current_session=state.get("current_session"),
error_count=state.get("error_count", 0)
)
except AgentLoopError as e:
logger.error(f"Agent error getting status: {e}")
raise handle_agent_error(e)
except Exception as e:
logger.error(f"Error getting status: {e}")
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=500, detail=str(e))
@app.get("/tasks", response_model=PaginatedTaskResponse)
@app.get("/api/v1/tasks", response_model=PaginatedTaskResponse, tags=["Tasks"])
@limiter.limit("60/minute")
def get_tasks(
request: Request,
status_filter: Optional[str] = None,
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
api_key: str = Depends(get_api_key)
) -> PaginatedTaskResponse:
"""Get task list with pagination support, optionally filtered by status.
- **page**: Page number (starting from 1)
- **per_page**: Number of items per page (max 100)
- **status_filter**: Filter by task status (pending, completed, failed, in_progress)
"""
try:
state_manager = StateManager()
data = state_manager.load_feature_list()
features = data.get("features", [])
# Filter by status if provided (exclude archived unless explicitly requested)
if status_filter and status_filter != "all":
features = [f for f in features if f.get("status") == status_filter]
else:
# By default, exclude archived tasks
features = [f for f in features if f.get("status") != "archived"]
# Sort by priority
features.sort(key=lambda x: x.get("priority", 99))
total = len(features)
total_pages = (total + per_page - 1) // per_page if total > 0 else 1
# Calculate pagination
start_idx = (page - 1) * per_page
end_idx = start_idx + per_page
paginated_features = features[start_idx:end_idx]
return PaginatedTaskResponse(
items=[
TaskResponse(
id=f.get("id", ""),
name=f.get("name", ""),
description=f.get("description", ""),
priority=f.get("priority", 99),
status=f.get("status", "pending"),
passes=f.get("passes", False),
created_at=f.get("created_at", ""),
updated_at=f.get("updated_at", ""),
depends_on=f.get("depends_on")
)
for f in paginated_features
],
page=page,
per_page=per_page,
total=total,
total_pages=total_pages
)
except AgentLoopError as e:
logger.error(f"Agent error getting tasks: {e}")
raise handle_agent_error(e)
except Exception as e:
logger.error(f"Error getting tasks: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/tasks", response_model=TaskResponse, status_code=201)
@limiter.limit("30/minute")
def create_task(request: Request, task: TaskCreate, api_key: str = Depends(get_api_key)) -> TaskResponse:
"""Add a new task"""
try:
state_manager = StateManager()
# Generate ID if not provided
task_id = task.id
if not task_id:
existing_features = state_manager.load_feature_list().get("features", [])
task_id = f"task-{len(existing_features) + 1:03d}"