@@ -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 {