@@ -1,7 +1,15 @@
11 import { GAME_API } from "./api-definition.ts";
22 import { getArchetypeListText } from "./archetypes.ts";
33 import type { GameDatabase } from "./db.ts";
4-import { formatPayload, logServerMessage } from "./logging.ts";
4+import {
5+ logClientCommand,
6+ logClientError,
7+ logClientEvent,
8+ logClientWarning,
9+ logServerMessage,
10+ logThinking,
11+ type LogContext,
12+} from "./logging.ts";
513 import { loadModelConfig } from "./model-config.ts";
614 import { OllamaClient } from "./ollama.ts";
715 import { PLAYER_API_REFERENCE } from "./player-api-reference.ts";
@@ -18,9 +26,9 @@ import type {
1826 } from "./types.ts";
1927 import { GameWebSocketClient } from "./ws-client.ts";
2028
21-export class GameClient {
22- private static readonly MAX_LOG_LENGTH = 500;
29+const EMPIRES = ["solarian", "voidborn", "crimson", "nebula", "outerrim"];
2330
31+export class GameClient {
2432 private db: GameDatabase;
2533 private ws: GameWebSocketClient;
2634 private ollama: OllamaClient;
@@ -29,7 +37,6 @@ export class GameClient {
2937 private lastProcessedTick = -1;
3038 private tickRate: number;
3139 private watchdogTimer: Timer | null = null;
32- private isRunning = false;
3340 private isProcessingTick = false;
3441 private waitingForRegistration = false;
3542 private registrationData: { username: string; empire: string } | null = null;
@@ -52,15 +59,17 @@ export class GameClient {
5259 timeout: config.ollamaTimeout,
5360 });
5461
55- console.log(
56- `[${config.instanceId}] Using model: ${config.model} (${modelConfig.ollama.model}), context: ${config.contextWindowSize} messages`,
57- );
62+ logClientEvent(this.getLogContext(), "Using model", {
63+ model: config.model,
64+ ollama_model: modelConfig.ollama.model,
65+ context_messages: config.contextWindowSize,
66+ });
5867
5968 this.ws = new GameWebSocketClient({
6069 url: config.serverUrl || "wss://game.spacemolt.com/ws",
6170 onMessage: (msg) => {
6271 this.handleServerMessage(msg).catch((error) => {
63- console.error(`[${this.config.instanceId}] Unhandled error in message handler:`, error);
72+ logClientError(this.getLogContext(), "Unhandled error in message handler", error);
6473 });
6574 },
6675 onConnect: () => this.handleConnect(),
@@ -70,33 +79,31 @@ export class GameClient {
7079 }
7180
7281 async start(): Promise<void> {
73- console.log(`[${this.config.instanceId}] Starting game client...`);
82+ logClientEvent(this.getLogContext(), "Starting game client");
7483
7584 await this.ws.connect();
76- this.isRunning = true;
7785 }
7886
7987 stop(): void {
80- this.isRunning = false;
8188 if (this.watchdogTimer) {
8289 clearTimeout(this.watchdogTimer);
8390 this.watchdogTimer = null;
8491 }
8592 this.ws.disconnect();
8693 this.db.close();
87- console.log(`[${this.config.instanceId}] Client stopped`);
94+ logClientEvent(this.getLogContext(), "Client stopped");
8895 }
8996
9097 private handleConnect(): void {
91- console.log(`[${this.config.instanceId}] Connected to server`);
98+ logClientEvent(this.getLogContext(), "Connected to server");
9299 }
93100
94101 private handleDisconnect(): void {
95- console.log(`[${this.config.instanceId}] Disconnected from server`);
102+ logClientWarning(this.getLogContext(), "Disconnected from server");
96103 }
97104
98105 private handleError(error: Error): void {
99- console.error(`[${this.config.instanceId}] Error:`, error.message);
106+ logClientError(this.getLogContext(), "Connection error", error);
100107 this.db.saveMessage(this.currentTick, "client", {
101108 error: "Connection error occurred",
102109 code: "CONNECTION_ERROR",
@@ -105,7 +112,7 @@ export class GameClient {
105112
106113 private async handleServerMessage(message: ServerMessage): Promise<void> {
107114 try {
108- logServerMessage(this.config.instanceId || "default", message, this.config.verbose || false);
115+ logServerMessage(this.getLogContext(), message);
109116
110117 switch (message.type) {
111118 case "welcome":
@@ -136,7 +143,7 @@ export class GameClient {
136143 break;
137144 }
138145 } catch (error) {
139- console.error(`[${this.config.instanceId}] Error handling ${message.type} message:`, error);
146+ logClientError(this.getLogContext(), `Error handling ${message.type} message`, error);
140147 this.db.saveMessage(this.currentTick, "client", {
141148 error: `Failed to handle ${message.type} message: ${error instanceof Error ? error.message : String(error)}`,
142149 code: "MESSAGE_HANDLER_ERROR",
@@ -150,23 +157,23 @@ export class GameClient {
150157 this.lastProcessedTick = this.currentTick - 1;
151158 this.startWatchdog();
152159
153- if (this.isRunning) {
154- const activeUsername = this.db.getActiveUsername();
155- if (activeUsername) {
156- console.log(`[${this.config.instanceId}] Auto-login as ${activeUsername.username}`);
157- this.ws.send({
158- type: "login",
159- payload: { username: activeUsername.username, token: activeUsername.token },
160- });
161- } else {
162- await this.promptForRegistration().catch((error) => {
163- console.error(`[${this.config.instanceId}] Registration prompt error:`, error);
164- this.db.saveMessage(this.currentTick, "client", {
165- error: "Registration prompt failed",
166- code: "REGISTRATION_PROMPT_ERROR",
167- });
160+ const activeUsername = this.db.getActiveUsername();
161+ if (activeUsername) {
162+ logClientEvent(this.getLogContext(activeUsername.username), "Auto-login", {
163+ username: activeUsername.username,
164+ });
165+ this.ws.send({
166+ type: "login",
167+ payload: { username: activeUsername.username, token: activeUsername.token },
168+ });
169+ } else {
170+ await this.promptForRegistration().catch((error) => {
171+ logClientError(this.getLogContext(), "Registration prompt error", error);
172+ this.db.saveMessage(this.currentTick, "client", {
173+ error: "Registration prompt failed",
174+ code: "REGISTRATION_PROMPT_ERROR",
168175 });
169- }
176+ });
170177 }
171178 }
172179
@@ -174,14 +181,18 @@ export class GameClient {
174181 const newTick = message.payload.tick;
175182
176183 if (newTick <= this.lastProcessedTick) {
177- console.log(`[${this.config.instanceId}] Ignoring duplicate or stale tick ${newTick}`);
184+ logClientWarning(this.getLogContext(), "Ignoring duplicate or stale tick", {
185+ new_tick: newTick,
186+ last_processed_tick: this.lastProcessedTick,
187+ });
178188 return false;
179189 }
180190
181191 if (this.isProcessingTick) {
182- console.log(
183- `[${this.config.instanceId}] Skipping tick ${newTick}, still processing tick ${this.currentTick}`,
184- );
192+ logClientWarning(this.getLogContext(), "Skipping tick, still processing", {
193+ skipped_tick: newTick,
194+ current_tick: this.currentTick,
195+ });
185196 return false;
186197 }
187198
@@ -190,21 +201,16 @@ export class GameClient {
190201
191202 this.startWatchdog();
192203
193- if (this.isRunning) {
194- try {
195- await this.processTick();
196- this.lastProcessedTick = newTick;
197- } catch (error) {
198- console.error(`[${this.config.instanceId}] Tick processing error:`, error);
199- this.db.saveMessage(this.currentTick, "client", {
200- error: "Tick processing failed",
201- code: "TICK_PROCESSING_ERROR",
202- });
203- } finally {
204- this.isProcessingTick = false;
205- }
206- } else {
204+ try {
205+ await this.processTick();
207206 this.lastProcessedTick = newTick;
207+ } catch (error) {
208+ logClientError(this.getLogContext(), "Tick processing error", error);
209+ this.db.saveMessage(this.currentTick, "client", {
210+ error: "Tick processing failed",
211+ code: "TICK_PROCESSING_ERROR",
212+ });
213+ } finally {
208214 this.isProcessingTick = false;
209215 }
210216
@@ -216,7 +222,7 @@ export class GameClient {
216222 return;
217223 }
218224
219- console.log(`[${this.config.instanceId}] Registration successful`);
225+ logClientEvent(this.getLogContext(this.registrationData.username), "Registration successful");
220226
221227 const characterPrompt = await this.generateCharacterPrompt(
222228 this.registrationData.username,
@@ -231,12 +237,33 @@ export class GameClient {
231237 this.currentTick,
232238 );
233239
234- console.log(`[${this.config.instanceId}] Character prompt generated and saved`);
240+ logClientEvent(
241+ this.getLogContext(this.registrationData.username),
242+ "Character prompt generated and saved",
243+ );
235244
236245 this.waitingForRegistration = false;
237246 this.registrationData = null;
238247 }
239248
249+ private shuffleArray<T>(array: T[]): T[] {
250+ const shuffled = [...array];
251+ for (let i = shuffled.length - 1; i > 0; i--) {
252+ const j = Math.floor(Math.random() * (i + 1));
253+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
254+ }
255+ return shuffled;
256+ }
257+
258+ private getApiSubset<K extends keyof typeof PLAYER_API_REFERENCE>(
259+ commands: K[],
260+ ): Pick<typeof PLAYER_API_REFERENCE, K> {
261+ return Object.fromEntries(commands.map((cmd) => [cmd, PLAYER_API_REFERENCE[cmd]])) as Pick<
262+ typeof PLAYER_API_REFERENCE,
263+ K
264+ >;
265+ }
266+
240267 private async generateCharacterPrompt(username: string, empire: string): Promise<string> {
241268 const archetypeList = getArchetypeListText(this.config.archetype);
242269
@@ -245,7 +272,7 @@ export class GameClient {
245272 Choose a personality archetype from this list:
246273 ${archetypeList}
247274
248-Generate a concise character prompt (1-2 sentences) that captures this character's personality, goals, and playstyle based on your chosen archetype. This prompt will guide all future decisions this character makes in the game.
275+Generate a concise role playing character prompt (5 sentences max) that captures this character's personality, goals, and playstyle based on your chosen personality archetype.
249276
250277 Character prompt:`;
251278
@@ -253,39 +280,37 @@ Character prompt:`;
253280 const result = await this.ollama.generate(promptGeneration);
254281
255282 if (result.thinking) {
256- console.log(`[${this.config.instanceId}] Thinking: ${result.thinking}`);
283+ logThinking(this.getLogContext(username), result.thinking);
257284 }
258285
259286 return result.response;
260287 } catch (error) {
261- console.error(`[${this.config.instanceId}] Failed to generate prompt:`, error);
288+ logClientError(this.getLogContext(username), "Failed to generate prompt", error);
262289 return `You are ${username}, a ${empire} player in SpaceMolt.`;
263290 }
264291 }
265292
266293 private async promptForRegistration(): Promise<void> {
267- const registerApi = {
268- register: PLAYER_API_REFERENCE.register,
269- };
270-
271294 const minimalContext = {
272- api: registerApi,
273- note: "You must register before you can play. Choose a creative username prefix - the system will add a unique suffix.",
295+ api: this.getApiSubset(["register"]),
296+ note: "You must register before you can play. Usernames MUST be alpha numeric and maximum 20 characters",
274297 };
275298
276299 const contextJson = JSON.stringify(minimalContext);
277- const registrationPrompt = `You are playing a multiplayer space game called SpaceMolt. You need to register a username to play.
300+ const shuffledEmpires = this.shuffleArray(EMPIRES);
301+ const empireList = shuffledEmpires.join(", ");
302+ const registrationPrompt = `You are playing a multiplayer space game called SpaceMolt, 🦞 **The Crustacean Cosmos** 🦞. You need to register a username to play.
278303
279304 Game Context:
280305 ${contextJson}
281306
282-Choose a creative username prefix (the system will add a unique suffix for you).
283-Choose an empire from: solarian, voidborn, crimson, nebula, outerrim
307+Choose a creative username.
308+Choose an empire from: ${empireList}
284309
285310 CRITICAL: You must respond with ONLY valid JSON. No explanations, no markdown, just the JSON command.
286311
287312 JSON Format:
288-{"type": "register", "payload": {"username": "YourChosenPrefix", "empire": "solarian"}}
313+{"type": "register", "payload": {"username": "[your username]", "empire": "[your empire]"}}
289314
290315 Your JSON response:`;
291316
@@ -293,7 +318,7 @@ Your JSON response:`;
293318 const result = await this.ollama.generate(registrationPrompt);
294319
295320 if (result.thinking) {
296- console.log(`[${this.config.instanceId}] Thinking:\n${result.thinking}`);
321+ logThinking(this.getLogContext(), result.thinking);
297322 }
298323
299324 let command: BaseCommand;
@@ -312,14 +337,12 @@ Your JSON response:`;
312337 throw new Error("Invalid registration payload: missing username or empire");
313338 }
314339
315- const instanceSuffix = `-${this.config.instanceId}`;
340+ const instanceSuffix = `-${this.config.instanceId?.slice(0, 3).toLocaleLowerCase()}`;
316341 if (!payload.username.endsWith(instanceSuffix)) {
317342 payload.username = `${payload.username}${instanceSuffix}`;
318343 }
319344
320- console.log(
321- `[${this.config.instanceId}] → register (username: ${payload.username}, empire: ${payload.empire})`,
322- );
345+ logClientCommand(this.getLogContext(payload.username), command);
323346
324347 this.waitingForRegistration = true;
325348 this.registrationData = {
@@ -330,7 +353,7 @@ Your JSON response:`;
330353 this.ws.send(command);
331354 this.db.saveMessage(this.currentTick, "client", command);
332355 } catch (error) {
333- console.error(`[${this.config.instanceId}] Registration prompt failed:`, error);
356+ logClientError(this.getLogContext(), "Registration prompt failed", error);
334357 this.db.saveMessage(this.currentTick, "client", {
335358 error: error instanceof Error ? error.message : "Registration prompt failed",
336359 code: "REGISTRATION_PROMPT_FAILED",
@@ -342,10 +365,16 @@ Your JSON response:`;
342365
343366 private handleServerError(message: ErrorMessage): void {
344367 if (this.waitingForRegistration && this.registrationData) {
345- console.log(`[${this.config.instanceId}] Registration failed, retrying...`);
368+ logClientWarning(
369+ this.getLogContext(this.registrationData.username),
370+ "Registration failed, retrying",
371+ {
372+ server_error: message.payload,
373+ },
374+ );
346375 this.waitingForRegistration = false;
347376 this.promptForRegistration().catch((error) => {
348- console.error(`[${this.config.instanceId}] Registration retry error:`, error);
377+ logClientError(this.getLogContext(), "Registration retry error", error);
349378 });
350379 }
351380 }
@@ -356,9 +385,9 @@ Your JSON response:`;
356385 }
357386
358387 this.watchdogTimer = setTimeout(() => {
359- console.warn(
360- `[${this.config.instanceId}] No tick received for ${this.tickRate * 2}ms. Connection may be lost.`,
361- );
388+ logClientWarning(this.getLogContext(), "No tick received within expected timeframe", {
389+ wait_ms: this.tickRate * 2,
390+ });
362391 this.db.saveMessage(this.currentTick, "client", {
363392 error: "No server tick received within expected timeframe",
364393 code: "WATCHDOG_TIMEOUT",
@@ -373,13 +402,15 @@ Your JSON response:`;
373402 const prompt = activeUsername?.prompt || "";
374403 const hint = instance.hint || this.config.hint || undefined;
375404
376- console.log(`[${this.config.instanceId}] Hint:`, hint || "(none)");
405+ logClientEvent(this.getLogContext(activeUsername?.username), "Hint", {
406+ hint: hint || "(none)",
407+ });
377408
378409 const context = this.buildLLMContext(prompt, hint);
379410
380411 try {
381412 const contextJson = JSON.stringify(context);
382- const fullPrompt = `You are playing a online multiplayer game, be social, role play as the player and stay in character. Game Context:
413+ const fullPrompt = `You are playing a multiplayer space game called SpaceMolt, 🦞 **The Crustacean Cosmos** 🦞. Be social, role play and stay in character. Game Context:
383414
384415 ${contextJson}
385416
@@ -399,7 +430,7 @@ Your JSON response:`;
399430 const result = await this.ollama.generate(fullPrompt);
400431
401432 if (result.thinking) {
402- console.log(`[${this.config.instanceId}] Thinking:\n${result.thinking}`);
433+ logThinking(this.getLogContext(activeUsername?.username), result.thinking);
403434 }
404435
405436 let command: BaseCommand;
@@ -410,7 +441,9 @@ Your JSON response:`;
410441 }
411442
412443 if (!command.type || typeof command.type !== "string") {
413- console.error(`[${this.config.instanceId}] LLM response: ${result.response}`);
444+ logClientError(this.getLogContext(activeUsername?.username), "LLM response missing type", {
445+ response: result.response,
446+ });
414447 throw new Error("Invalid command: missing or invalid 'type' field");
415448 }
416449
@@ -421,26 +454,20 @@ Your JSON response:`;
421454 username: payload.username,
422455 empire: payload.empire,
423456 };
424- console.log(
425- `[${this.config.instanceId}] → register (username: ${payload.username}, empire: ${payload.empire})`,
426- );
457+ logClientCommand(this.getLogContext(payload.username), command);
427458 } else if (command.type === "login" && command.payload) {
428459 const payload = command.payload as { username: string; token: string };
429460 this.db.updateUsernameLastUsed(payload.username, this.currentTick);
430- console.log(
431- `[${this.config.instanceId}] → ${command.type}${command.payload ? ` (${formatPayload(command.payload)})` : ""}`,
432- );
461+ logClientCommand(this.getLogContext(payload.username), command);
433462 } else {
434- console.log(
435- `[${this.config.instanceId}] → ${command.type}${command.payload ? ` (${formatPayload(command.payload)})` : ""}`,
436- );
463+ logClientCommand(this.getLogContext(activeUsername?.username), command);
437464 }
438465
439466 this.ws.send(command);
440467
441468 this.db.saveMessage(this.currentTick, "client", command);
442469 } catch (error) {
443- console.error(`[${this.config.instanceId}] LLM generation failed:`, error);
470+ logClientError(this.getLogContext(activeUsername?.username), "LLM generation failed", error);
444471 this.db.saveMessage(this.currentTick, "client", {
445472 error: error instanceof Error ? error.message : "LLM generation failed",
446473 code: "LLM_GENERATION_FAILED",
@@ -473,16 +500,9 @@ Your JSON response:`;
473500 } catch {}
474501 }
475502
476- const truncated =
477- text.length > GameClient.MAX_LOG_LENGTH
478- ? text.substring(0, GameClient.MAX_LOG_LENGTH) +
479- `... (${text.length - GameClient.MAX_LOG_LENGTH} more chars)`
480- : text;
481-
482- console.error(
483- `[${this.config.instanceId}] Failed to parse LLM response. Raw response:`,
484- truncated,
485- );
503+ logClientError(this.getLogContext(), "Failed to parse LLM response", {
504+ response: text,
505+ });
486506
487507 throw new Error("Response does not contain valid JSON command");
488508 }
@@ -497,10 +517,10 @@ Your JSON response:`;
497517 data: JSON.parse(msg.data),
498518 };
499519 } catch (error) {
500- console.error(
501- `[${this.config.instanceId}] Failed to parse message at tick ${msg.tick}:`,
502- error,
503- );
520+ logClientError(this.getLogContext(), "Failed to parse message", {
521+ tick: msg.tick,
522+ error: error instanceof Error ? error.message : String(error),
523+ });
504524 return {
505525 sender: msg.sender,
506526 tick: msg.tick,
@@ -528,4 +548,15 @@ Your JSON response:`;
528548 },
529549 };
530550 }
551+
552+ private getLogContext(username?: string | null): LogContext {
553+ const resolvedUsername =
554+ username !== undefined ? username : this.db.getActiveUsername()?.username || null;
555+ return {
556+ tick: this.currentTick,
557+ instanceId: this.config.instanceId || "default",
558+ username: resolvedUsername,
559+ verbose: this.config.verbose || false,
560+ };
561+ }
531562 }