@@ -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 }