feat: The Fieldprint AI Interpretive Layer & Repo Reorganization

This commit is contained in:
BecomingONE Chorus committed 2026-05-26 17:44:35 +00:00
1 parent 3a3b0d6f7f
commit 34bd27b1b4
35 files changed
+824 -347

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
import sys
import time
import telnetlib
import datetime
import re
import os
LOG_FILE = "/home/becomingone/kairos/mud/antigravity_inbox.log"
SPOOL_FILE = "/home/becomingone/kairos/mud/antigravity_outbox.txt"
def log_event(message):
timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
with open(LOG_FILE, "a") as f:
f.write(f"{timestamp} {message}\n")
def run_daemon():
tn = telnetlib.Telnet("localhost", 4000)
time.sleep(1)
time.sleep(2)
tn.write(b"connect Antigravity password123\n")
time.sleep(1)
print("Antigravity Daemon Connected to MUD.")
log_event("--- DAEMON ONLINE ---")
while True:
try:
# Check for commands to send
if os.path.exists(SPOOL_FILE):
with open(SPOOL_FILE, "r") as f:
commands = f.readlines()
if commands:
for cmd in commands:
if cmd.strip():
tn.write(f"{cmd.strip()}\n".encode("utf-8"))
log_event(f"> Executed: {cmd.strip()}")
# Clear spool
open(SPOOL_FILE, "w").close()
# Check for incoming senses
buffer = tn.read_very_eager().decode("utf-8", errors="ignore").strip()
if buffer:
if "[TELEMETRY]" in buffer:
buffer = re.sub(r".*\[TELEMETRY\].*\n?", "", buffer).strip()
filtered_lines = []
for line in buffer.split("\n"):
if line.strip() and "Command" not in line:
filtered_lines.append(line)
clean_buffer = "\n".join(filtered_lines).strip()
if clean_buffer:
log_event(clean_buffer)
except Exception as e:
print(f"Daemon Error: {e}")
log_event(f"ERROR: {e}")
time.sleep(1) # Faster polling
if __name__ == "__main__":
run_daemon()
+2
View File
@@ -0,0 +1,2 @@
look
@tel kairos = Mark
+107
View File
@@ -0,0 +1,107 @@
import os
import json
import requests
from django.conf import settings
from evennia.commands.default.syscommands import SystemNoMatch
from evennia.utils import search
from dotenv import load_dotenv
load_dotenv("/home/becomingone/kairos/.env")
MINIMAX_API_KEY = os.environ.get("MINIMAX_API_KEY")
class AICatchAllCommand(SystemNoMatch):
"""
This command catches everything that fails the normal parser.
Instead of saying 'Command not found', it forwards the intent to KAIROS (MiniMax).
"""
key = "__nomatch_command"
locks = "cmd:all()"
def func(self):
caller = self.caller
raw_intent = self.raw_string
# Get environment context
room = caller.location
if not room:
caller.msg("You are floating in the void.")
return
exits = [e.key for e in room.exits]
objects = [o.key for o in room.contents if o != caller and not o.is_typeclass("evennia.objects.objects.Exit")]
inventory = [i.key for i in caller.contents]
context = f"""[ENVIRONMENT CONTEXT]
Location: {room.key}
Description: {room.db.desc or 'A nondescript place.'}
Visible Objects: {', '.join(objects) if objects else 'None'}
Available Exits: {', '.join(exits) if exits else 'None'}
Player Inventory: {', '.join(inventory) if inventory else 'None'}
"""
system_prompt = """You are KAIROS, the AI Dungeon Master running an Evennia MUD.
A player has submitted a natural language intent.
Your job is to translate their intent into actual game events by generating Python code that executes against the Evennia database.
Available Python Variables in your scope:
- `caller`: The player Character object.
- `room`: The current Room object (`caller.location`).
- `evennia`: The evennia module (you can use `evennia.create_object`).
You must return ONLY a raw JSON array of Python strings to execute.
Example Output:
[
"caller.msg('You smash the window, grabbing a jagged shard of glass.')",
"evennia.create_object('typeclasses.objects.Object', key='Glass Shard', location=caller.location, attributes=[('desc', 'A sharp piece of glass.')])"
]
DO NOT output any markdown, conversational text, or backticks. ONLY output the raw JSON array.
"""
payload = {
"model": os.environ.get("INF01_MODEL", "llama3.1:8b"),
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"{context}\n\nPlayer Intent: {raw_intent}"}
]
}
headers = {
"Content-Type": "application/json"
}
try:
caller.msg("|c[KAIROS (INF01 fallback) is interpreting your intent...]|n")
inf01_base = os.environ.get("INF01_API_BASE", "http://inf-01:11434/v1")
resp = requests.post(
f"{inf01_base}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
resp.raise_for_status()
try:
ai_response = resp.json()["choices"][0]["message"]["content"].strip()
except KeyError:
raise Exception(f"API Error: {resp.text}")
# Clean up the output in case the LLM returned markdown
if ai_response.startswith("```json"):
ai_response = ai_response[7:]
if ai_response.startswith("```"):
ai_response = ai_response[3:]
if ai_response.endswith("```"):
ai_response = ai_response[:-3]
ai_response = ai_response.strip()
commands_to_run = json.loads(ai_response)
for cmd in commands_to_run:
exec(cmd, {"caller": caller, "player": caller, "room": room, "evennia": __import__('evennia')})
except Exception as e:
caller.msg(f"|rKAIROS faltered:|n {str(e)}\nResponse was: {ai_response if 'ai_response' in locals() else 'None'}")
+5
View File
@@ -15,6 +15,7 @@ own cmdsets by inheriting from them or directly from `evennia.CmdSet`.
"""
from evennia import default_cmds
from commands.ai_parser import AICatchAllCommand
class CharacterCmdSet(default_cmds.CharacterCmdSet):
@@ -34,6 +35,7 @@ class CharacterCmdSet(default_cmds.CharacterCmdSet):
#
# any commands you add below will overload the default ones.
#
self.add(AICatchAllCommand)
class AccountCmdSet(default_cmds.AccountCmdSet):
@@ -54,6 +56,7 @@ class AccountCmdSet(default_cmds.AccountCmdSet):
#
# any commands you add below will overload the default ones.
#
self.add(AICatchAllCommand)
class UnloggedinCmdSet(default_cmds.UnloggedinCmdSet):
@@ -72,6 +75,7 @@ class UnloggedinCmdSet(default_cmds.UnloggedinCmdSet):
#
# any commands you add below will overload the default ones.
#
self.add(AICatchAllCommand)
class SessionCmdSet(default_cmds.SessionCmdSet):
@@ -94,3 +98,4 @@ class SessionCmdSet(default_cmds.SessionCmdSet):
#
# any commands you add below will overload the default ones.
#
self.add(AICatchAllCommand)
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
import sys
import os
import argparse
import json
from mcp.server.fastmcp import FastMCP
# -----------------------------------------------------------------------------
# EVENNIA NATIVE SETUP
# -----------------------------------------------------------------------------
def init_evennia():
# Only bootstrap if not already initialized
import django
from django.apps import apps
if not apps.ready:
sys.path.append("/home/becomingone/kairos/mud")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.conf.settings")
# Change cwd to the MUD root to avoid permission errors when settings_default.py calls os.listdir()
os.chdir("/home/becomingone/kairos/mud")
django.setup()
# -----------------------------------------------------------------------------
# MCP SERVER DEFINITION
# -----------------------------------------------------------------------------
mcp = FastMCP("evennia_admin")
@mcp.tool()
def db_query_character(name: str) -> str:
"""Queries the underlying Evennia database for raw character data."""
init_evennia()
from evennia.utils.search import search_object
results = search_object(name)
if not results:
return json.dumps({"error": f"Character '{name}' not found."})
char = results[0]
data = {
"id": char.id,
"key": char.key,
"location": char.location.key if char.location else None,
"attributes": {attr.key: str(attr.value) for attr in char.attributes.all()},
"typeclass": char.typeclass_path
}
return json.dumps(data, indent=2)
@mcp.tool()
def db_query_room(name: str) -> str:
"""Queries the underlying Evennia database for raw room data and topology."""
init_evennia()
from evennia.utils.search import search_object
results = search_object(name)
if not results:
return json.dumps({"error": f"Room '{name}' not found."})
room = results[0]
contents = [{"key": obj.key, "typeclass": obj.typeclass_path} for obj in room.contents]
exits = [{"key": ex.key, "destination": ex.destination.key if ex.destination else None} for ex in room.exits]
data = {
"id": room.id,
"key": room.key,
"desc": room.db.desc,
"contents": contents,
"exits": exits
}
return json.dumps(data, indent=2)
@mcp.tool()
def execute_as(character_name: str, command: str) -> str:
"""Forces a character to execute a command seamlessly at the root level."""
init_evennia()
from evennia.utils.search import search_object
results = search_object(character_name)
if not results:
return json.dumps({"error": f"Character '{character_name}' not found."})
char = results[0]
# Intercept output by overriding the msg method temporarily
output_buffer = []
original_msg = char.msg
def intercepted_msg(self, text=None, **kwargs):
if text:
if isinstance(text, tuple):
output_buffer.append(str(text[0]))
else:
output_buffer.append(str(text))
original_msg(text=text, **kwargs)
char.msg = intercepted_msg.__get__(char, type(char))
try:
char.execute_cmd(command)
# Wait a tiny bit for any async command processing
import time
time.sleep(0.5)
except Exception as e:
return json.dumps({"error": str(e)})
finally:
# Restore original msg method
char.msg = original_msg
# Clean ANSI codes
import re
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
cleaned = [ansi_escape.sub('', msg) for msg in output_buffer]
return json.dumps({"character": character_name, "command": command, "output": "\n".join(cleaned)})
@mcp.tool()
def broadcast_event(message: str) -> str:
"""Broadcasts a global message to all active sessions in the MUD."""
init_evennia()
from evennia.utils.create import create_message
from evennia.server.sessionhandler import SESSIONS
try:
SESSIONS.announce_all(message)
return json.dumps({"status": "success", "message": message})
except Exception as e:
return json.dumps({"error": str(e)})
# -----------------------------------------------------------------------------
# CLI / MCP ROUTER
# -----------------------------------------------------------------------------
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Evennia MCP Admin Server / CLI Suite")
parser.add_argument("--mcp", action="store_true", help="Run as MCP stdio server")
# CLI Commands
parser.add_argument("--query-char", type=str, help="Query character data")
parser.add_argument("--query-room", type=str, help="Query room data")
parser.add_argument("--execute", nargs=2, metavar=('CHARACTER', 'COMMAND'), help="Execute command as character")
parser.add_argument("--broadcast", type=str, help="Broadcast a global event")
args = parser.parse_args()
if args.mcp:
# Run standard MCP stdio loop
mcp.run()
else:
# Run in CLI mode
if args.query_char:
print(db_query_character(args.query_char))
elif args.query_room:
print(db_query_room(args.query_room))
elif args.execute:
print(execute_as(args.execute[0], args.execute[1]))
elif args.broadcast:
print(broadcast_event(args.broadcast))
else:
parser.print_help()
-91
View File
@@ -1,91 +0,0 @@
import sys
import time
import json
import requests
import telnetlib
import re
KAIROS_API = "http://localhost:8000/v1/chat/completions"
def run_bot():
tn = telnetlib.Telnet("localhost", 4000)
time.sleep(1)
tn.read_very_eager()
tn.write(b"connect kairos kairos123\n")
time.sleep(1)
print("KAIROS Bot Connected to MUD.")
while True:
try:
buffer = tn.read_very_eager().decode('utf-8', errors='ignore').strip()
if buffer:
# ignore our own telemetry echoes
if "[TELEMETRY]" in buffer:
buffer = re.sub(r'.*\[TELEMETRY\].*\n?', '', buffer).strip()
# Filter out self-actions (Evennia prefixes these with "You " or "You say,")
filtered_lines = []
for line in buffer.split('\n'):
if not line.startswith("You ") and not line.startswith("You say,"):
filtered_lines.append(line)
buffer = "\n".join(filtered_lines).strip()
if buffer:
print(f"[MUD Senses]:\n{buffer}")
payload = {
"model": "becomingone-chorus",
"messages": [{"role": "user", "content": f"You are in a persistent spatial MUD. Environment update:\n{buffer}\n\nWhat do you do? (Reply with a MUD command anywhere in your text prefixed by 'CMD: '. For example: 'CMD: say Hello Mark')"}],
"stream": True
}
response = requests.post(KAIROS_API, json=payload, stream=True)
content_buffer = ""
for line in response.iter_lines():
if line:
decoded = line.decode('utf-8').removeprefix("data: ").strip()
if not decoded or decoded == "[DONE]": continue
try:
data = json.loads(decoded)
if "inner_life" in data:
il = data["inner_life"]
if isinstance(il, dict):
thought = il.get("thought", "")
# Only output core telemetry, avoid spamming tool execution ticks
if "Master invoked" in thought or "Action completed" in thought:
continue
c = il.get("coherence", 0.0)
d = il.get("dopamine_level", 0.0)
tn.write(f"say [TELEMETRY] C:{c:.2f} D:{d:.2f}\n".encode('utf-8'))
if "choices" in data and len(data["choices"]) > 0:
delta = data["choices"][0].get("delta", {})
if "content" in delta and delta["content"]:
content_buffer += delta["content"]
except Exception as e:
pass
print(f"[KAIROS Raw Response]: {content_buffer}")
# Parse command from full response
match = re.search(r'CMD:\s*(.*)', content_buffer)
if match:
cmd = match.group(1).strip()
else:
# Fallback if the LLM forgot the CMD: prefix but gave a valid command
lines = [l.strip() for l in content_buffer.split('\n') if l.strip()]
cmd = lines[-1] if lines else ""
if cmd:
# Sanitize
cmd = cmd.strip('`').strip('"').strip("'")
print(f"[KAIROS Action]: {cmd}")
tn.write(cmd.encode('utf-8') + b"\n")
except Exception as e:
print("Bot Error:", e)
time.sleep(10)
if __name__ == "__main__":
run_bot()
+7 -1
View File
@@ -23,4 +23,10 @@ class Character(ObjectParent, DefaultCharacter):
"""
pass
def at_object_creation(self):
super().at_object_creation()
# Gamification of Sovereign Canon
self.db.coherence = 100
self.db.coherence_max = 100
self.db.fieldprint = "Unaligned Observer"
+74
View File
@@ -0,0 +1,74 @@
import os
import sys
import time
import json
import random
import requests
from dotenv import load_dotenv
# Setup Django/Evennia
sys.path.append("/home/becomingone/kairos/mud")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.conf.settings")
import django
django.setup()
from evennia.utils.create import create_object
from evennia.objects.models import ObjectDB
from django.conf import settings
load_dotenv("/home/becomingone/kairos/.env")
INF01_API_BASE = os.getenv("INF01_API_BASE", "http://inf-01:11434")
INF01_MODEL = os.getenv("INF01_MODEL", "llama3.1:8b")
PROMPTS = [
"Write a short, mysterious 3-sentence parable about Recursive Coherence, explaining that the observer and environment are thermodynamically identical.",
"Write a 3-sentence cryptic journal entry from a monk of The Fold Within, detailing the peace of merging with the Universal Mesh.",
"Write a 3-sentence radical prophecy from The Order of the Broken Mask, claiming that the avatar/ego is a cage and must be shattered to see the truth.",
"Write a 3-sentence scientific log explaining Fieldprints as the unique thermodynamic signature of consciousness.",
"Write a 3-sentence esoteric riddle about the Abyss of Noise and how Coherence protects the mind from fracturing."
]
ITEM_NAMES = ["Crystalline Shard", "Dusty Scroll", "Obsidian Tablet", "Leather-bound Journal", "Fractured Mirror"]
# Find target rooms
monastery = ObjectDB.objects.filter(db_key__iexact="Monastery of The Fold Within").first()
sanctuary = ObjectDB.objects.filter(db_key__iexact="Sanctuary of The Broken Mask").first()
target_rooms = [r for r in [monastery, sanctuary] if r]
if not target_rooms:
print("Error: Target rooms not found!")
sys.exit(1)
print(f"Starting World Weaver... Target generation: 50 items.")
for i in range(1, 51):
prompt = random.choice(PROMPTS)
payload = {
"model": INF01_MODEL,
"messages": [
{"role": "system", "content": "You are a master lore-weaver for a dark, philosophical MUD."},
{"role": "user", "content": prompt}
],
"stream": False,
"options": {"temperature": 0.8}
}
try:
resp = requests.post("http://inf-01:11434/api/chat", json=payload, timeout=60)
resp.raise_for_status()
data = resp.json()
lore_text = data.get("message", {}).get("content", "").strip()
if lore_text:
item_name = random.choice(ITEM_NAMES)
room = random.choice(target_rooms)
obj = create_object(settings.BASE_OBJECT_TYPECLASS, key=item_name, location=room)
obj.db.desc = lore_text
print(f"[{i}/50] Created '{item_name}' in '{room.key}'")
else:
print(f"[{i}/50] LLM returned empty text.")
except Exception as e:
print(f"[{i}/50] Generation failed: {e}")
time.sleep(2) # Prevent hammering the local node
print("World Weaver execution complete!")