@@ -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);