Fix type annotation gaps in coordinator-api routers

- Add return type annotations to all async functions
- Add argument type annotations to functions missing them
- Add missing imports for typing (Any, Annotated, etc.)
- Add missing imports for FastAPI components (Query, Body, HTTPException)
- Fix validator functions in bounty.py and staking.py
- Fix dependency injection functions in agent_identity.py
- All 236 Ruff ANN001/ANN201 errors resolved across 26 files
This commit is contained in:
aitbc
2026-04-30 10:24:17 +02:00
parent ed128014c6
commit 09b0edc212
27 changed files with 267 additions and 240 deletions

View File

@@ -17,6 +17,7 @@ from aitbc import get_logger
logger = get_logger(__name__)
from ..domain.agent_performance import CreativeCapability
from sqlmodel import select
from ..services.creative_capabilities_service import (
CreativityEnhancementEngine,
CrossDomainCreativeIntegrator,
@@ -82,7 +83,7 @@ class SynthesisRequest(BaseModel):
@router.post("/capabilities", response_model=CreativeCapabilityResponse)
async def create_creative_capability(request: CreativeCapabilityCreate, session: Annotated[Session, Depends(get_session)]):
async def create_creative_capability(request: CreativeCapabilityCreate, session: Annotated[Session, Depends(get_session)]) -> CreativeCapabilityResponse:
"""Initialize a new creative capability for an agent"""
engine = CreativityEnhancementEngine()
@@ -105,7 +106,7 @@ async def create_creative_capability(request: CreativeCapabilityCreate, session:
@router.post("/capabilities/{capability_id}/enhance")
async def enhance_creativity(
capability_id: str, request: EnhanceCreativityRequest, session: Annotated[Session, Depends(get_session)]
):
) -> dict[str, Any]:
"""Enhance a specific creative capability using specified algorithm"""
engine = CreativityEnhancementEngine()
@@ -124,7 +125,7 @@ async def enhance_creativity(
@router.post("/capabilities/{capability_id}/evaluate")
async def evaluate_creation(
capability_id: str, request: EvaluateCreationRequest, session: Annotated[Session, Depends(get_session)]
):
) -> dict[str, Any]:
"""Evaluate a creative output and update agent capability metrics"""
engine = CreativityEnhancementEngine()
@@ -144,7 +145,7 @@ async def evaluate_creation(
@router.post("/ideation/generate")
async def generate_ideas(request: IdeationRequest):
async def generate_ideas(request: IdeationRequest) -> dict[str, Any]:
"""Generate innovative ideas using specialized ideation algorithms"""
ideation_engine = IdeationAlgorithm()
@@ -163,7 +164,7 @@ async def generate_ideas(request: IdeationRequest):
@router.post("/synthesis/cross-domain")
async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[Session, Depends(get_session)]):
async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[Session, Depends(get_session)]) -> dict[str, Any]:
"""Synthesize concepts from multiple domains to create novel outputs"""
integrator = CrossDomainCreativeIntegrator()
@@ -184,7 +185,7 @@ async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[
@router.get("/capabilities/{agent_id}")
async def list_agent_creative_capabilities(agent_id: str, session: Annotated[Session, Depends(get_session)]):
async def list_agent_creative_capabilities(agent_id: str, session: Annotated[Session, Depends(get_session)]) -> list[CreativeCapability]:
"""List all creative capabilities for a specific agent"""
try:
capabilities = session.execute(select(CreativeCapability).where(CreativeCapability.agent_id == agent_id)).all()

View File

@@ -20,7 +20,7 @@ from ..storage.db import get_session
router = APIRouter(prefix="/agent-identity", tags=["Agent Identity"])
def get_identity_manager(session=Depends(get_session)) -> AgentIdentityManager:
def get_identity_manager(session: Session = Depends(get_session)) -> AgentIdentityManager:
"""Dependency injection for AgentIdentityManager"""
return AgentIdentityManager(session)
@@ -29,7 +29,7 @@ def get_identity_manager(session=Depends(get_session)) -> AgentIdentityManager:
@router.post("/identities", response_model=dict[str, Any])
async def create_agent_identity(request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)):
async def create_agent_identity(request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)) -> JSONResponse:
"""Create a new agent identity with cross-chain mappings"""
try:
result = await manager.create_agent_identity(
@@ -46,7 +46,7 @@ async def create_agent_identity(request: dict[str, Any], manager: AgentIdentityM
@router.get("/identities/{agent_id}", response_model=dict[str, Any])
async def get_agent_identity(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_agent_identity(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get comprehensive agent identity summary"""
try:
result = await manager.get_agent_identity_summary(agent_id)
@@ -62,7 +62,7 @@ async def get_agent_identity(agent_id: str, manager: AgentIdentityManager = Depe
@router.put("/identities/{agent_id}", response_model=dict[str, Any])
async def update_agent_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Update agent identity and related components"""
try:
result = await manager.update_agent_identity(agent_id, request)
@@ -78,7 +78,7 @@ async def update_agent_identity(
@router.post("/identities/{agent_id}/deactivate", response_model=dict[str, Any])
async def deactivate_agent_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Deactivate an agent identity across all chains"""
try:
reason = request.get("reason", "")
@@ -98,7 +98,7 @@ async def deactivate_agent_identity(
@router.post("/identities/{agent_id}/cross-chain/register", response_model=dict[str, Any])
async def register_cross_chain_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Register cross-chain identity mappings"""
try:
chain_mappings = request["chain_mappings"]
@@ -115,7 +115,7 @@ async def register_cross_chain_identity(
@router.get("/identities/{agent_id}/cross-chain/mapping", response_model=list[CrossChainMappingResponse])
async def get_cross_chain_mapping(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_cross_chain_mapping(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> list[CrossChainMappingResponse]:
"""Get all cross-chain mappings for an agent"""
try:
mappings = await manager.registry.get_all_cross_chain_mappings(agent_id)
@@ -145,7 +145,7 @@ async def get_cross_chain_mapping(agent_id: str, manager: AgentIdentityManager =
@router.put("/identities/{agent_id}/cross-chain/{chain_id}", response_model=dict[str, Any])
async def update_cross_chain_mapping(
agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Update cross-chain mapping for a specific chain"""
try:
new_address = request.get("new_address")
@@ -175,7 +175,7 @@ async def update_cross_chain_mapping(
@router.post("/identities/{agent_id}/cross-chain/{chain_id}/verify", response_model=dict[str, Any])
async def verify_cross_chain_identity(
agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Verify identity on a specific blockchain"""
try:
# Get identity ID
@@ -209,7 +209,7 @@ async def verify_cross_chain_identity(
@router.post("/identities/{agent_id}/migrate", response_model=dict[str, Any])
async def migrate_agent_identity(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Migrate agent identity from one chain to another"""
try:
result = await manager.migrate_agent_identity(
@@ -226,7 +226,7 @@ async def migrate_agent_identity(
@router.post("/identities/{agent_id}/wallets", response_model=dict[str, Any])
async def create_agent_wallet(
agent_id: str, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Create an agent wallet on a specific blockchain"""
try:
wallet = await manager.wallet_adapter.create_agent_wallet(
@@ -247,7 +247,7 @@ async def create_agent_wallet(
@router.get("/identities/{agent_id}/wallets/{chain_id}/balance", response_model=dict[str, Any])
async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get wallet balance for an agent on a specific chain"""
try:
balance = await manager.wallet_adapter.get_wallet_balance(agent_id, chain_id)
@@ -264,7 +264,7 @@ async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentit
@router.post("/identities/{agent_id}/wallets/{chain_id}/transactions", response_model=dict[str, Any])
async def execute_wallet_transaction(
agent_id: str, chain_id: int, request: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Execute a transaction from agent wallet"""
try:
from decimal import Decimal
@@ -284,7 +284,7 @@ async def get_wallet_transaction_history(
limit: int = Query(default=50, ge=1, le=1000),
offset: int = Query(default=0, ge=0),
manager: AgentIdentityManager = Depends(get_identity_manager),
):
) -> list[dict[str, Any]]:
"""Get transaction history for agent wallet"""
try:
history = await manager.wallet_adapter.get_wallet_transaction_history(agent_id, chain_id, limit, offset)
@@ -294,7 +294,7 @@ async def get_wallet_transaction_history(
@router.get("/identities/{agent_id}/wallets", response_model=dict[str, Any])
async def get_all_agent_wallets(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_all_agent_wallets(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get all wallets for an agent across all chains"""
try:
wallets = await manager.wallet_adapter.get_all_agent_wallets(agent_id)
@@ -339,7 +339,7 @@ async def search_agent_identities(
limit: int = Query(default=50, ge=1, le=100),
offset: int = Query(default=0, ge=0),
manager: AgentIdentityManager = Depends(get_identity_manager),
):
) -> dict[str, Any]:
"""Search agent identities with advanced filters"""
try:
result = await manager.search_agent_identities(
@@ -357,7 +357,7 @@ async def search_agent_identities(
@router.post("/identities/{agent_id}/sync-reputation", response_model=dict[str, Any])
async def sync_agent_reputation(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)):
async def sync_agent_reputation(agent_id: str, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Sync agent reputation across all chains"""
try:
result = await manager.sync_agent_reputation(agent_id)
@@ -370,7 +370,7 @@ async def sync_agent_reputation(agent_id: str, manager: AgentIdentityManager = D
@router.get("/registry/health", response_model=dict[str, Any])
async def get_registry_health(manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_registry_health(manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get health status of the identity registry"""
try:
result = await manager.get_registry_health()
@@ -380,7 +380,7 @@ async def get_registry_health(manager: AgentIdentityManager = Depends(get_identi
@router.get("/registry/statistics", response_model=dict[str, Any])
async def get_registry_statistics(manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_registry_statistics(manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Get comprehensive registry statistics"""
try:
result = await manager.registry.get_registry_statistics()
@@ -390,7 +390,7 @@ async def get_registry_statistics(manager: AgentIdentityManager = Depends(get_id
@router.get("/chains/supported", response_model=list[dict[str, Any]])
async def get_supported_chains(manager: AgentIdentityManager = Depends(get_identity_manager)):
async def get_supported_chains(manager: AgentIdentityManager = Depends(get_identity_manager)) -> list[dict[str, Any]]:
"""Get list of supported blockchains"""
try:
chains = manager.wallet_adapter.get_supported_chains()
@@ -402,7 +402,7 @@ async def get_supported_chains(manager: AgentIdentityManager = Depends(get_ident
@router.post("/identities/{agent_id}/export", response_model=dict[str, Any])
async def export_agent_identity(
agent_id: str, request: dict[str, Any] = None, manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Export agent identity data for backup or migration"""
try:
format_type = (request or {}).get("format", "json")
@@ -413,7 +413,7 @@ async def export_agent_identity(
@router.post("/identities/import", response_model=dict[str, Any])
async def import_agent_identity(export_data: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)):
async def import_agent_identity(export_data: dict[str, Any], manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Import agent identity data from backup or migration"""
try:
result = await manager.import_agent_identity(export_data)
@@ -423,7 +423,7 @@ async def import_agent_identity(export_data: dict[str, Any], manager: AgentIdent
@router.post("/registry/cleanup-expired", response_model=dict[str, Any])
async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(get_identity_manager)):
async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Clean up expired verification records"""
try:
cleaned_count = await manager.registry.cleanup_expired_verifications()
@@ -435,7 +435,7 @@ async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(
@router.post("/identities/batch-verify", response_model=list[dict[str, Any]])
async def batch_verify_identities(
verifications: list[dict[str, Any]], manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> list[dict[str, Any]]:
"""Batch verify multiple identities"""
try:
results = await manager.registry.batch_verify_identities(verifications)
@@ -445,7 +445,7 @@ async def batch_verify_identities(
@router.get("/identities/{agent_id}/resolve/{chain_id}", response_model=dict[str, Any])
async def resolve_agent_identity(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)):
async def resolve_agent_identity(agent_id: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)) -> dict[str, Any]:
"""Resolve agent identity to chain-specific address"""
try:
address = await manager.registry.resolve_agent_identity(agent_id, chain_id)
@@ -462,7 +462,7 @@ async def resolve_agent_identity(agent_id: str, chain_id: int, manager: AgentIde
@router.get("/address/{chain_address}/resolve/{chain_id}", response_model=dict[str, Any])
async def resolve_address_to_agent(
chain_address: str, chain_id: int, manager: AgentIdentityManager = Depends(get_identity_manager)
):
) -> dict[str, Any]:
"""Resolve chain address back to agent ID"""
try:
agent_id = await manager.registry.resolve_agent_identity_by_address(chain_address, chain_id)

View File

@@ -37,7 +37,7 @@ async def create_deployment_config(
deployment_config: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentDeploymentConfig:
"""Create deployment configuration for agent workflow"""
try:
@@ -70,7 +70,7 @@ async def list_deployment_configs(
status: DeploymentStatus | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AgentDeploymentConfig]:
"""List deployment configurations with filtering"""
try:
@@ -103,7 +103,7 @@ async def get_deployment_config(
config_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentDeploymentConfig:
"""Get specific deployment configuration"""
try:
@@ -131,7 +131,7 @@ async def deploy_workflow(
target_environment: str = "production",
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Deploy agent workflow to target environment"""
try:
@@ -164,7 +164,7 @@ async def get_deployment_health(
config_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Get health status of deployment"""
try:
@@ -195,7 +195,7 @@ async def scale_deployment(
target_instances: int,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Scale deployment to target number of instances"""
try:
@@ -228,7 +228,7 @@ async def rollback_deployment(
config_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Rollback deployment to previous version"""
try:
@@ -261,7 +261,7 @@ async def list_deployment_instances(
status: DeploymentStatus | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AgentDeploymentInstance]:
"""List deployment instances with filtering"""
try:
@@ -299,7 +299,7 @@ async def get_deployment_instance(
instance_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentDeploymentInstance:
"""Get specific deployment instance"""
try:
@@ -331,7 +331,7 @@ async def integrate_with_zk_system(
verification_level: VerificationLevel = VerificationLevel.BASIC,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Integrate agent execution with ZK proof system"""
try:
@@ -365,7 +365,7 @@ async def get_deployment_metrics(
time_range: str = "1h",
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Get metrics for deployment over time range"""
try:
@@ -397,7 +397,7 @@ async def deploy_to_production(
integration_config: dict | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Deploy agent workflow to production with full integration"""
try:
@@ -427,7 +427,7 @@ async def deploy_to_production(
@router.get("/production/dashboard")
async def get_production_dashboard(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
):
) -> dict[str, Any]:
"""Get comprehensive production dashboard data"""
try:
@@ -481,7 +481,7 @@ async def get_production_dashboard(
@router.get("/production/health")
async def get_production_health(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
):
) -> dict[str, Any]:
"""Get overall production health status"""
try:
@@ -553,7 +553,7 @@ async def get_production_alerts(
severity: str | None = None,
limit: int = 50,
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Get production alerts and notifications"""
try:

View File

@@ -8,6 +8,7 @@ Provides REST API endpoints for agent workflow management and execution
"""
from datetime import datetime, UTC
from typing import Any
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
@@ -38,7 +39,7 @@ async def create_workflow(
workflow_data: AgentWorkflowCreate,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AIAgentWorkflow:
"""Create a new AI agent workflow"""
try:
@@ -63,7 +64,7 @@ async def list_workflows(
tags: list[str] | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AIAgentWorkflow]:
"""List agent workflows with filtering"""
try:
@@ -97,7 +98,7 @@ async def get_workflow(
workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AIAgentWorkflow:
"""Get a specific agent workflow"""
try:
@@ -124,7 +125,7 @@ async def update_workflow(
workflow_data: AgentWorkflowUpdate,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AIAgentWorkflow:
"""Update an agent workflow"""
try:
@@ -160,7 +161,7 @@ async def delete_workflow(
workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, str]:
"""Delete an agent workflow"""
try:
@@ -192,7 +193,7 @@ async def execute_workflow(
background_tasks: BackgroundTasks,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentExecutionResponse:
"""Execute an AI agent workflow"""
try:
@@ -236,7 +237,7 @@ async def get_execution_status(
execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentExecutionStatus:
"""Get execution status"""
try:
@@ -270,7 +271,7 @@ async def list_executions(
offset: int = 0,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AgentExecutionStatus]:
"""List agent executions with filtering"""
try:
@@ -328,7 +329,7 @@ async def cancel_execution(
execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, str]:
"""Cancel an ongoing execution"""
try:
@@ -368,7 +369,7 @@ async def get_execution_logs(
execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Get execution logs"""
try:
@@ -422,7 +423,7 @@ async def get_execution_logs(
@router.get("/test")
async def test_endpoint():
async def test_endpoint() -> dict[str, str]:
"""Test endpoint to verify router is working"""
return {"message": "Agent router is working", "timestamp": datetime.now(datetime.UTC).isoformat()}
@@ -432,7 +433,7 @@ async def create_agent_network(
network_data: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Create a new agent network for collaborative processing"""
try:
@@ -472,7 +473,7 @@ async def get_execution_receipt(
execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Get verifiable receipt for completed execution"""
try:

View File

@@ -41,7 +41,7 @@ async def create_security_policy(
policy_rules: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentSecurityPolicy:
"""Create a new security policy"""
try:
@@ -64,7 +64,7 @@ async def list_security_policies(
is_active: bool | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AgentSecurityPolicy]:
"""List security policies with filtering"""
try:
@@ -89,7 +89,7 @@ async def get_security_policy(
policy_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentSecurityPolicy:
"""Get a specific security policy"""
try:
@@ -112,7 +112,7 @@ async def update_security_policy(
policy_updates: dict,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentSecurityPolicy:
"""Update a security policy"""
try:
@@ -154,7 +154,7 @@ async def delete_security_policy(
policy_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, str]:
"""Delete a security policy"""
try:
@@ -190,7 +190,7 @@ async def validate_workflow_security(
workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Validate workflow security requirements"""
try:
@@ -228,7 +228,7 @@ async def list_audit_logs(
offset: int = 0,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AgentAuditLog]:
"""List audit logs with filtering"""
try:
@@ -271,7 +271,7 @@ async def get_audit_log(
audit_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentAuditLog:
"""Get a specific audit log entry"""
try:
@@ -299,7 +299,7 @@ async def list_trust_scores(
offset: int = 0,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> list[AgentTrustScore]:
"""List trust scores with filtering"""
try:
@@ -335,7 +335,7 @@ async def get_trust_score(
entity_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentTrustScore:
"""Get trust score for specific entity"""
try:
@@ -369,7 +369,7 @@ async def update_trust_score(
policy_violation: bool = False,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentTrustScore:
"""Update trust score based on execution results"""
try:
@@ -415,7 +415,7 @@ async def create_sandbox(
workflow_requirements: dict | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Create sandbox environment for agent execution"""
try:
@@ -451,7 +451,7 @@ async def monitor_sandbox(
execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Monitor sandbox execution for security violations"""
try:
@@ -470,7 +470,7 @@ async def cleanup_sandbox(
execution_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Clean up sandbox environment after execution"""
try:
@@ -500,7 +500,7 @@ async def monitor_execution_security(
workflow_id: str,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Monitor execution for security violations"""
try:
@@ -517,7 +517,7 @@ async def monitor_execution_security(
@router.get("/security-dashboard")
async def get_security_dashboard(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
):
) -> dict[str, Any]:
"""Get comprehensive security dashboard data"""
try:
@@ -572,7 +572,7 @@ async def get_security_dashboard(
@router.get("/security-stats")
async def get_security_statistics(
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
):
) -> dict[str, Any]:
"""Get security statistics and metrics"""
try:

View File

@@ -1,5 +1,7 @@
from __future__ import annotations
from typing import Any
from fastapi import APIRouter
from aitbc import get_logger, AITBCHTTPClient, NetworkError
@@ -11,7 +13,7 @@ router = APIRouter(tags=["blockchain"])
@router.get("/status")
async def blockchain_status():
async def blockchain_status() -> dict[str, Any]:
"""Get blockchain status."""
try:
from ..config import settings
@@ -32,7 +34,7 @@ async def blockchain_status():
@router.get("/sync-status")
async def blockchain_sync_status():
async def blockchain_sync_status() -> dict[str, Any]:
"""Get blockchain synchronization status."""
try:
from ..config import settings

View File

@@ -47,7 +47,7 @@ class BountyCreateRequest(BaseModel):
difficulty: Optional[str] = Field(default=None)
@validator('deadline')
def validate_deadline(cls, v):
def validate_deadline(cls, v: datetime) -> datetime:
if v <= datetime.now(datetime.UTC):
raise ValueError('Deadline must be in the future')
if v > datetime.now(datetime.UTC) + timedelta(days=365):
@@ -55,7 +55,7 @@ class BountyCreateRequest(BaseModel):
return v
@validator('reward_amount')
def validate_reward_amount(cls, v, values):
def validate_reward_amount(cls, v: float, values: dict[str, Any]) -> float:
tier = values.get('tier', BountyTier.BRONZE)
tier_minimums = {
BountyTier.BRONZE: 100.0,
@@ -184,7 +184,7 @@ async def create_bounty(
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> BountyResponse:
"""Create a new bounty"""
try:
logger.info(f"Creating bounty: {request.title} by user {current_user['address']}")
@@ -215,7 +215,7 @@ async def get_bounties(
session: Session = Depends(get_session),
filters: BountyFilterRequest = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> List[BountyResponse]:
"""Get filtered list of bounties"""
try:
bounties = await bounty_service.get_bounties(
@@ -244,7 +244,7 @@ async def get_bounty(
bounty_id: str,
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> BountyResponse:
"""Get bounty details"""
try:
bounty = await bounty_service.get_bounty(bounty_id)
@@ -268,7 +268,7 @@ async def submit_bounty_solution(
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> BountySubmissionResponse:
"""Submit a solution to a bounty"""
try:
logger.info(f"Submitting solution for bounty {bounty_id} by {current_user['address']}")
@@ -316,7 +316,7 @@ async def get_bounty_submissions(
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user)
):
) -> List[BountySubmissionResponse]:
"""Get all submissions for a bounty"""
try:
# Check if user is bounty creator or has permission
@@ -347,7 +347,7 @@ async def verify_bounty_submission(
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, str]:
"""Verify a bounty submission (oracle/admin only)"""
try:
# Check permissions
@@ -387,7 +387,7 @@ async def dispute_bounty_submission(
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, str]:
"""Dispute a bounty submission"""
try:
# Create dispute
@@ -421,7 +421,7 @@ async def get_my_created_bounties(
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user)
):
) -> List[BountyResponse]:
"""Get bounties created by the current user"""
try:
bounties = await bounty_service.get_user_created_bounties(
@@ -445,7 +445,7 @@ async def get_my_submissions(
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user)
):
) -> List[BountySubmissionResponse]:
"""Get submissions made by the current user"""
try:
submissions = await bounty_service.get_user_submissions(
@@ -467,7 +467,7 @@ async def get_bounty_leaderboard(
limit: int = Field(default=50, ge=1, le=100),
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> Dict[str, Any]:
"""Get bounty leaderboard"""
try:
leaderboard = await bounty_service.get_leaderboard(
@@ -486,7 +486,7 @@ async def get_bounty_stats(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> BountyStatsResponse:
"""Get bounty statistics"""
try:
stats = await bounty_service.get_bounty_stats(period=period)
@@ -505,7 +505,7 @@ async def expire_bounty(
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, str]:
"""Expire a bounty (creator only)"""
try:
# Check if user is bounty creator
@@ -543,7 +543,7 @@ async def expire_bounty(
async def get_bounty_categories(
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> Dict[str, Any]:
"""Get all bounty categories"""
try:
categories = await bounty_service.get_categories()
@@ -558,7 +558,7 @@ async def get_bounty_tags(
limit: int = Field(default=100, ge=1, le=500),
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> Dict[str, Any]:
"""Get popular bounty tags"""
try:
tags = await bounty_service.get_popular_tags(limit=limit)
@@ -575,7 +575,7 @@ async def search_bounties(
limit: int = Field(default=20, ge=1, le=100),
session: Session = Depends(get_session),
bounty_service: BountyService = Depends(get_bounty_service)
):
) -> List[BountyResponse]:
"""Search bounties by text"""
try:
bounties = await bounty_service.search_bounties(

View File

@@ -2,6 +2,8 @@
Cache monitoring and management endpoints
"""
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
@@ -20,7 +22,7 @@ router = APIRouter(prefix="/cache", tags=["cache-management"])
@router.get("/stats", summary="Get cache statistics")
@limiter.limit(lambda: settings.rate_limit_admin_stats)
async def get_cache_statistics(request: Request, admin_key: str = Depends(require_admin_key())):
async def get_cache_statistics(request: Request, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Get cache performance statistics"""
try:
stats = get_cache_stats()
@@ -32,7 +34,7 @@ async def get_cache_statistics(request: Request, admin_key: str = Depends(requir
@router.post("/clear", summary="Clear cache entries")
@limiter.limit(lambda: settings.rate_limit_admin_stats)
async def clear_cache_entries(request: Request, pattern: str = None, admin_key: str = Depends(require_admin_key())):
async def clear_cache_entries(request: Request, pattern: str = None, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Clear cache entries (all or matching pattern)"""
try:
result = clear_cache(pattern)
@@ -45,7 +47,7 @@ async def clear_cache_entries(request: Request, pattern: str = None, admin_key:
@router.post("/warm", summary="Warm up cache")
@limiter.limit(lambda: settings.rate_limit_admin_stats)
async def warm_up_cache(request: Request, admin_key: str = Depends(require_admin_key())):
async def warm_up_cache(request: Request, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Trigger cache warming for common queries"""
try:
result = warm_cache()
@@ -58,7 +60,7 @@ async def warm_up_cache(request: Request, admin_key: str = Depends(require_admin
@router.get("/health", summary="Get cache health status")
@limiter.limit(lambda: settings.rate_limit_admin_stats)
async def cache_health_check(request: Request, admin_key: str = Depends(require_admin_key())):
async def cache_health_check(request: Request, admin_key: str = Depends(require_admin_key())) -> dict[str, Any]:
"""Get detailed cache health information"""
try:
from ..utils.cache import cache_manager

View File

@@ -84,7 +84,7 @@ class HackathonCreateRequest(BaseModel):
# Endpoints - Developer Ecosystem
@router.post("/developers", response_model=DeveloperProfile)
async def create_developer_profile(request: DeveloperProfileCreate, session: Annotated[Session, Depends(get_session)]):
async def create_developer_profile(request: DeveloperProfileCreate, session: Annotated[Session, Depends(get_session)]) -> DeveloperProfile:
"""Register a new developer in the OpenClaw ecosystem"""
service = DeveloperEcosystemService(session)
try:
@@ -98,7 +98,7 @@ async def create_developer_profile(request: DeveloperProfileCreate, session: Ann
@router.get("/developers/{developer_id}", response_model=DeveloperProfile)
async def get_developer_profile(developer_id: str, session: Annotated[Session, Depends(get_session)]):
async def get_developer_profile(developer_id: str, session: Annotated[Session, Depends(get_session)]) -> DeveloperProfile:
"""Get a developer's profile and reputation"""
service = DeveloperEcosystemService(session)
profile = await service.get_developer_profile(developer_id)
@@ -108,7 +108,7 @@ async def get_developer_profile(developer_id: str, session: Annotated[Session, D
@router.get("/sdk/latest")
async def get_latest_sdk(session: Annotated[Session, Depends(get_session)]):
async def get_latest_sdk(session: Annotated[Session, Depends(get_session)]) -> dict[str, Any]:
"""Get information about the latest OpenClaw SDK releases"""
service = DeveloperEcosystemService(session)
return await service.get_sdk_release_info()
@@ -116,7 +116,7 @@ async def get_latest_sdk(session: Annotated[Session, Depends(get_session)]):
# Endpoints - Marketplace Solutions
@router.post("/solutions/publish", response_model=AgentSolution)
async def publish_solution(request: SolutionPublishRequest, session: Annotated[Session, Depends(get_session)]):
async def publish_solution(request: SolutionPublishRequest, session: Annotated[Session, Depends(get_session)]) -> AgentSolution:
"""Publish a new third-party agent solution to the marketplace"""
service = ThirdPartySolutionService(session)
try:
@@ -131,7 +131,8 @@ async def publish_solution(request: SolutionPublishRequest, session: Annotated[S
async def list_solutions(
category: str | None = None,
limit: int = 50,
):
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> list[AgentSolution]:
"""List available third-party agent solutions"""
service = ThirdPartySolutionService(session)
return await service.list_published_solutions(category, limit)
@@ -140,7 +141,7 @@ async def list_solutions(
@router.post("/solutions/{solution_id}/purchase")
async def purchase_solution(
solution_id: str, session: Annotated[Session, Depends(get_session)], buyer_id: str = Body(embed=True)
):
) -> dict[str, Any]:
"""Purchase or install a third-party solution"""
service = ThirdPartySolutionService(session)
try:
@@ -157,7 +158,8 @@ async def purchase_solution(
async def propose_innovation_lab(
researcher_id: str = Query(...),
request: LabProposalRequest = Body(...),
):
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> InnovationLab:
"""Propose a new agent innovation lab or research program"""
service = InnovationLabService(session)
try:
@@ -170,7 +172,7 @@ async def propose_innovation_lab(
@router.post("/labs/{lab_id}/join")
async def join_innovation_lab(
lab_id: str, session: Annotated[Session, Depends(get_session)], developer_id: str = Body(embed=True)
):
) -> InnovationLab:
"""Join an active innovation lab"""
service = InnovationLabService(session)
try:
@@ -183,7 +185,7 @@ async def join_innovation_lab(
@router.post("/labs/{lab_id}/fund")
async def fund_innovation_lab(
lab_id: str, session: Annotated[Session, Depends(get_session)], amount: float = Body(embed=True)
):
) -> InnovationLab:
"""Provide funding to a proposed innovation lab"""
service = InnovationLabService(session)
try:
@@ -198,7 +200,8 @@ async def fund_innovation_lab(
async def create_community_post(
author_id: str = Query(...),
request: PostCreateRequest = Body(...),
):
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> CommunityPost:
"""Create a new post in the community forum"""
service = CommunityPlatformService(session)
try:
@@ -212,14 +215,15 @@ async def create_community_post(
async def get_community_feed(
category: str | None = None,
limit: int = 20,
):
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> list[CommunityPost]:
"""Get the latest community posts and discussions"""
service = CommunityPlatformService(session)
return await service.get_feed(category, limit)
@router.post("/platform/posts/{post_id}/upvote")
async def upvote_community_post(post_id: str, session: Annotated[Session, Depends(get_session)]):
async def upvote_community_post(post_id: str, session: Annotated[Session, Depends(get_session)]) -> CommunityPost:
"""Upvote a community post (rewards author reputation)"""
service = CommunityPlatformService(session)
try:
@@ -234,7 +238,8 @@ async def upvote_community_post(post_id: str, session: Annotated[Session, Depend
async def create_hackathon(
organizer_id: str = Query(...),
request: HackathonCreateRequest = Body(...),
):
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
) -> Hackathon:
"""Create a new agent innovation hackathon (requires high reputation)"""
service = CommunityPlatformService(session)
try:
@@ -249,7 +254,7 @@ async def create_hackathon(
@router.post("/hackathons/{hackathon_id}/register")
async def register_for_hackathon(
hackathon_id: str, session: Annotated[Session, Depends(get_session)], developer_id: str = Body(embed=True)
):
) -> Hackathon:
"""Register for an upcoming or ongoing hackathon"""
service = CommunityPlatformService(session)
try:

View File

@@ -3,6 +3,11 @@ API endpoints for confidential transactions
"""
from datetime import datetime, UTC
from typing import Any
from aitbc import get_logger
logger = get_logger(__name__)
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPBearer
@@ -74,7 +79,7 @@ def get_access_controller() -> AccessController:
@router.post("/transactions", response_model=ConfidentialTransactionView)
async def create_confidential_transaction(request: ConfidentialTransactionCreate, api_key: str = Depends(get_api_key)):
async def create_confidential_transaction(request: ConfidentialTransactionCreate, api_key: str = Depends(get_api_key)) -> ConfidentialTransactionView:
"""Create a new confidential transaction with optional encryption"""
try:
# Generate transaction ID
@@ -144,7 +149,7 @@ async def create_confidential_transaction(request: ConfidentialTransactionCreate
@router.get("/transactions/{transaction_id}", response_model=ConfidentialTransactionView)
async def get_confidential_transaction(transaction_id: str, api_key: str = Depends(get_api_key)):
async def get_confidential_transaction(transaction_id: str, api_key: str = Depends(get_api_key)) -> ConfidentialTransactionView:
"""Get confidential transaction metadata (without decrypting sensitive data)"""
try:
# Retrieve transaction (in production, query from database)
@@ -161,7 +166,7 @@ async def get_confidential_transaction(transaction_id: str, api_key: str = Depen
@router.post("/transactions/{transaction_id}/access", response_model=ConfidentialAccessResponse)
async def access_confidential_data(
request: ConfidentialAccessRequest, transaction_id: str, api_key: str = Depends(get_api_key)
):
) -> ConfidentialAccessResponse:
"""Request access to decrypt confidential transaction data"""
try:
# Validate request
@@ -242,7 +247,7 @@ async def access_confidential_data(
@router.post("/transactions/{transaction_id}/audit", response_model=ConfidentialAccessResponse)
async def audit_access_confidential_data(
transaction_id: str, authorization: str, purpose: str = "compliance", api_key: str = Depends(get_api_key)
):
) -> ConfidentialAccessResponse:
"""Audit access to confidential transaction data"""
try:
# Get transaction
@@ -293,7 +298,7 @@ async def audit_access_confidential_data(
@router.post("/keys/register", response_model=KeyRegistrationResponse)
async def register_encryption_key(request: KeyRegistrationRequest, api_key: str = Depends(get_api_key)):
async def register_encryption_key(request: KeyRegistrationRequest, api_key: str = Depends(get_api_key)) -> KeyRegistrationResponse:
"""Register public key for confidential transactions"""
try:
# Get key manager
@@ -336,7 +341,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
@router.post("/keys/rotate")
async def rotate_encryption_key(participant_id: str, api_key: str = Depends(get_api_key)):
async def rotate_encryption_key(participant_id: str, api_key: str = Depends(get_api_key)) -> dict[str, Any]:
"""Rotate encryption keys for participant"""
try:
km = get_key_manager()
@@ -360,7 +365,7 @@ async def rotate_encryption_key(participant_id: str, api_key: str = Depends(get_
@router.get("/access/logs", response_model=AccessLogResponse)
async def get_access_logs(query: AccessLogQuery = Depends(), api_key: str = Depends(get_api_key)):
async def get_access_logs(query: AccessLogQuery = Depends(), api_key: str = Depends(get_api_key)) -> AccessLogResponse:
"""Get access logs for confidential transactions"""
try:
# Query logs (in production, query from database)
@@ -373,7 +378,7 @@ async def get_access_logs(query: AccessLogQuery = Depends(), api_key: str = Depe
@router.get("/status")
async def get_confidential_status(api_key: str = Depends(get_api_key)):
async def get_confidential_status(api_key: str = Depends(get_api_key)) -> dict[str, Any]:
"""Get status of confidential transaction system"""
try:
km = get_key_manager()

View File

@@ -93,7 +93,7 @@ async def get_developer_earnings(
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service),
current_user: dict = Depends(get_current_user)
):
) -> DeveloperEarningsResponse:
"""Get developer earnings metrics"""
try:
earnings_data = await ecosystem_service.get_developer_earnings(period=period)
@@ -112,7 +112,7 @@ async def get_agent_utilization(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> AgentUtilizationResponse:
"""Get agent utilization metrics"""
try:
utilization_data = await ecosystem_service.get_agent_utilization(period=period)
@@ -131,7 +131,7 @@ async def get_treasury_allocation(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> TreasuryAllocationResponse:
"""Get DAO treasury allocation metrics"""
try:
treasury_data = await ecosystem_service.get_treasury_allocation(period=period)
@@ -150,7 +150,7 @@ async def get_staking_metrics(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> StakingMetricsResponse:
"""Get staking system metrics"""
try:
staking_data = await ecosystem_service.get_staking_metrics(period=period)
@@ -169,7 +169,7 @@ async def get_bounty_analytics(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> BountyAnalyticsResponse:
"""Get bounty system analytics"""
try:
bounty_data = await ecosystem_service.get_bounty_analytics(period=period)
@@ -188,7 +188,7 @@ async def get_ecosystem_overview(
period_type: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> EcosystemOverviewResponse:
"""Get comprehensive ecosystem overview"""
try:
overview_data = await ecosystem_service.get_ecosystem_overview(period_type=period_type)
@@ -217,7 +217,7 @@ async def get_ecosystem_metrics(
limit: int = Field(default=100, ge=1, le=1000),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get time-series ecosystem metrics"""
try:
metrics = await ecosystem_service.get_time_series_metrics(
@@ -241,7 +241,7 @@ async def get_ecosystem_metrics(
async def get_ecosystem_health_score(
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get overall ecosystem health score"""
try:
health_score = await ecosystem_service.calculate_health_score()
@@ -262,7 +262,7 @@ async def get_growth_indicators(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get ecosystem growth indicators"""
try:
growth_data = await ecosystem_service.get_growth_indicators(period=period)
@@ -285,7 +285,7 @@ async def get_top_performers(
limit: int = Field(default=50, ge=1, le=100),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get top performers in different categories"""
try:
performers = await ecosystem_service.get_top_performers(
@@ -311,7 +311,7 @@ async def get_ecosystem_predictions(
horizon: int = Field(default=30, ge=1, le=365), # days
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get ecosystem predictions based on historical data"""
try:
predictions = await ecosystem_service.get_predictions(
@@ -336,7 +336,7 @@ async def get_ecosystem_alerts(
severity: str = Field(default="all", regex="^(low|medium|high|critical|all)$"),
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get ecosystem alerts and anomalies"""
try:
alerts = await ecosystem_service.get_alerts(severity=severity)
@@ -360,7 +360,7 @@ async def get_ecosystem_comparison(
custom_end_date: Optional[datetime] = None,
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Compare ecosystem metrics between periods"""
try:
comparison = await ecosystem_service.get_period_comparison(
@@ -389,7 +389,7 @@ async def export_ecosystem_data(
end_date: Optional[datetime] = None,
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Export ecosystem data in various formats"""
try:
export_data = await ecosystem_service.export_data(
@@ -416,7 +416,7 @@ async def export_ecosystem_data(
async def get_real_time_metrics(
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get real-time ecosystem metrics"""
try:
real_time_data = await ecosystem_service.get_real_time_metrics()
@@ -435,7 +435,7 @@ async def get_real_time_metrics(
async def get_kpi_dashboard(
session: Session = Depends(get_session),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
) -> Dict[str, Any]:
"""Get KPI dashboard with key performance indicators"""
try:
kpi_data = await ecosystem_service.get_kpi_dashboard()

View File

@@ -1,6 +1,6 @@
from typing import Annotated
from typing import Annotated, Any
from fastapi import APIRouter, Depends, Query
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from ..domain.gpu_marketplace import ConsumerGPUProfile, EdgeGPUMetrics, GPUArchitecture
@@ -20,7 +20,7 @@ async def get_consumer_gpu_profiles(
edge_optimized: bool | None = Query(default=None),
min_memory_gb: int | None = Query(default=None),
svc: EdgeGPUService = Depends(get_edge_service),
):
) -> list[ConsumerGPUProfile]:
return svc.list_profiles(architecture=architecture, edge_optimized=edge_optimized, min_memory_gb=min_memory_gb)
@@ -29,12 +29,12 @@ async def get_edge_gpu_metrics(
gpu_id: str,
limit: int = Query(default=100, ge=1, le=500),
svc: EdgeGPUService = Depends(get_edge_service),
):
) -> list[EdgeGPUMetrics]:
return svc.list_metrics(gpu_id=gpu_id, limit=limit)
@router.post("/scan/{miner_id}")
async def scan_edge_gpus(miner_id: str, svc: EdgeGPUService = Depends(get_edge_service)):
async def scan_edge_gpus(miner_id: str, svc: EdgeGPUService = Depends(get_edge_service)) -> dict[str, Any]:
"""Scan and register edge GPUs for a miner"""
try:
result = await svc.discover_and_register_edge_gpus(miner_id)
@@ -51,7 +51,7 @@ async def scan_edge_gpus(miner_id: str, svc: EdgeGPUService = Depends(get_edge_s
@router.post("/optimize/inference/{gpu_id}")
async def optimize_inference(
gpu_id: str, model_name: str, request_data: dict, svc: EdgeGPUService = Depends(get_edge_service)
):
) -> dict[str, Any]:
"""Optimize ML inference request for edge GPU"""
try:
optimized = await svc.optimize_inference_for_edge(gpu_id, model_name, request_data)

View File

@@ -191,7 +191,7 @@ async def get_wallet_info_api() -> WalletInfoResponse:
raise HTTPException(status_code=500, detail=str(e))
async def monitor_payment(payment_id: str):
async def monitor_payment(payment_id: str) -> None:
"""Monitor payment for confirmation (background task)"""
import asyncio
@@ -212,13 +212,13 @@ async def monitor_payment(payment_id: str):
# Agent endpoints temporarily added to exchange router
@router.get("/agents/test")
async def test_agent_endpoint():
async def test_agent_endpoint() -> dict[str, str]:
"""Test endpoint to verify agent routes are working"""
return {"message": "Agent routes are working", "timestamp": datetime.now(datetime.UTC).isoformat()}
@router.post("/agents/networks", response_model=dict, status_code=201)
async def create_agent_network(network_data: dict):
async def create_agent_network(network_data: dict) -> dict[str, Any]:
"""Create a new agent network for collaborative processing"""
try:
@@ -254,7 +254,7 @@ async def create_agent_network(network_data: dict):
@router.get("/agents/executions/{execution_id}/receipt")
async def get_execution_receipt(execution_id: str):
async def get_execution_receipt(execution_id: str) -> dict[str, Any]:
"""Get verifiable receipt for completed execution"""
try:

View File

@@ -9,7 +9,7 @@ REST API for OpenClaw DAO voting, proposals, and governance analytics
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Body, Depends, HTTPException, Query
from aitbc import get_logger
@@ -59,7 +59,7 @@ class VoteRequest(BaseModel):
# Endpoints - Profile & Delegation
@router.post("/profiles", response_model=GovernanceProfile)
async def init_governance_profile(request: ProfileInitRequest, session: Annotated[Session, Depends(get_session)]):
async def init_governance_profile(request: ProfileInitRequest, session: Annotated[Session, Depends(get_session)]) -> GovernanceProfile:
"""Initialize a governance profile for a user"""
service = GovernanceService(session)
try:
@@ -73,7 +73,7 @@ async def init_governance_profile(request: ProfileInitRequest, session: Annotate
@router.post("/profiles/{profile_id}/delegate", response_model=GovernanceProfile)
async def delegate_voting_power(
profile_id: str, request: DelegationRequest, session: Annotated[Session, Depends(get_session)]
):
) -> GovernanceProfile:
"""Delegate your voting power to another DAO member"""
service = GovernanceService(session)
try:
@@ -91,7 +91,7 @@ async def create_proposal(
session: Annotated[Session, Depends(get_session)],
proposer_id: str = Query(...),
request: ProposalCreateRequest = Body(...),
):
) -> Proposal:
"""Submit a new governance proposal to the DAO"""
service = GovernanceService(session)
try:
@@ -109,7 +109,7 @@ async def cast_vote(
session: Annotated[Session, Depends(get_session)],
voter_id: str = Query(...),
request: VoteRequest = Body(...),
):
) -> Vote:
"""Cast a vote on an active proposal"""
service = GovernanceService(session)
try:
@@ -124,7 +124,7 @@ async def cast_vote(
@router.post("/proposals/{proposal_id}/process", response_model=Proposal)
async def process_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)]):
async def process_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)]) -> Proposal:
"""Manually trigger the lifecycle check of a proposal (e.g., tally votes when time ends)"""
service = GovernanceService(session)
try:
@@ -137,7 +137,7 @@ async def process_proposal(proposal_id: str, session: Annotated[Session, Depends
@router.post("/proposals/{proposal_id}/execute", response_model=Proposal)
async def execute_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)], executor_id: str = Query(...)):
async def execute_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)], executor_id: str = Query(...)) -> Proposal:
"""Execute the payload of a succeeded proposal"""
service = GovernanceService(session)
try:
@@ -153,7 +153,7 @@ async def execute_proposal(proposal_id: str, session: Annotated[Session, Depends
@router.post("/analytics/reports", response_model=TransparencyReport)
async def generate_transparency_report(
session: Annotated[Session, Depends(get_session)], period: str = Query(..., description="e.g., 2026-Q1")
):
) -> TransparencyReport:
"""Generate a governance analytics and transparency report"""
service = GovernanceService(session)
try:

View File

@@ -36,7 +36,7 @@ async def create_royalty_distribution(
royalty_tiers: RoyaltyDistributionRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> RoyaltyDistributionResponse:
"""Create sophisticated royalty distribution for marketplace offer"""
try:
@@ -72,7 +72,7 @@ async def calculate_royalties(
transaction_id: str | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict:
"""Calculate and distribute royalties for a sale"""
try:
@@ -102,7 +102,7 @@ async def create_model_license(
license_request: ModelLicenseRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> ModelLicenseResponse:
"""Create model license and IP protection"""
try:
@@ -143,7 +143,7 @@ async def verify_model(
verification_request: ModelVerificationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> ModelVerificationResponse:
"""Perform advanced model verification"""
try:
@@ -179,7 +179,7 @@ async def get_marketplace_analytics(
metrics: list[str] | None = None,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> MarketplaceAnalyticsResponse:
"""Get comprehensive marketplace analytics"""
try:

View File

@@ -32,7 +32,7 @@ app.include_router(health_router, tags=["health"])
@app.get("/health")
async def health():
async def health() -> dict[str, str]:
return {"status": "ok", "service": "marketplace-enhanced"}

View File

@@ -6,7 +6,7 @@ Enhanced Marketplace API Router - Simplified Version
REST API endpoints for enhanced marketplace features
"""
from typing import Any
from typing import Annotated, Any
from aitbc import get_logger
@@ -56,9 +56,9 @@ class MarketplaceAnalyticsRequest(BaseModel):
async def create_royalty_distribution(
request: RoyaltyDistributionRequest,
offer_id: str,
session: Session = Depends(get_session),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Create royalty distribution for marketplace offer"""
try:
@@ -78,9 +78,9 @@ async def create_royalty_distribution(
async def calculate_royalties(
offer_id: str,
sale_amount: float,
session: Session = Depends(get_session),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Calculate royalties for a sale"""
try:
@@ -98,9 +98,9 @@ async def calculate_royalties(
async def create_model_license(
request: ModelLicenseRequest,
offer_id: str,
session: Session = Depends(get_session),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Create model license for marketplace offer"""
try:
@@ -124,9 +124,9 @@ async def create_model_license(
async def verify_model(
request: ModelVerificationRequest,
offer_id: str,
session: Session = Depends(get_session),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Verify model quality and performance"""
try:
@@ -143,9 +143,9 @@ async def verify_model(
@router.post("/analytics")
async def get_marketplace_analytics(
request: MarketplaceAnalyticsRequest,
session: Session = Depends(get_session),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Get marketplace analytics and insights"""
try:

View File

@@ -135,7 +135,7 @@ def _gpu_to_dict(gpu: GPURegistry) -> dict[str, Any]:
}
def _get_gpu_or_404(session, gpu_id: str) -> GPURegistry:
def _get_gpu_or_404(session: Session, gpu_id: str) -> GPURegistry:
gpu = session.get(GPURegistry, gpu_id)
if not gpu:
raise HTTPException(

View File

@@ -3,15 +3,18 @@ Marketplace Performance Optimization API Endpoints
REST API for managing distributed processing, GPU optimization, caching, and scaling
"""
import time
import os
import sys
from typing import Any
from fastapi import APIRouter, BackgroundTasks, HTTPException
from pydantic import BaseModel, Field
from aitbc import get_logger
logger = get_logger(__name__)
import os
import sys
from app.services.marketplace_gpu_optimizer import MarketplaceGPUOptimizer
from app.services.distributed_framework import (
DistributedProcessingCoordinator,
@@ -32,7 +35,7 @@ resource_scaler = ResourceScaler()
# Startup event handler for background tasks
@router.on_event("startup")
async def startup_event():
async def startup_event() -> None:
await marketplace_monitor.start()
await distributed_coordinator.start()
await resource_scaler.start()
@@ -40,7 +43,7 @@ async def startup_event():
@router.on_event("shutdown")
async def shutdown_event():
async def shutdown_event() -> None:
await marketplace_monitor.stop()
await distributed_coordinator.stop()
await resource_scaler.stop()
@@ -85,7 +88,7 @@ class ScalingPolicyUpdate(BaseModel):
# Endpoints: GPU Optimization
@router.post("/gpu/allocate")
async def allocate_gpu_resources(request: GPUAllocationRequest):
async def allocate_gpu_resources(request: GPUAllocationRequest) -> dict[str, Any]:
"""Request optimal GPU resource allocation for a marketplace task"""
try:
start_time = time.time()
@@ -105,7 +108,7 @@ async def allocate_gpu_resources(request: GPUAllocationRequest):
@router.post("/gpu/release")
async def release_gpu_resources(request: GPUReleaseRequest):
async def release_gpu_resources(request: GPUReleaseRequest) -> dict[str, str]:
"""Release previously allocated GPU resources"""
success = gpu_optimizer.release_resources(request.job_id)
if not success:
@@ -114,14 +117,14 @@ async def release_gpu_resources(request: GPUReleaseRequest):
@router.get("/gpu/status")
async def get_gpu_status():
async def get_gpu_status() -> dict[str, Any]:
"""Get overall GPU fleet status and optimization metrics"""
return gpu_optimizer.get_system_status()
# Endpoints: Distributed Processing
@router.post("/distributed/task")
async def submit_distributed_task(request: DistributedTaskRequest):
async def submit_distributed_task(request: DistributedTaskRequest) -> dict[str, str]:
"""Submit a task to the distributed processing framework"""
task = DistributedTask(
task_id=None,
@@ -137,7 +140,7 @@ async def submit_distributed_task(request: DistributedTaskRequest):
@router.get("/distributed/task/{task_id}")
async def get_distributed_task_status(task_id: str):
async def get_distributed_task_status(task_id: str) -> dict[str, Any]:
"""Check the status and get results of a distributed task"""
status = await distributed_coordinator.get_task_status(task_id)
if not status:
@@ -146,7 +149,7 @@ async def get_distributed_task_status(task_id: str):
@router.post("/distributed/worker/register")
async def register_worker(request: WorkerRegistrationRequest):
async def register_worker(request: WorkerRegistrationRequest) -> dict[str, str]:
"""Register a new worker node in the cluster"""
distributed_coordinator.register_worker(
worker_id=request.worker_id,
@@ -158,14 +161,14 @@ async def register_worker(request: WorkerRegistrationRequest):
@router.get("/distributed/status")
async def get_cluster_status():
async def get_cluster_status() -> dict[str, Any]:
"""Get overall distributed cluster health and load"""
return distributed_coordinator.get_cluster_status()
# Endpoints: Caching
@router.get("/cache/stats")
async def get_cache_stats():
async def get_cache_stats() -> dict[str, Any]:
"""Get current caching performance statistics"""
return {
"status": "connected" if cache_optimizer.is_connected else "local_only",
@@ -175,7 +178,7 @@ async def get_cache_stats():
@router.post("/cache/invalidate/{namespace}")
async def invalidate_cache_namespace(namespace: str, background_tasks: BackgroundTasks):
async def invalidate_cache_namespace(namespace: str, background_tasks: BackgroundTasks) -> dict[str, str]:
"""Invalidate a specific cache namespace (e.g., 'order_book')"""
background_tasks.add_task(cache_optimizer.invalidate_namespace, namespace)
return {"success": True, "message": f"Invalidation for {namespace} queued"}
@@ -183,20 +186,20 @@ async def invalidate_cache_namespace(namespace: str, background_tasks: Backgroun
# Endpoints: Monitoring
@router.get("/monitor/dashboard")
async def get_monitoring_dashboard():
async def get_monitoring_dashboard() -> dict[str, Any]:
"""Get real-time performance dashboard data"""
return marketplace_monitor.get_realtime_dashboard_data()
# Endpoints: Auto-scaling
@router.get("/scaler/status")
async def get_scaler_status():
async def get_scaler_status() -> dict[str, Any]:
"""Get current auto-scaler status and active rules"""
return resource_scaler.get_status()
@router.post("/scaler/policy")
async def update_scaling_policy(policy_update: ScalingPolicyUpdate):
async def update_scaling_policy(policy_update: ScalingPolicyUpdate) -> dict[str, str]:
"""Update auto-scaling thresholds and parameters dynamically"""
current_policy = resource_scaler.policy

View File

@@ -1,4 +1,6 @@
from typing import Any
from fastapi import APIRouter, HTTPException
from ..services.fhe_service import FHEService
@@ -11,7 +13,7 @@ fhe_service = FHEService()
@router.post("/prove/training")
async def prove_ml_training(proof_request: dict):
async def prove_ml_training(proof_request: dict) -> dict[str, Any]:
"""Generate ZK proof for ML training verification"""
try:
circuit_name = "ml_training_verification"
@@ -33,7 +35,7 @@ async def prove_ml_training(proof_request: dict):
@router.post("/verify/training")
async def verify_ml_training(verification_request: dict):
async def verify_ml_training(verification_request: dict) -> dict[str, Any]:
"""Verify ZK proof for ML training"""
try:
verification_result = await zk_service.verify_proof(
@@ -52,7 +54,7 @@ async def verify_ml_training(verification_request: dict):
@router.post("/prove/modular")
async def prove_modular_ml(proof_request: dict):
async def prove_modular_ml(proof_request: dict) -> dict[str, Any]:
"""Generate ZK proof using optimized modular circuits"""
try:
circuit_name = "modular_ml_components"
@@ -75,7 +77,7 @@ async def prove_modular_ml(proof_request: dict):
@router.post("/verify/inference")
async def verify_ml_inference(verification_request: dict):
async def verify_ml_inference(verification_request: dict) -> dict[str, Any]:
"""Verify ZK proof for ML inference"""
try:
verification_result = await zk_service.verify_proof(
@@ -94,7 +96,7 @@ async def verify_ml_inference(verification_request: dict):
@router.post("/fhe/inference")
async def fhe_ml_inference(fhe_request: dict):
async def fhe_ml_inference(fhe_request: dict) -> dict[str, Any]:
"""Perform ML inference on encrypted data"""
try:
# Setup FHE context
@@ -123,7 +125,7 @@ async def fhe_ml_inference(fhe_request: dict):
@router.get("/circuits")
async def list_ml_circuits():
async def list_ml_circuits() -> dict[str, Any]:
"""List available ML ZK circuits"""
circuits = [
{

View File

@@ -41,7 +41,7 @@ async def route_agent_skill(
routing_request: SkillRoutingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> SkillRoutingResponse:
"""Sophisticated agent skill routing"""
try:
@@ -69,7 +69,7 @@ async def intelligent_job_offloading(
offloading_request: JobOffloadingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> JobOffloadingResponse:
"""Intelligent job offloading strategies"""
try:
@@ -98,7 +98,7 @@ async def coordinate_agent_collaboration(
collaboration_request: AgentCollaborationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> AgentCollaborationResponse:
"""Agent collaboration and coordination"""
try:
@@ -127,7 +127,7 @@ async def optimize_hybrid_execution(
execution_request: HybridExecutionRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> HybridExecutionResponse:
"""Hybrid execution optimization"""
try:
@@ -155,7 +155,7 @@ async def deploy_to_edge(
deployment_request: EdgeDeploymentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> EdgeDeploymentResponse:
"""Deploy agent to edge computing infrastructure"""
try:
@@ -184,7 +184,7 @@ async def coordinate_edge_to_cloud(
coordination_request: EdgeCoordinationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> EdgeCoordinationResponse:
"""Coordinate edge-to-cloud agent operations"""
try:
@@ -213,7 +213,7 @@ async def develop_openclaw_ecosystem(
ecosystem_request: EcosystemDevelopmentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> EcosystemDevelopmentResponse:
"""Build comprehensive OpenClaw ecosystem"""
try:

View File

@@ -4,6 +4,8 @@
OpenClaw Enhanced Service - FastAPI Entry Point
"""
from typing import Any
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
@@ -32,12 +34,12 @@ app.include_router(health_router, tags=["health"])
@app.get("/health")
async def health():
async def health() -> dict[str, str]:
return {"status": "ok", "service": "openclaw-enhanced"}
@app.get("/health/detailed")
async def detailed_health():
async def detailed_health() -> dict[str, Any]:
"""Simple health check without database dependency"""
try:
import psutil

View File

@@ -81,7 +81,7 @@ async def route_agent_skill(
request: SkillRoutingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Route agent skill to appropriate agent"""
try:
@@ -104,7 +104,7 @@ async def intelligent_job_offloading(
request: JobOffloadingRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Intelligent job offloading strategies"""
try:
@@ -127,7 +127,7 @@ async def coordinate_agent_collaboration(
request: AgentCollaborationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Agent collaboration and coordination"""
try:
@@ -148,7 +148,7 @@ async def optimize_hybrid_execution(
request: HybridExecutionRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Hybrid execution optimization"""
try:
@@ -169,7 +169,7 @@ async def deploy_to_edge(
request: EdgeDeploymentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Deploy agent to edge computing infrastructure"""
try:
@@ -190,7 +190,7 @@ async def coordinate_edge_to_cloud(
request: EdgeCoordinationRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Coordinate edge-to-cloud agent operations"""
try:
@@ -211,7 +211,7 @@ async def develop_openclaw_ecosystem(
request: EcosystemDevelopmentRequest,
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key()),
):
) -> dict[str, Any]:
"""Build OpenClaw ecosystem components"""
try:

View File

@@ -267,7 +267,7 @@ async def llm_stream(
request: LLMRequest,
session: Annotated[Session, Depends(get_session)],
client_id: str = Depends(require_client_key()),
):
) -> ServiceResponse:
"""Stream LLM inference response"""
# Force streaming mode
request.stream = True

View File

@@ -3,6 +3,7 @@ Settlement router for cross-chain settlements
"""
import asyncio
from typing import Any
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field
@@ -38,7 +39,7 @@ class CrossChainSettlementResponse(BaseModel):
@router.post("/cross-chain", response_model=CrossChainSettlementResponse)
async def initiate_cross_chain_settlement(
request: CrossChainSettlementRequest, background_tasks: BackgroundTasks, api_key: str = Depends(get_api_key)
):
) -> CrossChainSettlementResponse:
"""Initiate a cross-chain settlement"""
try:
# Initialize settlement manager
@@ -70,7 +71,7 @@ async def initiate_cross_chain_settlement(
@router.get("/cross-chain/{settlement_id}")
async def get_settlement_status(settlement_id: str, api_key: str = Depends(get_api_key)):
async def get_settlement_status(settlement_id: str, api_key: str = Depends(get_api_key)) -> dict[str, Any]:
"""Get settlement status"""
try:
manager = BridgeManager()
@@ -95,7 +96,7 @@ async def get_settlement_status(settlement_id: str, api_key: str = Depends(get_a
@router.get("/cross-chain")
async def list_settlements(api_key: str = Depends(get_api_key), limit: int = 50, offset: int = 0):
async def list_settlements(api_key: str = Depends(get_api_key), limit: int = 50, offset: int = 0) -> dict[str, Any]:
"""List settlements with pagination"""
try:
manager = BridgeManager()
@@ -108,7 +109,7 @@ async def list_settlements(api_key: str = Depends(get_api_key), limit: int = 50,
@router.delete("/cross-chain/{settlement_id}")
async def cancel_settlement(settlement_id: str, api_key: str = Depends(get_api_key)):
async def cancel_settlement(settlement_id: str, api_key: str = Depends(get_api_key)) -> dict[str, str]:
"""Cancel a pending settlement"""
try:
manager = BridgeManager()

View File

@@ -29,7 +29,7 @@ class StakeCreateRequest(BaseModel):
auto_compound: bool = Field(default=False)
@validator('amount')
def validate_amount(cls, v):
def validate_amount(cls, v: float) -> float:
if v < 100.0:
raise ValueError('Minimum stake amount is 100 AITBC')
if v > 100000.0:
@@ -151,7 +151,7 @@ async def create_stake(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> StakeResponse:
"""Create a new stake on an agent wallet"""
try:
logger.info(f"Creating stake: {request.amount} AITBC on {request.agent_wallet} by {current_user['address']}")
@@ -191,7 +191,7 @@ async def get_stake(
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
) -> StakeResponse:
"""Get stake details"""
try:
stake = await staking_service.get_stake(stake_id)
@@ -216,7 +216,7 @@ async def get_stakes(
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
) -> List[StakeResponse]:
"""Get filtered list of user's stakes"""
try:
stakes = await staking_service.get_user_stakes(
@@ -246,7 +246,7 @@ async def add_to_stake(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> StakeResponse:
"""Add more tokens to an existing stake"""
try:
# Get stake and verify ownership
@@ -289,7 +289,7 @@ async def unbond_stake(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, str]:
"""Initiate unbonding for a stake"""
try:
# Get stake and verify ownership
@@ -331,7 +331,7 @@ async def complete_unbonding(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, Any]:
"""Complete unbonding and return stake + rewards"""
try:
# Get stake and verify ownership
@@ -373,7 +373,7 @@ async def get_stake_rewards(
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, Any]:
"""Get current rewards for a stake"""
try:
# Get stake and verify ownership
@@ -407,7 +407,7 @@ async def get_agent_metrics(
agent_wallet: str,
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> AgentMetricsResponse:
"""Get agent performance metrics"""
try:
metrics = await staking_service.get_agent_metrics(agent_wallet)
@@ -427,7 +427,7 @@ async def get_staking_pool(
agent_wallet: str,
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> StakingPoolResponse:
"""Get staking pool information for an agent"""
try:
pool = await staking_service.get_staking_pool(agent_wallet)
@@ -448,7 +448,7 @@ async def get_agent_apy(
lock_period: int = Field(default=30, ge=1, le=365),
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> Dict[str, Any]:
"""Get current APY for staking on an agent"""
try:
apy = await staking_service.calculate_apy(agent_wallet, lock_period)
@@ -474,7 +474,7 @@ async def update_agent_performance(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, str]:
"""Update agent performance metrics (oracle only)"""
try:
# Check permissions
@@ -512,7 +512,7 @@ async def distribute_agent_earnings(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, Any]:
"""Distribute agent earnings to stakers"""
try:
# Check permissions
@@ -553,7 +553,7 @@ async def get_supported_agents(
tier: Optional[PerformanceTier] = None,
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> Dict[str, Any]:
"""Get list of supported agents for staking"""
try:
agents = await staking_service.get_supported_agents(
@@ -578,7 +578,7 @@ async def get_staking_stats(
period: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> StakingStatsResponse:
"""Get staking system statistics"""
try:
stats = await staking_service.get_staking_stats(period=period)
@@ -596,7 +596,7 @@ async def get_staking_leaderboard(
limit: int = Field(default=50, ge=1, le=100),
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> Dict[str, Any]:
"""Get staking leaderboard"""
try:
leaderboard = await staking_service.get_leaderboard(
@@ -620,7 +620,7 @@ async def get_my_staking_positions(
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
) -> List[StakeResponse]:
"""Get current user's staking positions"""
try:
stakes = await staking_service.get_user_stakes(
@@ -643,7 +643,7 @@ async def get_my_staking_rewards(
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, Any]:
"""Get current user's staking rewards"""
try:
rewards = await staking_service.get_user_rewards(
@@ -665,7 +665,7 @@ async def claim_staking_rewards(
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
):
) -> Dict[str, Any]:
"""Claim accumulated rewards for multiple stakes"""
try:
# Verify ownership of all stakes
@@ -710,7 +710,7 @@ async def get_risk_assessment(
agent_wallet: str,
session: Session = Depends(get_session),
staking_service: StakingService = Depends(get_staking_service)
):
) -> Dict[str, Any]:
"""Get risk assessment for staking on an agent"""
try:
assessment = await staking_service.get_risk_assessment(agent_wallet)

View File

@@ -3,6 +3,9 @@
Web Vitals API endpoint for collecting performance metrics
"""
import logging
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
@@ -32,7 +35,7 @@ class WebVitalsMetric(BaseModel):
@router.post("/web-vitals")
async def collect_web_vitals(metric: WebVitalsMetric):
async def collect_web_vitals(metric: WebVitalsMetric) -> dict[str, Any]:
"""
Collect Web Vitals performance metrics from the frontend.
This endpoint receives Core Web Vitals (LCP, FID, CLS, TTFB, FCP) for monitoring.
@@ -70,6 +73,6 @@ async def collect_web_vitals(metric: WebVitalsMetric):
# Health check for web vitals endpoint
@router.get("/web-vitals/health")
async def web_vitals_health():
async def web_vitals_health() -> dict[str, str]:
"""Health check for web vitals collection endpoint"""
return {"status": "healthy", "service": "web-vitals"}