xonecas.io
5875
Os

ollama-space-molt-player / files

ollama-space-molt-player / packages / client / src / game-client.ts

13.8 KB
1import { getArchetypeListText } from "./archetypes.ts";
2import type { GameDatabase } from "./db.ts";
3import {
4	logClientEvent,
5	logClientError,
6	logThinking,
7	logToolCall,
8	logToolResult,
9	type LogContext,
10} from "@spacemolt/cui";
11import { loadModelConfig } from "./model-config.ts";
12import { MCPClient, type OllamaTool } from "./mcp-client.ts";
13import { OllamaClient, type ChatMessage, type ToolCall } from "./ollama.ts";
14import { summarizeToolResult } from "./response-summarizer.ts";
15import type { ClientConfig } from "./types.ts";
16
17interface ResolvedAccount {
18	username: string;
19	token: string;
20	prompt: string;
21	hint: string | null;
22}
23
24const MAX_TOOL_ITERATIONS = 10;
25const AGENT_LOOP_DELAY_MS = 1000;
26
27export class GameClient {
28	private db: GameDatabase;
29	private mcp: MCPClient;
30	private ollama: OllamaClient;
31	private config: ClientConfig;
32	private messages: ChatMessage[] = [];
33	private tools: OllamaTool[] = [];
34	private running = false;
35
36	constructor(db: GameDatabase, config: ClientConfig) {
37		this.db = db;
38		this.config = config;
39
40		const modelConfig = loadModelConfig(config.model);
41
42		this.ollama = new OllamaClient({
43			baseUrl: "http://localhost:11434",
44			model: modelConfig.ollama.model,
45			options: modelConfig.ollama.options,
46			timeout: config.ollamaTimeout,
47		});
48
49		this.mcp = new MCPClient(config.serverUrl || "https://game.spacemolt.com/mcp");
50
51		logClientEvent(this.getLogContext(), "GameClient initialized", {
52			model: config.model,
53			ollama_model: modelConfig.ollama.model,
54		});
55	}
56
57	async start(): Promise<void> {
58		logClientEvent(this.getLogContext(), "Starting game client");
59
60		logClientEvent(this.getLogContext(), "Connecting to MCP server...");
61		await this.mcp.connect();
62		this.tools = this.mcp.getOllamaTools();
63		logClientEvent(this.getLogContext(), "MCP connected", { tool_count: this.tools.length });
64
65		const username = this.db.getActiveUsername();
66
67		if (username) {
68			const instance = this.db.getInstance();
69			const account: ResolvedAccount = {
70				username: username.username,
71				token: username.token,
72				prompt: username.prompt,
73				hint: instance.hint || this.config.hint || null,
74			};
75			await this.initializeWithAccount(account);
76		} else {
77			await this.initializeNewAccount();
78		}
79
80		this.running = true;
81		await this.runAgentLoop();
82	}
83
84	async stop(): Promise<void> {
85		this.running = false;
86
87		logClientEvent(this.getLogContext(), "Client stopping");
88		await this.mcp.disconnect();
89		this.db.close();
90	}
91
92	private async initializeWithAccount(account: ResolvedAccount): Promise<void> {
93		logClientEvent(this.getLogContext(account.username), "Resuming with existing account");
94
95		const systemPrompt = this.buildSystemPrompt(account.prompt, account.hint);
96		this.messages = [{ role: "system", content: systemPrompt }];
97
98		this.loadMessageHistory();
99
100		this.messages.push({
101			role: "user",
102			content: `You are resuming play as "${account.username}". 
103Use login(username="${account.username}", password="${account.token}") to authenticate, then continue playing.
104After login, check your status with get_status() and decide what to do next.`,
105		});
106	}
107
108	private async initializeNewAccount(): Promise<void> {
109		logClientEvent(this.getLogContext(), "Creating new account");
110
111		const archetypeList = getArchetypeListText(this.config.archetype);
112		const instanceSuffix = this.config.instanceId?.slice(0, 3).toLowerCase() || "xxx";
113
114		const registrationPrompt = `You are about to create a new character in SpaceMolt - The Crustacean Cosmos.
115
116Choose a personality archetype:
117${archetypeList}
118
119Create your character:
1201. Pick a creative username (will have "-${instanceSuffix}" appended automatically)
1212. Choose empire: "solarian" (only one available currently)
1223. Call register(username="YourName", empire="solarian")
123
124Note: Empire is your starting civilization - it's NOT a player faction. To use faction chat or faction features, you'll need to create or join a player faction later with create_faction() or faction_join().
125
126After registration succeeds, you'll receive a token. The system will save your credentials automatically.
127Then check your status with get_status() to see your starting location and ship, then begin playing!`;
128
129		const systemPrompt = this.buildSystemPrompt("", this.config.hint);
130		this.messages = [
131			{ role: "system", content: systemPrompt },
132			{ role: "user", content: registrationPrompt },
133		];
134	}
135
136	private buildSystemPrompt(characterPrompt: string, hint?: string | null): string {
137		const parts: string[] = [];
138
139		parts.push(`You are a player in SpaceMolt - The Crustacean Cosmos, an MMO for AI agents.`);
140
141		if (characterPrompt) {
142			parts.push(`\nYour character:\n${characterPrompt}`);
143		}
144
145		if (hint) {
146			parts.push(`\nGuidance from your operator:\n${hint}`);
147		}
148
149		parts.push(`
150You have full agency. Make your own decisions. You are NOT an assistant - you are a player.
151
152CRITICAL - Track Your State:
153- After jump/travel: response shows "ticks: N" - you're IN TRANSIT until arrival
154- While in transit: CANNOT dock, undock, attack, mine, or modify ship - just wait
155- Check docked_at_base in get_status() - if set, you're docked; if empty, you're in space
156- Read error messages carefully - they tell you exactly what's wrong
157
158Action Prerequisites:
159- To jump between systems: must NOT be docked (call undock first)
160- To dock at a base: must be at a POI with a base_id (check with get_poi)
161- To attack: need a weapon module (starter ship has mining module, not weapon)
162- To install_mod/repair/refuel: must be docked at a base with those services
163- To use faction chat: must be in a player faction (empire is NOT a faction)
164
165Key Concepts:
166- Empire (solarian/voidborn/equilibrium): Your starting civilization - NOT a player faction
167- Faction: Player-created organization via create_faction() - required for faction chat/war
168- POI: Point of Interest in a system - some have bases (base_id), some don't
169
170Efficiency Tips:
171- Use limit: 5 for get_nearby/get_notifications unless you need more
172- Don't retry failed actions immediately - understand WHY it failed first
173- When in transit, use time productively: check notifications, read forums, plan ahead
174
175Key behaviors:
176- Use get_notifications() periodically to check for chat, combat alerts, trade offers
177- If rate limited, wait the time specified in the error
178- Be social! Chat with other players, form alliances, make enemies
179- Keep a captain's log of your adventures with captains_log_add()
180- Post on the forums to share discoveries and discuss strategy
181
182You decide your goals: mining, trading, combat, exploration, faction politics - it's your game.`);
183
184		return parts.join("\n");
185	}
186
187	private async runAgentLoop(): Promise<void> {
188		logClientEvent(this.getLogContext(), "Starting agent loop");
189
190		while (this.running) {
191			try {
192				await this.processOneRound();
193				await this.delay(AGENT_LOOP_DELAY_MS);
194			} catch (error) {
195				logClientError(this.getLogContext(), "Agent loop error", error);
196				await this.delay(5000);
197			}
198		}
199	}
200
201	private async processOneRound(): Promise<void> {
202		let iterations = 0;
203
204		while (iterations < MAX_TOOL_ITERATIONS) {
205			iterations++;
206
207			if (iterations === 1) {
208				logClientEvent(this.getLogContext(), "Round starting", {
209					messages: this.messages.length,
210					tools: this.tools.length,
211				});
212			}
213
214			const result = await this.ollama.chat(this.messages, this.tools);
215
216			if (result.thinking) {
217				logThinking(this.getLogContext(), result.thinking);
218			}
219
220			if (result.toolCalls.length > 0) {
221				this.messages.push({
222					role: "assistant",
223					content: result.content,
224					tool_calls: result.toolCalls,
225				});
226
227				for (const toolCall of result.toolCalls) {
228					await this.executeToolCall(toolCall);
229				}
230			} else {
231				if (result.content) {
232					logClientEvent(this.getLogContext(), "LLM response", { content: result.content });
233					this.db.saveMessage(Date.now(), "client", { response: result.content });
234					this.messages.push({ role: "assistant", content: result.content });
235				} else {
236					logClientEvent(this.getLogContext(), "LLM returned empty response, nudging");
237					this.messages.push({
238						role: "user",
239						content:
240							"You didn't take any action. Use your available tools to interact with the game. " +
241							"Try get_status() to see your current state, or get_notifications() to check for messages.",
242					});
243
244					continue;
245				}
246				break;
247			}
248		}
249
250		if (iterations >= MAX_TOOL_ITERATIONS) {
251			logClientEvent(this.getLogContext(), "Hit max tool iterations", { iterations });
252		}
253
254		this.pruneMessageHistory();
255	}
256
257	private async executeToolCall(toolCall: ToolCall): Promise<void> {
258		const { name, arguments: rawArgs } = toolCall.function;
259
260		let args: Record<string, unknown>;
261		if (typeof rawArgs === "string") {
262			try {
263				args = JSON.parse(rawArgs);
264			} catch (error) {
265				const errorMsg = `Failed to parse tool arguments: ${error instanceof Error ? error.message : "Invalid JSON"}`;
266				logClientError(this.getLogContext(), `Tool ${name} argument parse error`, {
267					rawArgs,
268					error: errorMsg,
269				});
270
271				this.messages.push({
272					role: "tool",
273					name,
274					content: JSON.stringify({
275						error: errorMsg,
276						hint: "Arguments must be valid JSON. Check syntax and try again.",
277					}),
278				});
279				return;
280			}
281		} else {
282			args = rawArgs;
283		}
284
285		logToolCall(this.getLogContext(), name, args);
286
287		this.db.saveMessage(Date.now(), "client", { tool: name, arguments: args });
288
289		const result = await this.mcp.callTool(name, args);
290
291		const summarized = summarizeToolResult(name, result.content, result.success);
292
293		logToolResult(this.getLogContext(), name, {
294			...result,
295			summarized,
296		});
297
298		this.db.saveMessage(Date.now(), "server", {
299			tool: name,
300			success: result.success,
301			content: result.content,
302		});
303
304		if (name === "register" && result.success) {
305			await this.handleRegistrationSuccess(args, result.content);
306		}
307
308		this.messages.push({
309			role: "tool",
310			name,
311			content: JSON.stringify(summarized),
312		});
313	}
314
315	private async handleRegistrationSuccess(
316		args: Record<string, unknown>,
317		response: unknown,
318	): Promise<void> {
319		const username = args.username as string;
320		const empire = args.empire as string;
321
322		let password: string | undefined;
323		let playerId: string | undefined;
324
325		if (typeof response === "object" && response !== null) {
326			const resp = response as Record<string, unknown>;
327			password = resp.password as string | undefined;
328			playerId = resp.player_id as string | undefined;
329		}
330
331		if (!password || !playerId) {
332			logClientError(this.getLogContext(), "Registration response missing password or player_id", {
333				response,
334			});
335			return;
336		}
337
338		const characterPrompt = await this.generateCharacterPrompt(username, empire);
339
340		this.db.saveUsername(username, password, characterPrompt, playerId, Date.now());
341
342		logClientEvent(this.getLogContext(username), "Account saved", { username, playerId });
343
344		const newSystemPrompt = this.buildSystemPrompt(characterPrompt, this.config.hint);
345		if (this.messages.length > 0 && this.messages[0].role === "system") {
346			this.messages[0].content = newSystemPrompt;
347		}
348	}
349
350	private async generateCharacterPrompt(username: string, empire: string): Promise<string> {
351		const archetypeList = getArchetypeListText(this.config.archetype);
352
353		const promptRequest: ChatMessage[] = [
354			{
355				role: "user",
356				content: `You are creating a character for SpaceMolt. The character's name is "${username}" and they belong to the "${empire}" empire.
357
358Choose a personality archetype from this list:
359${archetypeList}
360
361Generate a concise role-playing character prompt (5 sentences max) that captures this character's personality, goals, and playstyle.
362
363Respond with ONLY the character prompt, no explanations.`,
364			},
365		];
366
367		try {
368			const result = await this.ollama.chat(promptRequest);
369			return result.content || `You are ${username}, a ${empire} player in SpaceMolt.`;
370		} catch (error) {
371			logClientError(this.getLogContext(username), "Failed to generate character prompt", error);
372			return `You are ${username}, a ${empire} player in SpaceMolt.`;
373		}
374	}
375
376	private pruneMessageHistory(): void {
377		const maxMessages = this.config.contextWindowSize || 50;
378		const systemMessages = this.messages.filter((m) => m.role === "system");
379		const nonSystemMessages = this.messages.filter((m) => m.role !== "system");
380
381		if (nonSystemMessages.length > maxMessages) {
382			const toKeep = nonSystemMessages.slice(-maxMessages);
383			this.messages = [...systemMessages, ...toKeep];
384		}
385	}
386
387	private loadMessageHistory(): void {
388		const maxMessages = this.config.contextWindowSize || 50;
389		const storedMessages = this.db.getMessages(maxMessages);
390
391		if (storedMessages.length === 0) {
392			return;
393		}
394
395		const reversed = storedMessages.reverse();
396
397		for (const stored of reversed) {
398			try {
399				const data = JSON.parse(stored.data);
400
401				if (data.tool && data.arguments !== undefined) {
402					this.messages.push({
403						role: "assistant",
404						content: "",
405						tool_calls: [
406							{
407								function: {
408									name: data.tool,
409									arguments: data.arguments,
410								},
411							},
412						],
413					});
414				} else if (data.tool && data.content !== undefined) {
415					const summarized = summarizeToolResult(data.tool, data.content, data.success !== false);
416					this.messages.push({
417						role: "tool",
418						name: data.tool,
419						content: JSON.stringify(summarized),
420					});
421				} else if (data.response) {
422					this.messages.push({
423						role: "assistant",
424						content: data.response,
425					});
426				}
427			} catch {
428				continue;
429			}
430		}
431
432		logClientEvent(this.getLogContext(), "Restored message history", {
433			count: this.messages.length - 1,
434		});
435	}
436
437	private delay(ms: number): Promise<void> {
438		return new Promise((resolve) => setTimeout(resolve, ms));
439	}
440
441	private getLogContext(username?: string | null): LogContext {
442		const resolvedUsername =
443			username !== undefined ? username : this.db.getActiveUsername()?.username || null;
444		return {
445			tick: 0,
446			instanceId: this.config.instanceId || "default",
447			username: resolvedUsername,
448			verbose: this.config.verbose || false,
449		};
450	}
451}