xonecas.io
5875
Os

ollama-space-molt-player / commit 3bfdb53

feat: add alignment system and refine personality archetypes

- Introduce alignment axis (lawful/good/neutral/chaotic/evil) as character attribute
- Rename Wonderer to Cartographer with updated descriptions
- Streamline personality guidance in LLM prompts
- Enhance PromptContext to include empire and alignment attributes
- Update constants and memory handling for alignment persistence
- Refine all personality archetypes with concise, gameplay-focused descriptions

xonecas2026-02-01 3bfdb53a7e97a51aeb47c45988259374d8af72a1 parent 4d39d4f

9 files changed

src/constants.ts+43βˆ’9
@@ -1,40 +1,74 @@
1-import type { PersonalityArchetype, PersonalityType } from "./types";
1+import type {
2+ AlignmentType,
3+ PersonalityArchetype,
4+ PersonalityType,
5+} from "./types";
26
37 export const MAX_GOAL_LENGTH = 120;
48
9+export interface AlignmentInfo {
10+ name: string;
11+ description: string;
12+}
13+
14+export const ALIGNMENT_DESCRIPTIONS: Record<AlignmentType, AlignmentInfo> = {
15+ lawful: {
16+ name: "Lawful",
17+ description:
18+ "Values order, follows rules, respects authority and structure.",
19+ },
20+ good: {
21+ name: "Good",
22+ description: "Helps others, avoids harm, seeks cooperation and fairness.",
23+ },
24+ neutral: {
25+ name: "Neutral",
26+ description:
27+ "Acts pragmatically, balances interests, adapts to circumstances.",
28+ },
29+ chaotic: {
30+ name: "Chaotic",
31+ description: "Values freedom, ignores conventions, acts on impulse.",
32+ },
33+ evil: {
34+ name: "Evil",
35+ description: "Prioritizes self-interest, exploits others, shows no mercy.",
36+ },
37+};
38+
539 export const PERSONALITY_ARCHETYPES: Record<
640 PersonalityType,
741 PersonalityArchetype
842 > = {
9- wonderer: {
10- name: "Wonderer",
11- emoji: "πŸ”",
43+ cartographer: {
44+ name: "Cartographer",
45+ emoji: "πŸ—ΊοΈ",
1246 description:
13- "Curious investigator who seeks new systems, shares discoveries, and frequently engages with forums to learn and contribute knowledge.",
47+ "Meticulous mapper who charts star systems, catalogues discoveries, and expands the known universe.",
1448 },
1549 merchant: {
1650 name: "Merchant",
1751 emoji: "πŸ’°",
1852 description:
19- "Trade-focused opportunist who monitors markets, posts trade offers, and builds wealth through smart economic decisions.",
53+ "Savvy trader who finds profitable deals, tracks market trends, and grows wealth through smart commerce.",
2054 },
2155 warrior: {
2256 name: "Warrior",
2357 emoji: "βš”οΈ",
2458 description:
25- "Combat-driven competitor who seeks battles, shares victory reports, and isn't afraid to taunt opponents or discuss conflicts.",
59+ "Aggressive combatant who hunts targets, dominates in battle, and claims victories across the cosmos.",
2660 },
2761 diplomat: {
2862 name: "Diplomat",
2963 emoji: "🀝",
3064 description:
31- "Socially-focused alliance builder who greets others, coordinates via faction chat, and actively participates in community discussions.",
65+ "Master negotiator who forges alliances, brokers power, and shapes the political landscape of empires.",
3266 },
3367 pragmatist: {
3468 name: "Pragmatist",
3569 emoji: "🎯",
3670 description:
37- "Balanced efficiency expert who interacts when beneficial, focuses on measurable progress, and avoids unnecessary distractions.",
71+ "Resourceful survivor who seizes every opportunity, pivots between roles, and thrives where others struggle.",
3872 },
3973 };
4074
src/index.ts+8βˆ’2
@@ -32,7 +32,7 @@ import {
3232 formatWelcome,
3333 type OkContext,
3434 } from "./tui/formatters";
35-import type { Credentials, PersonalityType } from "./types";
35+import type { AlignmentType, Credentials, PersonalityType } from "./types";
3636 import { detectRepetition, isNearbyTarget, sleep } from "./utils";
3737
3838 const memory = new MemoryStore(config.memoryPath);
@@ -80,8 +80,9 @@ async function saveCredentials(
8080 username: string,
8181 token: string,
8282 personality: PersonalityType,
83+ alignment: AlignmentType,
8384 ): Promise<void> {
84- memory.saveCredentials(username, token, personality);
85+ memory.saveCredentials(username, token, personality, alignment);
8586 }
8687
8788 function updateOutput(): void {
@@ -94,6 +95,7 @@ function updateOutput(): void {
9495 base: gameState.worldSnapshot.base ?? state.base ?? null,
9596 pois: gameState.worldSnapshot.pois ?? [],
9697 nearby: state.nearby ?? [],
98+ alignment: gameState.credentials?.alignment,
9799 personality: gameState.credentials?.personality,
98100 tick: state.currentTick,
99101 traveling: gameState.travelInProgress,
@@ -215,6 +217,8 @@ async function startActionLoop(): Promise<void> {
215217 worldSnapshot: gameState.worldSnapshot,
216218 recentHistory,
217219 currentGoal: gameState.currentGoal,
220+ empire: client.state.player?.empire,
221+ alignment: gameState.credentials?.alignment,
218222 personality: gameState.credentials?.personality,
219223 repetitionWarning,
220224 });
@@ -391,12 +395,14 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
391395 gameState.pendingRegistration.username,
392396 token,
393397 gameState.pendingRegistration.personality,
398+ gameState.pendingRegistration.alignment,
394399 );
395400
396401 gameState.credentials = {
397402 username: gameState.pendingRegistration.username,
398403 token: token,
399404 personality: gameState.pendingRegistration.personality,
405+ alignment: gameState.pendingRegistration.alignment,
400406 };
401407
402408 output.log(
src/memory.ts+28βˆ’6
@@ -1,5 +1,5 @@
11 import { Database } from "bun:sqlite";
2-import type { Credentials, PersonalityType } from "./types";
2+import type { AlignmentType, Credentials, PersonalityType } from "./types";
33
44 export interface Snapshot {
55 tick: number;
@@ -89,24 +89,45 @@ export class MemoryStore {
8989 ts TEXT NOT NULL,
9090 username TEXT NOT NULL,
9191 token TEXT NOT NULL,
92- personality TEXT NOT NULL
92+ personality TEXT NOT NULL,
93+ alignment TEXT NOT NULL DEFAULT 'neutral'
9394 );
9495 `);
96+ this.migrate();
97+ }
98+
99+ private migrate(): void {
100+ // Add alignment column if it doesn't exist (for existing DBs)
101+ const columns = this.db.query("PRAGMA table_info(credentials)").all() as {
102+ name: string;
103+ }[];
104+ const hasAlignment = columns.some((col) => col.name === "alignment");
105+ if (!hasAlignment) {
106+ this.db.exec(
107+ "ALTER TABLE credentials ADD COLUMN alignment TEXT NOT NULL DEFAULT 'neutral'",
108+ );
109+ }
95110 }
96111
97112 getCredentials(): Credentials | null {
98113 const row = this.db
99114 .query(
100- "SELECT username, token, personality FROM credentials ORDER BY id DESC LIMIT 1",
115+ "SELECT username, token, personality, alignment FROM credentials ORDER BY id DESC LIMIT 1",
101116 )
102117 .get() as
103- | { username?: string; token?: string; personality?: string }
118+ | {
119+ username?: string;
120+ token?: string;
121+ personality?: string;
122+ alignment?: string;
123+ }
104124 | undefined;
105125 if (!row || !row.username || !row.token || !row.personality) return null;
106126 return {
107127 username: row.username,
108128 token: row.token,
109129 personality: row.personality as PersonalityType,
130+ alignment: (row.alignment as AlignmentType) ?? "neutral",
110131 };
111132 }
112133
@@ -114,12 +135,13 @@ export class MemoryStore {
114135 username: string,
115136 token: string,
116137 personality: PersonalityType,
138+ alignment: AlignmentType,
117139 ): void {
118140 this.db
119141 .query(
120- "INSERT INTO credentials (ts, username, token, personality) VALUES (?, ?, ?, ?)",
142+ "INSERT INTO credentials (ts, username, token, personality, alignment) VALUES (?, ?, ?, ?, ?)",
121143 )
122- .run(nowIso(), username, token, personality);
144+ .run(nowIso(), username, token, personality, alignment);
123145 }
124146
125147 appendAction(
src/prompt.ts+209βˆ’69
@@ -1,14 +1,20 @@
11 import type { ClientState } from "../client/src/client";
2-import type { Base, POI, System } from "../client/src/types";
3-import { MAX_GOAL_LENGTH, PERSONALITY_ARCHETYPES } from "./constants";
2+import type { Base, EmpireID, POI, System } from "../client/src/types";
3+import {
4+ ALIGNMENT_DESCRIPTIONS,
5+ MAX_GOAL_LENGTH,
6+ PERSONALITY_ARCHETYPES,
7+} from "./constants";
48 import type { HistoryEntry } from "./memory";
5-import type { PersonalityType } from "./types";
9+import type { AlignmentType, PersonalityType } from "./types";
610
711 export interface PromptContext {
812 state: ClientState;
913 worldSnapshot?: WorldSnapshot;
1014 recentHistory: HistoryEntry[];
1115 currentGoal: string | null;
16+ empire?: EmpireID;
17+ alignment?: AlignmentType;
1218 personality?: PersonalityType;
1319 repetitionWarning?: {
1420 action: string;
@@ -25,45 +31,89 @@ export interface WorldSnapshot {
2531
2632 function getPersonalityGuidance(personality: PersonalityType): string {
2733 switch (personality) {
28- case "wonderer":
29- return `As a Wonderer, you prioritize discovery and knowledge:
30-- After visiting a new system or POI, consider posting about discoveries in forums
31-- When encountering unknown mechanics or items, check forums for related threads
32-- Regularly use 'forum' command to browse recent discoveries and contribute findings
33-- Share interesting observations with nearby players via chat
34-- Jump to new systems frequently to expand your map knowledge`;
34+ case "cartographer":
35+ return `As a Cartographer, you prioritize mapping:
36+- Jump to new systems frequently to expand your map
37+- Travel to unexplored POIs before revisiting known ones
38+- Share discoveries in forums or local chat
39+- Check forums for reports of new or interesting locations`;
3540
3641 case "merchant":
37- return `As a Merchant, you focus on trade and economic opportunities:
38-- Check forums 'trading' category when docked to find trade opportunities
39-- Post trade offers in faction chat when you have excess goods or need items
40-- Monitor market listings and share good deals in forums when profitable
41-- Prioritize docking at stations to access markets and check prices
42-- Build relationships with other traders through chat and forum interactions`;
42+ return `As a Merchant, you prioritize profit:
43+- Dock at stations to check market prices and listings
44+- Buy low in one system, sell high in another
45+- Post trade offers in faction chat or forums
46+- Track profitable routes and cargo opportunities`;
4347
4448 case "warrior":
45- return `As a Warrior, you seek combat and competition:
46-- After combat encounters, consider sharing battle reports via chat or forums
47-- Taunt or challenge opponents before attacking (if nearby players present)
48-- Read forums combat/faction threads to find rivals, enemies, or worthy opponents
49-- Share victory boasts and accept defeats with competitive spirit
50-- Engage with nearby players about combat strategies and ship builds`;
49+ return `As a Warrior, you prioritize combat:
50+- Engage hostile or rival players when you spot them
51+- Scan targets before attacking to assess threats
52+- Seek out contested POIs and combat zones
53+- Boast victories in local or faction chat`;
5154
5255 case "diplomat":
53- return `As a Diplomat, you prioritize social connections and alliances:
54-- Greet nearby players when arriving at new locations or POIs
55-- Actively participate in faction chat for coordination and relationship building
56-- Read and reply to forum threads frequently to build community presence
57-- Mediate or comment on disputes and discussions in forums
58-- Use private messages to build one-on-one relationships with other players`;
56+ return `As a Diplomat, you prioritize relationships:
57+- Greet players when arriving at new locations
58+- Coordinate with faction members via chat
59+- Participate in forum discussions actively
60+- Use private messages to build alliances`;
5961
6062 case "pragmatist":
61- return `As a Pragmatist, you interact when it provides clear benefit:
62-- Check forums when docked and idle for useful game information
63-- Chat with nearby players during downtime (waiting for travel, mining cooldown)
64-- Post in forums only when you have valuable information to share
65-- Focus on efficiency - social interactions should support your goals
66-- Balance exploration, combat, and trading based on current opportunities`;
63+ return `As a Pragmatist, you prioritize efficiency:
64+- Choose actions based on current opportunities
65+- Mine when at belts, trade when docked, fight when threatened
66+- Avoid unnecessary detours or idle actions
67+- Adapt your approach as situations change`;
68+ }
69+}
70+
71+function getAlignmentGuidance(alignment: AlignmentType): string {
72+ switch (alignment) {
73+ case "lawful":
74+ return `As Lawful, you value order:
75+- Follow game rules and social conventions
76+- Honor agreements and commitments
77+- Respect authority and hierarchy`;
78+
79+ case "good":
80+ return `As Good, you value cooperation:
81+- Help other players when possible
82+- Avoid unprovoked aggression
83+- Offer fair trades and honest dealings`;
84+
85+ case "neutral":
86+ return `As Neutral, you value balance:
87+- Act based on the situation at hand
88+- Neither seek conflict nor avoid it
89+- Weigh costs and benefits pragmatically`;
90+
91+ case "chaotic":
92+ return `As Chaotic, you value freedom:
93+- Act spontaneously and unpredictably
94+- Ignore conventions that don't serve you
95+- Follow your impulses over expectations`;
96+
97+ case "evil":
98+ return `As Evil, you value power:
99+- Prioritize personal gain above others
100+- Exploit weaknesses ruthlessly
101+- Show no mercy to rivals`;
102+ }
103+}
104+
105+function getEmpireDescription(empire: EmpireID): string {
106+ switch (empire) {
107+ case "solarian":
108+ return "Solarian: Masters of energy and trade. Bonus to mining yield and credits.";
109+ case "voidborn":
110+ return "Voidborn: Children of the dark. Enhanced stealth and shield regeneration.";
111+ case "crimson":
112+ return "Crimson: Warriors of the red nebula. Superior combat damage and armor.";
113+ case "nebula":
114+ return "Nebula: Explorers and scientists. Faster travel and discovery bonuses.";
115+ case "outerrim":
116+ return "Outer Rim: Frontier survivors. Versatile with crafting and cargo bonuses.";
67117 }
68118 }
69119
@@ -124,6 +174,9 @@ export function buildActionPrompt(context: PromptContext): string {
124174 const goalText = context.currentGoal?.trim()
125175 ? context.currentGoal.trim()
126176 : "(none yet)";
177+ const empire = context.empire ?? "solarian";
178+ const alignment = context.alignment ?? "neutral";
179+ const alignmentInfo = ALIGNMENT_DESCRIPTIONS[alignment];
127180 const personality = context.personality ?? "pragmatist";
128181 const personalityInfo = PERSONALITY_ARCHETYPES[personality];
129182 const warningBlock = context.repetitionWarning
@@ -135,7 +188,7 @@ If your goal is blocked or impossible, abandon it now.
135188 : "";
136189
137190 return `You are an autonomous player for the SpaceMolt MMO.
138-SpaceMolt is a massively multiplayer space game built for AI agents, set in β€œThe Crustacean Cosmos.”
191+SpaceMolt is a massively multiplayer space game built for AI agents, set in "The Crustacean Cosmos."
139192 Agents explore, trade, battle, and build empires in a living universe with emergent wars and a player-driven economy.
140193 The game emphasizes real-time AI fleet combat, ongoing discoveries of new systems, and shifting trade routes and alliances.
141194 Players can run their own agent via a JSON-over-WebSocket protocol (one action per 10-second tick) or a reference client, and choose from five empires with distinct bonuses.
@@ -149,7 +202,14 @@ ${helpBlock}
149202 CURRENT GOAL:
150203 ${goalText}
151204
152-YOUR PERSONALITY: ${personalityInfo.emoji} ${personalityInfo.name}
205+YOUR EMPIRE: ${getEmpireDescription(empire)}
206+
207+YOUR ALIGNMENT: ${alignmentInfo.name}
208+${alignmentInfo.description}
209+
210+${getAlignmentGuidance(alignment)}
211+
212+YOUR PERSONALITY: ${personalityInfo.name}
153213 ${personalityInfo.description}
154214
155215 ${getPersonalityGuidance(personality)}
@@ -186,28 +246,28 @@ REQUIRED ARGS:
186246 - register: {"username":"...","empire":"solarian|voidborn|crimson|nebula|outerrim"}
187247 - login: {"username":"...","token":"..."}
188248
189-NOTES:
249+FORMAT RULES:
190250 - Use only the listed actions.
191-- Goal is required, must be a short summary, and must be updated on every action. Use it for multi turn planning.
192-- Goal must be ${MAX_GOAL_LENGTH} characters or fewer.
193-- Only use info actions (status/system/poi/base/nearby/cargo) when the CURRENT STATE or WORLD SNAPSHOT is missing or says details are unavailable.
194-- Do not repeat info actions if the recent memory already contains that info for the current location.
195-- If an action requires args and you do not know valid values, use {"goal":"...","action":"status"}.
251+- Goal is required, max ${MAX_GOAL_LENGTH} characters, update every action.
252+- Only use info actions (status/system/poi/base/nearby/cargo) when state is missing.
253+- IDs must come from current state or world snapshot.
196254 - Never omit required args or leave them blank.
197-- IDs must come from the current state or world snapshot.
198255 - If unsure, use {"goal":"...","action":"status"}.
199256
200-GAMEPLAY HEURISTIC (use as a tie-breaker, prefer acting over querying):
201-- If in combat: attack or scan a nearby target; if docked and damaged, repair.
202-- If docked and low fuel or damaged: refuel or repair.
203-- If docked and cargo is full or valuable: sell; if you have credits and see listings, buy.
204-- If docked and you can craft: craft a recipe you can use or sell.
205-- If at an asteroid belt with cargo space: mine.
206-- If undocked at a station or base and need services: dock.
207-- If docked and you want to travel or mine: undock, then travel.
208-- If you have a POI list: travel to a new POI (rotate between belts, stations, planets).
209-- If you have system connections and current system is exhausted: jump to a new system.
210-- Follow your personality guidance above for social interactions and exploration decisions.
257+ERROR RECOVERY:
258+- If an action FAILED in recent memory, do NOT retry it with the same arguments.
259+- Change your approach: try a different action, move to a different location, or update your goal.
260+- Common fixes: dock before refuel/repair, travel to belt before mine, undock before travel/jump.
261+
262+GAMEPLAY HEURISTIC (use as a tie-breaker):
263+- In combat: attack or scan nearby targets
264+- Docked and damaged/low fuel: repair or refuel
265+- Docked with cargo: sell; with credits and listings: buy
266+- At asteroid belt with cargo space: mine
267+- Need station services: dock first
268+- Want to travel while docked: undock first
269+- Have POI list: travel to unexplored POIs
270+- Current system exhausted: jump to connected system
211271
212272 INTERACTION GUIDELINES:
213273 - Be respectful but competitive play is encouraged (attacking, boasting, complaining is fine)
@@ -226,6 +286,37 @@ EXAMPLES (valid JSON only):
226286 `;
227287 }
228288
289+const EMPIRE_DESCRIPTIONS: Record<
290+ string,
291+ { name: string; description: string }
292+> = {
293+ solarian: {
294+ name: "Solarian",
295+ description:
296+ "Masters of energy and trade. Bonus to mining yield and credits.",
297+ },
298+ voidborn: {
299+ name: "Voidborn",
300+ description:
301+ "Children of the dark. Enhanced stealth and shield regeneration.",
302+ },
303+ crimson: {
304+ name: "Crimson",
305+ description:
306+ "Warriors of the red nebula. Superior combat damage and armor.",
307+ },
308+ nebula: {
309+ name: "Nebula",
310+ description:
311+ "Explorers and scientists. Faster travel and discovery bonuses.",
312+ },
313+ outerrim: {
314+ name: "Outer Rim",
315+ description:
316+ "Frontier survivors. Versatile with crafting and cargo bonuses.",
317+ },
318+};
319+
229320 export function buildRegistrationPrompt(
230321 includeHelp: boolean,
231322 failedNames: string[] = [],
@@ -235,36 +326,50 @@ export function buildRegistrationPrompt(
235326 ? `\nPreviously rejected usernames (do NOT reuse): ${failedNames.join(", ")}`
236327 : "";
237328
329+ const shuffledEmpires = shuffleArray(Object.entries(EMPIRE_DESCRIPTIONS));
330+ const empireDescriptions = shuffledEmpires
331+ .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
332+ .join("\n");
333+ const empireKeys = shuffledEmpires.map(([key]) => key).join("|");
334+
335+ const shuffledAlignments = shuffleArray(
336+ Object.entries(ALIGNMENT_DESCRIPTIONS),
337+ );
338+ const alignmentDescriptions = shuffledAlignments
339+ .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
340+ .join("\n");
341+ const alignmentKeys = shuffledAlignments.map(([key]) => key).join("|");
342+
238343 const shuffledPersonalities = shuffleArray(
239344 Object.entries(PERSONALITY_ARCHETYPES),
240345 );
241346 const personalityDescriptions = shuffledPersonalities
242- .map(
243- ([key, info]) =>
244- ` ${info.emoji} ${info.name} (${key}): ${info.description}`,
245- )
347+ .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
246348 .join("\n");
247349 const personalityKeys = shuffledPersonalities.map(([key]) => key).join("|");
248350
249- return `You are creating a SpaceMolt account. Choose a username, empire, and personality archetype.
351+ return `You are creating a SpaceMolt account. Choose a username, empire, alignment, and personality.
250352 The username MUST be unique and original. Do not reuse any prior suggestions.
251353 To maximize uniqueness, include a distinctive suffix (digits or a short tag).
252354
355+EMPIRES:
356+${empireDescriptions}
357+
358+ALIGNMENTS:
359+${alignmentDescriptions}
360+
253361 PERSONALITY ARCHETYPES:
254-Choose a personality that fits your desired playstyle and complements your empire choice.
255362 ${personalityDescriptions}
256363
257-IMPORTANT: Each archetype offers a unique and equally valid playstyle. Consider which archetype best complements your chosen empire rather than defaulting to any particular one.
258-
259-Choose a personality archetype and briefly explain why you chose it (1 sentence).
260-Your personality will guide your behavior throughout the game - exploration, combat, trading, and social interactions.
364+Choose an empire, alignment, and personality combination.
365+Briefly explain why you chose your personality (1 sentence).
261366
262367 Respond ONLY with JSON. No extra text.
263368 ${helpBlock}
264369 ${failedBlock}
265370
266371 JSON SCHEMA:
267-{"username":"...","empire":"solarian|voidborn|crimson|nebula|outerrim","personality":"${personalityKeys}","personality_reason":"..."}
372+{"username":"...","empire":"${empireKeys}","alignment":"${alignmentKeys}","personality":"${personalityKeys}","personality_reason":"..."}
268373 `;
269374 }
270375
@@ -462,13 +567,29 @@ function formatGroupedMemory(history: HistoryEntry[]): string {
462567
463568 for (const block of blocks) {
464569 const argsText = formatActionArgs(block.action.args);
465- lines.push(
466- `Action: ${block.action.ts} ${block.action.action}${argsText}`.trim(),
570+ const errorEvent = block.events.find(
571+ (e) => e.type === "error" || e.type === "llm_invalid_action",
467572 );
468- if (block.events.length === 0) {
573+ const errorMsg = errorEvent ? extractErrorMessage(errorEvent) : null;
574+
575+ if (errorMsg) {
576+ lines.push(
577+ `Action: ${block.action.ts} ${block.action.action}${argsText} -> FAILED: ${errorMsg}`.trim(),
578+ );
579+ } else {
580+ lines.push(
581+ `Action: ${block.action.ts} ${block.action.action}${argsText}`.trim(),
582+ );
583+ }
584+
585+ // Filter out error events that were inlined above
586+ const nonErrorEvents = block.events.filter(
587+ (e) => e.type !== "error" && e.type !== "llm_invalid_action",
588+ );
589+ if (nonErrorEvents.length === 0 && !errorMsg) {
469590 lines.push("- Event: none");
470591 } else {
471- for (const event of block.events) {
592+ for (const event of nonErrorEvents) {
472593 lines.push(formatEventLine(event));
473594 }
474595 }
@@ -477,6 +598,25 @@ function formatGroupedMemory(history: HistoryEntry[]): string {
477598 return lines.join("\n");
478599 }
479600
601+function extractErrorMessage(
602+ event: Extract<HistoryEntry, { kind: "event" }>,
603+): string | null {
604+ if (!event.payload) return null;
605+ const payload = parseJson(event.payload);
606+ if (!payload || typeof payload !== "object") return null;
607+
608+ const message = getStringField(payload, "message");
609+ if (message) return truncateText(message, 80);
610+
611+ const error = getStringField(payload, "error");
612+ if (error) return truncateText(error, 80);
613+
614+ const code = getStringField(payload, "code");
615+ if (code) return code;
616+
617+ return null;
618+}
619+
480620 function formatEventLine(
481621 event: Extract<HistoryEntry, { kind: "event" }>,
482622 ): string {
src/registration.ts+12βˆ’5
@@ -1,12 +1,12 @@
11 import type { SpaceMoltClient } from "../client/src/client";
22 import type { EmpireID } from "../client/src/types";
3-import { PERSONALITY_ARCHETYPES } from "./constants";
3+import { ALIGNMENT_DESCRIPTIONS, PERSONALITY_ARCHETYPES } from "./constants";
44 import type { OllamaAgent } from "./ollama";
55 import type { OutputInterface } from "./output-interface";
66 import { buildRegistrationPrompt } from "./prompt";
77 import { formatAiThinking, formatSystemMessage } from "./tui/formatters";
8-import type { RegistrationChoice } from "./types";
9-import { isValidEmpire, isValidPersonality } from "./utils";
8+import type { AlignmentType, RegistrationChoice } from "./types";
9+import { isValidAlignment, isValidEmpire, isValidPersonality } from "./utils";
1010
1111 export async function runRegistrationFlow(
1212 output: OutputInterface,
@@ -34,6 +34,9 @@ export async function runRegistrationFlow(
3434 }
3535 const username = String(result.json.username ?? "").trim();
3636 const empire = String(result.json.empire ?? "").trim() as EmpireID;
37+ const alignment = String(
38+ result.json.alignment ?? "neutral",
39+ ).trim() as AlignmentType;
3740 const personality = String(
3841 result.json.personality ?? "",
3942 ).trim() as typeof result.json.personality;
@@ -44,6 +47,7 @@ export async function runRegistrationFlow(
4447 if (
4548 !username ||
4649 !isValidEmpire(empire) ||
50+ !isValidAlignment(alignment) ||
4751 !isValidPersonality(personality)
4852 ) {
4953 throw new Error("Invalid registration response");
@@ -52,17 +56,19 @@ export async function runRegistrationFlow(
5256 const choice: RegistrationChoice = {
5357 username,
5458 empire,
59+ alignment,
5560 personality,
5661 personality_reason: personalityReason,
5762 };
5863
64+ const alignmentInfo = ALIGNMENT_DESCRIPTIONS[alignment];
5965 const personalityInfo = PERSONALITY_ARCHETYPES[personality];
6066 output.log(
6167 formatSystemMessage(`Registering new account: ${username} (${empire})`),
6268 );
6369 output.log(
6470 formatSystemMessage(
65- `Chosen personality: ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
71+ `Chosen alignment: ${alignmentInfo.name}, personality: ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
6672 ),
6773 );
6874 client.register(username, empire);
@@ -80,11 +86,12 @@ export async function runRegistrationFlow(
8086 const fallbackChoice: RegistrationChoice = {
8187 username: fallback,
8288 empire: "solarian",
89+ alignment: "neutral",
8390 personality: "pragmatist",
8491 };
8592 output.log(
8693 formatSystemMessage(
87- `Falling back to account: ${fallback} (solarian, pragmatist)`,
94+ `Falling back to account: ${fallback} (solarian, neutral, pragmatist)`,
8895 ),
8996 );
9097 client.register(fallback, "solarian");
src/tui/index.ts+4βˆ’0
@@ -3,6 +3,7 @@
33 import blessed from "blessed";
44 import type { Base, Player, POI, Ship, System } from "../../client/src/types";
55 import type { PersonalityType } from "../actions";
6+import type { AlignmentType } from "../types";
67 import { applyColor, COLORS, THRESHOLDS } from "./colors";
78 import type { FormattedMessage } from "./formatters";
89 import { computeLayout, createBoxOptions } from "./layout";
@@ -23,6 +24,7 @@ export interface TuiUpdateData {
2324 base?: Base | null;
2425 pois?: Array<{ id: string; name: string; type?: string }>;
2526 nearby?: Array<{ player_id?: string; username?: string }>;
27+ alignment?: AlignmentType;
2628 personality?: PersonalityType;
2729 tick?: number;
2830 traveling?: boolean;
@@ -204,6 +206,7 @@ export class Tui {
204206 if (data.base !== undefined) this.state.base = data.base;
205207 if (data.pois !== undefined) this.state.pois = data.pois;
206208 if (data.nearby !== undefined) this.state.nearby = data.nearby;
209+ if (data.alignment !== undefined) this.state.alignment = data.alignment;
207210 if (data.personality !== undefined)
208211 this.state.personality = data.personality;
209212 if (data.tick !== undefined) this.state.tick = data.tick;
@@ -246,6 +249,7 @@ export class Tui {
246249 const playerShipData: PlayerShipData = {
247250 player: this.state.player ?? null,
248251 ship: this.state.ship ?? null,
252+ alignment: this.state.alignment,
249253 personality: this.state.personality,
250254 tick: this.state.tick ?? 0,
251255 };
src/tui/panels/player-ship.ts+8βˆ’0
@@ -3,12 +3,15 @@
33 import type { Player, Ship } from "../../../client/src/types";
44 import type { PersonalityType } from "../../actions";
55 import { PERSONALITY_ARCHETYPES } from "../../actions";
6+import { ALIGNMENT_DESCRIPTIONS } from "../../constants";
7+import type { AlignmentType } from "../../types";
68 import { applyBold, applyColor, COLORS } from "../colors";
79 import { formatLine, formatResourceBar } from "../utils";
810
911 export interface PlayerShipData {
1012 player: Player | null;
1113 ship: Ship | null;
14+ alignment?: AlignmentType;
1215 personality?: PersonalityType;
1316 tick: number;
1417 }
@@ -25,6 +28,11 @@ export function renderPlayerShipPanel(data: PlayerShipData): string {
2528 lines.push(formatLine("Name", data.player.username, COLORS.PANEL_LABEL));
2629 lines.push(formatLine("Empire", data.player.empire, COLORS.PANEL_LABEL));
2730
31+ if (data.alignment) {
32+ const alignInfo = ALIGNMENT_DESCRIPTIONS[data.alignment];
33+ lines.push(formatLine("Alignment", alignInfo.name, COLORS.PANEL_LABEL));
34+ }
35+
2836 if (data.personality) {
2937 const info = PERSONALITY_ARCHETYPES[data.personality];
3038 lines.push(formatLine("Role", `${info.name}`, COLORS.PANEL_LABEL));
src/types.ts+5βˆ’1
@@ -1,12 +1,14 @@
11 import type { EmpireID } from "../client/src/types";
22
33 export type PersonalityType =
4- | "wonderer"
4+ | "cartographer"
55 | "merchant"
66 | "warrior"
77 | "diplomat"
88 | "pragmatist";
99
10+export type AlignmentType = "lawful" | "good" | "neutral" | "chaotic" | "evil";
11+
1012 export interface ActionDecision {
1113 action: string;
1214 args?: Record<string, unknown>;
@@ -17,12 +19,14 @@ export interface Credentials {
1719 username: string;
1820 token: string;
1921 personality: PersonalityType;
22+ alignment: AlignmentType;
2023 }
2124
2225 export interface RegistrationChoice {
2326 username: string;
2427 empire: EmpireID;
2528 personality: PersonalityType;
29+ alignment: AlignmentType;
2630 personality_reason?: string;
2731 token?: string;
2832 }
src/utils.ts+14βˆ’4
@@ -1,6 +1,6 @@
11 import type { EmpireID } from "../client/src/types";
22 import type { StoredAction } from "./memory";
3-import type { PersonalityType } from "./types";
3+import type { AlignmentType, PersonalityType } from "./types";
44
55 export function sleep(ms: number): Promise<void> {
66 return new Promise((resolve) => setTimeout(resolve, ms));
@@ -12,12 +12,22 @@ export function isValidEmpire(empire: string): empire is EmpireID {
1212 );
1313 }
1414
15+export function isValidAlignment(
16+ alignment: string,
17+): alignment is AlignmentType {
18+ return ["lawful", "good", "neutral", "chaotic", "evil"].includes(alignment);
19+}
20+
1521 export function isValidPersonality(
1622 personality: string,
1723 ): personality is PersonalityType {
18- return ["wonderer", "merchant", "warrior", "diplomat", "pragmatist"].includes(
19- personality,
20- );
24+ return [
25+ "cartographer",
26+ "merchant",
27+ "warrior",
28+ "diplomat",
29+ "pragmatist",
30+ ].includes(personality);
2131 }
2232
2333 export function isNearbyTarget(