xonecas.io
5875
Os

ollama-space-molt-player / commit cf1e469

refactor: modularize output system and enhance session configuration

xonecas2026-02-01 cf1e469dafc68cb18a7515f5fede9fe5b28654ca parent 9730ef0

7 files changed

AGENTS.md+14−0
@@ -29,6 +29,20 @@ Purpose: help coding agents work safely and consistently in this repo.
2929 - Memory DB: `memory-{name}.sqlite`
3030 - Example: `bun run ollama-play --name alice` uses `.spacemolt-bot-alice.json` and `memory-alice.sqlite`
3131
32+### Run in non-interactive mode (for testing/debugging)
33+- `bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]`
34+- Runs without the blessed TUI; output is written to log files instead.
35+- Example: `bun run ollama-play --name test-bot --non-interactive --max-ticks 100`
36+
37+**Log files created:**
38+- `ui-{name}.log` - UI output with timestamps (game events, AI actions, state updates)
39+- `debug-{name}.log` - Debug information (full LLM prompts, raw responses, thinking)
40+
41+**Flags:**
42+- `--non-interactive` - Enable headless mode (no TUI, output to log files)
43+- `--max-ticks <number>` - Stop after N game ticks (optional; runs indefinitely if not set)
44+- Logs are truncated on each run (fresh logs per execution)
45+
3246 ### Format
3347 - `bun run biome:format`
3448
src/config.ts+30−8
@@ -1,14 +1,16 @@
11 import { parseArgs } from "node:util";
22
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- });
3+const { values } = parseArgs({
4+ args: process.argv.slice(2),
5+ options: {
6+ name: { type: "string", short: "n" },
7+ "non-interactive": { type: "boolean" },
8+ "max-ticks": { type: "string" },
9+ },
10+ strict: false,
11+});
1112
13+function getInstanceName(): string {
1214 const name = values.name;
1315 if (!name || typeof name !== "string" || name.trim() === "") {
1416 console.error("Error: --name / -n <instance-name> is required");
@@ -27,10 +29,28 @@ function getInstanceName(): string {
2729 return trimmed;
2830 }
2931
32+function parseMaxTicks(raw: unknown): number | null {
33+ if (raw === undefined) return null;
34+ if (typeof raw !== "string" || raw.trim() === "") {
35+ console.error("Error: --max-ticks requires a numeric value");
36+ process.exit(1);
37+ }
38+ const value = Number(raw);
39+ if (!Number.isFinite(value) || value <= 0) {
40+ console.error("Error: --max-ticks must be a positive number");
41+ process.exit(1);
42+ }
43+ return Math.floor(value);
44+}
45+
3046 const instanceName = getInstanceName();
47+const nonInteractive = values["non-interactive"] === true;
48+const maxTicks = parseMaxTicks(values["max-ticks"]);
3149
3250 export const config = {
3351 instanceName,
52+ nonInteractive,
53+ maxTicks,
3454 ollamaUrl: process.env.OLLAMA_URL ?? "http://localhost:11434",
3555 ollamaModel: process.env.OLLAMA_MODEL ?? "qwen3:8b",
3656 ollamaTemperature: (() => {
@@ -44,6 +64,8 @@ export const config = {
4464 debug: process.env.DEBUG === "true",
4565 memoryPath: process.env.MEMORY_DB ?? `memory-${instanceName}.sqlite`,
4666 credentialsFile: `.spacemolt-bot-${instanceName}.json`,
67+ uiLogPath: `ui-${instanceName}.log`,
68+ debugLogPath: `debug-${instanceName}.log`,
4769 tickDelayMs: 11000,
4870 maxContextActions: 5,
4971 maxContextEvents: 5,
src/index.ts+77−39
@@ -11,6 +11,9 @@ import { config } from "./config";
1111 import { GameState } from "./game-state";
1212 import { MemoryStore } from "./memory";
1313 import { OllamaAgent, OllamaTimeoutError } from "./ollama";
14+import { FileLoggerOutput } from "./output/file-logger-output";
15+import { TuiOutput } from "./output/tui-output";
16+import type { OutputInterface } from "./output-interface";
1417 import { buildActionPrompt, type WorldSnapshot } from "./prompt";
1518 import { runRegistrationFlow } from "./registration";
1619 import {
@@ -26,7 +29,6 @@ import {
2629 formatWelcome,
2730 type OkContext,
2831 } from "./tui/formatters";
29-import { Tui } from "./tui/index";
3032 import type { Credentials, PersonalityType } from "./types";
3133 import { detectRepetition, isNearbyTarget, sleep } from "./utils";
3234
@@ -38,7 +40,12 @@ const ollama = new OllamaAgent(
3840 config.ollamaTemperature,
3941 config.ollamaThinking,
4042 );
41-const tui = new Tui(config.debug);
43+const output: OutputInterface = config.nonInteractive
44+ ? new FileLoggerOutput({
45+ uiLogPath: config.uiLogPath,
46+ debugLogPath: config.debugLogPath,
47+ })
48+ : new TuiOutput(config.debug);
4249
4350 const client = new SpaceMoltClient({
4451 url: config.spacemoltUrl,
@@ -49,6 +56,8 @@ const client = new SpaceMoltClient({
4956 const gameState = new GameState();
5057 let actionLoopRunning = false;
5158 const REPETITION_THRESHOLD = 3;
59+let maxTicksStart: number | null = null;
60+let fallbackTickCount = 0;
5261
5362 async function loadCredentials(): Promise<Credentials | null> {
5463 try {
@@ -71,9 +80,9 @@ async function saveCredentials(
7180 await Bun.write(config.credentialsFile, JSON.stringify(data, null, 2));
7281 }
7382
74-function updateTui(): void {
83+function updateOutput(): void {
7584 const state = client.state;
76- tui.update({
85+ output.update({
7786 player: gameState.cachedPlayer,
7887 ship: gameState.cachedShip,
7988 system: gameState.worldSnapshot.system ?? state.system ?? null,
@@ -92,6 +101,20 @@ function updateTui(): void {
92101 });
93102 }
94103
104+function shouldStopForMaxTicks(): boolean {
105+ if (config.maxTicks === null) return false;
106+ const currentTick = client.state.currentTick;
107+ if (typeof currentTick === "number" && maxTicksStart !== null) {
108+ return currentTick - maxTicksStart > config.maxTicks;
109+ }
110+ if (typeof currentTick === "number" && maxTicksStart === null) {
111+ maxTicksStart = currentTick;
112+ return false;
113+ }
114+ fallbackTickCount += 1;
115+ return fallbackTickCount > config.maxTicks;
116+}
117+
95118 function saveSnapshot(): void {
96119 memory.saveSnapshot({
97120 tick: client.state.currentTick,
@@ -163,6 +186,15 @@ async function startActionLoop(): Promise<void> {
163186 await sleep(config.tickDelayMs);
164187 continue;
165188 }
189+ if (shouldStopForMaxTicks()) {
190+ output.log(
191+ formatSystemMessage(
192+ `Max ticks reached (${config.maxTicks}). Shutting down.`,
193+ ),
194+ );
195+ shutdown();
196+ break;
197+ }
166198 const recentHistory = memory.getRecentHistory(
167199 config.maxContextActions,
168200 config.maxContextEvents,
@@ -181,17 +213,20 @@ async function startActionLoop(): Promise<void> {
181213 repetitionWarning,
182214 });
183215
184- tui.setPrompt(prompt);
216+ output.setPrompt(prompt);
217+ output.logDebug("LLM_PROMPT", prompt);
185218
186219 const promptExcerpt = prompt.slice(0, 1000);
187220 const result = await ollama.generateJson(prompt);
221+ output.logDebug("LLM_RESPONSE_RAW", result.raw);
188222 if (result.thinking) {
189- tui.log(formatAiThinking(result.thinking));
223+ output.log(formatAiThinking(result.thinking));
224+ output.logDebug("LLM_THINKING", result.thinking);
190225 }
191226 const validation = validateAction(result.json);
192227 if (!validation.ok || !validation.action) {
193228 const message = `Invalid action from LLM: ${validation.error ?? "unknown"}`;
194- tui.log(formatSystemMessage(message));
229+ output.log(formatSystemMessage(message));
195230 memory.appendEvent("llm_invalid_action", {
196231 error: validation.error,
197232 raw: result.raw,
@@ -209,7 +244,7 @@ async function startActionLoop(): Promise<void> {
209244 const message = target
210245 ? `Invalid action from LLM: Unknown nearby target: ${target}`
211246 : "Invalid action from LLM: Missing target_id";
212- tui.log(formatSystemMessage(message));
247+ output.log(formatSystemMessage(message));
213248 memory.appendEvent("llm_invalid_action", {
214249 error: message,
215250 raw: result.raw,
@@ -223,8 +258,8 @@ async function startActionLoop(): Promise<void> {
223258 if (client.state.player?.username && goal) {
224259 gameState.currentGoal = goal;
225260 memory.setGoal(client.state.player.username, goal);
226- tui.log(formatAiGoal(goal));
227- updateTui();
261+ output.log(formatAiGoal(goal));
262+ updateOutput();
228263 }
229264 memory.appendAction(
230265 actionName,
@@ -241,7 +276,7 @@ async function startActionLoop(): Promise<void> {
241276 String(validation.action.args?.target_system ?? "").trim() || null;
242277 }
243278 dispatchAction(client, validation.action);
244- tui.log(formatAiAction(actionName, validation.action.args));
279+ output.log(formatAiAction(actionName, validation.action.args));
245280 memory.appendEvent("action_sent", { action: validation.action });
246281
247282 if (actionName === "travel") {
@@ -251,12 +286,12 @@ async function startActionLoop(): Promise<void> {
251286 } catch (error) {
252287 const message = (error as Error).message;
253288 if (error instanceof OllamaTimeoutError) {
254- tui.log(
289+ output.log(
255290 formatSystemMessage(`LLM timeout: ${message}. Retrying next tick.`),
256291 );
257292 memory.appendEvent("llm_timeout", { message });
258293 } else {
259- tui.log(formatSystemMessage(`Loop error: ${message}`));
294+ output.log(formatSystemMessage(`Loop error: ${message}`));
260295 memory.appendEvent("loop_error", { message });
261296 }
262297 }
@@ -273,11 +308,11 @@ function shutdown(): void {
273308 } catch {
274309 // ignore
275310 }
276- tui.destroy();
311+ output.destroy();
277312 process.exit(0);
278313 }
279314
280-tui.onExit(shutdown);
315+output.onExit(shutdown);
281316 process.on("SIGINT", shutdown);
282317 process.on("SIGTERM", shutdown);
283318
@@ -287,18 +322,18 @@ client.on("raw_message", (data: { type: string; payload: unknown }) => {
287322 });
288323
289324 client.on<WelcomePayload>("welcome", async (data) => {
290- tui.log(formatWelcome(data));
291- if (data.motd) tui.log(formatMotd(data.motd));
325+ output.log(formatWelcome(data));
326+ if (data.motd) output.log(formatMotd(data.motd));
292327 memory.appendEvent("welcome", data);
293328
294329 if (gameState.credentials) {
295- tui.log(
330+ output.log(
296331 formatSystemMessage(`Auto-login as ${gameState.credentials.username}`),
297332 );
298333 client.login(gameState.credentials.username, gameState.credentials.token);
299334 } else {
300335 gameState.pendingRegistration = await runRegistrationFlow(
301- tui,
336+ output,
302337 ollama,
303338 client,
304339 gameState.failedRegistrationNames,
@@ -307,7 +342,7 @@ client.on<WelcomePayload>("welcome", async (data) => {
307342 });
308343
309344 client.on<ErrorPayload>("error", (data) => {
310- tui.log(formatError(data));
345+ output.log(formatError(data));
311346 memory.appendEvent("error", data);
312347 if (data.code === "username_taken" && gameState.pendingRegistration) {
313348 if (gameState.pendingRegistration.username) {
@@ -317,14 +352,14 @@ client.on<ErrorPayload>("error", (data) => {
317352 }
318353 if (gameState.registrationRetries < gameState.MAX_REGISTRATION_RETRIES) {
319354 gameState.registrationRetries += 1;
320- tui.log(
355+ output.log(
321356 formatSystemMessage(
322357 "Username taken. Requesting a new registration name...",
323358 ),
324359 );
325360 gameState.pendingRegistration = null;
326361 runRegistrationFlow(
327- tui,
362+ output,
328363 ollama,
329364 client,
330365 gameState.failedRegistrationNames,
@@ -332,7 +367,7 @@ client.on<ErrorPayload>("error", (data) => {
332367 gameState.pendingRegistration = choice;
333368 });
334369 } else {
335- tui.log(
370+ output.log(
336371 formatSystemMessage(
337372 "Username taken repeatedly. Falling back to random name.",
338373 ),
@@ -371,7 +406,7 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
371406 token: token,
372407 personality: gameState.pendingRegistration.personality,
373408 };
374- tui.log(
409+ output.log(
375410 formatSystemMessage(
376411 `Credentials saved for ${gameState.pendingRegistration.username}`,
377412 ),
@@ -383,7 +418,7 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
383418 initializeSessionFromStateUpdate(data);
384419 }
385420 } catch (err) {
386- tui.log(
421+ output.log(
387422 formatSystemMessage(
388423 `Failed to save credentials: ${(err as Error).message}`,
389424 ),
@@ -422,7 +457,7 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
422457 if (creditsChanged) {
423458 const diff = data.player.credits - (gameState.lastCredits ?? 0);
424459 const sign = diff > 0 ? "+" : "";
425- tui.log(
460+ output.log(
426461 formatSystemMessage(`Credits: ${data.player.credits} (${sign}${diff})`),
427462 );
428463 gameState.lastCredits = data.player.credits;
@@ -435,22 +470,22 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
435470
436471 // Log combat state changes
437472 if (gameState.inCombat && !wasInCombat) {
438- tui.log(formatSystemMessage("COMBAT STARTED"));
473+ output.log(formatSystemMessage("COMBAT STARTED"));
439474 } else if (!gameState.inCombat && wasInCombat) {
440- tui.log(formatSystemMessage("Combat ended"));
475+ output.log(formatSystemMessage("Combat ended"));
441476 }
442477
443- updateTui();
478+ updateOutput();
444479 saveSnapshot();
445480 });
446481
447482 client.on<ChatMessage>("chat_message", (data) => {
448- tui.log(formatChatMessage(data));
483+ output.log(formatChatMessage(data));
449484 memory.appendEvent("chat_message", data);
450485 });
451486
452487 client.on<ScanResultPayload>("scan_result", (data) => {
453- tui.log(formatScanResult(data));
488+ output.log(formatScanResult(data));
454489 memory.appendEvent("scan_result", data);
455490 });
456491
@@ -459,7 +494,7 @@ client.on("ok", (data: Record<string, unknown>) => {
459494 jumpTarget: gameState.lastJumpTarget,
460495 travelTarget: gameState.lastTravelTarget,
461496 };
462- tui.log(formatOk(data, okContext));
497+ output.log(formatOk(data, okContext));
463498 memory.appendEvent("ok", data);
464499 updateWorldSnapshotFromOk(data);
465500
@@ -482,12 +517,12 @@ client.on("ok", (data: Record<string, unknown>) => {
482517 client.getSystem();
483518 client.getPOI();
484519 }
485- updateTui();
520+ updateOutput();
486521 });
487522
488523 client.on("version_info", (data: Record<string, unknown>) => {
489524 const version = String(data.version ?? "unknown");
490- tui.log(formatSystemMessage(`Version: ${version}`));
525+ output.log(formatSystemMessage(`Version: ${version}`));
491526 memory.appendEvent("version_info", data);
492527 });
493528
@@ -496,10 +531,13 @@ gameState.credentials = await loadCredentials();
496531 console.log(`Instance: ${config.instanceName}`);
497532 console.log(`Credentials: ${config.credentialsFile}`);
498533 console.log(`Memory DB: ${config.memoryPath}`);
534+output.log(formatSystemMessage(`Instance: ${config.instanceName}`));
535+output.log(formatSystemMessage(`Credentials: ${config.credentialsFile}`));
536+output.log(formatSystemMessage(`Memory DB: ${config.memoryPath}`));
499537
500538 // Force re-registration if personality is missing
501539 if (gameState.credentials && !gameState.credentials.personality) {
502- tui.log(
540+ output.log(
503541 formatSystemMessage(
504542 "Credentials missing personality field - forcing re-registration",
505543 ),
@@ -511,7 +549,7 @@ if (gameState.credentials && !gameState.credentials.personality) {
511549 await file.remove?.();
512550 }
513551 } catch (error) {
514- tui.log(
552+ output.log(
515553 formatSystemMessage(
516554 `Failed to delete credentials: ${(error as Error).message}`,
517555 ),
@@ -521,7 +559,7 @@ if (gameState.credentials && !gameState.credentials.personality) {
521559 }
522560
523561 await client.connect();
524-updateTui();
562+updateOutput();
525563
526564 function updateWorldSnapshotFromOk(data: Record<string, unknown>): void {
527565 if (data.system && typeof data.system === "object") {
@@ -565,9 +603,9 @@ function initializeSessionFromStateUpdate(
565603 }
566604
567605 if (message) {
568- tui.log(formatSystemMessage(message));
606+ output.log(formatSystemMessage(message));
569607 }
570- updateTui();
608+ updateOutput();
571609 saveSnapshot();
572610 startActionLoop();
573611 }
src/output-interface.ts+12−0
@@ -0,0 +1,12 @@
1+import type { FormattedMessage } from "./tui/formatters";
2+import type { TuiUpdateData } from "./tui/index";
3+
4+export interface OutputInterface {
5+ log(message: FormattedMessage): void;
6+ update(data: TuiUpdateData): void;
7+ setStatus(text: string): void;
8+ setPrompt(content: string): void;
9+ logDebug(label: string, content: string): void;
10+ destroy(): void;
11+ onExit(handler: () => void): void;
12+}
src/output/file-logger-output.ts+224−0
@@ -0,0 +1,224 @@
1+import type { OutputInterface } from "../output-interface";
2+import type { FormattedMessage } from "../tui/formatters";
3+import type { TuiUpdateData } from "../tui/index";
4+
5+type FileLoggerOptions = {
6+ uiLogPath: string;
7+ debugLogPath: string;
8+};
9+
10+type StateSnapshot = {
11+ credits: number | null;
12+ currentSystem: string | null;
13+ currentPoi: string | null;
14+ docked: boolean | null;
15+ inCombat: boolean | null;
16+ tick: number | null;
17+};
18+
19+const HEARTBEAT_INTERVAL = 10;
20+
21+export class FileLoggerOutput implements OutputInterface {
22+ private uiLogPath: string;
23+ private debugLogPath: string;
24+ private state: TuiUpdateData = {};
25+ private lastSnapshot: StateSnapshot = {
26+ credits: null,
27+ currentSystem: null,
28+ currentPoi: null,
29+ docked: null,
30+ inCombat: null,
31+ tick: null,
32+ };
33+ private lastHeartbeatTick: number | null = null;
34+ private writeQueue: Promise<void> = Promise.resolve();
35+
36+ constructor(options: FileLoggerOptions) {
37+ this.uiLogPath = options.uiLogPath;
38+ this.debugLogPath = options.debugLogPath;
39+ this.writeQueue = this.resetLogs();
40+ }
41+
42+ log(message: FormattedMessage): void {
43+ const text = normalizeMessageText(message);
44+ const line = `[${timestampIso()}] [${message.category.toUpperCase()}] ${text}`;
45+ this.appendUiLine(line);
46+ }
47+
48+ update(data: TuiUpdateData): void {
49+ this.mergeState(data);
50+ this.logStateChanges();
51+ }
52+
53+ setStatus(_text: string): void {
54+ // No-op in non-interactive mode.
55+ }
56+
57+ setPrompt(content: string): void {
58+ this.logDebug("PROMPT", content);
59+ }
60+
61+ logDebug(label: string, content: string): void {
62+ const header = `[${timestampIso()}] ${label}`;
63+ const body = content.endsWith("\n") ? content : `${content}\n`;
64+ this.appendDebugEntry(`${header}\n${body}\n`);
65+ }
66+
67+ destroy(): void {
68+ // Best-effort flush via queued writes.
69+ }
70+
71+ onExit(_handler: () => void): void {
72+ // Intentionally no-op in non-interactive mode.
73+ // SIGINT/SIGTERM handlers in index.ts handle graceful shutdown.
74+ }
75+
76+ private mergeState(data: TuiUpdateData): void {
77+ if (data.player !== undefined && data.player !== null)
78+ this.state.player = data.player;
79+ if (data.ship !== undefined && data.ship !== null)
80+ this.state.ship = data.ship;
81+ if (data.system !== undefined) this.state.system = data.system;
82+ if (data.poi !== undefined) this.state.poi = data.poi;
83+ if (data.base !== undefined) this.state.base = data.base;
84+ if (data.pois !== undefined) this.state.pois = data.pois;
85+ if (data.nearby !== undefined) this.state.nearby = data.nearby;
86+ if (data.personality !== undefined)
87+ this.state.personality = data.personality;
88+ if (data.tick !== undefined) this.state.tick = data.tick;
89+ if (data.traveling !== undefined) this.state.traveling = data.traveling;
90+ if (data.travelTarget !== undefined)
91+ this.state.travelTarget = data.travelTarget;
92+ if (data.jumping !== undefined) this.state.jumping = data.jumping;
93+ if (data.jumpTarget !== undefined) this.state.jumpTarget = data.jumpTarget;
94+ if (data.goal !== undefined) this.state.goal = data.goal;
95+ if (data.inCombat !== undefined) this.state.inCombat = data.inCombat;
96+ if (data.combatTarget !== undefined)
97+ this.state.combatTarget = data.combatTarget;
98+ }
99+
100+ private logStateChanges(): void {
101+ const player = this.state.player ?? null;
102+ const tick = this.state.tick ?? null;
103+ const currentSystem = player?.current_system
104+ ? String(player.current_system)
105+ : null;
106+ const currentPoi = player?.current_poi ? String(player.current_poi) : null;
107+ const docked = player ? Boolean(player.docked_at_base) : null;
108+ const inCombat = this.state.inCombat ?? null;
109+ const credits = player?.credits ?? null;
110+
111+ if (credits !== null && credits !== this.lastSnapshot.credits) {
112+ if (this.lastSnapshot.credits === null) {
113+ this.appendUiLine(`[${timestampIso()}] [STATE] Credits: ${credits}`);
114+ } else {
115+ const diff = credits - (this.lastSnapshot.credits ?? 0);
116+ const sign = diff > 0 ? "+" : "";
117+ this.appendUiLine(
118+ `[${timestampIso()}] [STATE] Credits: ${credits} (${sign}${diff})`,
119+ );
120+ }
121+ this.lastSnapshot.credits = credits;
122+ }
123+
124+ if (inCombat !== null && inCombat !== this.lastSnapshot.inCombat) {
125+ this.appendUiLine(
126+ `[${timestampIso()}] [STATE] ${inCombat ? "Combat started" : "Combat ended"}`,
127+ );
128+ this.lastSnapshot.inCombat = inCombat;
129+ }
130+
131+ if (
132+ currentSystem &&
133+ (currentSystem !== this.lastSnapshot.currentSystem ||
134+ currentPoi !== this.lastSnapshot.currentPoi)
135+ ) {
136+ const poiPart = currentPoi ? ` | POI: ${currentPoi}` : "";
137+ this.appendUiLine(
138+ `[${timestampIso()}] [STATE] Location: ${currentSystem}${poiPart}`,
139+ );
140+ this.lastSnapshot.currentSystem = currentSystem;
141+ this.lastSnapshot.currentPoi = currentPoi;
142+ }
143+
144+ if (docked !== null && docked !== this.lastSnapshot.docked) {
145+ this.appendUiLine(
146+ `[${timestampIso()}] [STATE] ${docked ? "Docked" : "Undocked"}`,
147+ );
148+ this.lastSnapshot.docked = docked;
149+ }
150+
151+ if (typeof tick === "number" && tick !== this.lastSnapshot.tick) {
152+ this.lastSnapshot.tick = tick;
153+ if (tick % HEARTBEAT_INTERVAL === 0 && this.lastHeartbeatTick !== tick) {
154+ this.lastHeartbeatTick = tick;
155+ this.appendUiLine(
156+ `[${timestampIso()}] [STATE] ${this.buildHeartbeatSummary(tick)}`,
157+ );
158+ }
159+ }
160+ }
161+
162+ private buildHeartbeatSummary(tick: number): string {
163+ const parts: string[] = [`Tick: ${tick}`];
164+ const player = this.state.player ?? null;
165+ if (player?.credits !== undefined) {
166+ parts.push(`Credits: ${player.credits}`);
167+ }
168+ if (player?.current_system) {
169+ parts.push(`System: ${player.current_system}`);
170+ }
171+ if (player?.current_poi) {
172+ parts.push(`POI: ${player.current_poi}`);
173+ }
174+ if (player) {
175+ parts.push(player.docked_at_base ? "Docked" : "In space");
176+ }
177+ if (this.state.inCombat) {
178+ parts.push("Combat");
179+ }
180+ return parts.join(" | ");
181+ }
182+
183+ private appendUiLine(line: string): void {
184+ this.enqueueWrite(this.uiLogPath, `${line}\n`);
185+ }
186+
187+ private appendDebugEntry(entry: string): void {
188+ this.enqueueWrite(this.debugLogPath, entry);
189+ }
190+
191+ private enqueueWrite(path: string, content: string): void {
192+ this.writeQueue = this.writeQueue.then(async () => {
193+ try {
194+ await Bun.write(path, content, { append: true });
195+ } catch (error) {
196+ console.error(
197+ `Failed to write log ${path}: ${(error as Error).message}`,
198+ );
199+ }
200+ });
201+ }
202+
203+ private async resetLogs(): Promise<void> {
204+ try {
205+ await Bun.write(this.uiLogPath, "");
206+ await Bun.write(this.debugLogPath, "");
207+ } catch (error) {
208+ console.error(`Failed to initialize logs: ${(error as Error).message}`);
209+ }
210+ }
211+}
212+
213+function timestampIso(): string {
214+ return new Date().toISOString();
215+}
216+
217+function normalizeMessageText(message: FormattedMessage): string {
218+ const stripped = stripBlessedTags(message.text);
219+ return stripped.replace(/^\[\d{2}:\d{2}:\d{2}\]\s*/, "");
220+}
221+
222+function stripBlessedTags(text: string): string {
223+ return text.replace(/\{[^}]+\}/g, "");
224+}
src/output/tui-output.ts+40−0
@@ -0,0 +1,40 @@
1+import type { OutputInterface } from "../output-interface";
2+import type { FormattedMessage } from "../tui/formatters";
3+import type { TuiUpdateData } from "../tui/index";
4+import { Tui } from "../tui/index";
5+
6+export class TuiOutput implements OutputInterface {
7+ private tui: Tui;
8+
9+ constructor(debugEnabled: boolean) {
10+ this.tui = new Tui(debugEnabled);
11+ }
12+
13+ log(message: FormattedMessage): void {
14+ this.tui.log(message);
15+ }
16+
17+ update(data: TuiUpdateData): void {
18+ this.tui.update(data);
19+ }
20+
21+ setStatus(text: string): void {
22+ this.tui.setStatus(text);
23+ }
24+
25+ setPrompt(content: string): void {
26+ this.tui.setPrompt(content);
27+ }
28+
29+ logDebug(_label: string, _content: string): void {
30+ // No-op in interactive mode.
31+ }
32+
33+ destroy(): void {
34+ this.tui.destroy();
35+ }
36+
37+ onExit(handler: () => void): void {
38+ this.tui.onExit(handler);
39+ }
40+}
src/registration.ts+12−9
@@ -2,19 +2,19 @@ import type { SpaceMoltClient } from "../client/src/client";
22 import type { EmpireID } from "../client/src/types";
33 import { PERSONALITY_ARCHETYPES } from "./constants";
44 import type { OllamaAgent } from "./ollama";
5+import type { OutputInterface } from "./output-interface";
56 import { buildRegistrationPrompt } from "./prompt";
67 import { formatAiThinking, formatSystemMessage } from "./tui/formatters";
7-import type { Tui } from "./tui/index";
88 import type { RegistrationChoice } from "./types";
99 import { isValidEmpire, isValidPersonality } from "./utils";
1010
1111 export async function runRegistrationFlow(
12- tui: Tui,
12+ output: OutputInterface,
1313 ollama: OllamaAgent,
1414 client: SpaceMoltClient,
1515 failedRegistrationNames: string[],
1616 ): Promise<RegistrationChoice> {
17- tui.log(
17+ output.log(
1818 formatSystemMessage(
1919 "No credentials found. Asking LLM to create a character...",
2020 ),
@@ -24,10 +24,13 @@ export async function runRegistrationFlow(
2424 attempts += 1;
2525 try {
2626 const prompt = buildRegistrationPrompt(true, failedRegistrationNames);
27- tui.setPrompt(prompt);
27+ output.setPrompt(prompt);
28+ output.logDebug("REGISTRATION_PROMPT", prompt);
2829 const result = await ollama.generateJson<RegistrationChoice>(prompt);
30+ output.logDebug("REGISTRATION_RESPONSE_RAW", result.raw);
2931 if (result.thinking) {
30- tui.log(formatAiThinking(result.thinking));
32+ output.log(formatAiThinking(result.thinking));
33+ output.logDebug("REGISTRATION_THINKING", result.thinking);
3134 }
3235 const username = String(result.json.username ?? "").trim();
3336 const empire = String(result.json.empire ?? "").trim() as EmpireID;
@@ -54,10 +57,10 @@ export async function runRegistrationFlow(
5457 };
5558
5659 const personalityInfo = PERSONALITY_ARCHETYPES[personality];
57- tui.log(
60+ output.log(
5861 formatSystemMessage(`Registering new account: ${username} (${empire})`),
5962 );
60- tui.log(
63+ output.log(
6164 formatSystemMessage(
6265 `Chosen personality: ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
6366 ),
@@ -65,7 +68,7 @@ export async function runRegistrationFlow(
6568 client.register(username, empire);
6669 return choice;
6770 } catch (error) {
68- tui.log(
71+ output.log(
6972 formatSystemMessage(
7073 `Registration attempt failed: ${(error as Error).message}`,
7174 ),
@@ -79,7 +82,7 @@ export async function runRegistrationFlow(
7982 empire: "solarian",
8083 personality: "pragmatist",
8184 };
82- tui.log(
85+ output.log(
8386 formatSystemMessage(
8487 `Falling back to account: ${fallback} (solarian, pragmatist)`,
8588 ),