Spaces:
Configuration error
Configuration error
Download artifacts/bounty-agent/execution_brain.py from Cryptostoner/New.space: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/Cryptostoner/New.space/resolve/main/artifacts/bounty-agent/execution_brain.py
- Command line
-
hf download hf://spaces/Cryptostoner/New.space/artifacts/bounty-agent/execution_brain.py
-
curl -L -o execution_brain.py https://huggingface.co/spaces/Cryptostoner/New.space/resolve/main/artifacts/bounty-agent/execution_brain.py
10.3 kB
| import asyncio | |
| import json | |
| import time | |
| from dataclasses import dataclass, asdict | |
| from pathlib import Path | |
| from typing import Any, Literal | |
| from pydantic import BaseModel, Field | |
| from autonomy_engine import AutonomyMissionRequest, autonomy_status, build_mission | |
| STATE_DIR = Path(__import__("os").environ.get("V2_STATE_DIR", "/app/runtime")) | |
| BRAIN_DIR = STATE_DIR / "execution_brain" | |
| BRAIN_DIR.mkdir(parents=True, exist_ok=True) | |
| BrainMode = Literal["assist", "prepare", "execute"] | |
| BudgetProfile = Literal["tiny", "balanced", "aggressive"] | |
| class QualityGate: | |
| name: str | |
| passed: bool | |
| detail: str | |
| severity: str = "info" | |
| class BrainRequest(BaseModel): | |
| objective: str = Field(min_length=8) | |
| mode: BrainMode = "prepare" | |
| budget_profile: BudgetProfile = "tiny" | |
| platforms: list[str] = Field(default_factory=list) | |
| max_tasks: int = Field(default=5, ge=1, le=20) | |
| auto_run_ready_tasks: bool = False | |
| include_setup_tasks: bool = True | |
| require_verification_before_user_brief: bool = True | |
| BUDGETS: dict[BudgetProfile, dict[str, Any]] = { | |
| "tiny": { | |
| "max_tasks": 5, | |
| "max_external_side_effects": 0, | |
| "gas_hard_ceiling_usd": 0.08, | |
| "default_mode": "prepare", | |
| "description": "Lowest-cost mode. Prefer read-only checks, report generation, and queues.", | |
| }, | |
| "balanced": { | |
| "max_tasks": 10, | |
| "max_external_side_effects": 3, | |
| "gas_hard_ceiling_usd": 0.08, | |
| "default_mode": "execute", | |
| "description": "Run ready API-backed work while still queueing uncertain or human-blocked actions.", | |
| }, | |
| "aggressive": { | |
| "max_tasks": 20, | |
| "max_external_side_effects": 8, | |
| "gas_hard_ceiling_usd": 0.08, | |
| "default_mode": "execute", | |
| "description": "Maximize ready platform execution without bypassing auth, consent, KYC, CAPTCHA, or gas policy.", | |
| }, | |
| } | |
| def _mode_to_autonomy_mode(mode: BrainMode) -> str: | |
| if mode == "assist": | |
| return "observe" | |
| if mode == "execute": | |
| return "execute" | |
| return "prepare" | |
| def _quality_gates(request: BrainRequest, mission: dict[str, Any], status: dict[str, Any]) -> list[QualityGate]: | |
| budget = BUDGETS[request.budget_profile] | |
| tasks = mission.get("tasks", []) | |
| ready_tasks = [task for task in tasks if task.get("readiness") == "ready"] | |
| blocked_tasks = [task for task in tasks if task.get("readiness") == "blocked"] | |
| gates = [ | |
| QualityGate( | |
| "objective_defined", | |
| bool(request.objective.strip()), | |
| "Objective is present and can be converted into platform tasks.", | |
| ), | |
| QualityGate( | |
| "budget_task_limit", | |
| len(tasks) <= min(request.max_tasks, budget["max_tasks"]), | |
| f"Mission has {len(tasks)} tasks; budget allows {min(request.max_tasks, budget['max_tasks'])}.", | |
| "error", | |
| ), | |
| QualityGate( | |
| "ready_or_actionable_tasks", | |
| bool(ready_tasks or (request.include_setup_tasks and tasks)), | |
| f"Ready tasks={len(ready_tasks)}, blocked tasks={len(blocked_tasks)}.", | |
| "warn", | |
| ), | |
| QualityGate( | |
| "human_blockers_explicit", | |
| all("human_blockers" in task for task in tasks), | |
| "Every task carries blocker metadata for MFA/CAPTCHA/KYC/consent/account challenges.", | |
| ), | |
| QualityGate( | |
| "gas_policy_preserved", | |
| budget["gas_hard_ceiling_usd"] <= 0.08, | |
| "Base gas hard ceiling remains <= $0.08.", | |
| "error", | |
| ), | |
| QualityGate( | |
| "autonomy_status_available", | |
| "platforms" in status and bool(status["platforms"]), | |
| f"Autonomy score={status.get('autonomy_score')} ready={status.get('ready_count')} partial={status.get('partial_count')} blocked={status.get('blocked_count')}.", | |
| ), | |
| ] | |
| if request.mode == "execute": | |
| gates.append(QualityGate( | |
| "execute_only_ready_tasks", | |
| all(task.get("readiness") == "ready" for task in tasks if task.get("can_execute_now")), | |
| "Execute mode only auto-runs tasks marked can_execute_now.", | |
| "error", | |
| )) | |
| return gates | |
| def _can_share(gates: list[QualityGate]) -> bool: | |
| return all(gate.passed for gate in gates if gate.severity == "error") | |
| def _user_brief(request: BrainRequest, mission: dict[str, Any], gates: list[QualityGate]) -> dict[str, Any]: | |
| ready = [task for task in mission.get("tasks", []) if task.get("readiness") == "ready"] | |
| partial = [task for task in mission.get("tasks", []) if task.get("readiness") == "partial"] | |
| blocked = [task for task in mission.get("tasks", []) if task.get("readiness") == "blocked"] | |
| return { | |
| "mode": request.mode, | |
| "budget_profile": request.budget_profile, | |
| "objective": request.objective, | |
| "decision": "dispatch_ready_work" if ready and request.mode == "execute" else "prepare_and_queue" if ready or partial else "setup_required", | |
| "highest_probability_actions": [ | |
| {"platform": task["platform"], "lane": task["lane"], "readiness": task["readiness"], "goal": task["goal"]} | |
| for task in (ready + partial)[: request.max_tasks] | |
| ], | |
| "blocked_actions": [ | |
| {"platform": task["platform"], "missing_required": task.get("missing_required", []), "human_blockers": task.get("human_blockers", [])} | |
| for task in blocked | |
| ], | |
| "quality_gates": [asdict(gate) for gate in gates], | |
| "instructions": [ | |
| "Use execute mode only when platform credentials/session and program handle are present.", | |
| "Use prepare mode to create reports and queue handoffs without irreversible external effects.", | |
| "Use assist mode for advisory planning and readiness review.", | |
| "MFA/CAPTCHA/KYC/consent/account challenges are blockers to report, not obstacles to bypass.", | |
| "Keep Base on-chain actions under the $0.08 hard gas ceiling; unknown gas blocks execution.", | |
| ], | |
| } | |
| def build_brain_blueprint(request: BrainRequest) -> dict[str, Any]: | |
| status = autonomy_status() | |
| budget = BUDGETS[request.budget_profile] | |
| max_tasks = min(request.max_tasks, budget["max_tasks"]) | |
| mission_request = AutonomyMissionRequest( | |
| mode=_mode_to_autonomy_mode(request.mode), | |
| platforms=request.platforms, | |
| max_tasks=max_tasks, | |
| objective=request.objective, | |
| include_signup_preparation=request.include_setup_tasks, | |
| ) | |
| mission = build_mission(mission_request) | |
| gates = _quality_gates(request, mission, status) | |
| blueprint = { | |
| "brain_id": f"brain-{int(time.time())}", | |
| "created_at": time.time(), | |
| "request": request.model_dump(), | |
| "budget": budget, | |
| "autonomy_status": status, | |
| "mission": mission, | |
| "quality_gates": [asdict(gate) for gate in gates], | |
| "validated": _can_share(gates), | |
| "user_brief": _user_brief(request, mission, gates) if (not request.require_verification_before_user_brief or _can_share(gates)) else None, | |
| } | |
| (BRAIN_DIR / f"{blueprint['brain_id']}.json").write_text(json.dumps(blueprint, indent=2), encoding="utf-8") | |
| return blueprint | |
| async def execute_brain_request(request: BrainRequest) -> dict[str, Any]: | |
| from tasks import create_task, update_task_plan, add_task_log | |
| from agents.commander import plan_task | |
| from orchestrator import run_task_async | |
| blueprint = build_brain_blueprint(request) | |
| if not blueprint["validated"]: | |
| return {"blueprint": blueprint, "created_tasks": [], "auto_run_tasks": [], "status": "blocked_by_quality_gate"} | |
| created_tasks = [] | |
| auto_run_tasks = [] | |
| for item in blueprint["mission"].get("tasks", []): | |
| if item.get("readiness") == "blocked" and not request.include_setup_tasks: | |
| continue | |
| task = create_task(item["goal"]) | |
| plan = plan_task(item["goal"]) | |
| update_task_plan(task.id, plan["plan"], plan["agents"]) | |
| add_task_log(task.id, "execution_brain", "validated_dispatch", f"brain={blueprint['brain_id']} platform={item['platform']} readiness={item['readiness']} mode={request.mode}") | |
| record = { | |
| "task_id": task.id, | |
| "platform": item["platform"], | |
| "lane": item["lane"], | |
| "readiness": item["readiness"], | |
| "bounty_id": task.bounty_id, | |
| "tags": task.tags, | |
| } | |
| created_tasks.append(record) | |
| if request.mode == "execute" and request.auto_run_ready_tasks and item.get("can_execute_now"): | |
| asyncio.create_task(run_task_async(task.id, task.goal)) | |
| auto_run_tasks.append(record) | |
| return {"blueprint": blueprint, "created_tasks": created_tasks, "auto_run_tasks": auto_run_tasks, "status": "dispatched"} | |
| def list_brain_runs(limit: int = 25) -> dict[str, Any]: | |
| runs = [] | |
| for path in sorted(BRAIN_DIR.glob("brain-*.json"), key=lambda item: item.stat().st_mtime, reverse=True)[:limit]: | |
| try: | |
| runs.append(json.loads(path.read_text(encoding="utf-8"))) | |
| except Exception: | |
| pass | |
| return {"runs": runs, "total": len(runs), "brain_dir": str(BRAIN_DIR)} | |
| def register_brain_routes(app) -> None: | |
| async def get_brain_runs(limit: int = 25) -> dict[str, Any]: | |
| return list_brain_runs(limit=limit) | |
| async def get_brain_status() -> dict[str, Any]: | |
| return { | |
| "budgets": BUDGETS, | |
| "contract": { | |
| "execution_first": "plan internally, validate utility/readiness/budget/risk, then dispatch eligible work", | |
| "share_after_validation": "user_brief is returned only after hard quality gates pass unless explicitly disabled", | |
| "assistance_mode": "assist mode creates an iron-clad brief without dispatching tasks", | |
| }, | |
| } | |
| async def create_brain_blueprint(request: BrainRequest) -> dict[str, Any]: | |
| return build_brain_blueprint(request) | |
| async def execute_brain(request: BrainRequest) -> dict[str, Any]: | |
| return await execute_brain_request(request) | |