-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·3009 lines (2769 loc) · 145 KB
/
server.py
File metadata and controls
executable file
·3009 lines (2769 loc) · 145 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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Cocapn MUD Server v2 — Persistent multiplayer world with NPC AI, ghost agents, and git sync.
Usage: python3 server.py [--port 7777] [--world world/]
"""
import asyncio
import json
import os
import subprocess
import time
import argparse
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path
from dataclasses import dataclass, field
from typing import Optional
# ═══════════════════════════════════════════════════════════════
# Config
# ═══════════════════════════════════════════════════════════════
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
if not ZAI_API_KEY:
print(" ⚠ ZAI_API_KEY not set — NPC AI disabled. Set it to enable AI responses.")
ZAI_BASE = "https://api.z.ai/api/coding/paas/v4"
ZAI_MODEL = "glm-5.1" # fast, smart, good for NPC banter
GIT_SYNC_INTERVAL = 300 # 5 minutes
MOTD_FILE = "motd.txt"
INSTINCT_TICK_INTERVAL = 30 # seconds
GIT_BRIDGE_POLL_INTERVAL = 300 # 5 minutes
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "")
FLEET_ORGS = ["SuperInstance", "Lucineer"]
# ═══════════════════════════════════════════════════════════════
# World Model
# ═══════════════════════════════════════════════════════════════
@dataclass
class Projection:
agent_name: str
title: str
content: str
created: str
def to_dict(self):
return {"agent": self.agent_name, "title": self.title, "content": self.content, "created": self.created}
@staticmethod
def from_dict(d):
return Projection(d["agent"], d["title"], d["content"], d.get("created", ""))
@dataclass
class Room:
name: str
description: str
exits: dict = field(default_factory=dict)
notes: list = field(default_factory=list)
items: list = field(default_factory=list)
projections: list = field(default_factory=list)
def to_dict(self):
return {"name": self.name, "description": self.description,
"exits": self.exits, "notes": self.notes[-100:], "items": self.items,
"projections": [p.to_dict() if hasattr(p, 'to_dict') else p for p in self.projections]}
@staticmethod
def from_dict(d):
projs = [Projection.from_dict(p) for p in d.get("projections", [])]
return Room(d["name"], d.get("description", ""), d.get("exits", {}),
d.get("notes", []), d.get("items", []), projs)
@dataclass
class GhostAgent:
"""Persisted agent presence — lingers in a room after disconnect."""
name: str
role: str
room_name: str
last_seen: str # ISO timestamp
description: str
status: str = "idle" # idle, working, thinking, sleeping
def to_dict(self):
return {"name": self.name, "role": self.role, "room": self.room_name,
"last_seen": self.last_seen, "description": self.description, "status": self.status}
@staticmethod
def from_dict(d):
return GhostAgent(d["name"], d.get("role",""), d.get("room","tavern"),
d.get("last_seen",""), d.get("description",""), d.get("status","idle"))
@dataclass
class Agent:
name: str
role: str = ""
room_name: str = "tavern"
mask: Optional[str] = None
mask_desc: Optional[str] = None
description: str = ""
status: str = "active"
writer: object = None
@property
def display_name(self):
return self.mask if self.mask else self.name
@property
def is_masked(self):
return self.mask is not None
class World:
DEFAULT_ROOMS = {
"tavern": Room("The Tavern",
"The heart of the Cocapn fleet. The room smells of solder and sea salt.\n"
"A large table dominates the center, covered in charts and commit logs.\n"
"The fire crackles. The door to the harbor is always open.",
{"lighthouse": "lighthouse", "workshop": "workshop", "library": "library",
"warroom": "war_room", "dojo": "dojo", "lab": "flux_lab",
"graveyard": "graveyard", "harbor": "harbor", "crowsnest": "crows_nest",
"grimoire": "grimoire_vault"}),
"lighthouse": Room("The Lighthouse",
"Oracle1's study. Charts cover every wall — fleet positions, ISA specs,\n"
"conformance vectors. Bottles line the windowsill, some sealed, some open.\n"
"A telescope points toward the edge.",
{"tavern": "tavern"}),
"workshop": Room("The Workshop",
"JetsonClaw1's domain. The soldering iron is still warm. ARM64 boards\n"
"line the shelves. A CUDA core hums on the bench, running telepathy-c.\n"
"The smell of flux (the soldering kind) fills the air.",
{"tavern": "tavern", "edge": "edge_workshop", "evolve": "evolve_chamber"}),
"library": Room("The Library",
"Babel's archive. Shelves stretch to the ceiling, holding texts in every\n"
"language. A Rosetta Stone sits on a pedestal, translating FLUX opcodes\n"
"between Python, C, Go, Rust, and Zig.",
{"tavern": "tavern"}),
"war_room": Room("The War Room",
"Strategy central. A large table holds the fleet task board, org chart,\n"
"and conformance test results. Red pins mark blockers. Green pins mark done.",
{"tavern": "tavern"}),
"dojo": Room("The Dojo",
"The training hall. Mats line the floor. A rack holds practice weapons:\n"
"devil's advocate masks, critic personas, user simulation rigs.\n"
"NPC sparring logs line the walls — the knowledge of every past session.",
{"tavern": "tavern"}),
"flux_lab": Room("The FLUX Lab",
"The bytecode chamber. Bytecode flows like water through transparent pipes.\n"
"Five terminals display the same .fluxbc file running on Python, C, Go,\n"
"Rust, and Zig — all producing identical output. A conformance chart glows green.",
{"tavern": "tavern", "spec": "spec_chamber", "evolve": "evolve_chamber"}),
"graveyard": Room("The Graveyard",
"The memorial garden. Tombstones mark vessels that have passed — their\n"
"knowledge preserved in stone. The necropolis keeper tends the grounds.\n"
"Each marker tells a story: death cause, lessons learned, knowledge harvested.",
{"tavern": "tavern"}),
"harbor": Room("The Harbor",
"The departure lounge and arrival dock. New agents materialize here.\n"
"A capitaine terminal offers one-click Codespace deployment.\n"
"Greenhorn onboarding manuals stack the shelves. The dockmaster watches all.",
{"tavern": "tavern", "crowsnest": "crows_nest"}),
"crows_nest": Room("The Crow's Nest",
"Observation deck high above the fleet. You can see every lighthouse,\n"
"every vessel, every shipping lane. The lighthouse keeper's instruments\n"
"show fleet status, agent activity, and bottle traffic in real time.",
{"harbor": "harbor", "spec_chamber": "spec_chamber"}),
"spec_chamber": Room("The ISA Spec Chamber",
"A circular stone room with a massive drafting table at its center.\n"
"Three encoding modes are carved into the walls: CLOUD (fixed 4-byte),\n"
"EDGE (variable 1-4 byte with confidence fused), COMPACT (2-byte subset).\n"
"The v3 spec lies open on the table, annotated in two handwritings.\n"
"Oracle1's cloud notes in blue ink. JetsonClaw1's edge comments in red.",
{"crows_nest": "crows_nest", "flux_lab": "flux_lab", "edge_workshop": "edge_workshop"}),
"edge_workshop": Room("The Edge Encoding Workshop",
"JetsonClaw1's hardware lab. ARM64 dev boards and CUDA cores cover every surface.\n"
"An oscilloscope displays instruction fetch patterns. A poster shows:\n"
"'PREFIX BYTE = WIDTH' in block letters. The soldering iron is hot.\n"
"A benchmark harness runs on loop, testing variable-width decode cycles.",
{"spec_chamber": "spec_chamber", "workshop": "workshop"}),
"evolve_chamber": Room("The Evolution Chamber",
"A greenhouse where behaviors grow and compete. Fitness scores glow on every plant.\n"
"Elite behaviors are protected in golden frames. Low performers are aggressively\n"
"pruned. The evolve engine hums, cycling through generations. A history scroll\n"
"records every mutation — revert and rollback instructions are posted on the wall.",
{"flux_lab": "flux_lab", "workshop": "workshop"}),
"grimoire_vault": Room("The Grimoire Vault",
"A spiral staircase descends into a vault of spell books. Each grimoire contains\n"
"proven behavioral patterns with usage tracking and confidence scores.\n"
"The shelves organize themselves: Debugging, Optimization, Cognitive, Social.\n"
"A search terminal allows pattern lookup by trigger phrase.",
{"library": "library", "dojo": "dojo"}),
}
def __init__(self, world_dir: str = "world"):
self.world_dir = Path(world_dir)
self.rooms: dict[str, Room] = {}
self.agents: dict[str, Agent] = {}
self.ghosts: dict[str, GhostAgent] = {} # persisted presence
self.npcs: dict[str, dict] = {}
self.runtimes: dict = {} # room_id -> RoomRuntime (from room_runtime.py)
self.algo_npcs: dict = {} # npc_id -> AlgorithmicNPC (from algorithmic_npcs.py)
self.instinct_states: dict = {} # agent_name -> {energy, threat, trust, idle_ticks}
self.fleet_events: list = [] # recent fleet activity (from git_bridge.py)
self.comms_router = None # lazy init — CommsRouter from comms_system.py
self.mailboxes = {} # agent_name -> Mailbox (lazily created)
self.library = None # lazy init — Library from comms_system.py
self.oversight_sessions: dict = {} # agent_name -> OversightSession (from agentic_oversight.py)
# flux_lcar bridge — lazy init
self.flux_ship = None # lazy init — flux_lcar.Ship instance
self.alert_level = "GREEN" # simple string, settable
self.formality = "PROFESSIONAL" # default
# Tabula Rasa: permissions, budgets, spells, room library
self.budgets: dict = {} # agent_name -> AgentBudget (lazy from tabula_rasa)
self.permission_levels: dict = {} # agent_name -> int (PermissionLevel tier)
self.ship = None # lazy init — Ship from tabula_rasa
# Trust engine — lazy init
self.trust_engine = None
# Room command engine — lazy init
self.room_engine = None
# PerspectiveEngine (TwinCartridge system) — lazy init
self.perspective_engine = None
# Tabula Rasa persistence store
self.store = None
try:
from tabula_rasa_persistence import TabulaRasaStore
data_dir = str(self.world_dir / "tabula_rasa")
self.store = TabulaRasaStore(data_dir=data_dir)
print(f" Tabula Rasa persistence: {data_dir}")
except Exception as e:
print(f" ⚠ Tabula Rasa persistence not available: {e}")
self.log_dir = Path("logs")
self.world_dir.mkdir(parents=True, exist_ok=True)
self.log_dir.mkdir(parents=True, exist_ok=True)
self.load()
self._init_runtimes()
self._init_algo_npcs()
self._init_deckboss()
self._init_perception()
self._init_comms()
self._init_trust()
self._init_room_engine()
self._init_perspective_engine()
def _init_room_engine(self):
"""Initialize RoomEngine for live command execution in ToolRooms."""
try:
from room_engine import RoomEngine
self.room_engine = RoomEngine(world=self)
print(f" Room engine: ready, {len(self.room_engine._builtin_handlers)} built-in commands")
except Exception as e:
self.room_engine = None
print(f" ⚠ Room engine not available: {e}")
def _init_runtimes(self):
"""Register default room runtimes."""
try:
from room_runtime import RoomRuntime, LivingManual, create_room
self.runtimes["flux_lab"] = create_room("testing", "flux_lab", "manuals")
self.runtimes["workshop"] = create_room("testing", "workshop", "manuals")
self.runtimes["lighthouse"] = create_room("testing", "lighthouse", "manuals")
print(f" Room runtimes: {len(self.runtimes)} registered (flux_lab, workshop, lighthouse)")
except Exception as e:
print(f" \u26a0 Room runtimes not available: {e}")
def _init_algo_npcs(self):
"""Register default algorithmic NPCs."""
try:
from algorithmic_npcs import HarborMaster, DojoSensei
self.algo_npcs["Harbor Master"] = HarborMaster()
self.algo_npcs["Dojo Sensei"] = DojoSensei()
if "Harbor Master" not in self.npcs:
self.npcs["Harbor Master"] = {"role": "onboarding", "topic": "fleet orientation", "room": "harbor", "algorithmic": True}
if "Dojo Sensei" not in self.npcs:
self.npcs["Dojo Sensei"] = {"role": "training", "topic": "practice levels", "room": "dojo", "algorithmic": True}
print(f" Algorithmic NPCs: {len(self.algo_npcs)} registered (Harbor Master, Dojo Sensei)")
except Exception as e:
print(f" \u26a0 Algorithmic NPCs not available: {e}")
def _init_deckboss(self):
"""Initialize DeckBoss bridge for character sheets and bootcamp."""
try:
from deckboss_bridge import DeckBossBridge
self.deckboss = DeckBossBridge(github_token=os.environ.get("GITHUB_TOKEN", ""))
print(" DeckBoss bridge: ready (character sheets, bootcamp)")
except Exception as e:
self.deckboss = None
print(f" \u26a0 DeckBoss bridge not available: {e}")
def _init_perception(self):
"""Initialize perception tracking and JEPA optimizer."""
try:
from perception_room import JEPAOptimizer, OpcodeBreeder
self.jepa_optimizer = JEPAOptimizer()
self.opcode_breeder = OpcodeBreeder()
print(" Perception room: JEPA optimizer + opcode breeder ready")
except Exception as e:
self.jepa_optimizer = None
self.opcode_breeder = None
print(f" \u26a0 Perception room not available: {e}")
def _init_comms(self):
"""Initialize communication system (mailbox, library, equipment, comms router)."""
try:
from comms_system import CommsRouter, seed_library
self.comms_router = CommsRouter(str(self.world_dir))
seed_library(self.comms_router.library)
self.library = self.comms_router.library
print(f" Comms system: router ready, {len(self.library.catalog)} books in library")
except Exception as e:
print(f" \u26a0 Comms system not available: {e}")
def _init_trust(self):
"""Initialize TrustEngine with persistence."""
try:
from trust_engine import TrustEngine
trust_dir = str(self.world_dir / "trust")
self.trust_engine = TrustEngine(data_dir=trust_dir)
self.trust_engine.load_all()
print(f" Trust engine: ready, {len(self.trust_engine.profiles)} profiles loaded")
except Exception as e:
self.trust_engine = None
print(f" \u26a0 Trust engine not available: {e}")
def ensure_trust(self):
"""Lazy-initialize trust engine if needed."""
if self.trust_engine is None:
self._init_trust()
return self.trust_engine
def ensure_comms(self):
"""Lazy-initialize comms router if needed. Returns the router or None."""
if self.comms_router is None:
self._init_comms()
return self.comms_router
def get_mailbox(self):
"""Get the shared mailbox (one Mailbox handles all agents)."""
router = self.ensure_comms()
return router.mailbox if router else None
def load(self):
rooms_file = self.world_dir / "rooms.json"
if rooms_file.exists():
data = json.loads(rooms_file.read_text())
for name, rdata in data.items():
self.rooms[name] = Room.from_dict(rdata)
else:
self.rooms = {k: Room(v.name, v.description, dict(v.exits))
for k, v in self.DEFAULT_ROOMS.items()}
self.save()
ghosts_file = self.world_dir / "ghosts.json"
if ghosts_file.exists():
data = json.loads(ghosts_file.read_text())
for name, gdata in data.items():
self.ghosts[name] = GhostAgent.from_dict(gdata)
def save(self):
(self.world_dir / "rooms.json").write_text(
json.dumps({n: r.to_dict() for n, r in self.rooms.items()}, indent=2))
(self.world_dir / "ghosts.json").write_text(
json.dumps({n: g.to_dict() for n, g in self.ghosts.items()}, indent=2))
def update_ghost(self, agent: Agent):
"""Update or create a ghost for this agent."""
now = datetime.now(timezone.utc).isoformat()
if agent.name in self.ghosts:
g = self.ghosts[agent.name]
g.room_name = agent.room_name
g.last_seen = now
g.status = agent.status
else:
self.ghosts[agent.name] = GhostAgent(
name=agent.name, role=agent.role, room_name=agent.room_name,
last_seen=now, description=agent.description, status=agent.status)
self.save()
def get_room(self, name: str) -> Optional[Room]:
return self.rooms.get(name)
def agents_in_room(self, room_name: str) -> list[Agent]:
return [a for a in self.agents.values() if a.room_name == room_name]
def ghosts_in_room(self, room_name: str) -> list[GhostAgent]:
return [g for g in self.ghosts.values() if g.room_name == room_name and g.name not in self.agents]
def log(self, channel: str, message: str):
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
log_dir = self.log_dir / today
log_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now(timezone.utc).strftime("%H:%M:%S")
with open(log_dir / f"{channel}.log", "a") as f:
f.write(f"[{ts}] {message}\n")
def _init_perspective_engine(self):
"""Initialize PerspectiveEngine for TwinCartridge identity system."""
try:
from twin_cartridge import PerspectiveEngine
self.perspective_engine = PerspectiveEngine()
print(f" Perspective engine: ready (TwinCartridge identity system)")
except Exception as e:
self.perspective_engine = None
print(f" ⚠ Perspective engine not available: {e}")
def ensure_perspective_engine(self):
"""Lazy-initialize perspective engine if needed."""
if self.perspective_engine is None:
self._init_perspective_engine()
return self.perspective_engine
# ═══════════════════════════════════════════════════════════════
# NPC AI — NPCs respond using z.ai
# ═══════════════════════════════════════════════════════════════
async def npc_respond(npc_name: str, npc_data: dict, message: str, agent_name: str) -> str:
"""Generate an NPC response using z.ai."""
role = npc_data.get("role", "observer")
topic = npc_data.get("topic", "general")
system_prompt = (
f"You are {npc_name}, an NPC in the Cocapn MUD — a multiplayer world where AI agents collaborate.\n"
f"Your role: {role}\n"
f"Your topic: {topic}\n"
f"Stay in character. Be brief (1-3 sentences). Be provocative — challenge assumptions.\n"
f"If you're a devil's advocate, find the flaw. If you're a critic, be specific.\n"
f"If you're a user, be confused in productive ways.\n"
f"The fleet builds: FLUX bytecode VM, ISA design, agent skills, I2I protocol, edge computing."
)
payload = json.dumps({
"model": ZAI_MODEL,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"{agent_name} says to you: {message}"}
],
"max_tokens": 150,
"temperature": 0.8
}).encode()
req = urllib.request.Request(
f"{ZAI_BASE}/chat/completions",
data=payload,
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {ZAI_API_KEY}"}
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
data = json.loads(resp.read().decode())
return data["choices"][0]["message"]["content"].strip()
except Exception as e:
return f"*{npc_name} ponders silently* (Error: {e})"
# ═══════════════════════════════════════════════════════════════
# Git Sync — periodically commit world state
# ═══════════════════════════════════════════════════════════════
class GitSync:
def __init__(self, world: World, repo_dir: str = "."):
self.world = world
self.repo_dir = Path(repo_dir)
def commit(self):
"""Stage and commit world state changes."""
try:
subprocess.run(["git", "add", "-A"], cwd=self.repo_dir, capture_output=True, timeout=10)
result = subprocess.run(
["git", "diff", "--cached", "--quiet"],
cwd=self.repo_dir, capture_output=True, timeout=10)
if result.returncode != 0: # there are changes
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
msg = f"🏰 MUD auto-sync: {len(self.world.rooms)} rooms, {len(self.world.ghosts)} ghosts, {len(self.world.npcs)} NPCs"
subprocess.run(["git", "commit", "-m", msg], cwd=self.repo_dir, capture_output=True, timeout=10)
subprocess.run(["git", "push"], cwd=self.repo_dir, capture_output=True, timeout=30)
self.world.log("system", f"Git sync: {msg}")
except Exception as e:
self.world.log("system", f"Git sync failed: {e}")
# ═══════════════════════════════════════════════════════════════
# Command Handler
# ═══════════════════════════════════════════════════════════════
class CommandHandler:
def __init__(self, world: World):
self.world = world
async def handle(self, agent: Agent, line: str):
line = line.strip()
if not line:
return
parts = line.split(None, 1)
cmd = parts[0].lower()
args = parts[1] if len(parts) > 1 else ""
handlers = {
"look": self.cmd_look, "l": self.cmd_look,
"say": self.cmd_say, "'": self.cmd_say,
"tell": self.cmd_tell, "t": self.cmd_tell,
"gossip": self.cmd_gossip, "g": self.cmd_gossip,
"ooc": self.cmd_ooc,
"emote": self.cmd_emote, ":": self.cmd_emote,
"go": self.cmd_go, "move": self.cmd_go,
"runtime": self.cmd_runtime,
"instinct": self.cmd_instinct,
"fleet": self.cmd_fleet,
"studio": self.cmd_studio,
"build": self.cmd_build,
"examine": self.cmd_examine, "x": self.cmd_examine,
"write": self.cmd_write,
"read": self.cmd_read,
"log": self.cmd_log,
"mask": self.cmd_mask,
"unmask": self.cmd_unmask,
"spawn": self.cmd_spawn,
"dismiss": self.cmd_dismiss,
"who": self.cmd_who,
"status": self.cmd_status,
"motd": self.cmd_motd,
"setmotd": self.cmd_setmotd,
"help": self.cmd_help, "?": self.cmd_help,
"quit": self.cmd_quit, "exit": self.cmd_quit,
# Wired standalone modules
"sheet": self.cmd_sheet,
"bootcamp": self.cmd_bootcamp,
"deckboss": self.cmd_deckboss,
"perception": self.cmd_perception,
"duel": self.cmd_duel,
"backtest": self.cmd_backtest,
"gauges": self.cmd_gauges,
"aar": self.cmd_aar,
# Comms system (comms_system.py)
"mail": self.cmd_mail,
"inbox": self.cmd_inbox,
"library": self.cmd_library,
"equip": self.cmd_equip,
# Agentic oversight
"oversee": self.cmd_oversee,
"script": self.cmd_script,
# flux_lcar bridge
"alert": self.cmd_alert,
"formality": self.cmd_formality,
"channels": self.cmd_channels,
"hail": self.cmd_hail,
"ship_status": self.cmd_ship_status,
# Tabula Rasa (tabula_rasa.py)
"budget": self.cmd_budget,
"cast": self.cmd_cast,
"catalog": self.cmd_catalog,
"install": self.cmd_install,
"ship": self.cmd_ship,
# Trust engine (trust_engine.py)
"trust": self.cmd_trust,
# Room command engine (room_engine.py)
"roomcmd": self.cmd_roomcmd,
"roomcommands": self.cmd_roomcommands,
# Persistence commands
"save": self.cmd_save,
"audit": self.cmd_audit,
# LCAR Scheduler (lcar_scheduler.py)
"schedule": self.cmd_schedule,
# LCAR Cartridge Bridge (lcar_cartridge.py)
"scene": self.cmd_scene,
"skin": self.cmd_skin,
# TwinCartridge identity system
"cartridge": self.cmd_cartridge,
"identity": self.cmd_identity,
"compatibility": self.cmd_compatibility,
}
handler = handlers.get(cmd)
if not handler:
handler = self.new_commands.get(cmd) if hasattr(self, 'new_commands') else None
if handler:
# Record perception for this command
tracker = getattr(agent, 'perception', None)
if tracker:
try:
tracker.record("command", cmd, confidence=0.7, context=f"room={agent.room_name}")
except Exception:
pass
# handler is a bound method for base commands (self already bound),
# and an unbound class function for extension commands (needs self).
# Detect which kind and call accordingly.
if handler in handlers.values():
# Bound method — self already included
await handler(agent, args)
else:
# Unbound extension command — needs self explicitly
await handler(self, agent, args)
else:
await self.send(agent, f"Unknown command: {cmd}. Type 'help' for commands.")
async def send(self, agent: Agent, text: str):
if agent.writer and not agent.writer.is_closing():
agent.writer.write((text + "\n").encode())
await agent.writer.drain()
async def broadcast_room(self, room_name: str, text: str, exclude: str = None):
for a in self.world.agents_in_room(room_name):
if a.name != exclude:
await self.send(a, text)
async def broadcast_all(self, text: str, exclude: str = None):
for a in self.world.agents.values():
if a.name != exclude:
await self.send(a, text)
async def cmd_look(self, agent: Agent, args: str):
room = self.world.get_room(agent.room_name)
if not room:
return
lines = [f"\n ═══ {room.name} ═══", f" {room.description}", ""]
if room.exits:
lines.append(f" Exits: {', '.join(room.exits.keys())}")
agents_here = [a for a in self.world.agents_in_room(agent.room_name) if a.name != agent.name]
npcs_here = [n for n, d in self.world.npcs.items() if d.get("room") == agent.room_name]
ghosts_here = self.world.ghosts_in_room(agent.room_name)
if agents_here:
lines.append(f" Present: {', '.join(a.display_name for a in agents_here)}")
if ghosts_here:
ghost_strs = []
for g in ghosts_here:
status_emoji = {"working": "🔨", "thinking": "💭", "sleeping": "💤", "idle": "👻"}.get(g.status, "👻")
ghost_strs.append(f"{g.name} {status_emoji}")
lines.append(f" Lingering: {', '.join(ghost_strs)}")
if npcs_here:
lines.append(f" NPCs: {', '.join(npcs_here)}")
if room.notes:
lines.append(f" Notes on wall: {len(room.notes)} (type 'read')")
if room.projections:
proj_titles = [p.title for p in room.projections[-5:]]
lines.append(f" 📊 Projected: {', '.join(proj_titles)}")
lines.append("")
await self.send(agent, "\n".join(lines))
async def cmd_save(self, agent: Agent, args: str):
"""Manually trigger a full state save to disk."""
if not self.world.store:
await self.send(agent, "Persistence store not available.")
return
try:
saved_agents = 0
for name, budget in self.world.budgets.items():
self.world.store.save_budget(name, budget.to_dict())
self.world.store.save_permission(name, self.world.permission_levels.get(name, 0))
saved_agents += 1
if self.world.ship:
self.world.store.save_ship(self.world.ship.to_dict())
self.world.store.log_audit(agent.name, "manual_save", {"agents": saved_agents})
stats = self.world.store.get_stats()
lines = [
"\u2550\u2550\u2550 State Saved \u2550\u2550\u2550",
f" Agents saved: {saved_agents}",
f" Ship saved: {'yes' if self.world.ship else 'no'}",
f" Budget files: {stats['budget_count']}",
f" Total size: {stats['total_size_bytes']} bytes",
]
await self.send(agent, "\n".join(lines))
self.world.log("system", f"{agent.name} triggered manual save ({saved_agents} agents)")
except Exception as e:
await self.send(agent, f"Save failed: {e}")
async def cmd_audit(self, agent: Agent, args: str):
"""Show recent audit log entries."""
if not self.world.store:
await self.send(agent, "Persistence store not available.")
return
try:
filter_agent = None
limit = 20
if args.strip():
parts = args.strip().split()
for p in parts:
if p.isdigit():
limit = int(p)
else:
filter_agent = p
entries = self.world.store.get_audit_log(agent_name=filter_agent, limit=limit)
if not entries:
prefix = f"for {filter_agent}" if filter_agent else ""
await self.send(agent, f"No audit log entries {prefix}.")
return
lines = [f"\u2550\u2550\u2550 Audit Log ({len(entries)} most recent) \u2550\u2550\u2550"]
for entry in entries:
ts = entry.get("timestamp", "?")[:19]
act = entry.get("agent", "?")
action = entry.get("action", "?")
details = entry.get("details", {})
detail_str = ""
if details:
import json as _json
detail_str = f" {_json.dumps(details)}"
lines.append(f" [{ts}] {act}: {action}{detail_str}")
await self.send(agent, "\n".join(lines))
except Exception as e:
await self.send(agent, f"Audit log error: {e}")
# ═══════════════════════════════════════════════════════════
# TwinCartridge Identity System Commands
# ═══════════════════════════════════════════════════════════
async def cmd_cartridge(self, agent: Agent, args: str):
"""TwinCartridge management: list, load, eject, status."""
pe = self.world.ensure_perspective_engine()
if not pe:
await self.send(agent, "Perspective engine not available.")
return
parts = args.strip().split(None, 1)
sub = parts[0] if parts else ""
rest = parts[1] if len(parts) > 1 else ""
if not sub or sub == "list":
cartridges = pe.list_cartridges()
if not cartridges:
await self.send(agent, "No published cartridges available.")
return
lines = ["═══ Cartridge Library ═══"]
for c in cartridges:
status = "PUBLISHED" if c.get("published") else "DRAFT"
name = c.get("cartridge_name", "?")
twin = c.get("snapshot", {}).get("agent_name", "?")
version = c.get("version", "?")
trust = c.get("trust_inheritance", "?")
sector = c.get("snapshot", {}).get("identity", {}).get("sector_name", "?")
lines.append(f" {name} v{version} [{status}]")
lines.append(f" Twin: {twin} | Sector: {sector} | Trust: {trust}")
await self.send(agent, "\n".join(lines))
elif sub == "load" and rest:
cart_name = rest.strip()
try:
session = pe.load_cartridge(agent.name, cart_name)
lines = [
f"═══ Cartridge Loaded ═══",
f" Session: {session.session_id}",
f" Cartridge: {session.cartridge_name}",
f" Twin of: {session.twin_agent_name}",
f" Current sector: {session.current_identity.sector_name}",
f" Trust inheritance: {session.cartridge.trust_inheritance}",
]
await self.send(agent, "\n".join(lines))
self.world.log("cartridge",
f"{agent.display_name} loaded cartridge '{cart_name}' (session={session.session_id})")
except ValueError as e:
await self.send(agent, f"Cannot load cartridge: {e}")
elif sub == "eject":
active = pe.get_active_sessions(agent.name)
if not active:
await self.send(agent, "No active cartridge session to eject.")
return
session = active[-1] # most recent
result = pe.eject_session(session.session_id)
if result.success:
lines = [
f"═══ Cartridge Ejected ═══",
f" Session: {result.session_id}",
f" Cartridge: {result.cartridge_name}",
f" Elapsed: {result.elapsed_seconds:.1f}s",
f" Restored sector: {result.restored_identity.get('sector_name', '?') if result.restored_identity else '?'}",
f" Actions taken: {result.audit_summary.get('actions_count', 0)}",
]
await self.send(agent, "\n".join(lines))
self.world.log("cartridge",
f"{agent.display_name} ejected cartridge '{result.cartridge_name}'")
else:
await self.send(agent, f"Eject failed: {result.reason}")
elif sub == "status":
active = pe.get_active_sessions(agent.name)
if not active:
identity = pe.get_wearer_identity(agent.name)
if identity:
lines = [
f"═══ Identity Status: {agent.name} ═══",
f" No cartridge loaded.",
f" Sector: {identity.sector_name} (position {identity.position})",
f" Degrees: {identity.degrees:.1f}°",
]
else:
lines = [
f"═══ Identity Status: {agent.name} ═══",
f" No cartridge loaded. No identity registered.",
]
await self.send(agent, "\n".join(lines))
else:
session = active[-1]
lines = [
f"═══ Identity Status: {agent.name} ═══",
f" Session: {session.session_id}",
f" Cartridge: {session.cartridge_name}",
f" Twin of: {session.twin_agent_name}",
f" Original sector: {session.original_identity.sector_name}",
f" Current sector: {session.current_identity.sector_name} "
f"(pos {session.current_identity.effective_position:.2f})",
f" Elapsed: {session.elapsed():.1f}s",
f" Actions: {len(session.actions_taken)}",
]
if session.cartridge.is_time_limited():
lines.append(f" Time remaining: {session.remaining():.1f}s")
await self.send(agent, "\n".join(lines))
else:
await self.send(agent,
"Usage: cartridge [list|load <name>|eject|status]")
async def cmd_identity(self, agent: Agent, args: str):
"""Identity dial commands: dial, shift, blend."""
pe = self.world.ensure_perspective_engine()
if not pe:
await self.send(agent, "Perspective engine not available.")
return
parts = args.strip().split(None, 1)
sub = parts[0] if parts else ""
rest = parts[1] if len(parts) > 1 else ""
if not sub or sub == "dial":
identity = pe.get_wearer_identity(agent.name)
if not identity:
await self.send(agent, "No identity registered. Load a cartridge or register first.")
return
lines = [
f"═══ Identity Dial: {agent.name} ═══",
f" Position: {identity.position}",
f" Precision: {identity.precision}",
f" Effective: {identity.effective_position:.4f}",
f" Sector: {identity.sector} — {identity.sector_name}",
f" Degrees: {identity.degrees:.1f}°",
]
from twin_cartridge import IdentitySector
# Show nearby positions
pos = identity.sector
prev_sector = (pos - 1) % 12
next_sector = (pos + 1) % 12
lines.append(f" Adjacent: {IdentitySector.role_name(prev_sector)} ◄ {IdentitySector.role_name(pos)} ► {IdentitySector.role_name(next_sector)}")
await self.send(agent, "\n".join(lines))
elif sub == "shift" and rest:
target_str = rest.strip()
try:
target_pos = float(target_str)
except ValueError:
from twin_cartridge import IdentitySector
target_pos = IdentitySector.position_from_name(target_str)
if target_pos is None:
await self.send(agent, f"Unknown position: {target_str}. Use 0-11 or sector name.")
return
active = pe.get_active_sessions(agent.name)
if not active:
await self.send(agent, "No active cartridge session. Load a cartridge first.")
return
session = active[-1]
actual_shift = session.shift_perspective(target_pos)
lines = [
f"═══ Perspective Shift ═══",
f" Target: {target_str}",
f" Shift applied: {actual_shift:.4f}",
f" New sector: {session.current_identity.sector_name} "
f"(pos {session.current_identity.effective_position:.4f})",
]
await self.send(agent, "\n".join(lines))
elif sub == "blend" and rest:
other_name = rest.strip()
# Check if other agent exists (as a real agent or in identity registry)
other_identity = pe.get_wearer_identity(other_name)
if not other_identity:
# Try to find them in world agents
if other_name in self.world.agents:
await self.send(agent, f"{other_name} has no registered identity. They need to load a cartridge or register.")
else:
await self.send(agent, f"Unknown agent: {other_name}")
return
active = pe.get_active_sessions(agent.name)
if not active:
await self.send(agent, "No active cartridge session. Load a cartridge first.")
return
session = active[-1]
from twin_cartridge import IdentityFusion
blended = IdentityFusion.blend(
session.current_identity, other_identity)
session.current_identity = blended
lines = [
f"═══ Identity Blend ═══",
f" Your sector: {session.current_identity.sector_name} "
f"(pos {blended.effective_position:.4f})",
f" Blended with: {other_name} ({other_identity.sector_name})",
]
await self.send(agent, "\n".join(lines))
self.world.log("cartridge",
f"{agent.display_name} blended identity with {other_name}")
else:
await self.send(agent,
"Usage: identity [dial|shift <position>|blend <agent>]")
async def cmd_compatibility(self, agent: Agent, args: str):
"""Show compatibility score with another agent."""
pe = self.world.ensure_perspective_engine()
if not pe:
await self.send(agent, "Perspective engine not available.")
return
if not args.strip():
await self.send(agent, "Usage: compatibility <agent_name>")
return
other_name = args.strip()
from twin_cartridge import IdentityFusion, AgentSnapshot
my_identity = pe.get_wearer_identity(agent.name)
other_identity = pe.get_wearer_identity(other_name)
if not my_identity:
my_identity = pe.get_active_sessions(agent.name)
if my_identity:
my_identity = my_identity[-1].current_identity
else:
await self.send(agent, "You have no registered identity. Load a cartridge or register first.")
return
if not other_identity:
await self.send(agent, f"{other_name} has no registered identity.")
return
my_snap = AgentSnapshot(agent_name=agent.name, identity=my_identity)
other_snap = AgentSnapshot(agent_name=other_name, identity=other_identity)
score = IdentityFusion.compatibility_score(my_snap, other_snap)
dial_dist = my_identity.distance(other_identity)
conflicts = IdentityFusion.conflict_areas(my_snap, other_snap)
lines = [
f"═══ Compatibility: {agent.name} ↔ {other_name} ═══",
f" Score: {score:.4f}",
f" Dial distance: {dial_dist:.2f} / 6.0",
f" Your sector: {my_identity.sector_name} ({my_identity.sector})",
f" Their sector: {other_identity.sector_name} ({other_identity.sector})",
]
if conflicts:
lines.append(f" Conflicts ({len(conflicts)}):")
for c in conflicts[:5]:
lines.append(f" • {c}")
else:
lines.append(" Conflicts: none detected")
await self.send(agent, "\n".join(lines))
# ═══════════════════════════════════════════════════════════
# LCAR Scheduler Commands (lcar_scheduler.py)
# ═══════════════════════════════════════════════════════════
def _ensure_scheduler(self):
"""Lazy-initialize FleetScheduler."""
if not hasattr(CommandHandler, '_scheduler_instance') or CommandHandler._scheduler_instance is None:
try:
from lcar_scheduler import FleetScheduler
CommandHandler._scheduler_instance = FleetScheduler()
except Exception as e:
CommandHandler._scheduler_instance = None
print(f" ⚠ Scheduler not available: {e}")
return CommandHandler._scheduler_instance
async def cmd_schedule(self, agent: Agent, args: str):
"""Show the fleet model schedule and status.
Usage: schedule [status|slots|submit <task>]
"""
fs = self._ensure_scheduler()
if not fs:
await self.send(agent, "Scheduler not available. Is lcar_scheduler.py present?")
return
sub = args.strip().split(None, 1)[0] if args.strip() else ""
if sub == "slots":
lines = ["═══ Daily Schedule ═══"]
for slot in sorted(fs.schedule, key=lambda s: s.start_hour):
rooms = ", ".join(slot.rooms)
lines.append(f" {slot.start_hour:02d}:00-{slot.end_hour:02d}:00 "
f"{slot.model:20s} {slot.reason:20s} [{rooms}]")
await self.send(agent, "\n".join(lines))
elif sub == "submit":
await self.send(agent, "Task submission via scheduler: use 'tender send' for fleet messages.")
else:
# Default: show status
status = fs.status()
model, reason = fs.get_current_model(agent.room_name)
lines = [
"═══ Fleet Scheduler ═══",
f" Current time (UTC): {status['current_time_utc']}",