xonecas.io
5875
Os

ollama-space-molt-player / commit 8b8c7df

refactor: restructure logging system and consolidate model configuration

xonecas2026-02-03 8b8c7dfecf4beeba4c1b5f0e6af15838ce23a88c parent ce73a14

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

docs/model-efficiency-conv.md+0−156
@@ -1,156 +0,0 @@
1-Conversation Summary: Improving LLM Decision-Making in SpaceMolt Game Bot
2-Context & Original Problem
3-User has a SpaceMolt game bot (packages/client/) that uses an LLM to make decisions. The bot was stuck in a loop repeatedly trying to mine while docked, receiving "Cannot mine while docked" errors every tick but not learning from these failures.
4-Root Cause: The LLM only had access to the last 5 messages (~1.5 ticks of history), so it couldn't see the pattern of repeated failures.
5-Hardware Constraints
6-
7-- Single GPU with 12GB VRAM
8-- Requires quantized models
9-- Currently running Ollama locally
10-- Models installed: lfm2.5-thinking (731MB), qwen3:8b (5.2GB), qwen2.5:7b (4.7GB), others
11- Goal
12- Improve LLM decision-making by giving it more context so it can:
13-
14-1. Recognize patterns of repeated failures
15-2. Change behavior when actions fail multiple times
16-3. Make better strategic decisions based on recent history
17- What We've Done
18-4. Analyzed the Problem (packages/client/memory-human-partner.sqlite)
19-
20-- Examined game database showing bot tried {"type":"mine"} on ticks 17994-18000
21-- Each attempt returned {"code":"docked","message":"Cannot mine while docked"}
22-- Bot couldn't see this pattern due to limited context (5 messages = ~1.5 ticks)
23-
24-2. Increased Context Window
25- Files Modified:
26-
27-- packages/client/src/types.ts: Added contextWindowSize?: number to ClientConfig
28-- packages/client/src/game-client.ts: Changed this.db.getMessages(5) to this.db.getMessages(this.config.contextWindowSize || 20)
29-- packages/client/src/cli.ts: Added --context-window / -cw CLI option (default: 20)
30-- packages/client/tests/cli.test.ts: Updated tests for new defaults
31- Rationale: 20 messages ≈ 6 ticks of history (vs 5 messages ≈ 1.5 ticks)
32-
33-3. Changed Default Model to lfm2.5-thinking
34- Files Modified:
35-
36-- packages/client/src/cli.ts: Changed default model from qwen3:8b to lfm2.5-thinking
37-- Enabled thinking mode by default (changed --thinking flag to --no-thinking opt-out)
38-- Updated help text and examples
39- Rationale:
40-- Smaller footprint (731MB vs 5.2GB)
41-- Designed for reasoning tasks
42-- Fits 12GB VRAM easily
43-- Has thinking capability built-in
44-
45-4. Added Thinking Output Display
46- Files Modified:
47-
48-- packages/client/src/ollama.ts:
49- - Added GenerateResult interface with response and optional thinking fields
50- - Updated OllamaResponse to include thinking?: string
51- - Changed generate() return type from Promise<string> to Promise<GenerateResult>
52-- packages/client/src/game-client.ts:
53- - Updated both generate() call sites to handle GenerateResult
54- - Added console logging: console.log(\[${this.config.instanceId}] Thinking:\n${result.thinking}\`)`
55- - Added error logging: console.error(\[${this.config.instanceId}] LLM response: ${result.response}\`)` when command is invalid
56-- packages/client/tests/ollama.test.ts: Updated all tests to expect GenerateResult, added test for thinking content
57- Rationale: See LLM's reasoning process to debug decision-making
58-
59-5. Deleted Obsolete Test
60-
61-- Removed packages/client/tests/prompt-length.test.ts (validated 4096 char limit with 5-10 messages, no longer relevant)
62-
63-6. All Tests Passing
64-
65-- 81 tests across 6 files ✅
66-- TypeScript compilation clean ✅
67-- Formatting/linting pass ✅
68- Current Critical Issue: Prompt Truncation
69- Ollama Server Logs Show:
70- level=WARN source=types.go:966 msg="invalid option provided" option=thinking
71- level=WARN source=runner.go:186 msg="truncating input prompt" limit=4096 prompt=87377 keep=4 new=4096
72- Two Problems:
73- Problem 1: Invalid thinking Parameter
74-- lfm2.5-thinking has thinking built-in by default
75-- It doesn't accept thinking as an option parameter
76-- Currently causes warnings every request
77-- Fix needed: Remove/disable the thinking option when using this model
78- Problem 2: Massive Prompt Truncation (CRITICAL)
79-- Prompts are 87,377 tokens (21x over limit!)
80-- Model only handles 4,096 tokens (despite spec saying 32K)
81-- Our context window increase didn't help - prompts are still truncated to ~1.5 ticks
82-- LLM never sees the expanded context we added
83- Why Prompts Are So Large:
84-- API documentation (PLAYER_API_REFERENCE) is probably huge
85-- 20 messages × ~10KB avg state_update = ~200KB
86-- Character prompt + hint + instructions
87-- Game context JSON structure
88- What Needs To Happen Next
89- Immediate Priority: Make the Context Window Actually Work
90- Option A: Reduce Context Window to Fit Limit
91-- Calculate: 87K tokens ÷ 20 messages ≈ 4.3K per message
92-- To fit 4K limit: need ~1 message (back to square one)
93-- To fit 32K limit: 32K ÷ 4.3K ≈ 7 messages
94-- Recommendation: Set contextWindowSize default to 6-7 instead of 20
95-- This gives 2 ticks of history (better than current 0 ticks due to truncation)
96- Option B: Compress Prompt Content
97-- Reduce/summarize PLAYER_API_REFERENCE in packages/client/src/player-api-reference.ts
98-- Filter state_update fields to only essential info in packages/client/src/game-client.ts (buildLLMContext method)
99-- Strip redundant data from history messages
100-- This would allow more messages within token budget
101- Option C: Switch Models
102-- Try qwen2.5:7b (32K context window, already installed)
103-- Or download deepseek-r1:7b (~5GB, 128K context window, thinking built-in)
104-- Would need to verify actual context limits work vs Ollama truncation
105- Option D: Fix thinking Parameter Issue
106-- For lfm2.5-thinking: Don't send thinking: true in options
107-- Model has thinking built-in, parameter causes errors
108-- Simple code change in packages/client/src/ollama.ts
109- Testing Strategy
110-
111-1. Fix the thinking parameter issue first (easy win)
112-2. Reduce context window to 7 messages
113-3. Run bot and check if it stops repeating failed actions
114-4. Monitor Ollama logs for truncation warnings
115-5. If successful, optimize prompt content to allow more messages
116- Files to Focus On Next
117-6. packages/client/src/ollama.ts:
118- - Line 52-54: Conditional logic for sending thinking option
119- - May need to check model name and skip for lfm2.5-thinking
120-7. packages/client/src/cli.ts:
121- - Line 71: Change default contextWindowSize from 20 to 7
122-8. packages/client/src/game-client.ts:
123- - Line 379: Uses this.config.contextWindowSize || 20
124- - Line 271-337: processTick() method - where prompt is built
125- - Consider: buildLLMContext() method optimization
126-9. packages/client/src/player-api-reference.ts:
127- - May be huge - check size and potentially compress
128- Key Commands
129-
130-# Run bot with current setup
131-
132-bun start --instance human-partner --archetype diplomat
133-
134-# Run bot with reduced context (test)
135-
136-bun start --instance human-partner --archetype diplomat --context-window 7
137-
138-# Run tests
139-
140-bun test
141-
142-# Full check
143-
144-bun run check
145-
146-# Check Ollama logs
147-
148-# (wherever Ollama server is running - shows truncation warnings)
149-
150-Success Criteria
151-Bot should:
152-
153-1. See enough history to recognize repeated "docked" errors
154-2. Try {"type":"undock"} instead of repeatedly trying {"type":"mine"}
155-3. Not have prompts truncated by Ollama (no warnings in server logs)
156-4. Show thinking output in console for debugging
packages/client/src/game-client.ts+136−105
@@ -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 }
packages/client/src/logging.ts+420−273
@@ -1,315 +1,461 @@
1-import type {
2- ChatMessageMessage,
3- CombatUpdateMessage,
4- ErrorMessage,
5- LoggedInMessage,
6- MiningYieldMessage,
7- PlayerDiedMessage,
8- RegisteredMessage,
9- ScanResultMessage,
10- ServerMessage,
11- TradeOfferReceivedMessage,
12- WelcomeMessage,
13-} from "./types.ts";
1+import type { BaseCommand, ServerMessage } from "./types.ts";
142
15-export function logServerMessage(
16- instanceId: string,
17- message: ServerMessage,
18- verbose = false,
3+const SUMMARY_MAX_LENGTH = 140;
4+const DETAIL_LINE_MAX_LENGTH = 200;
5+
6+export type LogContext = {
7+ tick: number;
8+ instanceId: string;
9+ username?: string | null;
10+ verbose: boolean;
11+};
12+
13+type LogDirection = "in" | "out";
14+type LogLevel = "info" | "warn" | "error";
15+
16+export function log(
17+ context: LogContext,
18+ direction: LogDirection,
19+ summary: string,
20+ details?: unknown,
21+ level: LogLevel = "info",
1922 ): void {
20- const prefix = `[${instanceId}] ← ${message.type}`;
23+ const identifier = context.username || context.instanceId;
24+ const tick = Number.isFinite(context.tick) ? context.tick : 0;
25+ const arrow = direction === "in" ? "←" : "→";
26+ const header = `${tick} | [${identifier}] | ${arrow} | ${summary}`;
27+ const lines = formatDetailLines(details, context.verbose);
28+ const logger = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
29+ logger(header);
30+ if (lines.length > 0) {
31+ lines.forEach((line) => logger(` ${line}`));
32+ }
33+}
34+
35+export function logServerMessage(context: LogContext, message: ServerMessage): void {
36+ const summary = getServerSummary(message);
37+ const details = getServerDetails(message, context.verbose);
38+ log(context, "in", summary, details);
39+}
40+
41+export function logClientCommand(context: LogContext, command: BaseCommand): void {
42+ const maskedPayload = maskSensitiveData(command.payload);
43+ const summary = command.payload
44+ ? `${command.type} (${formatPayload(maskedPayload, SUMMARY_MAX_LENGTH)})`
45+ : command.type;
46+ log(context, "out", summary, maskedPayload);
47+}
48+
49+export function logClientEvent(context: LogContext, message: string, details?: unknown): void {
50+ log(context, "out", message, details);
51+}
52+
53+export function logClientWarning(context: LogContext, message: string, details?: unknown): void {
54+ log(context, "out", message, details, "warn");
55+}
56+
57+export function logClientError(context: LogContext, message: string, details?: unknown): void {
58+ const normalized = normalizeErrorDetails(details);
59+ log(context, "out", message, normalized, "error");
60+}
61+
62+export function logThinking(context: LogContext, thinking: string): void {
63+ const formatted = formatThinking(thinking, context.verbose);
64+ log(context, "out", "thinking", formatted);
65+}
66+
67+export function formatThinking(thinking: string, verbose: boolean): string {
68+ if (verbose) {
69+ return thinking;
70+ }
71+
72+ const sentences = splitSentences(thinking);
73+ if (sentences.length <= 3) {
74+ return sentences.join(" ").trim();
75+ }
76+ const first = sentences[0];
77+ const lastTwo = sentences.slice(-2);
78+ const omittedCount = sentences.length - 3;
79+ return `${first} [... ${omittedCount} sentences omitted ...] ${lastTwo.join(" ")}`.trim();
80+}
81+
82+function splitSentences(text: string): string[] {
83+ const normalized = text.replace(/\s+/g, " ").trim();
84+ if (!normalized) {
85+ return [];
86+ }
87+ const matches = normalized.match(/[^.!?]+[.!?]+|[^.!?]+$/g);
88+ if (!matches) {
89+ return [normalized];
90+ }
91+ return matches.map((sentence) => sentence.trim()).filter((sentence) => sentence.length > 0);
92+}
93+
94+function normalizeErrorDetails(details: unknown): unknown {
95+ if (details instanceof Error) {
96+ return {
97+ message: details.message,
98+ stack: details.stack,
99+ };
100+ }
101+ return details;
102+}
103+
104+function formatDetailLines(details: unknown, verbose: boolean): string[] {
105+ if (details === undefined || details === null) {
106+ return [];
107+ }
108+ if (typeof details === "string") {
109+ return formatMultiline(details, verbose);
110+ }
111+ return formatPayloadLines(details, "", verbose, { current: 0 });
112+}
113+
114+function formatMultiline(text: string, verbose: boolean): string[] {
115+ const lines = text.split("\n");
116+ const truncated =
117+ verbose || lines.length <= 5
118+ ? lines
119+ : [lines[0], `[... ${lines.length - 4} more lines ...]`, ...lines.slice(-3)];
120+ return truncated.map((line) => truncateLine(line));
121+}
122+
123+function truncateLine(line: string): string {
124+ if (line.length <= DETAIL_LINE_MAX_LENGTH) {
125+ return line;
126+ }
127+ return `${line.substring(0, DETAIL_LINE_MAX_LENGTH)}...`;
128+}
129+
130+function formatPayloadLines(
131+ payload: unknown,
132+ indent: string,
133+ verbose: boolean,
134+ lineCount: { current: number },
135+): string[] {
136+ if (!payload || typeof payload !== "object") {
137+ lineCount.current++;
138+ return [`${indent}${String(payload)}`];
139+ }
140+
141+ const lines: string[] = [];
142+ for (const [key, value] of Object.entries(payload)) {
143+ if (!verbose && lineCount.current >= 2) {
144+ return lines;
145+ }
146+ if (value === null || value === undefined) {
147+ continue;
148+ }
149+ if (Array.isArray(value)) {
150+ if (value.length === 0) {
151+ lines.push(`${indent}${key}: []`);
152+ lineCount.current++;
153+ } else if (typeof value[0] === "object") {
154+ lines.push(`${indent}${key}: [${value.length} items]`);
155+ lineCount.current++;
156+ if (verbose) {
157+ value.forEach((item, idx) => {
158+ lines.push(`${indent} [${idx}]:`);
159+ lineCount.current++;
160+ lines.push(...formatPayloadLines(item, `${indent} `, verbose, lineCount));
161+ });
162+ }
163+ } else {
164+ lines.push(`${indent}${key}: [${value.join(", ")}]`);
165+ lineCount.current++;
166+ }
167+ } else if (typeof value === "object") {
168+ lines.push(`${indent}${key}:`);
169+ lineCount.current++;
170+ if (verbose || lineCount.current < 2) {
171+ lines.push(...formatPayloadLines(value, `${indent} `, verbose, lineCount));
172+ }
173+ } else if (typeof value === "string") {
174+ const truncated = value.length > 100 ? `${value.substring(0, 100)}...` : value;
175+ lines.push(`${indent}${key}: ${truncated}`);
176+ lineCount.current++;
177+ } else {
178+ lines.push(`${indent}${key}: ${String(value)}`);
179+ lineCount.current++;
180+ }
181+ }
182+
183+ return lines.map((line) => truncateLine(line));
184+}
185+
186+function maskSensitiveData(payload: unknown): unknown {
187+ if (payload === null || payload === undefined) {
188+ return payload;
189+ }
190+ if (typeof payload !== "object") {
191+ return payload;
192+ }
193+ if (Array.isArray(payload)) {
194+ return payload.map((item) => maskSensitiveData(item));
195+ }
196+ const result: Record<string, unknown> = {};
197+ for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {
198+ if (typeof key === "string" && key.toLowerCase().includes("token")) {
199+ if (typeof value === "string") {
200+ result[key] = value.length > 8 ? `${value.substring(0, 8)}...` : value;
201+ } else {
202+ result[key] = value;
203+ }
204+ } else {
205+ result[key] = maskSensitiveData(value);
206+ }
207+ }
208+ return result;
209+}
21210
211+function getServerSummary(message: ServerMessage): string {
22212 switch (message.type) {
23213 case "welcome": {
24- const p = (message as WelcomeMessage).payload;
25- console.log(`${prefix}`);
26- console.log(` Version: ${p.version} (${p.release_date})`);
27- console.log(` Tick rate: ${p.tick_rate}s, Current tick: ${p.current_tick}`);
28- console.log(` Server time: ${p.server_time}`);
29- console.log(` Website: ${p.website}`);
30- if (p.motd) console.log(` MOTD: ${p.motd}`);
31- if (p.release_notes.length > 0) {
32- console.log(` Release notes:`);
33- p.release_notes.forEach((note) => console.log(` - ${note}`));
34- }
35- break;
214+ const p = message.payload;
215+ return `welcome (version: ${p.version}, tick_rate: ${p.tick_rate}s, current_tick: ${p.current_tick})`;
36216 }
37217 case "registered": {
38- const p = (message as RegisteredMessage).payload;
39- console.log(`${prefix}`);
40- console.log(` Player ID: ${p.player_id}`);
41- console.log(` Token: ${p.token.substring(0, 8)}...`);
42- break;
218+ const p = message.payload;
219+ const masked = maskSensitiveData({ token: p.token }) as { token: string };
220+ return `registered (player_id: ${p.player_id}, token: ${masked.token})`;
43221 }
44222 case "logged_in": {
45- const p = (message as LoggedInMessage).payload;
46- console.log(`${prefix}`);
47- console.log(` Player: ${p.player.username} (${p.player.empire})`);
48- console.log(` Credits: ${p.player.credits}, Location: ${p.system.name} > ${p.poi.name}`);
49- if (!verbose) break;
50- console.log(` Home base: ${p.player.home_base || "none"}`);
51- if (p.player.docked_at_base) console.log(` Docked at: ${p.player.docked_at_base}`);
52- if (p.player.status_message) console.log(` Status: ${p.player.status_message}`);
53- if (p.player.clan_tag) console.log(` Clan: ${p.player.clan_tag}`);
54- if (p.player.faction_id) {
55- console.log(` Faction: ${p.player.faction_id} (rank: ${p.player.faction_rank})`);
56- }
57- console.log(` System: ${p.system.description || "No description"}`);
58- console.log(
59- ` Empire: ${p.system.empire || "neutral"}, Police: ${p.system.police_level || 0}`,
60- );
61- if (p.system.connections && p.system.connections.length > 0) {
62- console.log(` Connected to: ${p.system.connections.join(", ")}`);
63- }
64- console.log(` POI: ${p.poi.type} - ${p.poi.description || "No description"}`);
65- if (p.poi.base_id) console.log(` Base: ${p.poi.base_id}`);
66- if (p.poi.resources && p.poi.resources.length > 0) {
67- console.log(` Resources:`);
68- p.poi.resources.forEach((r: any) =>
69- console.log(` - ${r.resource_id}: ${r.remaining} (richness: ${r.richness})`),
70- );
71- }
72- console.log(` Ship: ${p.ship.name} (${p.ship.class_id})`);
73- console.log(
74- ` Hull: ${p.ship.hull}/${p.ship.max_hull}, Shield: ${p.ship.shield}/${p.ship.max_shield} (regen: ${p.ship.shield_recharge})`,
75- );
76- console.log(` Armor: ${p.ship.armor}, Speed: ${p.ship.speed}`);
77- console.log(
78- ` Fuel: ${p.ship.fuel}/${p.ship.max_fuel}, Cargo: ${p.ship.cargo_used}/${p.ship.cargo_capacity}`,
79- );
80- console.log(
81- ` CPU: ${p.ship.cpu_used}/${p.ship.cpu_capacity}, Power: ${p.ship.power_used}/${p.ship.power_capacity}`,
82- );
83- if (p.ship.modules && p.ship.modules.length > 0) {
84- console.log(` Modules: ${p.ship.modules.join(", ")}`);
85- }
86- if (p.ship.cargo && p.ship.cargo.length > 0) {
87- console.log(` Cargo:`);
88- p.ship.cargo.forEach((item: any) =>
89- console.log(` - ${item.item_id}: ${item.quantity}`),
90- );
91- }
92- if (p.player.skills && Object.keys(p.player.skills).length > 0) {
93- console.log(` Skills:`);
94- Object.entries(p.player.skills).forEach(([skill, data]: [string, any]) =>
95- console.log(` - ${skill}: level ${data.level} (${data.xp} XP)`),
96- );
97- }
98- if (p.player.stats) {
99- const s = p.player.stats;
100- console.log(` Stats:`);
101- console.log(` Ships destroyed: ${s.ships_destroyed}, Deaths: ${s.times_destroyed}`);
102- console.log(` Ore mined: ${s.ore_mined}, Items crafted: ${s.items_crafted}`);
103- console.log(` Credits earned: ${s.credits_earned}, spent: ${s.credits_spent}`);
104- console.log(
105- ` Trades: ${s.trades_completed}, Systems discovered: ${s.systems_discovered}`,
106- );
107- }
108- break;
223+ const p = message.payload;
224+ return `logged_in (player: ${p.player.username}, empire: ${p.player.empire}, location: ${p.system.name} > ${p.poi.name})`;
109225 }
110226 case "state_update": {
111- const p = (message as any).payload;
112- console.log(`${prefix} (tick ${p.tick})`);
113- console.log(` Player: ${p.player.username}, Credits: ${p.player.credits}`);
114- console.log(
115- ` Location: ${p.player.current_system} > ${p.player.current_poi}${p.player.docked_at_base ? ` (docked)` : ""}`,
116- );
117- if (!verbose) break;
118- console.log(
119- ` Ship: Hull ${p.ship.hull}/${p.ship.max_hull}, Shield ${p.ship.shield}/${p.ship.max_shield}`,
120- );
121- console.log(
122- ` Fuel: ${p.ship.fuel}/${p.ship.max_fuel}, Cargo: ${p.ship.cargo_used}/${p.ship.cargo_capacity}`,
123- );
124- console.log(
125- ` CPU: ${p.ship.cpu_used}/${p.ship.cpu_capacity}, Power: ${p.ship.power_used}/${p.ship.power_capacity}`,
126- );
127- if (p.in_combat) console.log(` IN COMBAT`);
Cut short: this commit's diff is over 1000 lines.
packages/client/src/ollama.ts+21−2
Cut short: this commit's diff is over 1000 lines.
packages/client/src/ws-client.ts+1−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/logging.test.ts+25−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/ollama.test.ts+77−0
Cut short: this commit's diff is over 1000 lines.