xonecas.io
5875
Os

ollama-space-molt-player / commit 4d39d4f

refactor: extract prompt and session initialization logic

xonecas2026-02-01 4d39d4f2150fb5b89bed548b3a01c80469ceb2a0 parent 6e012c3

6 files changed

AGENTS.md+8−9
@@ -25,9 +25,8 @@ Purpose: help coding agents work safely and consistently in this repo.
2525 ### Run app
2626 - `bun run ollama-play --name <instance-name>` (or `-n <instance-name>`)
2727 - 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`
28+ - Memory DB (includes credentials): `memory-{name}.sqlite`
29+- Example: `bun run ollama-play --name alice` uses `memory-alice.sqlite`
3130
3231 ### Run in non-interactive mode (for testing/debugging)
3332 - `bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]`
@@ -45,15 +44,15 @@ Purpose: help coding agents work safely and consistently in this repo.
4544
4645 ### Reusing test accounts
4746 - Prefer reusing the same instance names to avoid creating new accounts on every run.
48-- The credentials files are stored locally as `.spacemolt-bot-{name}.json` and should not be committed.
47+- Credentials are stored in the instance SQLite DB and should not be committed.
4948
5049 **Known test instances:**
51-- `debug-bot` -> `.spacemolt-bot-debug-bot.json`
52-- `test-bot-1` -> `.spacemolt-bot-test-bot-1.json`
53-- `test-bot-2` -> `.spacemolt-bot-test-bot-2.json`
50+- `debug-bot` -> `memory-debug-bot.sqlite`
51+- `test-bot-1` -> `memory-test-bot-1.sqlite`
52+- `test-bot-2` -> `memory-test-bot-2.sqlite`
5453
5554 **Troubleshooting:**
56-- If you see `Invalid username or token`, delete the instance credentials and memory files, then rerun to create a new account.
55+- If you see `Invalid username or token`, delete the instance DB (`memory-{name}.sqlite`), then rerun to create a new account.
5756
5857 ### Format
5958 - `bun run biome:format`
@@ -143,7 +142,7 @@ Purpose: help coding agents work safely and consistently in this repo.
143142 - Avoid changing `client/` unless the change is intended for the submodule.
144143
145144 ## Editing Safety
146-- Do not edit `memory.sqlite` or `.spacemolt-bot-credentials.json`.
145+- Do not edit `memory.sqlite` or `memory-*.sqlite`.
147146 - Do not commit secrets or credentials.
148147 - Keep changes minimal and aligned with the current architecture.
149148
README.md+1−1
@@ -19,7 +19,7 @@ When the script starts,
1919 - Introduce the LLM to the game https://www.spacemolt.com/
2020 - show the LLM the help menu from the reference client
2121
22-- we read the credentials file (.spacemolt-bot-credentials.json). If we find one login.
22+- we read credentials from sqlite. If we find one login.
2323 - If there is not one, we prompt the llm to choose a name, faction, etc, and register a new account and login.
2424
2525 Now that we have a playable account.
src/config.ts+0−1
@@ -63,7 +63,6 @@ export const config = {
6363 spacemoltUrl: process.env.SPACEMOLT_URL ?? "wss://game.spacemolt.com/ws",
6464 debug: process.env.DEBUG === "true",
6565 memoryPath: process.env.MEMORY_DB ?? `memory-${instanceName}.sqlite`,
66- credentialsFile: `.spacemolt-bot-${instanceName}.json`,
6766 uiLogPath: `ui-${instanceName}.log`,
6867 debugLogPath: `debug-${instanceName}.log`,
6968 tickDelayMs: 11000,
src/index.ts+12−36
@@ -64,14 +64,16 @@ let fallbackTickCount = 0;
6464
6565 async function loadCredentials(): Promise<Credentials | null> {
6666 try {
67- const file = Bun.file(config.credentialsFile);
68- if (await file.exists()) {
69- return (await file.json()) as Credentials;
70- }
71- } catch {
67+ return memory.getCredentials();
68+ } catch (error) {
69+ output.log(
70+ formatSystemMessage(
71+ `FATAL: Failed to load credentials: ${(error as Error).message}`,
72+ ),
73+ );
74+ shutdown();
7275 return null;
7376 }
74- return null;
7577 }
7678
7779 async function saveCredentials(
@@ -79,8 +81,7 @@ async function saveCredentials(
7981 token: string,
8082 personality: PersonalityType,
8183 ): Promise<void> {
82- const data: Credentials = { username, token, personality };
83- await Bun.write(config.credentialsFile, JSON.stringify(data, null, 2));
84+ memory.saveCredentials(username, token, personality);
8485 }
8586
8687 function updateOutput(): void {
@@ -430,7 +431,7 @@ client.on<ErrorPayload>("error", (data) => {
430431 );
431432 output.log(
432433 formatSystemMessage(
433- `Delete ${config.credentialsFile} and run again to create a new account.`,
434+ `Delete ${config.memoryPath} and run again to create a new account.`,
434435 ),
435436 );
436437 shutdown();
@@ -573,34 +574,9 @@ client.on("version_info", (data: Record<string, unknown>) => {
573574 gameState.credentials = await loadCredentials();
574575
575576 console.log(`Instance: ${config.instanceName}`);
576-console.log(`Credentials: ${config.credentialsFile}`);
577-console.log(`Memory DB: ${config.memoryPath}`);
577+console.log(`DB: ${config.memoryPath}`);
578578 output.log(formatSystemMessage(`Instance: ${config.instanceName}`));
579-output.log(formatSystemMessage(`Credentials: ${config.credentialsFile}`));
580-output.log(formatSystemMessage(`Memory DB: ${config.memoryPath}`));
581-
582-// Force re-registration if personality is missing
583-if (gameState.credentials && !gameState.credentials.personality) {
584- output.log(
585- formatSystemMessage(
586- "Credentials missing personality field - forcing re-registration",
587- ),
588- );
589- try {
590- await Bun.write(config.credentialsFile, "");
591- const file = Bun.file(config.credentialsFile);
592- if (await file.exists()) {
593- await file.remove?.();
594- }
595- } catch (error) {
596- output.log(
597- formatSystemMessage(
598- `Failed to delete credentials: ${(error as Error).message}`,
599- ),
600- );
601- }
602- gameState.credentials = null;
603-}
579+output.log(formatSystemMessage(`DB: ${config.memoryPath}`));
604580
605581 await client.connect();
606582 updateOutput();
src/memory.ts+36−0
@@ -1,4 +1,5 @@
11 import { Database } from "bun:sqlite";
2+import type { Credentials, PersonalityType } from "./types";
23
34 export interface Snapshot {
45 tick: number;
@@ -83,9 +84,44 @@ export class MemoryStore {
8384 base TEXT,
8485 nearby TEXT
8586 );
87+ CREATE TABLE IF NOT EXISTS credentials (
88+ id INTEGER PRIMARY KEY AUTOINCREMENT,
89+ ts TEXT NOT NULL,
90+ username TEXT NOT NULL,
91+ token TEXT NOT NULL,
92+ personality TEXT NOT NULL
93+ );
8694 `);
8795 }
8896
97+ getCredentials(): Credentials | null {
98+ const row = this.db
99+ .query(
100+ "SELECT username, token, personality FROM credentials ORDER BY id DESC LIMIT 1",
101+ )
102+ .get() as
103+ | { username?: string; token?: string; personality?: string }
104+ | undefined;
105+ if (!row || !row.username || !row.token || !row.personality) return null;
106+ return {
107+ username: row.username,
108+ token: row.token,
109+ personality: row.personality as PersonalityType,
110+ };
111+ }
112+
113+ saveCredentials(
114+ username: string,
115+ token: string,
116+ personality: PersonalityType,
117+ ): void {
118+ this.db
119+ .query(
120+ "INSERT INTO credentials (ts, username, token, personality) VALUES (?, ?, ?, ?)",
121+ )
122+ .run(nowIso(), username, token, personality);
123+ }
124+
89125 appendAction(
90126 action: string,
91127 args: unknown,
src/tui-screenshot.ts+10−14
@@ -12,10 +12,12 @@ import type {
1212 WelcomePayload,
1313 } from "../client/src/types";
1414 import { config } from "./config";
15+import { MemoryStore } from "./memory";
1516 import { renderLocationPanel } from "./tui/panels/location";
1617 import { renderPlayerShipPanel } from "./tui/panels/player-ship";
1718 import { renderTacticalPanel } from "./tui/panels/tactical";
1819 import { renderWorldInfoPanel } from "./tui/panels/world-info";
20+import type { Credentials } from "./types";
1921
2022 const client = new SpaceMoltClient({
2123 url: config.spacemoltUrl,
@@ -23,10 +25,7 @@ const client = new SpaceMoltClient({
2325 reconnect: false,
2426 });
2527
26-type Credentials = {
27- username: string;
28- token: string;
29-};
28+const memory = new MemoryStore(config.memoryPath);
3029
3130 type WorldSnapshot = {
3231 system?: System | null;
@@ -40,16 +39,13 @@ let cachedPlayer: Player | null = null;
4039 let cachedShip: Ship | null = null;
4140 const worldSnapshot: WorldSnapshot = {};
4241
43-async function loadCredentials(): Promise<Credentials | null> {
42+function loadCredentials(): Credentials | null {
4443 try {
45- const file = Bun.file(config.credentialsFile);
46- if (await file.exists()) {
47- return (await file.json()) as Credentials;
48- }
49- } catch {
50- return null;
44+ return memory.getCredentials();
45+ } catch (error) {
46+ console.log(`Failed to load credentials: ${(error as Error).message}`);
47+ process.exit(1);
5148 }
52- return null;
5349 }
5450
5551 function dumpTuiState() {
@@ -162,10 +158,10 @@ client.on("ok", (data: Record<string, unknown>) => {
162158 }
163159 });
164160
165-credentials = await loadCredentials();
161+credentials = loadCredentials();
166162
167163 if (!credentials) {
168- console.log("No credentials file found. Please run the main app first.");
164+ console.log("No credentials found in DB. Please run the main app first.");
169165 process.exit(1);
170166 }