@sharedots/cli 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,415 +1,361 @@
1
- #!/usr/bin/env node
2
- import { spawn, spawnSync } from "node:child_process";
3
- import {
4
- closeSync,
5
- existsSync,
6
- mkdirSync,
7
- openSync,
8
- readFileSync,
9
- realpathSync,
10
- rmSync,
11
- writeFileSync,
12
- } from "node:fs";
13
- import { homedir } from "node:os";
14
- import { dirname, join, resolve } from "node:path";
15
- import { fileURLToPath } from "node:url";
16
- import { Sharedots } from "sharedots";
17
-
18
- const __dirname = dirname(fileURLToPath(import.meta.url));
19
-
20
- interface LocalWorkerConfig {
21
- coordinator: string;
22
- roomId: string;
23
- token: string;
24
- joinedAt: string;
25
- }
26
-
27
- function getHomeDir(): string {
28
- const dir = process.env.SHAREDOTS_HOME
29
- ? resolve(process.env.SHAREDOTS_HOME)
30
- : join(homedir(), ".sharedots");
31
- mkdirSync(dir, { recursive: true });
32
- return dir;
33
- }
34
-
35
- function configPath(): string {
36
- return join(getHomeDir(), "worker-config.json");
37
- }
38
-
39
- function pidPath(): string {
40
- return join(getHomeDir(), "worker.pid");
41
- }
42
-
43
- function logPath(): string {
44
- return join(getHomeDir(), "worker.log");
45
- }
46
-
47
- function readConfig(): LocalWorkerConfig | null {
48
- const p = configPath();
49
- if (!existsSync(p)) return null;
50
- return JSON.parse(readFileSync(p, "utf8")) as LocalWorkerConfig;
51
- }
52
-
53
- function writeConfig(cfg: LocalWorkerConfig): void {
54
- writeFileSync(configPath(), `${JSON.stringify(cfg, null, 2)}\n`, "utf8");
55
- }
56
-
57
- function resolveDaemonBinary(): string {
58
- if (process.env.SHAREDOTS_DAEMON_BIN && existsSync(process.env.SHAREDOTS_DAEMON_BIN)) {
59
- return process.env.SHAREDOTS_DAEMON_BIN;
60
- }
61
- const exe = process.platform === "win32" ? "sharedots-daemon.exe" : "sharedots-daemon";
62
- const repoRoot = resolve(__dirname, "../../..");
63
- const candidates = [
64
- join(repoRoot, "target", "release", exe),
65
- join(repoRoot, "target", "debug", exe),
66
- join(process.cwd(), "target", "release", exe),
67
- join(process.cwd(), "target", "debug", exe),
68
- ];
69
- for (const c of candidates) {
70
- if (existsSync(c)) return c;
71
- }
72
- return exe; // fallback to PATH
73
- }
74
-
75
- function isProcessRunning(pid: number): boolean {
76
- try {
77
- process.kill(pid, 0);
78
- return true;
79
- } catch {
80
- return false;
81
- }
82
- }
83
-
84
- export function parseFlags(argv: string[]): { positional: string[]; flags: Record<string, string | boolean> } {
85
- const positional: string[] = [];
86
- const flags: Record<string, string | boolean> = {};
87
- for (let i = 0; i < argv.length; i++) {
88
- const arg = argv[i]!;
89
- if (arg.startsWith("--")) {
90
- const key = arg.slice(2);
91
- const eq = key.indexOf("=");
92
- if (eq !== -1) {
93
- flags[key.slice(0, eq)] = key.slice(eq + 1);
94
- } else {
95
- const next = argv[i + 1];
96
- if (next && !next.startsWith("--")) {
97
- flags[key] = next;
98
- i++;
99
- } else {
100
- flags[key] = true;
101
- }
102
- }
103
- } else {
104
- positional.push(arg);
105
- }
106
- }
107
- return { positional, flags };
108
- }
109
-
110
- function printHelp(): void {
111
- console.log(`Sharedots CLI v0.1.0 — Universal Distributed Compute Network
112
-
113
- Usage:
114
- sharedots tui [--coordinator URL]
115
- sharedots room create [--name NAME] [--coordinator URL]
116
- sharedots worker join <ROOM_ID> --token <SECRET> [--coordinator URL]
117
- sharedots worker start [--cpu-limit N] [--memory-limit MB] [--gpu] [--foreground]
118
- sharedots worker status
119
- sharedots worker stop
120
- sharedots worker leave
121
- sharedots worker logs [--lines N]
122
- sharedots job submit <job.json> [--coordinator URL] [--room ROOM_ID] [--token SECRET]
123
- sharedots bench [--size N] [--partitions P] [--coordinator URL] [--room ROOM_ID] [--token SECRET]
124
- `);
125
- }
126
-
127
- async function main(): Promise<void> {
128
- const { positional, flags } = parseFlags(process.argv.slice(2));
129
- const [group, sub, ...rest] = positional;
130
-
131
- if (!group || flags.help || group === "help") {
132
- printHelp();
133
- return;
134
- }
135
-
136
- const defaultCoord =
137
- (typeof flags.coordinator === "string" ? flags.coordinator : undefined) ??
138
- process.env.SHAREDOTS_COORDINATOR ??
139
- "http://localhost:4000";
140
-
141
- if (group === "tui") {
142
- try {
143
- const tui = await import("@sharedots/tui");
144
- if (typeof tui.runTui === "function") {
145
- await tui.runTui({
146
- initialCoordinator: defaultCoord,
147
- });
148
- return;
149
- }
150
- } catch {
151
- // Fallback to relative path lookup
152
- const repoRoot = resolve(__dirname, "../../..");
153
- const candidates = [
154
- join(repoRoot, "apps", "tui", "dist", "index.js"),
155
- join(process.cwd(), "apps", "tui", "dist", "index.js"),
156
- ];
157
- for (const cand of candidates) {
158
- if (existsSync(cand)) {
159
- const mod = await import(`file://${cand.replace(/\\/g, "/")}`);
160
- if (typeof mod.runTui === "function") {
161
- await mod.runTui({ initialCoordinator: defaultCoord });
162
- return;
163
- }
164
- }
165
- }
166
- console.error("Failed to load @sharedots/tui. Please build apps/tui first.");
167
- process.exit(1);
168
- }
169
- return;
170
- }
171
-
172
- if (group === "room" && sub === "create") {
173
- const client = new Sharedots({ coordinator: defaultCoord });
174
- const name = typeof flags.name === "string" ? flags.name : undefined;
175
- const room = await client.createRoom(name);
176
- if (flags.json) {
177
- console.log(JSON.stringify(room, null, 2));
178
- } else {
179
- console.log(`Room created successfully`);
180
- console.log(` ROOM_ID: ${room.roomId}`);
181
- console.log(` ROOM_SECRET: ${room.secret}`);
182
- console.log(` COORDINATOR: ${defaultCoord}`);
183
- console.log(`\nJoin a worker with:`);
184
- console.log(` sharedots worker join ${room.roomId} --coordinator ${defaultCoord} --token ${room.secret}`);
185
- }
186
- return;
187
- }
188
-
189
- if (group === "worker") {
190
- if (sub === "join") {
191
- const roomId = rest[0];
192
- const token =
193
- (typeof flags.token === "string" ? flags.token : undefined) ?? process.env.SHAREDOTS_TOKEN;
194
- if (!roomId || !token) {
195
- console.error("Usage: sharedots worker join <ROOM_ID> --token <SECRET> [--coordinator URL]");
196
- process.exit(1);
197
- }
198
- writeConfig({
199
- coordinator: defaultCoord,
200
- roomId,
201
- token,
202
- joinedAt: new Date().toISOString(),
203
- });
204
- console.log(`Saved worker configuration for room ${roomId} (${defaultCoord})`);
205
- console.log(`Start the background daemon with: sharedots worker start`);
206
- return;
207
- }
208
-
209
- if (sub === "start") {
210
- const cfg = readConfig();
211
- const roomId = (typeof flags.room === "string" ? flags.room : undefined) ?? cfg?.roomId;
212
- const token = (typeof flags.token === "string" ? flags.token : undefined) ?? cfg?.token;
213
- const coordinator =
214
- (typeof flags.coordinator === "string" ? flags.coordinator : undefined) ??
215
- cfg?.coordinator ??
216
- defaultCoord;
217
-
218
- if (!roomId || !token) {
219
- console.error("Worker is not joined to a room. Run `sharedots worker join <ROOM_ID> --token <SECRET>` first.");
220
- process.exit(1);
221
- }
222
-
223
- const bin = resolveDaemonBinary();
224
- const home = getHomeDir();
225
- const args = [
226
- "--coordinator",
227
- coordinator,
228
- "--room-id",
229
- roomId,
230
- "--token",
231
- token,
232
- "--state-dir",
233
- join(home, "state"),
234
- "--work-dir",
235
- join(home, "work"),
236
- ];
237
- if (typeof flags["cpu-limit"] === "string") {
238
- args.push("--cpu-limit", flags["cpu-limit"]);
239
- }
240
- if (typeof flags["memory-limit"] === "string") {
241
- args.push("--memory-limit", flags["memory-limit"]);
242
- }
243
- if (flags.gpu === true) {
244
- args.push("--gpu");
245
- }
246
-
247
- if (flags.foreground === true) {
248
- const child = spawn(bin, args, { stdio: "inherit" });
249
- child.on("exit", (code) => process.exit(code ?? 0));
250
- return;
251
- }
252
-
253
- const logFd = openSync(logPath(), "a");
254
- const child = spawn(bin, args, {
255
- detached: true,
256
- stdio: ["ignore", logFd, logFd],
257
- });
258
- child.unref();
259
- closeSync(logFd);
260
-
261
- if (child.pid) {
262
- writeFileSync(pidPath(), String(child.pid), "utf8");
263
- console.log(`Started sharedots-daemon (PID ${child.pid}) for room ${roomId}`);
264
- console.log(`Logs: ${logPath()}`);
265
- } else {
266
- console.error(`Failed to start daemon binary: ${bin}`);
267
- process.exit(1);
268
- }
269
- return;
270
- }
271
-
272
- if (sub === "status") {
273
- const cfg = readConfig();
274
- const pidFile = pidPath();
275
- const pid = existsSync(pidFile) ? Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10) : null;
276
- const running = pid !== null && Number.isFinite(pid) && isProcessRunning(pid);
277
- const widFile = join(getHomeDir(), "state", "worker_id");
278
- const workerId = existsSync(widFile) ? readFileSync(widFile, "utf8").trim() : null;
279
-
280
- console.log(`Worker Status: ${running ? "running" : "stopped"}`);
281
- if (pid) console.log(` PID: ${pid}`);
282
- if (workerId) console.log(` Worker ID: ${workerId}`);
283
- if (cfg) {
284
- console.log(` Room ID: ${cfg.roomId}`);
285
- console.log(` Coordinator: ${cfg.coordinator}`);
286
- }
287
- return;
288
- }
289
-
290
- if (sub === "stop") {
291
- const pidFile = pidPath();
292
- if (!existsSync(pidFile)) {
293
- console.log("Worker daemon is not running.");
294
- return;
295
- }
296
- const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);
297
- if (Number.isFinite(pid) && isProcessRunning(pid)) {
298
- try {
299
- process.kill(pid, "SIGTERM");
300
- } catch {
301
- // ignore
302
- }
303
- console.log(`Stopped worker daemon (PID ${pid})`);
304
- } else {
305
- console.log("Worker daemon was already stopped.");
306
- }
307
- rmSync(pidFile, { force: true });
308
- return;
309
- }
310
-
311
- if (sub === "leave") {
312
- const pidFile = pidPath();
313
- if (existsSync(pidFile)) {
314
- const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);
315
- if (Number.isFinite(pid) && isProcessRunning(pid)) {
316
- try {
317
- process.kill(pid, "SIGTERM");
318
- } catch {
319
- // ignore
320
- }
321
- }
322
- rmSync(pidFile, { force: true });
323
- }
324
- rmSync(configPath(), { force: true });
325
- console.log("Worker left room and cleared local room configuration.");
326
- return;
327
- }
328
-
329
- if (sub === "logs") {
330
- const p = logPath();
331
- if (!existsSync(p)) {
332
- console.log("No worker logs found yet.");
333
- return;
334
- }
335
- const lines = readFileSync(p, "utf8").split(/\r?\n/);
336
- const count = typeof flags.lines === "string" ? Number.parseInt(flags.lines, 10) : 50;
337
- console.log(lines.slice(-count).join("\n"));
338
- return;
339
- }
340
- }
341
-
342
- if (group === "job" && sub === "submit") {
343
- const jobFile = rest[0];
344
- if (!jobFile || !existsSync(resolve(jobFile))) {
345
- console.error("Usage: sharedots job submit <job.json> [--coordinator URL] [--room ROOM_ID] [--token SECRET]");
346
- process.exit(1);
347
- }
348
- const cfg = readConfig();
349
- const coordinator =
350
- (typeof flags.coordinator === "string" ? flags.coordinator : undefined) ??
351
- cfg?.coordinator ??
352
- defaultCoord;
353
- const roomId =
354
- (typeof flags.room === "string" ? flags.room : undefined) ??
355
- process.env.SHAREDOTS_ROOM_ID ??
356
- cfg?.roomId;
357
- const token =
358
- (typeof flags.token === "string" ? flags.token : undefined) ??
359
- process.env.SHAREDOTS_TOKEN ??
360
- cfg?.token;
361
-
362
- if (!roomId || !token) {
363
- console.error("Missing --room and --token (or join a room first).");
364
- process.exit(1);
365
- }
366
-
367
- const spec = JSON.parse(readFileSync(resolve(jobFile), "utf8"));
368
- const client = new Sharedots({ coordinator, token });
369
- const room = await client.connect(roomId);
370
- const job = await room.submit(spec);
371
- console.log(`Submitted job ${job.jobId} to room ${roomId}`);
372
- job.on("progress", (p) => {
373
- console.log(` progress: ${p.percent}% (${p.completedTasks ?? 0}/${p.totalTasks ?? 0})`);
374
- });
375
- const result = await job.result();
376
- console.log(JSON.stringify(result, null, 2));
377
- return;
378
- }
379
-
380
- if (group === "bench") {
381
- const repoRoot = resolve(__dirname, "../../..");
382
- const benchScript = join(repoRoot, "scripts", "bench", "run-matrix-bench.mjs");
383
- if (!existsSync(benchScript)) {
384
- console.error(`Benchmark script not found at ${benchScript}`);
385
- process.exit(1);
386
- }
387
- const res = spawnSync(process.execPath, [benchScript, ...process.argv.slice(3)], {
388
- stdio: "inherit",
389
- });
390
- process.exit(res.status ?? 0);
391
- }
392
-
393
- console.error(`Unknown command: ${positional.join(" ")}`);
394
- printHelp();
395
- process.exit(1);
396
- }
397
-
398
- const checkIsMain = () => {
399
- if (!process.argv[1]) return false;
400
- const target = resolve(fileURLToPath(import.meta.url)).toLowerCase();
401
- if (resolve(process.argv[1]).toLowerCase() === target) return true;
402
- try {
403
- if (realpathSync(process.argv[1]).toLowerCase() === target) return true;
404
- } catch {}
405
- return false;
406
- };
407
-
408
- const isMain = checkIsMain();
409
-
410
- if (isMain) {
411
- main().catch((err) => {
412
- console.error(err instanceof Error ? err.message : String(err));
413
- process.exit(1);
414
- });
415
- }
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { decodeInviteCode, encodeInviteCode } from "@sharedots/protocol";
7
+ import { Sharedots } from "sharedots";
8
+ import {
9
+ configPath,
10
+ getHomeDir,
11
+ isProcessRunning,
12
+ logPath,
13
+ pidPath,
14
+ readConfig,
15
+ startDaemonProcess,
16
+ stopDaemonProcess,
17
+ writeConfig,
18
+ } from "./daemon-runner.js";
19
+ import { runUpWizard } from "./up-wizard.js";
20
+
21
+ const __dirname = dirname(fileURLToPath(import.meta.url));
22
+
23
+ export { parseFlags } from "./parser.js";
24
+ import { parseFlags } from "./parser.js";
25
+
26
+ function printHelp(): void {
27
+ console.log(`Sharedots CLI v0.1.0 — Universal Distributed Compute Network
28
+
29
+ Usage:
30
+ sharedots up [--join CODE] [--cluster] [--contributor] [--yes]
31
+ sharedots join <INVITE_CODE_OR_URL> [--foreground]
32
+ sharedots tui [--coordinator URL]
33
+ sharedots room create [--name NAME] [--coordinator URL]
34
+ sharedots worker join <ROOM_ID> --token <SECRET> [--coordinator URL]
35
+ sharedots worker start [--cpu-limit N] [--memory-limit MB] [--gpu] [--foreground]
36
+ sharedots worker status
37
+ sharedots worker stop
38
+ sharedots worker leave
39
+ sharedots worker logs [--lines N]
40
+ sharedots job submit <job.json> [--coordinator URL] [--room ROOM_ID] [--token SECRET]
41
+ sharedots bench [--size N] [--partitions P] [--coordinator URL] [--room ROOM_ID] [--token SECRET]
42
+ `);
43
+ }
44
+
45
+ async function main(): Promise<void> {
46
+ const { positional, flags } = parseFlags(process.argv.slice(2));
47
+ const [group, sub, ...rest] = positional;
48
+
49
+ if (!group || flags.help || group === "help") {
50
+ printHelp();
51
+ return;
52
+ }
53
+
54
+ const defaultCoord =
55
+ (typeof flags.coordinator === "string" ? flags.coordinator : undefined) ??
56
+ process.env.SHAREDOTS_COORDINATOR ??
57
+ "http://localhost:4000";
58
+
59
+ if (group === "up") {
60
+ await runUpWizard({
61
+ cluster: Boolean(flags.cluster),
62
+ contributor: Boolean(flags.contributor),
63
+ joinCode: typeof flags.join === "string" ? flags.join : sub?.startsWith("sd_join_") ? sub : undefined,
64
+ coordinator: typeof flags.coordinator === "string" ? flags.coordinator : undefined,
65
+ yes: Boolean(flags.yes || flags.y),
66
+ foreground: Boolean(flags.foreground),
67
+ });
68
+ return;
69
+ }
70
+
71
+ if (group === "join") {
72
+ const rawInput = sub ?? rest[0] ?? (typeof flags.code === "string" ? flags.code : undefined);
73
+ if (!rawInput) {
74
+ console.error("Usage: sharedots join <INVITE_CODE_OR_URL> [--foreground]");
75
+ process.exit(1);
76
+ }
77
+ const decoded = decodeInviteCode(rawInput);
78
+ if (!decoded) {
79
+ console.error("✖ Invalid invite code format. Expected 'sd_join_...' or URL containing it.");
80
+ process.exit(1);
81
+ }
82
+
83
+ console.log(`Verifying connection to coordinator at ${decoded.coordinatorUrl}...`);
84
+ try {
85
+ const res = await fetch(`${decoded.coordinatorUrl}/api/overview`, { signal: AbortSignal.timeout(3000) });
86
+ if (!res.ok && res.status !== 401 && res.status !== 403) {
87
+ console.warn(`Warning: Coordinator returned status ${res.status}`);
88
+ }
89
+ } catch (err) {
90
+ console.warn(`Notice: Could not ping ${decoded.coordinatorUrl} (${err instanceof Error ? err.message : String(err)}). Continuing with configuration.`);
91
+ }
92
+
93
+ writeConfig({
94
+ coordinator: decoded.coordinatorUrl,
95
+ roomId: decoded.roomId,
96
+ token: decoded.token,
97
+ joinedAt: new Date().toISOString(),
98
+ });
99
+ console.log(`Saved worker configuration for room ${decoded.roomId} (${decoded.coordinatorUrl})`);
100
+
101
+ const started = startDaemonProcess({
102
+ coordinator: decoded.coordinatorUrl,
103
+ roomId: decoded.roomId,
104
+ token: decoded.token,
105
+ cpuLimit: typeof flags["cpu-limit"] === "string" ? flags["cpu-limit"] : undefined,
106
+ memoryLimit: typeof flags["memory-limit"] === "string" ? flags["memory-limit"] : undefined,
107
+ gpu: flags.gpu === true,
108
+ foreground: flags.foreground === true,
109
+ });
110
+
111
+ if (started.pid) {
112
+ console.log(`Started sharedots-daemon (PID ${started.pid}) for room ${decoded.roomId}`);
113
+ console.log(`Logs: ${logPath()}`);
114
+ console.log(`Run 'sharedots tui' or 'sharedots worker status' to monitor.`);
115
+ }
116
+ return;
117
+ }
118
+
119
+ if (group === "tui") {
120
+ try {
121
+ const tui = await import("@sharedots/tui");
122
+ if (typeof tui.runTui === "function") {
123
+ await tui.runTui({
124
+ initialCoordinator: defaultCoord,
125
+ });
126
+ return;
127
+ }
128
+ } catch {
129
+ // Fallback to relative path lookup
130
+ const repoRoot = resolve(__dirname, "../../..");
131
+ const candidates = [
132
+ join(repoRoot, "apps", "tui", "dist", "index.js"),
133
+ join(process.cwd(), "apps", "tui", "dist", "index.js"),
134
+ ];
135
+ for (const cand of candidates) {
136
+ if (existsSync(cand)) {
137
+ const mod = await import(`file://${cand.replace(/\\/g, "/")}`);
138
+ if (typeof mod.runTui === "function") {
139
+ await mod.runTui({ initialCoordinator: defaultCoord });
140
+ return;
141
+ }
142
+ }
143
+ }
144
+ console.error("Failed to load @sharedots/tui. Please build apps/tui first.");
145
+ process.exit(1);
146
+ }
147
+ return;
148
+ }
149
+
150
+ if (group === "room" && sub === "create") {
151
+ const client = new Sharedots({ coordinator: defaultCoord });
152
+ const name = typeof flags.name === "string" ? flags.name : undefined;
153
+ const room = await client.createRoom(name);
154
+ const inviteCode = encodeInviteCode(defaultCoord, room.roomId, room.secret);
155
+
156
+ if (flags.json) {
157
+ console.log(JSON.stringify({ ...room, inviteCode }, null, 2));
158
+ } else {
159
+ console.log(`Room created successfully`);
160
+ console.log(` ROOM_ID: ${room.roomId}`);
161
+ console.log(` ROOM_SECRET: ${room.secret}`);
162
+ console.log(` COORDINATOR: ${defaultCoord}`);
163
+ console.log(` INVITE_CODE: ${inviteCode}`);
164
+ console.log(`\nJoin a worker with 1-command:`);
165
+ console.log(` sharedots join ${inviteCode}`);
166
+ console.log(`Or classic style:`);
167
+ console.log(` sharedots worker join ${room.roomId} --coordinator ${defaultCoord} --token ${room.secret}`);
168
+ }
169
+ return;
170
+ }
171
+
172
+ if (group === "worker") {
173
+ if (sub === "join") {
174
+ const firstArg = rest[0];
175
+ // If first argument is an invite code, decode it directly
176
+ if (firstArg && (firstArg.startsWith("sd_join_") || firstArg.includes("sd_join_"))) {
177
+ const decoded = decodeInviteCode(firstArg);
178
+ if (decoded) {
179
+ writeConfig({
180
+ coordinator: decoded.coordinatorUrl,
181
+ roomId: decoded.roomId,
182
+ token: decoded.token,
183
+ joinedAt: new Date().toISOString(),
184
+ });
185
+ console.log(`Saved worker configuration for room ${decoded.roomId} (${decoded.coordinatorUrl})`);
186
+ console.log(`Start the background daemon with: sharedots worker start`);
187
+ return;
188
+ }
189
+ }
190
+
191
+ const roomId = firstArg;
192
+ const token =
193
+ (typeof flags.token === "string" ? flags.token : undefined) ?? process.env.SHAREDOTS_TOKEN;
194
+ if (!roomId || !token) {
195
+ console.error("Usage: sharedots worker join <ROOM_ID> --token <SECRET> [--coordinator URL] OR sharedots join <CODE>");
196
+ process.exit(1);
197
+ }
198
+ writeConfig({
199
+ coordinator: defaultCoord,
200
+ roomId,
201
+ token,
202
+ joinedAt: new Date().toISOString(),
203
+ });
204
+ console.log(`Saved worker configuration for room ${roomId} (${defaultCoord})`);
205
+ console.log(`Start the background daemon with: sharedots worker start`);
206
+ return;
207
+ }
208
+
209
+ if (sub === "start") {
210
+ const cfg = readConfig();
211
+ const roomId = (typeof flags.room === "string" ? flags.room : undefined) ?? cfg?.roomId;
212
+ const token = (typeof flags.token === "string" ? flags.token : undefined) ?? cfg?.token;
213
+ const coordinator =
214
+ (typeof flags.coordinator === "string" ? flags.coordinator : undefined) ??
215
+ cfg?.coordinator ??
216
+ defaultCoord;
217
+
218
+ if (!roomId || !token) {
219
+ console.error("Worker is not joined to a room. Run `sharedots join <INVITE_CODE>` or `sharedots worker join <ROOM_ID> --token <SECRET>` first.");
220
+ process.exit(1);
221
+ }
222
+
223
+ const started = startDaemonProcess({
224
+ coordinator,
225
+ roomId,
226
+ token,
227
+ cpuLimit: typeof flags["cpu-limit"] === "string" ? flags["cpu-limit"] : undefined,
228
+ memoryLimit: typeof flags["memory-limit"] === "string" ? flags["memory-limit"] : undefined,
229
+ gpu: flags.gpu === true,
230
+ foreground: flags.foreground === true,
231
+ });
232
+
233
+ if (started.pid) {
234
+ console.log(`Started sharedots-daemon (PID ${started.pid}) for room ${roomId}`);
235
+ console.log(`Logs: ${logPath()}`);
236
+ }
237
+ return;
238
+ }
239
+
240
+ if (sub === "status") {
241
+ const cfg = readConfig();
242
+ const pidFile = pidPath();
243
+ const pid = existsSync(pidFile) ? Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10) : null;
244
+ const running = pid !== null && Number.isFinite(pid) && isProcessRunning(pid);
245
+ const widFile = join(getHomeDir(), "state", "worker_id");
246
+ const workerId = existsSync(widFile) ? readFileSync(widFile, "utf8").trim() : null;
247
+
248
+ console.log(`Worker Status: ${running ? "running" : "stopped"}`);
249
+ if (pid) console.log(` PID: ${pid}`);
250
+ if (workerId) console.log(` Worker ID: ${workerId}`);
251
+ if (cfg) {
252
+ console.log(` Room ID: ${cfg.roomId}`);
253
+ console.log(` Coordinator: ${cfg.coordinator}`);
254
+ }
255
+ return;
256
+ }
257
+
258
+ if (sub === "stop") {
259
+ const res = stopDaemonProcess();
260
+ if (res.stopped) {
261
+ console.log(`Stopped worker daemon (PID ${res.pid})`);
262
+ } else {
263
+ console.log("Worker daemon was already stopped.");
264
+ }
265
+ return;
266
+ }
267
+
268
+ if (sub === "leave") {
269
+ stopDaemonProcess();
270
+ rmSync(configPath(), { force: true });
271
+ console.log("Worker left room and cleared local room configuration.");
272
+ return;
273
+ }
274
+
275
+ if (sub === "logs") {
276
+ const p = logPath();
277
+ if (!existsSync(p)) {
278
+ console.log("No worker logs found yet.");
279
+ return;
280
+ }
281
+ const lines = readFileSync(p, "utf8").split(/\r?\n/);
282
+ const count = typeof flags.lines === "string" ? Number.parseInt(flags.lines, 10) : 50;
283
+ console.log(lines.slice(-count).join("\n"));
284
+ return;
285
+ }
286
+ }
287
+
288
+ if (group === "job" && sub === "submit") {
289
+ const jobFile = rest[0];
290
+ if (!jobFile || !existsSync(resolve(jobFile))) {
291
+ console.error("Usage: sharedots job submit <job.json> [--coordinator URL] [--room ROOM_ID] [--token SECRET]");
292
+ process.exit(1);
293
+ }
294
+ const cfg = readConfig();
295
+ const coordinator =
296
+ (typeof flags.coordinator === "string" ? flags.coordinator : undefined) ??
297
+ cfg?.coordinator ??
298
+ defaultCoord;
299
+ const roomId =
300
+ (typeof flags.room === "string" ? flags.room : undefined) ??
301
+ process.env.SHAREDOTS_ROOM_ID ??
302
+ cfg?.roomId;
303
+ const token =
304
+ (typeof flags.token === "string" ? flags.token : undefined) ??
305
+ process.env.SHAREDOTS_TOKEN ??
306
+ cfg?.token;
307
+
308
+ if (!roomId || !token) {
309
+ console.error("Missing --room and --token (or join a room first).");
310
+ process.exit(1);
311
+ }
312
+
313
+ const spec = JSON.parse(readFileSync(resolve(jobFile), "utf8"));
314
+ const client = new Sharedots({ coordinator, token });
315
+ const room = await client.connect(roomId);
316
+ const job = await room.submit(spec);
317
+ console.log(`Submitted job ${job.jobId} to room ${roomId}`);
318
+ job.on("progress", (p) => {
319
+ console.log(` progress: ${p.percent}% (${p.completedTasks ?? 0}/${p.totalTasks ?? 0})`);
320
+ });
321
+ const result = await job.result();
322
+ console.log(JSON.stringify(result, null, 2));
323
+ return;
324
+ }
325
+
326
+ if (group === "bench") {
327
+ const repoRoot = resolve(__dirname, "../../..");
328
+ const benchScript = join(repoRoot, "scripts", "bench", "run-matrix-bench.mjs");
329
+ if (!existsSync(benchScript)) {
330
+ console.error(`Benchmark script not found at ${benchScript}`);
331
+ process.exit(1);
332
+ }
333
+ const res = spawnSync(process.execPath, [benchScript, ...process.argv.slice(3)], {
334
+ stdio: "inherit",
335
+ });
336
+ process.exit(res.status ?? 0);
337
+ }
338
+
339
+ console.error(`Unknown command: ${positional.join(" ")}`);
340
+ printHelp();
341
+ process.exit(1);
342
+ }
343
+
344
+ const checkIsMain = () => {
345
+ if (!process.argv[1]) return false;
346
+ const target = resolve(fileURLToPath(import.meta.url)).toLowerCase();
347
+ if (resolve(process.argv[1]).toLowerCase() === target) return true;
348
+ try {
349
+ if (realpathSync(process.argv[1]).toLowerCase() === target) return true;
350
+ } catch {}
351
+ return false;
352
+ };
353
+
354
+ const isMain = checkIsMain();
355
+
356
+ if (isMain) {
357
+ main().catch((err) => {
358
+ console.error(err instanceof Error ? err.message : String(err));
359
+ process.exit(1);
360
+ });
361
+ }