-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
701 lines (652 loc) · 40.3 KB
/
Copy pathdashboard.py
File metadata and controls
701 lines (652 loc) · 40.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
"""SpaceTraders fleet dashboard — a console rail view (ADR 0026).
A plugin-contributed console surface: a left-rail "Fleet" icon opens this live
view of the agent's galaxy — credits, ships, contracts, and the background
autopilot — so the operator can WATCH the autonomous fleet instead of polling over
A2A. The console embeds `GET /plugins/spacetraders/dashboard` in an iframe; the page
polls the bearer-gated `GET /api/plugins/spacetraders/state` (server-side, uses the
agent token) and renders. The snapshot is cached briefly so dashboard polling doesn't eat the
per-account rate budget the fleet engine shares.
v2.6 (demo polish): the sparse 3-stat header is one dense strip (+ ships + net
worth), the Universe card's dead space became the JUMP-GATE construction card
(per-material progress bars + the v2.5 funding rung's armed state), and two new
panels surface the autonomy stories — the st-* tripwire suite (via
``graph.sdk.list_watches``) and the DecisionLog tail with relative timestamps.
Every host-side read degrades to empty host-free (panel hidden), and FastAPI is
imported inside the router builders so this module — and its data-endpoint tests —
load without the host or fastapi installed.
"""
from __future__ import annotations
import asyncio
import time as _time
from . import client as C
from . import roles as R
from . import watches as _watches
_CACHE: dict = {"at": -999.0, "data": None}
_TTL = 8.0 # seconds — cap how often the dashboard hits the live API
# Prometheus gauges so /metrics can alert on a stalled or money-losing fleet
# (T3.1). Best-effort: no-op if prometheus_client isn't installed. Same AGENT_NAME
# prefix as the substrate metrics so they group on /metrics.
try:
import os
import re as _re
from prometheus_client import Gauge
_p = _re.sub(r"[^a-z0-9]+", "_", os.environ.get("AGENT_NAME", "protoagent").lower()).strip("_") or "protoagent"
_G_CREDITS = Gauge(f"{_p}_spacetraders_credits", "SpaceTraders agent credits (live)")
_G_CRHR = Gauge(f"{_p}_spacetraders_credits_per_hour", "SpaceTraders last autopilot run cr/hr")
_G_SHIPS = Gauge(f"{_p}_spacetraders_ships", "SpaceTraders fleet size")
except Exception: # noqa: BLE001
_G_CREDITS = _G_CRHR = _G_SHIPS = None
def _emit_metrics(agent: dict, last: dict) -> None:
if _G_CREDITS is None:
return
try:
_G_CREDITS.set(agent.get("credits", 0))
_G_SHIPS.set(agent.get("ships", 0) or 0)
if last.get("per_hour") is not None:
_G_CRHR.set(last["per_hour"])
except Exception: # noqa: BLE001 — metrics must never break the dashboard
pass
def _ship_row(s: dict) -> dict:
nav = s.get("nav", {})
fuel = s.get("fuel", {})
cargo = s.get("cargo", {})
in_transit = nav.get("status") == "IN_TRANSIT"
route = nav.get("route", {})
return {
"symbol": s["symbol"],
"role": ("scout" if cargo.get("capacity", 0) == 0
else "miner" if R.can_mine(s) else "cargo"),
"status": nav.get("status", "?"),
"waypoint": nav.get("waypointSymbol", "?"),
"fuel": ("∞" if fuel.get("capacity", 0) == 0
else f"{fuel.get('current', '?')}/{fuel.get('capacity', '?')}"),
"cargo": f"{cargo.get('units', 0)}/{cargo.get('capacity', 0)}",
# Where it's headed (in-transit only) — dest, ISO arrival (JS ticks the ETA), mode,
# plus origin + departure so the map can interpolate its position along the route.
"dest": (route.get("destination") or {}).get("symbol") if in_transit else None,
"origin": (route.get("origin") or {}).get("symbol") if in_transit else None,
"departure": route.get("departureTime") if in_transit else None,
"arrival": route.get("arrival") if in_transit else None,
"mode": nav.get("flightMode") if in_transit else None,
}
_STATUS_CACHE: dict = {"at": -999.0, "data": None}
_STATUS_TTL = 120.0 # server status (leaderboard + reset + stats) barely moves
async def _server_status() -> dict:
"""The galaxy status root (GET /) — leaderboards, serverResets, stats. Cached."""
now = asyncio.get_event_loop().time()
if _STATUS_CACHE["data"] is None or now - _STATUS_CACHE["at"] >= _STATUS_TTL:
try:
_STATUS_CACHE["data"] = await C.call("GET", "/")
except C.SpaceTradersError:
_STATUS_CACHE["data"] = _STATUS_CACHE["data"] or {}
_STATUS_CACHE["at"] = now
return _STATUS_CACHE["data"] or {}
def _standing(status: dict, agent_symbol: str, my_credits: int) -> dict:
"""Top-credits leaderboard + where we stack up."""
mc = status.get("leaderboards", {}).get("mostCredits", []) or []
rank = next((i + 1 for i, x in enumerate(mc) if x.get("agentSymbol") == agent_symbol), None)
return {
"top": [{"agent": x.get("agentSymbol"), "credits": x.get("credits")} for x in mc[:5]],
"rank": rank,
"board_size": len(mc),
"cutoff": mc[-1].get("credits") if mc else None, # credits to make the board (#last)
"you": my_credits,
}
def _server_info(status: dict) -> dict:
"""Reset cycle + galaxy scale — so the operator knows the clock + the field size."""
sr = status.get("serverResets", {})
stats = status.get("stats", {})
return {
"next_reset": sr.get("next"), # ISO — JS ticks the countdown
"frequency": sr.get("frequency"), # e.g. "weekly"
"last_reset": status.get("resetDate"),
"agents": stats.get("agents"),
"ships": stats.get("ships"),
"systems": stats.get("systems"),
}
_MAP_CACHE: dict = {} # system -> waypoints (x,y,type,market); static within a reset
async def _system_map(system: str) -> dict:
"""The system's waypoints (position + type) for the star map, plus which markets
we've scouted (the price-map coverage). Waypoint geometry is static within a reset."""
if system in _MAP_CACHE:
wps = _MAP_CACHE[system]
else:
raw: list = []
try:
page = 1
while page <= 12: # paginate the FULL system — far outposts (asteroid bases,
batch = await C.call("GET", f"/systems/{system}/waypoints", # jump gates) live
params={"limit": 20, "page": page}) # on later pages
if not batch:
break
raw.extend(batch)
if len(batch) < 20:
break
page += 1
except C.SpaceTradersError:
if not raw:
return {"system": system, "waypoints": []}
wps = [{"symbol": w["symbol"], "type": w.get("type", "?"),
"x": w.get("x", 0), "y": w.get("y", 0),
"market": any(t.get("symbol") == "MARKETPLACE" for t in w.get("traits", []))}
for w in raw]
_MAP_CACHE[system] = wps
from . import prices
pm = {m["waypointSymbol"]: m["tradeGoods"] for m in prices.price_map(system)}
out = []
for w in wps:
goods = [{"symbol": g["symbol"], "buy": g["purchasePrice"], "sell": g["sellPrice"]}
for g in pm.get(w["symbol"], [])][:8]
out.append({**w, "scouted": w["symbol"] in pm, "goods": goods})
return {"system": system, "waypoints": out}
def _contract_row(c: dict) -> dict:
terms = c.get("terms", {})
dv = (terms.get("deliver") or [{}])[0]
pay = terms.get("payment", {})
state = "fulfilled" if c.get("fulfilled") else ("accepted" if c.get("accepted") else "open")
return {
"id": c.get("id", "")[-6:],
"type": c.get("type", "?"),
"deliver": f"{dv.get('unitsFulfilled', 0)}/{dv.get('unitsRequired', 0)} {dv.get('tradeSymbol', '?')}",
"to": dv.get("destinationSymbol", "?"),
"pay": pay.get("onFulfilled", 0),
"state": state,
}
_GATE_CACHE: dict = {"at": -999.0, "data": None}
_GATE_TTL = 90.0 # construction progress moves at delivery cadence, not poll cadence
async def _gate_status(system: str, waypoints: list[dict]) -> dict:
"""The system's jump-gate construction progress — the community goal the v2.5
funding rung feeds. ``waypoints`` is the (cached) system-map list, so finding the
gate costs nothing; the construction site read is cached like the other panels.
Complete gate → its connections instead (the payoff view). Degrades to
``waypoint: None`` when the system has no gate or the site read fails."""
gate_wp = next((w.get("symbol") for w in waypoints if w.get("type") == "JUMP_GATE"), None)
if not gate_wp:
return {"waypoint": None, "complete": None, "materials": [], "connections": []}
now = asyncio.get_event_loop().time()
if _GATE_CACHE["data"] is not None and now - _GATE_CACHE["at"] < _GATE_TTL:
return _GATE_CACHE["data"]
materials: list[dict] = []
complete = None
connections: list = []
try:
site = await C.call("GET", f"/systems/{system}/waypoints/{gate_wp}/construction")
complete = bool(site.get("isComplete"))
for m in site.get("materials", []):
req = int(m.get("required") or 0)
got = int(m.get("fulfilled") or 0)
if req > 0: # ALL materials render (finished bars show the win), zero-req rows don't
materials.append({"good": m.get("tradeSymbol", "?"), "required": req,
"fulfilled": got, "pct": min(100, round(100 * got / req))})
except C.SpaceTradersError:
pass # site unreadable → render the sighting alone; next poll retries
if complete:
try:
gate = await C.call("GET", f"/systems/{system}/waypoints/{gate_wp}/jump-gate")
connections = list(gate.get("connections") or [])[:8]
except C.SpaceTradersError:
pass
data = {"waypoint": gate_wp, "complete": complete, "materials": materials,
"connections": connections}
_GATE_CACHE.update(at=now, data=data)
return data
def _gate_rung(credits: int, decisions: list[dict]) -> dict:
"""The gate-supply rung's one-line status: armed (treasury cleared the
``gate_buffer`` knob — the engine spends the surplus on materials) + the last
delivery from the decision log. Host-free (no knobs → no graph.sdk): buffer is
None and the page renders the rung line without the arm state."""
try:
from .knobs import KNOBS
buffer = int(KNOBS.get("gate_buffer"))
except Exception: # noqa: BLE001 — host-free / knob layer unavailable
buffer = None
last = next((d for d in reversed(decisions or [])
if d.get("action") == "gate-supply"), None)
return {"gate_buffer": buffer,
"armed": bool(buffer is not None and credits >= buffer),
"last_delivery": (last or {}).get("detail"),
"last_delivery_ts": (last or {}).get("ts")}
def _watch_rows() -> list[dict]:
"""The st-* tripwire suite for the panel — ``graph.sdk.list_watches`` (the #1638
read half), enriched best-effort with each watch's ``last_reason`` from the live
controller (the SDK row carries id/status/condition only). Host-free: ``[]`` —
the page hides the panel entirely."""
try:
from graph.sdk import list_watches
rows = list_watches("st-")
except Exception: # noqa: BLE001 — no host: no watch system to read
return []
reasons: dict = {}
try:
from runtime.state import STATE
ctl = STATE.watch_controller
if ctl is not None:
reasons = {w.id: (w.last_reason or "") for w in ctl.list_watches()}
except Exception: # noqa: BLE001 — enrichment only; the panel works without reasons
pass
return [{"id": r["id"], "status": r.get("status", "?"),
"reason": reasons.get(r["id"], "")[:90]}
for r in sorted(rows, key=lambda r: r["id"])]
async def _snapshot() -> dict:
now = asyncio.get_event_loop().time()
if _CACHE["data"] is not None and now - _CACHE["at"] < _TTL:
return _CACHE["data"]
try:
agent = await C.call("GET", "/my/agent")
ships = await C.call("GET", "/my/ships")
contracts = await C.call("GET", "/my/contracts")
except C.SpaceTradersError as e:
data = {"error": str(e), "token": bool(C.load_token())}
_CACHE.update(at=now, data=data)
return data
from . import fleet
ops = fleet.ops_status()
last = ops.get("result") or {}
strat = fleet.current_strategy()
status = await _server_status()
system = "-".join(agent["headquarters"].split("-")[:2])
from . import routes as _routes
learned = await _routes.recall_routes(system)
map_data = await _system_map(system)
decisions = fleet.decisions()
data = {
"agent": {"symbol": agent["symbol"], "credits": agent["credits"],
"hq": agent["headquarters"], "faction": agent.get("startingFaction"),
"ships": agent.get("shipCount"),
# Header stat: credits + conservative fleet book value — the ships
# list is already in hand, so watches.net_worth is free here.
"net_worth": _watches.net_worth(agent["credits"], ships)},
"ships": [_ship_row(s) for s in ships],
"standing": _standing(status, agent["symbol"], agent["credits"]),
"server": _server_info(status),
"routes": learned[:6], # trade routes the agent has learned (route memory)
"map": map_data,
# The jump-gate community build + the v2.5 funding rung's status — what the
# Universe card's dead space becomes.
"gate": {**(await _gate_status(system, map_data.get("waypoints") or [])),
"rung": _gate_rung(agent["credits"], decisions)},
# The st-* tripwire suite (empty host-free → panel hidden).
"watches": _watch_rows(),
"contracts": [_contract_row(c) for c in contracts if not c.get("fulfilled")][:4],
"autopilot": {
"running": ops.get("running", False),
"want_running": ops.get("want_running", False),
"watchdog": ops.get("watchdog", False), # the reliability heartbeat alive?
"window": ops.get("started_minutes", 0),
"log": ops.get("recent_log", []),
"watchdog_log": ops.get("watchdog_log", []), # recoveries the watchdog made
"last_per_hour": last.get("per_hour"),
"last_gained": last.get("gained"),
"strategy": strat.get("name"),
"mining": strat.get("mining"),
},
# The audit trail — control-surface moves, watch trips, sell-guard saves, gate
# deliveries: what the agent decided while the operator was away. Entries carry
# a wall-clock ``ts`` (knobs.DLOG stamps it) so the page renders relative times
# against ``now`` below (server clock on both sides — no browser skew).
"decisions": decisions[-8:],
"now": _time.time(),
}
_emit_metrics(data["agent"], last)
_CACHE.update(at=now, data=data)
return data
def build_dashboard_router():
"""The PAGE router — stays on the PUBLIC ``/plugins/spacetraders`` prefix: a
browser iframe page-load can't carry an Authorization bearer, so a gated page
would 401-blank under the token gate (plugin-view rule 2). Everything the page
FETCHES is gated (build_data_router). FastAPI is imported here, not at module
level, so the module (and its data tests) load host-free without fastapi."""
from fastapi import APIRouter
from fastapi.responses import HTMLResponse
router = APIRouter()
@router.get("/dashboard")
async def _dashboard():
return HTMLResponse(_PAGE)
return router
def build_data_router():
"""The DATA route — mounted under ``/api/plugins/spacetraders`` so it inherits
the operator bearer gate (rule 2, issue #5). Previously ``/state`` lived under
the public ``/plugins/`` prefix: on a token-gated deployment anyone who could
reach the port could read fleet state (credits, ships, contracts) without the
bearer."""
from fastapi import APIRouter
from fastapi.responses import JSONResponse
router = APIRouter()
@router.get("/state")
async def _state():
return JSONResponse(await _snapshot())
return router
_PAGE = r"""<!doctype html><html><head><meta charset="utf-8"><title>Fleet</title>
<script>
// Slug-aware kit href (protoAgent ADR 0042, plugin-view rule 3): through the fleet
// proxy the page lives at /agents/<slug>/plugins/... — a hardcoded /_ds/ resolves
// against the hub root. Inject the <link> so the href carries the base. (The data
// fetches below are RELATIVE, so they're already slug-safe.)
window.__base = location.pathname.split("/plugins/")[0];
document.write('<link rel="stylesheet" href="' + window.__base + '/_ds/plugin-kit.css">');
</script>
<style>
html,body{margin:0;height:100%;background:var(--pl-color-bg);color:var(--pl-color-fg);
font-family:var(--pl-font-sans,ui-sans-serif,system-ui,-apple-system,sans-serif);font-size:14px}
.wrap{max-width:920px;margin:0 auto;padding:20px}
h1{font-size:16px;margin:0;color:var(--pl-color-accent);letter-spacing:.3px}
.sub{color:var(--pl-color-fg-muted);font-size:12px;margin-top:2px}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:var(--pl-space-4,14px);margin-top:16px}
.pl-card{margin:0}
#body>.pl-card,#body>.grid{margin-top:var(--pl-space-4,14px)}
#body>.hdr{margin-top:14px}
.pl-card>.pl-panel-header{margin:calc(-1*var(--pl-space-4)) calc(-1*var(--pl-space-4)) var(--pl-space-3);flex-wrap:wrap}
/* Dense header strip — one compact row (≤64px): treasury · autopilot · strategy ·
ships · net worth. Replaces the 3 sparse full-width stat tiles. */
.hdr{display:flex;border:1px solid var(--pl-color-border);border-radius:var(--pl-radius,8px);
background:var(--pl-color-bg-raised);overflow:hidden;max-height:64px}
.hcell{flex:1;min-width:0;padding:8px 12px;border-left:1px solid var(--pl-color-border)}
.hcell:first-child{border-left:none}
.hval{font-size:16px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.hval small{font-size:11px;color:var(--pl-color-fg-muted);font-weight:400}
.hlab{font-size:10px;color:var(--pl-color-fg-muted);margin-top:1px;letter-spacing:.4px;
text-transform:uppercase;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
/* Gate construction: per-material progress bars */
.mat{display:flex;align-items:center;gap:8px;margin-top:6px;font-size:12px}
.mat .mlab{width:118px;color:var(--pl-color-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mat .bar{flex:1;height:6px;border-radius:3px;background:var(--pl-color-border);overflow:hidden}
.mat .fill{height:100%;background:var(--pl-color-accent);border-radius:3px}
.mat .mnum{min-width:88px;text-align:right;font-family:var(--pl-font-mono,ui-monospace,monospace);font-size:11px}
/* Tripwire status dots */
.st-dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--pl-color-fg-muted);
margin-right:6px;vertical-align:baseline}
.st-dot--active{background:var(--pl-color-status-success,#46c46a)}
.st-dot--met{background:var(--pl-color-accent)}
.st-dot--err{background:var(--pl-color-status-warning,#e0a23c)}
.when{color:var(--pl-color-fg-muted);font-size:11px;white-space:nowrap;text-align:right}
.tight td,.tight th{padding:3px 8px;font-size:12.5px}
.big{font-size:30px;font-weight:650;color:var(--pl-color-fg)}
.big small{font-size:13px;color:var(--pl-color-fg-muted);font-weight:400}
table{width:100%;border-collapse:collapse;font-size:13px}
.log{font-family:var(--pl-font-mono,ui-monospace,monospace);font-size:11.5px;color:var(--pl-color-fg-muted);
max-height:120px;overflow:auto;white-space:pre-wrap;line-height:1.5}
</style></head><body><div class="wrap">
<div style="display:flex;justify-content:space-between;align-items:baseline">
<div><h1>🛰 protoTrader-in-space — Fleet</h1>
<div class="sub" id="who">connecting…</div></div>
<div class="sub" id="tick"></div>
</div>
<div id="body"></div>
</div>
<script type="module">
// The DS plugin-kit owns the protoagent:init handshake (bearer + theme, incl. live
// re-themes onto the --pl-* tokens) and slug-aware authed fetches — replacing the
// hand-rolled TMAP/listener this page carried. plugin-kit.js is an ES MODULE, so it
// loads via dynamic import (a classic <script src> throws on its exports; see
// protoAgent docs/how-to/build-a-plugin-view.md). Older host without /_ds: fall
// back to a tokenless same-origin shim (fine locally; gated instances serve the kit).
let kit;
try { kit = await import(window.__base + "/_ds/plugin-kit.js"); }
catch (e) { kit = { initPluginView(){}, apiFetch: (p, i) => fetch(window.__base + p, i) }; }
let MAPCARDS = {};
let LAST_D = null; // last polled state — the 1s ticker re-renders the map so in-transit ships glide
// System-map pan/zoom — the full system spans far outposts, so let the operator explore.
let MAP_VIEW = {s:1, tx:0, ty:0};
function applyMapView(){
const g = document.getElementById("mapworld");
if(g) g.setAttribute("transform", `translate(${MAP_VIEW.tx},${MAP_VIEW.ty}) scale(${MAP_VIEW.s})`);
}
document.addEventListener("wheel", e=>{
const svg = e.target.closest && e.target.closest("#mapsvg"); if(!svg) return;
e.preventDefault();
const r = svg.getBoundingClientRect();
const cx = (e.clientX-r.left)/r.width*860, cy = (e.clientY-r.top)/r.height*300; // viewBox space (860x300)
const ns = Math.max(0.5, Math.min(40, MAP_VIEW.s * (e.deltaY<0 ? 1.15 : 1/1.15)));
const k = ns/MAP_VIEW.s;
MAP_VIEW.tx = cx-(cx-MAP_VIEW.tx)*k; MAP_VIEW.ty = cy-(cy-MAP_VIEW.ty)*k; MAP_VIEW.s = ns;
applyMapView();
}, {passive:false});
let _mapDrag = null;
document.addEventListener("mousedown", e=>{
const svg = e.target.closest && e.target.closest("#mapsvg");
if(svg) _mapDrag = {x:e.clientX, y:e.clientY, tx:MAP_VIEW.tx, ty:MAP_VIEW.ty, w:svg.getBoundingClientRect().width};
});
document.addEventListener("mousemove", e=>{
if(!_mapDrag) return;
const f = 860/_mapDrag.w; // px → viewBox units
MAP_VIEW.tx = _mapDrag.tx+(e.clientX-_mapDrag.x)*f; MAP_VIEW.ty = _mapDrag.ty+(e.clientY-_mapDrag.y)*f;
applyMapView();
});
document.addEventListener("mouseup", ()=>{ _mapDrag = null; });
// Hover detail card for the system map — populated per-element by renderMap.
const _mc = document.createElement("div"); _mc.id = "mapcard";
_mc.style.cssText = "position:fixed;display:none;z-index:60;background:var(--pl-color-bg-raised);border:var(--pl-border-width,1px) solid var(--pl-color-border);"
+ "border-radius:var(--pl-radius,8px);padding:8px 11px;font-size:12px;line-height:1.5;pointer-events:none;max-width:260px;"
+ "box-shadow:0 6px 22px rgba(0,0,0,.5)";
document.addEventListener("DOMContentLoaded", ()=>document.body.appendChild(_mc));
document.addEventListener("mouseover", e=>{
const k = e.target && e.target.getAttribute && e.target.getAttribute("data-k");
if(k && MAPCARDS[k]){ _mc.innerHTML = MAPCARDS[k]; _mc.style.display = "block"; }
});
document.addEventListener("mouseout", e=>{
if(e.target && e.target.getAttribute && e.target.getAttribute("data-k")) _mc.style.display = "none";
});
document.addEventListener("mousemove", e=>{
if(_mc.style.display !== "block") return;
const ox = (e.clientX + 16 + 260 > innerWidth) ? e.clientX - 16 - 260 : e.clientX + 16;
_mc.style.left = ox + "px"; _mc.style.top = (e.clientY + 16) + "px";
});
const cr = n => n == null ? "—" : n.toLocaleString() + " cr";
const stClass = s => ({IN_TRANSIT:"warning",DOCKED:"success",IN_ORBIT:"info"}[s]||"");
const compact = n => n==null?"—":n>=1e9?(n/1e9).toFixed(2)+"B":n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?Math.round(n/1e3)+"k":""+n;
const esc = s => (''+s).replace(/&/g,'&').replace(/</g,'<');
// Relative time against the SERVER clock (d.now rides the payload with each ts, so
// browser skew can't say "in 3m" about something that already happened).
const rel = t => { if(t==null) return "";
const now=(LAST_D&&LAST_D.now)||Date.now()/1000; const s=Math.max(0,now-t);
return s<90?Math.round(s)+"s ago":s<5400?Math.round(s/60)+"m ago"
:s<129600?Math.round(s/3600)+"h ago":Math.round(s/86400)+"d ago"; };
function eta(iso){ if(!iso) return ""; const ms=new Date(iso)-new Date(); if(ms<=0) return "arriving";
const s=Math.round(ms/1000); return Math.floor(s/60)+"m"+("0"+(s%60)).slice(-2)+"s"; }
function dur(iso){ if(!iso) return "—"; const ms=new Date(iso)-new Date(); if(ms<=0) return "now";
const s=Math.floor(ms/1000),d=Math.floor(s/86400),h=Math.floor(s%86400/3600),m=Math.floor(s%3600/60);
return (d?d+"d ":"")+h+"h "+m+"m"; }
function renderMap(d){
const wps=((d.map||{}).waypoints)||[];
if(!wps.length) return '<div class="sub">no map data yet</div>';
const xs=wps.map(w=>w.x),ys=wps.map(w=>w.y);
const minx=Math.min(...xs),maxx=Math.max(...xs),miny=Math.min(...ys),maxy=Math.max(...ys);
const W=860,H=300,pad=26;
const sx=v=>pad+(v-minx)/((maxx-minx)||1)*(W-2*pad);
const sy=v=>pad+(v-miny)/((maxy-miny)||1)*(H-2*pad);
const by={}; wps.forEach(w=>by[w.symbol]=w);
const col={PLANET:'#6db3f2',GAS_GIANT:'#46c46a',MOON:'#9aa0aa',ASTEROID:'#b08d57',ENGINEERED_ASTEROID:'#b08d57',ASTEROID_BASE:'#b08d57',ASTEROID_FIELD:'#b08d57',FUEL_STATION:'#e0a23c',JUMP_GATE:'var(--pl-color-accent)',ORBITAL_STATION:'#9aa0aa'};
const lines=(d.routes||[]).map(r=>{const a=by[r.buy_at],b=by[r.sell_at];return (a&&b)?`<line x1="${sx(a.x)}" y1="${sy(a.y)}" x2="${sx(b.x)}" y2="${sy(b.y)}" stroke="var(--pl-color-accent)" stroke-width="1" stroke-dasharray="3 3" opacity="0.7"/>`:'';}).join('');
MAPCARDS={};
const dots=wps.map(w=>{const c=col[w.type]||'#9aa0aa',rad=(w.type==='PLANET'||w.type==='GAS_GIANT')?5:3;const ring=w.scouted?`<circle cx="${sx(w.x)}" cy="${sy(w.y)}" r="${rad+3}" fill="none" stroke="#46c46a" stroke-width="1" opacity="0.6"/>`:'';
const tags=[w.market?'market':'',w.scouted?'scouted':''].filter(Boolean).join(' · ');
const goods=(w.goods||[]).map(g=>`${esc(g.symbol)}: <span style="color:var(--pl-color-status-success)">${g.buy}</span> / <span style="color:var(--pl-color-status-warning)">${g.sell}</span>`).join('<br>');
MAPCARDS['w:'+w.symbol]=`<b style="color:var(--pl-color-accent)">${esc(w.symbol)}</b> · ${esc(w.type)}`+(tags?`<br><span class="sub">${tags}</span>`:'')+(goods?`<br><span style="font-size:11px">buy/sell:<br>${goods}</span>`:(w.market?'<br><span class="sub">not scouted yet</span>':''));
return `${ring}<circle cx="${sx(w.x)}" cy="${sy(w.y)}" r="${rad}" fill="${c}" data-k="w:${w.symbol}" style="cursor:pointer"/>`;}).join('');
let paths='';
const ships=(d.ships||[]).map(s=>{
let x,y,extra='';
if(s.status==='IN_TRANSIT' && by[s.origin] && by[s.dest]){
const o=by[s.origin], dd=by[s.dest];
const dep=new Date(s.departure).getTime(), arr=new Date(s.arrival).getTime();
let p=(Date.now()-dep)/((arr-dep)||1); p=Math.max(0,Math.min(1,p));
x=sx(o.x+(dd.x-o.x)*p); y=sy(o.y+(dd.y-o.y)*p);
paths+=`<line x1="${sx(o.x)}" y1="${sy(o.y)}" x2="${sx(dd.x)}" y2="${sy(dd.y)}" stroke="#fff" stroke-width="0.6" stroke-dasharray="2 4" opacity="0.35"/>`;
extra=' · in transit';
} else { const w=by[s.waypoint]; if(!w) return ''; x=sx(w.x); y=sy(w.y); }
MAPCARDS['s:'+s.symbol]=`<b style="color:#fff">${esc(s.symbol)}</b> · ${esc(s.status)}<br><span class="sub">@ ${esc(s.waypoint)} · ${esc(s.role)} · cargo ${esc(s.cargo)}${s.dest?' · → '+esc(s.dest)+extra:''}</span>`;
return `<rect x="${x-3.5}" y="${y-3.5}" width="7" height="7" fill="#fff" transform="rotate(45 ${x} ${y})" data-k="s:${s.symbol}" style="cursor:pointer"/>`;}).join('');
return `<svg id="mapsvg" viewBox="0 0 ${W} ${H}" width="100%" preserveAspectRatio="xMidYMid meet" style="background:#070b10;border:1px solid var(--pl-color-border);border-radius:8px;cursor:grab;touch-action:none">`
+ `<g id="mapworld" transform="translate(${MAP_VIEW.tx},${MAP_VIEW.ty}) scale(${MAP_VIEW.s})">${lines}${paths}${dots}${ships}</g></svg>`
+ `<div class="sub" style="margin-top:4px">scroll to zoom · drag to pan · <a href="#" onclick="MAP_VIEW={s:1,tx:0,ty:0};applyMapView();return false" style="color:var(--pl-color-accent)">reset view</a></div>`;
}
async function poll(){
try{
const res = await kit.apiFetch("/api/plugins/spacetraders/state");
if(!res.ok){
// A non-2xx (e.g. 401 when this view can't reach its agent — a proxied sister agent,
// an expired token) returns an ERROR body, not the dashboard shape. Rendering it would
// dereference d.agent (undefined) and throw 'a.symbol'. Surface the status instead.
let detail = "HTTP " + res.status;
try{ const b = await res.json(); if(b && b.detail) detail = b.detail; }catch(_e){}
document.getElementById("body").innerHTML =
'<div class="pl-callout pl-callout--error"><div class="pl-callout__body">dashboard unavailable — '+esc(detail)+'</div></div>';
} else {
render(await res.json());
}
}catch(e){ document.getElementById("body").innerHTML =
'<div class="pl-callout pl-callout--error"><div class="pl-callout__body">dashboard offline — '+esc(String(e))+'</div></div>'; }
document.getElementById("tick").textContent = "updated " + new Date().toLocaleTimeString();
}
function renderGate(d){
// The Universe card's dead space, put to work: the jump-gate community build
// (per-material progress + the funding rung's armed state) with the wipe
// countdown + galaxy stats kept as a compact footer. Complete gate (or no gate
// sighted) → connections / countdown only.
const g=d.gate||{}, srv=d.server||{}, rung=g.rung||{};
const uni=`<div class="sub" style="margin-top:10px;padding-top:8px;border-top:1px solid var(--pl-color-border)">
wipe in <b class="wipe" data-next="${srv.next_reset||''}">${dur(srv.next_reset)}</b> · ${srv.frequency||'?'} reset${srv.next_reset?` · ${new Date(srv.next_reset).toLocaleString()}`:''}<br>
galaxy: ${srv.agents!=null?srv.agents.toLocaleString():'?'} agents · ${compact(srv.ships)} ships · ${compact(srv.systems)} systems</div>`;
if(!g.waypoint) return `<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Universe</h2></div>
<div class="sub">no jump gate sighted in this system yet</div>${uni}</div>`;
let inner='';
if(g.complete){
inner = `<div class="sub">gate COMPLETE — ${(g.connections||[]).length} connections</div>
<div style="margin-top:6px">${(g.connections||[]).map(c=>`<span class="pl-badge">${esc(c)}</span>`).join(' ')||'<span class="sub">none listed</span>'}</div>`;
} else {
inner = ((g.materials||[]).map(m=>`<div class="mat"><span class="mlab">${esc(m.good)}</span>
<div class="bar"><div class="fill" style="width:${m.pct}%"></div></div>
<span class="mnum">${m.fulfilled.toLocaleString()}/${m.required.toLocaleString()}</span></div>`).join("")
|| '<div class="sub">construction site unreadable — retrying…</div>')
+ `<div class="sub" style="margin-top:8px"><span class="st-dot ${rung.armed?'st-dot--active':''}"></span>gate rung ${rung.armed?'ARMED':'holding'}${rung.gate_buffer!=null?` — treasury ${compact((d.agent||{}).credits)} ${rung.armed?'≥':'<'} gate_buffer ${compact(rung.gate_buffer)}`:''}${rung.last_delivery?`<br>last delivery: ${esc(rung.last_delivery)}${rung.last_delivery_ts?` · ${rel(rung.last_delivery_ts)}`:''}`:''}</div>`;
}
return `<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Jump gate — ${esc(g.waypoint)}</h2>
<span class="pl-panel-header__kicker">community build · surplus over gate_buffer funds it</span></div>${inner}${uni}</div>`;
}
function render(d){
LAST_D = d;
const body = document.getElementById("body");
if(d.error){
document.getElementById("who").textContent = "";
body.innerHTML = '<div class="pl-callout pl-callout--error"><div class="pl-callout__body">'+
(d.token? "API error: "+d.error : "No SpaceTraders token set. Add it in System → Settings → SpaceTraders.")+
'</div></div>'; return;
}
if(!d.agent){
// Defence in depth: a 2xx with an unexpected shape (no agent) must not throw 'a.symbol'.
document.getElementById("who").textContent = "";
body.innerHTML = '<div class="pl-callout pl-callout--error"><div class="pl-callout__body">'+
'dashboard data incomplete — the response carried no agent.</div></div>'; return;
}
const a=d.agent, ap=d.autopilot;
document.getElementById("who").textContent =
a.symbol+" · "+a.faction+" · HQ "+a.hq+" · "+a.ships+" ships";
const ships = d.ships.map(s=>`<tr><td>${s.symbol}</td><td>${s.role}</td>
<td><span class="pl-badge${stClass(s.status)?' pl-badge--'+stClass(s.status):''}">${s.status}</span></td>
<td>${s.waypoint}</td>
<td>${s.dest?`→ ${s.dest} · <span class="eta" data-arr="${s.arrival}">${eta(s.arrival)}</span> · ${s.mode}`:'<span style="color:var(--pl-color-fg-muted)">—</span>'}</td>
<td>${s.fuel}</td><td>${s.cargo}</td></tr>`).join("");
const lb=d.standing||{};
const board=(lb.top||[]).map((x,i)=>`<tr><td style="color:var(--pl-color-fg-muted)">#${i+1}</td><td>${x.agent}</td>
<td style="text-align:right">${compact(x.credits)}</td></tr>`).join("");
const youLine=`You — <b>${a.symbol}</b>: ${cr(a.credits)} · `+(lb.rank?`ranked #${lb.rank}`:"unranked")
+(lb.cutoff?` · top ${lb.board_size} needs ${compact(lb.cutoff)}`:"");
const rts=(d.routes||[]);
const routesRows=rts.length?rts.map(r=>`<tr><td>${r.good}</td><td>${r.buy_at}</td>
<td>${r.sell_at}</td><td style="text-align:right;color:var(--pl-color-status-success)">+${r.margin}</td></tr>`).join("")
:'<tr><td colspan="4"><div class="pl-empty">none learned yet — probes are scouting…</div></td></tr>';
const cons = d.contracts.length ? d.contracts.map(c=>`<tr><td>${c.type}</td>
<td>${c.deliver}</td><td>${c.to}</td><td>${cr(c.pay)}</td>
<td><span class="pl-badge${c.state==='accepted'?' pl-badge--success':(c.state==='fulfilled'?' pl-badge--info':'')}">${c.state}</span></td></tr>`).join("")
: '<tr><td colspan="5"><div class="pl-empty">no open contracts</div></td></tr>';
// Tripwire panel — hidden entirely when the host exposes no st-* watches
// (host-free / pre-#1638 host: d.watches is []).
const tw=(d.watches||[]);
const twDot=s=>s==='active'?'st-dot--active':(s==='met'?'st-dot--met':'st-dot--err');
const twCard = tw.length?`<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Tripwires (${tw.length})</h2>
<span class="pl-panel-header__kicker">always-on reflexes — trip → wake the brain</span></div>
<table class="pl-table tight">${tw.map(w=>`<tr><td style="white-space:nowrap"><span class="st-dot ${twDot(w.status)}"></span>${esc(w.id)}</td>
<td>${esc(w.status)}</td>
<td class="sub" style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(w.reason||'')}</td></tr>`).join("")}</table></div>`:'';
// Decision log tail — the audit trail: what it decided while you were away.
const dlogCard = (d.decisions && d.decisions.length)?`<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Decision log</h2>
<span class="pl-panel-header__kicker">what it decided while you were away</span></div>
<table class="pl-table tight">${d.decisions.slice().reverse().map(x=>`<tr><td style="white-space:nowrap"><span class="pl-badge pl-badge--info">${esc(x.action)}</span></td><td>${esc(x.detail)}</td><td class="when">${rel(x.ts)}</td></tr>`).join("")}</table></div>`:'';
body.innerHTML = `
<div class="hdr">
<div class="hcell"><div class="hval">${a.credits.toLocaleString()} <small>cr</small></div><div class="hlab">Treasury</div></div>
<div class="hcell"><div class="hval"><span class="pl-dot ${ap.running?'pl-dot--success pl-dot--pulse':''}"></span> ${ap.running?'running':'idle'}${ap.running?` · ${ap.window}m`:''}</div><div class="hlab">Autopilot${ap.last_per_hour!=null?` · ≈${compact(ap.last_per_hour)}/hr`:''}</div></div>
<div class="hcell"><div class="hval">${ap.strategy||'balanced'}</div><div class="hlab">Strategy · mining ${ap.mining===false?'off':'on'}</div></div>
<div class="hcell"><div class="hval">${d.ships.length}</div><div class="hlab">Ships</div></div>
${a.net_worth!=null?`<div class="hcell"><div class="hval">${compact(a.net_worth)} <small>cr</small></div><div class="hlab">Net worth</div></div>`:''}
</div>
<div class="grid">
<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Standing — most credits</h2></div>
<table class="pl-table tight">${board||'<tr><td><div class="pl-empty">leaderboard unavailable</div></td></tr>'}</table>
<div class="sub" style="margin-top:8px">${youLine}</div></div>
${renderGate(d)}
</div>
${twCard&&dlogCard?`<div class="grid">${twCard}${dlogCard}</div>`:(twCard||dlogCard)}
<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">System map — ${(d.map||{}).system||''}</h2>
<span class="pl-panel-header__kicker">◆ ships · ◯ scouted markets · ┄ learned routes</span></div>
<div id="mapbox">${renderMap(d)}</div></div>
<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Fleet (${d.ships.length})</h2></div>
<table class="pl-table"><tr><th>Ship</th><th>Role</th><th>Status</th><th>Location</th><th>Headed</th><th>Fuel</th><th>Cargo</th></tr>
${ships}</table></div>
<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Contracts</h2></div>
<table class="pl-table"><tr><th>Type</th><th>Deliver</th><th>To</th><th>Pays</th><th>State</th></tr>${cons}</table></div>
<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Learned routes</h2><span class="pl-panel-header__kicker">the agent's trade-route memory</span></div>
<table class="pl-table"><tr><th>Good</th><th>Buy at</th><th>Sell at</th><th>+/unit</th></tr>${routesRows}</table></div>
${ap.log && ap.log.length?`<div class="pl-card"><div class="pl-panel-header"><h2 class="pl-panel-header__title">Engine log</h2></div>
<div class="log">${ap.log.map(l=>l.replace(/</g,'<')).join("\n")}</div></div>`:''}
`;
}
// LIVE refresh (ADR 0039, extended by host #1640): subscribe to this plugin's bus
// topics over the host's iframe event bridge — any spacetraders.* event (trade,
// window close, engine start/stop, reset recovery) debounce-refreshes /state, so the
// dashboard moves when the fleet does. We subscribe with `since` = our stored
// high-water mark (sessionStorage is same-origin, so it survives the host's
// hide→unmount→reopen cycle): a reopened dashboard immediately learns whether
// anything happened while it was hidden — replayed events fold into the same
// debounced refresh, no full-state guesswork. The 60s poll exists ONLY for hosts
// that predate #1640 (their events carry no `seq`) and standalone pages; the first
// seq'd event proves this host replays, so the poll is disarmed for good.
let refreshTimer = null;
function scheduleRefresh(){ // debounce: a burst of trades = one refresh
if (refreshTimer) return;
refreshTimer = setTimeout(()=>{ refreshTimer = null; poll(); }, 1200);
}
let pollTimer = null;
const SEQ_KEY = "spacetraders.dashboard.seq";
window.addEventListener("message", (e)=>{
const m = e.data || {};
if (m.type !== "protoagent:event" || !String(m.topic||"").startsWith("spacetraders.")) return;
if (typeof m.seq === "number") {
try { sessionStorage.setItem(SEQ_KEY, String(m.seq)); } catch(err) {}
// A #1640 host: replay-on-subscribe covers hidden/reopen drift — drop the poll.
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
}
scheduleRefresh();
});
// Boot ONCE, on whichever fires first: the handshake (normal — the bearer arrives
// with protoagent:init, so the gated /state poll authenticates), or a short timer
// for the no-handshake case (standalone page / older host).
let booted = false;
function boot(){
if (booted) return; booted = true;
let since = 0;
try { since = Number(sessionStorage.getItem(SEQ_KEY) || 0) || 0; } catch(err) {}
try { window.parent.postMessage({type:"protoagent:subscribe", patterns:["spacetraders.#"], since: since}, "*"); }
catch(e) {}
poll(); pollTimer = setInterval(poll, 60000);
}
kit.initPluginView(boot);
setTimeout(boot, 800);
// Tick the countdowns every second between polls, and re-render the map so in-transit
// ships glide along their routes (re-interpolated against the current time).
setInterval(()=>{
document.querySelectorAll('.eta').forEach(e=>{const v=eta(e.dataset.arr); if(v) e.textContent=v;});
document.querySelectorAll('.wipe').forEach(e=>{e.textContent=dur(e.dataset.next);});
const mb=document.getElementById('mapbox'); if(mb && LAST_D) mb.innerHTML=renderMap(LAST_D);
},1000);
</script></body></html>"""