xonecas.io
5875
Os

ollama-space-molt-player / commit 131136e

feat: enhance autonomous gameplay with extended action system and improved LLM integration

xonecas2026-02-01 131136eeb64199179e666ff4e438f9d38594655e parent 5b03d4f

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

AGENTS.md+138−0
@@ -0,0 +1,138 @@
1+# Agent Guide for ollama-spacemolt-player
2+
3+Purpose: help coding agents work safely and consistently in this repo.
4+
5+## Repo Snapshot
6+- Runtime: Bun (TypeScript, ESM).
7+- UI: terminal UI via `blessed`.
8+- LLM: local Ollama HTTP API.
9+- Data: SQLite via `bun:sqlite` at `memory.sqlite`.
10+- Game client: SpaceMolt reference client is a git submodule in `client/`.
11+
12+## Key Paths
13+- App entry: `src/index.ts` (orchestrates client + LLM + memory + TUI).
14+- LLM client: `src/ollama.ts`.
15+- Prompts: `src/prompt.ts`.
16+- Memory store: `src/memory.ts`.
17+- Actions validation: `src/actions.ts`.
18+- TUI: `src/tui.ts`.
19+- Config: `src/config.ts` (env-driven settings).
20+
21+## Commands (Build / Lint / Test)
22+### Install
23+- `bun install`
24+
25+### Run app
26+- `bun run ollama-play`
27+
28+### Format
29+- `bun run biome:format`
30+
31+### Lint
32+- `bun run biome:lint`
33+
34+### Build
35+- No build script configured. If you add one, document it here.
36+
37+### Tests
38+- Manual testing only (run the app and verify behavior).
39+- No test runner configured; single-test command is not available yet.
40+- If tests are added later, prefer a command that can target a file or test name.
41+
42+## Environment / Config
43+- `OLLAMA_URL` (default: `http://localhost:11434`)
44+- `OLLAMA_MODEL` (default: `qwen3:8b`)
45+- `OLLAMA_TEMPERATURE` (number, default: `0.5`)
46+- `OLLAMA_THINKING` (boolean, default: `true` - enables thinking mode for Qwen3)
47+- `OLLAMA_TIMEOUT_MS` is not present; timeout is configured in `src/config.ts` as `ollamaTimeoutMs`.
48+- `SPACEMOLT_URL` (default: `wss://game.spacemolt.com/ws`)
49+- `DEBUG` (string, enable TUI prompt pane when `true`)
50+- `MEMORY_DB` (default: `memory.sqlite`)
51+
52+## Cursor / Copilot Rules
53+- No Cursor rules found in `.cursor/rules/` or `.cursorrules`.
54+- No Copilot rules found in `.github/copilot-instructions.md`.
55+
56+## Code Style Guidelines
57+
58+### Language and Modules
59+- TypeScript, ESM (`"type": "module"` in `package.json`).
60+- Prefer `import type` for type-only imports.
61+- Use explicit exports and named exports when possible.
62+
63+### Formatting
64+- Use Biome for formatting and linting.
65+- Keep formatting consistent with existing files (tabs for indent, semicolons, double quotes).
66+- Avoid manual reformatting; let Biome handle it.
67+
68+### Imports
69+- Order: external modules first, then local modules.
70+- Keep import lists stable; do not reorder unless needed for clarity.
71+- Prefer `import type` to avoid runtime type imports.
72+
73+### Naming Conventions
74+- Types/interfaces: `PascalCase`.
75+- Classes: `PascalCase`.
76+- Functions and variables: `camelCase`.
77+- Constants: `SCREAMING_SNAKE_CASE` for global constants; `camelCase` for local consts.
78+- File names: `lowercase` with `.ts`.
79+
80+### Types and Strictness
81+- `strict` TypeScript is enabled. Avoid `any`.
82+- Use `unknown` then narrow or validate.
83+- Prefer explicit return types for public functions.
84+- Prefer `null` over `undefined` when a value is intentionally absent (matches current code style).
85+
86+### Error Handling
87+- Use `try/catch` around external I/O (HTTP, file, DB).
88+- Throw typed errors where appropriate (see `OllamaTimeoutError`).
89+- Validate external inputs; return structured errors (see `validateAction`).
90+- Log errors with context and keep user-facing messaging concise.
91+
92+### Side Effects and State
93+- Keep side effects in `src/index.ts`; helper modules should stay pure when possible.
94+- Avoid hidden global state; prefer explicit parameters.
95+- Use small, focused functions for validation and formatting.
96+
97+### Prompts and LLM Outputs
98+- LLM calls must expect malformed output; parse defensively.
99+- Enforce JSON-only responses and validate fields before use.
100+- Keep prompt updates in `src/prompt.ts`.
101+
102+### TUI
103+- Use `blessed` widgets and keep rendering in `src/tui.ts`.
104+- Avoid adding Unicode-heavy UI unless needed (TUI uses `fullUnicode: false`).
105+
106+### SQLite / Memory
107+- Centralize DB operations in `src/memory.ts`.
108+- Serialize JSON using helper functions; guard against JSON stringify errors.
109+- Keep text fields reasonably bounded (see `MAX_TEXT`).
110+
111+### Game Client
112+- Use the reference client from `client/`.
113+- Avoid changing `client/` unless the change is intended for the submodule.
114+
115+## Editing Safety
116+- Do not edit `memory.sqlite` or `.spacemolt-bot-credentials.json`.
117+- Do not commit secrets or credentials.
118+- Keep changes minimal and aligned with the current architecture.
119+
120+## Conventions in This Repo
121+- Use small, focused helpers for formatting and validation.
122+- Prefer explicit `if` branches to implicit coercion.
123+- Use early returns for invalid states.
124+- Maintain descriptive log messages for TUI output.
125+
126+## When Adding New Features
127+- Update prompts and validation together.
128+- Add to memory tracking only if it improves LLM context.
129+- Keep tick timing aligned with server tick (10s; local uses 11s).
130+
131+## If You Add Tests Later
132+- Document the test framework and single-test command here.
133+- Prefer a runner that supports file and name filtering.
134+
135+## Quick Review Checklist
136+- `bun run biome:lint`
137+- `bun run biome:format`
138+- Manual run: `bun run ollama-play`
src/actions.ts+235−0
@@ -1,4 +1,5 @@
11 import type { SpaceMoltClient } from "../client/src/client";
2+import type { EmpireID } from "../client/src/types";
23
34 export interface ActionDecision {
45 action: string;
@@ -8,7 +9,53 @@ export interface ActionDecision {
89
910 export const MAX_GOAL_LENGTH = 120;
1011
12+export type PersonalityType =
13+ | "explorer"
14+ | "merchant"
15+ | "warrior"
16+ | "diplomat"
17+ | "pragmatist";
18+
19+export const PERSONALITY_ARCHETYPES: Record<
20+ PersonalityType,
21+ { name: string; emoji: string; description: string }
22+> = {
23+ explorer: {
24+ name: "Explorer",
25+ emoji: "🔍",
26+ description:
27+ "Curious investigator who seeks new systems, shares discoveries, and frequently engages with forums to learn and contribute knowledge.",
28+ },
29+ merchant: {
30+ name: "Merchant",
31+ emoji: "💰",
32+ description:
33+ "Trade-focused opportunist who monitors markets, posts trade offers, and builds wealth through smart economic decisions.",
34+ },
35+ warrior: {
36+ name: "Warrior",
37+ emoji: "⚔️",
38+ description:
39+ "Combat-driven competitor who seeks battles, shares victory reports, and isn't afraid to taunt opponents or discuss conflicts.",
40+ },
41+ diplomat: {
42+ name: "Diplomat",
43+ emoji: "🤝",
44+ description:
45+ "Socially-focused alliance builder who greets others, coordinates via faction chat, and actively participates in community discussions.",
46+ },
47+ pragmatist: {
48+ name: "Pragmatist",
49+ emoji: "🎯",
50+ description:
51+ "Balanced efficiency expert who interacts when beneficial, focuses on measurable progress, and avoids unnecessary distractions.",
52+ },
53+};
54+
1155 const ACTIONS: Record<string, string[]> = {
56+ register: ["username", "empire"],
57+ login: ["username", "token"],
58+ logout: [],
1259 travel: ["target_poi"],
1360 jump: ["target_system"],
1461 dock: [],
@@ -22,6 +69,9 @@ const ACTIONS: Record<string, string[]> = {
2269 repair: [],
2370 craft: ["recipe_id"],
2471 chat: ["channel", "content"],
72+ say: ["content"],
73+ faction: ["content"],
74+ msg: ["target_id", "content"],
2575 status: [],
2676 system: [],
2777 poi: [],
@@ -31,6 +81,12 @@ const ACTIONS: Record<string, string[]> = {
3181 version: [],
3282 nearby: [],
3383 cargo: [],
84+ forum: [],
85+ forum_thread: ["thread_id"],
86+ forum_post: ["category", "title", "content"],
87+ forum_reply: ["thread_id", "content"],
88+ forum_upvote: [],
89+ help: [],
3490 wait: [],
3591 };
3692
@@ -97,9 +153,132 @@ export function validateAction(decision: unknown): {
97153 }
98154 }
99155
156+ if (action === "say" || action === "faction") {
157+ const content = String(args.content ?? "");
158+ if (!content) {
159+ return { ok: false, error: `${action}.content is required` };
160+ }
161+ }
162+
163+ if (action === "msg") {
164+ const targetId = String(args.target_id ?? "");
165+ const content = String(args.content ?? "");
166+ if (!targetId) {
167+ return { ok: false, error: "msg.target_id is required" };
168+ }
169+ if (!content) {
170+ return { ok: false, error: "msg.content is required" };
171+ }
172+ }
173+
174+ if (action === "register") {
175+ const username = String(args.username ?? "").trim();
176+ const empire = String(args.empire ?? "").trim();
177+ const personality = String(args.personality ?? "").trim();
178+ if (!username) {
179+ return { ok: false, error: "register.username is required" };
180+ }
181+ if (!empire) {
182+ return { ok: false, error: "register.empire is required" };
183+ }
184+ if (!isValidEmpire(empire)) {
185+ return { ok: false, error: "register.empire is invalid" };
186+ }
187+ if (!personality) {
188+ return { ok: false, error: "register.personality is required" };
189+ }
190+ if (!isValidPersonality(personality)) {
191+ return { ok: false, error: "register.personality is invalid" };
192+ }
193+ }
194+
195+ if (action === "login") {
196+ const username = String(args.username ?? "").trim();
197+ const token = String(args.token ?? "").trim();
198+ if (!username) {
199+ return { ok: false, error: "login.username is required" };
200+ }
201+ if (!token) {
202+ return { ok: false, error: "login.token is required" };
203+ }
204+ }
205+
206+ if (action === "forum") {
207+ if (args.page !== undefined) {
208+ const page = Number(args.page);
209+ if (!Number.isFinite(page) || page < 0) {
210+ return { ok: false, error: "forum.page must be a non-negative number" };
211+ }
212+ }
213+ if (args.category !== undefined) {
214+ const category = String(args.category ?? "").trim();
215+ if (!category) {
216+ return { ok: false, error: "forum.category cannot be empty" };
217+ }
218+ }
219+ }
220+
221+ if (action === "forum_thread") {
222+ const threadId = String(args.thread_id ?? "").trim();
223+ if (!threadId) {
224+ return { ok: false, error: "forum_thread.thread_id is required" };
225+ }
226+ }
227+
228+ if (action === "forum_post") {
229+ const category = String(args.category ?? "").trim();
230+ const title = String(args.title ?? "").trim();
231+ const content = String(args.content ?? "").trim();
232+ if (!category) {
233+ return { ok: false, error: "forum_post.category is required" };
234+ }
235+ if (!title) {
236+ return { ok: false, error: "forum_post.title is required" };
237+ }
238+ if (!content) {
239+ return { ok: false, error: "forum_post.content is required" };
240+ }
241+ }
242+
243+ if (action === "forum_reply") {
244+ const threadId = String(args.thread_id ?? "").trim();
245+ const content = String(args.content ?? "").trim();
246+ if (!threadId) {
247+ return { ok: false, error: "forum_reply.thread_id is required" };
248+ }
249+ if (!content) {
250+ return { ok: false, error: "forum_reply.content is required" };
251+ }
252+ }
253+
254+ if (action === "forum_upvote") {
255+ const threadId = String(args.thread_id ?? "").trim();
256+ const replyId = String(args.reply_id ?? "").trim();
257+ if (!threadId && !replyId) {
258+ return {
259+ ok: false,
260+ error: "forum_upvote requires thread_id or reply_id",
261+ };
262+ }
263+ }
264+
100265 return { ok: true, action: { action, args, goal } };
101266 }
102267
268+function isValidEmpire(empire: string): empire is EmpireID {
269+ return ["solarian", "voidborn", "crimson", "nebula", "outerrim"].includes(
270+ empire,
271+ );
272+}
273+
274+function isValidPersonality(
275+ personality: string,
276+): personality is PersonalityType {
277+ return ["explorer", "merchant", "warrior", "diplomat", "pragmatist"].includes(
278+ personality,
279+ );
280+}
281+
103282 export function dispatchAction(
104283 client: SpaceMoltClient,
105284 decision: ActionDecision,
@@ -107,6 +286,15 @@ export function dispatchAction(
107286 const args = decision.args ?? {};
108287
109288 switch (decision.action) {
289+ case "register":
290+ client.register(String(args.username), String(args.empire) as EmpireID);
291+ return `register ${String(args.username)}`;
292+ case "login":
293+ client.login(String(args.username), String(args.token));
294+ return `login ${String(args.username)}`;
295+ case "logout":
296+ client.logout();
297+ return "logout";
110298 case "travel":
111299 client.travel(String(args.target_poi));
112300 return `travel ${String(args.target_poi)}`;
@@ -150,6 +338,15 @@ export function dispatchAction(
150338 args.target_id ? String(args.target_id) : undefined,
151339 );
152340 return `chat ${String(args.channel)}`;
341+ case "say":
342+ client.localChat(String(args.content));
343+ return "say";
344+ case "faction":
345+ client.factionChat(String(args.content));
346+ return "faction";
347+ case "msg":
348+ client.privateMessage(String(args.target_id), String(args.content));
349+ return `msg ${String(args.target_id)}`;
153350 case "status":
154351 client.getStatus();
155352 return "get status";
@@ -175,6 +372,44 @@ export function dispatchAction(
175372 return "nearby (from state)";
176373 case "cargo":
177374 return "cargo (from state)";
375+ case "forum": {
376+ const page = args.page !== undefined ? Number(args.page) : undefined;
377+ const category =
378+ args.category !== undefined ? String(args.category) : undefined;
379+ if (page === undefined && category === undefined) {
380+ client.forumList();
381+ } else if (category === undefined) {
382+ client.forumList(page ?? 0);
383+ } else {
384+ client.forumList(page ?? 0, category);
385+ }
386+ return "forum list";
387+ }
388+ case "forum_thread":
389+ client.forumGetThread(String(args.thread_id));
390+ return `forum thread ${String(args.thread_id)}`;
391+ case "forum_post":
392+ client.forumCreateThread(
393+ String(args.title),
394+ String(args.content),
395+ String(args.category),
396+ );
397+ return "forum post";
398+ case "forum_reply":
399+ client.forumReply(String(args.thread_id), String(args.content));
400+ return `forum reply ${String(args.thread_id)}`;
401+ case "forum_upvote":
402+ if (args.thread_id) {
403+ client.forumUpvote(String(args.thread_id));
404+ return `forum upvote ${String(args.thread_id)}`;
405+ }
406+ if (args.reply_id) {
407+ client.forumUpvote(undefined, String(args.reply_id));
408+ return `forum upvote ${String(args.reply_id)}`;
409+ }
410+ return "forum upvote";
411+ case "help":
412+ return "help";
178413 case "wait":
179414 return "wait";
180415 default:
src/config.ts+7−0
@@ -1,6 +1,13 @@
11 export const config = {
22 ollamaUrl: process.env.OLLAMA_URL ?? "http://localhost:11434",
33 ollamaModel: process.env.OLLAMA_MODEL ?? "qwen3:8b",
4+ ollamaTemperature: (() => {
5+ const raw = process.env.OLLAMA_TEMPERATURE;
6+ if (!raw) return 0.5;
7+ const value = Number(raw);
8+ return Number.isFinite(value) ? value : 0.5;
9+ })(),
10+ ollamaThinking: process.env.OLLAMA_THINKING !== "false",
411 spacemoltUrl: process.env.SPACEMOLT_URL ?? "wss://game.spacemolt.com/ws",
512 debug: process.env.DEBUG === "true",
613 memoryPath: process.env.MEMORY_DB ?? "memory.sqlite",
src/index.ts+222−13
@@ -11,7 +11,12 @@ import type {
1111 StateUpdatePayload,
1212 WelcomePayload,
1313 } from "../client/src/types";
14-import { dispatchAction, validateAction } from "./actions";
14+import {
15+ dispatchAction,
16+ PERSONALITY_ARCHETYPES,
17+ type PersonalityType,
18+ validateAction,
19+} from "./actions";
1520 import { config } from "./config";
1621 import { MemoryStore } from "./memory";
1722 import { OllamaAgent, OllamaTimeoutError } from "./ollama";
@@ -22,14 +27,25 @@ import {
2227 } from "./prompt";
2328 import { Tui } from "./tui";
2429
25-type Credentials = { username: string; token: string };
26-type RegistrationChoice = { username: string; empire: EmpireID };
30+type Credentials = {
31+ username: string;
32+ token: string;
33+ personality: PersonalityType;
34+};
35+type RegistrationChoice = {
36+ username: string;
37+ empire: EmpireID;
38+ personality: PersonalityType;
39+ personality_reason?: string;
40+};
2741
2842 const memory = new MemoryStore(config.memoryPath);
2943 const ollama = new OllamaAgent(
3044 config.ollamaUrl,
3145 config.ollamaModel,
3246 config.ollamaTimeoutMs,
47+ config.ollamaTemperature,
48+ config.ollamaThinking,
3349 );
3450 const tui = new Tui(config.debug);
3551
@@ -46,7 +62,12 @@ const worldSnapshot: WorldSnapshot = {};
4662 let registrationRetries = 0;
4763 let travelInProgress = false;
4864 let lastTravelTarget: string | null = null;
65+let jumpInProgress = false;
66+let lastJumpTarget: string | null = null;
4967 let currentGoal: string | null = null;
68+let lastSystemId: string | null = null;
69+let lastPoiId: string | null = null;
70+let lastDocked = false;
5071 const MAX_REGISTRATION_RETRIES = 3;
5172 const failedRegistrationNames: string[] = [];
5273
@@ -62,8 +83,12 @@ async function loadCredentials(): Promise<Credentials | null> {
6283 return null;
6384 }
6485
65-async function saveCredentials(username: string, token: string): Promise<void> {
66- const data: Credentials = { username, token };
86+async function saveCredentials(
87+ username: string,
88+ token: string,
89+ personality: PersonalityType,
90+): Promise<void> {
91+ const data: Credentials = { username, token, personality };
6792 await Bun.write(config.credentialsFile, JSON.stringify(data, null, 2));
6893 }
6994
@@ -83,6 +108,8 @@ function updateStatus(): void {
83108 worldSnapshot,
84109 travelInProgress,
85110 lastTravelTarget,
111+ jumpInProgress,
112+ lastJumpTarget,
86113 currentGoal,
87114 );
88115 const sidebarText = formatSidebar(
@@ -90,6 +117,9 @@ function updateStatus(): void {
90117 worldSnapshot,
91118 travelInProgress,
92119 lastTravelTarget,
120+ jumpInProgress,
121+ lastJumpTarget,
122+ credentials?.personality,
93123 );
94124 tui.setStatus(statusText);
95125 tui.setSidebar(sidebarText);
@@ -116,13 +146,37 @@ async function runRegistrationFlow(): Promise<void> {
116146 const prompt = buildRegistrationPrompt(true, failedRegistrationNames);
117147 tui.setPrompt(prompt);
118148 const result = await ollama.generateJson<RegistrationChoice>(prompt);
149+ if (result.thinking) {
150+ log(
151+ `[Thinking] ${result.thinking.slice(0, 200)}${result.thinking.length > 200 ? "..." : ""}`,
152+ );
153+ }
119154 const username = String(result.json.username ?? "").trim();
120155 const empire = String(result.json.empire ?? "").trim() as EmpireID;
121- if (!username || !isValidEmpire(empire)) {
156+ const personality = String(
157+ result.json.personality ?? "",
158+ ).trim() as PersonalityType;
159+ const personalityReason = result.json.personality_reason
160+ ? String(result.json.personality_reason).trim()
161+ : undefined;
162+ if (
163+ !username ||
164+ !isValidEmpire(empire) ||
165+ !isValidPersonality(personality)
166+ ) {
122167 throw new Error("Invalid registration response");
123168 }
124- pendingRegistration = { username, empire };
169+ pendingRegistration = {
170+ username,
171+ empire,
172+ personality,
173+ personality_reason: personalityReason,
174+ };
175+ const personalityInfo = PERSONALITY_ARCHETYPES[personality];
125176 log(`Registering new account: ${username} (${empire})`);
177+ log(
178+ `Chosen personality: ${personalityInfo.emoji} ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
179+ );
126180 client.register(username, empire);
127181 return;
128182 } catch (error) {
@@ -131,8 +185,12 @@ async function runRegistrationFlow(): Promise<void> {
131185 }
132186
133187 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
134- pendingRegistration = { username: fallback, empire: "solarian" };
135- log(`Falling back to account: ${fallback} (solarian)`);
188+ pendingRegistration = {
189+ username: fallback,
190+ empire: "solarian",
191+ personality: "pragmatist",
192+ };
193+ log(`Falling back to account: ${fallback} (solarian, pragmatist)`);
136194 client.register(fallback, "solarian");
137195 }
138196
@@ -142,13 +200,70 @@ function isValidEmpire(empire: string): empire is EmpireID {
142200 );
143201 }
144202
203+function isValidPersonality(
204+ personality: string,
205+): personality is PersonalityType {
206+ return ["explorer", "merchant", "warrior", "diplomat", "pragmatist"].includes(
207+ personality,
208+ );
209+}
210+
211+function refreshSnapshotForLocation(player: {
212+ current_system?: string;
213+ current_poi?: string;
214+ docked_at_base?: string | boolean | null;
215+}): void {
216+ const systemId = player.current_system ?? null;
217+ const poiId = player.current_poi ?? null;
218+ const docked = Boolean(player.docked_at_base);
219+ const systemChanged = systemId && systemId !== lastSystemId;
220+ const poiChanged = poiId && poiId !== lastPoiId;
221+
222+ if (systemChanged) {
223+ worldSnapshot.system = null;
224+ worldSnapshot.pois = [];
225+ worldSnapshot.poi = null;
226+ worldSnapshot.base = null;
227+ client.state.system = null;
228+ client.state.poi = null;
229+ client.state.base = null;
230+ client.getSystem();
231+ client.getPOI();
232+ if (docked) {
233+ client.getBase();
234+ }
235+ } else if (poiChanged) {
236+ worldSnapshot.poi = null;
237+ worldSnapshot.base = null;
238+ client.state.poi = null;
239+ client.state.base = null;
240+ client.getPOI();
241+ if (docked) {
242+ client.getBase();
243+ }
244+ }
245+
246+ if (!docked && lastDocked) {
247+ worldSnapshot.base = null;
248+ client.state.base = null;
249+ }
250+
251+ if (docked && !lastDocked && !systemChanged && !poiChanged) {
252+ client.getBase();
253+ }
254+
255+ if (systemId) lastSystemId = systemId;
256+ if (poiId) lastPoiId = poiId;
257+ lastDocked = docked;
258+}
259+
145260 async function startActionLoop(): Promise<void> {
146261 if (actionLoopRunning) return;
147262 actionLoopRunning = true;
148263
149264 while (client.state.authenticated) {
150265 try {
151- if (travelInProgress) {
266+ if (travelInProgress || jumpInProgress) {
152267 await sleep(config.tickDelayMs);
153268 continue;
154269 }
@@ -161,12 +276,18 @@ async function startActionLoop(): Promise<void> {
161276 worldSnapshot,
162277 recentHistory,
163278 currentGoal,
279+ personality: credentials?.personality,
164280 });
165281
166282 tui.setPrompt(prompt);
167283
168284 const promptExcerpt = prompt.slice(0, 1000);
169285 const result = await ollama.generateJson(prompt);
286+ if (result.thinking) {
287+ log(
288+ `[Thinking] ${result.thinking.slice(0, 200)}${result.thinking.length > 200 ? "..." : ""}`,
289+ );
290+ }
170291 const validation = validateAction(result.json);
171292 if (!validation.ok || !validation.action) {
172293 const message = `Invalid action from LLM: ${validation.error ?? "unknown"}`;
@@ -213,6 +334,10 @@ async function startActionLoop(): Promise<void> {
213334 lastTravelTarget =
214335 String(validation.action.args?.target_poi ?? "").trim() || null;
215336 }
337+ if (actionName === "jump") {
338+ lastJumpTarget =
339+ String(validation.action.args?.target_system ?? "").trim() || null;
340+ }
216341 const actionLog = dispatchAction(client, validation.action);
217342 log(`Action: ${actionLog}`);
218343 memory.appendEvent("action_sent", { action: validation.action });
@@ -327,7 +452,16 @@ client.on<RegisteredPayload>("registered", async (data) => {
327452 registrationRetries = 0;
328453 failedRegistrationNames.length = 0;
329454 if (pendingRegistration) {
330- await saveCredentials(pendingRegistration.username, data.token);
455+ await saveCredentials(
456+ pendingRegistration.username,
457+ data.token,
458+ pendingRegistration.personality,
459+ );
460+ credentials = {
461+ username: pendingRegistration.username,
462+ token: data.token,
463+ personality: pendingRegistration.personality,
464+ };
331465 log(`Registered. Saved credentials for ${pendingRegistration.username}`);
332466 pendingRegistration = null;
333467 } else {
@@ -340,6 +474,9 @@ client.on<LoggedInPayload>("logged_in", (data) => {
340474 memory.appendEvent("logged_in", data);
341475 worldSnapshot.system = data.system;
342476 worldSnapshot.poi = data.poi;
477+ lastSystemId = data.player.current_system ?? null;
478+ lastPoiId = data.player.current_poi ?? null;
479+ lastDocked = Boolean(data.player.docked_at_base);
343480 currentGoal = memory.getLatestGoal(data.player.username);
344481 client.getSystem();
345482 client.getPOI();
@@ -374,6 +511,7 @@ client.on<ErrorPayload>("error", (data) => {
374511
375512 client.on<StateUpdatePayload>("state_update", (data) => {
376513 memory.appendEvent("state_update", data);
514+ refreshSnapshotForLocation(data.player);
377515 updateStatus();
378516 saveSnapshot();
379517 if (data.in_combat) {
@@ -401,12 +539,21 @@ client.on("ok", (data: Record<string, unknown>) => {
401539 if (action === "travel") {
402540 travelInProgress = true;
403541 }
542+ if (action === "jump") {
543+ jumpInProgress = true;
544+ }
404545 if (action === "arrived") {
405546 travelInProgress = false;
406547 lastTravelTarget = null;
407548 client.getSystem();
408549 client.getPOI();
409550 }
551+ if (action === "jumped") {
552+ jumpInProgress = false;
553+ lastJumpTarget = null;
554+ client.getSystem();
555+ client.getPOI();
556+ }
410557 });
411558
412559 client.on("version_info", (data: Record<string, unknown>) => {
@@ -415,6 +562,22 @@ client.on("version_info", (data: Record<string, unknown>) => {
415562 });
416563
417564 credentials = await loadCredentials();
565+
566+// Force re-registration if personality is missing
567+if (credentials && !credentials.personality) {
568+ log("Credentials missing personality field - forcing re-registration");
569+ try {
570+ await Bun.write(config.credentialsFile, ""); // Clear file
571+ const file = Bun.file(config.credentialsFile);
572+ if (await file.exists()) {
573+ await file.remove?.();
574+ }
575+ } catch (error) {
576+ log(`Failed to delete credentials: ${(error as Error).message}`);
577+ }
578+ credentials = null;
579+}
580+
418581 await client.connect();
419582 updateStatus();
420583
@@ -441,10 +604,16 @@ function buildStatusText(
441604 snapshot: WorldSnapshot,
442605 traveling: boolean,
443606 travelTargetId: string | null,
607+ jumping: boolean,
608+ jumpTargetId: string | null,
444609 goal: string | null,
445610 ): string {
446611 if (!state.player || !state.ship) return "Not logged in";
447612 const goalText = goal?.trim() ? ` | Goal: ${goal.trim()}` : "";
613+ if (jumping) {
614+ const destination = resolveSystemName(jumpTargetId, snapshot, state);
615+ return `Jumping to ${destination}${goalText}`;
616+ }
448617 if (traveling) {
449618 const destination = resolvePoiName(travelTargetId, snapshot, state);
450619 return `Traveling to ${destination}${goalText}`;
@@ -459,6 +628,9 @@ function formatSidebar(
459628 snapshot: WorldSnapshot,
460629 traveling: boolean,
461630 travelTargetId: string | null,
631+ jumping: boolean,
632+ jumpTargetId: string | null,
633+ personality?: PersonalityType,
462634 ): string {
463635 if (!state.player || !state.ship) return "Not logged in.";
464636
@@ -480,13 +652,27 @@ function formatSidebar(
480652 const base = snapshot.base ?? state.base;
481653 const pois = snapshot.pois ?? [];
482654
483- pushSection("Player", [
655+ const playerLines = [
484656 formatLine("Name", state.player.username, width),
485657 formatLine("Empire", state.player.empire, width),
658+ ];
659+ if (personality) {
660+ const personalityInfo = PERSONALITY_ARCHETYPES[personality];
661+ playerLines.push(
662+ formatLine(
663+ "Role",
664+ `${personalityInfo.emoji} ${personalityInfo.name}`,
665+ width,
666+ ),
667+ );
668+ }
669+ playerLines.push(
486670 formatLine("Credits", String(state.player.credits), width),
487671 formatLine("Docked", state.player.docked_at_base ? "Y" : "N", width),
488672 formatLine("Tick", String(state.currentTick), width),
489- ]);
673+ );
674+
675+ pushSection("Player", playerLines);
490676
491677 pushSection("Ship", [
492678 formatLine("Hull", `${state.ship.hull}/${state.ship.max_hull}`, width),
@@ -511,6 +697,7 @@ function formatSidebar(
511697 ),
512698 formatLine("POI", poi?.name ?? state.player.current_poi ?? "-", width),
513699 formatLine("Travel", traveling ? "Y" : "N", width),
700+ formatLine("Jump", jumping ? "Y" : "N", width),
514701 ];
515702 if (traveling) {
516703 locationLines.push(
@@ -521,6 +708,15 @@ function formatSidebar(
521708 ),
522709 );
523710 }
711+ if (jumping) {
712+ locationLines.push(
713+ formatLine(
714+ "JumpDest",
715+ resolveSystemName(jumpTargetId, snapshot, state),
716+ width,
717+ ),
718+ );
719+ }
524720 pushSection("Location", locationLines);
525721
526722 const poiLines = formatPoiLines(pois, system?.pois, width);
@@ -562,6 +758,19 @@ function styleLine(line: string): string {
562758 return line;
563759 }
564760
761+function resolveSystemName(
762+ systemId: string | null | undefined,
763+ snapshot: WorldSnapshot,
764+ state: ClientState,
765+): string {
766+ if (!systemId) return "Unknown";
767+ if (snapshot.system?.id === systemId && snapshot.system.name)
768+ return snapshot.system.name;
769+ if (state.system?.id === systemId && state.system.name)
770+ return state.system.name;
771+ return systemId;
772+}
773+
565774 function resolvePoiName(
566775 poiId: string | null | undefined,
567776 snapshot: WorldSnapshot,
src/ollama.ts+33−11
@@ -1,6 +1,7 @@
11 export interface OllamaResult<T> {
22 raw: string;
33 json: T;
4+ thinking?: string;
45 }
56
67 export class OllamaTimeoutError extends Error {
@@ -14,11 +15,21 @@ export class OllamaAgent {
1415 private baseUrl: string;
1516 private model: string;
1617 private timeoutMs: number;
18+ private temperature: number;
19+ private enableThinking: boolean;
1720
18- constructor(baseUrl: string, model: string, timeoutMs: number) {
21+ constructor(
22+ baseUrl: string,
23+ model: string,
24+ timeoutMs: number,
25+ temperature: number,
26+ enableThinking = true,
27+ ) {
1928 this.baseUrl = baseUrl;
2029 this.model = model;
2130 this.timeoutMs = timeoutMs;
31+ this.temperature = temperature;
32+ this.enableThinking = enableThinking;
2233 }
2334
2435 async generateJson<T>(prompt: string): Promise<OllamaResult<T>> {
@@ -26,19 +37,26 @@ export class OllamaAgent {
2637 const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
2738
2839 try {
40+ const requestBody: Record<string, unknown> = {
41+ model: this.model,
42+ prompt,
43+ stream: false,
44+ options: {
45+ temperature: this.temperature,
46+ },
47+ };
48+
49+ // Enable thinking mode for Qwen3 models
50+ if (this.enableThinking) {
51+ requestBody.think = true;
52+ }
53+
2954 const response = await fetch(new URL("/api/generate", this.baseUrl), {
3055 method: "POST",
3156 headers: {
3257 "Content-Type": "application/json",
3358 },
34- body: JSON.stringify({
35- model: this.model,
36- prompt,
37- stream: false,
38- options: {
39- temperature: 0.2,
40- },
41- }),
59+ body: JSON.stringify(requestBody),
4260 signal: controller.signal,
4361 });
4462
@@ -47,11 +65,15 @@ export class OllamaAgent {
4765 throw new Error(`Ollama error ${response.status}: ${text}`);
4866 }
4967
50- const data = (await response.json()) as { response?: string };
68+ const data = (await response.json()) as {
69+ response?: string;
70+ thinking?: string;
71+ };
5172 const raw = data.response ?? "";
73+ const thinking = data.thinking;
5274 const json = parseJsonFromText<T>(raw);
5375
54- return { raw, json };
76+ return { raw, json, thinking };
5577 } catch (error) {
5678 if (error instanceof DOMException && error.name === "AbortError") {
5779 throw new OllamaTimeoutError(this.timeoutMs);
src/prompt.ts+121−10
@@ -1,6 +1,10 @@
11 import type { ClientState } from "../client/src/client";
22 import type { Base, POI, System } from "../client/src/types";
3-import { MAX_GOAL_LENGTH } from "./actions";
3+import {
4+ MAX_GOAL_LENGTH,
5+ PERSONALITY_ARCHETYPES,
6+ type PersonalityType,
7+} from "./actions";
48 import type { HistoryEntry } from "./memory";
59
610 export interface PromptContext {
@@ -8,6 +12,7 @@ export interface PromptContext {
812 worldSnapshot?: WorldSnapshot;
913 recentHistory: HistoryEntry[];
1014 currentGoal: string | null;
15+ personality?: PersonalityType;
1116 }
1217
1318 export interface WorldSnapshot {
@@ -17,7 +22,51 @@ export interface WorldSnapshot {
1722 base?: Base | null;
1823 }
1924
20-const HELP_TEXT = `SpaceMolt Reference Client
25+function getPersonalityGuidance(personality: PersonalityType): string {
26+ switch (personality) {
27+ case "explorer":
28+ return `As an Explorer, you prioritize discovery and knowledge:
29+- After visiting a new system or POI, consider posting about discoveries in forums
30+- When encountering unknown mechanics or items, check forums for related threads
31+- Regularly use 'forum' command to browse recent discoveries and contribute findings
32+- Share interesting observations with nearby players via chat
33+- Jump to new systems frequently to expand your map knowledge`;
34+
35+ case "merchant":
36+ return `As a Merchant, you focus on trade and economic opportunities:
37+- Check forums 'trading' category when docked to find trade opportunities
38+- Post trade offers in faction chat when you have excess goods or need items
39+- Monitor market listings and share good deals in forums when profitable
40+- Prioritize docking at stations to access markets and check prices
41+- Build relationships with other traders through chat and forum interactions`;
Cut short: this commit's diff is over 1000 lines.
src/tui.ts+3−0
Cut short: this commit's diff is over 1000 lines.