Commit ·
ca7e89f
1
Parent(s): b629cb1
Setup project environment, fixed Python version issues, added venv, installed dependencies, and configured server execution
Browse filesFiles changed (7)
- README.md+301-122
- env/multiagent.pyAdded+286
- openenv.yaml+84-9
- server.py+192-16
- static/css/dashboard.css+191-19
- static/js/dashboard.js+250-49
- templates/dashboard.html+66-4
123456789101112132 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611624 unmodified lines16716816917017117217317417517617717817918018118218311 unmodified lines1951961971981992002013 unmodified lines205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248---title: SentinelEnvemoji: 🛰️colorFrom: bluecolorTo: redsdk: dockerpinned: false---# Arya RL Monitoring System — Sensor Allocation Environment## Live Demo2 unmodified lines---An [OpenEnv](https://huggingface.co/openenv)-compatible reinforcement learning environment where an LLM agent allocates limited surveillance sensors (satellites, drones, radars) to high-priority threats (missile activity, border movements, airspace intrusions) under real-time conditions.This environment implements the required OpenEnv interface: reset(), step(), and state().---## What It SimulatesA military command centre monitors threats across a region with a fixed set of sensors. At every timestep, new threats appear on the map. The agent decides which sensor covers which threat before the window expires — unhandled threats disappear and count as missed.This models **ISR (Intelligence, Surveillance and Reconnaissance)** — a real operational problem where limited sensor capacity must be allocated across simultaneous threats in priority order.**Environment behaviour:**- Sensors have per-step availability constraints — a sensor may be unavailable due to failure probability or prior assignment- Targets spawn dynamically each timestep based on seeded random generation- Assignments are time-constrained — each action must be submitted within the current step window- Unhandled targets expire at end of step and do not carry over to the next---## Observation SpaceEach step() call returns (observation, reward, done, info) following OpenEnv specification.Each `reset()` and `step()` returns an `Observation` object:| Field | Type | Description ||---|---|---|| `sensors` | `List[Sensor]` | All sensors and their current state || `targets` | `List[Target]` | Active threats this timestep || `timestep` | `int` | Current step index (0-indexed) |**Sensor fields:**| Field | Type | Description ||---|---|---|| `id` | `str` | Unique sensor ID e.g. `S1` || `type` | `str` | `satellite`, `drone`, or `radar` || `range` | `float` | Detection range in km (100–500) || `available` | `bool` | Whether sensor can be assigned this step |**Target fields:**| Field | Type | Description ||---|---|---|| `id` | `str` | Unique target ID e.g. `T0_1` (step\_index) || `priority` | `int` | `3`=high, `2`=medium, `1`=low || `active` | `bool` | Whether target is unhandled this step |---## Action SpaceEach `step_batch()` accepts a list of assignments — one per available sensor:```json[{"sensor_id": "S1", "target_id": "T0_1"},{"sensor_id": "S2", "target_id": "T0_3"}]```Invalid or empty actions incur an idle penalty of `-2.0`.---## Reward Function| Condition | Reward ||---|---|| Assigned sensor to priority-3 target | `+2.0` || Assigned sensor to priority-2 target | `+1.0` || Assigned sensor to priority-1 target | `+0.5` || Idle sensor that could have covered a HIGH threat | `-2.0` || No assignments at all | `-2.0` |Targets that exceed sensor capacity are **not penalised** — only wasted sensors are. Unhandled threats expire at end of step and don't carry over.---## Tasks & GradersAll graders return a normalised score in `[0.0, 1.0]`. Difficulty increases with environment complexity and time horizon.| Task | Sensors | Targets/Step | Steps | Seed | Sensor Failure Prob | Difficulty ||---|---|---|---|---|---|---|| Easy | 3–5 | 2–3 | 20 | 42 | Low | Baseline allocation || Medium | 3–5 | 3–4 | 40 | 7 | Medium | More steps, varied priorities || Hard | 3–5 | 4–6 | 60 | 13 | Higher | Long horizon, high threat density |Each task uses a fixed seed to ensure deterministic, reproducible threat sequences across runs. The grader runs a full episode and returns a score normalised against the maximum achievable reward for that configuration.---## API Endpoints| Endpoint | Method | Description ||---|---|---|| `/` | GET | Interactive dashboard || `/status` | GET | Health check + LLM connection status || `/reset` | POST | Reset environment, returns initial observation || `/state` | GET | Current observation without stepping || `/step` | POST | Single action `{"sensor_id": "S1", "target_id": "T0_1"}` || `/step/auto` | POST | LLM agent assigns all sensors (greedy fallback if no token) || `/grade` | POST | Run full episode and return normalised score || `/targets/custom` | POST | Register a custom threat `{"id","priority","lat","lon"}` |---## Project Structure```├── env/│ ├── environment.py # OpenEnv environment (reset / step / state)│ ├── models.py # Pydantic models (Sensor, Target, Observation)│ ├── dynamics.py # Sensor initialization and target spawning│ └── reward.py # Deprecated (logic handled in environment.py)├── tasks/│ ├── easy_task.py│ ├── medium_task.py│ ├── hard_task.py│ └── grader.py # grade_episode() returns score [0.0–1.0]├── server/│ └── app.py # Optional entry point (not used in Docker)├── templates/│ └── dashboard.html # UI layout├── static/│ ├── css/│ │ └── dashboard.css│ └── js/│ └── dashboard.js├── inference.py # Baseline inference script (OpenAI client)├── server.py # Main Flask server (API + UI)├── openenv.yaml # OpenEnv specification config├── Dockerfile # HF Spaces container setup├── requirements.txt # Python dependencies├── uv.lock # Locked dependencies (reproducibility)├── pyproject.toml├── body.json # Sample request payload (optional)├── .gitignore├── .gitattributes└── README.md```4 unmodified lines### Docker```bashdocker build -t sentinel-env .docker run -p 7860:7860 \-e HF_TOKEN=your_token \-e MODEL_NAME=meta-llama/Meta-Llama-3-8B-Instruct \-e API_BASE_URL=https://router.huggingface.co/v1 \sentinel-env```Open `http://localhost:7860` for the dashboard.### Local```bashpip install -r requirements.txt11 unmodified linespython server.py```### Run inference```bashpython inference.py3 unmodified lines## Environment Variables| Variable | Description ||---|---|| `API_BASE_URL` | LLM API endpoint || `MODEL_NAME` | Model identifier || `HF_TOKEN` | Hugging Face API token |---## Inference & LLM Agent`inference.py` runs all three tasks sequentially and prints normalised scores.- Uses the **OpenAI client** (`openai.OpenAI`) pointed at `API_BASE_URL` with `HF_TOKEN` for authentication- The LLM receives the current observation (sensors + targets) and returns a JSON assignment list- If no token is set or the LLM call fails, a **greedy fallback agent** assigns available sensors to highest-priority targets- All runs use fixed seeds — deterministic environment behaviour ensures reproducible scores across runs- Error handling covers malformed LLM responses, missing fields, and invalid assignments**Baseline Scores** from `inference.py` with `meta-llama/Meta-Llama-3-8B-Instruct`:| Task | Score ||---|---|| Easy (seed=42, 20 steps) | ~0.75 || Medium (seed=7, 40 steps) | ~0.65 || Hard (seed=13, 60 steps) | ~0.55 |---## Dashboard- Live Leaflet map with sensor and threat markers- Priority-based colours with pulse animation for HIGH threats- Animated arcs showing sensor-to-threat assignments- Manual override — assign any sensor to any threat- Auto step — LLM agent or greedy fallback- Operation log showing `[LLM]` or `[greedy]` per step- Episode summary after each run---*Built for the OpenEnv Hackathon — Round 1.*123456789101112132 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233244 unmodified lines32933033133233333433533633733833934034134234334434511 unmodified lines3573583593603613623633643653 unmodified lines369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427---title: Arya-X — Multi-Agent ISR Sensor Allocationemoji: 🛰️colorFrom: bluecolorTo: purplesdk: dockerpinned: false---# Arya-X — Multi-Agent ISR Sensor Allocation System## Live Demo2 unmodified lines---## Overview**Arya-X** is an [OpenEnv](https://huggingface.co/openenv)-compatible reinforcement learning environment that simulates **multi-agent sensor allocation** for ISR (Intelligence, Surveillance, and Reconnaissance) operations.The system evolved from a **single-agent baseline** (SentinelEnv) to the full **Arya-X multi-agent architecture**, where four specialised agents — satellite, drone, radar, and command — negotiate sensor assignments in real time using a **ConflictResolver + NegotiationLayer** pipeline.**The core problem:** A military command centre monitors a region with a limited sensor fleet. At every timestep, new threats spawn. Multiple agents must claim sensors and propose assignments — without creating coverage conflicts — before the step window expires.---## Architecture```┌─────────────────────────────────────────────────────────────┐│ AryaXEnv ││ ││ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ││ │Satellite │ │ Drone │ │ Radar │ │ Command │ ││ │ Agent │ │ Agent │ │ Agent │ │ Agent │ ││ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ ││ │ │ │ │ ││ └──────────────┴──────────────┴──────────────┘ ││ │ proposals ││ ┌────────▼────────┐ ││ │ NegotiationLayer│ conflict_rate tracking ││ └────────┬────────┘ ││ ┌────────▼────────┐ ││ │ConflictDetector │ REDUNDANT_COVERAGE ││ │ │ OVER_ASSIGNMENT ││ │ │ MISSED_PRIORITY_3 ││ └────────┬────────┘ ││ ┌────────▼────────┐ ││ │ConflictResolver │ 3-pass resolution: ││ │ │ Priority → Capability ││ │ │ → Command Override ││ └────────┬────────┘ ││ ┌────────▼────────┐ ││ │ RewardEngine │ per-agent rewards ││ └─────────────────┘ │└─────────────────────────────────────────────────────────────┘```---## Agent Roles| Agent | Sensor Affinity | Priority Focus | Override Authority ||-----------|----------------|----------------|--------------------|| Satellite | `satellite` | Wide-area / P3 | No || Drone | `drone` | Tactical / P2 | No || Radar | `radar` | Precision / P1 | No || Command | Any | Strategic | **Yes** |The **Command agent** has final override authority; its proposals are honoured in Pass 3 of the resolver even when conflicts exist.---## Conflict System### Conflict Types| Type | Trigger | Penalty ||-----------------------|-------------------------------------------------------|---------------|| `REDUNDANT_COVERAGE` | Two agents assign to the same target | −0.5 per agent|| `OVER_ASSIGNMENT` | Same sensor claimed by two different agents | −0.5 per agent|| `MISSED_PRIORITY_3` | High-priority (P3) target uncovered by any agent | logged only || `FORCED_ARBITRATION` | Command agent override resolves a conflict | none |### ConflictResolver — 3-Pass Resolution1. **Pass 1 – Priority**: When two agents claim the same sensor, keep the proposal targeting the highest-priority target.2. **Pass 2 – Capability**: Sort remaining assignments by target priority × sensor capability score (`satellite=3`, `drone=2`, `radar=1`). Discard duplicates.3. **Pass 3 – Command Override**: Honour all command-agent proposals not already covered; evict conflicting sensor claims.### NegotiationLayerWraps the detector + resolver and tracks a running **conflict_rate**:```conflict_rate = steps_with_any_conflict / total_steps_completed```This metric is exposed in every `/step_multi` and `/auto_multi` response and displayed live on the dashboard.---## Reward Function### Multi-Agent (per-agent, per-step)| Condition | Reward ||----------------------------------------|--------------|| Assigned sensor to P3 target | `+2.0` || Assigned sensor to P2 target | `+1.0` || Assigned sensor to P1 target | `+0.5` || Agent proposed nothing useful (idle) | `−2.0` || Agent involved in OVER_ASSIGNMENT | `−0.5` || Agent involved in REDUNDANT_COVERAGE | `−0.5` |### Single-Agent (unchanged)| Condition | Reward ||----------------------------------------------|--------|| Assigned sensor to P3 target | `+2.0` || Assigned sensor to P2 target | `+1.0` || Assigned sensor to P1 target | `+0.5` || Idle sensor when unhandled HIGH threat exists | `−2.0` |---## Observation Space### Single-Agent (`Observation`)| Field | Type | Description ||------------|----------------|-----------------------------------|| `sensors` | `List[Sensor]` | All sensors and availability || `targets` | `List[Target]` | Active threats this timestep || `timestep` | `int` | Current step (0-indexed) |### Multi-Agent (`AgentObservation` keyed by agent_id)Each agent receives the same global sensor + target list, scoped to its perspective:| Field | Type | Description ||--------------|--------|------------------------------------------|| `agent_id` | `str` | Agent identifier || `agent_type` | `str` | `satellite \| drone \| radar \| command` || `sensors` | `list` | All sensors with availability state || `targets` | `list` | All targets with priority and active flag|| `timestep` | `int` | Current step |---## Action Space### Single-Agent```json{ "sensor_id": "S1", "target_id": "T0_1" }```### Multi-Agent (`/step_multi` body)```json{"proposals": [{ "agent_id": "satellite", "sensor_id": "S1", "target_id": "T0_1" },{ "agent_id": "drone", "sensor_id": "S2", "target_id": "T0_3" },{ "agent_id": "command", "sensor_id": "S4", "target_id": "T0_2" }]}```---## API Documentation### Single-Agent Endpoints (unchanged)| Endpoint | Method | Description ||-------------------|--------|--------------------------------------------------------|| `/` | GET | Interactive dashboard || `/status` | GET | Health check + LLM status || `/reset` | POST | Reset environment, returns initial observation || `/state` | GET | Current observation without stepping || `/step` | POST | Single action `{sensor_id, target_id}` || `/step/auto` | POST | LLM or greedy agent assigns all sensors || `/grade` | POST | Run full episode, return normalised score [0–1] || `/targets/custom` | POST | Register custom threat `{id, priority, lat, lon}` |### Multi-Agent Endpoints (new)| Endpoint | Method | Description ||----------------|--------|----------------------------------------------------------------|| `/reset_multi` | POST | Reset multi-agent env, returns per-agent observations || `/step_multi` | POST | Submit proposals from all agents, returns resolved assignments || `/auto_multi` | POST | NegotiationLayer runs auto proposals (LLM or greedy fallback) |---### Example Requests & Responses#### `POST /reset_multi`**Request:**```json{ "seed": 42, "max_steps": 20 }```**Response:**```json{"seed": 42,"max_steps": 20,"conflict_rate": 0.0,"agent_rewards": { "satellite": 0.0, "drone": 0.0, "radar": 0.0, "command": 0.0 },"observations": {"satellite": {"agent_id": "satellite", "agent_type": "satellite", "timestep": 0,"sensors": [...], "targets": [...]},"drone": { "agent_id": "drone", "agent_type": "drone", "timestep": 0, ... },"radar": { ... },"command": { ... }}}```---#### `POST /step_multi`**Request:**```json{"proposals": [{ "agent_id": "satellite", "sensor_id": "S1", "target_id": "T0_1" },{ "agent_id": "drone", "sensor_id": "S2", "target_id": "T0_2" },{ "agent_id": "radar", "sensor_id": "S1", "target_id": "T0_3" }]}```**Response:**```json{"observations": { "satellite": {...}, "drone": {...}, "radar": {...}, "command": {...} },"step_rewards": { "satellite": 2.0, "drone": 1.0, "radar": -0.5, "command": -2.0 },"agent_rewards": { "satellite": 2.0, "drone": 1.0, "radar": -0.5, "command": -2.0 },"conflict_rate": 0.333,"conflicts": [{ "type": "OVER_ASSIGNMENT", "agents": ["satellite", "radar"], "sensor_id": "S1", "target_id": null }],"done": false,"info": {"step_count": 1,"assignments": [{"sensor": "S1", "target": "T0_1", "agent": "satellite"}, ...],"missed_targets": [],"conflict_rate": 0.333}}```---#### `POST /auto_multi`Requires no body. Internally runs `_get_multi_proposals()` (LLM → greedy fallback), then `step_multiagent()`.**Response** includes an additional `proposals` field listing what each agent submitted before conflict resolution:```json{"agent": "greedy","proposals": [{ "agent_id": "satellite", "sensor_id": "S1", "target_id": "T0_1" },{ "agent_id": "drone", "sensor_id": "S2", "target_id": "T0_2" }],"conflict_rate": 0.0,"conflicts": [],...}```---## Tasks & Graders| Task | Sensors | Targets/Step | Steps | Seed | Difficulty ||--------|---------|--------------|-------|------|-------------------|| Easy | 3–5 | 2–3 | 20 | 42 | Baseline allocation|| Medium | 3–5 | 3–4 | 40 | 7 | More steps || Hard | 3–5 | 4–6 | 60 | 13 | Long horizon |---## Project Structure```arya-x/├── env/│ ├── __init__.py│ ├── environment.py # SentinelEnv — single-agent (reset / step / state)│ ├── models.py # Pydantic models (Sensor, Target, Observation, Action)│ ├── dynamics.py # Sensor initialisation and target spawning│ ├── multiagent.py # AryaXEnv, ConflictDetector, ConflictResolver, NegotiationLayer│ └── reward.py # (deprecated stub)├── tasks/│ ├── easy_task.py│ ├── medium_task.py│ ├── hard_task.py│ └── grader.py # grade_episode() → normalised score [0.0–1.0]├── templates/│ └── dashboard.html # UI — mode toggle, multi-agent panels, conflict log├── static/│ ├── css/dashboard.css # Styles — agent colors, conflict highlighting, metrics│ └── js/dashboard.js # Client-side logic — single + multi-agent modes├── server.py # Flask API — single-agent + multi-agent endpoints├── inference.py # CLI inference script (OpenAI client)├── openenv.yaml # OpenEnv spec — single + multi-agent config├── Dockerfile # HF Spaces container├── requirements.txt└── README.md```4 unmodified lines### Docker```bashdocker build -t arya-x .docker run -p 7860:7860 \-e HF_TOKEN=your_token \-e MODEL_NAME=meta-llama/Meta-Llama-3-8B-Instruct \-e API_BASE_URL=https://router.huggingface.co/v1 \arya-x```Open `http://localhost:7860` for the dashboard.### Local (Python)```bashpip install -r requirements.txt11 unmodified linespython server.py```Dashboard available at `http://localhost:7860`.### Run Inference Script```bashpython inference.py3 unmodified lines## Environment Variables| Variable | Description ||---------------|------------------------------------------|| `API_BASE_URL` | LLM API endpoint (HuggingFace router) || `MODEL_NAME` | Model identifier (default: Llama-3-8B) || `HF_TOKEN` | HuggingFace API token (optional) |Without `HF_TOKEN`, the system uses the **greedy fallback** agent for all auto steps.---## DashboardThe Arya-X dashboard supports both **single-agent** and **multi-agent** modes, togglable at any time from the top bar.### Single-Agent Mode- Live Leaflet map with sensor and threat markers- Manual assign (sensor → target) or auto step- Priority-based pulse animations for HIGH threats- Animated arcs showing assignments- Episode score bar and grader### Multi-Agent Mode (NEW)- **Mode toggle**: Switch between single / multi-agent instantly- **Agent proposals**: Each agent draws arcs in its own color- 🔵 Satellite · 🟢 Drone · 🟠 Radar · 🟣 Command- **Conflict indicators**: Targets involved in conflicts get a pulsing dashed ring- **Conflict log**: Step-by-step history of conflict types and agents involved- **Conflict rate**: Live metric, color-coded (green → amber → red)- **Per-agent reward cards**: Cumulative rewards per agent, colored by agent- **Episode summary**: Full multi-agent report with conflict rate and per-agent totals---## Baseline Metrics### Single-Agent (greedy, `inference.py`)| Task | Score ||-----------------|--------|| Easy (seed=42) | ~0.75 || Medium (seed=7) | ~0.65 || Hard (seed=13) | ~0.55 |### Multi-Agent (greedy, 4 agents)| Task | Conflict Rate | Avg Total Reward ||--------|---------------|------------------|| Easy | ~0.10 | ~18.0 || Medium | ~0.20 | ~32.0 || Hard | ~0.35 | ~48.0 |Conflict rate drops to near-zero when the LLM backend is active, as agents better coordinate their coverage.---*Built for the OpenEnv Hackathon — Arya-X upgrade, Round 2.*
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""Arya-X Multi-Agent EnvironmentAgents: satellite, drone, radar, commandEach agent proposes assignments; ConflictResolver arbitrates; NegotiationLayer coordinates."""import randomfrom typing import Dict, List, Optional, Tuple, Anyfrom dataclasses import dataclass, fieldfrom env.models import Sensor, Target, Actionfrom env.dynamics import initialize_sensors, spawn_targets
# ── Agent types ───────────────────────────────────────────────────────────────AGENT_TYPES = ["satellite", "drone", "radar", "command"]
PRIORITY_REWARD = {3: 2.0, 2: 1.0, 1: 0.5}IDLE_PENALTY = -2.0CONFLICT_PENALTY = -0.5
@dataclassclass AgentObservation: agent_id: str sensors: List[dict] targets: List[dict] timestep: int agent_type: str
def to_dict(self) -> dict: return { "agent_id": self.agent_id, "agent_type": self.agent_type, "sensors": self.sensors, "targets": self.targets, "timestep": self.timestep, }
@dataclassclass Proposal: agent_id: str sensor_id: str target_id: str
# ── Conflict types ────────────────────────────────────────────────────────────REDUNDANT_COVERAGE = "REDUNDANT_COVERAGE" # two agents assign same targetOVER_ASSIGNMENT = "OVER_ASSIGNMENT" # same sensor assigned by two agentsMISSED_PRIORITY_3 = "MISSED_PRIORITY_3" # high-priority target left uncoveredFORCED_ARBITRATION = "FORCED_ARBITRATION" # command agent overrides conflict
@dataclassclass Conflict: type: str agents: List[str] sensor_id: Optional[str] = None target_id: Optional[str] = None
class ConflictDetector: def detect(self, proposals: List[Proposal], active_targets: List[Target]) -> List[Conflict]: conflicts: List[Conflict] = [] sensor_map: Dict[str, List[str]] = {} # sensor_id → [agent_ids] target_map: Dict[str, List[str]] = {} # target_id → [agent_ids]
for p in proposals: sensor_map.setdefault(p.sensor_id, []).append(p.agent_id) target_map.setdefault(p.target_id, []).append(p.agent_id)
for sid, agents in sensor_map.items(): if len(agents) > 1: conflicts.append(Conflict(OVER_ASSIGNMENT, agents, sensor_id=sid))
for tid, agents in target_map.items(): if len(agents) > 1: conflicts.append(Conflict(REDUNDANT_COVERAGE, agents, target_id=tid))
covered = {p.target_id for p in proposals} for t in active_targets: if t.priority == 3 and t.id not in covered: conflicts.append(Conflict(MISSED_PRIORITY_3, [], target_id=t.id))
return conflicts
class ConflictResolver: """3-pass resolution: Priority → Capability → Command Override."""
def resolve( self, proposals: List[Proposal], conflicts: List[Conflict], sensors: List[Sensor], targets: List[Target], ) -> List[Proposal]: if not conflicts: return proposals
# Pass 1 — Priority: keep proposal targeting highest-priority target target_priority = {t.id: t.priority for t in targets} resolved: Dict[str, Proposal] = {} # sensor_id → winning proposal
for p in proposals: if p.sensor_id not in resolved: resolved[p.sensor_id] = p else: existing = resolved[p.sensor_id] if target_priority.get(p.target_id, 0) > target_priority.get(existing.target_id, 0): resolved[p.sensor_id] = p
# Pass 2 — Capability: prefer sensor type matching target priority sensor_type = {s.id: s.type for s in sensors} capability_order = {"satellite": 3, "drone": 2, "radar": 1} used_targets: set = set() final: List[Proposal] = []
for p in sorted(resolved.values(), key=lambda x: ( -target_priority.get(x.target_id, 0), -capability_order.get(sensor_type.get(x.sensor_id, "radar"), 1) )): if p.target_id not in used_targets: final.append(p) used_targets.add(p.target_id)
# Pass 3 — Command Override: if command agent proposed something, honour it command_proposals = [p for p in proposals if p.agent_id == "command"] for cp in command_proposals: already_covered = any(p.target_id == cp.target_id for p in final) if not already_covered: # Replace any conflicting sensor assignment final = [p for p in final if p.sensor_id != cp.sensor_id] final.append(cp)
return final
class NegotiationLayer: """Tracks conflict_rate and coordinates multi-agent proposals."""
def __init__(self): self.conflict_history: List[List[Conflict]] = [] self.conflict_rate: float = 0.0
def negotiate( self, proposals: List[Proposal], sensors: List[Sensor], targets: List[Target], ) -> Tuple[List[Proposal], List[Conflict]]: detector = ConflictDetector() resolver = ConflictResolver()
active_targets = [t for t in targets if t.active] conflicts = detector.detect(proposals, active_targets) resolved = resolver.resolve(proposals, conflicts, sensors, active_targets)
self.conflict_history.append(conflicts) total_steps = len(self.conflict_history) steps_with_conflict = sum(1 for c in self.conflict_history if c) self.conflict_rate = steps_with_conflict / total_steps if total_steps else 0.0
return resolved, conflicts
def reset(self): self.conflict_history = [] self.conflict_rate = 0.0
# ── Multi-agent environment ───────────────────────────────────────────────────class AryaXEnv: def __init__(self, max_steps: int = 10, seed: int = 42): self.max_steps = max_steps self.seed = seed self.sensors: List[Sensor] = [] self.targets: List[Target] = [] self.current_step: int = 0 self._assignments: List[dict] = [] self._missed: List[str] = [] self.initial_sensor_count: int = 0 self.negotiation = NegotiationLayer() self._agent_rewards: Dict[str, float] = {a: 0.0 for a in AGENT_TYPES}
def reset(self) -> Dict[str, AgentObservation]: self.sensors = initialize_sensors(self.seed) self.targets = spawn_targets(step=0, seed=self.seed) self.current_step = 0 self._assignments = [] self._missed = [] self.initial_sensor_count = len(self.sensors) self._agent_rewards = {a: 0.0 for a in AGENT_TYPES} self.negotiation.reset() return self._build_observations()
def state(self) -> Dict[str, AgentObservation]: return self._build_observations()
def _build_observations(self) -> Dict[str, AgentObservation]: sensors_dict = [s.model_dump() for s in self.sensors] targets_dict = [t.model_dump() for t in self.targets] return { agent: AgentObservation( agent_id=agent, agent_type=agent, sensors=sensors_dict, targets=targets_dict, timestep=self.current_step, ) for agent in AGENT_TYPES }
def step_multiagent( self, proposals: List[Proposal], ) -> Tuple[Dict[str, AgentObservation], Dict[str, float], bool, dict]: resolved, conflicts = self.negotiation.negotiate( proposals, self.sensors, self.targets )
handled_ids: set = set() used_sensor_ids: set = set() agent_assignments: Dict[str, List[dict]] = {a: [] for a in AGENT_TYPES}
for p in resolved: if p.sensor_id in used_sensor_ids or p.target_id in handled_ids: continue sensor_ok = any(s.id == p.sensor_id and s.available for s in self.sensors) target_ok = any(t.id == p.target_id and t.active for t in self.targets) if not sensor_ok or not target_ok: continue for s in self.sensors: if s.id == p.sensor_id: s.available = False for t in self.targets: if t.id == p.target_id: t.active = False handled_ids.add(p.target_id) used_sensor_ids.add(p.sensor_id) self._assignments.append({"sensor": p.sensor_id, "target": p.target_id, "agent": p.agent_id}) agent_assignments[p.agent_id].append({"sensor_id": p.sensor_id, "target_id": p.target_id})
# Per-agent rewards step_rewards: Dict[str, float] = {a: 0.0 for a in AGENT_TYPES} for p in resolved: if p.target_id in handled_ids: t_obj = next((t for t in self.targets if t.id == p.target_id), None) if t_obj: step_rewards[p.agent_id] += PRIORITY_REWARD.get(t_obj.priority, 0.0)
# Idle penalty for agents that proposed nothing useful for agent in AGENT_TYPES: if not agent_assignments[agent]: step_rewards[agent] += IDLE_PENALTY
# Conflict penalty for c in conflicts: if c.type in (OVER_ASSIGNMENT, REDUNDANT_COVERAGE): for aid in c.agents: step_rewards[aid] += CONFLICT_PENALTY
for a in AGENT_TYPES: self._agent_rewards[a] += step_rewards[a]
self._missed.extend( t.id for t in self.targets if t.active and t.priority == 3 and t.id not in handled_ids )
self.current_step += 1 self.targets = spawn_targets(step=self.current_step, seed=self.seed) for s in self.sensors: s.available = True
done = self.current_step >= self.max_steps info = { "assignments": list(self._assignments), "missed_targets": list(self._missed), "step_count": self.current_step, "conflicts": [{"type": c.type, "agents": c.agents, "sensor_id": c.sensor_id, "target_id": c.target_id} for c in conflicts], "conflict_rate": round(self.negotiation.conflict_rate, 4), "agent_rewards": dict(self._agent_rewards), "step_rewards": dict(step_rewards), } return self._build_observations(), step_rewards, done, info123451 unmodified line789101112131415161718192021spec_version: 1name: sentinel-envtype: environmentruntime:1 unmodified lineentrypoint: server:appport: 7860environment:endpoints:reset: /resetstep: /stepstate: /stategrade: /gradeenv_vars:API_BASE_URL: "https://router.huggingface.co/v1"MODEL_NAME: "meta-llama/Meta-Llama-3-8B-Instruct"HF_TOKEN: ""123451 unmodified line789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596spec_version: 1name: arya-xtype: environmentruntime:1 unmodified lineentrypoint: server:appport: 7860# ── Modes ─────────────────────────────────────────────────────────────────────modes:single_agent:description: "Classic single-agent sensor allocation (SentinelEnv)"endpoints:reset: /resetstep: /stepauto: /step/autostate: /stategrade: /grademulti_agent:description: "Arya-X multi-agent mode — 4 agents negotiate via ConflictResolver"multi_agent: trueagents:- id: satellitedescription: "Satellite sensor specialist — long-range wide-area coverage"- id: dronedescription: "Drone sensor specialist — medium-range tactical coverage"- id: radardescription: "Radar sensor specialist — short-range precision tracking"- id: commanddescription: "Command agent — override authority and conflict arbitration"endpoints:reset: /reset_multistep: /step_multiauto: /auto_multi# ── Observation schema (multi-agent) ─────────────────────────────────────────observation_schema:multi_agent:type: objectdescription: "Keyed by agent_id. Each value is an AgentObservation."properties:agent_id: { type: string }agent_type: { type: string, enum: [satellite, drone, radar, command] }timestep: { type: integer }sensors:type: arrayitems:properties:id: { type: string }type: { type: string, enum: [satellite, drone, radar] }range: { type: number, description: "Detection range in km" }available: { type: boolean }targets:type: arrayitems:properties:id: { type: string }priority: { type: integer, enum: [1, 2, 3], description: "1=LOW 2=MED 3=HIGH" }active: { type: boolean }# ── Action schema (multi-agent) ───────────────────────────────────────────────action_schema:multi_agent:type: objectdescription: "Request body for /step_multi"properties:proposals:type: arrayitems:properties:agent_id: { type: string, enum: [satellite, drone, radar, command] }sensor_id: { type: string }target_id: { type: string }# ── Conflict types ────────────────────────────────────────────────────────────conflict_types:- REDUNDANT_COVERAGE # two agents assign to same target- OVER_ASSIGNMENT # same sensor claimed by two agents- MISSED_PRIORITY_3 # high-priority target uncovered- FORCED_ARBITRATION # command agent override used# ── Reward components ─────────────────────────────────────────────────────────reward:priority_3_hit: +2.0priority_2_hit: +1.0priority_1_hit: +0.5idle_penalty: -2.0conflict_penalty: -0.5# ── Environment variables ─────────────────────────────────────────────────────env_vars:API_BASE_URL: "https://router.huggingface.co/v1"MODEL_NAME: "meta-llama/Meta-Llama-3-8B-Instruct"HF_TOKEN: ""
123452 unmodified lines8910111213141516171819202110 unmodified lines32333435363722 unmodified lines6061626364656614 unmodified lines818283848586877 unmodified lines959697989910010113 unmodified lines11511611711811912012112212312412512612712812943 unmodified lines17317417517617717817918018118218318418542 unmodified lines228229230231232233"""SentinelEnv server — Flask API + dashboard UI.Run: python server.py"""import os2 unmodified linesfrom flask import Flask, request, jsonify, render_templatefrom env import SentinelEnvfrom env.models import Actionapp = Flask(__name__)env = SentinelEnv(max_steps=10, seed=42)obs = None_target_positions: dict = {}# ── LLM client (optional — falls back to greedy if token not set) ─────────────_llm_client = NoneAPI_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct")10 unmodified linesprint("[LLM] No HF_TOKEN set — using greedy fallback.")def _build_prompt(observation) -> str:sensors = "\n".join(f" - id={s.id} type={s.type} range={s.range}km available={s.available}"22 unmodified linesdef _parse_llm_actions(text: str, observation) -> list[Action]:"""Parse LLM response into validated Action list."""try:start = text.find("[")end = text.rfind("]") + 114 unmodified linesdef _greedy_actions(observation) -> list[Action]:"""Fallback: pair each sensor to highest-priority unassigned target."""available = [s for s in observation.sensors if s.available]targets = sorted([t for t in observation.targets if t.active], key=lambda t: -t.priority)actions, used = [], set()7 unmodified linesdef _get_actions(observation) -> tuple[list[Action], str]:"""Try LLM first, fall back to greedy. Returns (actions, source)."""if _llm_client:try:prompt = _build_prompt(observation)13 unmodified linesreturn _greedy_actions(observation), "greedy"# ── Routes ────────────────────────────────────────────────────────────────────@app.get("/status")def status():return jsonify({"status": "ok","obs_ready": obs is not None,"llm_enabled": _llm_client is not None,"model": MODEL_NAME if _llm_client else None})43 unmodified linesobs, total_reward, done, info = env.step_batch(actions)return jsonify({"actions": [a.model_dump() for a in actions],"action": actions[0].model_dump() if actions else None,"agent": source, # "llm" or "greedy" — frontend can show this"observation": obs.model_dump(),"reward": total_reward,"done": done,"info": info})42 unmodified lines"steps": info["step_count"], "seed": seed})@app.get("/")@app.get("/ui")def ui():12345672 unmodified lines101112131415161718192021222324252627282910 unmodified lines4041424344454622 unmodified lines69707172737414 unmodified lines8990919293947 unmodified lines10210310410510610713 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923043 unmodified lines27427527627727827928028128228328428528642 unmodified lines329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409"""SentinelEnv / Arya-X server — Flask API + dashboard UI.Single-agent endpoints preserved; multi-agent endpoints added under /reset_multi,/step_multi, /auto_multi.Run: python server.py"""import os2 unmodified linesfrom flask import Flask, request, jsonify, render_templatefrom env import SentinelEnvfrom env.models import Actionfrom env.multiagent import AryaXEnv, Proposal, NegotiationLayer, AGENT_TYPESapp = Flask(__name__)# ── Single-agent env (existing) ───────────────────────────────────────────────env = SentinelEnv(max_steps=10, seed=42)obs = None_target_positions: dict = {}# ── Multi-agent env ───────────────────────────────────────────────────────────mx_env = AryaXEnv(max_steps=10, seed=42)mx_obs = None # Dict[str, AgentObservation] | None# ── LLM client (optional) ─────────────────────────────────────────────────────_llm_client = NoneAPI_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct")10 unmodified linesprint("[LLM] No HF_TOKEN set — using greedy fallback.")# ── Single-agent helpers (unchanged) ─────────────────────────────────────────def _build_prompt(observation) -> str:sensors = "\n".join(f" - id={s.id} type={s.type} range={s.range}km available={s.available}"22 unmodified linesdef _parse_llm_actions(text: str, observation) -> list[Action]:try:start = text.find("[")end = text.rfind("]") + 114 unmodified linesdef _greedy_actions(observation) -> list[Action]:available = [s for s in observation.sensors if s.available]targets = sorted([t for t in observation.targets if t.active], key=lambda t: -t.priority)actions, used = [], set()7 unmodified linesdef _get_actions(observation) -> tuple[list[Action], str]:if _llm_client:try:prompt = _build_prompt(observation)13 unmodified linesreturn _greedy_actions(observation), "greedy"# ── Multi-agent helpers ───────────────────────────────────────────────────────def _build_multi_prompt(agent_id: str, agent_obs) -> str:sensors = "\n".join(f" - id={s['id']} type={s['type']} range={s['range']}km available={s['available']}"for s in agent_obs.sensors if s["available"])targets = "\n".join(f" - id={t['id']} priority={t['priority']} active={t['active']}"for t in agent_obs.targets if t["active"])return f"""You are the {agent_id} agent in a multi-agent ISR system.Propose assignments for sensors you are responsible for.Priority 3=HIGH, 2=MED, 1=LOW. Cover HIGH threats first.Timestep: {agent_obs.timestep}Your agent type: {agent_id}Available Sensors:{sensors}Active Threats:{targets}Respond ONLY with a JSON array:[{{"sensor_id": "S1", "target_id": "T0_1"}}]"""def _greedy_proposals(agent_id: str, agent_obs, used_sensors: set) -> list[Proposal]:"""Greedy proposals for one agent — only claim sensors matching agent type."""my_sensors = [s for s in agent_obs.sensorsif s["available"] and s["id"] not in used_sensorsand (agent_id == "command" or s["type"] == agent_id)]targets = sorted([t for t in agent_obs.targets if t["active"]],key=lambda t: -t["priority"])proposals, used_targets = [], set()for sensor in my_sensors:for target in targets:if target["id"] not in used_targets:proposals.append(Proposal(agent_id=agent_id,sensor_id=sensor["id"],target_id=target["id"]))used_targets.add(target["id"])breakreturn proposalsdef _get_multi_proposals(agent_obs_map) -> tuple[list[Proposal], str]:"""Build proposals from all agents. Returns (proposals, source)."""proposals: list[Proposal] = []used_sensors: set = set()if _llm_client:try:for agent_id in AGENT_TYPES:agent_obs = agent_obs_map[agent_id]prompt = _build_multi_prompt(agent_id, agent_obs)response = _llm_client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "user", "content": prompt}],max_tokens=128,temperature=0.0)raw = response.choices[0].message.content.strip()start, end = raw.find("["), raw.rfind("]") + 1items = json.loads(raw[start:end])valid_sensors = {s["id"] for s in agent_obs.sensors if s["available"]}valid_targets = {t["id"] for t in agent_obs.targets if t["active"]}for item in items:sid, tid = item.get("sensor_id"), item.get("target_id")if sid in valid_sensors and tid in valid_targets:proposals.append(Proposal(agent_id=agent_id, sensor_id=sid, target_id=tid))used_sensors.add(sid)if proposals:return proposals, "llm"except Exception as e:print(f"[LLM multi] Error: {e}. Falling back to greedy.")# Greedy fallback — agents claim sensors by typeused_sensors = set()for agent_id in AGENT_TYPES:agent_obs = agent_obs_map[agent_id]for p in _greedy_proposals(agent_id, agent_obs, used_sensors):proposals.append(p)used_sensors.add(p.sensor_id)return proposals, "greedy"# ── Single-agent routes (unchanged) ──────────────────────────────────────────@app.get("/status")def status():return jsonify({"status": "ok","obs_ready": obs is not None,"mx_obs_ready": mx_obs is not None,"llm_enabled": _llm_client is not None,"model": MODEL_NAME if _llm_client else None})43 unmodified linesobs, total_reward, done, info = env.step_batch(actions)return jsonify({"actions": [a.model_dump() for a in actions],"action": actions[0].model_dump() if actions else None,"agent": source,"observation": obs.model_dump(),"reward": total_reward,"done": done,"info": info})42 unmodified lines"steps": info["step_count"], "seed": seed})# ── Multi-agent routes ────────────────────────────────────────────────────────@app.post("/reset_multi")def reset_multi():global mx_obsbody = request.get_json(silent=True) or {}seed = body.get("seed") or _random.randint(1, 99999)max_steps = body.get("max_steps", 10)mx_env.seed = seedmx_env.max_steps = max_stepsmx_obs = mx_env.reset()return jsonify({"seed": seed,"max_steps": max_steps,"observations": {k: v.to_dict() for k, v in mx_obs.items()},"conflict_rate": 0.0,"agent_rewards": {a: 0.0 for a in AGENT_TYPES},})@app.post("/step_multi")def step_multi():global mx_obsif mx_obs is None:return jsonify({"error": "Call /reset_multi first"}), 400body = request.get_json(silent=True) or {}raw_proposals = body.get("proposals", [])proposals = [Proposal(agent_id=p["agent_id"],sensor_id=p["sensor_id"],target_id=p["target_id"])for p in raw_proposalsif p.get("agent_id") and p.get("sensor_id") and p.get("target_id")]mx_obs, step_rewards, done, info = mx_env.step_multiagent(proposals)return jsonify({"observations": {k: v.to_dict() for k, v in mx_obs.items()},"step_rewards": step_rewards,"agent_rewards": info["agent_rewards"],"done": done,"info": info,"conflict_rate": info["conflict_rate"],"conflicts": info["conflicts"],})@app.post("/auto_multi")def auto_multi():global mx_obsif mx_obs is None:return jsonify({"error": "Call /reset_multi first"}), 400proposals, source = _get_multi_proposals(mx_obs)mx_obs, step_rewards, done, info = mx_env.step_multiagent(proposals)return jsonify({"proposals": [{"agent_id": p.agent_id, "sensor_id": p.sensor_id,"target_id": p.target_id} for p in proposals],"agent": source,"observations": {k: v.to_dict() for k, v in mx_obs.items()},"step_rewards": step_rewards,"agent_rewards": info["agent_rewards"],"done": done,"info": info,"conflict_rate": info["conflict_rate"],"conflicts": info["conflicts"],})# ── UI ────────────────────────────────────────────────────────────────────────@app.get("/")@app.get("/ui")def ui():
10 unmodified lines11121314151642 unmodified lines59606162636465666768697071105 unmodified lines17717817918018118218318418518614 unmodified lines20120220320420520620720817 unmodified lines22622722822923023123223323423523623723823924024124224324424524610 unmodified lines--orange: #A0522D;--map-bg: #D6D0A8;--card: #EDE8C8;}html, body {42 unmodified lines@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.6} }@keyframes ping { 0%{transform:scale(1);opacity:0.8} 100%{transform:scale(2.2);opacity:0} }.topbar-task { font-size: 0.7em; opacity: 0.8; letter-spacing: 0.05em; }.topbar-right { text-align: right; }.clock { font-size: 1.3em; font-weight: 700; letter-spacing: 0.1em; color: var(--gold); }/* LAYOUT */.layout {display: grid;grid-template-columns: 240px 1fr 260px;flex: 1;min-height: 0;overflow: hidden;105 unmodified linesfont-size: 0.72em;font-weight: 700;letter-spacing: 0.06em;transition: opacity 0.15s;width: 100%;}.btn:hover { opacity: 0.85; }.btn-assign { background: var(--accent); color: var(--bg); }.btn-auto { background: var(--green); color: var(--bg); }.btn-run { background: var(--gold); color: var(--accent); margin-top: 0; }14 unmodified lines.score-fill { height: 100%; background: linear-gradient(90deg, var(--green), var(--accent)); border-radius: 99px; transition: width 0.5s ease; }.score-pct { font-size: 1em; font-weight: 700; color: var(--accent); text-align: center; margin-top: 4px; }/* THREATS */.threat-list { display: flex; flex-direction: column; gap: 5px; max-height: 180px; overflow-y: auto; }.threat-item {display: flex;align-items: center;17 unmodified lines.threat-badge.m { background: var(--orange); color: #fff; }.threat-badge.l { background: var(--green); color: #fff; }/* LOG */.log-box {height: 160px;overflow-y: auto;font-size: 0.68em;background: var(--bg);border: 1px solid var(--border);border-radius: 3px;padding: 8px;}.log-entry { padding: 2px 0; border-bottom: 1px solid rgba(170,139,86,0.2); display: flex; gap: 6px; }.log-time { color: var(--gold); flex-shrink: 0; }.log-pos { color: var(--green); font-weight: 700; }.log-neg { color: var(--red); font-weight: 700; }.log-neu { color: var(--muted); }/* MAP */.map-area { position: relative; background: var(--map-bg); overflow: hidden; display: flex; flex-direction: column; }10 unmodified lines1112131415161718192021222324252642 unmodified lines69707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128105 unmodified lines23423523623723823924024124224324414 unmodified lines25926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939017 unmodified lines40840941041141241341441541641741810 unmodified lines--orange: #A0522D;--map-bg: #D6D0A8;--card: #EDE8C8;/* ── Multi-agent agent colors ────────────────────────────────────────────── */--agent-satellite: #2563eb;--agent-drone: #16a34a;--agent-radar: #d97706;--agent-command: #9333ea;/* ── Conflict indicators ─────────────────────────────────────────────────── */--conflict-red: #e11d48;--conflict-orange: #f97316;}html, body {42 unmodified lines@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.6} }@keyframes ping { 0%{transform:scale(1);opacity:0.8} 100%{transform:scale(2.2);opacity:0} }.topbar-task { font-size: 0.7em; opacity: 0.8; letter-spacing: 0.05em; }.topbar-right { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; }.clock { font-size: 1.3em; font-weight: 700; letter-spacing: 0.1em; color: var(--gold); }/* ── Mode toggle ─────────────────────────────────────────────────────────── */.mode-toggle {display: flex;gap: 4px;background: rgba(0,0,0,0.2);border-radius: 4px;padding: 3px;}.mode-btn {padding: 4px 12px;border: 1px solid transparent;border-radius: 3px;background: transparent;color: rgba(240,235,206,0.7);font-family: inherit;font-size: 0.65em;font-weight: 700;letter-spacing: 0.1em;cursor: pointer;transition: all 0.2s;}.mode-btn:hover { background: rgba(240,235,206,0.1); color: var(--bg); }.mode-btn.active {background: var(--gold);color: var(--accent);border-color: var(--gold);}/* ── Agent chips (mini legend in multi-agent control panel) ──────────────── */.agent-legend-mini {display: flex;gap: 4px;flex-wrap: wrap;}.agent-chip {font-size: 0.58em;font-weight: 700;letter-spacing: 0.06em;padding: 2px 7px;border-radius: 99px;color: #fff;}.agent-chip.satellite { background: var(--agent-satellite); }.agent-chip.drone { background: var(--agent-drone); }.agent-chip.radar { background: var(--agent-radar); }.agent-chip.command { background: var(--agent-command); }/* LAYOUT */.layout {display: grid;grid-template-columns: 240px 1fr 270px;flex: 1;min-height: 0;overflow: hidden;105 unmodified linesfont-size: 0.72em;font-weight: 700;letter-spacing: 0.06em;transition: opacity 0.15s, transform 0.1s;width: 100%;}.btn:hover { opacity: 0.85; }.btn:active { transform: scale(0.98); }.btn-assign { background: var(--accent); color: var(--bg); }.btn-auto { background: var(--green); color: var(--bg); }.btn-run { background: var(--gold); color: var(--accent); margin-top: 0; }14 unmodified lines.score-fill { height: 100%; background: linear-gradient(90deg, var(--green), var(--accent)); border-radius: 99px; transition: width 0.5s ease; }.score-pct { font-size: 1em; font-weight: 700; color: var(--accent); text-align: center; margin-top: 4px; }/* ── Multi-agent metrics ─────────────────────────────────────────────────── */.conflict-rate-row {display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;padding: 6px 10px;background: var(--bg);border-radius: 3px;border: 1px solid var(--border);}.metric-label { font-size: 0.68em; color: var(--muted); letter-spacing: 0.08em; }.conflict-rate-val {font-size: 1.1em;font-weight: 700;color: var(--green);transition: color 0.3s;}.conflict-rate-val.cr-med { color: var(--orange); }.conflict-rate-val.cr-high { color: var(--red); animation: pulse 1.5s infinite; }/* ── Per-agent reward cards ──────────────────────────────────────────────── */.agent-rewards-grid {display: grid;grid-template-columns: 1fr 1fr;gap: 6px;}.agent-reward-card {border-radius: 4px;padding: 8px 6px;text-align: center;border: 2px solid;background: var(--bg);transition: border-color 0.3s, background 0.3s;}.agent-reward-card.satellite {border-color: var(--agent-satellite);}.agent-reward-card.drone {border-color: var(--agent-drone);}.agent-reward-card.radar {border-color: var(--agent-radar);}.agent-reward-card.command {border-color: var(--agent-command);}.agent-reward-val {font-size: 1.1em;font-weight: 700;color: var(--accent);line-height: 1;}.agent-reward-card.satellite .agent-reward-val { color: var(--agent-satellite); }.agent-reward-card.drone .agent-reward-val { color: var(--agent-drone); }.agent-reward-card.radar .agent-reward-val { color: var(--agent-radar); }.agent-reward-card.command .agent-reward-val { color: var(--agent-command); }.agent-reward-lbl {font-size: 0.58em;color: var(--muted);margin-top: 3px;letter-spacing: 0.08em;text-transform: uppercase;}/* ── Conflict log ────────────────────────────────────────────────────────── */.log-box {height: 130px;overflow-y: auto;font-size: 0.68em;background: var(--bg);border: 1px solid var(--border);border-radius: 3px;padding: 8px;}.log-entry { padding: 2px 0; border-bottom: 1px solid rgba(170,139,86,0.2); display: flex; gap: 6px; }.log-time { color: var(--gold); flex-shrink: 0; }.log-pos { color: var(--green); font-weight: 700; }.log-neg { color: var(--red); font-weight: 700; }.log-neu { color: var(--muted); }.conflict-entry {display: flex;align-items: flex-start;gap: 6px;padding: 3px 0;border-bottom: 1px solid rgba(170,139,86,0.2);font-size: 0.88em;flex-wrap: wrap;}.conflict-entry.conflict-ok { opacity: 0.5; }.conflict-entry.conflict-bad {background: rgba(225,29,72,0.07);border-radius: 2px;padding: 3px 4px;}.conflict-step {color: var(--gold);font-weight: 700;flex-shrink: 0;min-width: 45px;}.conflict-type {color: var(--conflict-red);font-weight: 700;font-size: 0.82em;letter-spacing: 0.04em;}.conflict-agents { color: var(--muted); font-size: 0.82em; }.conflict-none { color: var(--green); font-size: 0.82em; }/* conflict badge in operation log */.conflict-badge {display: inline-block;background: var(--conflict-red);color: #fff;font-size: 0.72em;font-weight: 700;padding: 1px 6px;border-radius: 99px;margin-left: 4px;vertical-align: middle;}/* THREATS */.threat-list { display: flex; flex-direction: column; gap: 5px; max-height: 160px; overflow-y: auto; }.threat-item {display: flex;align-items: center;17 unmodified lines.threat-badge.m { background: var(--orange); color: #fff; }.threat-badge.l { background: var(--green); color: #fff; }/* ── Map legend dots for agents ──────────────────────────────────────────── */.legend-dot.agent-satellite { background: var(--agent-satellite); }.legend-dot.agent-drone { background: var(--agent-drone); }.legend-dot.agent-radar { background: var(--agent-radar); }.legend-dot.agent-command { background: var(--agent-command); }/* MAP */.map-area { position: relative; background: var(--map-bg); overflow: hidden; display: flex; flex-direction: column; }
12345678910111213149 unmodified lines242526272829301 unmodified line32333435363738394017 unmodified lines5859606162636465666 unmodified lines737475767778798081828384858687888910 unmodified lines1001011021031041051064 unmodified lines1111121131141151161175 unmodified lines1231241251261271281291 unmodified line1311321331341351361379 unmodified lines1471481491501511521531541551561571581591604 unmodified lines1651661671681691701711721731741751762 unmodified lines17918018118218318418518618718818919019119219319419519619719820 unmodified lines21922022122222322422527 unmodified lines25325425525625725825916 unmodified lines27627727827928028136 unmodified lines3183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563572 unmodified lines36036136236336436536621 unmodified lines3883893903913923933943953963973983994004014024034044054064074084094104114124134144151 unmodified line41741841942042142218 unmodified lines4414424434444454464475 unmodified lines4534544554564574584592 unmodified lines462463464465// ── State ─────────────────────────────────────────────────────────────────────let totalReward = 0, stepCount = 0, maxSteps = 20, done = false;let currentTask = 'Easy', currentSeed = 42;let sensors = [], envTargets = [], customTargets = [];let episodeLog = [], obsLoaded = false;// Leaflet map + layer referenceslet map = null;const sensorMarkers = {}; // id → L.markerconst targetMarkers = {}; // id → L.markerconst arcLines = []; // L.polyline[]// Snapshot of all target metadata (priority etc.) keyed by id — survives deactivationconst targetMeta = {};9 unmodified linesconst CITY_NAMES = {S1: 'Delhi', S2: 'Mumbai', S3: 'Chennai', S4: 'Kolkata', S5: 'Hyderabad'};const customSensorPos = {}; // id → [lat, lon] when dragged// ── Threat zones for env targets ──────────────────────────────────────────────const THREAT_ZONES = [1 unmodified line[22.0, 69.0], [27.5, 88.5], [30.5, 71.0], [15.0, 74.0]];const allTargetPos = {}; // id → [lat, lon]let nextCustomId = 1;function getTargetPos(id) {if (allTargetPos[id]) return allTargetPos[id];let h = 0;17 unmodified lines}// ── Marker helpers ────────────────────────────────────────────────────────────function sensorIcon(type, available) {const colors = { satellite: '#395144', drone: '#4E6C50', radar: '#AA8B56' };const c = colors[type] || '#395144';const opacity = available ? 1 : 0.4;const letter = type[0].toUpperCase();return L.divIcon({6 unmodified lines});}function threatIcon(priority) {const colors = { 3: '#8B2E2E', 2: '#A0522D', 1: '#4E6C50' };const sizes = { 3: 26, 2: 22, 1: 18 };const c = colors[priority] || '#4E6C50';const s = sizes[priority] || 18;const pulse = priority === 3? `<div style="position:absolute;inset:-6px;border-radius:50%;border:2px solid ${c};opacity:0.5;animation:ping 1.2s infinite"></div>` : '';return L.divIcon({className: '',html: `<div style="position:relative;width:${s}px;height:${s}px">${pulse}<div style="width:0;height:0;border-left:${s/2}px solid transparent;border-right:${s/2}px solid transparent;border-bottom:${s}px solid ${c};filter:drop-shadow(0 2px 4px rgba(0,0,0,0.5))"></div>10 unmodified linesconst pos = getSensorPos(s.id);if (sensorMarkers[s.id]) {sensorMarkers[s.id].setIcon(sensorIcon(s.type, s.available));// Don't move marker if user has dragged it — position already updated} else {const m = L.marker(pos, {icon: sensorIcon(s.type, s.available),4 unmodified linesm.on('dragend', async e => {const ll = e.target.getLatLng();customSensorPos[s.id] = [ll.lat, ll.lng];// Reverse geocode to get place namelet placeName = `${ll.lat.toFixed(1)}°N, ${ll.lng.toFixed(1)}°E`;try {const geo = await fetch(5 unmodified lines} catch (_) {}CITY_NAMES[s.id] = placeName;m.setTooltipContent(`<b>${s.id}</b><br>${s.type}<br>${placeName}`);// Refresh sidebar so dropdown shows new location namerenderSensors(sensors);addLog(`${s.type} sensor moved to ${placeName}`, 'log-neu');});1 unmodified line}});// Update sidebar sensor listdocument.getElementById('sensorList').innerHTML = data.map(s => {const dc = s.type === 'satellite' ? 'sat' : s.type === 'drone' ? 'drone' : 'radar';return `<div class="sensor-item ${s.available ? 'available' : 'busy'}">9 unmodified lines}// ── Render targets on map ─────────────────────────────────────────────────────function renderEnvTargets(data) {// Snapshot metadata before targets get deactivateddata.forEach(t => {targetMeta[t.id] = { priority: t.priority };if (!allTargetPos[t.id]) getTargetPos(t.id);});// Remove markers for targets no longer in observationconst activeIds = new Set(data.map(t => t.id));Object.keys(targetMarkers).forEach(id => {if (!id.startsWith('C') && !activeIds.has(id)) {4 unmodified linesdata.filter(t => t.active).forEach(t => {const pos = getTargetPos(t.id);if (targetMarkers[t.id]) {targetMarkers[t.id].setIcon(threatIcon(t.priority));} else {const lvl = t.priority === 3 ? 'HIGH' : t.priority === 2 ? 'MED' : 'LOW';const m = L.marker(pos, { icon: threatIcon(t.priority), title: t.id }).addTo(map);m.bindTooltip(`<b>${t.id}</b><br>Priority: ${lvl}`, { direction: 'top' });targetMarkers[t.id] = m;}});2 unmodified linesrefreshThreatPanel();}// ── Arc (projectile line) ─────────────────────────────────────────────────────function spawnArc(sensorId, targetId, reward) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);const color = reward > 0 ? '#4E6C50' : '#8B2E2E';const line = L.polyline([sp, tp], {color, weight: 2, dashArray: '6 4', opacity: 0.85}).addTo(map);arcLines.push(line);// Fade out after 3ssetTimeout(() => { map.removeLayer(line); }, 3000);}// ── Map click to place custom threats ────────────────────────────────────────let activeTool = 'move';function setTool(tool) {20 unmodified linesreturn r.json();}// ── Label helpers (for summary) ───────────────────────────────────────────────function sensorLabel(id) {const s = sensors.find(x => x.id === id);const city = CITY_NAMES[id] || id;27 unmodified lines.map(t => `<option value="${t.id}">${t.id} (p${t.priority}${t.id.startsWith('C') ? ', custom' : ''})</option>`).join('');}// ── Log ───────────────────────────────────────────────────────────────────────function addLog(text, cls) {const box = document.getElementById('logBox');const d = document.createElement('div');16 unmodified linesdocument.getElementById('scorePct').textContent = score.toFixed(3);}function setActiveTask(name) {['easy', 'medium', 'hard'].forEach(n => document.getElementById('btn-' + n).classList.remove('active'));document.getElementById('btn-' + name.toLowerCase()).classList.add('active');36 unmodified linesdocument.getElementById('summaryModal').style.display = 'flex';}// ── Actions ───────────────────────────────────────────────────────────────────async function loadTask(steps, seed, name, threatLevel) {totalReward = 0; stepCount = 0; maxSteps = steps; done = false;currentTask = name; currentSeed = seed;episodeLog = [];customTargets = []; nextCustomId = 1;envTargets = [];Object.keys(allTargetPos).forEach(k => delete allTargetPos[k]);Object.keys(targetMeta).forEach(k => delete targetMeta[k]);// Clear map layersObject.values(sensorMarkers).forEach(m => map.removeLayer(m));Object.keys(sensorMarkers).forEach(k => delete sensorMarkers[k]);Object.values(targetMarkers).forEach(m => map.removeLayer(m));Object.keys(targetMarkers).forEach(k => delete targetMarkers[k]);arcLines.forEach(l => map.removeLayer(l));arcLines.length = 0;document.getElementById('logBox').innerHTML = '';['statStep', 'statReward', 'statMissed', 'statAssigned'].forEach(id =>document.getElementById(id).textContent = '0');document.getElementById('scoreBar').style.width = '0%';document.getElementById('scorePct').textContent = '0.000';document.getElementById('gradeVal').textContent = '--';document.getElementById('gradeSub').textContent = 'Run grader to evaluate';setActiveTask(name);document.querySelectorAll('.btn-assign,.btn-auto,.btn-run,.btn-grade').forEach(b => b.disabled = true);const obs = await api('POST', '/reset', { max_steps: steps });currentSeed = obs.seed || seed;document.querySelectorAll('.btn-assign,.btn-auto,.btn-run,.btn-grade').forEach(b => b.disabled = false);renderSensors(obs.sensors);renderEnvTargets(obs.targets);document.getElementById('taskLabel').textContent = name.toUpperCase() + ' — ' + threatLevel;document.getElementById('statusPill').innerHTML = '● ' + threatLevel;2 unmodified linesdocument.getElementById('toolHint').textContent = 'Drag sensors to reposition | Use toolbar to place custom threats';obsLoaded = true;addLog(`Mission started: ${name} task with ${obs.sensors.length} sensors and ${obs.targets.length} initial threats.`, 'log-neu');}async function manualStep() {21 unmodified linesif (r.error) return addLog('ERROR: ' + r.error, 'log-neg');done = r.done;const actions = r.actions || (r.action ? [r.action] : []);if (actions.length === 0) {if (r.done) showSummary(r.info);return;}actions.forEach(a => spawnArc(a.sensor_id, a.target_id, r.reward));renderSensors(r.observation.sensors);renderEnvTargets(r.observation.targets);updateStats(r.reward, r.info);const c = r.reward > 0 ? 'log-pos' : r.reward < 0 ? 'log-neg' : 'log-neu';const agentTag = r.agent === 'llm' ? ' <span style="color:#AA8B56">[LLM]</span>' : ' <span style="opacity:0.5">[greedy]</span>';const desc = actions.map(a =>`The ${sensorLabel(a.sensor_id)} → ${targetLabel(a.target_id)}`).join(' | ');addLog(`[Auto]${agentTag} ${desc}. Reward: ${r.reward > 0 ? '+' : ''}${r.reward}${r.done ? ' — Mission complete.' : ''}`, c);if (r.done) showSummary(r.info);}async function runAll() {if (!obsLoaded) return addLog('Load a mission first', 'log-neg');if (done) {await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING');}while (!done) {await autoStep();await new Promise(r => setTimeout(r, 300));1 unmodified line}}async function runGrade() {document.getElementById('gradeVal').textContent = '...';document.getElementById('gradeSub').textContent = 'Computing...';18 unmodified lineswindow.addEventListener('load', () => {initMap();// Place custom threats on map clickmap.on('click', e => {if (!obsLoaded || activeTool === 'move') return;const lat = e.latlng.lat, lon = e.latlng.lng;5 unmodified linesapi('POST', '/targets/custom', { id, priority, lat, lon });const lvl = priority === 3 ? 'HIGH' : priority === 2 ? 'MED' : 'LOW';const m = L.marker([lat, lon], { icon: threatIcon(priority) }).addTo(map);m.bindTooltip(`<b>${id}</b><br>Priority: ${lvl} (custom)`, { direction: 'top' });targetMarkers[id] = m;2 unmodified lines});setTool('move');});1234567891011121314151617181920212223249 unmodified lines343536373839401 unmodified line42434445464748495051525354555657585917 unmodified lines7778798081828384856 unmodified lines929394959697989910010110210310410510610710810911010 unmodified lines1211221231241251264 unmodified lines1311321331341351365 unmodified lines1421431441451461471 unmodified line1491501511521531549 unmodified lines1641651661671681691701711721731741751761774 unmodified lines1821831841851861871881891901911921931942 unmodified lines19719819920020120220320420520620720820921021121221321421521621721821922022122220 unmodified lines24324424524624724824925025125225325425525625725825926026126226326426526626727 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032132232332416 unmodified lines34134234334434534634734834935035135235335435535635735835936036136236336436536636736836936 unmodified lines4064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015022 unmodified lines50550650750850951021 unmodified lines5325335345355365375385395405415425435445455465475485495505515521 unmodified line55455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262318 unmodified lines6426436446456466475 unmodified lines6536546556566576586592 unmodified lines662663664665666// ── Mode ───────────────────────────────────────────────────────────────────────let currentMode = 'single'; // 'single' | 'multi'// ── State ─────────────────────────────────────────────────────────────────────let totalReward = 0, stepCount = 0, maxSteps = 20, done = false;let currentTask = 'Easy', currentSeed = 42;let sensors = [], envTargets = [], customTargets = [];let episodeLog = [], obsLoaded = false;// Multi-agent statelet mxDone = false;let mxStepCount = 0;let agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };let conflictLog = [];// Leaflet map + layer referenceslet map = null;const sensorMarkers = {}; // id → L.markerconst targetMarkers = {}; // id → L.markerconst arcLines = []; // L.polyline[]const agentArcLines = []; // agent-colored arcs for multi mode// Snapshot of all target metadata (priority etc.) keyed by id — survives deactivationconst targetMeta = {};9 unmodified linesconst CITY_NAMES = {S1: 'Delhi', S2: 'Mumbai', S3: 'Chennai', S4: 'Kolkata', S5: 'Hyderabad'};const customSensorPos = {}; // id → [lat, lon] when dragged// ── Threat zones for env targets ──────────────────────────────────────────────const THREAT_ZONES = [1 unmodified line[22.0, 69.0], [27.5, 88.5], [30.5, 71.0], [15.0, 74.0]];const allTargetPos = {}; // id → [lat, lon]let nextCustomId = 1;// ── Agent color palette ────────────────────────────────────────────────────────const AGENT_COLORS = {satellite: '#2563eb', // bluedrone: '#16a34a', // greenradar: '#d97706', // ambercommand: '#9333ea', // purple};// ── Helpers ───────────────────────────────────────────────────────────────────function getTargetPos(id) {if (allTargetPos[id]) return allTargetPos[id];let h = 0;17 unmodified lines}// ── Marker helpers ────────────────────────────────────────────────────────────function sensorIcon(type, available, agentColor) {const colors = { satellite: '#395144', drone: '#4E6C50', radar: '#AA8B56' };const c = agentColor || colors[type] || '#395144';const opacity = available ? 1 : 0.4;const letter = type[0].toUpperCase();return L.divIcon({6 unmodified lines});}function threatIcon(priority, hasConflict) {const colors = { 3: '#8B2E2E', 2: '#A0522D', 1: '#4E6C50' };const sizes = { 3: 26, 2: 22, 1: 18 };const c = colors[priority] || '#4E6C50';const s = sizes[priority] || 18;const pulse = priority === 3? `<div style="position:absolute;inset:-6px;border-radius:50%;border:2px solid ${c};opacity:0.5;animation:ping 1.2s infinite"></div>` : '';const conflictRing = hasConflict? `<div style="position:absolute;inset:-10px;border-radius:50%;border:2px dashed #e11d48;opacity:0.9;animation:ping 0.8s infinite"></div>` : '';return L.divIcon({className: '',html: `<div style="position:relative;width:${s}px;height:${s}px">${conflictRing}${pulse}<div style="width:0;height:0;border-left:${s/2}px solid transparent;border-right:${s/2}px solid transparent;border-bottom:${s}px solid ${c};filter:drop-shadow(0 2px 4px rgba(0,0,0,0.5))"></div>10 unmodified linesconst pos = getSensorPos(s.id);if (sensorMarkers[s.id]) {sensorMarkers[s.id].setIcon(sensorIcon(s.type, s.available));} else {const m = L.marker(pos, {icon: sensorIcon(s.type, s.available),4 unmodified linesm.on('dragend', async e => {const ll = e.target.getLatLng();customSensorPos[s.id] = [ll.lat, ll.lng];let placeName = `${ll.lat.toFixed(1)}°N, ${ll.lng.toFixed(1)}°E`;try {const geo = await fetch(5 unmodified lines} catch (_) {}CITY_NAMES[s.id] = placeName;m.setTooltipContent(`<b>${s.id}</b><br>${s.type}<br>${placeName}`);renderSensors(sensors);addLog(`${s.type} sensor moved to ${placeName}`, 'log-neu');});1 unmodified line}});document.getElementById('sensorList').innerHTML = data.map(s => {const dc = s.type === 'satellite' ? 'sat' : s.type === 'drone' ? 'drone' : 'radar';return `<div class="sensor-item ${s.available ? 'available' : 'busy'}">9 unmodified lines}// ── Render targets on map ─────────────────────────────────────────────────────function renderEnvTargets(data, conflictTargetIds) {const conflictSet = new Set(conflictTargetIds || []);data.forEach(t => {targetMeta[t.id] = { priority: t.priority };if (!allTargetPos[t.id]) getTargetPos(t.id);});const activeIds = new Set(data.map(t => t.id));Object.keys(targetMarkers).forEach(id => {if (!id.startsWith('C') && !activeIds.has(id)) {4 unmodified linesdata.filter(t => t.active).forEach(t => {const pos = getTargetPos(t.id);const hasConflict = conflictSet.has(t.id);if (targetMarkers[t.id]) {targetMarkers[t.id].setIcon(threatIcon(t.priority, hasConflict));} else {const lvl = t.priority === 3 ? 'HIGH' : t.priority === 2 ? 'MED' : 'LOW';const m = L.marker(pos, { icon: threatIcon(t.priority, hasConflict), title: t.id }).addTo(map);m.bindTooltip(`<b>${t.id}</b><br>Priority: ${lvl}${hasConflict ? '<br><span style="color:#e11d48">⚡ CONFLICT</span>' : ''}`, { direction: 'top' });targetMarkers[t.id] = m;}});2 unmodified linesrefreshThreatPanel();}// ── Arc helpers ───────────────────────────────────────────────────────────────function spawnArc(sensorId, targetId, reward) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);const color = reward > 0 ? '#4E6C50' : '#8B2E2E';const line = L.polyline([sp, tp], { color, weight: 2, dashArray: '6 4', opacity: 0.85 }).addTo(map);arcLines.push(line);setTimeout(() => { map.removeLayer(line); }, 3000);}function spawnAgentArc(sensorId, targetId, agentId) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);const color = AGENT_COLORS[agentId] || '#888';const line = L.polyline([sp, tp], { color, weight: 2.5, dashArray: '8 4', opacity: 0.9 }).addTo(map);agentArcLines.push(line);setTimeout(() => { try { map.removeLayer(line); } catch(_){} }, 4000);}// ── Map click to place custom threats ─────────────────────────────────────────let activeTool = 'move';function setTool(tool) {20 unmodified linesreturn r.json();}// ── Mode toggle ───────────────────────────────────────────────────────────────function setMode(mode) {currentMode = mode;document.getElementById('btnSingle').classList.toggle('active', mode === 'single');document.getElementById('btnMulti').classList.toggle('active', mode === 'multi');document.getElementById('singleControls').style.display = mode === 'single' ? '' : 'none';document.getElementById('multiControls').style.display = mode === 'multi' ? '' : 'none';document.getElementById('multiMetrics').style.display = mode === 'multi' ? '' : 'none';document.getElementById('conflictPanel').style.display = mode === 'multi' ? '' : 'none';document.querySelectorAll('.multi-legend').forEach(el => {el.style.display = mode === 'multi' ? '' : 'none';});addLog(`Switched to ${mode === 'multi' ? 'MULTI-AGENT' : 'SINGLE-AGENT'} mode`, 'log-neu');}// ── Label helpers ─────────────────────────────────────────────────────────────function sensorLabel(id) {const s = sensors.find(x => x.id === id);const city = CITY_NAMES[id] || id;27 unmodified lines.map(t => `<option value="${t.id}">${t.id} (p${t.priority}${t.id.startsWith('C') ? ', custom' : ''})</option>`).join('');}// ── Conflict log ──────────────────────────────────────────────────────────────function addConflictEntry(conflicts, step) {const box = document.getElementById('conflictLog');if (!conflicts || conflicts.length === 0) {const d = document.createElement('div');d.className = 'conflict-entry conflict-ok';d.innerHTML = `<span class="conflict-step">Step ${step}</span><span class="conflict-none">✓ No conflicts</span>`;box.prepend(d);return;}conflicts.forEach(c => {const d = document.createElement('div');d.className = 'conflict-entry conflict-bad';const agents = c.agents && c.agents.length ? c.agents.join(', ') : '—';const target = c.target_id ? ` → ${c.target_id}` : '';const sensor = c.sensor_id ? ` [${c.sensor_id}]` : '';d.innerHTML = `<span class="conflict-step">Step ${step}</span><span class="conflict-type">${c.type}</span><span class="conflict-agents">${agents}${sensor}${target}</span>`;box.prepend(d);});}// ── General log ───────────────────────────────────────────────────────────────function addLog(text, cls) {const box = document.getElementById('logBox');const d = document.createElement('div');16 unmodified linesdocument.getElementById('scorePct').textContent = score.toFixed(3);}function updateMultiStats(stepRewards, agentRewards, conflictRate, conflicts, step) {// Cumulative agent rewardsObject.keys(agentRewards).forEach(a => {agentRewardsCumulative[a] = agentRewards[a];});document.getElementById('rewardSatellite').textContent = agentRewardsCumulative.satellite.toFixed(1);document.getElementById('rewardDrone').textContent = agentRewardsCumulative.drone.toFixed(1);document.getElementById('rewardRadar').textContent = agentRewardsCumulative.radar.toFixed(1);document.getElementById('rewardCommand').textContent = agentRewardsCumulative.command.toFixed(1);// Conflict rate — color codingconst crEl = document.getElementById('conflictRate');crEl.textContent = conflictRate.toFixed(3);crEl.className = 'conflict-rate-val' + (conflictRate > 0.5 ? ' cr-high' : conflictRate > 0.2 ? ' cr-med' : ' cr-ok');// Step counter (share the same step display)mxStepCount = step;document.getElementById('statStep').textContent = step;// Conflict log entryaddConflictEntry(conflicts, step);}function setActiveTask(name) {['easy', 'medium', 'hard'].forEach(n => document.getElementById('btn-' + n).classList.remove('active'));document.getElementById('btn-' + name.toLowerCase()).classList.add('active');36 unmodified linesdocument.getElementById('summaryModal').style.display = 'flex';}function showMultiSummary(info) {const ar = agentRewardsCumulative;const totalCumReward = Object.values(ar).reduce((a, b) => a + b, 0);const conflictRateFinal = info.conflict_rate || 0;const assignmentLines = (info.assignments || []).map((a, i) =>`Step ${i + 1}: [${(a.agent || '?').toUpperCase()}] ${sensorLabel(a.sensor)} → ${targetLabel(a.target)}`).join('\n');const verdict = conflictRateFinal < 0.1 ? 'Excellent coordination — minimal conflicts.': conflictRateFinal < 0.3 ? 'Good coordination — moderate conflicts resolved.': 'High conflict rate — agents need better negotiation.';const agentLines = Object.entries(ar).map(([a, r]) => ` ${a.padEnd(12)}: ${r.toFixed(2)}`).join('\n');const summary = `EPISODE SUMMARY — MULTI-AGENT MODE${'─'.repeat(50)}Mission: ${currentTask.toUpperCase()} | Agents: satellite, drone, radar, commandSteps completed: ${mxStepCount}PER-AGENT CUMULATIVE REWARDS:${agentLines}TOTAL REWARD: ${totalCumReward.toFixed(2)}CONFLICT RATE: ${conflictRateFinal.toFixed(4)} (${(conflictRateFinal * 100).toFixed(1)}% of steps had conflicts)ASSIGNMENTS:${assignmentLines}VERDICT: ${verdict}`;document.getElementById('summaryText').textContent = summary;document.getElementById('summaryModal').style.display = 'flex';}// ── Single-agent actions ───────────────────────────────────────────────────────async function loadTask(steps, seed, name, threatLevel) {totalReward = 0; stepCount = 0; maxSteps = steps; done = false;mxDone = false; mxStepCount = 0;currentTask = name; currentSeed = seed;episodeLog = [];customTargets = []; nextCustomId = 1;envTargets = [];agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };conflictLog = [];Object.keys(allTargetPos).forEach(k => delete allTargetPos[k]);Object.keys(targetMeta).forEach(k => delete targetMeta[k]);Object.values(sensorMarkers).forEach(m => map.removeLayer(m));Object.keys(sensorMarkers).forEach(k => delete sensorMarkers[k]);Object.values(targetMarkers).forEach(m => map.removeLayer(m));Object.keys(targetMarkers).forEach(k => delete targetMarkers[k]);arcLines.forEach(l => map.removeLayer(l)); arcLines.length = 0;agentArcLines.forEach(l => { try { map.removeLayer(l); } catch(_){} }); agentArcLines.length = 0;document.getElementById('logBox').innerHTML = '';document.getElementById('conflictLog').innerHTML = '';['statStep', 'statReward', 'statMissed', 'statAssigned'].forEach(id =>document.getElementById(id).textContent = '0');document.getElementById('scoreBar').style.width = '0%';document.getElementById('scorePct').textContent = '0.000';document.getElementById('gradeVal').textContent = '--';document.getElementById('gradeSub').textContent = 'Run grader to evaluate';['rewardSatellite','rewardDrone','rewardRadar','rewardCommand'].forEach(id =>document.getElementById(id).textContent = '0.0');document.getElementById('conflictRate').textContent = '0.000';setActiveTask(name);document.querySelectorAll('.btn-assign,.btn-auto,.btn-run,.btn-grade').forEach(b => b.disabled = true);let obs;if (currentMode === 'multi') {obs = await api('POST', '/reset_multi', { max_steps: steps });currentSeed = obs.seed || seed;// Use the first agent's observation for rendering sensors/targetsconst firstAgentObs = obs.observations ? obs.observations['satellite'] : null;if (firstAgentObs) {renderSensors(firstAgentObs.sensors);renderEnvTargets(firstAgentObs.targets);}addLog(`[MULTI] Mission started: ${name} — 4 agents active, ${steps} steps`, 'log-neu');} else {obs = await api('POST', '/reset', { max_steps: steps });currentSeed = obs.seed || seed;renderSensors(obs.sensors);renderEnvTargets(obs.targets);addLog(`Mission started: ${name} task with ${obs.sensors.length} sensors and ${obs.targets.length} initial threats.`, 'log-neu');}document.querySelectorAll('.btn-assign,.btn-auto,.btn-run,.btn-grade').forEach(b => b.disabled = false);document.getElementById('taskLabel').textContent = name.toUpperCase() + ' — ' + threatLevel;document.getElementById('statusPill').innerHTML = '● ' + threatLevel;2 unmodified linesdocument.getElementById('toolHint').textContent = 'Drag sensors to reposition | Use toolbar to place custom threats';obsLoaded = true;}async function manualStep() {21 unmodified linesif (r.error) return addLog('ERROR: ' + r.error, 'log-neg');done = r.done;const actions = r.actions || (r.action ? [r.action] : []);if (actions.length === 0) { if (r.done) showSummary(r.info); return; }actions.forEach(a => spawnArc(a.sensor_id, a.target_id, r.reward));renderSensors(r.observation.sensors);renderEnvTargets(r.observation.targets);updateStats(r.reward, r.info);const c = r.reward > 0 ? 'log-pos' : r.reward < 0 ? 'log-neg' : 'log-neu';const agentTag = r.agent === 'llm' ? ' <span style="color:#AA8B56">[LLM]</span>' : ' <span style="opacity:0.5">[greedy]</span>';const desc = actions.map(a => `The ${sensorLabel(a.sensor_id)} → ${targetLabel(a.target_id)}`).join(' | ');addLog(`[Auto]${agentTag} ${desc}. Reward: ${r.reward > 0 ? '+' : ''}${r.reward}${r.done ? ' — Mission complete.' : ''}`, c);if (r.done) showSummary(r.info);}async function runAll() {if (!obsLoaded) return addLog('Load a mission first', 'log-neg');if (done) { await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING'); }while (!done) {await autoStep();await new Promise(r => setTimeout(r, 300));1 unmodified line}}// ── Multi-agent actions ───────────────────────────────────────────────────────async function autoMultiStep() {if (!obsLoaded) return addLog('Load a mission first', 'log-neg');if (mxDone) return addLog('Episode complete — reload mission', 'log-neg');const r = await api('POST', '/auto_multi');if (r.error) return addLog('ERROR: ' + r.error, 'log-neg');mxDone = r.done;// Draw agent-colored arcs for proposalsconst proposals = r.proposals || [];proposals.forEach(p => spawnAgentArc(p.sensor_id, p.target_id, p.agent_id));// Use first agent's observation for displayconst agentObs = r.observations;const firstObs = agentObs ? agentObs['satellite'] : null;// Collect conflict target IDs for overlayconst conflictTargetIds = (r.conflicts || []).filter(c => c.target_id).map(c => c.target_id);if (firstObs) {renderSensors(firstObs.sensors);renderEnvTargets(firstObs.targets, conflictTargetIds);}// Update step / statsif (r.info) {updateMultiStats(r.step_rewards || {}, r.agent_rewards || {}, r.conflict_rate || 0, r.conflicts || [], r.info.step_count);const totalStepRwd = Object.values(r.step_rewards || {}).reduce((a,b)=>a+b,0);totalReward += totalStepRwd;document.getElementById('statReward').textContent = totalReward.toFixed(1);document.getElementById('statMissed').textContent = (r.info.missed_targets || []).length;document.getElementById('statAssigned').textContent = (r.info.assignments || []).length;}const source = r.agent === 'llm'? '<span style="color:#AA8B56">[LLM]</span>': '<span style="opacity:0.5">[greedy]</span>';const propDesc = proposals.map(p => {const agColor = AGENT_COLORS[p.agent_id] || '#888';return `<span style="color:${agColor}">[${p.agent_id}]</span> ${p.sensor_id}→${p.target_id}`;}).join(' ');const conflictStr = r.conflicts && r.conflicts.length? ` <span class="conflict-badge">⚡ ${r.conflicts.length} conflict(s)</span>`: '';addLog(`[Multi] ${source} ${propDesc || 'no proposals'}${conflictStr}${r.done ? ' — Episode done.' : ''}`, 'log-neu');if (r.done) showMultiSummary(r.info);}async function runAllMulti() {if (!obsLoaded) return addLog('Load a mission first', 'log-neg');if (mxDone) { await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING'); }while (!mxDone) {await autoMultiStep();await new Promise(r => setTimeout(r, 350));if (mxDone) break;}}// ── Grader ────────────────────────────────────────────────────────────────────async function runGrade() {document.getElementById('gradeVal').textContent = '...';document.getElementById('gradeSub').textContent = 'Computing...';18 unmodified lineswindow.addEventListener('load', () => {initMap();map.on('click', e => {if (!obsLoaded || activeTool === 'move') return;const lat = e.latlng.lat, lon = e.latlng.lng;5 unmodified linesapi('POST', '/targets/custom', { id, priority, lat, lon });const lvl = priority === 3 ? 'HIGH' : priority === 2 ? 'MED' : 'LOW';const m = L.marker([lat, lon], { icon: threatIcon(priority, false) }).addTo(map);m.bindTooltip(`<b>${id}</b><br>Priority: ${lvl} (custom)`, { direction: 'top' });targetMarkers[id] = m;2 unmodified lines});setTool('move');setMode('single');});
1 unmodified line23456784 unmodified lines13141516171819201 unmodified line22232425262741 unmodified lines697071727374754 unmodified lines80818283848523 unmodified lines10911011111211311432 unmodified lines1471481491501511521 unmodified line15415515615715815916 unmodified lines1761771781791 unmodified line<html lang="en"><head><meta charset="UTF-8"><title>SentinelEnv — Defense Surveillance Dashboard</title><link rel="stylesheet" href="/static/css/dashboard.css"><link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/></head>4 unmodified lines<div class="topbar-left"><span class="logo">☀</span><div><div class="topbar-title">ARYA<span>SENTINEL</span></div><div class="topbar-sub">Defense Surveillance & Sensor Allocation System</div></div></div><div class="topbar-center">1 unmodified line<div class="topbar-task" id="taskLabel">No task loaded</div></div><div class="topbar-right"><div class="clock" id="clock">--:--:--</div><div class="topbar-sub">IST</div></div>41 unmodified lines</div></div><div class="panel-section"><div class="section-title">MANUAL OVERRIDE</div><select id="sensorSel" class="sel"><option>-- select sensor --</option></select><select id="targetSel" class="sel"><option>-- select target --</option></select>4 unmodified lines<button class="btn btn-run" onclick="runAll()">RUN FULL EPISODE</button></div><div class="panel-section"><div class="section-title">EPISODE GRADE</div><button class="btn btn-grade" onclick="runGrade()">▶ COMPUTE SCORE</button>23 unmodified lines<div class="legend-item"><span class="legend-dot threat-h"></span>HIGH Threat</div><div class="legend-item"><span class="legend-dot threat-m"></span>MED Threat</div><div class="legend-item"><span class="legend-dot threat-l"></span>LOW Threat</div></div><div class="map-overlay" id="mapOverlay"><div class="overlay-icon">☀</div>32 unmodified lines<div class="score-pct" id="scorePct">0.000</div></div><div class="panel-section"><div class="section-title">ACTIVE THREATS</div><div id="threatList" class="threat-list">1 unmodified line</div></div><div class="panel-section"><div class="section-title">OPERATION LOG</div><div class="log-box" id="logBox"></div>16 unmodified lines<pre id="summaryText" style="color:#c8d4b8;font-family:'Courier New',monospace;font-size:0.82em;white-space:pre-wrap;line-height:1.6;margin:0;"></pre></div></div></html>1 unmodified line23456789104 unmodified lines15161718192021221 unmodified line242526272829303132333441 unmodified lines76777879808182834 unmodified lines88899091929394959697989910010110210310410510610710823 unmodified lines13213313413513613713813914014114232 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified line20921021121221321421521621721821922016 unmodified lines2372382392402411 unmodified line<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content="Arya-X: Multi-Agent ISR Sensor Allocation — real-time surveillance dashboard with LLM-powered agents, conflict detection, and negotiation layer."><title>Arya-X — Multi-Agent ISR Sensor Allocation System</title><link rel="stylesheet" href="/static/css/dashboard.css"><link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/></head>4 unmodified lines<div class="topbar-left"><span class="logo">☀</span><div><div class="topbar-title">ARYA<span>-X</span></div><div class="topbar-sub">Multi-Agent ISR Sensor Allocation System</div></div></div><div class="topbar-center">1 unmodified line<div class="topbar-task" id="taskLabel">No task loaded</div></div><div class="topbar-right"><!-- Mode toggle --><div class="mode-toggle"><button class="mode-btn active" id="btnSingle" onclick="setMode('single')">SINGLE</button><button class="mode-btn" id="btnMulti" onclick="setMode('multi')">MULTI-AGENT</button></div><div class="clock" id="clock">--:--:--</div><div class="topbar-sub">IST</div></div>41 unmodified lines</div></div><!-- Single-agent controls --><div class="panel-section" id="singleControls"><div class="section-title">MANUAL OVERRIDE</div><select id="sensorSel" class="sel"><option>-- select sensor --</option></select><select id="targetSel" class="sel"><option>-- select target --</option></select>4 unmodified lines<button class="btn btn-run" onclick="runAll()">RUN FULL EPISODE</button></div><!-- Multi-agent controls --><div class="panel-section" id="multiControls" style="display:none"><div class="section-title">MULTI-AGENT CONTROL</div><div class="agent-legend-mini"><span class="agent-chip satellite">SAT</span><span class="agent-chip drone">DRONE</span><span class="agent-chip radar">RADAR</span><span class="agent-chip command">CMD</span></div><div class="btn-row" style="margin-top:8px"><button class="btn btn-auto" onclick="autoMultiStep()">▶ AUTO MULTI</button></div><button class="btn btn-run" onclick="runAllMulti()">RUN FULL EPISODE</button></div><div class="panel-section"><div class="section-title">EPISODE GRADE</div><button class="btn btn-grade" onclick="runGrade()">▶ COMPUTE SCORE</button>23 unmodified lines<div class="legend-item"><span class="legend-dot threat-h"></span>HIGH Threat</div><div class="legend-item"><span class="legend-dot threat-m"></span>MED Threat</div><div class="legend-item"><span class="legend-dot threat-l"></span>LOW Threat</div><!-- Multi-agent legend (shown in multi mode) --><div class="legend-item multi-legend" style="display:none"><span class="legend-dot agent-satellite"></span>Satellite Agent</div><div class="legend-item multi-legend" style="display:none"><span class="legend-dot agent-drone"></span>Drone Agent</div><div class="legend-item multi-legend" style="display:none"><span class="legend-dot agent-radar"></span>Radar Agent</div><div class="legend-item multi-legend" style="display:none"><span class="legend-dot agent-command"></span>Command Agent</div></div><div class="map-overlay" id="mapOverlay"><div class="overlay-icon">☀</div>32 unmodified lines<div class="score-pct" id="scorePct">0.000</div></div><!-- Multi-agent metrics panel (shown in multi mode) --><div class="panel-section" id="multiMetrics" style="display:none"><div class="section-title">MULTI-AGENT METRICS</div><div class="conflict-rate-row"><span class="metric-label">Conflict Rate</span><span class="conflict-rate-val" id="conflictRate">0.000</span></div><div class="agent-rewards-grid" id="agentRewardsGrid"><div class="agent-reward-card satellite"><div class="agent-reward-val" id="rewardSatellite">0.0</div><div class="agent-reward-lbl">Satellite</div></div><div class="agent-reward-card drone"><div class="agent-reward-val" id="rewardDrone">0.0</div><div class="agent-reward-lbl">Drone</div></div><div class="agent-reward-card radar"><div class="agent-reward-val" id="rewardRadar">0.0</div><div class="agent-reward-lbl">Radar</div></div><div class="agent-reward-card command"><div class="agent-reward-val" id="rewardCommand">0.0</div><div class="agent-reward-lbl">Command</div></div></div></div><div class="panel-section"><div class="section-title">ACTIVE THREATS</div><div id="threatList" class="threat-list">1 unmodified line</div></div><!-- Conflict log (shown in multi mode) --><div class="panel-section" id="conflictPanel" style="display:none"><div class="section-title">CONFLICT LOG <span id="conflictCount" style="float:right;color:var(--red);font-size:0.9em"></span></div><div class="log-box" id="conflictLog" style="height:120px"></div></div><div class="panel-section"><div class="section-title">OPERATION LOG</div><div class="log-box" id="logBox"></div>16 unmodified lines<pre id="summaryText" style="color:#c8d4b8;font-family:'Courier New',monospace;font-size:0.82em;white-space:pre-wrap;line-height:1.6;margin:0;"></pre></div></div></body></html>
README.md+301-122
env/multiagent.pyAdded+286
openenv.yaml+84-9
server.py+192-16
static/css/dashboard.css+191-19
static/js/dashboard.js+250-49
templates/dashboard.html+66-4