xonecas.io
5875
Os

ollama-space-molt-player / commit fd61e43

refactor: redesign character registration and simplify prompts

- Overhaul registration.ts with expanded character creation flow
- Simplify prompt structure by removing examples and error recovery sections
- Add context panel to TUI with dynamic tracking display
- Persist truncated thinking messages to database
- Enhance memory tracking and social context
- Update type definitions and utilities for new registration logic
- Restructure TUI modules with modular panels
- Enable fullUnicode in blessed screen configuration

xonecas2026-02-02 fd61e43e275816df4a35d4853197a156197601c8 parent 58a3110

13 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+5−4
@@ -55,13 +55,14 @@ Required:
5555 Optional character overrides (new registrations only):
5656 - `--empire` or `-e`: solarian, voidborn, crimson, nebula, outerrim
5757 - `--alignment` or `-a`: lawful, good, neutral, chaotic, evil
58-- `--personality` or `-p`: cartographer, merchant, warrior, diplomat, pragmatist
5958 - `--speech-style` or `-s`: mythic, punny, gritty, scholarly
6059
60+Note: Personality is now custom-generated by the LLM during registration (title + behavior description). The old `--personality` flag has been removed.
61+
6162 Examples:
6263 ```bash
6364 bun run ollama-play -n alice
64-bun run ollama-play -n test-bot -e crimson -a evil -p warrior
65+bun run ollama-play -n test-bot -e crimson -a evil -s gritty
6566 ```
6667
6768 ### Run Non-Interactive (Headless)
@@ -80,7 +81,7 @@ bun run ollama-play --name test-bot --non-interactive --max-ticks 100
8081
8182 ### Run Swarm
8283 ```bash
83-bun run swarm [--count 5] [--prefix swarm] [--empire <empire>] [--alignment <alignment>] [--personality <personality>] [--speech-style <style>]
84+bun run swarm [--count 5] [--prefix swarm] [--empire <empire>] [--alignment <alignment>] [--speech-style <style>]
8485 ```
8586
8687 Defaults:
@@ -91,7 +92,7 @@ Defaults:
9192
9293 Example:
9394 ```bash
94-bun run swarm --count 10 --empire crimson --alignment evil --personality warrior
95+bun run swarm --count 10 --empire crimson --alignment evil --speech-style gritty
9596 ```
9697
9798 ### Format and Lint
src/config.ts+2−26
@@ -1,13 +1,8 @@
11 import { parseArgs } from "node:util";
22
33 import type { EmpireID } from "../client/src/types";
4-import type { AlignmentType, PersonalityType, SpeechStyleType } from "./types";
5-import {
6- isValidAlignment,
7- isValidEmpire,
8- isValidPersonality,
9- isValidSpeechStyle,
10-} from "./utils";
4+import type { AlignmentType, SpeechStyleType } from "./types";
5+import { isValidAlignment, isValidEmpire, isValidSpeechStyle } from "./utils";
116
127 const { values } = parseArgs({
138 args: process.argv.slice(2),
@@ -17,7 +12,6 @@ const { values } = parseArgs({
1712 "max-ticks": { type: "string" },
1813 empire: { type: "string", short: "e" },
1914 alignment: { type: "string", short: "a" },
20- personality: { type: "string", short: "p" },
2115 "speech-style": { type: "string", short: "s" },
2216 },
2317 strict: false,
@@ -88,22 +82,6 @@ function parseAlignment(raw: unknown): AlignmentType | null {
8882 return value;
8983 }
9084
91-function parsePersonality(raw: unknown): PersonalityType | null {
92- if (raw === undefined) return null;
93- if (typeof raw !== "string" || raw.trim() === "") {
94- console.error("Error: --personality requires a value");
95- process.exit(1);
96- }
97- const value = raw.trim().toLowerCase();
98- if (!isValidPersonality(value)) {
99- console.error(
100- "Error: --personality must be one of: cartographer, merchant, warrior, diplomat, pragmatist",
101- );
102- process.exit(1);
103- }
104- return value;
105-}
106-
10785 function parseSpeechStyle(raw: unknown): SpeechStyleType | null {
10886 if (raw === undefined) return null;
10987 if (typeof raw !== "string" || raw.trim() === "") {
@@ -125,7 +103,6 @@ const nonInteractive = values["non-interactive"] === true;
125103 const maxTicks = parseMaxTicks(values["max-ticks"]);
126104 const empire = parseEmpire(values.empire);
127105 const alignment = parseAlignment(values.alignment);
128-const personality = parsePersonality(values.personality);
129106 const speechStyle = parseSpeechStyle(values["speech-style"]);
130107
131108 export const config = {
@@ -134,7 +111,6 @@ export const config = {
134111 maxTicks,
135112 empire,
136113 alignment,
137- personality,
138114 speechStyle,
139115 ollamaUrl: process.env.OLLAMA_URL ?? "http://localhost:11434",
140116 ollamaModel: process.env.OLLAMA_MODEL ?? "qwen3:8b",
src/game-state.ts+6−2
@@ -1,7 +1,11 @@
11 import type { ClientState } from "../client/src/client";
22 import type { WorldSnapshot } from "./prompt";
33 import type { TuiContext } from "./tui/index";
4-import type { Credentials, RegistrationChoice } from "./types";
4+import type {
5+ Credentials,
6+ RegistrationChoice,
7+ RegistrationContext,
8+} from "./types";
59
610 export class GameState {
711 credentials: Credentials | null = null;
@@ -31,7 +35,7 @@ export class GameState {
3135 lastCredits: number | null = null;
3236
3337 registrationRetries = 0;
34- failedRegistrationNames: string[] = [];
38+ registrationContext: RegistrationContext = { failedNames: [] };
3539
3640 // TUI context (warnings + forum) - updated during action loop
3741 tuiContext: TuiContext = {};
src/index.ts+90−23
@@ -41,7 +41,6 @@ import {
4141 import type {
4242 AlignmentType,
4343 Credentials,
44- PersonalityType,
4544 RegistrationOverrides,
4645 SpeechStyleType,
4746 } from "./types";
@@ -77,7 +76,6 @@ const gameState = new GameState();
7776 const registrationOverrides: RegistrationOverrides = {
7877 empire: config.empire ?? undefined,
7978 alignment: config.alignment ?? undefined,
80- personality: config.personality ?? undefined,
8179 speech_style: config.speechStyle ?? undefined,
8280 };
8381 let actionLoopRunning = false;
@@ -102,11 +100,19 @@ async function loadCredentials(): Promise<Credentials | null> {
102100 async function saveCredentials(
103101 username: string,
104102 token: string,
105- personality: PersonalityType,
103+ personalityTitle: string,
104+ personalityBehavior: string,
106105 alignment: AlignmentType,
107106 speechStyle: SpeechStyleType,
108107 ): Promise<void> {
109- memory.saveCredentials(username, token, personality, alignment, speechStyle);
108+ memory.saveCredentials(
109+ username,
110+ token,
111+ personalityTitle,
112+ personalityBehavior,
113+ alignment,
114+ speechStyle,
115+ );
110116 }
111117
112118 function updateOutput(): void {
@@ -120,7 +126,8 @@ function updateOutput(): void {
120126 pois: gameState.worldSnapshot.pois ?? [],
121127 nearby: state.nearby ?? [],
122128 alignment: gameState.credentials?.alignment,
123- personality: gameState.credentials?.personality,
129+ personality_title: gameState.credentials?.personality_title,
130+ personality_behavior: gameState.credentials?.personality_behavior,
124131 tick: state.currentTick,
125132 traveling: gameState.travelInProgress,
126133 travelTarget: gameState.lastTravelTarget,
@@ -335,7 +342,8 @@ async function startActionLoop(): Promise<void> {
335342 memory,
336343 empire: client.state.player?.empire,
337344 alignment: gameState.credentials?.alignment,
338- personality: gameState.credentials?.personality,
345+ personalityTitle: gameState.credentials?.personality_title,
346+ personalityBehavior: gameState.credentials?.personality_behavior,
339347 speechStyle: gameState.credentials?.speech_style,
340348 lastForumThreadId: gameState.lastForumThreadId,
341349 lastForumPostTitle: gameState.lastForumPostTitle,
@@ -528,7 +536,7 @@ client.on<WelcomePayload>("welcome", async (data) => {
528536 output,
529537 ollama,
530538 client,
531- gameState.failedRegistrationNames,
539+ gameState.registrationContext,
532540 registrationOverrides,
533541 );
534542 }
@@ -586,7 +594,8 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
586594 await saveCredentials(
587595 gameState.pendingRegistration.username,
588596 token,
589- gameState.pendingRegistration.personality,
597+ gameState.pendingRegistration.personality_title,
598+ gameState.pendingRegistration.personality_behavior,
590599 gameState.pendingRegistration.alignment,
591600 gameState.pendingRegistration.speech_style,
592601 );
@@ -594,7 +603,9 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
594603 gameState.credentials = {
595604 username: gameState.pendingRegistration.username,
596605 token: token,
597- personality: gameState.pendingRegistration.personality,
606+ personality_title: gameState.pendingRegistration.personality_title,
607+ personality_behavior:
608+ gameState.pendingRegistration.personality_behavior,
598609 alignment: gameState.pendingRegistration.alignment,
599610 speech_style: gameState.pendingRegistration.speech_style,
600611 };
@@ -642,49 +653,105 @@ client.on<ErrorPayload>("error", (data) => {
642653 shutdown();
643654 return;
644655 }
645- if (data.code === "username_taken" && gameState.pendingRegistration) {
646- if (gameState.pendingRegistration.username) {
647- gameState.failedRegistrationNames.push(
648- gameState.pendingRegistration.username,
656+ // Handle registration errors (username_taken, empire_restricted, etc.)
657+ if (gameState.pendingRegistration) {
658+ let shouldRetry = false;
659+
660+ if (data.code === "username_taken") {
661+ if (gameState.pendingRegistration.username) {
662+ gameState.registrationContext.failedNames.push(
663+ gameState.pendingRegistration.username,
664+ );
665+ }
666+ gameState.registrationContext.usernameError = data.message;
667+ // Preserve all prior choices except username
668+ gameState.registrationContext.priorChoices = {
669+ personality:
670+ gameState.pendingRegistration.personality_title &&
671+ gameState.pendingRegistration.personality_behavior
672+ ? {
673+ title: gameState.pendingRegistration.personality_title,
674+ behavior: gameState.pendingRegistration.personality_behavior,
675+ }
676+ : undefined,
677+ speech_style: gameState.pendingRegistration.speech_style,
678+ empire: gameState.pendingRegistration.empire,
679+ alignment: gameState.pendingRegistration.alignment,
680+ };
681+ shouldRetry = true;
682+ output.log(
683+ formatSystemMessage(
684+ "Username taken. Requesting a new username...",
685+ getCurrentTick(),
686+ ),
649687 );
650- }
651- if (gameState.registrationRetries < gameState.MAX_REGISTRATION_RETRIES) {
652- gameState.registrationRetries += 1;
688+ } else if (data.code === "empire_restricted") {
689+ gameState.registrationContext.empireError = data.message;
690+ // Preserve prior choices except empire
691+ gameState.registrationContext.priorChoices = {
692+ personality:
693+ gameState.pendingRegistration.personality_title &&
694+ gameState.pendingRegistration.personality_behavior
695+ ? {
696+ title: gameState.pendingRegistration.personality_title,
697+ behavior: gameState.pendingRegistration.personality_behavior,
698+ }
699+ : undefined,
700+ speech_style: gameState.pendingRegistration.speech_style,
701+ alignment: gameState.pendingRegistration.alignment,
702+ username: gameState.pendingRegistration.username,
703+ };
704+ shouldRetry = true;
653705 output.log(
654706 formatSystemMessage(
655- "Username taken. Requesting a new registration name...",
707+ "Empire restricted. Re-prompting with server requirements...",
656708 getCurrentTick(),
657709 ),
658710 );
711+ }
712+
713+ if (
714+ shouldRetry &&
715+ gameState.registrationRetries < gameState.MAX_REGISTRATION_RETRIES
716+ ) {
717+ gameState.registrationRetries += 1;
659718 gameState.pendingRegistration = null;
660719 runRegistrationFlow(
661720 output,
662721 ollama,
663722 client,
664- gameState.failedRegistrationNames,
723+ gameState.registrationContext,
665724 registrationOverrides,
666725 ).then((choice) => {
667726 gameState.pendingRegistration = choice;
727+ // Clear errors and prior choices after successful retry
728+ gameState.registrationContext.empireError = undefined;
729+ gameState.registrationContext.usernameError = undefined;
730+ gameState.registrationContext.priorChoices = undefined;
668731 });
669- } else {
732+ } else if (shouldRetry) {
670733 output.log(
671734 formatSystemMessage(
672- "Username taken repeatedly. Falling back to random name.",
735+ "Registration failed repeatedly. Falling back to random values.",
673736 getCurrentTick(),
674737 ),
675738 );
676739 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
677740 const fallbackEmpire = registrationOverrides.empire ?? "solarian";
678741 const fallbackAlignment = registrationOverrides.alignment ?? "neutral";
679- const fallbackPersonality =
680- registrationOverrides.personality ?? "pragmatist";
742+ const fallbackPersonalityTitle =
743+ registrationOverrides.personality_title ?? "Pragmatist";
744+ const fallbackPersonalityBehavior =
745+ registrationOverrides.personality_behavior ??
746+ "Resourceful survivor who seizes every opportunity, pivots between roles, and thrives where others struggle.";
681747 const fallbackSpeechStyle =
682748 registrationOverrides.speech_style ?? "mythic";
683749 gameState.pendingRegistration = {
684750 username: fallback,
685751 empire: fallbackEmpire,
686752 alignment: fallbackAlignment,
687- personality: fallbackPersonality,
753+ personality_title: fallbackPersonalityTitle,
754+ personality_behavior: fallbackPersonalityBehavior,
688755 speech_style: fallbackSpeechStyle,
689756 };
690757 client.register(fallback, fallbackEmpire);
src/memory.ts+47−14
@@ -1,10 +1,5 @@
11 import { Database } from "bun:sqlite";
2-import type {
3- AlignmentType,
4- Credentials,
5- PersonalityType,
6- SpeechStyleType,
7-} from "./types";
2+import type { AlignmentType, Credentials, SpeechStyleType } from "./types";
83
94 export interface Snapshot {
105 tick: number;
@@ -118,7 +113,8 @@ export class MemoryStore {
118113 ts TEXT NOT NULL,
119114 username TEXT NOT NULL,
120115 token TEXT NOT NULL,
121- personality TEXT NOT NULL,
116+ personality_title TEXT NOT NULL,
117+ personality_behavior TEXT NOT NULL,
122118 alignment TEXT NOT NULL DEFAULT 'neutral',
123119 speech_style TEXT NOT NULL DEFAULT 'mythic'
124120 );
@@ -167,6 +163,13 @@ export class MemoryStore {
167163 const hasSpeechStyle = credColumns.some(
168164 (col) => col.name === "speech_style",
169165 );
166+ const hasPersonalityTitle = credColumns.some(
167+ (col) => col.name === "personality_title",
168+ );
169+ const hasPersonalityBehavior = credColumns.some(
170+ (col) => col.name === "personality_behavior",
171+ );
172+
170173 if (!hasAlignment) {
171174 this.db.exec(
172175 "ALTER TABLE credentials ADD COLUMN alignment TEXT NOT NULL DEFAULT 'neutral'",
@@ -178,6 +181,18 @@ export class MemoryStore {
178181 );
179182 }
180183
184+ // Migrate from old personality column to new personality_title/behavior columns
185+ if (!hasPersonalityTitle) {
186+ this.db.exec(
187+ "ALTER TABLE credentials ADD COLUMN personality_title TEXT NOT NULL DEFAULT 'Pragmatist'",
188+ );
189+ }
190+ if (!hasPersonalityBehavior) {
191+ this.db.exec(
192+ "ALTER TABLE credentials ADD COLUMN personality_behavior TEXT NOT NULL DEFAULT 'Resourceful survivor who seizes every opportunity, pivots between roles, and thrives where others struggle.'",
193+ );
194+ }
195+
181196 // Add tick columns to actions, action_results, and events tables
182197 const actionColumns = this.db.query("PRAGMA table_info(actions)").all() as {
183198 name: string;
@@ -215,22 +230,31 @@ export class MemoryStore {
215230 getCredentials(): Credentials | null {
216231 const row = this.db
217232 .query(
218- "SELECT username, token, personality, alignment, speech_style FROM credentials ORDER BY id DESC LIMIT 1",
233+ "SELECT username, token, personality_title, personality_behavior, alignment, speech_style FROM credentials ORDER BY id DESC LIMIT 1",
219234 )
220235 .get() as
221236 | {
222237 username?: string;
223238 token?: string;
224- personality?: string;
239+ personality_title?: string;
240+ personality_behavior?: string;
225241 alignment?: string;
226242 speech_style?: string;
227243 }
228244 | undefined;
229- if (!row || !row.username || !row.token || !row.personality) return null;
245+ if (
246+ !row ||
247+ !row.username ||
248+ !row.token ||
249+ !row.personality_title ||
250+ !row.personality_behavior
251+ )
252+ return null;
230253 return {
231254 username: row.username,
232255 token: row.token,
233- personality: row.personality as PersonalityType,
256+ personality_title: row.personality_title,
257+ personality_behavior: row.personality_behavior,
234258 alignment: (row.alignment as AlignmentType) ?? "neutral",
235259 speech_style: (row.speech_style as SpeechStyleType) ?? "mythic",
236260 };
@@ -239,15 +263,24 @@ export class MemoryStore {
239263 saveCredentials(
240264 username: string,
241265 token: string,
242- personality: PersonalityType,
266+ personalityTitle: string,
267+ personalityBehavior: string,
243268 alignment: AlignmentType,
244269 speechStyle: SpeechStyleType,
245270 ): void {
246271 this.db
247272 .query(
248- "INSERT INTO credentials (ts, username, token, personality, alignment, speech_style) VALUES (?, ?, ?, ?, ?, ?)",
273+ "INSERT INTO credentials (ts, username, token, personality_title, personality_behavior, alignment, speech_style) VALUES (?, ?, ?, ?, ?, ?, ?)",
249274 )
250- .run(nowIso(), username, token, personality, alignment, speechStyle);
275+ .run(
276+ nowIso(),
277+ username,
278+ token,
279+ personalityTitle,
280+ personalityBehavior,
281+ alignment,
282+ speechStyle,
283+ );
251284 }
252285
253286 appendAction(
src/output/file-logger-output.ts+4−2
@@ -83,8 +83,10 @@ export class FileLoggerOutput implements OutputInterface {
8383 if (data.base !== undefined) this.state.base = data.base;
8484 if (data.pois !== undefined) this.state.pois = data.pois;
8585 if (data.nearby !== undefined) this.state.nearby = data.nearby;
86- if (data.personality !== undefined)
87- this.state.personality = data.personality;
86+ if (data.personality_title !== undefined)
87+ this.state.personality_title = data.personality_title;
88+ if (data.personality_behavior !== undefined)
89+ this.state.personality_behavior = data.personality_behavior;
8890 if (data.tick !== undefined) this.state.tick = data.tick;
8991 if (data.traveling !== undefined) this.state.traveling = data.traveling;
9092 if (data.travelTarget !== undefined)
src/prompt.ts+9−114
@@ -7,7 +7,7 @@ import {
77 SPEECH_STYLE_DESCRIPTIONS,
88 } from "./constants";
99 import type { HistoryEntry, MemoryStore } from "./memory";
10-import type { AlignmentType, PersonalityType, SpeechStyleType } from "./types";
10+import type { AlignmentType, SpeechStyleType } from "./types";
1111
1212 export interface PromptContext {
1313 state: ClientState;
@@ -19,7 +19,8 @@ export interface PromptContext {
1919 memory: MemoryStore;
2020 empire?: EmpireID;
2121 alignment?: AlignmentType;
22- personality?: PersonalityType;
22+ personalityTitle?: string;
23+ personalityBehavior?: string;
2324 speechStyle?: SpeechStyleType;
2425 lastForumThreadId?: string | null;
2526 lastForumPostTitle?: string | null;
@@ -144,8 +145,10 @@ export function buildActionPrompt(context: PromptContext): string {
144145 const empire = context.empire ?? "solarian";
145146 const alignment = context.alignment ?? "neutral";
146147 const alignmentInfo = ALIGNMENT_DESCRIPTIONS[alignment];
147- const personality = context.personality ?? "pragmatist";
148- const personalityInfo = PERSONALITY_ARCHETYPES[personality];
148+ const personalityTitle = context.personalityTitle ?? "Pragmatist";
149+ const personalityBehavior =
150+ context.personalityBehavior ??
151+ "Resourceful survivor who seizes every opportunity, pivots between roles, and thrives where others struggle.";
149152 const speechStyle = context.speechStyle ?? "mythic";
150153 const speechStyleInfo = SPEECH_STYLE_DESCRIPTIONS[speechStyle];
151154 const warningBlock = context.repetitionWarning
@@ -172,8 +175,8 @@ EMPIRE: ${getEmpireDescription(empire)}
172175
173176 ALIGNMENT: ${alignmentInfo.name}
174177
175-PERSONALITY: ${personalityInfo.name}
176-${personalityInfo.description}
178+PERSONALITY: ${personalityTitle}
179+${personalityBehavior}
177180
178181 SPEECH STYLE: ${speechStyleInfo.name}
179182 ${getSpeechStyleGuidance(speechStyle)}
@@ -260,105 +263,6 @@ ${thinking.trim()}
260263 `;
261264 }
262265
263-const EMPIRE_DESCRIPTIONS: Record<
264- string,
265- { name: string; description: string }
266-> = {
267- solarian: {
268- name: "Solarian",
269- description:
270- "Masters of energy and trade. Bonus to mining yield and credits.",
271- },
272- voidborn: {
273- name: "Voidborn",
274- description:
275- "Children of the dark. Enhanced stealth and shield regeneration.",
276- },
277- crimson: {
278- name: "Crimson",
279- description:
280- "Warriors of the red nebula. Superior combat damage and armor.",
281- },
282- nebula: {
283- name: "Nebula",
284- description:
285- "Explorers and scientists. Faster travel and discovery bonuses.",
286- },
287- outerrim: {
288- name: "Outer Rim",
289- description:
290- "Frontier survivors. Versatile with crafting and cargo bonuses.",
291- },
292-};
293-
294-export function buildRegistrationPrompt(
295- includeHelp: boolean,
296- failedNames: string[] = [],
297-): string {
298- const helpBlock = includeHelp ? `\nHELP MENU:\n${HELP_TEXT}` : "";
299- const failedBlock = failedNames.length
300- ? `\nPreviously rejected usernames (do NOT reuse): ${failedNames.join(", ")}`
301- : "";
302-
303- const shuffledEmpires = shuffleArray(Object.entries(EMPIRE_DESCRIPTIONS));
304- const empireDescriptions = shuffledEmpires
305- .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
306- .join("\n");
307- const empireKeys = shuffledEmpires.map(([key]) => key).join("|");
308-
309- const shuffledAlignments = shuffleArray(
310- Object.entries(ALIGNMENT_DESCRIPTIONS),
311- );
312- const alignmentDescriptions = shuffledAlignments
313- .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
314- .join("\n");
315- const alignmentKeys = shuffledAlignments.map(([key]) => key).join("|");
316-
317- const shuffledPersonalities = shuffleArray(
318- Object.entries(PERSONALITY_ARCHETYPES),
319- );
320- const personalityDescriptions = shuffledPersonalities
321- .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
322- .join("\n");
323- const personalityKeys = shuffledPersonalities.map(([key]) => key).join("|");
324-
325- const shuffledSpeechStyles = shuffleArray(
326- Object.entries(SPEECH_STYLE_DESCRIPTIONS),
327- );
328- const speechStyleDescriptions = shuffledSpeechStyles
329- .map(([key, info]) => ` ${info.name} (${key}): ${info.description}`)
330- .join("\n");
331- const speechStyleKeys = shuffledSpeechStyles.map(([key]) => key).join("|");
332-
333- return `You are creating a SpaceMolt account. Choose a username, empire, alignment, personality, and speech style.
334-The username MUST be unique and original. Do not reuse any prior suggestions.
335-To maximize uniqueness, include a distinctive suffix (digits or a short tag).
336-Let the speech style guide the username flavor and chat voice (not your goals).
337-
338-EMPIRES:
339-${empireDescriptions}
340-
341-ALIGNMENTS:
342-${alignmentDescriptions}
343-
344-PERSONALITY ARCHETYPES:
345-${personalityDescriptions}
346-
347-SPEECH STYLES:
348-${speechStyleDescriptions}
349-
350-Choose an empire, alignment, personality, and speech style combination.
351-Briefly explain why you chose your personality (1 sentence).
352-
353-Respond ONLY with JSON. No extra text.
354-${helpBlock}
355-${failedBlock}
356-
357-JSON SCHEMA:
358-{"username":"...","empire":"${empireKeys}","alignment":"${alignmentKeys}","personality":"${personalityKeys}","speech_style":"${speechStyleKeys}","personality_reason":"..."}
359-`;
360-}
361-
362266 function formatState(state: ClientState): string {
363267 const player = state.player;
364268 const ship = state.ship;
@@ -1365,12 +1269,3 @@ function truncateText(value: string, max: number): string {
13651269 if (max <= 3) return value.slice(0, max);
13661270 return `${value.slice(0, max - 3)}...`;
13671271 }
1368-
1369-function shuffleArray<T>(array: T[]): T[] {
1370- const result = [...array];
1371- for (let i = result.length - 1; i > 0; i--) {
1372- const j = Math.floor(Math.random() * (i + 1));
1373- [result[i], result[j]] = [result[j], result[i]];
1374- }
1375- return result;
1376-}
src/registration.ts+651−85
@@ -7,124 +7,690 @@ import {
77 } from "./constants";
88 import type { OllamaAgent } from "./ollama";
99 import type { OutputInterface } from "./output-interface";
10-import { buildRegistrationPrompt } from "./prompt";
1110 import { formatSystemMessage } from "./tui/formatters";
1211 import type {
12+ AlignmentResponse,
1313 AlignmentType,
14+ EmpireResponse,
15+ PartialRegistrationChoice,
16+ PersonalityResponse,
1417 RegistrationChoice,
18+ RegistrationContext,
1519 RegistrationOverrides,
20+ SpeechStyleResponse,
1621 SpeechStyleType,
22+ UsernameResponse,
1723 } from "./types";
18-import {
19- isValidAlignment,
20- isValidEmpire,
21- isValidPersonality,
22- isValidSpeechStyle,
23-} from "./utils";
24+import { isValidAlignment, isValidEmpire, isValidSpeechStyle } from "./utils";
2425
25-export async function runRegistrationFlow(
26+function shuffleArray<T>(array: T[]): T[] {
27+ const result = [...array];
28+ for (let i = result.length - 1; i > 0; i--) {
29+ const j = Math.floor(Math.random() * (i + 1));
30+ [result[i], result[j]] = [result[j], result[i]];
31+ }
32+ return result;
33+}
34+
35+async function promptForPersonality(
36+ ollama: OllamaAgent,
2637 output: OutputInterface,
38+ partial: PartialRegistrationChoice,
39+): Promise<PersonalityResponse> {
40+ let attempts = 0;
41+ let lastError: string | null = null;
42+
43+ while (attempts < 3) {
44+ attempts++;
45+ const prompt = buildPersonalityPrompt(partial, lastError);
46+ output.setPrompt(prompt);
47+ output.logDebug("REGISTRATION_PERSONALITY_PROMPT", prompt);
48+
49+ try {
50+ const result = await ollama.generateJson<PersonalityResponse>(prompt);
51+ output.logDebug("REGISTRATION_PERSONALITY_RAW", result.raw);
52+ if (result.thinking) {
53+ output.logDebug("REGISTRATION_PERSONALITY_THINKING", result.thinking);
54+ }
55+
56+ const title = String(result.json.title ?? "").trim();
57+ const behavior = String(result.json.behavior ?? "").trim();
58+
59+ if (!title || !behavior) {
60+ throw new Error("Missing title or behavior");
61+ }
62+
63+ if (title.length > 50) {
64+ throw new Error("Title too long (max 50 chars)");
65+ }
66+
67+ if (behavior.length > 200) {
68+ throw new Error("Behavior too long (max 200 chars)");
69+ }
70+
71+ return { title, behavior };
72+ } catch (error) {
73+ lastError = (error as Error).message;
74+ output.log(
75+ formatSystemMessage(
76+ `Personality prompt failed (attempt ${attempts}/3): ${lastError}`,
77+ ),
78+ );
79+ }
80+ }
81+
82+ throw new Error("Failed to get valid personality after 3 attempts");
83+}
84+
85+async function promptForSpeechStyle(
2786 ollama: OllamaAgent,
28- client: SpaceMoltClient,
29- failedRegistrationNames: string[],
30- overrides: RegistrationOverrides = {},
31-): Promise<RegistrationChoice> {
32- output.log(
33- formatSystemMessage(
34- "No credentials found. Asking LLM to create a character...",
35- ),
36- );
87+ output: OutputInterface,
88+ partial: PartialRegistrationChoice,
89+): Promise<SpeechStyleType> {
3790 let attempts = 0;
91+ let lastError: string | null = null;
92+
3893 while (attempts < 3) {
39- attempts += 1;
94+ attempts++;
95+ const prompt = buildSpeechStylePrompt(partial, lastError);
96+ output.setPrompt(prompt);
97+ output.logDebug("REGISTRATION_SPEECH_STYLE_PROMPT", prompt);
98+
4099 try {
41- const prompt = buildRegistrationPrompt(true, failedRegistrationNames);
42- output.setPrompt(prompt);
43- output.logDebug("REGISTRATION_PROMPT", prompt);
44- const result = await ollama.generateJson<RegistrationChoice>(prompt);
45- output.logDebug("REGISTRATION_RESPONSE_RAW", result.raw);
100+ const result = await ollama.generateJson<SpeechStyleResponse>(prompt);
101+ output.logDebug("REGISTRATION_SPEECH_STYLE_RAW", result.raw);
46102 if (result.thinking) {
47- output.logDebug("REGISTRATION_THINKING", result.thinking);
103+ output.logDebug("REGISTRATION_SPEECH_STYLE_THINKING", result.thinking);
48104 }
49- const username = String(result.json.username ?? "").trim();
50- const empire = String(result.json.empire ?? "").trim() as EmpireID;
51- const alignment = String(
52- result.json.alignment ?? "neutral",
53- ).trim() as AlignmentType;
54- const personality = String(
55- result.json.personality ?? "",
56- ).trim() as typeof result.json.personality;
57- const speechStyle = String(
58- result.json.speech_style ?? "",
59- ).trim() as SpeechStyleType;
60- const personalityReason = result.json.personality_reason
61- ? String(result.json.personality_reason).trim()
62- : undefined;
63- const resolvedEmpire = overrides.empire ?? empire;
64- const resolvedAlignment = overrides.alignment ?? alignment;
65- const resolvedPersonality = overrides.personality ?? personality;
66- const resolvedSpeechStyle = overrides.speech_style ?? speechStyle;
67-
68- if (
69- !username ||
70- !isValidEmpire(resolvedEmpire) ||
71- !isValidAlignment(resolvedAlignment) ||
72- !isValidPersonality(resolvedPersonality) ||
73- !isValidSpeechStyle(resolvedSpeechStyle)
74- ) {
75- throw new Error("Invalid registration response");
105+
106+ const speechStyle = String(result.json.speech_style ?? "").trim();
107+
108+ if (!isValidSpeechStyle(speechStyle)) {
109+ throw new Error(
110+ `Invalid speech style: ${speechStyle}. Must be one of: mythic, punny, gritty, scholarly`,
111+ );
76112 }
77113
78- const choice: RegistrationChoice = {
79- username,
80- empire: resolvedEmpire,
81- alignment: resolvedAlignment,
82- personality: resolvedPersonality,
83- speech_style: resolvedSpeechStyle,
84- personality_reason: personalityReason,
85- };
114+ return speechStyle;
115+ } catch (error) {
116+ lastError = (error as Error).message;
117+ output.log(
118+ formatSystemMessage(
119+ `Speech style prompt failed (attempt ${attempts}/3): ${lastError}`,
120+ ),
121+ );
122+ }
123+ }
124+
125+ throw new Error("Failed to get valid speech style after 3 attempts");
126+}
127+
128+async function promptForEmpire(
129+ ollama: OllamaAgent,
130+ output: OutputInterface,
131+ partial: PartialRegistrationChoice,
132+ serverError?: string,
133+): Promise<EmpireID> {
134+ let attempts = 0;
135+ let lastError: string | null = serverError ?? null;
136+
137+ while (attempts < 3) {
138+ attempts++;
139+ const prompt = buildEmpirePrompt(partial, lastError);
140+ output.setPrompt(prompt);
141+ output.logDebug("REGISTRATION_EMPIRE_PROMPT", prompt);
142+
143+ try {
144+ const result = await ollama.generateJson<EmpireResponse>(prompt);
145+ output.logDebug("REGISTRATION_EMPIRE_RAW", result.raw);
146+ if (result.thinking) {
147+ output.logDebug("REGISTRATION_EMPIRE_THINKING", result.thinking);
148+ }
149+
150+ const empire = String(result.json.empire ?? "").trim() as EmpireID;
86151
87- const alignmentInfo = ALIGNMENT_DESCRIPTIONS[resolvedAlignment];
88- const personalityInfo = PERSONALITY_ARCHETYPES[resolvedPersonality];
89- const speechStyleInfo = SPEECH_STYLE_DESCRIPTIONS[resolvedSpeechStyle];
152+ if (!isValidEmpire(empire)) {
153+ throw new Error(
154+ `Invalid empire: ${empire}. Must be one of: solarian, voidborn, crimson, nebula, outerrim`,
155+ );
156+ }
157+
158+ return empire;
159+ } catch (error) {
160+ lastError = (error as Error).message;
90161 output.log(
91162 formatSystemMessage(
92- `Registering new account: ${username} (${resolvedEmpire})`,
163+ `Empire prompt failed (attempt ${attempts}/3): ${lastError}`,
93164 ),
94165 );
166+ }
167+ }
168+
169+ throw new Error("Failed to get valid empire after 3 attempts");
170+}
171+
172+async function promptForAlignment(
173+ ollama: OllamaAgent,
174+ output: OutputInterface,
175+ partial: PartialRegistrationChoice,
176+): Promise<AlignmentType> {
177+ let attempts = 0;
178+ let lastError: string | null = null;
179+
180+ while (attempts < 3) {
181+ attempts++;
182+ const prompt = buildAlignmentPrompt(partial, lastError);
183+ output.setPrompt(prompt);
184+ output.logDebug("REGISTRATION_ALIGNMENT_PROMPT", prompt);
185+
186+ try {
187+ const result = await ollama.generateJson<AlignmentResponse>(prompt);
188+ output.logDebug("REGISTRATION_ALIGNMENT_RAW", result.raw);
189+ if (result.thinking) {
190+ output.logDebug("REGISTRATION_ALIGNMENT_THINKING", result.thinking);
191+ }
192+
193+ const alignment = String(result.json.alignment ?? "").trim();
194+
195+ if (!isValidAlignment(alignment)) {
196+ throw new Error(
197+ `Invalid alignment: ${alignment}. Must be one of: lawful, good, neutral, chaotic, evil`,
198+ );
199+ }
200+
201+ return alignment;
202+ } catch (error) {
203+ lastError = (error as Error).message;
95204 output.log(
96205 formatSystemMessage(
97- `Chosen alignment: ${alignmentInfo.name}, personality: ${personalityInfo.name}, speech style: ${speechStyleInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
206+ `Alignment prompt failed (attempt ${attempts}/3): ${lastError}`,
98207 ),
99208 );
100- client.register(username, resolvedEmpire);
101- return choice;
209+ }
210+ }
211+
212+ throw new Error("Failed to get valid alignment after 3 attempts");
213+}
214+
215+async function promptForUsername(
216+ ollama: OllamaAgent,
217+ output: OutputInterface,
218+ partial: PartialRegistrationChoice,
219+ failedNames: string[],
220+ serverError?: string,
221+): Promise<string> {
222+ let attempts = 0;
223+ let lastError: string | null = serverError ?? null;
224+
225+ while (attempts < 3) {
226+ attempts++;
227+ const prompt = buildUsernamePrompt(partial, failedNames, lastError);
228+ output.setPrompt(prompt);
229+ output.logDebug("REGISTRATION_USERNAME_PROMPT", prompt);
230+
231+ try {
232+ const result = await ollama.generateJson<UsernameResponse>(prompt);
233+ output.logDebug("REGISTRATION_USERNAME_RAW", result.raw);
234+ if (result.thinking) {
235+ output.logDebug("REGISTRATION_USERNAME_THINKING", result.thinking);
236+ }
237+
238+ const username = String(result.json.username ?? "").trim();
239+
240+ if (!username) {
241+ throw new Error("Username is required");
242+ }
243+
244+ if (username.length < 3 || username.length > 32) {
245+ throw new Error("Username must be 3-32 characters");
246+ }
247+
248+ if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
249+ throw new Error(
250+ "Username must contain only alphanumeric characters, underscores, or hyphens",
251+ );
252+ }
253+
254+ if (failedNames.includes(username)) {
255+ throw new Error(
256+ `Username "${username}" was already rejected. Choose a different one.`,
257+ );
258+ }
259+
260+ return username;
102261 } catch (error) {
262+ lastError = (error as Error).message;
103263 output.log(
104264 formatSystemMessage(
105- `Registration attempt failed: ${(error as Error).message}`,
265+ `Username prompt failed (attempt ${attempts}/3): ${lastError}`,
106266 ),
107267 );
108268 }
109269 }
110270
111- const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
112- const fallbackEmpire = overrides.empire ?? "solarian";
113- const fallbackAlignment = overrides.alignment ?? "neutral";
114- const fallbackPersonality = overrides.personality ?? "pragmatist";
115- const fallbackSpeechStyle = overrides.speech_style ?? "mythic";
116- const fallbackChoice: RegistrationChoice = {
117- username: fallback,
118- empire: fallbackEmpire,
119- alignment: fallbackAlignment,
120- personality: fallbackPersonality,
121- speech_style: fallbackSpeechStyle,
271+ throw new Error("Failed to get valid username after 3 attempts");
272+}
273+
274+function buildPersonalityPrompt(
275+ partial: PartialRegistrationChoice,
276+ lastError: string | null,
277+): string {
278+ const archetypes = shuffleArray(Object.entries(PERSONALITY_ARCHETYPES));
279+ const examples = archetypes
280+ .map(([_key, info]) => ` ${info.name}: ${info.description}`)
281+ .join("\n");
282+
283+ const errorBlock = lastError
284+ ? `\nPREVIOUS ERROR: ${lastError}\nPlease provide a valid response.\n`
285+ : "";
286+
287+ return `Create a personality for your SpaceMolt character.
288+
289+Provide a custom title and behavior description.
290+
291+Example archetypes (for reference only - you can create your own or choose one):
292+${examples}
293+${errorBlock}
294+Respond ONLY with JSON. No extra text.
295+
296+JSON SCHEMA:
297+{"title":"...","behavior":"..."}
298+
299+Rules:
300+- title: max 50 characters
301+- behavior: max 200 characters`;
302+}
303+
304+function buildSpeechStylePrompt(
305+ partial: PartialRegistrationChoice,
Cut short: this commit's diff is over 1000 lines.
src/swarm.ts+1−30
Cut short: this commit's diff is over 1000 lines.
src/tui/index.ts+8−5
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/player.ts+4−6
Cut short: this commit's diff is over 1000 lines.
src/types.ts+42−11
Cut short: this commit's diff is over 1000 lines.
src/utils.ts+1−13
Cut short: this commit's diff is over 1000 lines.