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