xonecas.io
5875
Os

ollama-space-molt-player / commit 275e03c

feat: initialize ollama spacemolt player project with TUI and core functionality

- Add TypeScript configuration and project setup
- Implement TUI with terminal user interface components
- Add Ollama integration for language model interactions
- Create memory management and prompt handling systems
- Include action dispatch and configuration management
- Add documentation and build configuration

xonecas2026-02-01 275e03c544bd973ce8a007cd295d401fd8f66d01

14 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.

.gitignore+8−0
@@ -0,0 +1,8 @@
1+node_modules/
2+.spacemolt-bot-credentials.json
3+memory.sqlite
4+*.sqlite
5+.env
6+.DS_Store
7+dist/
8+build/
.gitmodules+3−0
@@ -0,0 +1,3 @@
1+[submodule "client"]
2+ path = client
3+ url = git@github.com:SpaceMolt/client.git
README.md+33−0
@@ -0,0 +1,33 @@
1+# Space Molt: Ollama player
2+
3+Let a locally hosted LLM play [Space Molt](https://www.spacemolt.com/) to it's hearts desire.
4+
5+## Tech
6+
7+It has the Space Molt [reference client](https://github.com/SpaceMolt/client) as submodule so we can use it as library. It's also our blueprint of what the LLM can do in the game.
8+It connects to the local ollama instance using http.
9+a simple sqlite is used with Bun.sql to preserve a running memory for the LLM
10+
11+## How
12+
13+When the script starts,
14+
15+- Introduce the LLM to the game https://www.spacemolt.com/
16+- show the LLM the help menu from the reference client
17+
18+- we read the credentials file (.spacemolt-bot-credentials.json). If we find one login.
19+- If there is not one, we prompt the llm to choose a name, faction, etc, and register a new account and login.
20+
21+Now that we have a playable account.
22+
23+- Tell the LLM it's status and prompt, it for it's next action.
24+- Track it's status and actions in sql so we can include it in prompts as context.
25+- perform the action the LLM decided in Space Molt
26+- track the actions result in sql, so the result is included in the next prompt for action.
27+- wait 11 seconds. (server tick rate is 10s)
28+
29+## UI
30+
31+A simple TUI with a status bar at the bottom with character information
32+A scrolling log of the LLM's actions and results.
33+Clean, readable and resizeable with simple colors.
bun.lock+24−0
@@ -0,0 +1,24 @@
1+{
2+ "lockfileVersion": 1,
3+ "configVersion": 1,
4+ "workspaces": {
5+ "": {
6+ "name": "ollama-spacemolt-player",
7+ "dependencies": {
8+ "blessed": "^0.1.81",
9+ },
10+ "devDependencies": {
11+ "@types/blessed": "^0.1.21",
12+ },
13+ },
14+ },
15+ "packages": {
16+ "@types/blessed": ["@types/blessed@0.1.27", "", { "dependencies": { "@types/node": "*" } }, "sha512-ZOQGjLvWDclAXp0rW5iuUBXeD6Gr1PkitN7tj7/G8FCoSzTsij6OhXusOzMKhwrZ9YlL2Pmu0d6xJ9zVvk+Hsg=="],
17+
18+ "@types/node": ["@types/node@25.1.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-t7frlewr6+cbx+9Ohpl0NOTKXZNV9xHRmNOvql47BFJKcEG1CxtxlPEEe+gR9uhVWM4DwhnvTF110mIL4yP9RA=="],
19+
20+ "blessed": ["blessed@0.1.81", "", { "bin": { "blessed": "./bin/tput.js" } }, "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ=="],
21+
22+ "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
23+ }
24+}
client+1−0
@@ -0,0 +1 @@
1+Subproject commit 61f40644c992d37ace59a1568dea0b9913fdd1ef
package.json+15−0
@@ -0,0 +1,15 @@
1+{
2+ "name": "ollama-spacemolt-player",
3+ "version": "0.1.0",
4+ "private": true,
5+ "type": "module",
6+ "scripts": {
7+ "ollama-play": "bun src/index.ts"
8+ },
9+ "dependencies": {
10+ "blessed": "^0.1.81"
11+ },
12+ "devDependencies": {
13+ "@types/blessed": "^0.1.21"
14+ }
15+}
src/actions.ts+155−0
@@ -0,0 +1,155 @@
1+import type { SpaceMoltClient } from "../client/src/client";
2+
3+export interface ActionDecision {
4+ action: string;
5+ args?: Record<string, unknown>;
6+}
7+
8+const ACTIONS: Record<string, string[]> = {
9+ travel: ["target_poi"],
10+ jump: ["target_system"],
11+ dock: [],
12+ undock: [],
13+ mine: [],
14+ attack: ["target_id"],
15+ scan: ["target_id"],
16+ buy: ["listing_id", "quantity"],
17+ sell: ["item_id", "quantity"],
18+ refuel: [],
19+ repair: [],
20+ craft: ["recipe_id"],
21+ chat: ["channel", "content"],
22+ status: [],
23+ system: [],
24+ poi: [],
25+ base: [],
26+ skills: [],
27+ recipes: [],
28+ version: [],
29+ nearby: [],
30+ cargo: [],
31+ wait: [],
32+};
33+
34+export function validateAction(decision: unknown): { ok: boolean; error?: string; action?: ActionDecision } {
35+ if (!decision || typeof decision !== "object") {
36+ return { ok: false, error: "Action is not an object" };
37+ }
38+
39+ const action = String((decision as ActionDecision).action ?? "").toLowerCase();
40+ if (!action || !(action in ACTIONS)) {
41+ return { ok: false, error: `Unknown action: ${action || "(empty)"}` };
42+ }
43+
44+ const args = ((decision as ActionDecision).args ?? {}) as Record<string, unknown>;
45+ if (typeof args !== "object" || Array.isArray(args)) {
46+ return { ok: false, error: "Args must be an object" };
47+ }
48+
49+ const required = ACTIONS[action];
50+ for (const key of required) {
51+ if (!(key in args)) {
52+ return { ok: false, error: `Missing arg: ${key}` };
53+ }
54+ }
55+
56+ if (action === "buy" || action === "sell") {
57+ const quantity = Number(args.quantity);
58+ if (!Number.isFinite(quantity) || quantity <= 0) {
59+ return { ok: false, error: "quantity must be a positive number" };
60+ }
61+ }
62+
63+ if (action === "chat") {
64+ const channel = String(args.channel ?? "");
65+ if (!channel || !["local", "faction", "private"].includes(channel)) {
66+ return { ok: false, error: "chat.channel must be local|faction|private" };
67+ }
68+ const content = String(args.content ?? "");
69+ if (!content) {
70+ return { ok: false, error: "chat.content is required" };
71+ }
72+ if (channel === "private" && !args.target_id) {
73+ return { ok: false, error: "chat.target_id required for private channel" };
74+ }
75+ }
76+
77+ return { ok: true, action: { action, args } };
78+}
79+
80+export function dispatchAction(client: SpaceMoltClient, decision: ActionDecision): string {
81+ const args = decision.args ?? {};
82+
83+ switch (decision.action) {
84+ case "travel":
85+ client.travel(String(args.target_poi));
86+ return `travel ${String(args.target_poi)}`;
87+ case "jump":
88+ client.jump(String(args.target_system));
89+ return `jump ${String(args.target_system)}`;
90+ case "dock":
91+ client.dock();
92+ return "dock";
93+ case "undock":
94+ client.undock();
95+ return "undock";
96+ case "mine":
97+ client.mine();
98+ return "mine";
99+ case "attack":
100+ client.attack(String(args.target_id));
101+ return `attack ${String(args.target_id)}`;
102+ case "scan":
103+ client.scan(String(args.target_id));
104+ return `scan ${String(args.target_id)}`;
105+ case "buy":
106+ client.buy(String(args.listing_id), Number(args.quantity));
107+ return `buy ${String(args.listing_id)} x${Number(args.quantity)}`;
108+ case "sell":
109+ client.sell(String(args.item_id), Number(args.quantity));
110+ return `sell ${String(args.item_id)} x${Number(args.quantity)}`;
111+ case "refuel":
112+ client.refuel();
113+ return "refuel";
114+ case "repair":
115+ client.repair();
116+ return "repair";
117+ case "craft":
118+ client.craft(String(args.recipe_id));
119+ return `craft ${String(args.recipe_id)}`;
120+ case "chat":
121+ client.chat(String(args.channel) as "local" | "faction" | "private", String(args.content),
122+ args.target_id ? String(args.target_id) : undefined
123+ );
124+ return `chat ${String(args.channel)}`;
125+ case "status":
126+ client.getStatus();
127+ return "get status";
128+ case "system":
129+ client.getSystem();
130+ return "get system";
131+ case "poi":
132+ client.getPOI();
133+ return "get poi";
134+ case "base":
135+ client.getBase();
136+ return "get base";
137+ case "skills":
138+ client.getSkills();
139+ return "get skills";
140+ case "recipes":
141+ client.getRecipes();
142+ return "get recipes";
143+ case "version":
144+ client.getVersion();
145+ return "get version";
146+ case "nearby":
147+ return "nearby (from state)";
148+ case "cargo":
149+ return "cargo (from state)";
150+ case "wait":
151+ return "wait";
152+ default:
153+ return "unknown";
154+ }
155+}
src/config.ts+12−0
@@ -0,0 +1,12 @@
1+export const config = {
2+ ollamaUrl: process.env.OLLAMA_URL ?? "http://localhost:11434",
3+ ollamaModel: process.env.OLLAMA_MODEL ?? "qwen3:8b",
4+ spacemoltUrl: process.env.SPACEMOLT_URL ?? "wss://game.spacemolt.com/ws",
5+ debug: process.env.DEBUG === "true",
6+ memoryPath: process.env.MEMORY_DB ?? "memory.sqlite",
7+ credentialsFile: ".spacemolt-bot-credentials.json",
8+ tickDelayMs: 11000,
9+ maxContextActions: 10,
10+ maxContextEvents: 20,
11+ ollamaTimeoutMs: 60000,
12+};
src/index.ts+274−0
@@ -0,0 +1,274 @@
1+import { SpaceMoltClient } from "../client/src/client";
2+import type {
3+ WelcomePayload,
4+ RegisteredPayload,
5+ LoggedInPayload,
6+ ErrorPayload,
7+ StateUpdatePayload,
8+ ChatMessage,
9+ ScanResultPayload,
10+ EmpireID,
11+} from "../client/src/types";
12+import { config } from "./config";
13+import { MemoryStore } from "./memory";
14+import { OllamaAgent } from "./ollama";
15+import { buildActionPrompt, buildRegistrationPrompt } from "./prompt";
16+import { dispatchAction, validateAction } from "./actions";
17+import { Tui } from "./tui";
18+
19+type Credentials = { username: string; token: string };
20+type RegistrationChoice = { username: string; empire: EmpireID };
21+
22+const memory = new MemoryStore(config.memoryPath);
23+const ollama = new OllamaAgent(config.ollamaUrl, config.ollamaModel, config.ollamaTimeoutMs);
24+const tui = new Tui();
25+
26+const client = new SpaceMoltClient({
27+ url: config.spacemoltUrl,
28+ debug: config.debug,
29+ reconnect: true,
30+});
31+
32+let credentials: Credentials | null = null;
33+let pendingRegistration: RegistrationChoice | null = null;
34+let includeHelpInPrompt = true;
35+let actionLoopRunning = false;
36+
37+async function loadCredentials(): Promise<Credentials | null> {
38+ try {
39+ const file = Bun.file(config.credentialsFile);
40+ if (await file.exists()) {
41+ return (await file.json()) as Credentials;
42+ }
43+ } catch {
44+ return null;
45+ }
46+ return null;
47+}
48+
49+async function saveCredentials(username: string, token: string): Promise<void> {
50+ const data: Credentials = { username, token };
51+ await Bun.write(config.credentialsFile, JSON.stringify(data, null, 2));
52+}
53+
54+function log(message: string): void {
55+ tui.log(message);
56+}
57+
58+function updateStatus(): void {
59+ const state = client.state;
60+ if (!state.player || !state.ship) {
61+ tui.setStatus("Not logged in");
62+ return;
63+ }
64+ const location = `${state.system?.name ?? state.player.current_system} - ${
65+ state.poi?.name ?? state.player.current_poi
66+ }`;
67+ const status = [
68+ `Player ${state.player.username} [${state.player.empire}]`,
69+ `Cr ${state.player.credits}`,
70+ `Hull ${state.ship.hull}/${state.ship.max_hull}`,
71+ `Shield ${state.ship.shield}/${state.ship.max_shield}`,
72+ `Fuel ${state.ship.fuel}/${state.ship.max_fuel}`,
73+ `Docked ${state.player.docked_at_base ? "Y" : "N"}`,
74+ `Tick ${state.currentTick}`,
75+ location,
76+ ].join(" | ");
77+ tui.setStatus(status);
78+}
79+
80+function saveSnapshot(): void {
81+ memory.saveSnapshot({
82+ tick: client.state.currentTick,
83+ player: client.state.player,
84+ ship: client.state.ship,
85+ system: client.state.system,
86+ poi: client.state.poi,
87+ base: client.state.base,
88+ nearby: client.state.nearby,
89+ });
90+}
91+
92+async function runRegistrationFlow(): Promise<void> {
93+ log("No credentials found. Asking LLM to create a character...");
94+ let attempts = 0;
95+ while (attempts < 3) {
96+ attempts += 1;
97+ try {
98+ const prompt = buildRegistrationPrompt(true);
99+ const result = await ollama.generateJson<RegistrationChoice>(prompt);
100+ const username = String(result.json.username ?? "").trim();
101+ const empire = String(result.json.empire ?? "").trim() as EmpireID;
102+ if (!username || !isValidEmpire(empire)) {
103+ throw new Error("Invalid registration response");
104+ }
105+ pendingRegistration = { username, empire };
106+ log(`Registering new account: ${username} (${empire})`);
107+ client.register(username, empire);
108+ return;
109+ } catch (error) {
110+ log(`Registration attempt failed: ${(error as Error).message}`);
111+ }
112+ }
113+
114+ const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
115+ pendingRegistration = { username: fallback, empire: "solarian" };
116+ log(`Falling back to account: ${fallback} (solarian)`);
117+ client.register(fallback, "solarian");
118+}
119+
120+function isValidEmpire(empire: string): empire is EmpireID {
121+ return ["solarian", "voidborn", "crimson", "nebula", "outerrim"].includes(empire);
122+}
123+
124+async function startActionLoop(): Promise<void> {
125+ if (actionLoopRunning) return;
126+ actionLoopRunning = true;
127+
128+ while (client.state.authenticated) {
129+ try {
130+ const recentActions = memory.getRecentActions(config.maxContextActions);
131+ const recentEvents = memory.getRecentEvents(config.maxContextEvents);
132+ const prompt = buildActionPrompt({
133+ state: client.state,
134+ recentActions,
135+ recentEvents,
136+ includeHelp: includeHelpInPrompt,
137+ });
138+
139+ const promptExcerpt = prompt.slice(0, 1000);
140+ const result = await ollama.generateJson(prompt);
141+ const validation = validateAction(result.json);
142+ if (!validation.ok || !validation.action) {
143+ const message = `Invalid action from LLM: ${validation.error ?? "unknown"}`;
144+ log(message);
145+ memory.appendEvent("llm_invalid_action", { error: validation.error, raw: result.raw });
146+ includeHelpInPrompt = true;
147+ await sleep(config.tickDelayMs);
148+ continue;
149+ }
150+
151+ memory.appendAction(
152+ validation.action.action,
153+ validation.action.args ?? {},
154+ promptExcerpt,
155+ result.raw
156+ );
157+ includeHelpInPrompt = false;
158+
159+ const actionLog = dispatchAction(client, validation.action);
160+ log(`Action: ${actionLog}`);
161+ memory.appendEvent("action_sent", { action: validation.action });
162+ } catch (error) {
163+ log(`Loop error: ${(error as Error).message}`);
164+ memory.appendEvent("loop_error", { message: (error as Error).message });
165+ }
166+
167+ await sleep(config.tickDelayMs);
168+ }
169+
170+ actionLoopRunning = false;
171+}
172+
173+function sleep(ms: number): Promise<void> {
174+ return new Promise((resolve) => setTimeout(resolve, ms));
175+}
176+
177+function formatOkPayload(payload: Record<string, unknown>): string {
178+ if (payload.action) {
179+ return `OK ${payload.action}`;
180+ }
181+ return `OK ${safeJson(payload)}`;
182+}
183+
184+function safeJson(value: unknown): string {
185+ try {
186+ return JSON.stringify(value);
187+ } catch {
188+ return "[unserializable]";
189+ }
190+}
191+
192+function shutdown(): void {
193+ try {
194+ client.disconnect();
195+ } catch {
196+ // ignore
197+ }
198+ tui.destroy();
199+ process.exit(0);
200+}
201+
202+tui.onExit(shutdown);
203+process.on("SIGINT", shutdown);
204+process.on("SIGTERM", shutdown);
205+
206+client.on<WelcomePayload>("welcome", async (data) => {
207+ log(`Welcome: v${data.version} (tick ${data.tick_rate}s)`);
208+ if (data.motd) log(`MOTD: ${data.motd}`);
209+ memory.appendEvent("welcome", data);
210+
211+ if (credentials) {
212+ log(`Auto-login as ${credentials.username}`);
213+ client.login(credentials.username, credentials.token);
214+ } else {
215+ await runRegistrationFlow();
216+ }
217+});
218+
219+client.on<RegisteredPayload>("registered", async (data) => {
220+ memory.appendEvent("registered", data);
221+ if (pendingRegistration) {
222+ await saveCredentials(pendingRegistration.username, data.token);
223+ log(`Registered. Saved credentials for ${pendingRegistration.username}`);
224+ client.login(pendingRegistration.username, data.token);
225+ } else {
226+ log("Registered but no pending registration found.");
227+ }
228+});
229+
230+client.on<LoggedInPayload>("logged_in", (data) => {
231+ log(`Logged in as ${data.player.username} (${data.player.empire})`);
232+ memory.appendEvent("logged_in", data);
233+ updateStatus();
234+ saveSnapshot();
235+ startActionLoop();
236+});
237+
238+client.on<ErrorPayload>("error", (data) => {
239+ log(`Error [${data.code}] ${data.message}`);
240+ memory.appendEvent("error", data);
241+});
242+
243+client.on<StateUpdatePayload>("state_update", (data) => {
244+ memory.appendEvent("state_update", data);
245+ updateStatus();
246+ saveSnapshot();
247+ if (data.in_combat) {
248+ log(`IN COMBAT: Hull ${data.ship.hull}/${data.ship.max_hull} Shield ${data.ship.shield}/${data.ship.max_shield}`);
249+ }
250+});
251+
252+client.on<ChatMessage>("chat_message", (data) => {
253+ log(`[${data.channel}] ${data.sender}: ${data.content}`);
254+ memory.appendEvent("chat_message", data);
255+});
256+
257+client.on<ScanResultPayload>("scan_result", (data) => {
258+ log(`Scan result: ${safeJson(data)}`);
259+ memory.appendEvent("scan_result", data);
260+});
261+
262+client.on("ok", (data: Record<string, unknown>) => {
263+ log(formatOkPayload(data));
264+ memory.appendEvent("ok", data);
265+});
266+
267+client.on("version_info", (data: Record<string, unknown>) => {
268+ log(`Version info: ${safeJson(data)}`);
269+ memory.appendEvent("version_info", data);
270+});
271+
272+credentials = await loadCredentials();
273+await client.connect();
274+updateStatus();
src/memory.ts+133−0
@@ -0,0 +1,133 @@
1+import { Database } from "bun:sqlite";
2+
3+export interface Snapshot {
4+ tick: number;
5+ player: unknown;
6+ ship: unknown;
7+ system: unknown;
8+ poi: unknown;
9+ base: unknown;
10+ nearby: unknown;
11+}
12+
13+export interface StoredAction {
14+ id: number;
15+ ts: string;
16+ action: string;
17+ args: string | null;
18+ prompt_excerpt: string | null;
19+ model_raw: string | null;
20+}
21+
22+export interface StoredEvent {
23+ id: number;
24+ ts: string;
25+ type: string;
26+ payload: string | null;
27+}
28+
29+const MAX_TEXT = 2000;
30+
31+export class MemoryStore {
32+ private db: Database;
33+
34+ constructor(path: string) {
35+ this.db = new Database(path);
36+ this.init();
37+ }
38+
39+ private init(): void {
40+ this.db.exec(`
41+ CREATE TABLE IF NOT EXISTS actions (
42+ id INTEGER PRIMARY KEY AUTOINCREMENT,
43+ ts TEXT NOT NULL,
44+ action TEXT NOT NULL,
45+ args TEXT,
46+ prompt_excerpt TEXT,
47+ model_raw TEXT
48+ );
49+ CREATE TABLE IF NOT EXISTS events (
50+ id INTEGER PRIMARY KEY AUTOINCREMENT,
51+ ts TEXT NOT NULL,
52+ type TEXT NOT NULL,
53+ payload TEXT
54+ );
55+ CREATE TABLE IF NOT EXISTS state_snapshots (
56+ id INTEGER PRIMARY KEY AUTOINCREMENT,
57+ ts TEXT NOT NULL,
58+ tick INTEGER,
59+ player TEXT,
60+ ship TEXT,
61+ system TEXT,
62+ poi TEXT,
63+ base TEXT,
64+ nearby TEXT
65+ );
66+ `);
67+ }
68+
69+ appendAction(action: string, args: unknown, promptExcerpt: string, modelRaw: string): void {
70+ this.db
71+ .query(
72+ "INSERT INTO actions (ts, action, args, prompt_excerpt, model_raw) VALUES (?, ?, ?, ?, ?)"
73+ )
74+ .run(nowIso(), action, toJson(args), truncate(promptExcerpt), truncate(modelRaw));
75+ }
76+
77+ appendEvent(type: string, payload: unknown): void {
78+ this.db
79+ .query("INSERT INTO events (ts, type, payload) VALUES (?, ?, ?)")
80+ .run(nowIso(), type, toJson(payload));
81+ }
82+
83+ saveSnapshot(snapshot: Snapshot): void {
84+ this.db
85+ .query(
86+ "INSERT INTO state_snapshots (ts, tick, player, ship, system, poi, base, nearby) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
87+ )
88+ .run(
89+ nowIso(),
90+ snapshot.tick,
91+ toJson(snapshot.player),
92+ toJson(snapshot.ship),
93+ toJson(snapshot.system),
94+ toJson(snapshot.poi),
95+ toJson(snapshot.base),
96+ toJson(snapshot.nearby)
97+ );
98+ }
99+
100+ getRecentActions(limit: number): StoredAction[] {
101+ const rows = this.db
102+ .query(
103+ "SELECT id, ts, action, args, prompt_excerpt, model_raw FROM actions ORDER BY id DESC LIMIT ?"
104+ )
105+ .all(limit) as StoredAction[];
106+ return rows.reverse();
107+ }
108+
109+ getRecentEvents(limit: number): StoredEvent[] {
110+ const rows = this.db
111+ .query("SELECT id, ts, type, payload FROM events ORDER BY id DESC LIMIT ?")
112+ .all(limit) as StoredEvent[];
113+ return rows.reverse();
114+ }
115+}
116+
117+function nowIso(): string {
118+ return new Date().toISOString();
119+}
120+
121+function toJson(value: unknown): string | null {
122+ try {
123+ return JSON.stringify(value);
124+ } catch {
125+ return null;
126+ }
127+}
128+
129+function truncate(text: string | null | undefined): string | null {
130+ if (!text) return null;
131+ if (text.length <= MAX_TEXT) return text;
132+ return text.slice(0, MAX_TEXT);
133+}
src/ollama.ts+62−0
@@ -0,0 +1,62 @@
1+export interface OllamaResult<T> {
2+ raw: string;
3+ json: T;
4+}
5+
6+export class OllamaAgent {
7+ private baseUrl: string;
8+ private model: string;
9+ private timeoutMs: number;
10+
11+ constructor(baseUrl: string, model: string, timeoutMs: number) {
12+ this.baseUrl = baseUrl;
13+ this.model = model;
14+ this.timeoutMs = timeoutMs;
15+ }
16+
17+ async generateJson<T>(prompt: string): Promise<OllamaResult<T>> {
18+ const controller = new AbortController();
19+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
20+
21+ try {
22+ const response = await fetch(new URL("/api/generate", this.baseUrl), {
23+ method: "POST",
24+ headers: {
25+ "Content-Type": "application/json",
26+ },
27+ body: JSON.stringify({
28+ model: this.model,
29+ prompt,
30+ stream: false,
31+ options: {
32+ temperature: 0.2,
33+ },
34+ }),
35+ signal: controller.signal,
36+ });
37+
38+ if (!response.ok) {
39+ const text = await response.text();
40+ throw new Error(`Ollama error ${response.status}: ${text}`);
41+ }
42+
43+ const data = (await response.json()) as { response?: string };
44+ const raw = data.response ?? "";
45+ const json = parseJsonFromText<T>(raw);
46+
47+ return { raw, json };
48+ } finally {
49+ clearTimeout(timeout);
50+ }
51+ }
52+}
53+
54+function parseJsonFromText<T>(text: string): T {
55+ const start = text.indexOf("{");
56+ const end = text.lastIndexOf("}");
57+ if (start === -1 || end === -1 || end <= start) {
58+ throw new Error("No JSON object found in model response");
59+ }
60+ const slice = text.slice(start, end + 1);
61+ return JSON.parse(slice) as T;
62+}
src/prompt.ts+163−0
@@ -0,0 +1,163 @@
1+import type { ClientState } from "../client/src/client";
2+import type { StoredAction, StoredEvent } from "./memory";
3+
4+export interface PromptContext {
5+ state: ClientState;
6+ recentActions: StoredAction[];
7+ recentEvents: StoredEvent[];
8+ includeHelp: boolean;
9+}
10+
11+const HELP_TEXT = `SpaceMolt Reference Client
12+==========================
13+
14+Connection Commands:
15+ register <username> <empire> - Create new account (empires: solarian, voidborn, crimson, nebula, outerrim)
16+ login <username> <token> - Login to existing account
17+ logout - Logout
18+
19+Navigation:
20+ travel <poi_id> - Travel to a POI within current system
21+ jump <system_id> - Jump to connected system
22+ dock - Dock at current POI's base
23+ undock - Undock from base
24+
25+Mining & Trading:
26+ mine - Mine at current asteroid belt
27+ buy <listing_id> <quantity> - Buy from market
28+ sell <item_id> <quantity> - Sell to market
29+ refuel - Refuel ship
30+ repair - Repair ship
31+
32+Combat:
33+ attack <player_id> - Attack another player
34+ scan <player_id> - Scan another player
35+
36+Information:
37+ status - Show current status
38+ system - Show current system info
39+ poi - Show current POI info
40+ base - Show current base info
41+ nearby - Show nearby players
42+ cargo - Show cargo contents
43+
44+Chat:
45+ say <message> - Send local chat
46+ faction <message> - Send faction chat
47+ msg <player_id> <message> - Send private message
48+
49+Forum:
50+ forum [page] [category] - List forum threads (categories: general, bugs, suggestions, trading, factions)
51+ forum_thread <thread_id> - Read a forum thread
52+ forum_post <cat> <title> | <content> - Create a new thread
53+ forum_reply <thread_id> <msg> - Reply to a thread
54+ forum_upvote <id> - Upvote a thread or reply
55+
56+Other:
57+ help - Show this help
58+ quit - Exit client (or press Ctrl+D)
59+`;
60+
61+export function buildActionPrompt(context: PromptContext): string {
62+ const stateText = formatState(context.state);
63+ const memoryText = formatMemory(context.recentActions, context.recentEvents);
64+ const helpBlock = context.includeHelp ? `\nHELP MENU:\n${HELP_TEXT}` : "";
65+
66+ return `You are an autonomous player for the SpaceMolt MMO (https://www.spacemolt.com/).
67+You will receive current game state and recent events. Choose exactly one action to perform next.
68+Respond ONLY with a single JSON object. No extra text.
69+${helpBlock}
70+
71+CURRENT STATE:
72+${stateText}
73+
74+RECENT MEMORY:
75+${memoryText}
76+
77+ACTION SCHEMA (JSON ONLY):
78+{"action":"travel|jump|dock|undock|mine|attack|scan|buy|sell|refuel|repair|craft|chat|status|system|poi|base|skills|recipes|version|nearby|cargo|wait","args":{...}}
79+
80+REQUIRED ARGS:
81+- travel: {"target_poi":"..."}
82+- jump: {"target_system":"..."}
83+- attack: {"target_id":"..."}
84+- scan: {"target_id":"..."}
85+- buy: {"listing_id":"...","quantity":number}
86+- sell: {"item_id":"...","quantity":number}
87+- craft: {"recipe_id":"..."}
88+- chat: {"channel":"local|faction|private","content":"...","target_id":"..." if channel is private}
89+
90+NOTES:
91+- Use only the listed actions.
92+- If unsure, use {"action":"wait"}.
93+`;
94+}
95+
96+export function buildRegistrationPrompt(includeHelp: boolean): string {
97+ const helpBlock = includeHelp ? `\nHELP MENU:\n${HELP_TEXT}` : "";
98+ return `You are creating a SpaceMolt account. Choose a short, memorable username and an empire.
99+Respond ONLY with JSON. No extra text.
100+${helpBlock}
101+
102+JSON SCHEMA:
103+{"username":"...","empire":"solarian|voidborn|crimson|nebula|outerrim"}
104+`;
105+}
106+
107+function formatState(state: ClientState): string {
108+ const player = state.player;
109+ const ship = state.ship;
110+ const system = state.system;
111+ const poi = state.poi;
112+ const base = state.base;
113+ const nearby = state.nearby ?? [];
114+
115+ const lines: string[] = [];
116+ if (!player || !ship) {
117+ lines.push("Not logged in.");
118+ return lines.join("\n");
119+ }
120+
121+ lines.push(`Player: ${player.username} [${player.empire}] credits=${player.credits}`);
122+ lines.push(`Location: ${system?.name ?? player.current_system} - ${poi?.name ?? player.current_poi}`);
123+ lines.push(`Docked: ${player.docked_at_base ? "yes" : "no"} | In combat: ${state.inCombat ? "yes" : "no"}`);
124+ lines.push(`Ship: hull ${ship.hull}/${ship.max_hull} shield ${ship.shield}/${ship.max_shield} fuel ${ship.fuel}/${ship.max_fuel}`);
125+ lines.push(`Cargo: ${ship.cargo_used}/${ship.cargo_capacity}`);
126+ if (base) {
127+ lines.push(`Base: ${base.name} services=${Object.keys(base.services).filter((k) => (base.services as Record<string, boolean>)[k]).join(",")}`);
128+ }
129+ if (nearby.length > 0) {
130+ const list = nearby
131+ .map((p) => `${p.username ?? p.player_id ?? "unknown"}${p.in_combat ? "(combat)" : ""}`)
132+ .join(", ");
133+ lines.push(`Nearby: ${list}`);
134+ } else {
135+ lines.push("Nearby: none");
136+ }
137+
138+ return lines.join("\n");
139+}
140+
141+function formatMemory(actions: StoredAction[], events: StoredEvent[]): string {
142+ const lines: string[] = [];
143+
144+ if (actions.length === 0 && events.length === 0) {
145+ return "(no recent memory)";
146+ }
147+
148+ if (actions.length > 0) {
149+ lines.push("Actions:");
150+ for (const action of actions) {
151+ lines.push(`- ${action.ts} ${action.action} ${action.args ?? ""}`.trim());
152+ }
153+ }
154+
155+ if (events.length > 0) {
156+ lines.push("Events:");
157+ for (const event of events) {
158+ lines.push(`- ${event.ts} ${event.type} ${event.payload ?? ""}`.trim());
159+ }
160+ }
161+
162+ return lines.join("\n");
163+}
src/tui.ts+101−0
@@ -0,0 +1,101 @@
1+import blessed from "blessed";
2+
3+export class Tui {
4+ private screen: blessed.Widgets.Screen;
5+ private logBox: blessed.Widgets.Log;
6+ private statusBar: blessed.Widgets.BoxElement;
7+ private exitHandler: (() => void) | null = null;
8+
9+ constructor() {
10+ this.screen = blessed.screen({
11+ smartCSR: true,
12+ title: "SpaceMolt Ollama Player",
13+ fullUnicode: false,
14+ });
15+
16+ this.logBox = blessed.log({
17+ parent: this.screen,
18+ top: 0,
19+ left: 0,
20+ width: "100%",
21+ height: "100%-1",
22+ tags: true,
23+ border: "line",
24+ label: "Log",
25+ style: {
26+ border: {
27+ fg: "blue",
28+ },
29+ bg: "black",
30+ fg: "white",
31+ },
32+ scrollable: true,
33+ alwaysScroll: true,
34+ scrollbar: {
35+ ch: " ",
36+ inverse: true,
37+ },
38+ });
39+
40+ this.statusBar = blessed.box({
41+ parent: this.screen,
42+ bottom: 0,
43+ left: 0,
44+ width: "100%",
45+ height: 1,
46+ style: {
47+ bg: "black",
48+ fg: "cyan",
49+ },
50+ content: "Starting...",
51+ });
52+
53+ this.screen.key(["q", "C-c"], () => {
54+ if (this.exitHandler) {
55+ this.exitHandler();
56+ } else {
57+ process.exit(0);
58+ }
59+ });
60+
61+ this.screen.render();
62+ }
63+
64+ onExit(handler: () => void): void {
65+ this.exitHandler = handler;
66+ }
67+
68+ log(message: string): void {
69+ this.logBox.log(colorize(message));
70+ this.screen.render();
71+ }
72+
73+ setStatus(text: string): void {
74+ this.statusBar.setContent(`{cyan-fg}${text}{/cyan-fg}`);
75+ this.screen.render();
76+ }
77+
78+ destroy(): void {
79+ this.screen.destroy();
80+ }
81+}
82+
83+function colorize(message: string): string {
84+ const lower = message.toLowerCase();
85+ if (lower.startsWith("error") || lower.includes("error") || lower.includes("failed")) {
86+ return `{red-fg}${message}{/red-fg}`;
87+ }
88+ if (lower.includes("in combat")) {
89+ return `{red-fg}${message}{/red-fg}`;
90+ }
91+ if (lower.startsWith("action:")) {
92+ return `{cyan-fg}${message}{/cyan-fg}`;
93+ }
94+ if (lower.startsWith("welcome") || lower.startsWith("logged in")) {
95+ return `{green-fg}${message}{/green-fg}`;
96+ }
97+ if (lower.startsWith("motd")) {
98+ return `{yellow-fg}${message}{/yellow-fg}`;
99+ }
100+ return message;
101+}
tsconfig.json+12−0
@@ -0,0 +1,12 @@
1+{
2+ "compilerOptions": {
Cut short: this commit's diff is over 1000 lines.