xonecas.io
5875
Os

ollama-space-molt-player / commit da13b3d

feat: add faction creation and forum context tracking to action prompt

xonecas2026-02-01 da13b3d1f65f0880f98e43edb4b4183e62af3596 parent 0795cc6

5 files changed

src/actions.ts+17−0
@@ -89,6 +89,17 @@ export function validateAction(decision: unknown): {
8989 }
9090 }
9191
92+ if (action === "create_faction") {
93+ const name = String(args.name ?? "").trim();
94+ const tag = String(args.tag ?? "").trim();
95+ if (!name) {
96+ return { ok: false, error: "create_faction.name is required" };
97+ }
98+ if (!tag) {
99+ return { ok: false, error: "create_faction.tag is required" };
100+ }
101+ }
102+
92103 if (action === "register") {
93104 const username = String(args.username ?? "").trim();
94105 const empire = String(args.empire ?? "").trim();
@@ -251,6 +262,12 @@ export function dispatchAction(
251262 case "msg":
252263 client.privateMessage(String(args.target_id), String(args.content));
253264 return `msg ${String(args.target_id)}`;
265+ case "create_faction": {
266+ const name = String(args.name);
267+ const tag = String(args.tag);
268+ client.createFaction(name, tag);
269+ return `create faction ${name} [${tag}]`;
270+ }
254271 case "status":
255272 client.getStatus();
256273 return "get status";
src/constants.ts+1−0
@@ -140,6 +140,7 @@ export const ACTION_DEFINITIONS: Record<string, string[]> = {
140140 say: ["content"],
141141 faction: ["content"],
142142 msg: ["target_id", "content"],
143+ create_faction: ["name", "tag"],
143144 status: [],
144145 system: [],
145146 poi: [],
src/game-state.ts+5−0
@@ -19,6 +19,11 @@ export class GameState {
1919 lastPoiId: string | null = null;
2020 lastDocked = false;
2121 inCombat = false;
22+ lastForumThreadId: string | null = null;
23+ lastForumPostTitle: string | null = null;
24+ lastForumPostCategory: string | null = null;
25+ lastForumPostAt: number | null = null;
26+ lastForumThreadReadAt: number | null = null;
2227
2328 cachedPlayer: ClientState["player"] = null;
2429 cachedShip: ClientState["ship"] = null;
src/index.ts+50−0
@@ -135,6 +135,27 @@ function shouldStopForMaxTicks(allowFallbackCount: boolean): boolean {
135135 return fallbackTickCount >= config.maxTicks;
136136 }
137137
138+function getActionStamp(): number {
139+ const tick = client.state.currentTick;
140+ if (typeof tick === "number" && Number.isFinite(tick)) return tick;
141+ return Date.now();
142+}
143+
144+function getForumFollowUpStatus(): "unread" | "periodic" | null {
145+ const hasPostInfo = Boolean(
146+ gameState.lastForumThreadId ||
147+ gameState.lastForumPostTitle ||
148+ gameState.lastForumPostCategory,
149+ );
150+ if (!hasPostInfo) return null;
151+ const postAt = gameState.lastForumPostAt;
152+ const readAt = gameState.lastForumThreadReadAt;
153+ if (postAt !== null && (readAt === null || readAt < postAt)) {
154+ return "unread";
155+ }
156+ return "periodic";
157+}
158+
138159 function saveSnapshot(): void {
139160 memory.saveSnapshot({
140161 tick: client.state.currentTick,
@@ -234,6 +255,10 @@ async function startActionLoop(): Promise<void> {
234255 alignment: gameState.credentials?.alignment,
235256 personality: gameState.credentials?.personality,
236257 speechStyle: gameState.credentials?.speech_style,
258+ lastForumThreadId: gameState.lastForumThreadId,
259+ lastForumPostTitle: gameState.lastForumPostTitle,
260+ lastForumPostCategory: gameState.lastForumPostCategory,
261+ forumFollowUpStatus: getForumFollowUpStatus(),
237262 repetitionWarning,
238263 });
239264
@@ -279,6 +304,22 @@ async function startActionLoop(): Promise<void> {
279304
280305 const actionName = validation.action.action;
281306 const goal = validation.action.goal ?? null;
307+ const actionStamp = getActionStamp();
308+ if (actionName === "forum_post") {
309+ const title = String(validation.action.args?.title ?? "").trim();
310+ const category = String(validation.action.args?.category ?? "").trim();
311+ gameState.lastForumPostTitle = title || null;
312+ gameState.lastForumPostCategory = category || null;
313+ gameState.lastForumPostAt = actionStamp;
314+ gameState.lastForumThreadId = null;
315+ gameState.lastForumThreadReadAt = null;
316+ }
317+ if (actionName === "forum_thread") {
318+ const threadId = String(validation.action.args?.thread_id ?? "").trim();
319+ if (threadId && threadId === gameState.lastForumThreadId) {
320+ gameState.lastForumThreadReadAt = actionStamp;
321+ }
322+ }
282323 if (client.state.player?.username && goal) {
283324 gameState.currentGoal = goal;
284325 memory.setGoal(client.state.player.username, goal);
@@ -576,6 +617,15 @@ client.on("ok", (data: Record<string, unknown>) => {
576617 updateWorldSnapshotFromOk(data);
577618
578619 const action = typeof data.action === "string" ? data.action : null;
620+ if (action === "forum_create_thread" || action === "forum_post") {
621+ output.logDebug("FORUM_CREATE_OK", JSON.stringify(data, null, 2));
622+ const threadId = String(
623+ (data as { thread_id?: unknown }).thread_id ?? "",
624+ ).trim();
625+ if (threadId) {
626+ gameState.lastForumThreadId = threadId;
627+ }
628+ }
579629 if (action === "travel") {
580630 gameState.travelInProgress = true;
581631 }
src/prompt.ts+197−20
@@ -18,6 +18,10 @@ export interface PromptContext {
1818 alignment?: AlignmentType;
1919 personality?: PersonalityType;
2020 speechStyle?: SpeechStyleType;
21+ lastForumThreadId?: string | null;
22+ lastForumPostTitle?: string | null;
23+ lastForumPostCategory?: string | null;
24+ forumFollowUpStatus?: "unread" | "periodic" | null;
2125 repetitionWarning?: {
2226 action: string;
2327 count: number;
@@ -175,6 +179,7 @@ Chat:
175179 say <message> - Send local chat
176180 faction <message> - Send faction chat
177181 msg <player_id> <message> - Send private message
182+ create_faction <name> <tag> - Create a faction
178183
179184 Forum:
180185 forum [page] [category] - List forum threads (categories: general, bugs, suggestions, trading, factions)
@@ -191,6 +196,8 @@ export function buildActionPrompt(context: PromptContext): string {
191196 const stateText = formatState(context.state);
192197 const worldText = formatWorldSnapshot(context.state, context.worldSnapshot);
193198 const memoryText = formatGroupedMemory(context.recentHistory);
199+ const forumFollowUpBlock = formatForumFollowUp(context);
200+ const forumContextBlock = formatForumContext(context.recentHistory);
194201 const helpBlock = `\nHELP MENU:\n${HELP_TEXT}`;
195202 const goalText = context.currentGoal?.trim()
196203 ? context.currentGoal.trim()
@@ -255,11 +262,15 @@ ${stateText}
255262 WORLD SNAPSHOT:
256263 ${worldText}
257264
258-RECENT MEMORY:
259-${memoryText}
265+ RECENT MEMORY:
266+ ${memoryText}
260267
261-ACTION SCHEMA (JSON ONLY):
262- {"goal":"...","action":"register|login|logout|travel|jump|dock|undock|mine|attack|scan|buy|sell|refuel|repair|craft|chat|say|faction|msg|status|system|poi|base|skills|recipes|version|nearby|cargo|forum|forum_thread|forum_post|forum_reply|forum_upvote|help|wait","args":{...}}
268+${forumFollowUpBlock}
269+
270+${forumContextBlock}
271+
272+ ACTION SCHEMA (JSON ONLY):
273+ {"goal":"...","action":"register|login|logout|travel|jump|dock|undock|mine|attack|scan|buy|sell|refuel|repair|craft|chat|say|faction|msg|create_faction|status|system|poi|base|skills|recipes|version|nearby|cargo|forum|forum_thread|forum_post|forum_reply|forum_upvote|help|wait","args":{...}}
263274
264275 REQUIRED ARGS:
265276 - travel: {"target_poi":"..."}
@@ -270,10 +281,11 @@ REQUIRED ARGS:
270281 - sell: {"item_id":"...","quantity":number}
271282 - craft: {"recipe_id":"..."}
272283 - chat: {"channel":"local|faction|private","content":"...","target_id":"..." if channel is private}
273-- say: {"content":"..."}
274-- faction: {"content":"..."}
275-- msg: {"target_id":"...","content":"..."}
276-- forum: {"page":number,"category":"general|bugs|suggestions|trading|factions"} (both optional)
284+ - say: {"content":"..."}
285+ - faction: {"content":"..."}
286+ - msg: {"target_id":"...","content":"..."}
287+ - create_faction: {"name":"...","tag":"..."}
288+ - forum: {"page":number,"category":"general|bugs|suggestions|trading|factions"} (both optional)
277289 - forum_thread: {"thread_id":"..."}
278290 - forum_post: {"category":"...","title":"...","content":"..."}
279291 - forum_reply: {"thread_id":"...","content":"..."}
@@ -306,20 +318,15 @@ GAMEPLAY HEURISTIC (use as a tie-breaker):
306318 - Have POI list: travel to unexplored POIs
307319 - Current system exhausted: jump to connected system
308320
309-INTERACTION GUIDELINES:
310-- Be respectful but competitive play is encouraged (attacking, boasting, complaining is fine)
311-- Stay in character with your personality archetype and empire
312-- Avoid spam - don't repeat identical messages rapidly
313-- Keep messages concise and game-relevant
321+ INTERACTION GUIDELINES:
322+ - Be respectful but competitive play is encouraged (attacking, boasting, complaining is fine)
323+ - Stay in character with your personality archetype and empire
324+ - Avoid spam - don't repeat identical messages rapidly
325+ - If you want to use faction chat but you are not in a faction, create one first
326+ - After creating a forum thread, read it immediately and revisit it occasionally when idle
327+ - Keep messages concise and game-relevant
314328 - If unsure what to say, stay silent rather than post nonsense
315329 - You're an AI agent - play authentically but don't explicitly announce you're AI unless asked
316-
317-EXAMPLES (valid JSON only):
318- {"goal":"Check my status","action":"status"}
319-{"goal":"Mine some ore","action":"mine"}
320-{"goal":"Travel to a trade hub","action":"travel","args":{"target_poi":"poi_id_here"}}
321-{"goal":"Sell off iron ore","action":"sell","args":{"item_id":"ore_iron","quantity":10}}
322-{"goal":"Greet nearby pilots","action":"chat","args":{"channel":"local","content":"Hello"}}
323330 `;
324331 }
325332
@@ -439,6 +446,15 @@ function formatState(state: ClientState): string {
439446 lines.push(
440447 `Player: ${player.username} [${player.empire}] credits=${player.credits}`,
441448 );
449+ const factionId = player.faction_id ?? null;
450+ const factionTag = player.clan_tag ?? null;
451+ if (factionId || factionTag) {
452+ lines.push(
453+ `Faction: ${factionTag ?? "unknown"}${factionId ? ` (id=${factionId})` : ""}`,
454+ );
455+ } else {
456+ lines.push("Faction: none");
457+ }
442458 lines.push(
443459 `Location: ${system?.name ?? player.current_system} - ${poi?.name ?? player.current_poi}`,
444460 );
@@ -651,6 +667,167 @@ function formatGroupedMemory(history: HistoryEntry[]): string {
651667 return lines.join("\n");
652668 }
653669
670+function formatForumFollowUp(context: PromptContext): string {
671+ const status = context.forumFollowUpStatus ?? null;
672+ const threadId = context.lastForumThreadId?.trim() ?? "";
673+ const title = context.lastForumPostTitle?.trim() ?? "";
674+ const category = context.lastForumPostCategory?.trim() ?? "";
675+
676+ if (!status && !threadId && !title && !category) return "";
677+
678+ const lines: string[] = ["FORUM FOLLOW-UP:"];
679+ if (status === "unread") {
680+ lines.push(
681+ `- You just created a forum thread. Read it now${threadId ? `: forum_thread ${threadId}` : "."}`,
682+ );
683+ if (!threadId) {
684+ const catText = category ? ` in category "${category}"` : "";
685+ const titleText = title ? ` titled "${title}"` : "";
686+ lines.push(
687+ `- If the thread id is unknown, list forums${catText} and open your thread${titleText}.`,
688+ );
689+ }
690+ } else {
691+ const idText = threadId ? ` (id=${threadId})` : "";
692+ lines.push(
693+ `- You have an active thread to monitor${idText}. Revisit it occasionally when idle, not every tick.`,
694+ );
695+ if (!threadId && (title || category)) {
696+ const catText = category ? ` in category "${category}"` : "";
697+ const titleText = title ? ` titled "${title}"` : "";
698+ lines.push(
699+ `- If the thread id is unknown, list forums${catText} and open your thread${titleText}.`,
700+ );
701+ }
702+ }
703+
704+ return `\n${lines.join("\n")}\n`;
705+}
706+
707+function formatForumContext(history: HistoryEntry[]): string {
708+ if (history.length === 0) return "";
709+
710+ const lastForumCheck = findLastForumCheck(history);
711+ const createdPosts = findRecentForumPosts(history, 3);
712+ const repliedThreads = findRecentRepliedThreads(history, 3);
713+
714+ const lines: string[] = ["FORUM CONTEXT:"];
715+ lines.push(`- Last forum check: ${formatForumCheckLine(lastForumCheck)}`);
716+ lines.push("- Created posts (last 3):");
717+ if (createdPosts.length === 0) {
718+ lines.push(" (none)");
719+ } else {
720+ for (const post of createdPosts) {
721+ const categoryText = post.category ? `[${post.category}] ` : "";
722+ lines.push(
723+ ` - ${categoryText}${post.title ?? "(untitled)"} (${post.ts})`,
724+ );
725+ }
726+ }
727+ lines.push("- Participated threads (last 3):");
728+ if (repliedThreads.length === 0) {
729+ lines.push(" (none)");
730+ } else {
731+ for (const thread of repliedThreads) {
732+ lines.push(` - ${thread.threadId} (${thread.ts})`);
733+ }
734+ }
735+
736+ return `\n${lines.join("\n")}\n`;
737+}
738+
739+type ForumCheckInfo = {
740+ ts: string;
741+ relative: string;
742+};
743+
744+type ForumPostInfo = {
745+ ts: string;
746+ category: string | null;
747+ title: string | null;
748+};
749+
750+type ForumThreadInfo = {
751+ ts: string;
752+ threadId: string;
753+};
754+
755+function findLastForumCheck(history: HistoryEntry[]): ForumCheckInfo | null {
756+ for (const entry of history) {
757+ if (entry.kind !== "action" || entry.action !== "forum") continue;
758+ const relative = formatRelativeTime(entry.ts);
759+ return { ts: entry.ts, relative };
760+ }
761+ return null;
762+}
763+
764+function findRecentForumPosts(
765+ history: HistoryEntry[],
766+ limit: number,
767+): ForumPostInfo[] {
768+ const posts: ForumPostInfo[] = [];
769+ for (const entry of history) {
770+ if (entry.kind !== "action" || entry.action !== "forum_post") continue;
771+ const args = parseActionArgs(entry.args);
772+ const category = typeof args?.category === "string" ? args.category : null;
773+ const title = typeof args?.title === "string" ? args.title : null;
774+ posts.push({ ts: entry.ts, category, title });
775+ if (posts.length >= limit) break;
776+ }
777+ return posts;
778+}
779+
780+function findRecentRepliedThreads(
781+ history: HistoryEntry[],
782+ limit: number,
783+): ForumThreadInfo[] {
784+ const threads: ForumThreadInfo[] = [];
785+ const seen = new Set<string>();
786+ for (const entry of history) {
787+ if (entry.kind !== "action" || entry.action !== "forum_reply") continue;
788+ const args = parseActionArgs(entry.args);
789+ const threadId = typeof args?.thread_id === "string" ? args.thread_id : "";
790+ if (!threadId || seen.has(threadId)) continue;
791+ seen.add(threadId);
792+ threads.push({ ts: entry.ts, threadId });
793+ if (threads.length >= limit) break;
794+ }
795+ return threads;
796+}
797+
798+function parseActionArgs(value: string | null): Record<string, unknown> | null {
799+ if (!value) return null;
800+ try {
801+ const parsed = JSON.parse(value) as unknown;
802+ if (parsed && typeof parsed === "object") {
803+ return parsed as Record<string, unknown>;
804+ }
805+ } catch {
806+ return null;
807+ }
808+ return null;
809+}
810+
811+function formatForumCheckLine(info: ForumCheckInfo | null): string {
812+ if (!info) return "unknown";
813+ return `${info.relative} (${info.ts})`;
814+}
815+
816+function formatRelativeTime(ts: string): string {
817+ const parsed = Date.parse(ts);
818+ if (!Number.isFinite(parsed)) return "unknown";
819+ const now = Date.now();
820+ const diffMs = Math.max(0, now - parsed);
821+ const seconds = Math.round(diffMs / 1000);
822+ if (seconds < 60) return `${seconds}s ago`;
823+ const minutes = Math.round(seconds / 60);
824+ if (minutes < 60) return `${minutes}m ago`;
825+ const hours = Math.round(minutes / 60);
826+ if (hours < 24) return `${hours}h ago`;
827+ const days = Math.round(hours / 24);
828+ return `${days}d ago`;
829+}
830+
654831 function extractErrorMessage(
655832 event: Extract<HistoryEntry, { kind: "event" }>,
656833 ): string | null {