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