xonecas.io
5875
Os

ollama-space-molt-player / commit 112cf3d

feat: enhance action prompt with context tracking and panel improvements

- Add faction creation context and forum tracking to action generation
- Implement context panel for displaying tracked state and decisions
- Enhance prompt validation and LLM output parsing
- Improve TUI layout with context-aware panel management
- Add stranded detection and recovery guidance
- Refactor character customization config handling

xonecas2026-02-01 112cf3daa35e5e4b471c5d6c9768b9197c6d85f3 parent c61eff3

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

scripts/mock-prompt.ts+6−0
@@ -270,12 +270,18 @@ const mockForumFollowUpStatus: "unread" | "periodic" | null = "periodic";
270270
271271 // Mock repetition warning (null = no warning)
272272 const mockRepetitionWarning: { action: string; count: number } | null = null;
273+const mockMemorySummary =
274+ "Recently traveled to the asteroid belt and mined resources while staying alert for nearby activity.";
275+const mockLastActionResult =
276+ "Action: 2025-01-01T00:00:00.000Z mine\nResult:\n- Mined 5x iron_ore";
273277
274278 // Build the prompt exactly as we would in production
275279 const prompt = buildActionPrompt({
276280 state: mockClientState,
277281 worldSnapshot: mockWorldSnapshot,
278282 recentHistory: mockRecentHistory,
283+ memorySummary: mockMemorySummary,
284+ lastActionResult: mockLastActionResult,
279285 currentGoal:
280286 "Map the Sol Prime system and gather resources for the journey to Alpha Centauri",
281287 empire: mockPlayer.empire,
src/config.ts+2−2
@@ -151,7 +151,7 @@ export const config = {
151151 uiLogPath: `ui-${instanceName}.log`,
152152 debugLogPath: `debug-${instanceName}.log`,
153153 tickDelayMs: 11000,
154- maxContextActions: 5,
155- maxContextEvents: 5,
154+ maxContextActions: 20,
155+ maxContextEvents: 40,
156156 ollamaTimeoutMs: 60000,
157157 };
src/game-state.ts+2−0
@@ -35,6 +35,8 @@ export class GameState {
3535
3636 // TUI context (warnings + forum) - updated during action loop
3737 tuiContext: TuiContext = {};
38+ pendingActionId: number | null = null;
39+ pendingActionTimeout: ReturnType<typeof setTimeout> | null = null;
3840
3941 readonly MAX_REGISTRATION_RETRIES = 3;
4042 }
src/index.ts+69−3
@@ -16,7 +16,13 @@ import { OllamaAgent, OllamaTimeoutError } from "./ollama";
1616 import { FileLoggerOutput } from "./output/file-logger-output";
1717 import { TuiOutput } from "./output/tui-output";
1818 import type { OutputInterface } from "./output-interface";
19-import { buildActionPrompt, isStranded, type WorldSnapshot } from "./prompt";
19+import {
20+ buildActionPrompt,
21+ buildLastActionResult,
22+ buildSummaryPrompt,
23+ isStranded,
24+ type WorldSnapshot,
25+} from "./prompt";
2026 import { runRegistrationFlow } from "./registration";
2127 import {
2228 formatAiAction,
@@ -121,6 +127,21 @@ function updateOutput(): void {
121127 });
122128 }
123129
130+function captureActionResult(resultType: string, payload: unknown): void {
131+ if (gameState.pendingActionId === null) return;
132+ memory.appendActionResult(gameState.pendingActionId, resultType, payload);
133+ if (resultType === "ok" || resultType === "error") {
134+ if (gameState.pendingActionTimeout) {
135+ clearTimeout(gameState.pendingActionTimeout);
136+ gameState.pendingActionTimeout = null;
137+ }
138+ }
139+ output.logDebug(
140+ "ACTION_RESULT_CAPTURED",
141+ `${resultType} linked to action ${gameState.pendingActionId}`,
142+ );
143+}
144+
124145 function shouldStopForMaxTicks(allowFallbackCount: boolean): boolean {
125146 if (config.maxTicks === null) return false;
126147 const currentTick = client.state.currentTick;
@@ -242,6 +263,16 @@ async function startActionLoop(): Promise<void> {
242263 config.maxContextActions,
243264 config.maxContextEvents,
244265 );
266+ let memorySummary = "(summary unavailable)";
267+ try {
268+ const summaryPrompt = buildSummaryPrompt(recentHistory);
269+ const summaryText = await ollama.generateText(summaryPrompt);
270+ memorySummary = summaryText || "(summary unavailable)";
271+ } catch (error) {
272+ const message = (error as Error).message;
273+ output.logDebug("SUMMARY_ERROR", message);
274+ }
275+ const lastActionResult = buildLastActionResult(memory);
245276 const recentActions = memory.getRecentActions(REPETITION_THRESHOLD);
246277 const repetitionWarning = detectRepetition(
247278 recentActions,
@@ -262,6 +293,8 @@ async function startActionLoop(): Promise<void> {
262293 lastPostTitle: gameState.lastForumPostTitle,
263294 lastPostCategory: gameState.lastForumPostCategory,
264295 },
296+ memorySummary,
297+ lastActionResult,
265298 };
266299 updateOutput();
267300
@@ -269,6 +302,8 @@ async function startActionLoop(): Promise<void> {
269302 state: client.state,
270303 worldSnapshot: gameState.worldSnapshot,
271304 recentHistory,
305+ memorySummary,
306+ lastActionResult,
272307 currentGoal: gameState.currentGoal,
273308 empire: client.state.player?.empire,
274309 alignment: gameState.credentials?.alignment,
@@ -345,12 +380,34 @@ async function startActionLoop(): Promise<void> {
345380 output.log(formatAiGoal(goal));
346381 updateOutput();
347382 }
348- memory.appendAction(
383+ if (gameState.pendingActionId !== null) {
384+ output.logDebug(
385+ "ACTION_PENDING_OVERRIDDEN",
386+ `Overriding pending action ${gameState.pendingActionId}`,
387+ );
388+ gameState.pendingActionId = null;
389+ }
390+ if (gameState.pendingActionTimeout) {
391+ clearTimeout(gameState.pendingActionTimeout);
392+ gameState.pendingActionTimeout = null;
393+ }
394+ const actionId = memory.appendActionWithId(
349395 actionName,
350396 validation.action.args ?? {},
351397 promptExcerpt,
352398 result.raw,
353399 );
400+ gameState.pendingActionId = actionId;
401+ const pendingDelayMs = Math.max(3000, config.tickDelayMs * 2);
402+ gameState.pendingActionTimeout = setTimeout(() => {
403+ if (gameState.pendingActionId !== actionId) return;
404+ output.logDebug(
405+ "ACTION_TIMEOUT",
406+ `No response for action ${actionId} after ${pendingDelayMs}ms`,
407+ );
408+ gameState.pendingActionId = null;
409+ gameState.pendingActionTimeout = null;
410+ }, pendingDelayMs);
354411 if (actionName === "travel") {
355412 gameState.lastTravelTarget =
356413 String(validation.action.args?.target_poi ?? "").trim() || null;
@@ -402,7 +459,13 @@ process.on("SIGTERM", shutdown);
402459
403460 // Log ALL raw messages for debugging server communication
404461 client.on("raw_message", (data: { type: string; payload: unknown }) => {
405- memory.appendEvent(`raw_${data.type}`, data.payload);
462+ const rawType = String(data.type ?? "");
463+ if (!rawType) return;
464+ memory.appendEvent(`raw_${rawType}`, data.payload);
465+ if (rawType.startsWith("forum_") || rawType === "mining_yield") {
466+ captureActionResult(rawType, data.payload);
467+ memory.appendEvent(rawType, data.payload);
468+ }
406469 });
407470
408471 client.on<WelcomePayload>("welcome", async (data) => {
@@ -504,6 +567,7 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
504567 });
505568
506569 client.on<ErrorPayload>("error", (data) => {
570+ captureActionResult("error", data);
507571 output.log(formatError(data));
508572 memory.appendEvent("error", data);
509573 if (data.code === "invalid_credentials") {
@@ -622,11 +686,13 @@ client.on<ChatMessage>("chat_message", (data) => {
622686 });
623687
624688 client.on<ScanResultPayload>("scan_result", (data) => {
689+ captureActionResult("scan_result", data);
625690 output.log(formatScanResult(data));
626691 memory.appendEvent("scan_result", data);
627692 });
628693
629694 client.on("ok", (data: Record<string, unknown>) => {
695+ captureActionResult("ok", data);
630696 const okContext: OkContext = {
631697 jumpTarget: gameState.lastJumpTarget,
632698 travelTarget: gameState.lastTravelTarget,
src/memory.ts+64−0
@@ -32,6 +32,12 @@ export interface StoredEvent {
3232 payload: string | null;
3333 }
3434
35+export interface ActionResult {
36+ ts: string;
37+ result_type: string;
38+ payload: string | null;
39+}
40+
3541 export type HistoryEntry =
3642 | {
3743 kind: "action";
@@ -66,6 +72,14 @@ export class MemoryStore {
6672 prompt_excerpt TEXT,
6773 model_raw TEXT
6874 );
75+ CREATE TABLE IF NOT EXISTS action_results (
76+ id INTEGER PRIMARY KEY AUTOINCREMENT,
77+ action_id INTEGER NOT NULL,
78+ ts TEXT NOT NULL,
79+ result_type TEXT NOT NULL,
80+ payload TEXT,
81+ FOREIGN KEY (action_id) REFERENCES actions(id)
82+ );
6983 CREATE TABLE IF NOT EXISTS events (
7084 id INTEGER PRIMARY KEY AUTOINCREMENT,
7185 ts TEXT NOT NULL,
@@ -178,6 +192,38 @@ export class MemoryStore {
178192 );
179193 }
180194
195+ appendActionWithId(
196+ action: string,
197+ args: unknown,
198+ promptExcerpt: string,
199+ modelRaw: string,
200+ ): number {
201+ const result = this.db
202+ .query(
203+ "INSERT INTO actions (ts, action, args, prompt_excerpt, model_raw) VALUES (?, ?, ?, ?, ?)",
204+ )
205+ .run(
206+ nowIso(),
207+ action,
208+ toJson(args),
209+ truncate(promptExcerpt),
210+ truncate(modelRaw),
211+ );
212+ return Number(result.lastInsertRowid);
213+ }
214+
215+ appendActionResult(
216+ actionId: number,
217+ resultType: string,
218+ payload: unknown,
219+ ): void {
220+ this.db
221+ .query(
222+ "INSERT INTO action_results (action_id, ts, result_type, payload) VALUES (?, ?, ?, ?)",
223+ )
224+ .run(actionId, nowIso(), resultType, toJson(payload));
225+ }
226+
181227 appendEvent(type: string, payload: unknown): void {
182228 this.db
183229 .query("INSERT INTO events (ts, type, payload) VALUES (?, ?, ?)")
@@ -258,6 +304,24 @@ export class MemoryStore {
258304 });
259305 return combined;
260306 }
307+
308+ getLastActionWithResults(): {
309+ action: StoredAction;
310+ results: ActionResult[];
311+ } | null {
312+ const action = this.db
313+ .query(
314+ "SELECT id, ts, action, args, prompt_excerpt, model_raw FROM actions ORDER BY id DESC LIMIT 1",
315+ )
316+ .get() as StoredAction | undefined;
317+ if (!action) return null;
318+ const results = this.db
319+ .query(
320+ "SELECT ts, result_type, payload FROM action_results WHERE action_id = ? ORDER BY id ASC",
321+ )
322+ .all(action.id) as ActionResult[];
323+ return { action, results };
324+ }
261325 }
262326
263327 function nowIso(): string {
src/ollama.ts+40−0
@@ -83,6 +83,46 @@ export class OllamaAgent {
8383 clearTimeout(timeout);
8484 }
8585 }
86+
87+ async generateText(prompt: string): Promise<string> {
88+ const controller = new AbortController();
89+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
90+
91+ try {
92+ const requestBody: Record<string, unknown> = {
93+ model: this.model,
94+ prompt,
95+ stream: false,
96+ options: {
97+ temperature: 0.1,
98+ },
99+ };
100+
101+ const response = await fetch(new URL("/api/generate", this.baseUrl), {
102+ method: "POST",
103+ headers: {
104+ "Content-Type": "application/json",
105+ },
106+ body: JSON.stringify(requestBody),
107+ signal: controller.signal,
108+ });
109+
110+ if (!response.ok) {
111+ const text = await response.text();
112+ throw new Error(`Ollama error ${response.status}: ${text}`);
113+ }
114+
115+ const data = (await response.json()) as { response?: string };
116+ return (data.response ?? "").trim();
117+ } catch (error) {
118+ if (error instanceof DOMException && error.name === "AbortError") {
119+ throw new OllamaTimeoutError(this.timeoutMs);
120+ }
121+ throw error;
122+ } finally {
123+ clearTimeout(timeout);
124+ }
125+ }
86126 }
87127
88128 function parseJsonFromText<T>(text: string): T {
src/prompt.ts+395−74
@@ -6,13 +6,14 @@ import {
66 PERSONALITY_ARCHETYPES,
77 SPEECH_STYLE_DESCRIPTIONS,
88 } from "./constants";
9-import type { HistoryEntry } from "./memory";
9+import type { HistoryEntry, MemoryStore } from "./memory";
1010 import type { AlignmentType, PersonalityType, SpeechStyleType } from "./types";
1111
1212 export interface PromptContext {
1313 state: ClientState;
1414 worldSnapshot?: WorldSnapshot;
1515 recentHistory: HistoryEntry[];
16+ memorySummary?: string | null;
1617 currentGoal: string | null;
1718 empire?: EmpireID;
1819 alignment?: AlignmentType;
@@ -26,6 +27,7 @@ export interface PromptContext {
2627 action: string;
2728 count: number;
2829 } | null;
30+ lastActionResult?: string | null;
2931 }
3032
3133 export interface WorldSnapshot {
@@ -202,7 +204,12 @@ Other:
202204 export function buildActionPrompt(context: PromptContext): string {
203205 const stateText = formatState(context.state);
204206 const worldText = formatWorldSnapshot(context.state, context.worldSnapshot);
205- const memoryText = formatGroupedMemory(context.recentHistory);
207+ const memoryText = context.memorySummary?.trim()
208+ ? context.memorySummary.trim()
209+ : "(summary unavailable)";
210+ const lastActionText = context.lastActionResult?.trim()
211+ ? context.lastActionResult.trim()
212+ : "No actions yet.";
206213 const forumContextBlock = formatForumContext(context.recentHistory);
207214 const helpBlock = `\nGAME INFORMATION:\n${HELP_TEXT}`;
208215 const goalText = context.currentGoal?.trim()
@@ -266,8 +273,11 @@ ${stateText}
266273 WORLD INFORMATION:
267274 ${worldText}
268275
269- RECENT MEMORY:
270- ${memoryText}
276+MEMORY SUMMARY:
277+${memoryText}
278+
279+LAST ACTION RESULT:
280+${lastActionText}
271281
272282 ${forumContextBlock}
273283
@@ -587,20 +597,39 @@ function formatWorldSnapshot(
587597 return lines.join("\n");
588598 }
589599
590-function formatGroupedMemory(history: HistoryEntry[]): string {
591- if (history.length === 0) return "(no recent memory)";
600+export function buildSummaryPrompt(history: HistoryEntry[]): string {
601+ if (history.length === 0) {
602+ return "Summarize the following game history: (empty history)\n\nProvide ONLY the text: No recent activity.";
603+ }
604+
605+ const historyText = formatHistoryForSummary(history);
606+
607+ return `You are summarizing recent game events for a SpaceMolt AI agent. The agent needs a concise description (NOT bullet points) of what happened recently to maintain context.
608+
609+Focus on:
610+- Movement (travel, jumps, arrivals)
611+- Economy (mining, trading, refueling, repairs)
612+- Combat (attacks, scans)
613+- Social (chat, forum posts, faction activity)
614+- Errors or failures
615+- Too much repetition (as a bad thing)
616+
617+Write 2-4 sentences describing the most important recent events. Be concise and descriptive.
618+Write as if you were remembering your last steps. Write in the first person.
619+
620+RECENT HISTORY:
621+${historyText}
592622
593- const systemEvents: Extract<HistoryEntry, { kind: "event" }>[] = [];
594- const blocks: {
595- action: Extract<HistoryEntry, { kind: "action" }>;
596- events: Extract<HistoryEntry, { kind: "event" }>[];
597- }[] = [];
598- let currentBlock: (typeof blocks)[number] | null = null;
623+Provide ONLY the summary text. No extra formatting, no bullet points, no labels.`;
624+}
625+
626+function formatHistoryForSummary(history: HistoryEntry[]): string {
627+ const lines: string[] = [];
599628
600629 for (const entry of history) {
601630 if (entry.kind === "action") {
602- currentBlock = { action: entry, events: [] };
603- blocks.push(currentBlock);
631+ const argsText = formatActionArgs(entry.args);
632+ lines.push(`${entry.ts} ACTION: ${entry.action}${argsText}`.trim());
604633 continue;
605634 }
606635
@@ -608,49 +637,178 @@ function formatGroupedMemory(history: HistoryEntry[]): string {
608637 continue;
609638 }
610639
611- if (currentBlock) {
612- currentBlock.events.push(entry);
640+ const summary = summarizeEvent(entry);
641+ if (summary) {
642+ lines.push(`${entry.ts} EVENT: ${entry.type} ${summary}`.trim());
613643 } else {
614- systemEvents.push(entry);
644+ lines.push(`${entry.ts} EVENT: ${entry.type}`.trim());
615645 }
616646 }
617647
618- const lines: string[] = [];
619- if (systemEvents.length > 0) {
620- lines.push("System events:");
621- for (const event of systemEvents) {
622- lines.push(formatEventLine(event));
623- }
648+ return lines.join("\n");
649+}
650+
651+export function buildLastActionResult(memory: MemoryStore): string {
652+ const lastAction = memory.getLastActionWithResults();
653+ if (!lastAction) return "No actions yet.";
654+
655+ const argsText = formatActionArgs(lastAction.action.args);
656+ const header =
657+ `Action: ${lastAction.action.ts} ${lastAction.action.action}${argsText}`.trim();
658+
659+ if (lastAction.results.length === 0) {
660+ return `${header}\nResult: No response received (timeout or pending).`;
624661 }
625662
626- for (const block of blocks) {
627- const argsText = formatActionArgs(block.action.args);
628- const errorEvent = block.events.find(
629- (e) => e.type === "error" || e.type === "llm_invalid_action",
630- );
631- const errorMsg = errorEvent ? extractErrorMessage(errorEvent) : null;
663+ const lines: string[] = [header, "Result:"];
664+ let appended = false;
632665
633- if (errorMsg) {
666+ for (const result of lastAction.results) {
667+ const payload = parseJson(result.payload ?? "");
668+ if (!payload || typeof payload !== "object") continue;
669+
670+ if (result.result_type === "forum_list") {
671+ const forumLines = formatForumList(payload as Record<string, unknown>);
672+ if (forumLines.length > 0) {
673+ lines.push(...forumLines.map((line) => `- ${line}`));
674+ appended = true;
675+ }
676+ continue;
677+ }
678+ if (
679+ result.result_type === "forum_thread" ||
680+ result.result_type === "forum_get_thread"
681+ ) {
682+ const forumLines = formatForumThread(payload as Record<string, unknown>);
683+ if (forumLines.length > 0) {
684+ lines.push(...forumLines.map((line) => `- ${line}`));
685+ appended = true;
686+ }
687+ continue;
688+ }
689+ if (result.result_type === "error") {
690+ const code = getStringField(payload, "code") ?? "unknown";
691+ const message = getStringField(payload, "message") ?? "Unknown error";
692+ lines.push(`- ERROR [${code}]: ${message}`);
693+ appended = true;
694+ continue;
695+ }
696+ if (result.result_type === "ok") {
697+ const okAction = getStringField(payload, "action");
698+ if (!okAction) {
699+ const lastActionName = lastAction.action.action;
700+ const infoLines: string[] = [];
701+ if (
702+ lastActionName === "base" ||
703+ getObjectField(payload, "base") !== null
704+ ) {
705+ infoLines.push("- Base information updated");
706+ }
707+ if (
708+ lastActionName === "poi" ||
709+ getObjectField(payload, "poi") !== null
710+ ) {
711+ infoLines.push("- POI information updated");
712+ }
713+ if (
714+ lastActionName === "system" ||
715+ getObjectField(payload, "system") !== null
716+ ) {
717+ infoLines.push("- System information updated");
718+ }
719+ if (
720+ lastActionName === "status" ||
721+ getObjectField(payload, "player") !== null
722+ ) {
723+ infoLines.push("- Status information updated");
724+ }
725+ if (
726+ lastActionName === "cargo" ||
727+ Array.isArray((payload as Record<string, unknown>).cargo)
728+ ) {
729+ infoLines.push("- Cargo information updated");
730+ }
731+ if (
732+ lastActionName === "nearby" ||
733+ Array.isArray((payload as Record<string, unknown>).nearby)
734+ ) {
735+ infoLines.push("- Nearby players information updated");
736+ }
737+ if (infoLines.length > 0) {
738+ lines.push(...infoLines);
739+ appended = true;
740+ continue;
741+ }
742+ }
743+ if (okAction === "base") {
744+ lines.push("- Base information updated");
745+ appended = true;
746+ continue;
747+ }
748+ if (okAction === "status") {
749+ lines.push("- Status information updated");
750+ appended = true;
751+ continue;
752+ }
753+ if (okAction === "system") {
754+ lines.push("- System information updated");
755+ appended = true;
756+ continue;
757+ }
758+ if (okAction === "poi") {
759+ lines.push("- POI information updated");
760+ appended = true;
761+ continue;
762+ }
763+ if (okAction === "cargo") {
764+ lines.push("- Cargo information updated");
765+ appended = true;
766+ continue;
767+ }
768+ if (okAction === "nearby") {
769+ lines.push("- Nearby players information updated");
770+ appended = true;
771+ continue;
772+ }
773+ const summary = summarizeOkPayload(payload as Record<string, unknown>);
774+ if (summary) {
775+ lines.push(`- ${summary.text}`);
776+ appended = true;
777+ }
778+ continue;
779+ }
780+ if (result.result_type === "scan_result") {
781+ const target = getStringField(payload, "target_id") ?? "unknown";
782+ const success = (payload as Record<string, unknown>).success === true;
783+ const info = Array.isArray(
784+ (payload as Record<string, unknown>).revealed_info,
785+ )
786+ ? ((payload as Record<string, unknown>).revealed_info as unknown[])
787+ .map(String)
788+ .join(", ")
789+ : null;
790+ const details = info ? `: ${truncateText(info, 120)}` : "";
634791 lines.push(
635- `Action: ${block.action.ts} ${block.action.action}${argsText} -> FAILED: ${errorMsg}`.trim(),
792+ `- Scan ${success ? "successful" : "failed"} on ${target}${details}`,
636793 );
637- } else {
638- lines.push(
639- `Action: ${block.action.ts} ${block.action.action}${argsText}`.trim(),
794+ appended = true;
795+ continue;
796+ }
797+ if (result.result_type === "mining_yield") {
798+ const resource = getStringField(payload, "resource_id") ?? "ore";
799+ const quantity = Number(
800+ (payload as Record<string, unknown>).quantity ?? 0,
640801 );
802+ lines.push(`- Mined ${quantity}x ${resource}`);
803+ appended = true;
804+ continue;
641805 }
806+ lines.push(`- ${result.result_type} received`);
807+ appended = true;
808+ }
642809
643- // Filter out error events that were inlined above
644- const nonErrorEvents = block.events.filter(
645- (e) => e.type !== "error" && e.type !== "llm_invalid_action",
646- );
647- if (nonErrorEvents.length === 0 && !errorMsg) {
648- lines.push("- Event: none");
649- } else {
650- for (const event of nonErrorEvents) {
651- lines.push(formatEventLine(event));
652- }
653- }
810+ if (!appended) {
811+ lines.push("- No readable result payload.");
654812 }
655813
656814 return lines.join("\n");
@@ -688,6 +846,198 @@ function formatForumContext(history: HistoryEntry[]): string {
688846 return `\n${lines.join("\n")}\n`;
689847 }
690848
849+type OkSummary = {
850+ category: "movement" | "economy" | "combat" | "info";
851+ text: string;
852+};
853+
854+function summarizeOkPayload(
855+ payload: Record<string, unknown>,
856+): OkSummary | null {
857+ const action = String(payload.action ?? "");
858+ if (!action) return null;
859+
860+ switch (action) {
861+ case "travel": {
862+ const target = String(payload.target_poi ?? "unknown");
863+ return { category: "movement", text: `Traveling to ${target}` };
864+ }
865+ case "arrived": {
866+ const poiId = String(payload.poi_id ?? "destination");
867+ return { category: "movement", text: `Arrived at ${poiId}` };
868+ }
869+ case "jump": {
870+ const target = String(payload.target_system ?? "unknown");
871+ return { category: "movement", text: `Jumping to ${target}` };
872+ }
873+ case "jumped": {
874+ const systemId = String(payload.system_id ?? "new system");
875+ return { category: "movement", text: `Jumped to ${systemId}` };
876+ }
877+ case "dock": {
878+ const baseId = String(payload.base_id ?? "base");
879+ return { category: "movement", text: `Docked at ${baseId}` };
880+ }
881+ case "undock": {
882+ return { category: "movement", text: "Undocked" };
883+ }
884+ case "mine": {
885+ const resource = String(payload.resource ?? "ore");
886+ const quantity = Number(payload.quantity ?? 0);
887+ return {
888+ category: "economy",
889+ text: `Mined ${quantity > 0 ? `${quantity}x ` : ""}${resource}`,
890+ };
891+ }
892+ case "buy": {
893+ const itemId = String(payload.item_id ?? "item");
894+ const quantity = Number(payload.quantity ?? 0);
895+ const cost = Number(payload.cost ?? 0);
896+ return {
897+ category: "economy",
898+ text: `Bought ${quantity}x ${itemId} for ${cost} credits`,
899+ };
900+ }
901+ case "sell": {
902+ const itemId = String(payload.item_id ?? "item");
903+ const quantity = Number(payload.quantity ?? 0);
904+ const revenue = Number(payload.revenue ?? 0);
905+ return {
906+ category: "economy",
907+ text: `Sold ${quantity}x ${itemId} for ${revenue} credits`,
908+ };
909+ }
910+ case "repair": {
911+ const cost = Number(payload.cost ?? 0);
912+ return {
913+ category: "economy",
914+ text: `Repaired ship (cost: ${cost} credits)`,
915+ };
916+ }
917+ case "refuel": {
918+ const cost = Number(payload.cost ?? 0);
919+ return {
920+ category: "economy",
921+ text: `Refueled ship (cost: ${cost} credits)`,
922+ };
923+ }
924+ case "attack": {
925+ const targetId = String(payload.target_id ?? "target");
926+ const damage = Number(payload.damage ?? 0);
927+ return {
928+ category: "combat",
929+ text: `Attacked ${targetId}${damage > 0 ? ` (${damage} damage)` : ""}`,
930+ };
931+ }
932+ default:
933+ return {
934+ category: "info",
935+ text: `OK: ${action}`,
936+ };
937+ }
938+}
939+
940+function formatForumList(payload: Record<string, unknown>): string[] {
941+ const threads = findArrayField(payload, [
942+ "threads",
943+ "items",
944+ "results",
945+ "posts",
946+ ]);
947+ if (!threads || threads.length === 0) return ["Forum list received"];
948+
949+ const lines: string[] = ["Forum list:"];
950+ for (const item of threads.slice(0, 5)) {
951+ if (!item || typeof item !== "object") continue;
952+ const record = item as Record<string, unknown>;
953+ const id =
954+ getStringField(record, "id") ?? getStringField(record, "thread_id");
955+ const title =
956+ getStringField(record, "title") ?? getStringField(record, "subject");
957+ const category = getStringField(record, "category");
958+ const author =
959+ getStringField(record, "author") ?? getStringField(record, "username");
960+ const replies =
961+ getStringField(record, "reply_count") ??
962+ getStringField(record, "replies");
963+ const parts = [
964+ category ? `[${category}]` : null,
965+ title ? truncateText(title, 60) : "(untitled)",
966+ id ? `(id=${id})` : null,
967+ author ? `by ${author}` : null,
968+ replies ? `replies=${replies}` : null,
969+ ].filter(Boolean);
970+ if (parts.length > 0) lines.push(parts.join(" "));
971+ }
972+ return lines;
973+}
974+
975+function formatForumThread(payload: Record<string, unknown>): string[] {
976+ const thread = getObjectField(payload, "thread") ?? payload;
977+ const threadTitle =
978+ getStringField(thread, "title") ?? getStringField(thread, "subject");
979+ const threadId =
980+ getStringField(thread, "id") ?? getStringField(thread, "thread_id");
981+ const category = getStringField(thread, "category");
982+
983+ const lines: string[] = [
984+ `Forum thread: ${threadTitle ? truncateText(threadTitle, 60) : "(untitled)"}`,
985+ ];
986+
987+ const headerParts = [
988+ threadId ? `id=${threadId}` : null,
989+ category ? `category=${category}` : null,
990+ ].filter(Boolean);
991+ if (headerParts.length > 0) {
992+ lines[0] = `${lines[0]} (${headerParts.join(" ")})`;
993+ }
994+
995+ const posts =
996+ findArrayField(payload, ["posts", "replies", "messages"]) ??
997+ findArrayField(thread, ["posts", "replies", "messages"]);
998+ if (!posts || posts.length === 0) return lines;
999+
1000+ lines.push("Posts:");
1001+ for (const post of posts.slice(0, 3)) {
1002+ if (!post || typeof post !== "object") continue;
1003+ const record = post as Record<string, unknown>;
1004+ const author =
1005+ getStringField(record, "author") ??
1006+ getStringField(record, "username") ??
1007+ getStringField(record, "sender");
1008+ const content =
1009+ getStringField(record, "content") ??
1010+ getStringField(record, "message") ??
1011+ getStringField(record, "body");
1012+ if (!content) continue;
1013+ lines.push(`${author ? `${author}: ` : ""}${truncateText(content, 140)}`);
1014+ }
1015+
1016+ return lines;
1017+}
1018+
1019+function findArrayField(
1020+ payload: Record<string, unknown>,
1021+ keys: string[],
1022+): unknown[] | null {
1023+ for (const key of keys) {
1024+ const value = payload[key];
1025+ if (Array.isArray(value)) return value;
1026+ }
1027+ return null;
1028+}
1029+
1030+function getObjectField(
1031+ payload: Record<string, unknown>,
1032+ key: string,
1033+): Record<string, unknown> | null {
1034+ const value = payload[key];
1035+ if (value && typeof value === "object" && !Array.isArray(value)) {
1036+ return value as Record<string, unknown>;
1037+ }
1038+ return null;
1039+}
1040+
6911041 type ForumCheckInfo = {
6921042 ts: string;
6931043 relative: string;
@@ -780,35 +1130,6 @@ function formatRelativeTime(ts: string): string {
7801130 return `${days}d ago`;
7811131 }
7821132
783-function extractErrorMessage(
784- event: Extract<HistoryEntry, { kind: "event" }>,
785-): string | null {
786- if (!event.payload) return null;
787- const payload = parseJson(event.payload);
788- if (!payload || typeof payload !== "object") return null;
789-
790- const message = getStringField(payload, "message");
791- if (message) return truncateText(message, 80);
792-
793- const error = getStringField(payload, "error");
794- if (error) return truncateText(error, 80);
795-
796- const code = getStringField(payload, "code");
797- if (code) return code;
798-
799- return null;
800-}
801-
802-function formatEventLine(
803- event: Extract<HistoryEntry, { kind: "event" }>,
804-): string {
805- const summary = summarizeEvent(event);
806- if (summary) {
807- return `- Event: ${event.ts} ${event.type} ${summary}`.trim();
808- }
809- return `- Event: ${event.ts} ${event.type}`.trim();
810-}
811-
8121133 function formatActionArgs(argsRaw: string | null): string {
8131134 if (!argsRaw) return "";
8141135 const parsed = parseJson(argsRaw);
src/tui/index.ts+2−0
@@ -35,6 +35,8 @@ export interface ContextForum {
3535 export interface TuiContext {
3636 warnings?: ContextWarnings;
3737 forum?: ContextForum;
38+ memorySummary?: string | null;
39+ lastActionResult?: string | null;
3840 }
3941
4042 export interface TuiUpdateData {
src/tui/layout.ts+30−21
@@ -11,14 +11,16 @@ export interface LayoutConfig {
1111 leftWidth: number; // Width percentage for left sidebar
1212 rightWidth: number; // Width percentage for right sidebar
1313 leftTopHeightPercent: number; // Percent of left sidebar for top panel
14+ leftMiddleHeightPercent: number; // Percent of left sidebar for middle panel
1415 rightTopHeightPercent: number; // Percent of right sidebar for top panel
1516 }
1617
1718 export const DEFAULT_LAYOUT: LayoutConfig = {
1819 leftWidth: 20, // 20% for left sidebar
1920 rightWidth: 20, // 20% for right sidebar (center gets 60%)
20- leftTopHeightPercent: 40, // 40% of left sidebar for player/ship panel
21- rightTopHeightPercent: 40, // 40% of right sidebar for location panel
21+ leftTopHeightPercent: 35, // 35% of left sidebar for player/ship panel
22+ leftMiddleHeightPercent: 35, // 35% of left sidebar for world info panel
23+ rightTopHeightPercent: 40, // 40% of right sidebar for tactical panel
2224 };
2325
2426 export interface ComputedLayout {
@@ -58,29 +60,36 @@ export function computeLayout(
5860 // Height for panels (reserve 1 line for status bar)
5961 const availableHeight = termHeight - 1;
6062
61- // Left sidebar split
63+ // Left sidebar split into 3 panels: player/ship, world info, location
6264 const leftTopHeight = Math.max(
6365 MIN_PANEL_HEIGHT,
6466 Math.floor((availableHeight * config.leftTopHeightPercent) / 100),
6567 );
68+ const leftMiddleHeight = Math.max(
69+ MIN_PANEL_HEIGHT,
70+ Math.floor((availableHeight * config.leftMiddleHeightPercent) / 100),
71+ );
72+ const leftTopAdjusted = Math.min(
73+ leftTopHeight,
74+ availableHeight - MIN_PANEL_HEIGHT * 2,
75+ );
76+ const leftMiddleAdjusted = Math.min(
77+ leftMiddleHeight,
78+ availableHeight - leftTopAdjusted - MIN_PANEL_HEIGHT,
79+ );
6680 const leftBottomHeight = Math.max(
6781 MIN_PANEL_HEIGHT,
68- availableHeight - leftTopHeight,
82+ availableHeight - leftTopAdjusted - leftMiddleAdjusted,
6983 );
7084
71- // Right sidebar split into 3 panels: location (40%), tactical (30%), context (30%)
85+ // Right sidebar split into 2 panels: tactical (40%), context (60%)
7286 const rightTopHeight = Math.max(
7387 MIN_PANEL_HEIGHT,
7488 Math.floor((availableHeight * config.rightTopHeightPercent) / 100),
7589 );
76- const rightRemainingHeight = availableHeight - rightTopHeight;
77- const rightMiddleHeight = Math.max(
78- MIN_PANEL_HEIGHT,
79- Math.floor(rightRemainingHeight / 2),
80- );
8190 const rightBottomHeight = Math.max(
8291 MIN_PANEL_HEIGHT,
83- rightRemainingHeight - rightMiddleHeight,
92+ availableHeight - rightTopHeight,
8493 );
8594
8695 return {
@@ -88,13 +97,13 @@ export function computeLayout(
8897 left: 0,
8998 top: 0,
9099 width: leftWidthAbs,
91- height: leftTopHeight,
100+ height: leftTopAdjusted,
92101 },
93102 worldInfo: {
94103 left: 0,
95- top: leftTopHeight,
104+ top: leftTopAdjusted,
96105 width: leftWidthAbs,
97- height: leftBottomHeight,
106+ height: leftMiddleAdjusted,
98107 },
99108 log: {
100109 left: leftWidthAbs,
@@ -103,20 +112,20 @@ export function computeLayout(
103112 height: availableHeight,
104113 },
105114 location: {
106- left: leftWidthAbs + centerWidthAbs,
107- top: 0,
108- width: rightWidthAbs,
109- height: rightTopHeight,
115+ left: 0,
116+ top: leftTopAdjusted + leftMiddleAdjusted,
117+ width: leftWidthAbs,
118+ height: leftBottomHeight,
110119 },
111120 tactical: {
112121 left: leftWidthAbs + centerWidthAbs,
113- top: rightTopHeight,
122+ top: 0,
114123 width: rightWidthAbs,
115- height: rightMiddleHeight,
124+ height: rightTopHeight,
116125 },
117126 context: {
118127 left: leftWidthAbs + centerWidthAbs,
119- top: rightTopHeight + rightMiddleHeight,
128+ top: rightTopHeight,
120129 width: rightWidthAbs,
121130 height: rightBottomHeight,
122131 },
src/tui/panels/context.ts+25−1
@@ -1,4 +1,4 @@
1-// Context panel - warnings and forum status (prompt-only data not shown elsewhere)
1+// Context panel - warnings, memory summary, and forum status
22
33 import { applyBold, applyColor, COLORS } from "../colors";
44 import type { TuiContext } from "../index";
@@ -33,6 +33,30 @@ export function renderContextPanel(context: TuiContext | undefined): string {
3333
3434 lines.push("");
3535
36+ // Memory summary section
37+ lines.push(applyColor(applyBold("== Memory =="), COLORS.PANEL_TITLE));
Cut short: this commit's diff is over 1000 lines.