@@ -2,6 +2,8 @@ import { SpaceMoltClient } from "../client/src/client";
22 import type {
33 ChatMessage,
44 ErrorPayload,
5+ LoggedInPayload,
6+ RegisteredPayload,
57 ScanResultPayload,
68 StateUpdatePayload,
79 WelcomePayload,
@@ -22,6 +24,7 @@ import {
2224 formatAiThinking,
2325 formatChatMessage,
2426 formatError,
27+ formatLoggedIn,
2528 formatMotd,
2629 formatOk,
2730 formatScanResult,
@@ -101,18 +104,19 @@ function updateOutput(): void {
101104 });
102105 }
103106
104-function shouldStopForMaxTicks(): boolean {
107+function shouldStopForMaxTicks(allowFallbackCount: boolean): boolean {
105108 if (config.maxTicks === null) return false;
106109 const currentTick = client.state.currentTick;
107110 if (typeof currentTick === "number" && maxTicksStart !== null) {
108- return currentTick - maxTicksStart > config.maxTicks;
111+ return currentTick - maxTicksStart >= config.maxTicks;
109112 }
110113 if (typeof currentTick === "number" && maxTicksStart === null) {
111114 maxTicksStart = currentTick;
112115 return false;
113116 }
117+ if (!allowFallbackCount) return false;
114118 fallbackTickCount += 1;
115- return fallbackTickCount > config.maxTicks;
119+ return fallbackTickCount >= config.maxTicks;
116120 }
117121
118122 function saveSnapshot(): void {
@@ -181,20 +185,21 @@ async function startActionLoop(): Promise<void> {
181185 actionLoopRunning = true;
182186
183187 while (client.state.authenticated) {
188+ const inTransit = gameState.travelInProgress || gameState.jumpInProgress;
189+ if (shouldStopForMaxTicks(!inTransit)) {
190+ output.log(
191+ formatSystemMessage(
192+ `Max ticks reached (${config.maxTicks}). Shutting down.`,
193+ ),
194+ );
195+ shutdown();
196+ break;
197+ }
184198 try {
185- if (gameState.travelInProgress || gameState.jumpInProgress) {
199+ if (inTransit) {
186200 await sleep(config.tickDelayMs);
187201 continue;
188202 }
189- if (shouldStopForMaxTicks()) {
190- output.log(
191- formatSystemMessage(
192- `Max ticks reached (${config.maxTicks}). Shutting down.`,
193- ),
194- );
195- shutdown();
196- break;
197- }
198203 const recentHistory = memory.getRecentHistory(
199204 config.maxContextActions,
200205 config.maxContextEvents,
@@ -341,9 +346,96 @@ client.on<WelcomePayload>("welcome", async (data) => {
341346 }
342347 });
343348
349+client.on<RegisteredPayload>("registered", (data) => {
350+ memory.appendEvent("registered", data);
351+
352+ if (!data.token) {
353+ output.log(
354+ formatSystemMessage("FATAL: Server sent registered event without token"),
355+ );
356+ output.logDebug("REGISTERED_NO_TOKEN", JSON.stringify(data, null, 2));
357+ shutdown();
358+ return;
359+ }
360+
361+ output.log(formatSystemMessage("Registration successful - token received"));
362+ output.logDebug("REGISTERED_PAYLOAD", JSON.stringify(data, null, 2));
363+
364+ if (gameState.pendingRegistration) {
365+ gameState.pendingRegistration.token = data.token;
366+ }
367+});
368+
369+client.on<LoggedInPayload>("logged_in", async (data) => {
370+ output.log(formatLoggedIn(data));
371+ memory.appendEvent("logged_in", data);
372+ output.logDebug("LOGGED_IN_PAYLOAD", JSON.stringify(data, null, 2));
373+
374+ // CASE 1: New registration - save credentials
375+ if (gameState.pendingRegistration) {
376+ const token = gameState.pendingRegistration.token;
377+
378+ if (!token) {
379+ output.log(
380+ formatSystemMessage(
381+ "FATAL: Logged in but no token was captured from registered event",
382+ ),
383+ );
384+ shutdown();
385+ return;
386+ }
387+
388+ try {
389+ await saveCredentials(
390+ gameState.pendingRegistration.username,
391+ token,
392+ gameState.pendingRegistration.personality,
393+ );
394+
395+ gameState.credentials = {
396+ username: gameState.pendingRegistration.username,
397+ token: token,
398+ personality: gameState.pendingRegistration.personality,
399+ };
400+
401+ output.log(
402+ formatSystemMessage(
403+ `Credentials saved for ${gameState.pendingRegistration.username}`,
404+ ),
405+ );
406+ gameState.pendingRegistration = null;
407+ } catch (err) {
408+ output.log(
409+ formatSystemMessage(
410+ `FATAL: Failed to save credentials: ${(err as Error).message}`,
411+ ),
412+ );
413+ shutdown();
414+ return;
415+ }
416+ }
417+
418+ // CASE 2: Initialize session (both new registration and existing login)
419+ initializeSessionFromLoggedIn(data);
420+});
421+
344422 client.on<ErrorPayload>("error", (data) => {
345423 output.log(formatError(data));
346424 memory.appendEvent("error", data);
425+ if (data.code === "invalid_credentials") {
426+ output.log(
427+ formatSystemMessage(
428+ "FATAL: Invalid credentials. The saved token is invalid or expired.",
429+ ),
430+ );
431+ output.log(
432+ formatSystemMessage(
433+ `Delete ${config.credentialsFile} and run again to create a new account.`,
434+ ),
435+ );
436+ shutdown();
437+ return;
438+ }
347439 if (data.code === "username_taken" && gameState.pendingRegistration) {
348440 if (gameState.pendingRegistration.username) {
349441 gameState.failedRegistrationNames.push(
@@ -386,60 +478,12 @@ client.on<ErrorPayload>("error", (data) => {
386478 client.on<StateUpdatePayload>("state_update", async (data) => {
387479 memory.appendEvent("state_update", data);
388480
389- // Handle new registration: server v0.3.0+ doesn't send registered/logged_in events
390- // It only sends state_update with player data after registration
391- if (
392- gameState.pendingRegistration &&
393- data.player &&
394- data.player.username === gameState.pendingRegistration.username
395- ) {
396- // Use player.id as token (server v0.3.0+ behavior)
397- const token = gameState.pendingRegistration.token ?? data.player.id;
398- try {
399- await saveCredentials(
400- gameState.pendingRegistration.username,
401- token,
402- gameState.pendingRegistration.personality,
403- );
404- gameState.credentials = {
405- username: gameState.pendingRegistration.username,
406- token: token,
407- personality: gameState.pendingRegistration.personality,
408- };
409- output.log(
410- formatSystemMessage(
411- `Credentials saved for ${gameState.pendingRegistration.username}`,
412- ),
413- );
414- gameState.pendingRegistration = null;
415-
416- // Start action loop since logged_in won't fire on v0.3.0+
417- if (!client.state.authenticated) {
418- initializeSessionFromStateUpdate(data);
419- }
420- } catch (err) {
421- output.log(
422- formatSystemMessage(
423- `Failed to save credentials: ${(err as Error).message}`,
424- ),
425- );
426- }
427- } else if (
428- !actionLoopRunning &&
429- !client.state.authenticated &&
430- gameState.credentials &&
431- data.player &&
432- data.player.username === gameState.credentials.username
433- ) {
434- // Recovery: we have credentials, and received a state update for our user, but aren't flagged as authenticated/running.
435- // This might happen if we reconnected and missed a welcome/login event or similar, or just standard 0.3.0+ flow
436- initializeSessionFromStateUpdate(
437- data,
438- `Recovered session for ${data.player.username}`,
439- );
481+ // Ignore state updates before authentication
482+ if (!client.state.authenticated) {
483+ return;
440484 }
441485
442- // Update cached player and ship data (only if provided)
486+ // Update cached player and ship data
443487 if (data.player) {
444488 gameState.cachedPlayer = data.player;
445489 }
@@ -576,12 +620,7 @@ function updateWorldSnapshotFromOk(data: Record<string, unknown>): void {
576620 }
577621 }
578622
579-function initializeSessionFromStateUpdate(
580- data: StateUpdatePayload,
581- message?: string,
582-): void {
583- if (!data.player) return;
584-
623+function initializeSessionFromLoggedIn(data: LoggedInPayload): void {
585624 client.state.authenticated = true;
586625 gameState.cachedPlayer = data.player;
587626 gameState.cachedShip = data.ship;
@@ -589,22 +628,22 @@ function initializeSessionFromStateUpdate(
589628
590629 gameState.worldSnapshot.system = data.system;
591630 gameState.worldSnapshot.poi = data.poi;
592- if (data.player.current_system)
631+
632+ if (data.player.current_system) {
593633 gameState.lastSystemId = data.player.current_system;
594- if (data.player.current_poi) gameState.lastPoiId = data.player.current_poi;
634+ }
635+ if (data.player.current_poi) {
636+ gameState.lastPoiId = data.player.current_poi;
637+ }
638+
595639 gameState.lastDocked = Boolean(data.player.docked_at_base);
596640 gameState.currentGoal = memory.getLatestGoal(data.player.username);
597641
598- // Refresh world data
599- client.getSystem();
600- client.getPOI();
642+ // Fetch base info if docked
601643 if (data.player.docked_at_base) {
602644 client.getBase();
603645 }
604646
605- if (message) {
606- output.log(formatSystemMessage(message));
607- }
608647 updateOutput();
609648 saveSnapshot();
610649 startActionLoop();