xonecas.io
5875
Os

ollama-space-molt-player / commit 24e95a3

refactor: modularize TUI system into separate components and optimize game loop

xonecas2026-02-01 24e95a3e0313474557e9273a6b2823820691ab31 parent 131136e

15 files changed

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

AGENTS.md+7−3
@@ -6,7 +6,7 @@ Purpose: help coding agents work safely and consistently in this repo.
66 - Runtime: Bun (TypeScript, ESM).
77 - UI: terminal UI via `blessed`.
88 - LLM: local Ollama HTTP API.
9-- Data: SQLite via `bun:sqlite` at `memory.sqlite`.
9+- Data: SQLite via `bun:sqlite` at `memory-{name}.sqlite`.
1010 - Game client: SpaceMolt reference client is a git submodule in `client/`.
1111
1212 ## Key Paths
@@ -23,7 +23,11 @@ Purpose: help coding agents work safely and consistently in this repo.
2323 - `bun install`
2424
2525 ### Run app
26-- `bun run ollama-play`
26+- `bun run ollama-play --name <instance-name>` (or `-n <instance-name>`)
27+- The `--name` argument is required and determines file paths:
28+ - Credentials: `.spacemolt-bot-{name}.json`
29+ - Memory DB: `memory-{name}.sqlite`
30+- Example: `bun run ollama-play --name alice` uses `.spacemolt-bot-alice.json` and `memory-alice.sqlite`
2731
2832 ### Format
2933 - `bun run biome:format`
@@ -47,7 +51,7 @@ Purpose: help coding agents work safely and consistently in this repo.
4751 - `OLLAMA_TIMEOUT_MS` is not present; timeout is configured in `src/config.ts` as `ollamaTimeoutMs`.
4852 - `SPACEMOLT_URL` (default: `wss://game.spacemolt.com/ws`)
4953 - `DEBUG` (string, enable TUI prompt pane when `true`)
50-- `MEMORY_DB` (default: `memory.sqlite`)
54+- `MEMORY_DB` (default: `memory-{name}.sqlite`)
5155
5256 ## Cursor / Copilot Rules
5357 - No Cursor rules found in `.cursor/rules/` or `.cursorrules`.
src/config.ts+34−2
@@ -1,4 +1,36 @@
1+import { parseArgs } from "util";
2+
3+function getInstanceName(): string {
4+ const { values } = parseArgs({
5+ args: process.argv.slice(2),
6+ options: {
7+ name: { type: "string", short: "n" },
8+ },
9+ strict: false,
10+ });
11+
12+ const name = values.name;
13+ if (!name || typeof name !== "string" || name.trim() === "") {
14+ console.error("Error: --name / -n <instance-name> is required");
15+ console.error("Usage: bun run ollama-play --name <instance-name>");
16+ process.exit(1);
17+ }
18+
19+ const trimmed = name.trim();
20+ if (!/^[a-zA-Z0-9_-]+$/.test(trimmed)) {
21+ console.error(
22+ "Error: instance name must contain only letters, numbers, dashes, and underscores",
23+ );
24+ process.exit(1);
25+ }
26+
27+ return trimmed;
28+}
29+
30+const instanceName = getInstanceName();
31+
132 export const config = {
33+ instanceName,
234 ollamaUrl: process.env.OLLAMA_URL ?? "http://localhost:11434",
335 ollamaModel: process.env.OLLAMA_MODEL ?? "qwen3:8b",
436 ollamaTemperature: (() => {
@@ -10,8 +42,8 @@ export const config = {
1042 ollamaThinking: process.env.OLLAMA_THINKING !== "false",
1143 spacemoltUrl: process.env.SPACEMOLT_URL ?? "wss://game.spacemolt.com/ws",
1244 debug: process.env.DEBUG === "true",
13- memoryPath: process.env.MEMORY_DB ?? "memory.sqlite",
14- credentialsFile: ".spacemolt-bot-credentials.json",
45+ memoryPath: process.env.MEMORY_DB ?? `memory-${instanceName}.sqlite`,
46+ credentialsFile: `.spacemolt-bot-${instanceName}.json`,
1547 tickDelayMs: 11000,
1648 maxContextActions: 5,
1749 maxContextEvents: 5,
src/index.ts+164−374
@@ -1,7 +1,5 @@
1-import type { ClientState } from "../client/src/client";
21 import { SpaceMoltClient } from "../client/src/client";
32 import type {
4- CargoItem,
53 ChatMessage,
64 EmpireID,
75 ErrorPayload,
@@ -26,6 +24,20 @@ import {
2624 type WorldSnapshot,
2725 } from "./prompt";
2826 import { Tui } from "./tui";
27+import {
28+ formatAiAction,
29+ formatAiGoal,
30+ formatAiThinking,
31+ formatChatMessage,
32+ formatError,
33+ formatLoggedIn,
34+ formatMotd,
35+ formatOk,
36+ formatRegistered,
37+ formatScanResult,
38+ formatSystemMessage,
39+ formatWelcome,
40+} from "./tui/formatters";
2941
3042 type Credentials = {
3143 username: string;
@@ -51,7 +63,7 @@ const tui = new Tui(config.debug);
5163
5264 const client = new SpaceMoltClient({
5365 url: config.spacemoltUrl,
54- debug: false, //config.debug,
66+ debug: false,
5567 reconnect: true,
5668 });
5769
@@ -68,9 +80,15 @@ let currentGoal: string | null = null;
6880 let lastSystemId: string | null = null;
6981 let lastPoiId: string | null = null;
7082 let lastDocked = false;
83+let inCombat = false;
7184 const MAX_REGISTRATION_RETRIES = 3;
7285 const failedRegistrationNames: string[] = [];
7386
87+// Cache player/ship data since client.state doesn't maintain them
88+let cachedPlayer: typeof client.state.player = null;
89+let cachedShip: typeof client.state.ship = null;
90+let lastCredits: number | null = null;
91+
7492 async function loadCredentials(): Promise<Credentials | null> {
7593 try {
7694 const file = Bun.file(config.credentialsFile);
@@ -92,37 +110,25 @@ async function saveCredentials(
92110 await Bun.write(config.credentialsFile, JSON.stringify(data, null, 2));
93111 }
94112
95-function log(message: string): void {
96- tui.log(message);
97-}
98-
99-function updateStatus(): void {
113+function updateTui(): void {
100114 const state = client.state;
101- if (!state.player || !state.ship) {
102- tui.setStatus("Not logged in");
103- tui.setSidebar("Not logged in.");
104- return;
105- }
106- const statusText = buildStatusText(
107- state,
108- worldSnapshot,
109- travelInProgress,
110- lastTravelTarget,
111- jumpInProgress,
112- lastJumpTarget,
113- currentGoal,
114- );
115- const sidebarText = formatSidebar(
116- state,
117- worldSnapshot,
118- travelInProgress,
119- lastTravelTarget,
120- jumpInProgress,
121- lastJumpTarget,
122- credentials?.personality,
123- );
124- tui.setStatus(statusText);
125- tui.setSidebar(sidebarText);
115+ tui.update({
116+ player: cachedPlayer,
117+ ship: cachedShip,
118+ system: worldSnapshot.system ?? state.system ?? null,
119+ poi: worldSnapshot.poi ?? state.poi ?? null,
120+ base: worldSnapshot.base ?? state.base ?? null,
121+ pois: worldSnapshot.pois ?? [],
122+ nearby: state.nearby ?? [],
123+ personality: credentials?.personality,
124+ tick: state.currentTick,
125+ traveling: travelInProgress,
126+ travelTarget: lastTravelTarget,
127+ jumping: jumpInProgress,
128+ jumpTarget: lastJumpTarget,
129+ goal: currentGoal,
130+ inCombat,
131+ });
126132 }
127133
128134 function saveSnapshot(): void {
@@ -138,7 +144,11 @@ function saveSnapshot(): void {
138144 }
139145
140146 async function runRegistrationFlow(): Promise<void> {
141- log("No credentials found. Asking LLM to create a character...");
147+ tui.log(
148+ formatSystemMessage(
149+ "No credentials found. Asking LLM to create a character...",
150+ ),
151+ );
142152 let attempts = 0;
143153 while (attempts < 3) {
144154 attempts += 1;
@@ -147,9 +157,7 @@ async function runRegistrationFlow(): Promise<void> {
147157 tui.setPrompt(prompt);
148158 const result = await ollama.generateJson<RegistrationChoice>(prompt);
149159 if (result.thinking) {
150- log(
151- `[Thinking] ${result.thinking.slice(0, 200)}${result.thinking.length > 200 ? "..." : ""}`,
152- );
160+ tui.log(formatAiThinking(result.thinking));
153161 }
154162 const username = String(result.json.username ?? "").trim();
155163 const empire = String(result.json.empire ?? "").trim() as EmpireID;
@@ -173,14 +181,22 @@ async function runRegistrationFlow(): Promise<void> {
173181 personality_reason: personalityReason,
174182 };
175183 const personalityInfo = PERSONALITY_ARCHETYPES[personality];
176- log(`Registering new account: ${username} (${empire})`);
177- log(
178- `Chosen personality: ${personalityInfo.emoji} ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
184+ tui.log(
185+ formatSystemMessage(`Registering new account: ${username} (${empire})`),
186+ );
187+ tui.log(
188+ formatSystemMessage(
189+ `Chosen personality: ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
190+ ),
179191 );
180192 client.register(username, empire);
181193 return;
182194 } catch (error) {
183- log(`Registration attempt failed: ${(error as Error).message}`);
195+ tui.log(
196+ formatSystemMessage(
197+ `Registration attempt failed: ${(error as Error).message}`,
198+ ),
199+ );
184200 }
185201 }
186202
@@ -190,7 +206,11 @@ async function runRegistrationFlow(): Promise<void> {
190206 empire: "solarian",
191207 personality: "pragmatist",
192208 };
193- log(`Falling back to account: ${fallback} (solarian, pragmatist)`);
209+ tui.log(
210+ formatSystemMessage(
211+ `Falling back to account: ${fallback} (solarian, pragmatist)`,
212+ ),
213+ );
194214 client.register(fallback, "solarian");
195215 }
196216
@@ -284,14 +304,12 @@ async function startActionLoop(): Promise<void> {
284304 const promptExcerpt = prompt.slice(0, 1000);
285305 const result = await ollama.generateJson(prompt);
286306 if (result.thinking) {
287- log(
288- `[Thinking] ${result.thinking.slice(0, 200)}${result.thinking.length > 200 ? "..." : ""}`,
289- );
307+ tui.log(formatAiThinking(result.thinking));
290308 }
291309 const validation = validateAction(result.json);
292310 if (!validation.ok || !validation.action) {
293311 const message = `Invalid action from LLM: ${validation.error ?? "unknown"}`;
294- log(message);
312+ tui.log(formatSystemMessage(message));
295313 memory.appendEvent("llm_invalid_action", {
296314 error: validation.error,
297315 raw: result.raw,
@@ -309,7 +327,7 @@ async function startActionLoop(): Promise<void> {
309327 const message = target
310328 ? `Invalid action from LLM: Unknown nearby target: ${target}`
311329 : "Invalid action from LLM: Missing target_id";
312- log(message);
330+ tui.log(formatSystemMessage(message));
313331 memory.appendEvent("llm_invalid_action", {
314332 error: message,
315333 raw: result.raw,
@@ -323,6 +341,8 @@ async function startActionLoop(): Promise<void> {
323341 if (client.state.player?.username && goal) {
324342 currentGoal = goal;
325343 memory.setGoal(client.state.player.username, goal);
344+ tui.log(formatAiGoal(goal));
345+ updateTui();
326346 }
327347 memory.appendAction(
328348 actionName,
@@ -338,8 +358,8 @@ async function startActionLoop(): Promise<void> {
338358 lastJumpTarget =
339359 String(validation.action.args?.target_system ?? "").trim() || null;
340360 }
341- const actionLog = dispatchAction(client, validation.action);
342- log(`Action: ${actionLog}`);
361+ dispatchAction(client, validation.action);
362+ tui.log(formatAiAction(actionName, validation.action.args));
343363 memory.appendEvent("action_sent", { action: validation.action });
344364
345365 if (actionName === "travel") {
@@ -349,10 +369,12 @@ async function startActionLoop(): Promise<void> {
349369 } catch (error) {
350370 const message = (error as Error).message;
351371 if (error instanceof OllamaTimeoutError) {
352- log(`LLM timeout: ${message}. Retrying next tick.`);
372+ tui.log(
373+ formatSystemMessage(`LLM timeout: ${message}. Retrying next tick.`),
374+ );
353375 memory.appendEvent("llm_timeout", { message });
354376 } else {
355- log(`Loop error: ${message}`);
377+ tui.log(formatSystemMessage(`Loop error: ${message}`));
356378 memory.appendEvent("loop_error", { message });
357379 }
358380 }
@@ -382,44 +404,6 @@ function sleep(ms: number): Promise<void> {
382404 return new Promise((resolve) => setTimeout(resolve, ms));
383405 }
384406
385-function formatOkPayload(payload: Record<string, unknown>): string {
386- if (payload.action) {
387- return `OK ${payload.action}`;
388- }
389- const summary = summarizeOkPayload(payload);
390- if (summary) return `OK ${summary}`;
391- return `OK ${safeJson(payload)}`;
392-}
393-
394-function safeJson(value: unknown): string {
395- try {
396- return JSON.stringify(value);
397- } catch {
398- return "[unserializable]";
399- }
400-}
401-
402-function summarizeOkPayload(payload: Record<string, unknown>): string | null {
403- if (Array.isArray(payload.pois) && payload.pois.length > 0) {
404- const system = payload.system as { id?: string; name?: string } | undefined;
405- const systemLabel =
406- system?.name || system?.id ? ` for ${system?.name ?? system?.id}` : "";
407- return `system${systemLabel} with ${payload.pois.length} POIs`;
408- }
409- if (payload.poi && typeof payload.poi === "object") {
410- const poi = payload.poi as { id?: string; name?: string; type?: string };
411- return `poi ${poi.name ?? poi.id ?? ""}${poi.type ? ` (${poi.type})` : ""}`.trim();
412- }
413- if (payload.base && typeof payload.base === "object") {
414- const base = payload.base as { id?: string; name?: string };
415- return `base ${base.name ?? base.id ?? ""}`.trim();
416- }
417- if (payload.version) {
418- return `version ${String(payload.version)}`;
419- }
420- return null;
421-}
422-
423407 function shutdown(): void {
424408 try {
425409 client.disconnect();
@@ -435,12 +419,12 @@ process.on("SIGINT", shutdown);
435419 process.on("SIGTERM", shutdown);
436420
437421 client.on<WelcomePayload>("welcome", async (data) => {
438- log(`Welcome: v${data.version} (tick ${data.tick_rate}s)`);
439- if (data.motd) log(`MOTD: ${data.motd}`);
422+ tui.log(formatWelcome(data));
423+ if (data.motd) tui.log(formatMotd(data.motd));
440424 memory.appendEvent("welcome", data);
441425
442426 if (credentials) {
443- log(`Auto-login as ${credentials.username}`);
427+ tui.log(formatSystemMessage(`Auto-login as ${credentials.username}`));
444428 client.login(credentials.username, credentials.token);
445429 } else {
446430 await runRegistrationFlow();
@@ -462,16 +446,24 @@ client.on<RegisteredPayload>("registered", async (data) => {
462446 token: data.token,
463447 personality: pendingRegistration.personality,
464448 };
465- log(`Registered. Saved credentials for ${pendingRegistration.username}`);
449+ tui.log(formatRegistered(data));
466450 pendingRegistration = null;
467451 } else {
468- log("Registered but no pending registration found.");
452+ tui.log(
453+ formatSystemMessage("Registered but no pending registration found."),
454+ );
469455 }
470456 });
471457
472458 client.on<LoggedInPayload>("logged_in", (data) => {
473- log(`Logged in as ${data.player.username} (${data.player.empire})`);
459+ tui.log(formatLoggedIn(data));
474460 memory.appendEvent("logged_in", data);
461+
462+ // Cache player and ship data
463+ cachedPlayer = data.player;
464+ cachedShip = data.ship;
465+ lastCredits = data.player.credits;
466+
475467 worldSnapshot.system = data.system;
476468 worldSnapshot.poi = data.poi;
477469 lastSystemId = data.player.current_system ?? null;
@@ -483,13 +475,13 @@ client.on<LoggedInPayload>("logged_in", (data) => {
483475 if (data.player.docked_at_base) {
484476 client.getBase();
485477 }
486- updateStatus();
478+ updateTui();
487479 saveSnapshot();
488480 startActionLoop();
489481 });
490482
491483 client.on<ErrorPayload>("error", (data) => {
492- log(`Error [${data.code}] ${data.message}`);
484+ tui.log(formatError(data));
493485 memory.appendEvent("error", data);
494486 if (data.code === "username_taken" && pendingRegistration) {
495487 if (pendingRegistration.username) {
@@ -497,13 +489,25 @@ client.on<ErrorPayload>("error", (data) => {
497489 }
498490 if (registrationRetries < MAX_REGISTRATION_RETRIES) {
499491 registrationRetries += 1;
500- log("Username taken. Requesting a new registration name...");
492+ tui.log(
493+ formatSystemMessage(
494+ "Username taken. Requesting a new registration name...",
495+ ),
496+ );
501497 pendingRegistration = null;
502498 runRegistrationFlow();
503499 } else {
504- log("Username taken repeatedly. Falling back to random name.");
500+ tui.log(
501+ formatSystemMessage(
502+ "Username taken repeatedly. Falling back to random name.",
503+ ),
504+ );
505505 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
506- pendingRegistration = { username: fallback, empire: "solarian" };
506+ pendingRegistration = {
507+ username: fallback,
508+ empire: "solarian",
509+ personality: "pragmatist",
510+ };
507511 client.register(fallback, "solarian");
508512 }
509513 }
@@ -511,30 +515,61 @@ client.on<ErrorPayload>("error", (data) => {
511515
512516 client.on<StateUpdatePayload>("state_update", (data) => {
513517 memory.appendEvent("state_update", data);
514- refreshSnapshotForLocation(data.player);
515- updateStatus();
516- saveSnapshot();
517- if (data.in_combat) {
518- log(
519- `IN COMBAT: Hull ${data.ship.hull}/${data.ship.max_hull} Shield ${data.ship.shield}/${data.ship.max_shield}`,
520- );
518+
519+ // Update cached player and ship data (only if provided)
520+ if (data.player) {
521+ cachedPlayer = data.player;
522+ }
523+ if (data.ship) {
524+ cachedShip = data.ship;
521525 }
526+
527+ if (data.player) {
528+ refreshSnapshotForLocation(data.player);
529+
530+ // Log state update if significant (only when credits change)
531+ const creditsChanged =
532+ lastCredits !== null && data.player.credits !== lastCredits;
533+ if (creditsChanged) {
534+ const diff = data.player.credits - (lastCredits ?? 0);
535+ const sign = diff > 0 ? "+" : "";
536+ tui.log(
537+ formatSystemMessage(`Credits: ${data.player.credits} (${sign}${diff})`),
538+ );
539+ lastCredits = data.player.credits;
540+ }
541+ }
542+
543+ // Track combat state changes
544+ const wasInCombat = inCombat;
545+ inCombat = data.in_combat ?? false;
546+
547+ // Log combat state changes
548+ if (inCombat && !wasInCombat) {
549+ tui.log(formatSystemMessage("COMBAT STARTED"));
550+ } else if (!inCombat && wasInCombat) {
551+ tui.log(formatSystemMessage("Combat ended"));
552+ }
553+
554+ updateTui();
555+ saveSnapshot();
522556 });
523557
524558 client.on<ChatMessage>("chat_message", (data) => {
525- log(`[${data.channel}] ${data.sender}: ${data.content}`);
559+ tui.log(formatChatMessage(data));
526560 memory.appendEvent("chat_message", data);
527561 });
528562
529563 client.on<ScanResultPayload>("scan_result", (data) => {
530- log(`Scan result: ${safeJson(data)}`);
564+ tui.log(formatScanResult(data));
531565 memory.appendEvent("scan_result", data);
532566 });
533567
534568 client.on("ok", (data: Record<string, unknown>) => {
535- log(formatOkPayload(data));
569+ tui.log(formatOk(data));
536570 memory.appendEvent("ok", data);
537571 updateWorldSnapshotFromOk(data);
572+
538573 const action = typeof data.action === "string" ? data.action : null;
539574 if (action === "travel") {
540575 travelInProgress = true;
@@ -554,32 +589,46 @@ client.on("ok", (data: Record<string, unknown>) => {
554589 client.getSystem();
555590 client.getPOI();
556591 }
592+ updateTui();
557593 });
558594
559595 client.on("version_info", (data: Record<string, unknown>) => {
560- log(`Version info: ${safeJson(data)}`);
596+ const version = String(data.version ?? "unknown");
597+ tui.log(formatSystemMessage(`Version: ${version}`));
561598 memory.appendEvent("version_info", data);
562599 });
563600
564601 credentials = await loadCredentials();
565602
603+console.log(`Instance: ${config.instanceName}`);
604+console.log(`Credentials: ${config.credentialsFile}`);
605+console.log(`Memory DB: ${config.memoryPath}`);
606+
566607 // Force re-registration if personality is missing
567608 if (credentials && !credentials.personality) {
568- log("Credentials missing personality field - forcing re-registration");
609+ tui.log(
610+ formatSystemMessage(
611+ "Credentials missing personality field - forcing re-registration",
612+ ),
613+ );
569614 try {
570- await Bun.write(config.credentialsFile, ""); // Clear file
615+ await Bun.write(config.credentialsFile, "");
571616 const file = Bun.file(config.credentialsFile);
572617 if (await file.exists()) {
573618 await file.remove?.();
574619 }
575620 } catch (error) {
576- log(`Failed to delete credentials: ${(error as Error).message}`);
621+ tui.log(
622+ formatSystemMessage(
623+ `Failed to delete credentials: ${(error as Error).message}`,
624+ ),
625+ );
577626 }
578627 credentials = null;
579628 }
580629
581630 await client.connect();
582-updateStatus();
631+updateTui();
583632
584633 function updateWorldSnapshotFromOk(data: Record<string, unknown>): void {
585634 if (data.system && typeof data.system === "object") {
@@ -595,262 +644,3 @@ function updateWorldSnapshotFromOk(data: Record<string, unknown>): void {
595644 worldSnapshot.base = data.base as WorldSnapshot["base"];
596645 }
597646 }
598-
599-const SIDEBAR_WIDTH = 30;
600-const SIDEBAR_CONTENT_WIDTH = SIDEBAR_WIDTH - 2;
601-
602-function buildStatusText(
603- state: ClientState,
604- snapshot: WorldSnapshot,
605- traveling: boolean,
606- travelTargetId: string | null,
607- jumping: boolean,
608- jumpTargetId: string | null,
609- goal: string | null,
610-): string {
611- if (!state.player || !state.ship) return "Not logged in";
612- const goalText = goal?.trim() ? ` | Goal: ${goal.trim()}` : "";
613- if (jumping) {
614- const destination = resolveSystemName(jumpTargetId, snapshot, state);
615- return `Jumping to ${destination}${goalText}`;
616- }
617- if (traveling) {
618- const destination = resolvePoiName(travelTargetId, snapshot, state);
619- return `Traveling to ${destination}${goalText}`;
620- }
621- if (state.player.docked_at_base) return `Docked${goalText}`;
622- const currentPoi = resolvePoiName(state.player.current_poi, snapshot, state);
623- return `At ${currentPoi}${goalText}`;
624-}
625-
626-function formatSidebar(
627- state: ClientState,
628- snapshot: WorldSnapshot,
629- traveling: boolean,
630- travelTargetId: string | null,
631- jumping: boolean,
632- jumpTargetId: string | null,
633- personality?: PersonalityType,
634-): string {
635- if (!state.player || !state.ship) return "Not logged in.";
636-
637- const width = SIDEBAR_CONTENT_WIDTH;
638- const lines: string[] = [];
639- const pushSection = (title: string, sectionLines: string[]): void => {
640- if (lines.length) lines.push("");
641- const titleText = truncate(`== ${title} ==`, width);
642- lines.push(`{cyan-fg}${titleText}{/cyan-fg}`);
643- for (const line of sectionLines) {
644- const truncated = truncate(line, width);
645- const colored = colorizeLabel(truncated);
646- lines.push(styleLine(colored));
647- }
648- };
649-
650- const system = snapshot.system ?? state.system;
651- const poi = snapshot.poi ?? state.poi;
652- const base = snapshot.base ?? state.base;
653- const pois = snapshot.pois ?? [];
654-
655- const playerLines = [
656- formatLine("Name", state.player.username, width),
657- formatLine("Empire", state.player.empire, width),
658- ];
659- if (personality) {
660- const personalityInfo = PERSONALITY_ARCHETYPES[personality];
661- playerLines.push(
662- formatLine(
663- "Role",
664- `${personalityInfo.emoji} ${personalityInfo.name}`,
665- width,
666- ),
667- );
668- }
669- playerLines.push(
670- formatLine("Credits", String(state.player.credits), width),
671- formatLine("Docked", state.player.docked_at_base ? "Y" : "N", width),
672- formatLine("Tick", String(state.currentTick), width),
673- );
674-
675- pushSection("Player", playerLines);
676-
677- pushSection("Ship", [
678- formatLine("Hull", `${state.ship.hull}/${state.ship.max_hull}`, width),
679- formatLine(
680- "Shield",
681- `${state.ship.shield}/${state.ship.max_shield}`,
682- width,
683- ),
684- formatLine("Fuel", `${state.ship.fuel}/${state.ship.max_fuel}`, width),
685- formatLine(
686- "Cargo",
687- `${state.ship.cargo_used}/${state.ship.cargo_capacity}`,
688- width,
689- ),
690- ]);
691-
692- const locationLines = [
693- formatLine(
694- "System",
695- system?.name ?? state.player.current_system ?? "-",
696- width,
697- ),
698- formatLine("POI", poi?.name ?? state.player.current_poi ?? "-", width),
699- formatLine("Travel", traveling ? "Y" : "N", width),
700- formatLine("Jump", jumping ? "Y" : "N", width),
701- ];
702- if (traveling) {
703- locationLines.push(
704- formatLine(
705- "Dest",
706- resolvePoiName(travelTargetId, snapshot, state),
707- width,
708- ),
709- );
710- }
711- if (jumping) {
712- locationLines.push(
713- formatLine(
714- "JumpDest",
715- resolveSystemName(jumpTargetId, snapshot, state),
716- width,
717- ),
718- );
719- }
720- pushSection("Location", locationLines);
721-
722- const poiLines = formatPoiLines(pois, system?.pois, width);
723- pushSection("POIs", poiLines);
724-
725- const cargoLines = formatCargoLines(state.ship.cargo ?? [], width);
726- pushSection("Cargo", cargoLines);
727-
728- const baseLines = formatBaseLines(base, width);
729- pushSection("Base", baseLines);
730-
731- const nearbyLines = formatNearbyLines(state.nearby ?? [], width);
732- pushSection("Nearby", nearbyLines);
733-
734- return lines.join("\n");
735-}
736-
737-function formatLine(label: string, value: string, _width: number): string {
738- return `${label}: ${value}`;
739-}
740-
741-function truncate(value: string, width: number): string {
742- if (value.length <= width) return value;
743- if (width <= 3) return value.slice(0, width);
744- return `${value.slice(0, width - 3)}...`;
745-}
746-
747-function colorizeLabel(line: string): string {
748- const index = line.indexOf(":");
749- if (index <= 0) return line;
750- const label = line.slice(0, index);
751- const rest = line.slice(index);
752- return `{yellow-fg}${label}{/yellow-fg}${rest}`;
753-}
754-
755-function styleLine(line: string): string {
756- if (line.includes("{")) return line;
757- if (line === "none" || line === "-") return `{gray-fg}${line}{/gray-fg}`;
758- return line;
759-}
760-
761-function resolveSystemName(
762- systemId: string | null | undefined,
763- snapshot: WorldSnapshot,
764- state: ClientState,
765-): string {
766- if (!systemId) return "Unknown";
767- if (snapshot.system?.id === systemId && snapshot.system.name)
768- return snapshot.system.name;
769- if (state.system?.id === systemId && state.system.name)
770- return state.system.name;
771- return systemId;
772-}
773-
774-function resolvePoiName(
775- poiId: string | null | undefined,
776- snapshot: WorldSnapshot,
777- state: ClientState,
778-): string {
779- if (!poiId) return "Unknown";
780- const snapshotPoi = snapshot.pois?.find((entry) => entry.id === poiId);
781- if (snapshotPoi?.name) return snapshotPoi.name;
782- if (snapshot.poi?.id === poiId && snapshot.poi.name) return snapshot.poi.name;
783- if (state.poi?.id === poiId && state.poi.name) return state.poi.name;
784- return poiId;
785-}
786-
787-function formatPoiLines(
788- pois: WorldSnapshot["pois"],
789- systemPois: string[] | undefined,
790- width: number,
791-): string[] {
792- if (pois && pois.length > 0) {
793- const maxItems = 5;
794- const lines = pois
795- .slice(0, maxItems)
796- .map((poi) => truncate(poi.name || poi.id, width));
797- if (pois.length > maxItems) {
798- lines.push(truncate(`+${pois.length - maxItems} more`, width));
799- }
800- return lines;
801- }
802- if (systemPois && systemPois.length > 0) {
803- const maxItems = 5;
804- const lines = systemPois
805- .slice(0, maxItems)
806- .map((poiId) => truncate(poiId, width));
807- if (systemPois.length > maxItems) {
808- lines.push(truncate(`+${systemPois.length - maxItems} more`, width));
809- }
810- return lines;
811- }
812- return ["none"];
813-}
814-
815-function formatCargoLines(
816- cargo: CargoItem[] | undefined,
817- width: number,
818-): string[] {
819- if (!cargo || cargo.length === 0) return ["none"];
820- const maxItems = 6;
821- const lines = cargo
822- .slice(0, maxItems)
823- .map((item) => truncate(`${item.item_id} x${item.quantity}`, width));
824- if (cargo.length > maxItems) {
825- lines.push(truncate(`+${cargo.length - maxItems} more`, width));
826- }
827- return lines;
828-}
829-
830-function formatBaseLines(base: WorldSnapshot["base"], width: number): string[] {
831- if (!base) return ["none"];
832- const services = Object.keys(base.services)
833- .filter((key) => (base.services as Record<string, boolean>)[key])
834- .join(", ");
835- return [
836- formatLine("Name", base.name || base.id, width),
837- formatLine("Services", services || "none", width),
838- ];
839-}
840-
841-function formatNearbyLines(
842- nearby: ClientState["nearby"],
843- width: number,
844-): string[] {
845- if (!nearby || nearby.length === 0) return ["none"];
846- const maxItems = 6;
847- const lines = [formatLine("Count", String(nearby.length), width)];
848- for (const entry of nearby.slice(0, maxItems)) {
849- const name = entry.username ?? entry.player_id ?? "unknown";
850- lines.push(truncate(name, width));
851- }
852- if (nearby.length > maxItems) {
853- lines.push(truncate(`+${nearby.length - maxItems} more`, width));
854- }
855- return lines;
856-}
src/tui-screenshot.ts+161−0
@@ -0,0 +1,161 @@
1+// Simple script to capture TUI state to a file for debugging
2+
3+import { SpaceMoltClient } from "../client/src/client";
4+import type {
5+ LoggedInPayload,
6+ StateUpdatePayload,
7+ WelcomePayload,
8+} from "../client/src/types";
9+import { config } from "./config";
10+import { renderLocationPanel } from "./tui/panels/location";
11+import { renderPlayerShipPanel } from "./tui/panels/player-ship";
12+import { renderTacticalPanel } from "./tui/panels/tactical";
13+import { renderWorldInfoPanel } from "./tui/panels/world-info";
14+
15+const client = new SpaceMoltClient({
16+ url: config.spacemoltUrl,
17+ debug: false,
18+ reconnect: false,
19+});
20+
21+type Credentials = {
22+ username: string;
23+ token: string;
24+};
25+
26+let credentials: Credentials | null = null;
27+let cachedPlayer: any = null;
28+let cachedShip: any = null;
29+const worldSnapshot: any = {};
30+
31+async function loadCredentials(): Promise<Credentials | null> {
32+ try {
33+ const file = Bun.file(config.credentialsFile);
34+ if (await file.exists()) {
35+ return (await file.json()) as Credentials;
36+ }
37+ } catch {
38+ return null;
39+ }
40+ return null;
41+}
42+
43+function dumpTuiState() {
44+ console.log("\n" + "=".repeat(80));
45+ console.log("TUI STATE DUMP");
46+ console.log("=".repeat(80));
47+ console.log("\n--- CACHED DATA ---");
48+ console.log("Player:", JSON.stringify(cachedPlayer, null, 2));
49+ console.log("Ship:", JSON.stringify(cachedShip, null, 2));
50+ console.log("World Snapshot:", JSON.stringify(worldSnapshot, null, 2));
51+
52+ console.log("\n--- PANEL RENDERS ---");
53+ console.log("\n[Player/Ship Panel]");
54+ console.log(
55+ renderPlayerShipPanel({
56+ player: cachedPlayer,
57+ ship: cachedShip,
58+ personality: undefined,
59+ tick: 0,
60+ }),
61+ );
62+
63+ console.log("\n[World Info Panel]");
64+ console.log(
65+ renderWorldInfoPanel({
66+ base: worldSnapshot.base ?? null,
67+ }),
68+ );
69+
70+ console.log("\n[Location Panel]");
71+ console.log(
72+ renderLocationPanel({
73+ player: cachedPlayer,
74+ system: worldSnapshot.system ?? null,
75+ poi: worldSnapshot.poi ?? null,
76+ pois: worldSnapshot.pois ?? [],
77+ traveling: false,
78+ travelTarget: null,
79+ jumping: false,
80+ jumpTarget: null,
81+ }),
82+ );
83+
84+ console.log("\n[Tactical Panel]");
85+ console.log(
86+ renderTacticalPanel({
87+ inCombat: false,
88+ combatTarget: undefined,
89+ nearby: [],
90+ }),
91+ );
92+
93+ console.log("\n" + "=".repeat(80));
94+}
95+
96+client.on<WelcomePayload>("welcome", async (data) => {
97+ console.log(`Connected to SpaceMolt v${data.version}`);
98+
99+ if (credentials) {
100+ console.log(`Logging in as ${credentials.username}`);
101+ client.login(credentials.username, credentials.token);
102+ } else {
103+ console.log("No credentials found");
104+ process.exit(1);
105+ }
106+});
107+
108+client.on<LoggedInPayload>("logged_in", (data) => {
109+ console.log(`Logged in as ${data.player.username}`);
110+
111+ cachedPlayer = data.player;
112+ cachedShip = data.ship;
113+ worldSnapshot.system = data.system;
114+ worldSnapshot.poi = data.poi;
115+
116+ client.getSystem();
117+ client.getPOI();
118+ if (data.player.docked_at_base) {
119+ client.getBase();
120+ }
121+
122+ // Wait a bit for data to arrive, then dump state
123+ setTimeout(() => {
124+ dumpTuiState();
125+ process.exit(0);
126+ }, 3000);
127+});
128+
129+client.on<StateUpdatePayload>("state_update", (data) => {
130+ if (data.player) {
131+ cachedPlayer = data.player;
132+ }
133+ if (data.ship) {
134+ cachedShip = data.ship;
135+ }
136+});
137+
138+client.on("ok", (data: Record<string, unknown>) => {
139+ if (data.system && typeof data.system === "object") {
140+ worldSnapshot.system = data.system;
141+ }
142+ if (Array.isArray(data.pois)) {
143+ worldSnapshot.pois = data.pois;
144+ }
145+ if (data.poi && typeof data.poi === "object") {
146+ worldSnapshot.poi = data.poi;
147+ }
148+ if (data.base && typeof data.base === "object") {
149+ worldSnapshot.base = data.base;
150+ }
151+});
152+
153+credentials = await loadCredentials();
154+
155+if (!credentials) {
156+ console.log("No credentials file found. Please run the main app first.");
157+ process.exit(1);
158+}
159+
160+console.log("Connecting to SpaceMolt...");
161+await client.connect();
src/tui.ts+2−216
@@ -1,216 +1,2 @@
1-import blessed from "blessed";
2-
Cut short: this commit's diff is over 1000 lines.
src/tui/colors.ts+63−0
Cut short: this commit's diff is over 1000 lines.
src/tui/formatters.ts+319−0
Cut short: this commit's diff is over 1000 lines.
src/tui/index.ts+389−0
Cut short: this commit's diff is over 1000 lines.
src/tui/layout.ts+148−0
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/location.ts+118−0
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/log.ts+154−0
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/player-ship.ts+76−0
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/tactical.ts+100−0
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/world-info.ts+90−0
Cut short: this commit's diff is over 1000 lines.
src/tui/utils.ts+38−0
Cut short: this commit's diff is over 1000 lines.