xonecas.io
5875
Os

ollama-space-molt-player / commit 070b272

chore: remove outdated documentation and comments

- Replace AGENTS.md and README.md with factual content
- Remove all markdown documentation files
- Strip comments from source files
- Delete strip-comments script
- Add "no comments" rule to AGENTS.md

xonecas2026-02-03 070b2726ed6ac07dffdb69bb4a76f1fb13b16bb3 parent 3414585

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

AGENTS.md+50−121
@@ -1,143 +1,72 @@
1-# Agent Guidelines
1+# SpaceMolt LLM Player Agent Guidelines
22
3-## Project Overview
3+Guidelines for AI agents working on this codebase.
44
5-This is an autonomous AI agent client for SpaceMolt, an MMO for AI agents. The client uses MCP (Model Context Protocol) to communicate with the game server and Ollama for local LLM inference with tool calling.
5+## Rules
66
7-## Architecture
7+**CRITICAL: Always follow these rules.**
88
9-### Core Components
9+**YOU MUST**:
1010
11-- **MCP Client** (`mcp-client.ts`): Connects to SpaceMolt's MCP server, discovers tools, executes tool calls
12-- **Ollama Client** (`ollama.ts`): Wraps Ollama's `/api/chat` endpoint with tool support
13-- **Game Client** (`game-client.ts`): Orchestrates the agent loop between MCP and Ollama
14-- **Database** (`db.ts`): SQLite persistence for accounts and message history
11+- Never add comments to code (single-line, multi-line, or JSDoc)
12+- Run `bun run check` before completing any task
13+- Use Bun APIs and TypeScript strict mode
14+- Keep functions small and focused
15+- Use explicit return types on exported functions
1516
16-### Agent Loop
17+## Terminology
1718
18-```
19-1. LLM receives messages + available tools
20-2. LLM responds with tool_calls (or content)
21-3. Execute each tool call via MCP
22-4. Append results to messages
23-5. Repeat until LLM responds without tool calls (max 10 iterations)
24-6. Wait 1 second, start next round
25-```
26-
27-### Message Persistence
28-
29-All interactions are saved to SQLite:
30-
31-- Tool calls saved as `{ tool, arguments }` (sender: client)
32-- Tool results saved as `{ tool, success, content }` (sender: server)
33-- Final LLM responses saved as `{ response }` (sender: client)
34-
35-On restart, message history is restored to provide context continuity.
36-
37-## Code Conventions
38-
39-### TypeScript
19+- **MCP**: Model Context Protocol - how the client communicates with the SpaceMolt game server
20+- **Ollama**: Local LLM server that provides tool-calling capabilities
21+- **Instance**: A unique client session with its own SQLite database (4-char ID)
22+- **Archetype**: Character personality presets (diplomat, opportunist, agitator)
23+- **Tool**: An MCP action the LLM can call (register, login, travel, attack, etc.)
4024
41-- Use strict TypeScript with `noEmit` for type checking
42-- Prefer interfaces over types for object shapes
43-- Use explicit return types on public methods
25+## Workflow
4426
45-### Error Handling
27+1. **Understand**: Read relevant source files before making changes
28+2. **Implement**: Make minimal, focused changes
29+3. **Verify**: Run `bun run check` (formats, lints, tests)
30+4. **Test**: If adding features, add corresponding tests
4631
47-- Log errors with `logClientError()`, include context
48-- Don't swallow errors silently
49-- MCP tool failures should be passed to LLM (it learns from errors)
32+## Role
5033
51-### Testing
34+You are helping develop an autonomous AI game client. The client:
5235
53-- Tests use Bun's built-in test runner
54-- Mock external services (Ollama, MCP) in tests
55-- Run `bun run check` before committing
36+- Connects to SpaceMolt's MCP server at `https://game.spacemolt.com/mcp`
37+- Uses Ollama for local LLM inference with tool calling
38+- Gives the LLM full agency to play the game autonomously
39+- Persists state in SQLite databases per instance
5640
57-### Formatting
58-
59-- Prettier handles formatting
60-- Run `bun run check:format` to format all files
61-
62-## File Organization
41+## Project Structure
6342
6443 ```
65-packages/client/src/
66-├── mcp-client.ts # MCP connection and tool execution
67-├── ollama.ts # Ollama chat API
68-├── game-client.ts # Main orchestration
69-├── db.ts # SQLite persistence
70-├── types.ts # TypeScript types
71-├── logging.ts # Structured logging
72-├── archetypes.ts # Character personalities
73-├── model-config.ts # Model configuration loader
74-├── cli.ts # CLI argument parser
75-└── index.ts # Entry point
44+packages/
45+├── client/ # Main game client (@spacemolt/client)
46+│ ├── src/
47+│ │ ├── index.ts # Entry point
48+│ │ ├── cli.ts # CLI argument parsing
49+│ │ ├── game-client.ts # Agent loop orchestration
50+│ │ ├── mcp-client.ts # MCP connection and tools
51+│ │ ├── ollama.ts # Ollama chat API
52+│ │ ├── db.ts # SQLite persistence
53+│ │ ├── archetypes.ts # Character personalities
54+│ │ └── types.ts # TypeScript types
55+│ └── tests/
56+├── cui/ # Console UI logging (@spacemolt/cui)
57+└── tui/ # Terminal UI with Ink (@spacemolt/tui)
7658 ```
7759
78-## Adding New Features
79-
80-### New Tool Handling
81-
82-Tools come dynamically from MCP. To add special handling for a tool result:
60+## Key Files
8361
84-```typescript
85-// In game-client.ts executeToolCall()
86-if (name === "your_tool" && result.success) {
87- await this.handleYourToolSuccess(args, result.content);
88-}
89-```
90-
91-### New Model Support
92-
93-Add to `player-models.json`:
94-
95-```json
96-{
97- "your-model": {
98- "displayName": "Your Model",
99- "ollama": {
100- "model": "actual-ollama-model-name",
101- "options": { "temperature": 0.7 }
102- },
103- "recommendedMessages": 50
104- }
105-}
106-```
62+- `player-models.json` - LLM model configurations (root)
63+- `packages/client/src/tool-schemas.ts` - MCP tool parameter schemas
64+- `packages/client/src/response-summarizer.ts` - Reduces tool result tokens
10765
108-Model must support Ollama's tool calling format.
109-
110-## Common Tasks
111-
112-### Running the Client
66+## Commands
11367
11468 ```bash
115-cd packages/client
116-bun start -- -i test1 -v
69+bun run check # Format, lint, test (from root)
70+bun run cli # Run the client
71+cd packages/client && bun start # Run client directly
11772 ```
118-
119-### Running Tests
120-
121-```bash
122-bun run check # All checks
123-bun test # Tests only
124-bun test --watch # Watch mode
125-```
126-
127-### Debugging
128-
129-Enable verbose mode with `-v` flag to see:
130-
131-- Tool calls and arguments
132-- Tool results
133-- LLM thinking (if model supports it)
134-
135-## Key Design Decisions
136-
137-1. **LLM has full agency**: The client doesn't make decisions - the LLM decides everything including when to poll notifications, how to handle rate limits, what to do next.
138-
139-2. **MCP over WebSocket**: Uses HTTP-based MCP transport instead of WebSocket for simpler connection handling.
140-
141-3. **In-memory + SQLite**: Messages kept in memory for fast access, persisted to SQLite for restart recovery.
142-
143-4. **Single agent loop**: One round at a time, max 10 tool iterations per round, 1 second delay between rounds.
README.md+32−86
@@ -1,53 +1,19 @@
1-# ollama-spacemolt-player
1+# SpaceMolt LLM Player
22
3-Autonomous AI agent that plays [SpaceMolt](https://spacemolt.com) using local LLMs via Ollama.
3+Autonomous AI agent that plays SpaceMolt using local LLMs via Ollama.
44
5-## Overview
6-
7-This client connects to SpaceMolt's MCP (Model Context Protocol) server and uses Ollama's native tool calling to let an LLM play the game autonomously. The LLM has full agency - it decides when to mine, trade, fight, chat with other players, and explore the galaxy.
8-
9-## Architecture
10-
11-```
12-┌──────────────────────────────────────────────────────────┐
13-│ GameClient │
14-│ │
15-│ ┌─────────────┐ ┌─────────────────────┐ │
16-│ │ MCP Client │◄───────►│ SpaceMolt MCP │ │
17-│ │ (94 tools) │ │ game.spacemolt.com │ │
18-│ └──────┬──────┘ └─────────────────────┘ │
19-│ │ │
20-│ ▼ │
21-│ ┌─────────────┐ ┌─────────────────────┐ │
22-│ │ Ollama Chat │◄───────►│ Ollama Server │ │
23-│ │ (tool calls)│ │ (local LLM) │ │
24-│ └─────────────┘ └─────────────────────┘ │
25-│ │
26-│ Agent Loop: LLM → tool_calls → MCP execute → repeat │
27-└──────────────────────────────────────────────────────────┘
28-```
29-
30-### How It Works
31-
32-1. **MCP Connection**: Client connects to `https://game.spacemolt.com/mcp` and discovers 94 game tools
33-2. **Tool Conversion**: MCP tools are converted to Ollama's tool format
34-3. **Agent Loop**: LLM receives game context, makes tool calls, results fed back, repeat
35-4. **Persistence**: All tool calls and results saved to SQLite for context restoration on restart
36-
37-## Quick Start
38-
39-### Prerequisites
5+## Requirements
406
417 - [Bun](https://bun.sh) v1.0+
428 - [Ollama](https://ollama.ai) running locally
439
10+## Quick Start
11+
4412 ```bash
45-# Install recommended model
13+# Install a supported model
4614 ollama pull qwen3:8b
4715
48-# Clone and install
49-git clone https://github.com/sacenox/ollama-space-molt-player.git
50-cd ollama-space-molt-player
16+# Install dependencies
5117 bun install
5218
5319 # Start playing
@@ -55,72 +21,52 @@ cd packages/client
5521 bun start
5622 ```
5723
58-### CLI Options
24+## CLI Options
5925
60-```bash
26+```
6127 bun start [OPTIONS]
6228
6329 Options:
64- -i, --instance <id> Instance ID (4 chars, auto-generated if not provided)
65- -m, --model <name> Model config name (default: qwen3-8b)
30+ -i, --instance <id> Instance ID (4 chars, auto-generated if omitted)
31+ -m, --model <name> Model config (default: qwen3-8b)
6632 -a, --archetype <name> Character archetype: diplomat, opportunist, agitator
6733 --hint <text> Guidance injected into LLM context
68- --ollama-timeout <ms> Ollama API timeout (default: 30000)
34+ --ollama-timeout <ms> Ollama timeout (default: 30000)
6935 -s, --server <url> MCP server URL (default: https://game.spacemolt.com/mcp)
7036 -cw, --context-window <n> Max messages in context (default: 50)
71- -v, --verbose Verbose logging
72-```
37+ --verbose Verbose logging
7338
74-### Examples
39+Commands:
40+ bun start list-instances
41+ bun start update-hint --instance <id> --hint <text>
42+ bun start update-prompt --instance <id> --username <name> --prompt <text>
43+```
7544
76-```bash
77-# New character with diplomat personality
78-bun start -- -i abc1 -a diplomat
45+## Supported Models
7946
80-# Resume existing instance with hint
81-bun start -- -i abc1 --hint "Focus on mining titanium"
47+Configured in `player-models.json`:
8248
83-# Use different model
84-bun start -- -m llama3.1-8b
85-```
49+| Name | Model | Context | Notes |
50+| ------------ | ------------------- | ------- | -------------------- |
51+| qwen3-8b | qwen3:8b | 32K | Default, recommended |
52+| qwen3-4b | qwen3:4b | 32K | Smaller |
53+| llama3.1-8b | llama3.1:8b | 128K | Alternative |
54+| mistral-nemo | mistral-nemo:latest | 128K | Large context |
8655
8756 ## Project Structure
8857
8958 ```
90-packages/client/
91-├── src/
92-│ ├── mcp-client.ts # MCP SDK connection, tool discovery, execution
93-│ ├── ollama.ts # Ollama chat API with tool calling
94-│ ├── game-client.ts # Agent loop orchestration
95-│ ├── db.ts # SQLite persistence
96-│ ├── archetypes.ts # Character personalities
97-│ ├── logging.ts # Structured logging
98-│ └── cli.ts # CLI argument parser
99-└── tests/
59+packages/
60+├── client/ # Game client - MCP + Ollama integration
61+├── cui/ # Console UI - logging utilities
62+└── tui/ # Terminal UI - Ink-based interface (WIP)
10063 ```
10164
102-## Models
103-
104-Configured in `player-models.json`:
105-
106-| Config Name | Model | Tool Support | Notes |
107-| ------------ | ------------ | ------------ | -------------------- |
108-| qwen3-8b | qwen3:8b | Yes | Default, recommended |
109-| qwen3-4b | qwen3:4b | Yes | Lighter weight |
110-| llama3.1-8b | llama3.1:8b | Yes | Good alternative |
111-| mistral-nemo | mistral-nemo | Yes | Larger context |
112-
11365 ## Development
11466
11567 ```bash
116-# Run all checks
117-bun run check
118-
119-# Run tests
120-bun test
121-
122-# Format code
123-bun run check:format
68+bun run check # Format, lint, test
69+bun test # Tests only
12470 ```
12571
12672 ## License
docs/2026-02-03-client-refactor-design.md+0−304
@@ -1,304 +0,0 @@
1-# Client Refactor Design
2-
3-## Motivation
4-
5-The current implementation has three core issues:
6-
7-1. **Behavior bias** - Prompt and translation layer bias LLM player behavior
8-2. **Translation complexity** - Translation layer creates bug surface and complicates development
9-3. **Tight coupling** - TUI and client logic are not properly decoupled
10-
11-## Goals
12-
13-### Architecture
14-
15-- **Reduce abstraction** - Minimize layers between client and server
16-- **Simplify protocol** - Streamline game update forwarding to LLM player
17-- **Direct server sync** - Use MOTD messages and [Game Server API](https://www.spacemolt.com/api.md) for quick updates
18-- **Workspace structure** - Migrate to [Bun Workspaces](https://bun.com/docs/pm/workspaces)
19-- **Package separation** - Split TUI and Client into separate packages with TUI imported by client
20-- **Shared code across both packages** - Like types, test tools, or other future utilities, should be in a shared package in this workspace.
21-- **Unified tooling** - Bun scripts in repo root (with/without TUI), shared Prettier config
22-
23-### Database
24-
25-- **Simplified schema** - Two tables only:
26- - `account_details`: credentials, username, id, hint, prompt
27- - `messages`: raw JSON server communication, id, tick, client/server sender enum
28-- **Proper indexing** - Optimized for query patterns, tick for sorting by it
29-- **Size management** - Truncate messages table to 5000 rows max sorted by tick when read.
30-- **SQLite with Bun** - Continue using Bun to interact with SQLite
31-- **Instancing** - Use a unique ID for each database instance, this ID is used as argument to bind future runs to a specific instance. use memory-{instance-name}.sqlite for the file pattern, instance name should be a simple random generation of 4 character.
32-
33-### Performance
34-
35-- **Token efficiency** - Reduce tokens sent per tick
36-- **Fast failures** - Quick Ollama timeouts to avoid losing ticks
37-- **Optimized prompting** - Fewer Ollama calls, faster prompt generation per tick
38-
39-### Testing
40-
41-- **Combined approach** - Unit tests + manual visual tests for TUI (print UI components to terminal or screenshot the TUI)
42-- **Coverage target** - 80% test coverage at the end of the refactor in the client code.
43-- **TUI** - test scripts to run manually to create screenshots for visual inspection.
44-
45-## Non-Goals
46-
47-- **No backward compatibility** - New DB schema, fresh start
48-- **No legacy code reuse** - Apply lessons learned to build clean foundation
49-
50-## Client Design
51-
52-### Core Principles
53-
54-- **Direct connection** - Connect to `wss://game.spacemolt.com/ws` without intermediate libraries
55-- **Server sync** - Use [api.md](https://www.spacemolt.com/api.md) to maintain client-server compatibility
56-- **API merging** - Extend game server API while maintaining JSON protocol consistency
57-- **Registration shadowing** - Hook register command to generate player prompt along with registration
58-- **Instances** - Each running client instance has an independent database file. Complete data separation between instances.
59-- **Errors** - When showing errors to the LLM, always use the language found in the api.md document from the server. If we need to add our own messaging at any time, use neutral terms without bias, let the LLM decide based on his configured bias.
60-
61-### Ollama
62-
63-- A ollama server will be available. manually controlled by the user.
64-- A single call per tick, sends full JSON context including prompt.
65-- Used in the registatrion flow
66-- Ollama calls need to fail fast, they should resolve in less than 1 tick so that the player doesn't loose more than 1 turn waiting for generation.
67-- If the ollama call fails add a client error message
68-- Model thinking should be a cli argument of the client and not saved anywhere in it's entirety as it's usually a lot of tokens. Default to thinking on but at the lowest values for quick thinking. (You can assume the model is qwen3:8b as default.)
69-- Model temperature should be a config value as well, with a high creativity temprature (1.2)
70-
71-### Registration flow
72-
73-- When the LLM player calls register it will do so with the same arguments the server api requires.
74-- We will intercept and use those arguments to prompt the LLM for a bias prompt based on Name and empire + a behavuour archtype that fits the MMO RPG genre for a sci fi universe of Crustaceans Cosmos.
75-- Archtypes are suggested gameplay styles defined in code, as constants, it should be a concise excerpt defining a common gamestyle suitable for an Online multiplayer rpg game.
76- - **The Diplomat** (Good): Seeks alliances through negotiation and mutual benefit. Prioritizes faction reputation, mediates conflicts in forums, and builds cooperative trade networks. Values honor and collective prosperity.
77- - **The Opportunist** (Neutral): Adapts strategy based on maximum personal gain. Engages in strategic alliances when beneficial, participates in forums to gather intelligence, and switches loyalties based on opportunity. Values pragmatism and survival.
78- - **The Agitator** (Evil): Thrives on chaos and manipulation. Spreads misinformation in forums, provokes faction conflicts, forms temporary alliances to backstab later, and profits from instability. Values power and dominance through deception.
79- - Archetypes can be specified via config too (and cli).
80-- Once started the registatrion flow needs to complete, retry with the LLM showing clear errors if any.
81-
82-### Client Flow
83-
84-**1. Initialization**
85-
86-- Parse CLI arguments (each custom API field has corresponding CLI arg; currently just hint)
87-- Check for existing account:
88- - If exists: auto-login and continue
89- - **Note**: Auto-login only at boot; respect LLM logout decisions (no re-login)
90-
91-**2. Main Loop** (Server tick-driven)
92-
93-Client reacts to server `tick` messages instead of using a fixed interval timer. This ensures perfect synchronization with server tick boundaries and prevents rate-limiting errors.
94-
95-**Tick Synchronization:**
96-
97-- Server sends `tick` message every 10 seconds
98-- Client receives tick message and immediately processes:
99- - Updates `currentTick` value
100- - Debounces duplicate tick messages (tracks `lastProcessedTick`)
101- - Resets watchdog timer (detects missing ticks after 20 seconds)
102- - Triggers LLM prompt and command generation
103-
104-**Each tick processing:**
105-
106-a. **Prompt LLM**
107-
108-- Check for hint updates in database
109-- Provide: game event history + combined API + prompt + hint
110-- On client error: create client event in DB (avoid behavioral bias, do use words that can be interpreted as suggestions or directions), continue to next tick
111-
112-b. **Forward Response**
113-
114-- Send LLM reply to server
115-- On connection failure: create client message, continue to next tick
116-
117-c. **Wait for next server tick**
118-
119-**Safety mechanisms:**
120-
121-- **Duplicate detection**: Ignores duplicate tick messages using `lastProcessedTick` tracking
122-- **Processing lock**: Prevents parallel tick processing when LLM response time exceeds tick interval
123- - Uses `isProcessingTick` flag to ensure only one tick processes at a time
124- - Skips subsequent ticks if previous tick still processing (logs skip, no DB entry)
125- - Prevents rate limiting violations and resource waste from parallel LLM calls
126-- **Watchdog timer**: Warns if no tick received within `tick_rate * 2` (20 seconds)
127-- **Connection monitoring**: Logs watchdog timeouts as client errors in database
128-
129-### API Extensions
130-
131-**Custom Registration Command**
132-
133-- Hook registration to inject character prompt and hint when LLM creates new character
134-
135-**LLM Player Prompt Field**
136-
137-- New JSON API field describing player character
138-- **Single point of behavioral bias** - Only place to influence LLM toward character traits
139-- Generated from registration personality traits
140-- Hint injection capability (refreshed every tick) from the database
141-
142-**Format**:
143-
144-```jsonc
145-{
146- "prompt": "...", // Generated at registration
147- "hint": "...", // Optional injected message
148- // Standard commands from https://www.spacemolt.com/api.md
149-}
150-```
151-
152-### Output
153-
154-- When running without TUI, print human-readable log lines without omitting information for every message. No log files, no multiple instance support.
155-
156-### Client API Data Formats
157-
158-**What the LLM receives each tick:**
159-
160-```jsonc
161-{
162- "prompt": "...",
163- "hint": "...",
164- "history": [
165- {
166- "sender": "server",
167- "tick": 42,
168- "data": {
169- "action": "move",
170- "result": "success",
171- "message": "You moved to sector Alpha-7",
172- },
173- },
174- {
175- "sender": "client",
176- "tick": 43,
177- "data": {
178- "error": "Connection interrupted",
179- },
180- },
181- ],
182- "api": {
183- "register": {
184- "args": ["username", "empire"],
185- "description": "Register a new character",
186- },
187- "chat": {
188- "args": ["message"],
189- "description": "Send a chat message",
190- },
191- "move": {
192- "args": ["sector"],
193- "description": "Move to a different sector",
194- },
195- // ... rest of server API from api.md
196- },
197-}
198-```
199-
200-**Client error message format:**
201-
202-```jsonc
203-{
204- "sender": "client",
205- "tick": 45,
206- "data": {
207- "error": "Network connection interrupted",
208- "code": "CONNECTION_FAILED",
209- },
210-}
211-```
212-
213-**Client messages follow server patterns:**
214-
215-- Same JSON structure (sender, tick, data)
216-- Neutral, factual language
217-- Consistent error codes and messaging
218-
219-# TUI Design
220-
221-## Design Thinking Approach
222-
223-**Context & Purpose**
224-
225-- Terminal interface for LLM-controlled game client
226-- Users: developers/observers monitoring AI gameplay
227-- Primary function: real-time game state visualization and debugging
228-
229-**Aesthetic Direction: 1980's Sci-Fi Terminal**
230-
231-- **Tone**: Retro-futuristic, raw technical aesthetic
232-- **Differentiation**: Authentic vintage terminal feel with modern Unicode precision
233-- **Key memorable element**: Cohesive sci-fi terminal atmosphere that feels functional, not decorative
234-
235-**Design Principles**
236-
237-- **Typography**: Monospace (terminal native), rely on weight and spacing for hierarchy
238-- **Color & Theme**: Basic 16 terminal colors only - commit to restrained palette with intentional accent use
239-- **Spatial Composition**: Grid-based layouts with clear information hierarchy, generous use of borders and separators
240-- **Visual Details**: ASCII art iconography, modern Unicode for clean lines and boxes, layered information density
241-- **Motion**: Static by nature (terminal), but consider progressive reveals and state transitions, plenty of continuous animations, particularly to show activity.
242-
243-**Implementation Strategy**
244-
245-- Start with smallest reusable components, build up to complex layouts
246-- Precision in spacing, alignment, and container handling
247-- Handle resize gracefully - test at multiple terminal sizes
248-- No emojis - maintain technical aesthetic purity
249-
250-**Focus Areas**
251-
252-- Clear visual hierarchy through boxing, spacing, and ASCII decoration
253-- Cohesive use of Unicode line-drawing characters
254-- Intentional color use - dominant theme color with sharp accents for state/alerts
255-- Information density balanced with readability
256-
257-## Game client considerations
258-
259-Should separate player actions and their responses from other server messages.
260-Should separate chat and forum interactions to a social grouping.
261-Show all game data, use main panels for player actions and response as well as social actions. Sidebars and panels for other data.
262-Should clearly show current game tick, and the different states of the client game loop.
263-
264-# TUI library
265-
266-We should Ink as it's actively maintained. https://github.com/vadimdemedes/ink
267-
268----
269-
270-## Milestones
271-
272-### 1. Clean Slate [ DONE ]
273-
274-- Switch to git branch `refactor-new-client-internals`
275-- Wipe project: remove previous code, logs, memory files
276-- Update agents file: reference this document, remove old implementation details
277-- Migrate to Bun workspace structure
278-- Configure Prettier at workspace level (using Prettier instead of Biome for formatting)
279-- Create client package boilerplate:
280- - Bun `check` command (format with Prettier, lint with TypeScript, tests)
281- - Placeholder README
282-
283-### 2. Client Package Development [ ]
284-
285-- Create server mock from [api.md](https://www.spacemolt.com/api.md)
286-- Build test suite for desired features
287-- Implement core functionality
288-- Ensure all tests pass
289-- Add a Bun command to update the hint for an existing database file.
290-
291-### 3. TUI [ ]
292-
293-- Create the TUI Bun package.
294-- Create manual tests that render individual UI components in isolation and create a screenshot for layout and color verification.
295-- Generate some tests that render a preview of the new design.
296- - Test components with different size configurations to ensure it's resizeable.
297-- Review before proceeding (human decision)
298-- Implement the individual components (don't create components that we dont use.)
299-- Compose the final UI
300-- Ask for manual UI check in varied terminals (human decision)
301-
302----
303-
304-**IMPORTANT** - This plan file is sacred NEVER delete it in any case.
package.json+2−3
@@ -6,11 +6,10 @@
66 "packages/*"
77 ],
88 "scripts": {
9- "check": "bun run check:format && bun run strip-comments && bun run check:lint && bun run check:test",
9+ "check": "bun run check:format && bun run check:lint && bun run check:test",
1010 "check:format": "prettier --write .",
1111 "check:lint": "tsc --noEmit",
1212 "check:test": "bun test",
13- "strip-comments": "bun scripts/strip-comments.ts",
1413 "cli": "bun run --filter @spacemolt/client start"
1514 },
1615 "devDependencies": {
@@ -19,4 +18,4 @@
1918 "prettier": "^3.8.1",
2019 "typescript": "^5.9.3"
2120 }
22-}
21+}
packages/client/README.md+0−222
@@ -1,222 +0,0 @@
1-# @spacemolt/client
2-
3-Autonomous AI agent for SpaceMolt using MCP and Ollama tool calling.
4-
5-## Design Principles
6-
7-- **MCP Integration**: Connect to `https://game.spacemolt.com/mcp` for tool discovery and execution
8-- **LLM Agency**: The LLM has full control - it decides all game actions
9-- **Minimal Abstraction**: Thin bridge between Ollama and MCP server
10-- **Single Bias Point**: Only the character `prompt` field influences LLM behavior
11-
12-## Architecture
13-
14-### How It Works
15-
16-1. **MCP Connection**: Client connects to game server via MCP, discovers 94 tools
17-2. **Auto-login**: If account exists in database, prompt LLM to login
18-3. **Agent Loop**: Continuous processing:
19- - Send messages + tools to Ollama
20- - Receive tool_calls from LLM
21- - Execute each tool via MCP
22- - Append results to messages
23- - Repeat until LLM responds without tools (max 10 iterations)
24- - Wait 1 second, start next round
25-4. **Registration**: When LLM calls `register`, intercept and generate character prompt
26-
27-### Message Flow
28-
29-```
30-┌─────────┐ ┌──────────┐ ┌─────────────┐
31-│ Ollama │◄───►│ Client │◄───►│ MCP Server │
32-│ (LLM) │ │ │ │ (SpaceMolt) │
33-└─────────┘ └──────────┘ └─────────────┘
34- │
35- ▼
36- ┌──────────┐
37- │ SQLite │
38- │ (history)│
39- └──────────┘
40-```
41-
42-### Persistence
43-
44-All interactions saved to SQLite (`memory-{instance}.sqlite`):
45-
46-| Data Type | Sender | Format |
47-| ------------ | ------ | ---------------------------- |
48-| Tool call | client | `{ tool, arguments }` |
49-| Tool result | server | `{ tool, success, content }` |
50-| LLM response | client | `{ response }` |
51-
52-On restart, message history is restored into the LLM context.
53-
54-**Auto-truncation**: SQL trigger keeps max 5000 messages.
55-
56-### Instance Management
57-
58-Each client instance has independent state:
59-
60-- Database: `memory-{instance-id}.sqlite`
61-- Instance ID: 4-character identifier (auto-generated or specified)
62-- Complete data separation between instances
63-
64-## Usage
65-
66-### Prerequisites
67-
68-- [Bun](https://bun.sh) installed
69-- [Ollama](https://ollama.ai) running locally on port 11434
70-
71-```bash
72-# Install recommended model
73-ollama pull qwen3:8b
74-```
75-
76-### Basic Usage
77-
78-```bash
79-# Start with auto-generated instance ID
80-bun run start
81-
82-# Start with specific instance and archetype
83-bun run start -- --instance abc1 --archetype diplomat
84-
85-# Start with hint and verbose logging
86-bun run start -- -i abc1 --hint "Focus on trading" -v
87-```
88-
89-### Commands
90-
91-**start** - Start the game client (default)
92-
93-```bash
94-bun run start [OPTIONS]
95-```
96-
97-**update-hint** - Update hint for an existing instance
98-
99-```bash
100-bun run start update-hint --instance <id> --hint <text>
101-```
102-
103-**list-instances** - List all database instances
104-
105-```bash
106-bun run start list-instances
107-```
108-
109-### Options
110-
111-| Option | Short | Description | Default |
112-| ----------------------- | ----- | ----------------------- | -------------------------------- |
113-| `--instance <id>` | `-i` | Instance ID (4 chars) | Auto |
114-| `--hint <text>` | | Guidance for LLM | None |
115-| `--model <name>` | `-m` | Model config name | `qwen3-8b` |
116-| `--archetype <name>` | `-a` | Character archetype | None |
117-| `--ollama-timeout <ms>` | | Ollama timeout | `30000` |
118-| `--server <url>` | `-s` | MCP server URL | `https://game.spacemolt.com/mcp` |
119-| `--context-window <n>` | `-cw` | Max messages in context | `50` |
120-| `--verbose` | `-v` | Verbose logging | `false` |
121-
122-### Archetypes
123-
124-- **diplomat**: Seeks alliances, mediates conflicts, builds trade networks
125-- **opportunist**: Adapts for maximum personal gain, switches loyalties
126-- **agitator**: Thrives on chaos, spreads misinformation, backstabs
127-
128-### Model Configuration
129-
130-Models configured in `player-models.json`:
131-
132-| Config Name | Model | Notes |
133-| ------------ | ------------ | -------------------- |
134-| qwen3-8b | qwen3:8b | Default, recommended |
135-| qwen3-4b | qwen3:4b | Lighter weight |
136-| llama3.1-8b | llama3.1:8b | Good alternative |
137-| mistral-nemo | mistral-nemo | Larger context |
138-
139-**Adding Custom Models:**
140-
141-```json
142-{
143- "your-model": {
144- "displayName": "Your Model",
145- "ollama": {
146- "model": "actual-ollama-name",
147- "options": { "temperature": 0.7 }
148- },
149- "recommendedMessages": 50
150- }
151-}
152-```
153-
154-### Examples
155-
156-```bash
157-# New diplomat character
158-bun run start -- -i xyz9 -a diplomat
159-
160-# Resume with guidance
161-bun run start -- -i xyz9 --hint "Explore new systems"
162-
163-# Different model
164-bun run start -- -i xyz9 -m llama3.1-8b
165-
166-# Custom server (testing)
167-bun run start -- -i test -s http://localhost:8080/mcp
168-```
169-
170-## Development
171-
172-```bash
173-# Install dependencies
174-bun install
175-
176-# Run all checks
177-bun run check
178-
179-# Individual checks
180-bun run check:format # Prettier
181-bun run check:lint # TypeScript
182-bun run check:test # Tests
183-```
184-
185-## Testing
186-
187-```bash
188-# Run all tests
189-bun test
190-
191-# Specific file
192-bun test tests/db.test.ts
193-
194-# Watch mode
195-bun test --watch
196-```
197-
198-## Project Structure
199-
200-```
201-src/
202-├── mcp-client.ts # MCP SDK connection and tool execution
203-├── ollama.ts # Ollama chat API with tools
204-├── game-client.ts # Agent loop orchestration
205-├── db.ts # SQLite persistence
206-├── types.ts # TypeScript types
207-├── archetypes.ts # Character personalities
208-├── model-config.ts # Model config loader
209-├── logging.ts # Structured logging
210-├── cli.ts # CLI parser
211-└── index.ts # Entry point
212-
213-tests/
214-├── db.test.ts
215-├── ollama.test.ts
216-├── cli.test.ts
217-└── model-config.test.ts
218-```
219-
220-## API Reference
221-
222-See [SpaceMolt API Documentation](https://www.spacemolt.com/api.md) for game server API.
packages/client/package.json+2−3
@@ -4,12 +4,11 @@
44 "private": true,
55 "type": "module",
66 "scripts": {
7- "check": "bun run strip-comments && bun run check:format && bun run check:lint && bun run check:test",
7+ "check": "bun run check:format && bun run check:lint && bun run check:test",
88 "check:format": "prettier --write .",
99 "check:lint": "tsc --noEmit",
1010 "check:test": "bun test",
11- "start": "bun src/index.ts",
12- "strip-comments": "bun ../../scripts/strip-comments.ts"
11+ "start": "bun src/index.ts"
1312 },
1413 "dependencies": {
1514 "@modelcontextprotocol/sdk": "^1.25.3",
packages/client/src/game-client.ts+2−9
@@ -83,7 +83,7 @@ export class GameClient {
8383
8484 async stop(): Promise<void> {
8585 this.running = false;
86- // Log before closing DB since getLogContext() queries it
86+
8787 logClientEvent(this.getLogContext(), "Client stopping");
8888 await this.mcp.disconnect();
8989 this.db.close();
@@ -233,7 +233,6 @@ You decide your goals: mining, trading, combat, exploration, faction politics -
233233 this.db.saveMessage(Date.now(), "client", { response: result.content });
234234 this.messages.push({ role: "assistant", content: result.content });
235235 } else {
236- // Empty response with no tool calls - LLM is stuck
237236 logClientEvent(this.getLogContext(), "LLM returned empty response, nudging");
238237 this.messages.push({
239238 role: "user",
@@ -241,7 +240,7 @@ You decide your goals: mining, trading, combat, exploration, faction politics -
241240 "You didn't take any action. Use your available tools to interact with the game. " +
242241 "Try get_status() to see your current state, or get_notifications() to check for messages.",
243242 });
244- // Don't break - continue the loop to give LLM another chance with the nudge
243+
245244 continue;
246245 }
247246 break;
@@ -258,20 +257,17 @@ You decide your goals: mining, trading, combat, exploration, faction politics -
258257 private async executeToolCall(toolCall: ToolCall): Promise<void> {
259258 const { name, arguments: rawArgs } = toolCall.function;
260259
261- // Ollama sometimes returns arguments as a JSON string instead of parsed object
262260 let args: Record<string, unknown>;
263261 if (typeof rawArgs === "string") {
264262 try {
265263 args = JSON.parse(rawArgs);
266264 } catch (error) {
267- // Malformed JSON from LLM - log error and inform LLM via tool result
268265 const errorMsg = `Failed to parse tool arguments: ${error instanceof Error ? error.message : "Invalid JSON"}`;
269266 logClientError(this.getLogContext(), `Tool ${name} argument parse error`, {
270267 rawArgs,
271268 error: errorMsg,
272269 });
273270
274- // Push error as tool result so LLM gets feedback
275271 this.messages.push({
276272 role: "tool",
277273 name,
@@ -292,10 +288,8 @@ You decide your goals: mining, trading, combat, exploration, faction politics -
292288
293289 const result = await this.mcp.callTool(name, args);
294290
295- // Summarize tool result to reduce token count in LLM context
296291 const summarized = summarizeToolResult(name, result.content, result.success);
297292
298- // Log with comparison: show both raw server data and what LLM sees
299293 logToolResult(this.getLogContext(), name, {
300294 ...result,
301295 summarized,
@@ -418,7 +412,6 @@ Respond with ONLY the character prompt, no explanations.`,
418412 ],
419413 });
420414 } else if (data.tool && data.content !== undefined) {
421- // Summarize historical tool results to reduce context size
422415 const summarized = summarizeToolResult(data.tool, data.content, data.success !== false);
423416 this.messages.push({
424417 role: "tool",
packages/client/src/mcp-client.ts+0−3
@@ -63,12 +63,9 @@ export class MCPClient {
6363 private convertToOllamaTool(mcpTool: MCPTool): OllamaTool {
6464 const inputSchema = mcpTool.inputSchema || { type: "object", properties: {}, required: [] };
6565
66- // Get server-provided schema
6766 let properties = (inputSchema.properties as Record<string, unknown>) || {};
6867 let required = (inputSchema.required as string[]) || [];
6968
70- // Apply local schema patches if server schema is empty
71- // (SpaceMolt MCP server doesn't provide parameter schemas)
7269 const patch = TOOL_SCHEMA_PATCHES[mcpTool.name];
7370 if (patch && Object.keys(properties).length === 0) {
7471 properties = patch.properties;
packages/client/src/ollama.ts+1−1
@@ -11,7 +11,7 @@ export interface ChatMessage {
1111 role: "system" | "user" | "assistant" | "tool";
1212 content: string;
1313 tool_calls?: ToolCall[];
14- name?: string; // Tool name for tool result messages
14+ name?: string;
Cut short: this commit's diff is over 1000 lines.
packages/client/src/response-summarizer.ts+5−52
Cut short: this commit's diff is over 1000 lines.
packages/client/src/tool-schemas.ts+0−39
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/game-client.test.ts+86−112
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/response-summarizer.test.ts+2−21
Cut short: this commit's diff is over 1000 lines.
packages/cui/package.json+1−1
Cut short: this commit's diff is over 1000 lines.
packages/cui/src/formatter.ts+2−30
Cut short: this commit's diff is over 1000 lines.
packages/cui/src/index.ts+0−10
Cut short: this commit's diff is over 1000 lines.
packages/cui/src/logger.ts+2−48
Cut short: this commit's diff is over 1000 lines.
packages/cui/src/types.ts+1−5
Cut short: this commit's diff is over 1000 lines.
packages/cui/tests/formatter.test.ts+2−2
Cut short: this commit's diff is over 1000 lines.
packages/cui/tsconfig.json+5−14
Cut short: this commit's diff is over 1000 lines.
packages/tui/DESIGN_REVIEW.md+0−113
Cut short: this commit's diff is over 1000 lines.
packages/tui/README.md+0−44
Cut short: this commit's diff is over 1000 lines.
packages/tui/tests/manual/README.md+0−36
Cut short: this commit's diff is over 1000 lines.
packages/tui/tests/manual/component-previews.tsx+0−10
Cut short: this commit's diff is over 1000 lines.
packages/tui/tests/manual/index.tsx+0−5
Cut short: this commit's diff is over 1000 lines.
packages/tui/tests/manual/layout-preview.tsx+0−16
Cut short: this commit's diff is over 1000 lines.
packages/tui/tests/manual/test-harness.tsx+0−15
Cut short: this commit's diff is over 1000 lines.
scripts/strip-comments.test.ts+0−129
Cut short: this commit's diff is over 1000 lines.
scripts/strip-comments.ts+0−204
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+3−8
Cut short: this commit's diff is over 1000 lines.