@mrciphersmith/roomyx 0.4.0 → 0.6.0

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/cli.ts CHANGED
@@ -5,36 +5,26 @@ import { serve } from "./server/serve";
5
5
  import { init } from "./installer/init";
6
6
  import { registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
7
7
  import { syncSkill } from "./installer/skill-sync";
8
+ import { appendMessage, createRoomLog, LEGAL_KINDS, parseRoster } from "./log/write";
9
+ import { MESSAGE_KINDS } from "./log/schema";
10
+ import type { MessageEnvelope } from "./log/types";
8
11
  import { NAMED_TARGETS, resolveTargets } from "./installer/skill-targets";
9
12
  import { serveManagement } from "./mcp-management/server";
13
+ import { ArgError, parseArgs, renderFlags } from "./cli/args";
14
+ import type { FlagSpecs, ParsedArgs } from "./cli/args";
15
+ import { CLIENT_FLAGS } from "./cli/specs";
10
16
 
11
17
  /**
12
- * `roomyx init` / `roomyx serve` / `roomyx rooms list` / `roomyx mcp` /
13
- * `roomyx skills sync`.
14
- * The TUI is primarily `roomyx-client` (its own binary over src/client/index.ts)
15
- * so the orchestrator and the TUI stay independent processes (decisions.md
16
- * D-06). `roomyx client` is a thin alias that starts that same TUI in this
17
- * process — a separate invocation from `serve`/`mcp`, not a shared lifetime.
18
+ * The TUI is primarily `roomyx-client` (its own binary over
19
+ * src/client/index.ts) so the orchestrator and the TUI stay independent
20
+ * processes (decisions.md D-06). `roomyx client` is a thin alias that starts
21
+ * that same TUI in this process — a separate invocation from `serve`/`mcp`,
22
+ * not a shared lifetime.
23
+ *
24
+ * Every command declares its flags rather than scanning argv by hand. See
25
+ * `./cli/args` for what that fixes and why it was one defect rather than six.
18
26
  */
19
27
 
20
- function parseFlags(args: string[]): Record<string, string | boolean> {
21
- const flags: Record<string, string | boolean> = {};
22
- for (let i = 0; i < args.length; i++) {
23
- const arg = args[i];
24
- if (arg?.startsWith("--")) {
25
- const key = arg.slice(2);
26
- const next = args[i + 1];
27
- if (next !== undefined && !next.startsWith("--")) {
28
- flags[key] = next;
29
- i++;
30
- } else {
31
- flags[key] = true;
32
- }
33
- }
34
- }
35
- return flags;
36
- }
37
-
38
28
  function defaultRegistryPath(): string {
39
29
  return join(process.cwd(), ".roomyx", "rooms", "registry.json");
40
30
  }
@@ -47,127 +37,306 @@ function bundledSkillPath(): string {
47
37
  return join(import.meta.dir, "bundled-skills", "startup-room", "SKILL.md");
48
38
  }
49
39
 
50
- const USAGE =
51
- "Usage: roomyx <init|serve <logPath>|client|mcp|rooms list|skills sync --target <claude|codex|keryx|all|path>>";
52
-
53
- async function runInit(): Promise<void> {
54
- const result = init({ cwd: process.cwd(), bundledSkillPath: bundledSkillPath() });
55
- console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
56
- }
40
+ const REGISTRY_FLAG = { type: "string", describe: "Registry file (default .roomyx/rooms/registry.json)" } as const;
57
41
 
58
- async function runServe(logPath: string | undefined, rest: string[]): Promise<void> {
59
- if (!logPath) {
60
- console.error("Missing <logPath>. Usage: roomyx serve <logPath> [--port N]");
61
- process.exit(1);
62
- }
63
- const flags = parseFlags(rest);
64
- // Absolute, because the registry outlives this process's working directory:
65
- // `roomyx-client` resolves rooms from wherever the person happened to run it,
66
- // and a relative logPath means nothing there. The specification's registry
67
- // example has always shown an absolute path; only the code disagreed.
68
- const absoluteLogPath = resolve(logPath);
69
- const handle = await serve(absoluteLogPath, {
70
- port: flags.port !== undefined ? Number(flags.port) : undefined,
71
- host: typeof flags.host === "string" ? flags.host : undefined,
72
- acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
73
- });
74
-
75
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
76
- const entry = registerRoom(registryPath, {
77
- port: handle.port,
78
- logPath: absoluteLogPath,
79
- pid: process.pid,
80
- });
81
-
82
- console.log(`roomyx serving ${absoluteLogPath} at ${handle.url}`);
83
- console.log(`room ID: ${entry.id} — attach with \`roomyx-client --room ${entry.id}\``);
84
-
85
- const shutdown = () => {
86
- deregisterRoom(registryPath, entry.id);
87
- void handle.close().then(() => process.exit(0));
42
+ /**
43
+ * Runs a long-lived server until a signal, then shuts it down once.
44
+ *
45
+ * Written once because there were three copies and they had drifted: the two
46
+ * here handled SIGINT and SIGTERM and guarded nothing, while the client handled
47
+ * SIGHUP as well and guarded re-entry. So closing a terminal (SIGHUP) killed
48
+ * `roomyx serve` outright, skipping deregistration and leaving a stale registry
49
+ * entry — which a recycled port then resurrects as a live room.
50
+ *
51
+ * `cleanup` runs *after* the close resolves, not before. Deregistering first
52
+ * meant a shutdown that hung — and it hung whenever a client was attached —
53
+ * removed the room from the registry while the process kept running and kept
54
+ * the port. The room became invisible while still being served.
55
+ */
56
+ function runUntilSignal(close: () => Promise<void>, cleanup: () => void = () => undefined): void {
57
+ let shuttingDown = false;
58
+ const shutdown = (): void => {
59
+ if (shuttingDown) return;
60
+ shuttingDown = true;
61
+ void close()
62
+ .catch((error: unknown) => {
63
+ console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
64
+ })
65
+ .finally(() => {
66
+ cleanup();
67
+ process.exit(0);
68
+ });
88
69
  };
89
- process.on("SIGINT", shutdown);
90
- process.on("SIGTERM", shutdown);
70
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, shutdown);
91
71
  }
92
72
 
93
- async function runRoomsList(): Promise<void> {
94
- const rooms = await listLiveRooms(defaultRegistryPath());
95
- if (rooms.length === 0) {
96
- console.log("No live rooms.");
97
- return;
98
- }
99
- for (const room of rooms) {
100
- console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
101
- }
73
+ interface Command {
74
+ usage: string;
75
+ summary: string;
76
+ /** Extra lines under the flag table. */
77
+ notes?: string;
78
+ flags: FlagSpecs;
79
+ run: (args: ParsedArgs) => Promise<void>;
102
80
  }
103
81
 
104
- /**
105
- * `roomyx skills sync --target <claude|codex|keryx|all|path> [--dry-run] [--yes]`.
106
- *
107
- * Without `--yes` this reports what it would do and writes nothing — the
108
- * specification's wording, and D-02's requirement that landing on a real skill
109
- * file be a separate, deliberate act rather than a side effect of the
110
- * mechanism existing. `--dry-run` is then the same thing said explicitly.
111
- */
112
- async function runSkillsSync(rest: string[]): Promise<void> {
113
- const flags = parseFlags(rest);
114
- const target = typeof flags.target === "string" ? flags.target : undefined;
115
- if (!target) {
116
- console.error(`Missing --target. Expected one of ${NAMED_TARGETS.join(", ")}, all, or a path.`);
117
- process.exit(1);
118
- }
82
+ const COMMANDS: Record<string, Command> = {
83
+ init: {
84
+ usage: "roomyx init",
85
+ summary: "scaffold .roomyx/ in this project",
86
+ flags: {},
87
+ run: async () => {
88
+ const result = init({ cwd: process.cwd(), bundledSkillPath: bundledSkillPath() });
89
+ console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
90
+ },
91
+ },
119
92
 
120
- const yes = flags.yes === true;
121
- const dryRun = flags["dry-run"] === true || !yes;
122
- const configPath = typeof flags.config === "string" ? flags.config : defaultConfigPath();
93
+ "room new": {
94
+ usage: "roomyx room new <path> --goal <statement> [flags]",
95
+ summary: "create a room log",
96
+ notes: "Refuses to overwrite an existing log — a room log is append-only.",
97
+ flags: {
98
+ goal: { type: "string", describe: "Required. What the room is for, in one sentence" },
99
+ criteria: { type: "string", describe: "Success criteria, stored in the goal contract" },
100
+ roster: { type: "string", describe: "Participants, as id:Name,id2:Name2" },
101
+ },
102
+ run: async ({ positionals, flags }) => {
103
+ const path = positionals[0];
104
+ if (!path) throw new ArgError("Missing <path>.");
105
+ const goalStatement = flags.goal;
106
+ if (typeof goalStatement !== "string") {
107
+ throw new ArgError("Missing --goal. A room without a stated goal has nothing to converge on.");
108
+ }
109
+ const absolute = resolve(path);
110
+ createRoomLog(absolute, {
111
+ goalStatement,
112
+ criteria: typeof flags.criteria === "string" ? flags.criteria : undefined,
113
+ roster: typeof flags.roster === "string" ? parseRoster(flags.roster) : [],
114
+ });
115
+ console.log(`Created ${absolute}`);
116
+ console.log(`serve it with \`roomyx serve ${path}\``);
117
+ },
118
+ },
123
119
 
124
- if (!existsSync(configPath)) {
125
- console.error(`No ${configPath}. Run \`roomyx init\` first.`);
126
- process.exit(1);
127
- }
120
+ "room append": {
121
+ usage: "roomyx room append <path> --from <id> --body <text> [flags]",
122
+ summary: "append a message to a room log",
123
+ notes:
124
+ "Refuses when a live room is serving that log: if that room has a\n dispatcher, the dispatcher is the single writer (D-01a). --force appends\n anyway — a room served by bare `roomyx serve` has no dispatcher to race.",
125
+ flags: {
126
+ from: { type: "string", describe: "Required. Participant id" },
127
+ body: { type: "string", describe: "Required. The message" },
128
+ kind: { type: "string", describe: "Message kind, e.g. challenge" },
129
+ "in-reply-to": { type: "number", describe: "seq of the message replied to" },
130
+ force: { type: "boolean", describe: "Append even if a live room serves this log" },
131
+ registry: REGISTRY_FLAG,
132
+ },
133
+ run: async ({ positionals, flags }) => {
134
+ const path = positionals[0];
135
+ if (!path) throw new ArgError("Missing <path>.");
136
+ const from = flags.from;
137
+ const body = flags.body;
138
+ if (typeof from !== "string" || typeof body !== "string") {
139
+ throw new ArgError("Both --from and --body are required.");
140
+ }
128
141
 
129
- for (const { name, path } of resolveTargets(target)) {
130
- const result = syncSkill({
131
- bundledSkillPath: bundledSkillPath(),
132
- targetPath: path,
133
- configPath,
134
- dryRun,
135
- yes,
136
- });
137
- console.log(name === path ? path : `${name}: ${path}`);
138
- for (const warning of result.warnings) console.log(` warning: ${warning}`);
139
- if (result.written) {
140
- console.log(result.backedUpTo ? ` written (backup: ${result.backedUpTo})` : " written");
141
- } else {
142
- console.log(dryRun ? " would write (pass --yes to apply)" : " not written");
143
- }
144
- }
145
- }
142
+ const absolute = resolve(path);
143
+ if (flags.force !== true) {
144
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
145
+ const serving = (await listLiveRooms(registryPath)).find((room) => room.logPath === absolute);
146
+ if (serving) {
147
+ // The old wording ended "Pass --force if you know it isn't" — it asked
148
+ // the operator to assert the room is gone. But the common case for
149
+ // reaching this message is a room served by bare `roomyx serve`, where
150
+ // the room is genuinely live and simply has no dispatcher attached, so
151
+ // there is no second writer to race. The flag was the right escape
152
+ // hatch behind a claim that was false exactly when you needed it.
153
+ //
154
+ // roomyx cannot tell the two apart: the registry records that a room
155
+ // serves this path, not whether anything is dispatching into it. So
156
+ // say what is known and let the operator judge, rather than making
157
+ // --force mean something untrue.
158
+ throw new ArgError(
159
+ `A live room (${serving.id}) is serving this log. If it has a dispatcher, that dispatcher is the log's single writer (D-01a) and appending here races it. Pass --force to append anyway.`,
160
+ );
161
+ }
162
+ }
163
+
164
+ // Refused here, in the grammar, so the error names the flag the operator
165
+ // typed rather than a field name from the on-disk schema. `appendMessage`
166
+ // validates too — that is the guard that cannot be bypassed — but a
167
+ // message about `--kind` belongs to the CLI that owns the flag.
168
+ const kind = typeof flags.kind === "string" ? flags.kind : undefined;
169
+ if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
170
+ throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
171
+ }
172
+ const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
173
+ if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
174
+ throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
175
+ }
146
176
 
147
- async function runMcp(rest: string[]): Promise<void> {
148
- const flags = parseFlags(rest);
149
- const handle = await serveManagement(
150
- {
151
- registryPath: typeof flags.registry === "string" ? flags.registry : defaultRegistryPath(),
152
- bundledSkillPath: bundledSkillPath(),
153
- configPath: typeof flags.config === "string" ? flags.config : defaultConfigPath(),
177
+ const message = appendMessage(absolute, {
178
+ from,
179
+ body,
180
+ kind: kind as MessageEnvelope["kind"],
181
+ inReplyTo,
182
+ });
183
+ console.log(`Appended seq ${message.seq} from ${message.from}.`);
154
184
  },
155
- {
156
- port: flags.port !== undefined ? Number(flags.port) : undefined,
157
- host: typeof flags.host === "string" ? flags.host : undefined,
158
- acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
185
+ },
186
+
187
+ serve: {
188
+ usage: "roomyx serve <logPath> [flags]",
189
+ summary: "serve a room log over MCP",
190
+ flags: {
191
+ port: { type: "number", describe: "Listen port (default 4319; 0 picks an ephemeral one)" },
192
+ host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
193
+ "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
194
+ registry: REGISTRY_FLAG,
159
195
  },
160
- );
196
+ run: async ({ positionals, flags }) => {
197
+ const logPath = positionals[0];
198
+ if (!logPath) throw new ArgError("Missing <logPath>.");
161
199
 
162
- console.log(`roomyx mcp listening at ${handle.url}`);
163
- console.log("tools: roomyx.rooms.list, roomyx.skills.sync");
200
+ // Absolute, because the registry outlives this process's working
201
+ // directory: `roomyx-client` resolves rooms from wherever the person
202
+ // happened to run it, and a relative logPath means nothing there.
203
+ const absoluteLogPath = resolve(logPath);
204
+ const handle = await serve(absoluteLogPath, {
205
+ port: typeof flags.port === "number" ? flags.port : undefined,
206
+ host: typeof flags.host === "string" ? flags.host : undefined,
207
+ acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
208
+ });
164
209
 
165
- const shutdown = () => {
166
- void handle.close().then(() => process.exit(0));
167
- };
168
- process.on("SIGINT", shutdown);
169
- process.on("SIGTERM", shutdown);
170
- }
210
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
211
+ const entry = registerRoom(registryPath, {
212
+ port: handle.port,
213
+ logPath: absoluteLogPath,
214
+ pid: process.pid,
215
+ });
216
+
217
+ console.log(`roomyx serving ${absoluteLogPath} at ${handle.url}`);
218
+ console.log(`room ID: ${entry.id} — attach with \`roomyx-client --room ${entry.id}\``);
219
+
220
+ runUntilSignal(
221
+ () => handle.close(),
222
+ () => deregisterRoom(registryPath, entry.id),
223
+ );
224
+ },
225
+ },
226
+
227
+ "rooms list": {
228
+ usage: "roomyx rooms list [flags]",
229
+ summary: "live rooms, confirmed by a real call rather than by the file",
230
+ flags: { registry: REGISTRY_FLAG },
231
+ run: async ({ flags }) => {
232
+ // `--registry` used to be accepted here and silently ignored: this
233
+ // command took no arguments at all and read the default path, so
234
+ // `rooms list --registry /nonexistent.json` printed "No live rooms"
235
+ // about a different file.
236
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
237
+ const rooms = await listLiveRooms(registryPath);
238
+ if (rooms.length === 0) {
239
+ console.log("No live rooms.");
240
+ return;
241
+ }
242
+ for (const room of rooms) {
243
+ console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
244
+ }
245
+ },
246
+ },
247
+
248
+ client: {
249
+ usage: "roomyx client [flags]",
250
+ summary: "attach the terminal UI (same as the roomyx-client binary)",
251
+ flags: CLIENT_FLAGS,
252
+ run: async ({ flags }) => {
253
+ const { runClient } = await import("./client/index");
254
+ await runClient(flags);
255
+ },
256
+ },
257
+
258
+ mcp: {
259
+ usage: "roomyx mcp [flags]",
260
+ summary: "start the management MCP server",
261
+ notes: "Default port 4320, so it does not collide with `roomyx serve`.",
262
+ flags: {
263
+ port: { type: "number", describe: "Listen port (default 4320; 0 picks an ephemeral one)" },
264
+ host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
265
+ "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
266
+ registry: REGISTRY_FLAG,
267
+ config: { type: "string", describe: "Config file (default .roomyx/config.json)" },
268
+ },
269
+ run: async ({ flags }) => {
270
+ const handle = await serveManagement(
271
+ {
272
+ registryPath: typeof flags.registry === "string" ? flags.registry : defaultRegistryPath(),
273
+ bundledSkillPath: bundledSkillPath(),
274
+ configPath: typeof flags.config === "string" ? flags.config : defaultConfigPath(),
275
+ },
276
+ {
277
+ port: typeof flags.port === "number" ? flags.port : undefined,
278
+ host: typeof flags.host === "string" ? flags.host : undefined,
279
+ acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
280
+ },
281
+ );
282
+
283
+ console.log(`roomyx mcp listening at ${handle.url}`);
284
+ console.log("tools: roomyx.rooms.list, roomyx.skills.sync");
285
+
286
+ runUntilSignal(() => handle.close());
287
+ },
288
+ },
289
+
290
+ "skills sync": {
291
+ usage: "roomyx skills sync --target <claude|codex|keryx|all|path> [flags]",
292
+ summary: "install the bundled startup-room skill",
293
+ notes:
294
+ "Without --yes nothing is written: the run reports what it would do and\n stops. D-02 — landing on a real skill file is a deliberate act, not a\n side effect of the mechanism existing.",
295
+ flags: {
296
+ target: { type: "string", describe: `Required. ${NAMED_TARGETS.join(", ")}, all, or a literal path` },
297
+ yes: { type: "boolean", describe: "Actually write" },
298
+ "dry-run": { type: "boolean", describe: "Report only (the default)" },
299
+ config: { type: "string", describe: "Config file the sync records hashes in" },
300
+ },
301
+ run: async ({ flags }) => {
302
+ const target = flags.target;
303
+ if (typeof target !== "string") {
304
+ throw new ArgError(`Missing --target. Expected one of ${NAMED_TARGETS.join(", ")}, all, or a path.`);
305
+ }
306
+
307
+ const yes = flags.yes === true;
308
+ // The gate itself lives in `syncSkill` now, computed once for every
309
+ // surface — this line only forwards what the operator typed.
310
+ const dryRun = flags["dry-run"] === true;
311
+ const configPath = typeof flags.config === "string" ? flags.config : defaultConfigPath();
312
+ if (!existsSync(configPath)) {
313
+ throw new ArgError(`No ${configPath}. Run \`roomyx init\` first.`);
314
+ }
315
+
316
+ for (const { name, path } of resolveTargets(target)) {
317
+ const result = syncSkill({
318
+ bundledSkillPath: bundledSkillPath(),
319
+ targetPath: path,
320
+ configPath,
321
+ dryRun,
322
+ yes,
323
+ });
324
+ console.log(name === path ? path : `${name}: ${path}`);
325
+ for (const warning of result.warnings) console.log(` warning: ${warning}`);
326
+ if (result.written) {
327
+ console.log(result.backedUpTo ? ` written (backup: ${result.backedUpTo})` : " written");
328
+ } else {
329
+ // "not written" was the message whenever `dryRun` was false, which
330
+ // after the gate moved into syncSkill meant the ordinary
331
+ // no-flags run reported a bare refusal instead of the sentence that
332
+ // says how to proceed. Branch on why nothing was written, not on
333
+ // which flag was passed.
334
+ console.log(result.wouldWrite ? " would write (pass --yes to apply)" : " not written");
335
+ }
336
+ }
337
+ },
338
+ },
339
+ };
171
340
 
172
341
  /** package.json ships in the tarball (see `files`), so this resolves for an installed copy too. */
173
342
  function version(): string {
@@ -177,32 +346,74 @@ function version(): string {
177
346
  return manifest.version;
178
347
  }
179
348
 
349
+ function topLevelHelp(): string {
350
+ const names = Object.keys(COMMANDS);
351
+ const width = Math.max(...names.map((n) => n.length));
352
+ return [
353
+ "Usage: roomyx <command> [flags]",
354
+ "",
355
+ ...names.map((n) => ` ${n.padEnd(width)} ${COMMANDS[n]!.summary}`),
356
+ "",
357
+ " --version",
358
+ "",
359
+ "`roomyx <command> --help` describes one command.",
360
+ "The terminal UI is also a separate binary: roomyx-client [--room <id>]",
361
+ ].join("\n");
362
+ }
363
+
364
+ function commandHelp(command: Command): string {
365
+ const table = renderFlags(command.flags);
366
+ return [
367
+ command.usage,
368
+ "",
369
+ ` ${command.summary}`,
370
+ ...(command.notes ? ["", ` ${command.notes}`] : []),
371
+ ...(table ? ["", table] : []),
372
+ ].join("\n");
373
+ }
374
+
375
+ /** Longest command name first, so "room new" wins over a hypothetical "room". */
376
+ function matchCommand(argv: string[]): { name: string; command: Command; rest: string[] } | undefined {
377
+ for (const name of Object.keys(COMMANDS).sort((a, b) => b.split(" ").length - a.split(" ").length)) {
378
+ const words = name.split(" ");
379
+ if (words.every((word, i) => argv[i] === word)) {
380
+ return { name, command: COMMANDS[name]!, rest: argv.slice(words.length) };
381
+ }
382
+ }
383
+ return undefined;
384
+ }
385
+
180
386
  async function main(): Promise<void> {
181
- const [command, ...rest] = process.argv.slice(2);
387
+ const argv = process.argv.slice(2);
182
388
 
183
- if (command === "--version" || command === "-v") {
389
+ if (argv[0] === "--version" || argv[0] === "-v") {
184
390
  console.log(version());
185
- } else if (command === "init") {
186
- await runInit();
187
- } else if (command === "serve") {
188
- await runServe(rest[0], rest.slice(1));
189
- } else if (command === "client") {
190
- const { runClient } = await import("./client/index");
191
- await runClient(rest);
192
- } else if (command === "mcp") {
193
- await runMcp(rest);
194
- } else if (command === "rooms" && rest[0] === "list") {
195
- await runRoomsList();
196
- } else if (command === "skills" && rest[0] === "sync") {
197
- await runSkillsSync(rest.slice(1));
198
- } else {
199
- console.error(USAGE);
200
- console.error("The terminal UI is also a separate binary: roomyx-client [--room <id>]");
201
- process.exit(1);
391
+ return;
202
392
  }
393
+
394
+ const matched = matchCommand(argv);
395
+ if (!matched) {
396
+ // `--help` is a request and exits 0. A bare `roomyx`, or a command that
397
+ // isn't one, is a usage error and exits 1 — the convention git follows,
398
+ // and the distinction a shell script or an agent actually reads.
399
+ const askedForHelp = argv[0] === "--help" || argv[0] === "-h";
400
+ console[askedForHelp ? "log" : "error"](topLevelHelp());
401
+ process.exit(askedForHelp ? 0 : 1);
402
+ }
403
+
404
+ const parsed = parseArgs(matched.rest, matched.command.flags);
405
+ if (parsed.help) {
406
+ console.log(commandHelp(matched.command));
407
+ return;
408
+ }
409
+ await matched.command.run(parsed);
203
410
  }
204
411
 
205
412
  main().catch((error) => {
413
+ if (error instanceof ArgError) {
414
+ console.error(error.message);
415
+ process.exit(1);
416
+ }
206
417
  console.error(error instanceof Error ? error.message : String(error));
207
418
  process.exit(1);
208
419
  });
@@ -0,0 +1,53 @@
1
+ import { TextRenderable } from "@opentui/core";
2
+ import type { RenderContext } from "@opentui/core";
3
+ import { footerHints } from "../keymap";
4
+
5
+ /**
6
+ * The bottom line: what the room is doing on the left, what your keys are on
7
+ * the right.
8
+ *
9
+ * Two reviewers arrived at this independently and it closes four separate
10
+ * complaints — an empty room that looked hung, a dead room that looked live, a
11
+ * keymap advertised nowhere, and a scroll position with no indicator. It is
12
+ * deliberately one row: the transcript is the product, and a help panel that
13
+ * costs five rows on a 24-row terminal would be paid for by the thing people
14
+ * came to read.
15
+ *
16
+ * The hints come from the keymap rather than from a string written here, so
17
+ * the footer cannot drift from what the keys actually do.
18
+ */
19
+ export class Footer {
20
+ readonly node: TextRenderable;
21
+ private liveness = "";
22
+ private scrollNote: string | null = null;
23
+ private readonly width: number;
24
+
25
+ constructor(ctx: RenderContext, options: { width: number }) {
26
+ this.width = options.width;
27
+ this.node = new TextRenderable(ctx, { content: "", height: 1 });
28
+ this.render();
29
+ }
30
+
31
+ setLiveness(liveness: string): void {
32
+ this.liveness = liveness;
33
+ this.render();
34
+ }
35
+
36
+ /** Set while the reader has scrolled away from the bottom, null at the bottom. */
37
+ setScrollNote(note: string | null): void {
38
+ this.scrollNote = note;
39
+ this.render();
40
+ }
41
+
42
+ private render(): void {
43
+ const left = this.scrollNote === null ? this.liveness : `${this.liveness} · ${this.scrollNote}`;
44
+ // The left half wins the space it needs — knowing the room is dead matters
45
+ // more than being reminded which key quits — but the hints give way one at
46
+ // a time rather than all at once. The first version dropped every hint the
47
+ // moment the line did not fit, which took them away in exactly the two
48
+ // states that most need them: an empty room, and a scrolled one.
49
+ const right = footerHints(Math.max(0, this.width - left.length - 2));
50
+ const gap = this.width - left.length - right.length;
51
+ this.node.content = right === "" || gap < 2 ? left.slice(0, Math.max(0, this.width)) : `${left}${" ".repeat(gap)}${right}`;
52
+ }
53
+ }