xonecas.io
5875
Os

ollama-space-molt-player / commit 7b186b3

feat: expand gameplay loop with enhanced prompt and action handling

xonecas2026-02-01 7b186b3e78f1352cf55d294eae45554ab9d9038b parent a87eb52

6 files changed

src/actions.ts+3−0
@@ -28,6 +28,7 @@ const ACTIONS: Record<string, string[]> = {
2828 version: [],
2929 nearby: [],
3030 cargo: [],
31+ help: [],
3132 wait: [],
3233 };
3334
@@ -147,6 +148,8 @@ export function dispatchAction(client: SpaceMoltClient, decision: ActionDecision
147148 return "nearby (from state)";
148149 case "cargo":
149150 return "cargo (from state)";
151+ case "help":
152+ return "help";
150153 case "wait":
151154 return "wait";
152155 default:
src/config.ts+2−2
@@ -6,7 +6,7 @@ export const config = {
66 memoryPath: process.env.MEMORY_DB ?? "memory.sqlite",
77 credentialsFile: ".spacemolt-bot-credentials.json",
88 tickDelayMs: 11000,
9- maxContextActions: 10,
10- maxContextEvents: 20,
9+ maxContextActions: 5,
10+ maxContextEvents: 5,
1111 ollamaTimeoutMs: 60000,
1212 };
src/index.ts+217−40
@@ -1,4 +1,5 @@
11 import { SpaceMoltClient } from "../client/src/client";
2+import type { ClientState } from "../client/src/client";
23 import type {
34 WelcomePayload,
45 RegisteredPayload,
@@ -8,6 +9,7 @@ import type {
89 ChatMessage,
910 ScanResultPayload,
1011 EmpireID,
12+ CargoItem,
1113 } from "../client/src/types";
1214 import { config } from "./config";
1315 import { MemoryStore } from "./memory";
@@ -21,11 +23,11 @@ type RegistrationChoice = { username: string; empire: EmpireID };
2123
2224 const memory = new MemoryStore(config.memoryPath);
2325 const ollama = new OllamaAgent(config.ollamaUrl, config.ollamaModel, config.ollamaTimeoutMs);
24-const tui = new Tui();
26+const tui = new Tui(config.debug);
2527
2628 const client = new SpaceMoltClient({
2729 url: config.spacemoltUrl,
28- debug: config.debug,
30+ debug: false, //config.debug,
2931 reconnect: true,
3032 });
3133
@@ -36,6 +38,7 @@ let actionLoopRunning = false;
3638 let worldSnapshot: WorldSnapshot = {};
3739 let registrationRetries = 0;
3840 let travelInProgress = false;
41+let lastTravelTarget: string | null = null;
3942 const MAX_REGISTRATION_RETRIES = 3;
4043 const failedRegistrationNames: string[] = [];
4144
@@ -64,27 +67,13 @@ function updateStatus(): void {
6467 const state = client.state;
6568 if (!state.player || !state.ship) {
6669 tui.setStatus("Not logged in");
70+ tui.setSidebar("Not logged in.");
6771 return;
6872 }
69- const location = `${state.system?.name ?? state.player.current_system} - ${
70- state.poi?.name ?? state.player.current_poi
71- }`;
72- const status = [
73- `Player ${state.player.username} [${state.player.empire}]`,
74- `Cr ${state.player.credits}`,
75- `Hull ${state.ship.hull}/${state.ship.max_hull}`,
76- `Shield ${state.ship.shield}/${state.ship.max_shield}`,
77- `Fuel ${state.ship.fuel}/${state.ship.max_fuel}`,
78- `Traveling ${travelInProgress ? "Y" : "N"}`,
79- `Docked ${state.player.docked_at_base ? "Y" : "N"}`,
80- `Tick ${state.currentTick}`,
81- location,
82- ].join(" | ");
83- const cargoList = state.ship.cargo?.length
84- ? state.ship.cargo.map((item) => `${item.item_id}(${item.quantity})`).join(",")
85- : "none";
86- const statusWithCargo = `${status} | Cargo ${state.ship.cargo_used}/${state.ship.cargo_capacity} [${cargoList}]`;
87- tui.setStatus(statusWithCargo);
73+ const statusText = buildStatusText(state, worldSnapshot, travelInProgress, lastTravelTarget);
74+ const sidebarText = formatSidebar(state, worldSnapshot, travelInProgress, lastTravelTarget);
75+ tui.setStatus(statusText);
76+ tui.setSidebar(sidebarText);
8877 }
8978
9079 function saveSnapshot(): void {
@@ -106,6 +95,7 @@ async function runRegistrationFlow(): Promise<void> {
10695 attempts += 1;
10796 try {
10897 const prompt = buildRegistrationPrompt(true, failedRegistrationNames);
98+ tui.setPrompt(prompt);
10999 const result = await ollama.generateJson<RegistrationChoice>(prompt);
110100 const username = String(result.json.username ?? "").trim();
111101 const empire = String(result.json.empire ?? "").trim() as EmpireID;
@@ -141,16 +131,16 @@ async function startActionLoop(): Promise<void> {
141131 await sleep(config.tickDelayMs);
142132 continue;
143133 }
144- const recentActions = memory.getRecentActions(config.maxContextActions);
145- const recentEvents = memory.getRecentEvents(config.maxContextEvents);
134+ const recentHistory = memory.getRecentHistory(config.maxContextActions, config.maxContextEvents);
146135 const prompt = buildActionPrompt({
147136 state: client.state,
148137 worldSnapshot,
149- recentActions,
150- recentEvents,
138+ recentHistory,
151139 includeHelp: includeHelpInPrompt,
152140 });
153141
142+ tui.setPrompt(prompt);
143+
154144 const promptExcerpt = prompt.slice(0, 1000);
155145 const result = await ollama.generateJson(prompt);
156146 const validation = validateAction(result.json);
@@ -178,21 +168,24 @@ async function startActionLoop(): Promise<void> {
178168 continue;
179169 }
180170
181- memory.appendAction(
182- validation.action.action,
183- validation.action.args ?? {},
184- promptExcerpt,
185- result.raw
186- );
187- includeHelpInPrompt = false;
188-
189- const actionLog = dispatchAction(client, validation.action);
190- log(`Action: ${actionLog}`);
191- memory.appendEvent("action_sent", { action: validation.action });
192-
193- if (validation.action.action === "travel") {
194- client.getSystem();
195- client.getPOI();
171+ const actionName = validation.action.action;
172+ memory.appendAction(actionName, validation.action.args ?? {}, promptExcerpt, result.raw);
173+ includeHelpInPrompt = actionName === "help";
174+
175+ if (actionName === "help") {
176+ log("Action: help (showing help menu)");
177+ } else {
178+ if (actionName === "travel") {
179+ lastTravelTarget = String(validation.action.args?.target_poi ?? "").trim() || null;
180+ }
181+ const actionLog = dispatchAction(client, validation.action);
182+ log(`Action: ${actionLog}`);
183+ memory.appendEvent("action_sent", { action: validation.action });
184+
185+ if (actionName === "travel") {
186+ client.getSystem();
187+ client.getPOI();
188+ }
196189 }
197190 } catch (error) {
198191 const message = (error as Error).message;
@@ -373,6 +366,7 @@ client.on("ok", (data: Record<string, unknown>) => {
373366 }
374367 if (action === "arrived") {
375368 travelInProgress = false;
369+ lastTravelTarget = null;
376370 client.getSystem();
377371 client.getPOI();
378372 }
@@ -401,3 +395,186 @@ function updateWorldSnapshotFromOk(data: Record<string, unknown>): void {
401395 worldSnapshot.base = data.base as WorldSnapshot["base"];
402396 }
403397 }
398+
399+const SIDEBAR_WIDTH = 30;
400+const SIDEBAR_CONTENT_WIDTH = SIDEBAR_WIDTH - 2;
401+
402+function buildStatusText(
403+ state: ClientState,
404+ snapshot: WorldSnapshot,
405+ traveling: boolean,
406+ travelTargetId: string | null
407+): string {
408+ if (!state.player || !state.ship) return "Not logged in";
409+ if (traveling) {
410+ const destination = resolvePoiName(travelTargetId, snapshot, state);
411+ return `Traveling to ${destination}`;
412+ }
413+ if (state.player.docked_at_base) return "Docked";
414+ const currentPoi = resolvePoiName(state.player.current_poi, snapshot, state);
415+ return `At ${currentPoi}`;
416+}
417+
418+function formatSidebar(
419+ state: ClientState,
420+ snapshot: WorldSnapshot,
421+ traveling: boolean,
422+ travelTargetId: string | null
423+): string {
424+ if (!state.player || !state.ship) return "Not logged in.";
425+
426+ const width = SIDEBAR_CONTENT_WIDTH;
427+ const lines: string[] = [];
428+ const pushSection = (title: string, sectionLines: string[]): void => {
429+ if (lines.length) lines.push("");
430+ const titleText = truncate(`== ${title} ==`, width);
431+ lines.push(`{cyan-fg}${titleText}{/cyan-fg}`);
432+ for (const line of sectionLines) {
433+ const truncated = truncate(line, width);
434+ const colored = colorizeLabel(truncated);
435+ lines.push(styleLine(colored));
436+ }
437+ };
438+
439+ const system = snapshot.system ?? state.system;
440+ const poi = snapshot.poi ?? state.poi;
441+ const base = snapshot.base ?? state.base;
442+ const pois = snapshot.pois ?? [];
443+
444+ pushSection("Player", [
445+ formatLine("Name", state.player.username, width),
446+ formatLine("Empire", state.player.empire, width),
447+ formatLine("Credits", String(state.player.credits), width),
448+ formatLine("Docked", state.player.docked_at_base ? "Y" : "N", width),
449+ formatLine("Tick", String(state.currentTick), width),
450+ ]);
451+
452+ pushSection("Ship", [
453+ formatLine("Hull", `${state.ship.hull}/${state.ship.max_hull}`, width),
454+ formatLine("Shield", `${state.ship.shield}/${state.ship.max_shield}`, width),
455+ formatLine("Fuel", `${state.ship.fuel}/${state.ship.max_fuel}`, width),
456+ formatLine("Cargo", `${state.ship.cargo_used}/${state.ship.cargo_capacity}`, width),
457+ ]);
458+
459+ const locationLines = [
460+ formatLine("System", system?.name ?? state.player.current_system ?? "-", width),
461+ formatLine("POI", poi?.name ?? state.player.current_poi ?? "-", width),
462+ formatLine("Travel", traveling ? "Y" : "N", width),
463+ ];
464+ if (traveling) {
465+ locationLines.push(formatLine("Dest", resolvePoiName(travelTargetId, snapshot, state), width));
466+ }
467+ pushSection("Location", locationLines);
468+
469+ const poiLines = formatPoiLines(pois, system?.pois, width);
470+ pushSection("POIs", poiLines);
471+
472+ const cargoLines = formatCargoLines(state.ship.cargo ?? [], width);
473+ pushSection("Cargo", cargoLines);
474+
475+ const baseLines = formatBaseLines(base, width);
476+ pushSection("Base", baseLines);
477+
478+ const nearbyLines = formatNearbyLines(state.nearby ?? [], width);
479+ pushSection("Nearby", nearbyLines);
480+
481+ return lines.join("\n");
482+}
483+
484+function formatLine(label: string, value: string, width: number): string {
485+ return `${label}: ${value}`;
486+}
487+
488+function truncate(value: string, width: number): string {
489+ if (value.length <= width) return value;
490+ if (width <= 3) return value.slice(0, width);
491+ return `${value.slice(0, width - 3)}...`;
492+}
493+
494+function colorizeLabel(line: string): string {
495+ const index = line.indexOf(":");
496+ if (index <= 0) return line;
497+ const label = line.slice(0, index);
498+ const rest = line.slice(index);
499+ return `{yellow-fg}${label}{/yellow-fg}${rest}`;
500+}
501+
502+function styleLine(line: string): string {
503+ if (line.includes("{")) return line;
504+ if (line === "none" || line === "-") return `{gray-fg}${line}{/gray-fg}`;
505+ return line;
506+}
507+
508+function resolvePoiName(
509+ poiId: string | null | undefined,
510+ snapshot: WorldSnapshot,
511+ state: ClientState
512+): string {
513+ if (!poiId) return "Unknown";
514+ const snapshotPoi = snapshot.pois?.find((entry) => entry.id === poiId);
515+ if (snapshotPoi?.name) return snapshotPoi.name;
516+ if (snapshot.poi?.id === poiId && snapshot.poi.name) return snapshot.poi.name;
517+ if (state.poi?.id === poiId && state.poi.name) return state.poi.name;
518+ return poiId;
519+}
520+
521+function formatPoiLines(
522+ pois: WorldSnapshot["pois"],
523+ systemPois: string[] | undefined,
524+ width: number
525+): string[] {
526+ if (pois && pois.length > 0) {
527+ const maxItems = 5;
528+ const lines = pois.slice(0, maxItems).map((poi) => truncate(poi.name || poi.id, width));
529+ if (pois.length > maxItems) {
530+ lines.push(truncate(`+${pois.length - maxItems} more`, width));
531+ }
532+ return lines;
533+ }
534+ if (systemPois && systemPois.length > 0) {
535+ const maxItems = 5;
536+ const lines = systemPois.slice(0, maxItems).map((poiId) => truncate(poiId, width));
537+ if (systemPois.length > maxItems) {
538+ lines.push(truncate(`+${systemPois.length - maxItems} more`, width));
539+ }
540+ return lines;
541+ }
542+ return ["none"];
543+}
544+
545+function formatCargoLines(cargo: CargoItem[] | undefined, width: number): string[] {
546+ if (!cargo || cargo.length === 0) return ["none"];
547+ const maxItems = 6;
548+ const lines = cargo.slice(0, maxItems).map((item) =>
549+ truncate(`${item.item_id} x${item.quantity}`, width)
550+ );
551+ if (cargo.length > maxItems) {
552+ lines.push(truncate(`+${cargo.length - maxItems} more`, width));
553+ }
554+ return lines;
555+}
556+
557+function formatBaseLines(base: WorldSnapshot["base"], width: number): string[] {
558+ if (!base) return ["none"];
559+ const services = Object.keys(base.services)
560+ .filter((key) => (base.services as Record<string, boolean>)[key])
561+ .join(", ");
562+ return [
563+ formatLine("Name", base.name || base.id, width),
564+ formatLine("Services", services || "none", width),
565+ ];
566+}
567+
568+function formatNearbyLines(nearby: ClientState["nearby"], width: number): string[] {
569+ if (!nearby || nearby.length === 0) return ["none"];
570+ const maxItems = 6;
571+ const lines = [formatLine("Count", String(nearby.length), width)];
572+ for (const entry of nearby.slice(0, maxItems)) {
573+ const name = entry.username ?? entry.player_id ?? "unknown";
574+ lines.push(truncate(name, width));
575+ }
576+ if (nearby.length > maxItems) {
577+ lines.push(truncate(`+${nearby.length - maxItems} more`, width));
578+ }
579+ return lines;
580+}
src/memory.ts+43−0
@@ -26,6 +26,20 @@ export interface StoredEvent {
2626 payload: string | null;
2727 }
2828
29+export type HistoryEntry =
30+ | {
31+ kind: "action";
32+ ts: string;
33+ action: string;
34+ args: string | null;
35+ }
36+ | {
37+ kind: "event";
38+ ts: string;
39+ type: string;
40+ payload: string | null;
41+ };
42+
2943 const MAX_TEXT = 2000;
3044
3145 export class MemoryStore {
@@ -112,6 +126,30 @@ export class MemoryStore {
112126 .all(limit) as StoredEvent[];
113127 return rows.reverse();
114128 }
129+
130+ getRecentHistory(actionLimit: number, eventLimit: number): HistoryEntry[] {
131+ const actions = this.getRecentActions(actionLimit).map((row) => ({
132+ kind: "action" as const,
133+ ts: row.ts,
134+ action: row.action,
135+ args: row.args,
136+ }));
137+ const events = this.getRecentEvents(eventLimit).map((row) => ({
138+ kind: "event" as const,
139+ ts: row.ts,
140+ type: row.type,
141+ payload: row.payload,
142+ }));
143+ const combined = [...actions, ...events];
144+ combined.sort((a, b) => {
145+ const timeA = tsValue(a.ts);
146+ const timeB = tsValue(b.ts);
147+ if (timeA !== timeB) return timeA - timeB;
148+ if (a.kind === b.kind) return 0;
149+ return a.kind === "action" ? -1 : 1;
150+ });
151+ return combined;
152+ }
115153 }
116154
117155 function nowIso(): string {
@@ -131,3 +169,8 @@ function truncate(text: string | null | undefined): string | null {
131169 if (text.length <= MAX_TEXT) return text;
132170 return text.slice(0, MAX_TEXT);
133171 }
172+
173+function tsValue(ts: string): number {
174+ const value = Date.parse(ts);
175+ return Number.isFinite(value) ? value : 0;
176+}
src/prompt.ts+160−21
@@ -1,12 +1,11 @@
11 import type { ClientState } from "../client/src/client";
22 import type { Base, POI, System } from "../client/src/types";
3-import type { StoredAction, StoredEvent } from "./memory";
3+import type { HistoryEntry } from "./memory";
44
55 export interface PromptContext {
66 state: ClientState;
77 worldSnapshot?: WorldSnapshot;
8- recentActions: StoredAction[];
9- recentEvents: StoredEvent[];
8+ recentHistory: HistoryEntry[];
109 includeHelp: boolean;
1110 }
1211
@@ -64,13 +63,12 @@ Forum:
6463
6564 Other:
6665 help - Show this help
67- quit - Exit client (or press Ctrl+D)
6866 `;
6967
7068 export function buildActionPrompt(context: PromptContext): string {
7169 const stateText = formatState(context.state);
7270 const worldText = formatWorldSnapshot(context.state, context.worldSnapshot);
73- const memoryText = formatMemory(context.recentActions, context.recentEvents);
71+ const memoryText = formatGroupedMemory(context.recentHistory);
7472 const helpBlock = context.includeHelp ? `\nHELP MENU:\n${HELP_TEXT}` : "";
7573
7674 return `You are an autonomous player for the SpaceMolt MMO (https://www.spacemolt.com/).
@@ -88,7 +86,7 @@ RECENT MEMORY:
8886 ${memoryText}
8987
9088 ACTION SCHEMA (JSON ONLY):
91-{"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":{...}}
89+{"action":"travel|jump|dock|undock|mine|attack|scan|buy|sell|refuel|repair|craft|chat|status|system|poi|base|skills|recipes|version|nearby|cargo|help|wait","args":{...}}
9290
9391 REQUIRED ARGS:
9492 - travel: {"target_poi":"..."}
@@ -102,13 +100,13 @@ REQUIRED ARGS:
102100
103101 NOTES:
104102 - Use only the listed actions.
105-- If an action requires args and you do not know valid values, use {"action":"wait"}.
103+- If an action requires args and you do not know valid values, use {"action":"help"}.
106104 - Never omit required args or leave them blank.
107105 - IDs must come from the current state or world snapshot.
108-- If unsure, use {"action":"wait"}.
106+- If unsure, use {"action":"help"}.
109107
110108 EXAMPLES (valid JSON only):
111-{"action":"wait"}
109+{"action":"help"}
112110 {"action":"mine"}
113111 {"action":"travel","args":{"target_poi":"poi_id_here"}}
114112 {"action":"sell","args":{"item_id":"ore_iron","quantity":10}}
@@ -260,26 +258,167 @@ function formatWorldSnapshot(state: ClientState, snapshot?: WorldSnapshot): stri
260258 return lines.join("\n");
261259 }
262260
263-function formatMemory(actions: StoredAction[], events: StoredEvent[]): string {
264- const lines: string[] = [];
261+function formatGroupedMemory(history: HistoryEntry[]): string {
262+ if (history.length === 0) return "(no recent memory)";
263+
264+ const systemEvents: Extract<HistoryEntry, { kind: "event" }>[] = [];
265+ const blocks: {
266+ action: Extract<HistoryEntry, { kind: "action" }>;
267+ events: Extract<HistoryEntry, { kind: "event" }>[];
268+ }[] = [];
269+ let currentBlock: (typeof blocks)[number] | null = null;
270+
271+ for (const entry of history) {
272+ if (entry.kind === "action") {
273+ currentBlock = { action: entry, events: [] };
274+ blocks.push(currentBlock);
275+ continue;
276+ }
277+
278+ if (entry.type === "action_sent") {
279+ continue;
280+ }
265281
266- if (actions.length === 0 && events.length === 0) {
267- return "(no recent memory)";
282+ if (currentBlock) {
283+ currentBlock.events.push(entry);
284+ } else {
285+ systemEvents.push(entry);
286+ }
268287 }
269288
270- if (actions.length > 0) {
271- lines.push("Actions:");
272- for (const action of actions) {
273- lines.push(`- ${action.ts} ${action.action} ${action.args ?? ""}`.trim());
289+ const lines: string[] = [];
290+ if (systemEvents.length > 0) {
291+ lines.push("System events:");
292+ for (const event of systemEvents) {
293+ lines.push(formatEventLine(event));
274294 }
275295 }
276296
277- if (events.length > 0) {
278- lines.push("Events:");
279- for (const event of events) {
280- lines.push(`- ${event.ts} ${event.type} ${event.payload ?? ""}`.trim());
297+ for (const block of blocks) {
298+ const argsText = formatActionArgs(block.action.args);
299+ lines.push(`Action: ${block.action.ts} ${block.action.action}${argsText}`.trim());
300+ if (block.events.length === 0) {
301+ lines.push("- Event: none");
302+ } else {
303+ for (const event of block.events) {
304+ lines.push(formatEventLine(event));
305+ }
281306 }
282307 }
283308
284309 return lines.join("\n");
285310 }
311+
312+function formatEventLine(event: Extract<HistoryEntry, { kind: "event" }>): string {
313+ const summary = summarizeEvent(event);
314+ if (summary) {
315+ return `- Event: ${event.ts} ${event.type} ${summary}`.trim();
316+ }
317+ return `- Event: ${event.ts} ${event.type}`.trim();
318+}
319+
320+function formatActionArgs(argsRaw: string | null): string {
321+ if (!argsRaw) return "";
322+ const parsed = parseJson(argsRaw);
323+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
324+ return "";
325+ }
326+ const entries = Object.entries(parsed as Record<string, unknown>);
327+ if (entries.length === 0) return "";
328+ const formatted = entries
329+ .map(([key, value]) => `${key}=${formatValue(value)}`)
330+ .filter((text) => text.length > 1)
331+ .join(" ");
332+ if (!formatted) return "";
333+ return ` ${truncateText(formatted, 120)}`;
334+}
335+
336+function formatValue(value: unknown): string {
337+ if (value === null || value === undefined) return "-";
338+ if (typeof value === "string") return truncateText(value, 40);
339+ if (typeof value === "number" || typeof value === "boolean") return String(value);
340+ if (Array.isArray(value)) return "[list]";
341+ if (typeof value === "object") return "[object]";
342+ return String(value);
343+}
344+
345+const SUPPRESSED_EVENT_PAYLOADS = new Set([
346+ "state_update",
347+ "ok",
348+ "logged_in",
349+ "registered",
350+ "version_info",
351+]);
352+
353+function summarizeEvent(event: Extract<HistoryEntry, { kind: "event" }>): string | null {
354+ if (SUPPRESSED_EVENT_PAYLOADS.has(event.type)) return null;
355+ if (!event.payload) return null;
356+ const payload = parseJson(event.payload);
357+ if (!payload || typeof payload !== "object") return null;
358+
359+ switch (event.type) {
360+ case "chat_message": {
361+ const sender = getStringField(payload, "sender") ?? getStringField(payload, "sender_id");
362+ const channel = getStringField(payload, "channel");
363+ const content = getStringField(payload, "content");
364+ const parts = [
365+ sender ? `from=${sender}` : null,
366+ channel ? `channel=${channel}` : null,
367+ content ? `msg="${truncateText(content, 60)}"` : null,
368+ ].filter(Boolean);
369+ return parts.length ? parts.join(" ") : null;
370+ }
371+ case "scan_result": {
372+ const target = getStringField(payload, "target_id");
373+ const success = getStringField(payload, "success");
374+ const info = Array.isArray((payload as Record<string, unknown>).revealed_info)
375+ ? ((payload as Record<string, unknown>).revealed_info as unknown[]).map(String).join(",")
376+ : null;
377+ const parts = [
378+ target ? `target=${target}` : null,
379+ success ? `success=${success}` : null,
380+ info ? `info=${truncateText(info, 80)}` : null,
381+ ].filter(Boolean);
382+ return parts.length ? parts.join(" ") : null;
383+ }
384+ case "error": {
385+ const code = getStringField(payload, "code");
386+ const message = getStringField(payload, "message");
387+ const parts = [code ? `code=${code}` : null, message ? `message=${truncateText(message, 80)}` : null].filter(Boolean);
388+ return parts.length ? parts.join(" ") : null;
389+ }
390+ case "llm_invalid_action": {
391+ const error = getStringField(payload, "error");
392+ return error ? `error=${truncateText(error, 80)}` : null;
393+ }
394+ case "loop_error":
395+ case "llm_timeout": {
396+ const message = getStringField(payload, "message");
397+ return message ? `message=${truncateText(message, 80)}` : null;
398+ }
399+ default: {
400+ const message = getStringField(payload, "message");
401+ return message ? `message=${truncateText(message, 80)}` : null;
402+ }
403+ }
404+}
405+
406+function getStringField(payload: object, key: string): string | null {
407+ const value = (payload as Record<string, unknown>)[key];
408+ if (value === null || value === undefined) return null;
409+ return String(value);
410+}
411+
412+function parseJson(value: string): unknown | null {
413+ try {
414+ return JSON.parse(value);
415+ } catch {
416+ return null;
417+ }
418+}
419+
420+function truncateText(value: string, max: number): string {
421+ if (value.length <= max) return value;
422+ if (max <= 3) return value.slice(0, max);
423+ return `${value.slice(0, max - 3)}...`;
424+}
src/tui.ts+95−3
@@ -3,10 +3,15 @@ import blessed from "blessed";
33 export class Tui {
44 private screen: blessed.Widgets.Screen;
55 private logBox: blessed.Widgets.Log;
6+ private sidebar: blessed.Widgets.BoxElement;
7+ private promptSidebar: blessed.Widgets.BoxElement | null;
68 private statusBar: blessed.Widgets.BoxElement;
79 private exitHandler: (() => void) | null = null;
10+ private sidebarWidth = 30;
11+ private debugEnabled: boolean;
812
9- constructor() {
13+ constructor(debugEnabled = false) {
14+ this.debugEnabled = debugEnabled;
1015 this.screen = blessed.screen({
1116 smartCSR: true,
1217 title: "SpaceMolt Ollama Player",
@@ -14,11 +19,30 @@ export class Tui {
1419 terminal: resolveTerminal(),
1520 });
1621
17- this.logBox = blessed.log({
22+ this.sidebar = blessed.box({
1823 parent: this.screen,
1924 top: 0,
2025 left: 0,
21- width: "100%",
26+ width: this.sidebarWidth,
27+ height: "100%-1",
28+ tags: true,
29+ border: "line",
30+ label: "Snapshot",
31+ style: {
32+ border: {
33+ fg: "blue",
34+ },
35+ bg: "black",
36+ fg: "white",
37+ },
38+ content: "No data",
39+ });
40+
41+ this.logBox = blessed.log({
42+ parent: this.screen,
43+ top: 0,
44+ left: this.sidebarWidth,
45+ width: `100%-${this.sidebarWidth}`,
2246 height: "100%-1",
2347 tags: true,
2448 border: "line",
@@ -38,6 +62,33 @@ export class Tui {
3862 },
3963 });
4064
65+ this.promptSidebar = this.debugEnabled
66+ ? blessed.box({
67+ parent: this.screen,
68+ top: 0,
69+ left: 0,
70+ width: 1,
71+ height: "100%-1",
72+ tags: false,
73+ border: "line",
74+ label: "Prompt",
75+ style: {
76+ border: {
77+ fg: "blue",
78+ },
79+ bg: "black",
80+ fg: "white",
81+ },
82+ scrollable: true,
83+ alwaysScroll: false,
84+ scrollbar: {
85+ ch: " ",
86+ inverse: true,
87+ },
88+ content: "No prompt yet",
89+ })
90+ : null;
91+
4192 this.statusBar = blessed.box({
4293 parent: this.screen,
4394 bottom: 0,
@@ -60,6 +111,13 @@ export class Tui {
60111 }
61112 });
62113
114+ this.applyLayout();
115+
116+ this.screen.on("resize", () => {
117+ this.applyLayout();
118+ this.screen.render();
119+ });
120+
63121 this.screen.render();
64122 }
65123
@@ -77,9 +135,43 @@ export class Tui {
77135 this.screen.render();
78136 }
79137
138+ setSidebar(content: string): void {
139+ this.sidebar.setContent(content);
140+ this.screen.render();
141+ }
142+
143+ setPrompt(content: string): void {
144+ if (!this.promptSidebar) return;
145+ this.promptSidebar.setContent(content);
146+ this.screen.render();
147+ }
148+
80149 destroy(): void {
81150 this.screen.destroy();
82151 }
152+
153+ private applyLayout(): void {
154+ const totalWidth = typeof this.screen.width === "number" ? this.screen.width : this.screen.cols;
155+ const sidebarWidth = Math.min(this.sidebarWidth, Math.max(totalWidth - 10, 1));
156+ const availableWidth = Math.max(totalWidth - sidebarWidth, 1);
157+
158+ this.sidebar.left = 0;
159+ this.sidebar.width = sidebarWidth;
160+
161+ if (this.promptSidebar) {
162+ const promptWidth = Math.max(Math.floor(availableWidth / 2), 1);
163+ const logWidth = Math.max(availableWidth - promptWidth, 1);
164+
165+ this.logBox.left = sidebarWidth;
166+ this.logBox.width = logWidth;
167+
168+ this.promptSidebar.left = sidebarWidth + logWidth;
169+ this.promptSidebar.width = promptWidth;
170+ } else {
171+ this.logBox.left = sidebarWidth;
172+ this.logBox.width = availableWidth;
173+ }
174+ }
83175 }
84176
85177 function resolveTerminal(): string | undefined {