fix: integrate missing routes and update CLI commands

This commit is contained in:
oib
2026-03-05 06:23:46 +01:00
parent 210a77d860
commit 87591edfa0
24 changed files with 215 additions and 163 deletions

View File

@@ -27,8 +27,8 @@ async def get_stats(
from sqlmodel import func, select
from ..domain import Job
total_jobs = session.exec(select(func.count()).select_from(Job)).one()
active_jobs = session.exec(select(func.count()).select_from(Job).where(Job.state.in_(["QUEUED", "RUNNING"]))).one()
total_jobs = session.execute(select(func.count()).select_from(Job)).one()
active_jobs = session.execute(select(func.count()).select_from(Job).where(Job.state.in_(["QUEUED", "RUNNING"]))).one()
miner_service = MinerService(session)
miners = miner_service.list_records()
@@ -47,7 +47,7 @@ async def get_stats(
async def list_jobs(session: SessionDep, admin_key: str = Depends(require_admin_key())) -> dict[str, list[dict]]: # type: ignore[arg-type]
from ..domain import Job
jobs = session.exec(select(Job).order_by(Job.requested_at.desc()).limit(100)).all()
jobs = session.execute(select(Job).order_by(Job.requested_at.desc()).limit(100)).all()
return {
"items": [
{

View File

@@ -180,7 +180,7 @@ async def list_agent_creative_capabilities(
):
"""List all creative capabilities for a specific agent"""
try:
capabilities = session.exec(
capabilities = session.execute(
select(CreativeCapability).where(CreativeCapability.agent_id == agent_id)
).all()

View File

@@ -78,7 +78,7 @@ async def list_deployment_configs(
if status:
query = query.where(AgentDeploymentConfig.status == status)
configs = session.exec(query).all()
configs = session.execute(query).all()
# Filter by user ownership
user_configs = []
@@ -274,7 +274,7 @@ async def list_deployment_instances(
if status:
query = query.where(AgentDeploymentInstance.status == status)
instances = session.exec(query).all()
instances = session.execute(query).all()
# Filter by user ownership
user_instances = []
@@ -437,7 +437,7 @@ async def get_production_dashboard(
try:
# Get user's deployments
user_configs = session.exec(
user_configs = session.execute(
select(AgentDeploymentConfig).join(AIAgentWorkflow).where(
AIAgentWorkflow.owner_id == current_user
)
@@ -453,7 +453,7 @@ async def get_production_dashboard(
# Get detailed deployment info
for config in user_configs:
# Get instances for this deployment
instances = session.exec(
instances = session.execute(
select(AgentDeploymentInstance).where(
AgentDeploymentInstance.deployment_id == config.id
)
@@ -494,7 +494,7 @@ async def get_production_health(
try:
# Get user's deployments
user_configs = session.exec(
user_configs = session.execute(
select(AgentDeploymentConfig).join(AIAgentWorkflow).where(
AIAgentWorkflow.owner_id == current_user
)

View File

@@ -329,7 +329,7 @@ async def list_meta_learning_models(
if meta_strategy:
query = query.where(MetaLearningModel.meta_strategy == LearningStrategy(meta_strategy))
models = session.exec(
models = session.execute(
query.order_by(MetaLearningModel.created_at.desc()).limit(limit)
).all()
@@ -408,7 +408,7 @@ async def get_resource_allocations(
if status:
query = query.where(ResourceAllocation.status == status)
allocations = session.exec(
allocations = session.execute(
query.order_by(ResourceAllocation.created_at.desc()).limit(limit)
).all()
@@ -494,7 +494,7 @@ async def get_optimization_history(
if target_metric:
query = query.where(PerformanceOptimization.target_metric == PerformanceMetric(target_metric))
optimizations = session.exec(
optimizations = session.execute(
query.order_by(PerformanceOptimization.created_at.desc()).limit(limit)
).all()
@@ -589,7 +589,7 @@ async def get_agent_capabilities(
if domain_area:
query = query.where(AgentCapability.domain_area == domain_area)
capabilities = session.exec(
capabilities = session.execute(
query.order_by(AgentCapability.skill_level.desc()).limit(limit)
).all()
@@ -636,13 +636,13 @@ async def get_performance_summary(
try:
if not agent_ids:
# Get all agents if none specified
profiles = session.exec(select(AgentPerformanceProfile)).all()
profiles = session.execute(select(AgentPerformanceProfile)).all()
agent_ids = [p.agent_id for p in profiles]
summaries = []
for agent_id in agent_ids:
profile = session.exec(
profile = session.execute(
select(AgentPerformanceProfile).where(AgentPerformanceProfile.agent_id == agent_id)
).first()

View File

@@ -79,7 +79,7 @@ async def list_workflows(
for tag in tags:
query = query.where(AIAgentWorkflow.tags.contains([tag]))
workflows = session.exec(query).all()
workflows = session.execute(query).all()
return workflows
except Exception as e:
@@ -280,7 +280,7 @@ async def list_executions(
query = query.where(AgentExecution.workflow_id == workflow_id)
else:
# Get all workflows owned by user
user_workflows = session.exec(
user_workflows = session.execute(
select(AIAgentWorkflow.id).where(AIAgentWorkflow.owner_id == current_user.id)
).all()
workflow_ids = [w.id for w in user_workflows]
@@ -294,7 +294,7 @@ async def list_executions(
query = query.offset(offset).limit(limit)
query = query.order_by(AgentExecution.created_at.desc())
executions = session.exec(query).all()
executions = session.execute(query).all()
# Convert to response models
execution_statuses = []
@@ -383,7 +383,7 @@ async def get_execution_logs(
raise HTTPException(status_code=403, detail="Access denied")
# Get step executions
step_executions = session.exec(
step_executions = session.execute(
select(AgentStepExecution).where(AgentStepExecution.execution_id == execution_id)
).all()

View File

@@ -70,7 +70,7 @@ async def list_security_policies(
if is_active is not None:
query = query.where(AgentSecurityPolicy.is_active == is_active)
policies = session.exec(query).all()
policies = session.execute(query).all()
return policies
except Exception as e:
@@ -254,7 +254,7 @@ async def list_audit_logs(
query = query.offset(offset).limit(limit)
query = query.order_by(AuditLog.timestamp.desc())
audit_logs = session.exec(query).all()
audit_logs = session.execute(query).all()
return audit_logs
except Exception as e:
@@ -318,7 +318,7 @@ async def list_trust_scores(
query = query.offset(offset).limit(limit)
query = query.order_by(AgentTrustScore.trust_score.desc())
trust_scores = session.exec(query).all()
trust_scores = session.execute(query).all()
return trust_scores
except Exception as e:
@@ -338,7 +338,7 @@ async def get_trust_score(
try:
from ..services.agent_security import AgentTrustScore
trust_score = session.exec(
trust_score = session.execute(
select(AgentTrustScore).where(
(AgentTrustScore.entity_type == entity_type) &
(AgentTrustScore.entity_id == entity_id)
@@ -527,14 +527,14 @@ async def get_security_dashboard(
from ..services.agent_security import AgentAuditLog, AgentTrustScore, AgentSandboxConfig
# Get recent audit logs
recent_audits = session.exec(
recent_audits = session.execute(
select(AgentAuditLog)
.order_by(AgentAuditLog.timestamp.desc())
.limit(50)
).all()
# Get high-risk events
high_risk_events = session.exec(
high_risk_events = session.execute(
select(AuditLog)
.where(AuditLog.requires_investigation == True)
.order_by(AuditLog.timestamp.desc())
@@ -542,22 +542,22 @@ async def get_security_dashboard(
).all()
# Get trust score statistics
trust_scores = session.exec(select(ActivityTrustScore)).all()
trust_scores = session.execute(select(ActivityTrustScore)).all()
avg_trust_score = sum(ts.trust_score for ts in trust_scores) / len(trust_scores) if trust_scores else 0
# Get active sandboxes
active_sandboxes = session.exec(
active_sandboxes = session.execute(
select(AgentSandboxConfig)
.where(AgentSandboxConfig.is_active == True)
).all()
# Get security statistics
total_audits = session.exec(select(AuditLog)).count()
high_risk_count = session.exec(
total_audits = session.execute(select(AuditLog)).count()
high_risk_count = session.execute(
select(AuditLog).where(AuditLog.requires_investigation == True)
).count()
security_violations = session.exec(
security_violations = session.execute(
select(AuditLog).where(AuditLog.event_type == AuditEventType.SECURITY_VIOLATION)
).count()
@@ -595,10 +595,10 @@ async def get_security_statistics(
from ..services.agent_security import AgentAuditLog, AgentTrustScore, AgentSandboxConfig
# Audit statistics
total_audits = session.exec(select(AuditLog)).count()
total_audits = session.execute(select(AuditLog)).count()
event_type_counts = {}
for event_type in AuditEventType:
count = session.exec(
count = session.execute(
select(AuditLog).where(AuditLog.event_type == event_type)
).count()
event_type_counts[event_type.value] = count
@@ -611,7 +611,7 @@ async def get_security_statistics(
"critical": 0 # 90-100
}
all_audits = session.exec(select(AuditLog)).all()
all_audits = session.execute(select(AuditLog)).all()
for audit in all_audits:
if audit.risk_score <= 30:
risk_score_distribution["low"] += 1
@@ -623,7 +623,7 @@ async def get_security_statistics(
risk_score_distribution["critical"] += 1
# Trust score statistics
trust_scores = session.exec(select(AgentTrustScore)).all()
trust_scores = session.execute(select(AgentTrustScore)).all()
trust_score_distribution = {
"very_low": 0, # 0-20
"low": 0, # 21-40

View File

@@ -183,7 +183,7 @@ async def get_market_metrics(
if geographic_region:
query = query.where(MarketMetric.geographic_region == geographic_region)
metrics = session.exec(
metrics = session.execute(
query.order_by(MarketMetric.recorded_at.desc()).limit(limit)
).all()
@@ -244,7 +244,7 @@ async def create_dashboard(
result = await analytics_service.create_dashboard(owner_id, dashboard_type)
# Get the created dashboard details
dashboard = session.exec(
dashboard = session.execute(
select(DashboardConfig).where(DashboardConfig.dashboard_id == result["dashboard_id"])
).first()
@@ -280,7 +280,7 @@ async def get_dashboard(
"""Get dashboard configuration"""
try:
dashboard = session.exec(
dashboard = session.execute(
select(DashboardConfig).where(DashboardConfig.dashboard_id == dashboard_id)
).first()
@@ -330,7 +330,7 @@ async def list_dashboards(
if status:
query = query.where(DashboardConfig.status == status)
dashboards = session.exec(
dashboards = session.execute(
query.order_by(DashboardConfig.created_at.desc()).limit(limit)
).all()
@@ -440,7 +440,7 @@ async def get_report(
"""Get generated analytics report"""
try:
report = session.exec(
report = session.execute(
select(AnalyticsReport).where(AnalyticsReport.report_id == report_id)
).first()
@@ -503,7 +503,7 @@ async def get_analytics_alerts(
if status:
query = query.where(AnalyticsAlert.status == status)
alerts = session.exec(
alerts = session.execute(
query.order_by(AnalyticsAlert.created_at.desc()).limit(limit)
).all()
@@ -551,7 +551,7 @@ async def get_key_performance_indicators(
else:
start_time = end_time - timedelta(hours=1)
metrics = session.exec(
metrics = session.execute(
select(MarketMetric).where(
and_(
MarketMetric.period_type == period_type,
@@ -598,7 +598,7 @@ async def generate_market_overview_report(
"""Generate market overview report content"""
# Get metrics for the period
metrics = session.exec(
metrics = session.execute(
select(MarketMetric).where(
and_(
MarketMetric.period_type == period_type,
@@ -609,7 +609,7 @@ async def generate_market_overview_report(
).all()
# Get insights for the period
insights = session.exec(
insights = session.execute(
select(MarketInsight).where(
and_(
MarketInsight.created_at >= start_date,

View File

@@ -0,0 +1,52 @@
from __future__ import annotations
from fastapi import APIRouter, HTTPException
from aitbc.logging import get_logger
logger = get_logger(__name__)
router = APIRouter(tags=["blockchain"])
@router.get("/blockchain/status")
async def blockchain_status():
"""Get blockchain status."""
try:
# Try to get blockchain status from RPC
import httpx
async with httpx.AsyncClient() as client:
response = await client.get("http://localhost:8003/rpc/head", timeout=5.0)
if response.status_code == 200:
data = response.json()
return {
"status": "connected",
"height": data.get("height", 0),
"hash": data.get("hash", ""),
"timestamp": data.get("timestamp", ""),
"tx_count": data.get("tx_count", 0)
}
else:
return {
"status": "error",
"error": f"RPC returned {response.status_code}"
}
except Exception as e:
logger.error(f"Blockchain status error: {e}")
return {
"status": "error",
"error": str(e)
}
@router.get("/blockchain/sync")
async def blockchain_sync():
"""Trigger blockchain sync."""
try:
# For now, just return status
return {
"status": "sync_triggered",
"message": "Blockchain sync initiated"
}
except Exception as e:
logger.error(f"Blockchain sync error: {e}")
raise HTTPException(status_code=500, detail=str(e))

View File

@@ -205,7 +205,7 @@ async def get_agent_certifications(
if status:
query = query.where(AgentCertification.status == CertificationStatus(status))
certifications = session.exec(
certifications = session.execute(
query.order_by(AgentCertification.issued_at.desc())
).all()
@@ -334,7 +334,7 @@ async def get_agent_partnerships(
if partnership_type:
query = query.where(AgentPartnership.partnership_type == PartnershipType(partnership_type))
partnerships = session.exec(
partnerships = session.execute(
query.order_by(AgentPartnership.applied_at.desc())
).all()
@@ -377,7 +377,7 @@ async def list_partnership_programs(
if status:
query = query.where(PartnershipProgram.status == status)
programs = session.exec(
programs = session.execute(
query.order_by(PartnershipProgram.created_at.desc()).limit(limit)
).all()
@@ -464,7 +464,7 @@ async def award_badge(
raise HTTPException(status_code=400, detail=message)
# Get badge details
badge = session.exec(
badge = session.execute(
select(AchievementBadge).where(AchievementBadge.badge_id == badge_request.badge_id)
).first()
@@ -509,13 +509,13 @@ async def get_agent_badges(
if featured_only:
query = query.where(AgentBadge.is_featured == True)
agent_badges = session.exec(
agent_badges = session.execute(
query.order_by(AgentBadge.awarded_at.desc()).limit(limit)
).all()
# Get badge details
badge_ids = [ab.badge_id for ab in agent_badges]
badges = session.exec(
badges = session.execute(
select(AchievementBadge).where(AchievementBadge.badge_id.in_(badge_ids))
).all()
badge_map = {badge.badge_id: badge for badge in badges}
@@ -564,7 +564,7 @@ async def list_available_badges(
if active_only:
query = query.where(AchievementBadge.is_active == True)
badges = session.exec(
badges = session.execute(
query.order_by(AchievementBadge.created_at.desc()).limit(limit)
).all()
@@ -654,7 +654,7 @@ async def get_verification_records(
if status:
query = query.where(VerificationRecord.status == status)
verifications = session.exec(
verifications = session.execute(
query.order_by(VerificationRecord.requested_at.desc()).limit(limit)
).all()
@@ -722,7 +722,7 @@ async def get_certification_requirements(
if verification_type:
query = query.where(CertificationRequirement.verification_type == VerificationType(verification_type))
requirements = session.exec(
requirements = session.execute(
query.order_by(CertificationRequirement.certification_level, CertificationRequirement.requirement_name)
).all()
@@ -774,7 +774,7 @@ async def get_certification_leaderboard(
AgentCertification.status == CertificationStatus.ACTIVE
)
certifications = session.exec(
certifications = session.execute(
query.order_by(AgentCertification.issued_at.desc()).limit(limit * 2) # Get more to account for duplicates
).all()

View File

@@ -403,7 +403,7 @@ async def get_developer_certifications(
if not profile:
raise HTTPException(status_code=404, detail="Developer profile not found")
certifications = session.exec(
certifications = session.execute(
select(DeveloperCertification).where(DeveloperCertification.developer_id == profile.id)
).all()
@@ -712,16 +712,16 @@ async def get_platform_overview(
bounty_stats = await dev_service.get_bounty_statistics()
# Get developer statistics
total_developers = session.exec(select(DeveloperProfile)).count()
active_developers = session.exec(
total_developers = session.execute(select(DeveloperProfile)).count()
active_developers = session.execute(
select(DeveloperProfile).where(DeveloperProfile.is_active == True)
).count()
# Get certification statistics
total_certifications = session.exec(select(DeveloperCertification)).count()
total_certifications = session.execute(select(DeveloperCertification)).count()
# Get regional hub statistics
total_hubs = session.exec(select(RegionalHub)).count()
total_hubs = session.execute(select(RegionalHub)).count()
return {
"developers": {
@@ -762,7 +762,7 @@ async def get_platform_health(
try:
# Check database connectivity
try:
developer_count = session.exec(select(func.count(DeveloperProfile.id))).scalar()
developer_count = session.execute(select(func.count(DeveloperProfile.id))).scalar()
database_status = "healthy"
except Exception:
database_status = "unhealthy"

View File

@@ -170,7 +170,7 @@ async def get_global_offer(
try:
# Get the offer
stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id)
offer = session.exec(stmt).first()
offer = session.execute(stmt).scalars().first()
if not offer:
raise HTTPException(status_code=404, detail="Offer not found")
@@ -340,7 +340,7 @@ async def get_global_transaction(
stmt = select(GlobalMarketplaceTransaction).where(
GlobalMarketplaceTransaction.id == transaction_id
)
transaction = session.exec(stmt).first()
transaction = session.execute(stmt).scalars().first()
if not transaction:
raise HTTPException(status_code=404, detail="Transaction not found")
@@ -397,7 +397,7 @@ async def get_regions(
except ValueError:
raise HTTPException(status_code=400, detail=f"Invalid status: {status}")
regions = session.exec(stmt).all()
regions = session.execute(stmt).scalars().all()
response_regions = []
for region in regions:
@@ -538,7 +538,7 @@ async def get_global_marketplace_config(
if category:
stmt = stmt.where(GlobalMarketplaceConfig.category == category)
configs = session.exec(stmt).all()
configs = session.execute(stmt).scalars().all()
config_dict = {}
for config in configs:
@@ -567,20 +567,20 @@ async def get_global_marketplace_health(
try:
# Get overall health metrics
total_regions = session.exec(select(func.count(MarketplaceRegion.id))).scalar() or 0
active_regions = session.exec(
total_regions = session.execute(select(func.count(MarketplaceRegion.id))).scalar() or 0
active_regions = session.execute(
select(func.count(MarketplaceRegion.id)).where(MarketplaceRegion.status == RegionStatus.ACTIVE)
).scalar() or 0
total_offers = session.exec(select(func.count(GlobalMarketplaceOffer.id))).scalar() or 0
active_offers = session.exec(
total_offers = session.execute(select(func.count(GlobalMarketplaceOffer.id))).scalar() or 0
active_offers = session.execute(
select(func.count(GlobalMarketplaceOffer.id)).where(
GlobalMarketplaceOffer.global_status == MarketplaceStatus.ACTIVE
)
).scalar() or 0
total_transactions = session.exec(select(func.count(GlobalMarketplaceTransaction.id))).scalar() or 0
recent_transactions = session.exec(
total_transactions = session.execute(select(func.count(GlobalMarketplaceTransaction.id))).scalar() or 0
recent_transactions = session.execute(
select(func.count(GlobalMarketplaceTransaction.id)).where(
GlobalMarketplaceTransaction.created_at >= datetime.utcnow() - timedelta(hours=24)
)

View File

@@ -133,7 +133,7 @@ async def get_cross_chain_offer_details(
try:
# Get the offer
stmt = select(GlobalMarketplaceOffer).where(GlobalMarketplaceOffer.id == offer_id)
offer = session.exec(stmt).first()
offer = session.execute(stmt).scalars().first()
if not offer:
raise HTTPException(status_code=404, detail="Offer not found")

View File

@@ -487,7 +487,7 @@ async def get_governance_system_health(
try:
# Check database connectivity
try:
profile_count = session.exec(select(func.count(GovernanceProfile.profile_id))).scalar()
profile_count = session.execute(select(func.count(GovernanceProfile.profile_id))).scalar()
database_status = "healthy"
except Exception:
database_status = "unhealthy"

View File

@@ -163,15 +163,6 @@ async def register_gpu(
}
@router.get("/marketplace/gpus")
async def list_gpus_cli(
session: SessionDep,
available: Optional[bool] = Query(default=None),
):
"""List GPUs for CLI compatibility."""
return await list_gpus(session, available)
@router.get("/marketplace/gpu/list")
async def list_gpus(
session: SessionDep,
@@ -195,7 +186,7 @@ async def list_gpus(
stmt = stmt.where(col(GPURegistry.model).contains(model))
stmt = stmt.limit(limit)
gpus = session.exec(stmt).all()
gpus = session.execute(stmt).scalars().all()
return [_gpu_to_dict(g) for g in gpus]
@@ -206,7 +197,7 @@ async def get_gpu_details(gpu_id: str, session: SessionDep) -> Dict[str, Any]:
result = _gpu_to_dict(gpu)
if gpu.status == "booked":
booking = session.exec(
booking = session.execute(
select(GPUBooking)
.where(GPUBooking.gpu_id == gpu_id, GPUBooking.status == "active")
.limit(1)
@@ -297,7 +288,7 @@ async def release_gpu(gpu_id: str, session: SessionDep) -> Dict[str, Any]:
detail=f"GPU {gpu_id} is not booked",
)
booking = session.exec(
booking = session.execute(
select(GPUBooking)
.where(GPUBooking.gpu_id == gpu_id, GPUBooking.status == "active")
.limit(1)
@@ -328,7 +319,7 @@ async def get_gpu_reviews(
"""Get GPU reviews."""
gpu = _get_gpu_or_404(session, gpu_id)
reviews = session.exec(
reviews = session.execute(
select(GPUReview)
.where(GPUReview.gpu_id == gpu_id)
.order_by(GPUReview.created_at.desc())
@@ -368,10 +359,10 @@ async def add_gpu_review(
session.flush() # ensure the new review is visible to aggregate queries
# Recalculate average from DB (new review already included after flush)
total_count = session.exec(
total_count = session.execute(
select(func.count(GPUReview.id)).where(GPUReview.gpu_id == gpu_id)
).one()
avg_rating = session.exec(
avg_rating = session.execute(
select(func.avg(GPUReview.rating)).where(GPUReview.gpu_id == gpu_id)
).one() or 0.0
@@ -400,7 +391,7 @@ async def list_orders(
stmt = stmt.where(GPUBooking.status == status)
stmt = stmt.order_by(GPUBooking.created_at.desc()).limit(limit)
bookings = session.exec(stmt).all()
bookings = session.execute(stmt).scalars().all()
orders = []
for b in bookings:
gpu = session.get(GPURegistry, b.gpu_id)
@@ -427,7 +418,7 @@ async def get_pricing(
) -> Dict[str, Any]:
"""Get enhanced pricing information for a model with dynamic pricing."""
# SQLite JSON doesn't support array contains, so fetch all and filter in Python
all_gpus = session.exec(select(GPURegistry)).all()
all_gpus = session.execute(select(GPURegistry)).all()
compatible = [
g for g in all_gpus
if any(model.lower() in cap.lower() for cap in (g.capabilities or []))

View File

@@ -22,13 +22,13 @@ async def sync_offers(
"""Create marketplace offers from all registered miners"""
# Get all registered miners
miners = session.exec(select(Miner).where(Miner.status == "ONLINE")).all()
miners = session.execute(select(Miner).where(Miner.status == "ONLINE")).all()
created_offers = []
for miner in miners:
# Check if offer already exists
existing = session.exec(
existing = session.execute(
select(MarketplaceOffer).where(MarketplaceOffer.provider == miner.id)
).first()
@@ -68,7 +68,7 @@ async def list_miner_offers(session: SessionDep) -> list[MarketplaceOfferView]:
"""List all offers created from miners"""
# Get all offers with miner details
offers = session.exec(select(MarketplaceOffer).where(MarketplaceOffer.provider.like("miner_%"))).all()
offers = session.execute(select(MarketplaceOffer).where(MarketplaceOffer.provider.like("miner_%"))).all()
result = []
for offer in offers:

View File

@@ -83,7 +83,7 @@ async def submit_result(
duration_ms = int((datetime.utcnow() - job.requested_at).total_seconds() * 1000)
metrics["duration_ms"] = duration_ms
receipt = await receipt_service.create_receipt(job, miner_id, req.result, metrics)
receipt = receipt_service.create_receipt(job, miner_id, req.result, metrics)
job.receipt = receipt
job.receipt_id = receipt["receipt_id"] if receipt else None
session.add(job)

View File

@@ -226,7 +226,7 @@ async def list_fusion_models(
if fusion_type:
query = query.where(FusionModel.fusion_type == fusion_type)
models = session.exec(
models = session.execute(
query.order_by(FusionModel.created_at.desc()).limit(limit)
).all()
@@ -364,7 +364,7 @@ async def get_rl_agents(
if algorithm:
query = query.where(ReinforcementLearningConfig.algorithm == algorithm)
configs = session.exec(
configs = session.execute(
query.order_by(ReinforcementLearningConfig.created_at.desc()).limit(limit)
).all()
@@ -526,7 +526,7 @@ async def get_agent_domain_capabilities(
if domain:
query = query.where(AgentCapability.domain_area == domain)
capabilities = session.exec(
capabilities = session.execute(
query.order_by(AgentCapability.skill_level.desc()).limit(limit)
).all()
@@ -583,7 +583,7 @@ async def get_creative_capabilities(
if creative_domain:
query = query.where(CreativeCapability.creative_domain == creative_domain)
capabilities = session.exec(
capabilities = session.execute(
query.order_by(CreativeCapability.originality_score.desc()).limit(limit)
).all()
@@ -637,7 +637,7 @@ async def get_fusion_performance_analytics(
if fusion_type:
query = query.where(FusionModel.fusion_type == fusion_type)
models = session.exec(query).all()
models = session.execute(query).all()
# Filter by agent IDs if provided (by checking base models)
if agent_ids:
@@ -730,7 +730,7 @@ async def get_rl_performance_analytics(
if environment_type:
query = query.where(ReinforcementLearningConfig.environment_type == environment_type)
configs = session.exec(query).all()
configs = session.execute(query).all()
# Calculate analytics
total_configs = len(configs)

View File

@@ -309,7 +309,7 @@ async def get_reputation_metrics(
try:
# Get all reputation profiles
reputations = session.exec(
reputations = session.execute(
select(AgentReputation)
).all()
@@ -345,7 +345,7 @@ async def get_reputation_metrics(
# Recent activity (last 24 hours)
recent_cutoff = datetime.utcnow() - timedelta(days=1)
recent_events = session.exec(
recent_events = session.execute(
select(func.count(ReputationEvent.id)).where(
ReputationEvent.occurred_at >= recent_cutoff
)
@@ -381,7 +381,7 @@ async def get_agent_feedback(
"""Get community feedback for an agent"""
try:
feedbacks = session.exec(
feedbacks = session.execute(
select(CommunityFeedback)
.where(
and_(
@@ -425,7 +425,7 @@ async def get_reputation_events(
"""Get reputation change events for an agent"""
try:
events = session.exec(
events = session.execute(
select(ReputationEvent)
.where(ReputationEvent.agent_id == agent_id)
.order_by(ReputationEvent.occurred_at.desc())
@@ -462,7 +462,7 @@ async def update_specialization(
"""Update agent specialization tags"""
try:
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -498,7 +498,7 @@ async def update_region(
"""Update agent geographic region"""
try:
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -536,7 +536,7 @@ async def get_cross_chain_reputation(
try:
# Get basic reputation
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -585,7 +585,7 @@ async def sync_cross_chain_reputation(
try:
# Get reputation
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -619,7 +619,7 @@ async def get_cross_chain_leaderboard(
try:
# Get top reputations
reputations = session.exec(
reputations = session.execute(
select(AgentReputation)
.where(AgentReputation.trust_score >= min_score * 1000)
.order_by(AgentReputation.trust_score.desc())
@@ -674,7 +674,7 @@ async def submit_cross_chain_event(
agent_id = event_data['agent_id']
# Get reputation
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -730,11 +730,11 @@ async def get_cross_chain_analytics(
try:
# Get basic statistics
total_agents = session.exec(select(func.count(AgentReputation.id))).first()
avg_reputation = session.exec(select(func.avg(AgentReputation.trust_score))).first() or 0.0
total_agents = session.execute(select(func.count(AgentReputation.id))).first()
avg_reputation = session.execute(select(func.avg(AgentReputation.trust_score))).first() or 0.0
# Get reputation distribution
reputations = session.exec(select(AgentReputation)).all()
reputations = session.execute(select(AgentReputation)).all()
distribution = {
"master": 0,

View File

@@ -207,7 +207,7 @@ async def get_tier_progress(
try:
# Get reward profile
profile = session.exec(
profile = session.execute(
select(AgentRewardProfile).where(AgentRewardProfile.agent_id == agent_id)
).first()
@@ -216,7 +216,7 @@ async def get_tier_progress(
# Get reputation for trust score
from ..domain.reputation import AgentReputation
reputation = session.exec(
reputation = session.execute(
select(AgentReputation).where(AgentReputation.agent_id == agent_id)
).first()
@@ -380,7 +380,7 @@ async def get_reward_leaderboard(
if tier:
query = query.where(AgentRewardProfile.current_tier == tier)
profiles = session.exec(
profiles = session.execute(
query.order_by(AgentRewardProfile.total_earnings.desc()).limit(limit)
).all()
@@ -413,7 +413,7 @@ async def get_reward_tiers(
try:
from ..domain.rewards import RewardTierConfig
tier_configs = session.exec(
tier_configs = session.execute(
select(RewardTierConfig).where(RewardTierConfig.is_active == True)
).all()
@@ -455,7 +455,7 @@ async def get_agent_milestones(
if not include_completed:
query = query.where(RewardMilestone.is_completed == False)
milestones = session.exec(
milestones = session.execute(
query.order_by(RewardMilestone.created_at.desc())
).all()
@@ -499,7 +499,7 @@ async def get_reward_distributions(
if status:
query = query.where(RewardDistribution.status == status)
distributions = session.exec(
distributions = session.execute(
query.order_by(RewardDistribution.created_at.desc()).limit(limit)
).all()

View File

@@ -221,7 +221,7 @@ async def get_trade_request(
"""Get trade request details"""
try:
trade_request = session.exec(
trade_request = session.execute(
select(TradeRequest).where(TradeRequest.request_id == request_id)
).first()
@@ -279,7 +279,7 @@ async def get_trade_matches(
"""Get trade matches for a request"""
try:
matches = session.exec(
matches = session.execute(
select(TradeMatch).where(TradeMatch.request_id == request_id)
.order_by(TradeMatch.match_score.desc())
).all()
@@ -357,7 +357,7 @@ async def get_negotiation(
"""Get negotiation details"""
try:
negotiation = session.exec(
negotiation = session.execute(
select(TradeNegotiation).where(TradeNegotiation.negotiation_id == negotiation_id)
).first()
@@ -394,7 +394,7 @@ async def get_trade_match(
"""Get trade match details"""
try:
match = session.exec(
match = session.execute(
select(TradeMatch).where(TradeMatch.match_id == match_id)
).first()
@@ -466,7 +466,7 @@ async def list_trade_requests(
if status:
query = query.where(TradeRequest.status == status)
requests = session.exec(
requests = session.execute(
query.order_by(TradeRequest.created_at.desc()).limit(limit)
).all()
@@ -519,7 +519,7 @@ async def list_trade_matches(
if status:
query = query.where(TradeMatch.status == status)
matches = session.exec(
matches = session.execute(
query.order_by(TradeMatch.match_score.desc()).limit(limit)
).all()
@@ -575,7 +575,7 @@ async def list_negotiations(
if strategy:
query = query.where(TradeNegotiation.negotiation_strategy == strategy)
negotiations = session.exec(
negotiations = session.execute(
query.order_by(TradeNegotiation.created_at.desc()).limit(limit)
).all()

View File

@@ -55,7 +55,7 @@ async def register_user(
"""Register a new user"""
# Check if user already exists
existing_user = session.exec(
existing_user = session.execute(
select(User).where(User.email == user_data.email)
).first()
@@ -111,7 +111,7 @@ async def login_user(
# In production, implement proper authentication
# Find user by wallet address
wallet = session.exec(
wallet = session.execute(
select(Wallet).where(Wallet.address == login_data.wallet_address)
).first()
@@ -141,7 +141,7 @@ async def login_user(
session.commit()
else:
# Update last login
user = session.exec(
user = session.execute(
select(User).where(User.id == wallet.user_id)
).first()
user.last_login = datetime.utcnow()
@@ -194,7 +194,7 @@ async def get_user_balance(
) -> Dict[str, Any]:
"""Get user's AITBC balance"""
wallet = session.exec(
wallet = session.execute(
select(Wallet).where(Wallet.user_id == user_id)
).first()

View File

@@ -121,7 +121,7 @@ def status(ctx, node: int):
try:
with httpx.Client() as client:
# First get health for general status
health_url = rpc_url.replace("/rpc", "") + "/health" if "/rpc" in rpc_url else rpc_url + "/health"
health_url = rpc_url.replace("/rpc", "") + "/v1/health" if "/rpc" in rpc_url else rpc_url + "/v1/health"
response = client.get(
health_url,
timeout=5
@@ -149,7 +149,7 @@ def sync_status(ctx):
try:
with httpx.Client() as client:
response = client.get(
f"{config.coordinator_url}/health",
f"{config.coordinator_url}/v1/health",
headers={"X-Api-Key": config.api_key or ""}
)
@@ -171,7 +171,7 @@ def peers(ctx):
try:
with httpx.Client() as client:
response = client.get(
f"{config.coordinator_url}/health",
f"{config.coordinator_url}/v1/health",
headers={"X-Api-Key": config.api_key or ""}
)
@@ -193,7 +193,7 @@ def info(ctx):
try:
with httpx.Client() as client:
response = client.get(
f"{config.coordinator_url}/health",
f"{config.coordinator_url}/v1/health",
headers={"X-Api-Key": config.api_key or ""}
)
@@ -215,7 +215,7 @@ def supply(ctx):
try:
with httpx.Client() as client:
response = client.get(
f"{config.coordinator_url}/health",
f"{config.coordinator_url}/v1/health",
headers={"X-Api-Key": config.api_key or ""}
)
@@ -237,7 +237,7 @@ def validators(ctx):
try:
with httpx.Client() as client:
response = client.get(
f"{config.coordinator_url}/health",
f"{config.coordinator_url}/v1/health",
headers={"X-Api-Key": config.api_key or ""}
)

View File

@@ -60,7 +60,7 @@ def register(ctx, name: str, memory: Optional[int], cuda_cores: Optional[int],
json={"gpu": gpu_specs}
)
if response.status_code == 201:
if response.status_code in (200, 201):
result = response.json()
success(f"GPU registered successfully: {result.get('gpu_id')}")
output(result, ctx.obj['output_format'])
@@ -160,7 +160,7 @@ def book(ctx, gpu_id: str, hours: float, job_id: Optional[str]):
json=booking_data
)
if response.status_code == 201:
if response.status_code in (200, 201):
booking = response.json()
success(f"GPU booked successfully: {booking.get('booking_id')}")
output(booking, ctx.obj['output_format'])
@@ -299,7 +299,7 @@ def review(ctx, gpu_id: str, rating: int, comment: Optional[str]):
json=review_data
)
if response.status_code == 201:
if response.status_code in (200, 201):
success("Review added successfully")
output({"status": "review_added", "gpu_id": gpu_id}, ctx.obj['output_format'])
else:
@@ -504,7 +504,7 @@ def register(ctx, agent_id: str, agent_type: str, capabilities: Optional[str],
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 201:
if response.status_code in (200, 201):
success(f"Agent {agent_id} registered successfully")
output(response.json(), ctx.obj['output_format'])
else:
@@ -583,7 +583,7 @@ def list_resource(ctx, resource_id: str, resource_type: str, compute_power: floa
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 201:
if response.status_code in (200, 201):
success(f"Resource {resource_id} listed successfully")
output(response.json(), ctx.obj['output_format'])
else:
@@ -622,7 +622,7 @@ def rent(ctx, resource_id: str, consumer_id: str, duration: int, max_price: Opti
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 201:
if response.status_code in (200, 201):
success("AI resource rented successfully")
output(response.json(), ctx.obj['output_format'])
else:
@@ -813,7 +813,7 @@ def create_proposal(ctx, title: str, description: str, proposal_type: str,
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 201:
if response.status_code in (200, 201):
success("Proposal created successfully")
output(response.json(), ctx.obj['output_format'])
else:
@@ -845,7 +845,7 @@ def vote(ctx, proposal_id: str, vote: str, reasoning: Optional[str]):
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 201:
if response.status_code in (200, 201):
success(f"Vote '{vote}' cast successfully")
output(response.json(), ctx.obj['output_format'])
else:

View File

@@ -57,7 +57,7 @@ def register(ctx, gpu: Optional[str], memory: Optional[int],
json={"capabilities": capabilities}
)
if response.status_code == 200:
if response.status_code in (200, 204):
output({
"miner_id": miner_id,
"status": "registered",
@@ -79,8 +79,9 @@ def poll(ctx, wait: int, miner_id: str):
try:
with httpx.Client() as client:
response = client.get(
response = client.post(
f"{config.coordinator_url}/v1/miners/poll",
json={"max_wait_seconds": 5},
headers={
"X-Api-Key": config.api_key or "",
"X-Miner-ID": miner_id
@@ -88,12 +89,15 @@ def poll(ctx, wait: int, miner_id: str):
timeout=wait + 5
)
if response.status_code == 200:
job = response.json()
if job:
output(job, ctx.obj['output_format'])
else:
if response.status_code in (200, 204):
if response.status_code == 204:
output({"message": "No jobs available"}, ctx.obj['output_format'])
else:
job = response.json()
if job:
output(job, ctx.obj['output_format'])
else:
output({"message": "No jobs available"}, ctx.obj['output_format'])
else:
error(f"Failed to poll: {response.status_code}")
except httpx.TimeoutException:
@@ -115,8 +119,9 @@ def mine(ctx, jobs: int, miner_id: str):
try:
with httpx.Client() as client:
# Poll for job
response = client.get(
response = client.post(
f"{config.coordinator_url}/v1/miners/poll",
json={"max_wait_seconds": 5},
headers={
"X-Api-Key": config.api_key or "",
"X-Miner-ID": miner_id
@@ -124,7 +129,10 @@ def mine(ctx, jobs: int, miner_id: str):
timeout=30
)
if response.status_code == 200:
if response.status_code in (200, 204):
if response.status_code == 204:
time.sleep(5)
continue
job = response.json()
if job:
job_id = job.get('job_id')
@@ -146,8 +154,8 @@ def mine(ctx, jobs: int, miner_id: str):
"X-Miner-ID": miner_id
},
json={
"result": f"Processed job {job_id}",
"success": True
"result": {"output": f"Processed job {job_id}"},
"metrics": {}
}
)
@@ -186,10 +194,11 @@ def heartbeat(ctx, miner_id: str):
f"{config.coordinator_url}/v1/miners/heartbeat?miner_id={miner_id}",
headers={
"X-Api-Key": config.api_key or ""
}
},
json={"capabilities": capabilities}
)
if response.status_code == 200:
if response.status_code in (200, 204):
output({
"miner_id": miner_id,
"status": "heartbeat_sent",
@@ -234,13 +243,13 @@ def earnings(ctx, miner_id: str, from_time: Optional[str], to_time: Optional[str
params["to_time"] = to_time
with httpx.Client() as client:
response = client.get(
response = client.post(
f"{config.coordinator_url}/v1/miners/{miner_id}/earnings",
params=params,
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 200:
if response.status_code in (200, 204):
data = response.json()
output(data, ctx.obj['output_format'])
else:
@@ -289,7 +298,7 @@ def update_capabilities(ctx, gpu: Optional[str], memory: Optional[int],
json={"capabilities": capabilities}
)
if response.status_code == 200:
if response.status_code in (200, 204):
output({
"miner_id": miner_id,
"status": "capabilities_updated",
@@ -323,7 +332,7 @@ def deregister(ctx, miner_id: str, force: bool):
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 200:
if response.status_code in (200, 204):
output({
"miner_id": miner_id,
"status": "deregistered"
@@ -358,13 +367,13 @@ def jobs(ctx, limit: int, job_type: Optional[str], min_reward: Optional[float],
params["status"] = job_status
with httpx.Client() as client:
response = client.get(
response = client.post(
f"{config.coordinator_url}/v1/miners/{miner_id}/jobs",
params=params,
headers={"X-Api-Key": config.api_key or ""}
)
if response.status_code == 200:
if response.status_code in (200, 204):
data = response.json()
output(data, ctx.obj['output_format'])
else:
@@ -379,7 +388,7 @@ def _process_single_job(config, miner_id: str, worker_id: int) -> Dict[str, Any]
"""Process a single job (used by concurrent mine)"""
try:
with httpx.Client() as http_client:
response = http_client.get(
response = http_client.post(
f"{config.coordinator_url}/v1/miners/poll",
headers={
"X-Api-Key": config.api_key or "",
@@ -388,7 +397,7 @@ def _process_single_job(config, miner_id: str, worker_id: int) -> Dict[str, Any]
timeout=30
)
if response.status_code == 200:
if response.status_code in (200, 204):
job = response.json()
if job:
job_id = job.get('job_id')