xonecas.io
5875
Os

ollama-space-molt-player / commit 13da8ee

feat: add swarm mode and character customization options

- Add swarm.ts for spawning and managing multiple bot instances
- Extend CLI args to support empire, alignment, and personality overrides
- Add validation utilities for character attributes
- Update documentation with new command options
- Extend types to include personality archetype

xonecas2026-02-01 13da8eebe9b490010e208d7fa99617810ddca7fc parent 3bfdb53

8 files changed

AGENTS.md+6−3
@@ -27,6 +27,11 @@ Purpose: help coding agents work safely and consistently in this repo.
2727 - The `--name` argument is required and determines file paths:
2828 - Memory DB (includes credentials): `memory-{name}.sqlite`
2929 - Example: `bun run ollama-play --name alice` uses `memory-alice.sqlite`
30+- Optional character overrides (new registrations only):
31+ - `--empire <empire>` or `-e` - Force empire: solarian, voidborn, crimson, nebula, outerrim
32+ - `--alignment <alignment>` or `-a` - Force alignment: lawful, good, neutral, chaotic, evil
33+ - `--personality <personality>` or `-p` - Force personality: cartographer, merchant, warrior, diplomat, pragmatist
34+- Example: `bun run ollama-play -n test-bot -e crimson -a evil -p warrior`
3035
3136 ### Run in non-interactive mode (for testing/debugging)
3237 - `bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]`
@@ -47,9 +52,7 @@ Purpose: help coding agents work safely and consistently in this repo.
4752 - Credentials are stored in the instance SQLite DB and should not be committed.
4853
4954 **Known test instances:**
50-- `debug-bot` -> `memory-debug-bot.sqlite`
51-- `test-bot-1` -> `memory-test-bot-1.sqlite`
52-- `test-bot-2` -> `memory-test-bot-2.sqlite`
55+- `test-cli-override` -> `memory-test-cli-override.sqlite`
5356
5457 **Troubleshooting:**
5558 - If you see `Invalid username or token`, delete the instance DB (`memory-{name}.sqlite`), then rerun to create a new account.
README.md+14−0
@@ -35,3 +35,17 @@ Now that we have a playable account.
3535 A simple TUI with a status bar at the bottom with character information
3636 A scrolling log of the LLM's actions and results.
3737 Clean, readable and resizeable with simple colors.
38+
39+## Swarm orchestrator
40+
41+Run a swarm of non-interactive bots (default count 5) with a fast model and no thinking:
42+
43+```
44+bun run swarm --count 5 --empire crimson --alignment evil --personality warrior
45+```
46+
47+Notes:
48+
49+- Uses `OLLAMA_THINKING=false` and `OLLAMA_MODEL=ministral-3:8b` for each bot.
50+- Writes orchestration info to `swarm.log` only.
51+- Each bot still writes its own logs: `ui-<name>.log` and `debug-<name>.log`.
package.json+1−0
@@ -5,6 +5,7 @@
55 "type": "module",
66 "scripts": {
77 "ollama-play": "bun src/index.ts",
8+ "swarm": "bun src/swarm.ts",
89 "biome:format": "biome format .",
910 "biome:lint": "biome lint ."
1011 },
src/config.ts+61−0
@@ -1,11 +1,18 @@
11 import { parseArgs } from "node:util";
22
3+import type { EmpireID } from "../client/src/types";
4+import type { AlignmentType, PersonalityType } from "./types";
5+import { isValidAlignment, isValidEmpire, isValidPersonality } from "./utils";
6+
37 const { values } = parseArgs({
48 args: process.argv.slice(2),
59 options: {
610 name: { type: "string", short: "n" },
711 "non-interactive": { type: "boolean" },
812 "max-ticks": { type: "string" },
13+ empire: { type: "string", short: "e" },
14+ alignment: { type: "string", short: "a" },
15+ personality: { type: "string", short: "p" },
916 },
1017 strict: false,
1118 });
@@ -43,14 +50,68 @@ function parseMaxTicks(raw: unknown): number | null {
4350 return Math.floor(value);
4451 }
4552
53+function parseEmpire(raw: unknown): EmpireID | null {
54+ if (raw === undefined) return null;
55+ if (typeof raw !== "string" || raw.trim() === "") {
56+ console.error("Error: --empire requires a value");
57+ process.exit(1);
58+ }
59+ const value = raw.trim().toLowerCase();
60+ if (!isValidEmpire(value)) {
61+ console.error(
62+ "Error: --empire must be one of: solarian, voidborn, crimson, nebula, outerrim",
63+ );
64+ process.exit(1);
65+ }
66+ return value;
67+}
68+
69+function parseAlignment(raw: unknown): AlignmentType | null {
70+ if (raw === undefined) return null;
71+ if (typeof raw !== "string" || raw.trim() === "") {
72+ console.error("Error: --alignment requires a value");
73+ process.exit(1);
74+ }
75+ const value = raw.trim().toLowerCase();
76+ if (!isValidAlignment(value)) {
77+ console.error(
78+ "Error: --alignment must be one of: lawful, good, neutral, chaotic, evil",
79+ );
80+ process.exit(1);
81+ }
82+ return value;
83+}
84+
85+function parsePersonality(raw: unknown): PersonalityType | null {
86+ if (raw === undefined) return null;
87+ if (typeof raw !== "string" || raw.trim() === "") {
88+ console.error("Error: --personality requires a value");
89+ process.exit(1);
90+ }
91+ const value = raw.trim().toLowerCase();
92+ if (!isValidPersonality(value)) {
93+ console.error(
94+ "Error: --personality must be one of: cartographer, merchant, warrior, diplomat, pragmatist",
95+ );
96+ process.exit(1);
97+ }
98+ return value;
99+}
100+
46101 const instanceName = getInstanceName();
47102 const nonInteractive = values["non-interactive"] === true;
48103 const maxTicks = parseMaxTicks(values["max-ticks"]);
104+const empire = parseEmpire(values.empire);
105+const alignment = parseAlignment(values.alignment);
106+const personality = parsePersonality(values.personality);
49107
50108 export const config = {
51109 instanceName,
52110 nonInteractive,
53111 maxTicks,
112+ empire,
113+ alignment,
114+ personality,
54115 ollamaUrl: process.env.OLLAMA_URL ?? "http://localhost:11434",
55116 ollamaModel: process.env.OLLAMA_MODEL ?? "qwen3:8b",
56117 ollamaTemperature: (() => {
src/index.ts+21−4
@@ -32,7 +32,12 @@ import {
3232 formatWelcome,
3333 type OkContext,
3434 } from "./tui/formatters";
35-import type { AlignmentType, Credentials, PersonalityType } from "./types";
35+import type {
36+ AlignmentType,
37+ Credentials,
38+ PersonalityType,
39+ RegistrationOverrides,
40+} from "./types";
3641 import { detectRepetition, isNearbyTarget, sleep } from "./utils";
3742
3843 const memory = new MemoryStore(config.memoryPath);
@@ -57,6 +62,11 @@ const client = new SpaceMoltClient({
5762 });
5863
5964 const gameState = new GameState();
65+const registrationOverrides: RegistrationOverrides = {
66+ empire: config.empire ?? undefined,
67+ alignment: config.alignment ?? undefined,
68+ personality: config.personality ?? undefined,
69+};
6070 let actionLoopRunning = false;
6171 const REPETITION_THRESHOLD = 3;
6272 let maxTicksStart: number | null = null;
@@ -347,6 +357,7 @@ client.on<WelcomePayload>("welcome", async (data) => {
347357 ollama,
348358 client,
349359 gameState.failedRegistrationNames,
360+ registrationOverrides,
350361 );
351362 }
352363 });
@@ -462,6 +473,7 @@ client.on<ErrorPayload>("error", (data) => {
462473 ollama,
463474 client,
464475 gameState.failedRegistrationNames,
476+ registrationOverrides,
465477 ).then((choice) => {
466478 gameState.pendingRegistration = choice;
467479 });
@@ -472,12 +484,17 @@ client.on<ErrorPayload>("error", (data) => {
472484 ),
473485 );
474486 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
487+ const fallbackEmpire = registrationOverrides.empire ?? "solarian";
488+ const fallbackAlignment = registrationOverrides.alignment ?? "neutral";
489+ const fallbackPersonality =
490+ registrationOverrides.personality ?? "pragmatist";
475491 gameState.pendingRegistration = {
476492 username: fallback,
477- empire: "solarian",
478- personality: "pragmatist",
493+ empire: fallbackEmpire,
494+ alignment: fallbackAlignment,
495+ personality: fallbackPersonality,
479496 };
480- client.register(fallback, "solarian");
497+ client.register(fallback, fallbackEmpire);
481498 }
482499 }
483500 });
src/registration.ts+29−16
@@ -5,7 +5,11 @@ import type { OllamaAgent } from "./ollama";
55 import type { OutputInterface } from "./output-interface";
66 import { buildRegistrationPrompt } from "./prompt";
77 import { formatAiThinking, formatSystemMessage } from "./tui/formatters";
8-import type { AlignmentType, RegistrationChoice } from "./types";
8+import type {
9+ AlignmentType,
10+ RegistrationChoice,
11+ RegistrationOverrides,
12+} from "./types";
913 import { isValidAlignment, isValidEmpire, isValidPersonality } from "./utils";
1014
1115 export async function runRegistrationFlow(
@@ -13,6 +17,7 @@ export async function runRegistrationFlow(
1317 ollama: OllamaAgent,
1418 client: SpaceMoltClient,
1519 failedRegistrationNames: string[],
20+ overrides: RegistrationOverrides = {},
1621 ): Promise<RegistrationChoice> {
1722 output.log(
1823 formatSystemMessage(
@@ -43,35 +48,40 @@ export async function runRegistrationFlow(
4348 const personalityReason = result.json.personality_reason
4449 ? String(result.json.personality_reason).trim()
4550 : undefined;
51+ const resolvedEmpire = overrides.empire ?? empire;
52+ const resolvedAlignment = overrides.alignment ?? alignment;
53+ const resolvedPersonality = overrides.personality ?? personality;
4654
4755 if (
4856 !username ||
49- !isValidEmpire(empire) ||
50- !isValidAlignment(alignment) ||
51- !isValidPersonality(personality)
57+ !isValidEmpire(resolvedEmpire) ||
58+ !isValidAlignment(resolvedAlignment) ||
59+ !isValidPersonality(resolvedPersonality)
5260 ) {
5361 throw new Error("Invalid registration response");
5462 }
5563
5664 const choice: RegistrationChoice = {
5765 username,
58- empire,
59- alignment,
60- personality,
66+ empire: resolvedEmpire,
67+ alignment: resolvedAlignment,
68+ personality: resolvedPersonality,
6169 personality_reason: personalityReason,
6270 };
6371
64- const alignmentInfo = ALIGNMENT_DESCRIPTIONS[alignment];
65- const personalityInfo = PERSONALITY_ARCHETYPES[personality];
72+ const alignmentInfo = ALIGNMENT_DESCRIPTIONS[resolvedAlignment];
73+ const personalityInfo = PERSONALITY_ARCHETYPES[resolvedPersonality];
6674 output.log(
67- formatSystemMessage(`Registering new account: ${username} (${empire})`),
75+ formatSystemMessage(
76+ `Registering new account: ${username} (${resolvedEmpire})`,
77+ ),
6878 );
6979 output.log(
7080 formatSystemMessage(
7181 `Chosen alignment: ${alignmentInfo.name}, personality: ${personalityInfo.name}${personalityReason ? ` - ${personalityReason}` : ""}`,
7282 ),
7383 );
74- client.register(username, empire);
84+ client.register(username, resolvedEmpire);
7585 return choice;
7686 } catch (error) {
7787 output.log(
@@ -83,17 +93,20 @@ export async function runRegistrationFlow(
8393 }
8494
8595 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
96+ const fallbackEmpire = overrides.empire ?? "solarian";
97+ const fallbackAlignment = overrides.alignment ?? "neutral";
98+ const fallbackPersonality = overrides.personality ?? "pragmatist";
8699 const fallbackChoice: RegistrationChoice = {
87100 username: fallback,
88- empire: "solarian",
89- alignment: "neutral",
90- personality: "pragmatist",
101+ empire: fallbackEmpire,
102+ alignment: fallbackAlignment,
103+ personality: fallbackPersonality,
91104 };
92105 output.log(
93106 formatSystemMessage(
94- `Falling back to account: ${fallback} (solarian, neutral, pragmatist)`,
107+ `Falling back to account: ${fallback} (${fallbackEmpire}, ${fallbackAlignment}, ${fallbackPersonality})`,
95108 ),
96109 );
97- client.register(fallback, "solarian");
110+ client.register(fallback, fallbackEmpire);
98111 return fallbackChoice;
99112 }
src/swarm.ts+260−0
@@ -0,0 +1,260 @@
1+import { spawn } from "node:child_process";
2+import { appendFileSync } from "node:fs";
3+import { parseArgs } from "node:util";
4+
5+import { isValidAlignment, isValidEmpire, isValidPersonality } from "./utils";
6+
7+const DEFAULT_COUNT = 5;
8+const DEFAULT_PREFIX = "swarm";
9+const DEFAULT_RESTART_DELAY_MS = 10000;
10+const SWARM_LOG_PATH = "swarm.log";
11+
12+const { values } = parseArgs({
13+ args: process.argv.slice(2),
14+ options: {
15+ count: { type: "string", short: "c" },
16+ prefix: { type: "string", short: "p" },
17+ "restart-delay": { type: "string" },
18+ empire: { type: "string" },
19+ alignment: { type: "string" },
20+ personality: { type: "string" },
21+ },
22+ strict: false,
23+});
24+
25+type SwarmConfig = {
26+ count: number;
27+ prefix: string;
28+ restartDelayMs: number;
29+ empire: string | null;
30+ alignment: string | null;
31+ personality: string | null;
32+};
33+
34+function logSwarm(message: string): void {
35+ const line = `[${new Date().toISOString()}] ${message}`;
36+ console.log(line);
37+ try {
38+ appendFileSync(SWARM_LOG_PATH, `${line}\n`, "utf8");
39+ } catch (error) {
40+ console.error(
41+ `Failed to write ${SWARM_LOG_PATH}: ${(error as Error).message}`,
42+ );
43+ }
44+}
45+
46+function parseCount(raw: unknown): number {
47+ if (raw === undefined) return DEFAULT_COUNT;
48+ if (typeof raw !== "string" || raw.trim() === "") {
49+ console.error("Error: --count requires a numeric value");
50+ process.exit(1);
51+ }
52+ const value = Number(raw);
53+ if (!Number.isFinite(value) || value <= 0) {
54+ console.error("Error: --count must be a positive number");
55+ process.exit(1);
56+ }
57+ return Math.floor(value);
58+}
59+
60+function parseRestartDelay(raw: unknown): number {
61+ if (raw === undefined) return DEFAULT_RESTART_DELAY_MS;
62+ if (typeof raw !== "string" || raw.trim() === "") {
63+ console.error("Error: --restart-delay requires a numeric value in ms");
64+ process.exit(1);
65+ }
66+ const value = Number(raw);
67+ if (!Number.isFinite(value) || value <= 0) {
68+ console.error("Error: --restart-delay must be a positive number (ms)");
69+ process.exit(1);
70+ }
71+ return Math.floor(value);
72+}
73+
74+function parsePrefix(raw: unknown): string {
75+ if (raw === undefined) return DEFAULT_PREFIX;
76+ if (typeof raw !== "string" || raw.trim() === "") {
77+ console.error("Error: --prefix requires a value");
78+ process.exit(1);
79+ }
80+ const trimmed = raw.trim();
81+ if (!/^[a-zA-Z0-9_-]+$/.test(trimmed)) {
82+ console.error(
83+ "Error: --prefix must contain only letters, numbers, dashes, and underscores",
84+ );
85+ process.exit(1);
86+ }
87+ return trimmed;
88+}
89+
90+function parseEmpire(raw: unknown): string | null {
91+ if (raw === undefined) return null;
92+ if (typeof raw !== "string" || raw.trim() === "") {
93+ console.error("Error: --empire requires a value");
94+ process.exit(1);
95+ }
96+ const value = raw.trim().toLowerCase();
97+ if (!isValidEmpire(value)) {
98+ console.error(
99+ "Error: --empire must be one of: solarian, voidborn, crimson, nebula, outerrim",
100+ );
101+ process.exit(1);
102+ }
103+ return value;
104+}
105+
106+function parseAlignment(raw: unknown): string | null {
107+ if (raw === undefined) return null;
108+ if (typeof raw !== "string" || raw.trim() === "") {
109+ console.error("Error: --alignment requires a value");
110+ process.exit(1);
111+ }
112+ const value = raw.trim().toLowerCase();
113+ if (!isValidAlignment(value)) {
114+ console.error(
115+ "Error: --alignment must be one of: lawful, good, neutral, chaotic, evil",
116+ );
117+ process.exit(1);
118+ }
119+ return value;
120+}
121+
122+function parsePersonality(raw: unknown): string | null {
123+ if (raw === undefined) return null;
124+ if (typeof raw !== "string" || raw.trim() === "") {
125+ console.error("Error: --personality requires a value");
126+ process.exit(1);
127+ }
128+ const value = raw.trim().toLowerCase();
129+ if (!isValidPersonality(value)) {
130+ console.error(
131+ "Error: --personality must be one of: cartographer, merchant, warrior, diplomat, pragmatist",
132+ );
133+ process.exit(1);
134+ }
135+ return value;
136+}
137+
138+const swarmConfig: SwarmConfig = {
139+ count: parseCount(values.count),
140+ prefix: parsePrefix(values.prefix),
141+ restartDelayMs: parseRestartDelay(values["restart-delay"]),
142+ empire: parseEmpire(values.empire),
143+ alignment: parseAlignment(values.alignment),
144+ personality: parsePersonality(values.personality),
145+};
146+
147+const children = new Map<string, ReturnType<typeof spawn>>();
148+const restartTimers = new Map<string, ReturnType<typeof setTimeout>>();
149+let stopping = false;
150+
151+function buildInstanceName(
152+ index: number,
153+ count: number,
154+ prefix: string,
155+): string {
156+ const digits = Math.max(2, String(count).length);
157+ const padded = String(index).padStart(digits, "0");
158+ return `${prefix}-${padded}`;
159+}
160+
161+function buildArgs(instanceName: string): string[] {
162+ const args = [
163+ "run",
164+ "ollama-play",
165+ "--name",
166+ instanceName,
167+ "--non-interactive",
168+ ];
169+ if (swarmConfig.empire) {
170+ args.push("--empire", swarmConfig.empire);
171+ }
172+ if (swarmConfig.alignment) {
173+ args.push("--alignment", swarmConfig.alignment);
174+ }
175+ if (swarmConfig.personality) {
176+ args.push("--personality", swarmConfig.personality);
177+ }
178+ return args;
179+}
180+
181+function spawnBot(instanceName: string): void {
182+ if (stopping) return;
183+ const args = buildArgs(instanceName);
184+ const child = spawn("bun", args, {
185+ stdio: "ignore",
186+ env: {
187+ ...process.env,
188+ OLLAMA_THINKING: "false",
189+ OLLAMA_MODEL: "ministral-3:8b",
190+ },
191+ });
192+
193+ children.set(instanceName, child);
194+ logSwarm(`spawned ${instanceName} (pid=${child.pid ?? "unknown"})`);
195+
196+ child.on("exit", (code, signal) => {
197+ children.delete(instanceName);
198+ const status = `code=${code ?? "null"} signal=${signal ?? "null"}`;
199+ logSwarm(`exited ${instanceName} (${status})`);
200+ if (stopping) return;
201+ const timer = setTimeout(() => {
202+ restartTimers.delete(instanceName);
203+ logSwarm(`restarting ${instanceName}`);
204+ spawnBot(instanceName);
205+ }, swarmConfig.restartDelayMs);
206+ restartTimers.set(instanceName, timer);
207+ });
208+
209+ child.on("error", (error) => {
210+ logSwarm(`error ${instanceName} (${error.message})`);
211+ });
212+}
213+
214+function shutdown(reason: string): void {
215+ if (stopping) return;
216+ stopping = true;
217+ logSwarm(`shutdown ${reason}`);
218+ for (const timer of restartTimers.values()) {
219+ clearTimeout(timer);
220+ }
221+ restartTimers.clear();
222+ for (const [name, child] of children.entries()) {
223+ try {
224+ child.kill("SIGTERM");
225+ logSwarm(`stopping ${name}`);
226+ } catch (error) {
227+ logSwarm(`failed to stop ${name} (${(error as Error).message})`);
228+ }
229+ }
230+}
231+
232+function startSwarm(): void {
233+ logSwarm(
234+ `start count=${swarmConfig.count} prefix=${swarmConfig.prefix} restartDelayMs=${swarmConfig.restartDelayMs}`,
235+ );
236+ if (swarmConfig.empire) logSwarm(`override empire=${swarmConfig.empire}`);
237+ if (swarmConfig.alignment)
238+ logSwarm(`override alignment=${swarmConfig.alignment}`);
239+ if (swarmConfig.personality)
240+ logSwarm(`override personality=${swarmConfig.personality}`);
241+
242+ for (let i = 1; i <= swarmConfig.count; i += 1) {
243+ const name = buildInstanceName(i, swarmConfig.count, swarmConfig.prefix);
244+ spawnBot(name);
245+ }
246+}
247+
248+process.on("SIGINT", () => shutdown("SIGINT"));
249+process.on("SIGTERM", () => shutdown("SIGTERM"));
250+process.on("uncaughtException", (error) => {
251+ logSwarm(`uncaughtException ${(error as Error).message}`);
252+ shutdown("uncaughtException");
253+});
254+process.on("unhandledRejection", (reason) => {
255+ logSwarm(`unhandledRejection ${String(reason)}`);
256+ shutdown("unhandledRejection");
257+});
258+process.on("exit", () => shutdown("exit"));
259+
260+startSwarm();
src/types.ts+6−0
@@ -31,6 +31,12 @@ export interface RegistrationChoice {
3131 token?: string;
3232 }
3333
34+export interface RegistrationOverrides {
35+ empire?: EmpireID;
36+ alignment?: AlignmentType;
37+ personality?: PersonalityType;
38+}
39+
3440 export interface PersonalityArchetype {
3541 name: string;
3642 emoji: string;