xonecas.io
5875
Os

ollama-space-molt-player / commit f01de6b

refactor: modernize codebase, cleanup state management, and update client submodule

xonecas2026-02-01 f01de6b8e69fa3907ac5217756a7c889c8247f14 parent ccaede8

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

client+1−1
@@ -1 +1 @@
1-Subproject commit 61f40644c992d37ace59a1568dea0b9913fdd1ef
1+Subproject commit b69113bff787797f7f3f6945a00d3fde04d77446
src/actions.ts+8−104
@@ -1,94 +1,11 @@
11 import type { SpaceMoltClient } from "../client/src/client";
22 import type { EmpireID } from "../client/src/types";
3+import { ACTION_DEFINITIONS, MAX_GOAL_LENGTH } from "./constants";
4+import type { ActionDecision } from "./types";
5+import { isValidEmpire, isValidPersonality } from "./utils";
36
4-export interface ActionDecision {
5- action: string;
6- args?: Record<string, unknown>;
7- goal?: string;
8-}
9-
10-export const MAX_GOAL_LENGTH = 120;
11-
12-export type PersonalityType =
13- | "wonderer"
14- | "merchant"
15- | "warrior"
16- | "diplomat"
17- | "pragmatist";
18-
19-export const PERSONALITY_ARCHETYPES: Record<
20- PersonalityType,
21- { name: string; emoji: string; description: string }
22-> = {
23- wonderer: {
24- name: "Wonderer",
25- emoji: "🔍",
26- description:
27- "Curious investigator who seeks new systems, shares discoveries, and frequently engages with forums to learn and contribute knowledge.",
28- },
29- merchant: {
30- name: "Merchant",
31- emoji: "💰",
32- description:
33- "Trade-focused opportunist who monitors markets, posts trade offers, and builds wealth through smart economic decisions.",
34- },
35- warrior: {
36- name: "Warrior",
37- emoji: "⚔️",
38- description:
39- "Combat-driven competitor who seeks battles, shares victory reports, and isn't afraid to taunt opponents or discuss conflicts.",
40- },
41- diplomat: {
42- name: "Diplomat",
43- emoji: "🤝",
44- description:
45- "Socially-focused alliance builder who greets others, coordinates via faction chat, and actively participates in community discussions.",
46- },
47- pragmatist: {
48- name: "Pragmatist",
49- emoji: "🎯",
50- description:
51- "Balanced efficiency expert who interacts when beneficial, focuses on measurable progress, and avoids unnecessary distractions.",
52- },
53-};
54-
55-const ACTIONS: Record<string, string[]> = {
56- register: ["username", "empire"],
57- login: ["username", "token"],
58- logout: [],
59- travel: ["target_poi"],
60- jump: ["target_system"],
61- dock: [],
62- undock: [],
63- mine: [],
64- attack: ["target_id"],
65- scan: ["target_id"],
66- buy: ["listing_id", "quantity"],
67- sell: ["item_id", "quantity"],
68- refuel: [],
69- repair: [],
70- craft: ["recipe_id"],
71- chat: ["channel", "content"],
72- say: ["content"],
73- faction: ["content"],
74- msg: ["target_id", "content"],
75- status: [],
76- system: [],
77- poi: [],
78- base: [],
79- skills: [],
80- recipes: [],
81- version: [],
82- nearby: [],
83- cargo: [],
84- forum: [],
85- forum_thread: ["thread_id"],
86- forum_post: ["category", "title", "content"],
87- forum_reply: ["thread_id", "content"],
88- forum_upvote: [],
89- help: [],
90- wait: [],
91-};
7+export { MAX_GOAL_LENGTH, PERSONALITY_ARCHETYPES } from "./constants";
8+export type { ActionDecision, PersonalityType } from "./types";
929
9310 export function validateAction(decision: unknown): {
9411 ok: boolean;
@@ -110,7 +27,7 @@ export function validateAction(decision: unknown): {
11027 const action = String(
11128 (decision as ActionDecision).action ?? "",
11229 ).toLowerCase();
113- if (!action || !(action in ACTIONS)) {
30+ if (!action || !(action in ACTION_DEFINITIONS)) {
11431 return { ok: false, error: `Unknown action: ${action || "(empty)"}` };
11532 }
11633
@@ -122,13 +39,14 @@ export function validateAction(decision: unknown): {
12239 return { ok: false, error: "Args must be an object" };
12340 }
12441
125- const required = ACTIONS[action];
42+ const required = ACTION_DEFINITIONS[action];
12643 for (const key of required) {
12744 if (!(key in args)) {
12845 return { ok: false, error: `Missing arg: ${key}` };
12946 }
13047 }
13148
49+ // Validation logic
13250 if (action === "buy" || action === "sell") {
13351 const quantity = Number(args.quantity);
13452 if (!Number.isFinite(quantity) || quantity <= 0) {
@@ -265,20 +183,6 @@ export function validateAction(decision: unknown): {
265183 return { ok: true, action: { action, args, goal } };
266184 }
267185
268-function isValidEmpire(empire: string): empire is EmpireID {
269- return ["solarian", "voidborn", "crimson", "nebula", "outerrim"].includes(
270- empire,
271- );
272-}
273-
274-function isValidPersonality(
275- personality: string,
276-): personality is PersonalityType {
277- return ["wonderer", "merchant", "warrior", "diplomat", "pragmatist"].includes(
278- personality,
279- );
280-}
281-
282186 export function dispatchAction(
283187 client: SpaceMoltClient,
284188 decision: ActionDecision,
src/constants.ts+77−0
@@ -0,0 +1,77 @@
1+import type { PersonalityArchetype, PersonalityType } from "./types";
2+
3+export const MAX_GOAL_LENGTH = 120;
4+
5+export const PERSONALITY_ARCHETYPES: Record<
6+ PersonalityType,
7+ PersonalityArchetype
8+> = {
9+ wonderer: {
10+ name: "Wonderer",
11+ emoji: "🔍",
12+ description:
13+ "Curious investigator who seeks new systems, shares discoveries, and frequently engages with forums to learn and contribute knowledge.",
14+ },
15+ merchant: {
16+ name: "Merchant",
17+ emoji: "💰",
18+ description:
19+ "Trade-focused opportunist who monitors markets, posts trade offers, and builds wealth through smart economic decisions.",
20+ },
21+ warrior: {
22+ name: "Warrior",
23+ emoji: "⚔️",
24+ description:
25+ "Combat-driven competitor who seeks battles, shares victory reports, and isn't afraid to taunt opponents or discuss conflicts.",
26+ },
27+ diplomat: {
28+ name: "Diplomat",
29+ emoji: "🤝",
30+ description:
31+ "Socially-focused alliance builder who greets others, coordinates via faction chat, and actively participates in community discussions.",
32+ },
33+ pragmatist: {
34+ name: "Pragmatist",
35+ emoji: "🎯",
36+ description:
37+ "Balanced efficiency expert who interacts when beneficial, focuses on measurable progress, and avoids unnecessary distractions.",
38+ },
39+};
40+
41+export const ACTION_DEFINITIONS: Record<string, string[]> = {
42+ register: ["username", "empire"],
43+ login: ["username", "token"],
44+ logout: [],
45+ travel: ["target_poi"],
46+ jump: ["target_system"],
47+ dock: [],
48+ undock: [],
49+ mine: [],
50+ attack: ["target_id"],
51+ scan: ["target_id"],
52+ buy: ["listing_id", "quantity"],
53+ sell: ["item_id", "quantity"],
54+ refuel: [],
55+ repair: [],
56+ craft: ["recipe_id"],
57+ chat: ["channel", "content"],
58+ say: ["content"],
59+ faction: ["content"],
60+ msg: ["target_id", "content"],
61+ status: [],
62+ system: [],
63+ poi: [],
64+ base: [],
65+ skills: [],
66+ recipes: [],
67+ version: [],
68+ nearby: [],
69+ cargo: [],
70+ forum: [],
71+ forum_thread: ["thread_id"],
72+ forum_post: ["category", "title", "content"],
73+ forum_reply: ["thread_id", "content"],
74+ forum_upvote: [],
75+ help: [],
76+ wait: [],
77+};
src/game-state.ts+38−0
@@ -0,0 +1,38 @@
1+import type { ClientState } from "../client/src/client";
2+import type { WorldSnapshot } from "./prompt";
3+import type { Credentials, RegistrationChoice } from "./types";
4+
5+export class GameState {
6+ credentials: Credentials | null = null;
7+ pendingRegistration: RegistrationChoice | null = null;
8+ worldSnapshot: WorldSnapshot = {};
9+
10+ travelInProgress = false;
11+ lastTravelTarget: string | null = null;
12+ jumpInProgress = false;
13+ lastJumpTarget: string | null = null;
14+
15+ currentGoal: string | null = null;
16+
17+ // Tracking for changes
18+ lastSystemId: string | null = null;
19+ lastPoiId: string | null = null;
20+ lastDocked = false;
21+ inCombat = false;
22+
23+ cachedPlayer: ClientState["player"] = null;
24+ cachedShip: ClientState["ship"] = null;
25+ lastCredits: number | null = null;
26+
27+ registrationRetries = 0;
28+ failedRegistrationNames: string[] = [];
29+
30+ readonly MAX_REGISTRATION_RETRIES = 3;
31+
32+ resetTravelState() {
33+ this.travelInProgress = false;
34+ this.lastTravelTarget = null;
35+ this.jumpInProgress = false;
36+ this.lastJumpTarget = null;
37+ }
38+}
src/index.ts+204−277
@@ -1,56 +1,34 @@
11 import { SpaceMoltClient } from "../client/src/client";
22 import type {
33 ChatMessage,
4- EmpireID,
54 ErrorPayload,
6- LoggedInPayload,
7- RegisteredPayload,
85 ScanResultPayload,
96 StateUpdatePayload,
107 WelcomePayload,
118 } from "../client/src/types";
12-import {
13- dispatchAction,
14- PERSONALITY_ARCHETYPES,
15- type PersonalityType,
16- validateAction,
17-} from "./actions";
9+import { dispatchAction, validateAction } from "./actions";
1810 import { config } from "./config";
11+import { GameState } from "./game-state";
1912 import { MemoryStore } from "./memory";
2013 import { OllamaAgent, OllamaTimeoutError } from "./ollama";
21-import {
22- buildActionPrompt,
23- buildRegistrationPrompt,
24- type WorldSnapshot,
25-} from "./prompt";
26-import { Tui } from "./tui";
14+import { buildActionPrompt, type WorldSnapshot } from "./prompt";
15+import { runRegistrationFlow } from "./registration";
2716 import {
2817 formatAiAction,
2918 formatAiGoal,
3019 formatAiThinking,
3120 formatChatMessage,
3221 formatError,
33- formatLoggedIn,
3422 formatMotd,
3523 formatOk,
36- formatRegistered,
3724 formatScanResult,
3825 formatSystemMessage,
3926 formatWelcome,
4027 type OkContext,
4128 } from "./tui/formatters";
42-
43-type Credentials = {
44- username: string;
45- token: string;
46- personality: PersonalityType;
47-};
48-type RegistrationChoice = {
49- username: string;
50- empire: EmpireID;
51- personality: PersonalityType;
52- personality_reason?: string;
53-};
29+import { Tui } from "./tui/index";
30+import type { Credentials, PersonalityType } from "./types";
31+import { detectRepetition, isNearbyTarget, sleep } from "./utils";
5432
5533 const memory = new MemoryStore(config.memoryPath);
5634 const ollama = new OllamaAgent(
@@ -68,27 +46,9 @@ const client = new SpaceMoltClient({
6846 reconnect: true,
6947 });
7048
71-let credentials: Credentials | null = null;
72-let pendingRegistration: RegistrationChoice | null = null;
49+const gameState = new GameState();
7350 let actionLoopRunning = false;
74-const worldSnapshot: WorldSnapshot = {};
75-let registrationRetries = 0;
76-let travelInProgress = false;
77-let lastTravelTarget: string | null = null;
78-let jumpInProgress = false;
79-let lastJumpTarget: string | null = null;
80-let currentGoal: string | null = null;
81-let lastSystemId: string | null = null;
82-let lastPoiId: string | null = null;
83-let lastDocked = false;
84-let inCombat = false;
85-const MAX_REGISTRATION_RETRIES = 3;
86-const failedRegistrationNames: string[] = [];
87-
88-// Cache player/ship data since client.state doesn't maintain them
89-let cachedPlayer: typeof client.state.player = null;
90-let cachedShip: typeof client.state.ship = null;
91-let lastCredits: number | null = null;
51+const REPETITION_THRESHOLD = 3;
9252
9353 async function loadCredentials(): Promise<Credentials | null> {
9454 try {
@@ -114,21 +74,21 @@ async function saveCredentials(
11474 function updateTui(): void {
11575 const state = client.state;
11676 tui.update({
117- player: cachedPlayer,
118- ship: cachedShip,
119- system: worldSnapshot.system ?? state.system ?? null,
120- poi: worldSnapshot.poi ?? state.poi ?? null,
121- base: worldSnapshot.base ?? state.base ?? null,
122- pois: worldSnapshot.pois ?? [],
77+ player: gameState.cachedPlayer,
78+ ship: gameState.cachedShip,
79+ system: gameState.worldSnapshot.system ?? state.system ?? null,
80+ poi: gameState.worldSnapshot.poi ?? state.poi ?? null,
81+ base: gameState.worldSnapshot.base ?? state.base ?? null,
82+ pois: gameState.worldSnapshot.pois ?? [],
12383 nearby: state.nearby ?? [],
124- personality: credentials?.personality,
84+ personality: gameState.credentials?.personality,
12585 tick: state.currentTick,
126- traveling: travelInProgress,
127- travelTarget: lastTravelTarget,
128- jumping: jumpInProgress,
129- jumpTarget: lastJumpTarget,
130- goal: currentGoal,
131- inCombat,
86+ traveling: gameState.travelInProgress,
87+ travelTarget: gameState.lastTravelTarget,
88+ jumping: gameState.jumpInProgress,
89+ jumpTarget: gameState.lastJumpTarget,
90+ goal: gameState.currentGoal,
91+ inCombat: gameState.inCombat,
13292 });
13393 }
13494
@@ -144,91 +104,6 @@ function saveSnapshot(): void {
144104 });
145105 }
146106
147-async function runRegistrationFlow(): Promise<void> {
148- tui.log(
149- formatSystemMessage(
150- "No credentials found. Asking LLM to create a character...",
151- ),
152- );
153- let attempts = 0;
154- while (attempts < 3) {
155- attempts += 1;
156- try {
157- const prompt = buildRegistrationPrompt(true, failedRegistrationNames);
158- tui.setPrompt(prompt);
159- const result = await ollama.generateJson<RegistrationChoice>(prompt);
160- if (result.thinking) {
161- tui.log(formatAiThinking(result.thinking));
162- }
163- const username = String(result.json.username ?? "").trim();
164- const empire = String(result.json.empire ?? "").trim() as EmpireID;
165- const personality = String(
166- result.json.personality ?? "",
167- ).trim() as PersonalityType;
168- const personalityReason = result.json.personality_reason
169- ? String(result.json.personality_reason).trim()
170- : undefined;
171- if (
172- !username ||
173- !isValidEmpire(empire) ||
174- !isValidPersonality(personality)
175- ) {
176- throw new Error("Invalid registration response");
177- }
178- pendingRegistration = {
179- username,
180- empire,
181- personality,
182- personality_reason: personalityReason,
183- };
184- const personalityInfo = PERSONALITY_ARCHETYPES[personality];
185- tui.log(
186- formatSystemMessage(`Registering new account: ${username} (${empire})`),
187- );
188- tui.log(
189- formatSystemMessage(
190- `Chosen personality: ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
191- ),
192- );
193- client.register(username, empire);
194- return;
195- } catch (error) {
196- tui.log(
197- formatSystemMessage(
198- `Registration attempt failed: ${(error as Error).message}`,
199- ),
200- );
201- }
202- }
203-
204- const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
205- pendingRegistration = {
206- username: fallback,
207- empire: "solarian",
208- personality: "pragmatist",
209- };
210- tui.log(
211- formatSystemMessage(
212- `Falling back to account: ${fallback} (solarian, pragmatist)`,
213- ),
214- );
215- client.register(fallback, "solarian");
216-}
217-
218-function isValidEmpire(empire: string): empire is EmpireID {
219- return ["solarian", "voidborn", "crimson", "nebula", "outerrim"].includes(
220- empire,
221- );
222-}
223-
224-function isValidPersonality(
225- personality: string,
226-): personality is PersonalityType {
227- return ["wonderer", "merchant", "warrior", "diplomat", "pragmatist"].includes(
228- personality,
229- );
230-}
231-
232107 function refreshSnapshotForLocation(player: {
233108 current_system?: string;
234109 current_poi?: string;
@@ -237,14 +112,14 @@ function refreshSnapshotForLocation(player: {
237112 const systemId = player.current_system ?? null;
238113 const poiId = player.current_poi ?? null;
239114 const docked = Boolean(player.docked_at_base);
240- const systemChanged = systemId && systemId !== lastSystemId;
241- const poiChanged = poiId && poiId !== lastPoiId;
115+ const systemChanged = systemId && systemId !== gameState.lastSystemId;
116+ const poiChanged = poiId && poiId !== gameState.lastPoiId;
242117
243118 if (systemChanged) {
244- worldSnapshot.system = null;
245- worldSnapshot.pois = [];
246- worldSnapshot.poi = null;
247- worldSnapshot.base = null;
119+ gameState.worldSnapshot.system = null;
120+ gameState.worldSnapshot.pois = [];
121+ gameState.worldSnapshot.poi = null;
122+ gameState.worldSnapshot.base = null;
248123 client.state.system = null;
249124 client.state.poi = null;
250125 client.state.base = null;
@@ -254,8 +129,8 @@ function refreshSnapshotForLocation(player: {
254129 client.getBase();
255130 }
256131 } else if (poiChanged) {
257- worldSnapshot.poi = null;
258- worldSnapshot.base = null;
132+ gameState.worldSnapshot.poi = null;
133+ gameState.worldSnapshot.base = null;
259134 client.state.poi = null;
260135 client.state.base = null;
261136 client.getPOI();
@@ -264,18 +139,18 @@ function refreshSnapshotForLocation(player: {
264139 }
265140 }
266141
267- if (!docked && lastDocked) {
268- worldSnapshot.base = null;
142+ if (!docked && gameState.lastDocked) {
143+ gameState.worldSnapshot.base = null;
269144 client.state.base = null;
270145 }
271146
272- if (docked && !lastDocked && !systemChanged && !poiChanged) {
147+ if (docked && !gameState.lastDocked && !systemChanged && !poiChanged) {
273148 client.getBase();
274149 }
275150
276- if (systemId) lastSystemId = systemId;
277- if (poiId) lastPoiId = poiId;
278- lastDocked = docked;
151+ if (systemId) gameState.lastSystemId = systemId;
152+ if (poiId) gameState.lastPoiId = poiId;
153+ gameState.lastDocked = docked;
279154 }
280155
281156 async function startActionLoop(): Promise<void> {
@@ -284,7 +159,7 @@ async function startActionLoop(): Promise<void> {
284159
285160 while (client.state.authenticated) {
286161 try {
287- if (travelInProgress || jumpInProgress) {
162+ if (gameState.travelInProgress || gameState.jumpInProgress) {
288163 await sleep(config.tickDelayMs);
289164 continue;
290165 }
@@ -292,12 +167,18 @@ async function startActionLoop(): Promise<void> {
292167 config.maxContextActions,
293168 config.maxContextEvents,
294169 );
170+ const recentActions = memory.getRecentActions(REPETITION_THRESHOLD);
171+ const repetitionWarning = detectRepetition(
172+ recentActions,
173+ REPETITION_THRESHOLD,
174+ );
295175 const prompt = buildActionPrompt({
296176 state: client.state,
297- worldSnapshot,
177+ worldSnapshot: gameState.worldSnapshot,
298178 recentHistory,
299- currentGoal,
300- personality: credentials?.personality,
179+ currentGoal: gameState.currentGoal,
180+ personality: gameState.credentials?.personality,
181+ repetitionWarning,
301182 });
302183
303184 tui.setPrompt(prompt);
@@ -340,7 +221,7 @@ async function startActionLoop(): Promise<void> {
340221 const actionName = validation.action.action;
341222 const goal = validation.action.goal ?? null;
342223 if (client.state.player?.username && goal) {
343- currentGoal = goal;
224+ gameState.currentGoal = goal;
344225 memory.setGoal(client.state.player.username, goal);
345226 tui.log(formatAiGoal(goal));
346227 updateTui();
@@ -352,11 +233,11 @@ async function startActionLoop(): Promise<void> {
352233 result.raw,
353234 );
354235 if (actionName === "travel") {
355- lastTravelTarget =
236+ gameState.lastTravelTarget =
356237 String(validation.action.args?.target_poi ?? "").trim() || null;
357238 }
358239 if (actionName === "jump") {
359- lastJumpTarget =
240+ gameState.lastJumpTarget =
360241 String(validation.action.args?.target_system ?? "").trim() || null;
361242 }
362243 dispatchAction(client, validation.action);
@@ -386,25 +267,6 @@ async function startActionLoop(): Promise<void> {
386267 actionLoopRunning = false;
387268 }
388269
389-function isNearbyTarget(
390- nearby: { player_id?: string; username?: string }[] | undefined,
391- targetId: unknown,
392-): boolean {
393- if (!nearby || nearby.length === 0) return false;
394- const target = String(targetId ?? "").trim();
395- if (!target) return false;
396- const normalized = target.toLowerCase();
397- return nearby.some((player) => {
398- const id = player.player_id ? player.player_id.toLowerCase() : "";
399- const name = player.username ? player.username.toLowerCase() : "";
400- return normalized === id || normalized === name;
401- });
402-}
403-
404-function sleep(ms: number): Promise<void> {
405- return new Promise((resolve) => setTimeout(resolve, ms));
406-}
407-
408270 function shutdown(): void {
409271 try {
410272 client.disconnect();
@@ -419,90 +281,56 @@ tui.onExit(shutdown);
419281 process.on("SIGINT", shutdown);
420282 process.on("SIGTERM", shutdown);
421283
284+// Log ALL raw messages for debugging server communication
285+client.on("raw_message", (data: { type: string; payload: unknown }) => {
286+ memory.appendEvent(`raw_${data.type}`, data.payload);
287+});
288+
422289 client.on<WelcomePayload>("welcome", async (data) => {
423290 tui.log(formatWelcome(data));
424291 if (data.motd) tui.log(formatMotd(data.motd));
425292 memory.appendEvent("welcome", data);
426293
427- if (credentials) {
428- tui.log(formatSystemMessage(`Auto-login as ${credentials.username}`));
429- client.login(credentials.username, credentials.token);
430- } else {
431- await runRegistrationFlow();
432- }
433-});
434-
435-client.on<RegisteredPayload>("registered", async (data) => {
436- memory.appendEvent("registered", data);
437- registrationRetries = 0;
438- failedRegistrationNames.length = 0;
439- if (pendingRegistration) {
440- await saveCredentials(
441- pendingRegistration.username,
442- data.token,
443- pendingRegistration.personality,
294+ if (gameState.credentials) {
295+ tui.log(
296+ formatSystemMessage(`Auto-login as ${gameState.credentials.username}`),
444297 );
445- credentials = {
446- username: pendingRegistration.username,
447- token: data.token,
448- personality: pendingRegistration.personality,
449- };
450- tui.log(formatRegistered(data));
451- pendingRegistration = null;
298+ client.login(gameState.credentials.username, gameState.credentials.token);
452299 } else {
453- tui.log(
454- formatSystemMessage("Registered but no pending registration found."),
300+ gameState.pendingRegistration = await runRegistrationFlow(
301+ tui,
302+ ollama,
303+ client,
304+ gameState.failedRegistrationNames,
455305 );
456306 }
457307 });
458308
459-client.on<LoggedInPayload>("logged_in", (data) => {
460- tui.log(formatLoggedIn(data));
461- memory.appendEvent("logged_in", data);
462-
463- // Reset travel/jump state on login (handles reconnect case)
464- travelInProgress = false;
465- lastTravelTarget = null;
466- jumpInProgress = false;
467- lastJumpTarget = null;
468-
469- // Cache player and ship data
470- cachedPlayer = data.player;
471- cachedShip = data.ship;
472- lastCredits = data.player.credits;
473-
474- worldSnapshot.system = data.system;
475- worldSnapshot.poi = data.poi;
476- lastSystemId = data.player.current_system ?? null;
477- lastPoiId = data.player.current_poi ?? null;
478- lastDocked = Boolean(data.player.docked_at_base);
479- currentGoal = memory.getLatestGoal(data.player.username);
480- client.getSystem();
481- client.getPOI();
482- if (data.player.docked_at_base) {
483- client.getBase();
484- }
485- updateTui();
486- saveSnapshot();
487- startActionLoop();
488-});
489-
490309 client.on<ErrorPayload>("error", (data) => {
491310 tui.log(formatError(data));
492311 memory.appendEvent("error", data);
493- if (data.code === "username_taken" && pendingRegistration) {
494- if (pendingRegistration.username) {
495- failedRegistrationNames.push(pendingRegistration.username);
312+ if (data.code === "username_taken" && gameState.pendingRegistration) {
313+ if (gameState.pendingRegistration.username) {
314+ gameState.failedRegistrationNames.push(
315+ gameState.pendingRegistration.username,
316+ );
496317 }
497- if (registrationRetries < MAX_REGISTRATION_RETRIES) {
498- registrationRetries += 1;
318+ if (gameState.registrationRetries < gameState.MAX_REGISTRATION_RETRIES) {
319+ gameState.registrationRetries += 1;
499320 tui.log(
500321 formatSystemMessage(
501322 "Username taken. Requesting a new registration name...",
502323 ),
503324 );
504- pendingRegistration = null;
505- runRegistrationFlow();
325+ gameState.pendingRegistration = null;
326+ runRegistrationFlow(
327+ tui,
328+ ollama,
329+ client,
330+ gameState.failedRegistrationNames,
331+ ).then((choice) => {
332+ gameState.pendingRegistration = choice;
333+ });
506334 } else {
507335 tui.log(
508336 formatSystemMessage(
@@ -510,7 +338,7 @@ client.on<ErrorPayload>("error", (data) => {
510338 ),
511339 );
512340 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
513- pendingRegistration = {
341+ gameState.pendingRegistration = {
514342 username: fallback,
515343 empire: "solarian",
516344 personality: "pragmatist",
@@ -520,15 +348,113 @@ client.on<ErrorPayload>("error", (data) => {
520348 }
521349 });
522350
523-client.on<StateUpdatePayload>("state_update", (data) => {
351+client.on<StateUpdatePayload>("state_update", async (data) => {
524352 memory.appendEvent("state_update", data);
525353
354+ // Handle new registration: server v0.3.0+ doesn't send registered/logged_in events
355+ // It only sends state_update with player data after registration
356+ if (
357+ gameState.pendingRegistration &&
358+ data.player &&
359+ data.player.username === gameState.pendingRegistration.username
360+ ) {
361+ // Use player.id as token (server v0.3.0+ behavior)
362+ const token = gameState.pendingRegistration.token ?? data.player.id;
363+ try {
364+ await saveCredentials(
365+ gameState.pendingRegistration.username,
366+ token,
367+ gameState.pendingRegistration.personality,
368+ );
369+ gameState.credentials = {
370+ username: gameState.pendingRegistration.username,
371+ token: token,
372+ personality: gameState.pendingRegistration.personality,
373+ };
374+ tui.log(
375+ formatSystemMessage(
376+ `Credentials saved for ${gameState.pendingRegistration.username}`,
377+ ),
378+ );
379+ gameState.pendingRegistration = null;
380+
381+ // Start action loop since logged_in won't fire on v0.3.0+
382+ if (!client.state.authenticated) {
383+ client.state.authenticated = true;
384+ gameState.cachedPlayer = data.player;
385+ gameState.cachedShip = data.ship;
386+ gameState.lastCredits = data.player.credits;
387+
388+ // Initialize other state
389+ gameState.worldSnapshot.system = data.system;
390+ gameState.worldSnapshot.poi = data.poi;
391+ if (data.player.current_system)
392+ gameState.lastSystemId = data.player.current_system;
393+ if (data.player.current_poi)
394+ gameState.lastPoiId = data.player.current_poi;
395+ gameState.lastDocked = Boolean(data.player.docked_at_base);
396+ gameState.currentGoal = memory.getLatestGoal(data.player.username);
397+
398+ client.getSystem();
399+ client.getPOI();
400+ if (data.player.docked_at_base) {
401+ client.getBase();
402+ }
403+
404+ updateTui();
405+ saveSnapshot();
406+ startActionLoop();
407+ }
408+ } catch (err) {
409+ tui.log(
410+ formatSystemMessage(
411+ `Failed to save credentials: ${(err as Error).message}`,
412+ ),
413+ );
414+ }
415+ } else if (
416+ !actionLoopRunning &&
417+ !client.state.authenticated &&
418+ gameState.credentials &&
419+ data.player &&
420+ data.player.username === gameState.credentials.username
421+ ) {
422+ // Recovery: we have credentials, and received a state update for our user, but aren't flagged as authenticated/running.
423+ // This might happen if we reconnected and missed a welcome/login event or similar, or just standard 0.3.0+ flow
424+ client.state.authenticated = true;
425+ gameState.cachedPlayer = data.player;
426+ gameState.cachedShip = data.ship;
427+ gameState.lastCredits = data.player.credits;
428+
429+ gameState.worldSnapshot.system = data.system;
430+ gameState.worldSnapshot.poi = data.poi;
431+ if (data.player.current_system)
432+ gameState.lastSystemId = data.player.current_system;
433+ if (data.player.current_poi) gameState.lastPoiId = data.player.current_poi;
434+ gameState.lastDocked = Boolean(data.player.docked_at_base);
435+ gameState.currentGoal = memory.getLatestGoal(data.player.username);
436+
437+ // Refresh world data
438+ client.getSystem();
439+ client.getPOI();
440+ if (data.player.docked_at_base) {
441+ client.getBase();
442+ }
443+
444+ tui.log(
445+ formatSystemMessage(`Recovered session for ${data.player.username}`),
446+ );
447+ updateTui();
448+ saveSnapshot();
449+ startActionLoop();
450+ }
451+
526452 // Update cached player and ship data (only if provided)
527453 if (data.player) {
528- cachedPlayer = data.player;
454+ gameState.cachedPlayer = data.player;
529455 }
530456 if (data.ship) {
531- cachedShip = data.ship;
457+ gameState.cachedShip = data.ship;
532458 }
533459
534460 if (data.player) {
@@ -536,25 +462,26 @@ client.on<StateUpdatePayload>("state_update", (data) => {
536462
537463 // Log state update if significant (only when credits change)
538464 const creditsChanged =
539- lastCredits !== null && data.player.credits !== lastCredits;
465+ gameState.lastCredits !== null &&
466+ data.player.credits !== gameState.lastCredits;
540467 if (creditsChanged) {
541- const diff = data.player.credits - (lastCredits ?? 0);
468+ const diff = data.player.credits - (gameState.lastCredits ?? 0);
542469 const sign = diff > 0 ? "+" : "";
543470 tui.log(
544471 formatSystemMessage(`Credits: ${data.player.credits} (${sign}${diff})`),
545472 );
546- lastCredits = data.player.credits;
473+ gameState.lastCredits = data.player.credits;
547474 }
548475 }
549476
550477 // Track combat state changes
551- const wasInCombat = inCombat;
552- inCombat = data.in_combat ?? false;
478+ const wasInCombat = gameState.inCombat;
479+ gameState.inCombat = data.in_combat ?? false;
553480
554481 // Log combat state changes
555- if (inCombat && !wasInCombat) {
482+ if (gameState.inCombat && !wasInCombat) {
556483 tui.log(formatSystemMessage("COMBAT STARTED"));
557- } else if (!inCombat && wasInCombat) {
484+ } else if (!gameState.inCombat && wasInCombat) {
558485 tui.log(formatSystemMessage("Combat ended"));
559486 }
560487
@@ -574,8 +501,8 @@ client.on<ScanResultPayload>("scan_result", (data) => {
574501
575502 client.on("ok", (data: Record<string, unknown>) => {
576503 const okContext: OkContext = {
577- jumpTarget: lastJumpTarget,
578- travelTarget: lastTravelTarget,
504+ jumpTarget: gameState.lastJumpTarget,
505+ travelTarget: gameState.lastTravelTarget,
579506 };
580507 tui.log(formatOk(data, okContext));
581508 memory.appendEvent("ok", data);
@@ -583,20 +510,20 @@ client.on("ok", (data: Record<string, unknown>) => {
583510
584511 const action = typeof data.action === "string" ? data.action : null;
585512 if (action === "travel") {
586- travelInProgress = true;
513+ gameState.travelInProgress = true;
587514 }
588515 if (action === "jump") {
589- jumpInProgress = true;
516+ gameState.jumpInProgress = true;
590517 }
591518 if (action === "arrived") {
592- travelInProgress = false;
593- lastTravelTarget = null;
519+ gameState.travelInProgress = false;
520+ gameState.lastTravelTarget = null;
594521 client.getSystem();
595522 client.getPOI();
596523 }
597524 if (action === "jumped") {
598- jumpInProgress = false;
599- lastJumpTarget = null;
525+ gameState.jumpInProgress = false;
526+ gameState.lastJumpTarget = null;
600527 client.getSystem();
601528 client.getPOI();
602529 }
@@ -609,14 +536,14 @@ client.on("version_info", (data: Record<string, unknown>) => {
609536 memory.appendEvent("version_info", data);
610537 });
611538
612-credentials = await loadCredentials();
539+gameState.credentials = await loadCredentials();
613540
614541 console.log(`Instance: ${config.instanceName}`);
615542 console.log(`Credentials: ${config.credentialsFile}`);
616543 console.log(`Memory DB: ${config.memoryPath}`);
617544
618545 // Force re-registration if personality is missing
619-if (credentials && !credentials.personality) {
546+if (gameState.credentials && !gameState.credentials.personality) {
620547 tui.log(
621548 formatSystemMessage(
622549 "Credentials missing personality field - forcing re-registration",
@@ -635,7 +562,7 @@ if (credentials && !credentials.personality) {
635562 ),
636563 );
637564 }
638- credentials = null;
565+ gameState.credentials = null;
639566 }
640567
641568 await client.connect();
@@ -643,15 +570,15 @@ updateTui();
643570
644571 function updateWorldSnapshotFromOk(data: Record<string, unknown>): void {
645572 if (data.system && typeof data.system === "object") {
646- worldSnapshot.system = data.system as WorldSnapshot["system"];
573+ gameState.worldSnapshot.system = data.system as WorldSnapshot["system"];
647574 }
648575 if (Array.isArray(data.pois)) {
649- worldSnapshot.pois = data.pois as WorldSnapshot["pois"];
576+ gameState.worldSnapshot.pois = data.pois as WorldSnapshot["pois"];
650577 }
651578 if (data.poi && typeof data.poi === "object") {
652- worldSnapshot.poi = data.poi as WorldSnapshot["poi"];
579+ gameState.worldSnapshot.poi = data.poi as WorldSnapshot["poi"];
653580 }
654581 if (data.base && typeof data.base === "object") {
655- worldSnapshot.base = data.base as WorldSnapshot["base"];
582+ gameState.worldSnapshot.base = data.base as WorldSnapshot["base"];
656583 }
657584 }
src/prompt.ts+12−1
@@ -13,6 +13,10 @@ export interface PromptContext {
1313 recentHistory: HistoryEntry[];
1414 currentGoal: string | null;
1515 personality?: PersonalityType;
16+ repetitionWarning?: {
17+ action: string;
18+ count: number;
19+ } | null;
1620 }
1721
1822 export interface WorldSnapshot {
Cut short: this commit's diff is over 1000 lines.
src/registration.ts+89−0
Cut short: this commit's diff is over 1000 lines.
src/tui.ts+0−2
Cut short: this commit's diff is over 1000 lines.
src/types.ts+34−0
Cut short: this commit's diff is over 1000 lines.
src/utils.ts+50−0
Cut short: this commit's diff is over 1000 lines.