#!/usr/bin/env python3 # Optional ML AI subprocess bridge for Space Gaem providing status, policy prediction, and online training over JSON. # No idea if this works or not, but I think it kinda does. Hopefully. from __future__ import annotations import argparse import importlib.util import json import math import os import sys from pathlib import Path from typing import Any, Dict, List DEFAULT_WEIGHTS_PATH = Path(__file__).resolve().parent.parent / "data" / "ml_policy_weights.json" FEATURE_NAMES = [ "bias", "dv_margin_proxy", "budget_per_dv", "tier_norm", "is_home_sponsor", "rad_hazard", "meteor_hazard", "shear_hazard", "weather_sev", "skill", ] def detect_backends() -> Dict[str, Any]: candidates = ["onnxruntime", "torch", "sklearn", "numpy"] available = [pkg for pkg in candidates if importlib.util.find_spec(pkg) is not None] if "onnxruntime" in available: active = "onnxruntime" elif "torch" in available: active = "pytorch" elif "sklearn" in available: active = "sklearn-sgd" elif "numpy" in available: active = "numpy-mlp" else: active = "python-stdlib-mlp" return {"active": active, "availablePackages": available} def default_weights_store() -> Dict[str, Any]: return { "version": 1, "episodes": 0, "avgReward": 0.0, "sharedWeights": [0.2, 1.35, 1.1, 0.25, 0.65, -0.45, -0.35, -0.25, -0.35, 0.55], "hiddenBias": [0.1, -0.05, 0.15, 0.0], "agencies": {}, } def load_weights(path: Path) -> Dict[str, Any]: if not path.exists(): return default_weights_store() try: data = json.loads(path.read_text(encoding="utf-8")) base = default_weights_store() base.update(data) if len(base.get("sharedWeights", [])) != len(FEATURE_NAMES): base["sharedWeights"] = default_weights_store()["sharedWeights"] return base except Exception: return default_weights_store() def save_weights(path: Path, data: Dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=2), encoding="utf-8") os.replace(tmp, path) def dot(a: List[float], b: List[float]) -> float: return sum(float(x) * float(y) for x, y in zip(a, b)) def sigmoid(z: float) -> float: if z > 30: return 1.0 if z < -30: return 0.0 return 1.0 / (1.0 + math.exp(-z)) def _candidate_penalty(candidate: Dict[str, Any], payload: Dict[str, Any]) -> float: agency = payload.get("agency") or {} treasury = max(1e6, float(agency.get("treasury", 60e6))) difficulty = str(agency.get("difficulty", "engineer")) unlocked = set(agency.get("unlockedTechs") or ["starter"]) has_high_isp = difficulty in ("sandbox", "explorer") or bool( unlocked.intersection({"cryo-hydrolox", "methalox-reusable", "heavy-lift", "deep-space-ion"}) ) req_dv = max(1000.0, float(candidate.get("requiredDv", 9500))) tier = float(candidate.get("tier", 0)) est_cost = max(6e6, (req_dv / 9500.0) * 14.5e6 + tier * 5.5e6) penalty = 0.0 if not has_high_isp and req_dv > 9800.0: penalty += 2.4 if est_cost > treasury * 0.68: penalty += 2.5 return penalty def extract_features(candidate: Dict[str, Any], payload: Dict[str, Any]) -> List[float]: agency = payload.get("agency") or {} treasury = max(1e6, float(agency.get("treasury", 60e6))) skill = float(agency.get("aiSkill", 0.85)) difficulty = str(agency.get("difficulty", "engineer")) unlocked = set(agency.get("unlockedTechs") or ["starter"]) has_high_isp = difficulty in ("sandbox", "explorer") or bool( unlocked.intersection({"cryo-hydrolox", "methalox-reusable", "heavy-lift", "deep-space-ion"}) ) req_dv = max(1000.0, float(candidate.get("requiredDv", 9500))) budget = float(candidate.get("budget", 20e6)) tier = float(candidate.get("tier", 0)) is_home = 1.0 if candidate.get("isHomeSponsor") else 0.0 hazards = payload.get("hazards") or [] rad_haz = 1.0 if any(h.get("kind") == "stray-radiation" for h in hazards) else 0.0 met_haz = 1.0 if any(h.get("kind") == "meteorite-stream" for h in hazards) else 0.0 shear_haz = 1.0 if any(h.get("kind") == "jet-stream-shear" for h in hazards) else 0.0 weather = str(payload.get("weather", "nominal")) weather_sev = 0.0 if weather == "nominal" else (0.35 if weather == "solar-wind" else 0.8) tech_bonus_dv = 2600.0 if has_high_isp else 0.0 est_cap_dv = 9400.0 + tech_bonus_dv + min(2.0, treasury / 60e6) * 1200.0 + skill * 1000.0 afford_penalty = 1.0 if (max(6e6, (req_dv / 9500.0) * 14.5e6 + tier * 5.5e6) > treasury * 0.68) else 0.0 dv_margin_proxy = max(-2.0, min(2.0, (est_cap_dv - req_dv) / 4000.0 - afford_penalty)) budget_per_dv = min(3.0, (budget / 1e6) / max(1.0, req_dv / 1000.0)) tier_norm = min(1.0, tier / 3.0) return [ 1.0, dv_margin_proxy, budget_per_dv, tier_norm, is_home, rad_haz, met_haz, shear_haz, weather_sev, skill, ] def handle_status(weights_path: Path) -> Dict[str, Any]: backends = detect_backends() store = load_weights(weights_path) return { "ok": True, "pythonVersion": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}", "backend": backends["active"], "availablePackages": backends["availablePackages"], "weightsPath": str(weights_path), "weightsLoaded": weights_path.exists(), "episodes": int(store.get("episodes", 0)), "avgReward": round(float(store.get("avgReward", 0.0)), 4), } def handle_predict(payload: Dict[str, Any], weights_path: Path) -> Dict[str, Any]: backends = detect_backends() store = load_weights(weights_path) agency = payload.get("agency") or {} agency_name = str(agency.get("name", "")) ag_entry = store.get("agencies", {}).get(agency_name, {}) weights = ag_entry.get("weights") or store["sharedWeights"] if len(weights) != len(FEATURE_NAMES): weights = store["sharedWeights"] candidates = payload.get("candidates") or [] best_id = None best_tpl = None best_cand: Dict[str, Any] = {} best_score = -1e9 scores: List[Dict[str, Any]] = [] use_torch = False if backends["active"] == "pytorch": try: import torch use_torch = True w_tensor = torch.tensor(weights, dtype=torch.float32) for c in candidates: feats = extract_features(c, payload) x_tensor = torch.tensor(feats, dtype=torch.float32) logit = float(torch.dot(w_tensor, x_tensor).item()) - _candidate_penalty(c, payload) prob = sigmoid(logit) scores.append({"offerId": c.get("offerId") or c.get("id"), "score": round(prob, 4)}) if logit > best_score: best_score = logit best_id = c.get("offerId") or c.get("id") best_tpl = c.get("templateId") or c.get("id") best_cand = c except Exception: use_torch = False if not use_torch: for c in candidates: feats = extract_features(c, payload) logit = dot(weights, feats) - _candidate_penalty(c, payload) prob = sigmoid(logit) scores.append({"offerId": c.get("offerId") or c.get("id"), "score": round(prob, 4)}) if logit > best_score: best_score = logit best_id = c.get("offerId") or c.get("id") best_tpl = c.get("templateId") or c.get("id") best_cand = c hazards = payload.get("hazards") or [] has_shear = any(h.get("kind") == "jet-stream-shear" for h in hazards) has_rad = any(h.get("kind") == "stray-radiation" for h in hazards) or best_cand.get("radiationHazard") == "extreme" skill = float(agency.get("aiSkill", 0.85)) best_dv = float(best_cand.get("requiredDv", 9500)) pitch_kick = 7.4 if has_shear else (10.1 if best_dv > 10600 else 8.8 + skill * 1.1) return { "ok": True, "backend": backends["active"], "selectedOfferId": best_id, "selectedTemplateId": best_tpl, "policyConfidence": round(sigmoid(best_score), 3) if candidates else 0.5, "suggestedPitchKickDeg": round(pitch_kick, 2), "suggestedMaxQThrottle": round(0.66 if has_shear else 0.78, 2), "suggestedPreferRadHard": bool(has_rad), "scores": scores[:8], } def handle_train(payload: Dict[str, Any], weights_path: Path) -> Dict[str, Any]: backends = detect_backends() store = load_weights(weights_path) agency_name = str(payload.get("agencyName", "ML-AI")) reward = max(-1.5, min(2.0, float(payload.get("reward", 0.0)))) candidate = payload.get("candidate") or {} feats = payload.get("features") or extract_features(candidate, payload) if len(feats) != len(FEATURE_NAMES): feats = default_weights_store()["sharedWeights"] ag_map = store.setdefault("agencies", {}) ag_entry = ag_map.setdefault( agency_name, {"weights": list(store["sharedWeights"]), "episodes": 0, "avgReward": 0.0}, ) lr = 0.045 baseline = float(ag_entry.get("avgReward", 0.0)) advantage = reward - baseline * 0.5 if backends["active"] == "pytorch": try: import torch w_t = torch.tensor(ag_entry["weights"], dtype=torch.float32) x_t = torch.tensor(feats, dtype=torch.float32) pred = torch.sigmoid(torch.dot(w_t, x_t)) grad_scale = lr * (advantage - 0.15 * float(pred.item())) new_w = torch.clamp(w_t * 0.995 + grad_scale * x_t, -4.0, 4.0) ag_entry["weights"] = [round(float(v), 5) for v in new_w.tolist()] except Exception: pred = sigmoid(dot(ag_entry["weights"], feats)) ag_entry["weights"] = [ round(max(-4.0, min(4.0, w * 0.995 + lr * (advantage - 0.15 * pred) * f)), 5) for w, f in zip(ag_entry["weights"], feats) ] else: pred = sigmoid(dot(ag_entry["weights"], feats)) ag_entry["weights"] = [ round(max(-4.0, min(4.0, w * 0.995 + lr * (advantage - 0.15 * pred) * f)), 5) for w, f in zip(ag_entry["weights"], feats) ] store["sharedWeights"] = [ round(0.92 * sw + 0.08 * aw, 5) for sw, aw in zip(store["sharedWeights"], ag_entry["weights"]) ] ep_ag = int(ag_entry.get("episodes", 0)) + 1 ag_entry["episodes"] = ep_ag ag_entry["avgReward"] = round(((ep_ag - 1) * float(ag_entry.get("avgReward", 0.0)) + reward) / ep_ag, 4) ep_tot = int(store.get("episodes", 0)) + 1 store["episodes"] = ep_tot store["avgReward"] = round(((ep_tot - 1) * float(store.get("avgReward", 0.0)) + reward) / ep_tot, 4) save_weights(weights_path, store) return { "ok": True, "backend": backends["active"], "agencyEpisodes": ep_ag, "agencyAvgReward": ag_entry["avgReward"], "episodes": ep_tot, "avgReward": store["avgReward"], } def main() -> int: parser = argparse.ArgumentParser(description="Space Gaem optional ML AI bridge") parser.add_argument("action", nargs="?", default="status", choices=["status", "predict", "train"]) parser.add_argument("--payload", default="", help="JSON payload string") parser.add_argument("--weights", default=str(DEFAULT_WEIGHTS_PATH), help="Path to policy weights JSON") args = parser.parse_args() payload: Dict[str, Any] = {} raw = args.payload.strip() if raw == "-": raw = sys.stdin.read().strip() elif not raw and not sys.stdin.isatty(): raw = sys.stdin.read().strip() if raw: try: payload = json.loads(raw) except Exception as exc: print(json.dumps({"ok": False, "error": f"Invalid JSON payload: {exc}"})) return 1 action = payload.get("action") or args.action weights_path = Path(args.weights) if action == "status": out = handle_status(weights_path) elif action == "predict": out = handle_predict(payload, weights_path) elif action == "train": out = handle_train(payload, weights_path) else: out = {"ok": False, "error": f"Unknown action {action}"} print(json.dumps(out)) return 0 if __name__ == "__main__": raise SystemExit(main())