@mrciphersmith/roomyx 0.12.1 → 0.12.3

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +140 -12
  3. package/package.json +11 -10
  4. package/src/bin/launch.mjs +1 -1
  5. package/src/bundled-personas/groups.md +3 -3
  6. package/src/bundled-skills/startup-room/reference/roomyx.md +5 -0
  7. package/src/cli/client.ts +12 -0
  8. package/src/cli/experiment.ts +67 -0
  9. package/src/cli/init.ts +149 -0
  10. package/src/cli/mcp.ts +54 -0
  11. package/src/cli/personas.ts +40 -0
  12. package/src/cli/room-append.ts +357 -0
  13. package/src/cli/room.ts +91 -0
  14. package/src/cli/rooms.ts +65 -0
  15. package/src/cli/serve.ts +84 -0
  16. package/src/cli/shared.ts +71 -0
  17. package/src/cli/skills.ts +58 -0
  18. package/src/cli/specs.ts +1 -0
  19. package/src/cli.ts +29 -884
  20. package/src/client/index.ts +16 -3
  21. package/src/client/mcp-client.ts +106 -7
  22. package/src/client/shutdown.ts +29 -6
  23. package/src/experiment/manifest.ts +151 -0
  24. package/src/installer/init-apply.ts +38 -7
  25. package/src/installer/init.ts +5 -2
  26. package/src/installer/registry.ts +38 -6
  27. package/src/installer/resolve-connection.ts +54 -8
  28. package/src/installer/room-tool.ts +6 -3
  29. package/src/installer/skill-sync.ts +86 -3
  30. package/src/installer/skill-targets.ts +7 -3
  31. package/src/lockfile.ts +13 -2
  32. package/src/log/schema.ts +108 -38
  33. package/src/log/store.ts +1 -0
  34. package/src/log/types.ts +8 -1
  35. package/src/log/write.ts +115 -6
  36. package/src/mcp-management/server.ts +30 -4
  37. package/src/room-token.ts +129 -0
  38. package/src/server/http-transport.ts +43 -0
  39. package/src/server/index.ts +76 -3
  40. package/src/server/log-watcher.ts +80 -0
  41. package/src/server/owner-queue.ts +7 -1
  42. package/src/server/serve.ts +112 -30
  43. package/src/server/shutdown.ts +33 -7
  44. package/src/writer-lease.ts +161 -14
package/src/cli.ts CHANGED
@@ -1,32 +1,18 @@
1
1
  #!/usr/bin/env bun
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join, resolve } from "node:path";
5
- import { serve } from "./server/serve";
6
- import { createServerShutdown } from "./server/shutdown";
7
- import { init } from "./installer/init";
8
- import {
9
- findRoomServing,
10
- probeRoomState,
11
- registerRoom,
12
- deregisterRoom,
13
- listRoomsWithLiveness,
14
- } from "./installer/registry";
15
- import { archiveRoom, defaultHistoryPath, readHistory } from "./installer/history";
16
- import { syncSkillBundle } from "./installer/skill-sync";
17
- import { installPersonas, personaCount } from "./installer/personas";
18
- import { callRoomTool } from "./installer/room-tool";
19
- import { appendMessages, createRoomLog, LEGAL_KINDS, parseRoster } from "./log/write";
20
- import type { AppendMessageOptions } from "./log/write";
21
- import { acquireWriterLease, readWriterLease, writerLeasePathFor } from "./writer-lease";
22
- import { MESSAGE_KINDS } from "./log/schema";
23
- import { LogWriteError } from "./log/write";
24
- import type { MessageEnvelope } from "./log/types";
25
- import { NAMED_TARGETS, resolveTargets } from "./installer/skill-targets";
26
- import { serveManagement } from "./mcp-management/server";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
27
4
  import { ArgError, parseArgs, renderFlags } from "./cli/args";
28
- import type { FlagSpecs, FlagValues, ParsedArgs } from "./cli/args";
29
- import { CLIENT_FLAGS } from "./cli/specs";
5
+ import { initCommand, setupCommand } from "./cli/init";
6
+ import { roomNew, roomDelta, roomCommands, roomAck } from "./cli/room";
7
+ import { roomAppend } from "./cli/room-append";
8
+ import { serveCommand } from "./cli/serve";
9
+ import { roomsList, roomsHistory } from "./cli/rooms";
10
+ import { personasCommand } from "./cli/personas";
11
+ import { clientCommand } from "./cli/client";
12
+ import { mcpCommand } from "./cli/mcp";
13
+ import { skillsSync } from "./cli/skills";
14
+ import { experimentNew, experimentPlan } from "./cli/experiment";
15
+ import type { Command } from "./cli/shared";
30
16
 
31
17
  /**
32
18
  * The TUI is primarily `roomyx-client` (its own binary over
@@ -39,864 +25,23 @@ import { CLIENT_FLAGS } from "./cli/specs";
39
25
  * `./cli/args` for what that fixes and why it was one defect rather than six.
40
26
  */
41
27
 
42
- function defaultRegistryPath(): string {
43
- return join(process.cwd(), ".roomyx", "rooms", "registry.json");
44
- }
45
-
46
- function defaultConfigPath(): string {
47
- return join(process.cwd(), ".roomyx", "config.json");
48
- }
49
-
50
- /**
51
- * Turns the flags into the messages to write, or refuses.
52
- *
53
- * Four ways in, and they do not compose: an envelope says everything, so a
54
- * `--from` beside it is an ambiguity rather than an override — and guessing
55
- * which one the caller meant is how a body goes into the wrong speaker's mouth.
56
- */
57
- function pendingAppends(flags: FlagValues): AppendMessageOptions[] {
58
- // Two different things are being chosen here, and conflating them was wrong:
59
- // `--json` and `--many` carry a whole envelope (speaker included), while
60
- // `--body` and `--body-file` carry only the body and still need `--from`.
61
- // Refusing `--body-file --from b` refused a combination that has no ambiguity
62
- // in it at all.
63
- const envelopeSources = [flags.json !== undefined, flags.many === true].filter(Boolean).length;
64
- if (envelopeSources > 1) throw new ArgError("Use one of --json or --many, not both.");
65
- const bodySources = [flags.body !== undefined, flags["body-file"] !== undefined].filter(Boolean).length;
66
- if (bodySources > 1) throw new ArgError("Use one of --body or --body-file, not both.");
67
-
68
- if (envelopeSources === 1) {
69
- const conflicting = ["from", "body", "body-file", "kind", "in-reply-to"].filter((f) => flags[f] !== undefined);
70
- if (conflicting.length > 0) {
71
- // An envelope says everything. Silently preferring one source is how a
72
- // body ends up in the log under a speaker nobody chose.
73
- throw new ArgError(
74
- `--json/--many carry the whole envelope, so --${conflicting.join(", --")} cannot be combined with them.`,
75
- );
76
- }
77
- return flags.many === true ? parseBatch(readStdin()) : [envelopeFrom(flags.json as string)];
78
- }
79
-
80
- const from = flags.from;
81
- if (typeof from !== "string" || from === "") {
82
- throw new ArgError("Both --from and --body are required (or pass --json, --body-file or --many).");
83
- }
84
- const body = typeof flags["body-file"] === "string" ? bodyFromFile(flags["body-file"]) : flags.body;
85
- if (typeof body !== "string") throw new ArgError("Both --from and --body are required.");
86
-
87
- const kind = typeof flags.kind === "string" ? flags.kind : undefined;
88
- if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
89
- throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
90
- }
91
- const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
92
- if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
93
- throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
94
- }
95
- return [{ from, body, kind: kind as MessageEnvelope["kind"], inReplyTo }];
96
- }
97
-
98
- function readStdin(): string {
99
- if (process.stdin.isTTY === true) {
100
- // Reading fd 0 from a terminal blocks until Ctrl-D, which reads as a hang.
101
- throw new ArgError("This flag reads the message from stdin, and stdin is a terminal. Pipe the text in, or use --body.");
102
- }
103
- return readFileSync(0, "utf8");
104
- }
105
-
106
- function bodyFromFile(file: string): string {
107
- // A trailing newline is what every editor and every `echo` adds; it is not
108
- // part of what the speaker said, and it would land inside the quoted body.
109
- const raw = file === "-" ? readStdin() : readFileSync(resolve(file), "utf8");
110
- return raw.replace(/\r?\n$/, "");
111
- }
112
-
113
- const ENVELOPE_KEYS = ["from", "body", "kind", "in_reply_to", "change"] as const;
114
-
115
- /**
116
- * Parses one envelope, refusing keys that would silently vanish.
117
- *
118
- * An unknown key is a refusal rather than something ignored: `seq` and `type`
119
- * are assigned by the writer, and a caller who passes one believes they chose
120
- * it — so accepting the envelope while dropping their value is the one answer
121
- * that cannot be discovered from the log.
122
- */
123
- function envelopeFrom(text: string): AppendMessageOptions {
124
- let parsed: unknown;
125
- try {
126
- parsed = JSON.parse(text) as unknown;
127
- } catch (error) {
128
- throw new ArgError(`--json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
129
- }
130
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
131
- throw new ArgError("--json must be a JSON object.");
132
- }
133
- const envelope = parsed as Record<string, unknown>;
134
- for (const key of Object.keys(envelope)) {
135
- if (!(ENVELOPE_KEYS as readonly string[]).includes(key)) {
136
- throw new ArgError(`--json has an unknown key "${key}". Allowed: ${ENVELOPE_KEYS.join(", ")}.`);
137
- }
138
- }
139
- const { from, body, kind, in_reply_to: inReplyTo, change } = envelope;
140
- if (typeof from !== "string" || from === "") throw new ArgError('--json needs a non-empty "from".');
141
- if (typeof body !== "string") throw new ArgError('--json needs a string "body".');
142
- if (kind !== undefined && (typeof kind !== "string" || !(MESSAGE_KINDS as readonly string[]).includes(kind))) {
143
- throw new ArgError(`--json "kind" must be one of: ${LEGAL_KINDS}.`);
144
- }
145
- if (inReplyTo !== undefined && (typeof inReplyTo !== "number" || !Number.isInteger(inReplyTo) || inReplyTo < 1)) {
146
- throw new ArgError('--json "in_reply_to" must be a whole number of at least 1.');
147
- }
148
- // The change is passed through unexamined here and validated where the rule
149
- // lives (the log's own schema, imported by the writer). Re-checking its shape
150
- // in the CLI would be a second copy of a rule the log already owns — and the
151
- // two copies would drift, which is the failure `src/log/schema.ts` exists to
152
- // make impossible.
153
- if (change !== undefined && (typeof change !== "object" || change === null)) {
154
- throw new ArgError('--json "change" must be an object.');
155
- }
156
- return {
157
- from,
158
- body,
159
- kind: kind as MessageEnvelope["kind"],
160
- inReplyTo: inReplyTo as number | undefined,
161
- change: change as MessageEnvelope["change"],
162
- };
163
- }
164
-
165
- function parseBatch(text: string): AppendMessageOptions[] {
166
- const lines = text.split("\n").filter((line) => line.trim().length > 0);
167
- if (lines.length === 0) throw new ArgError("--many read no envelopes from stdin.");
168
- return lines.map((line, index) => {
169
- try {
170
- return envelopeFrom(line);
171
- } catch (error) {
172
- throw new ArgError(`--many line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
173
- }
174
- });
175
- }
176
-
177
- /**
178
- * Writes the batch, or none of it. `appendMessages` allocates consecutive `seq`
179
- * and validates every envelope before the first byte, so a refused batch leaves
180
- * the log exactly as it was.
181
- */
182
- function writeAll(path: string, pending: AppendMessageOptions[]) {
183
- try {
184
- return appendMessages(path, pending);
185
- } catch (error) {
186
- if (error instanceof LogWriteError) throw new ArgError(error.message);
187
- throw error;
188
- }
189
- }
190
-
191
- /** The holder a take-over displaced, when there was one. */
192
- function stateBefore(lease: import("./writer-lease").LeaseState): { pid: number; at: number } | undefined {
193
- if (lease.held) return { pid: lease.lease.pid, at: lease.lease.at };
194
- // A stale lease still identifies the writer that stopped: recording it is the
195
- // difference between a log that says "someone took this over" and one that
196
- // says who from.
197
- return lease.reason === "stale" ? { pid: lease.last.pid, at: lease.last.at } : undefined;
198
- }
199
-
200
- function bundledSkillPath(): string {
201
- return join(import.meta.dir, "bundled-skills", "startup-room", "SKILL.md");
202
- }
203
-
204
- function bundledPersonasPath(): string {
205
- return join(import.meta.dir, "bundled-personas");
206
- }
207
-
208
- function defaultPersonasPath(cwd: string = process.cwd()): string {
209
- return join(cwd, ".roomyx", "personas");
210
- }
211
-
212
- const REGISTRY_FLAG = { type: "string", describe: "Registry file (default .roomyx/rooms/registry.json)" } as const;
213
-
214
- /**
215
- * Wires the signals. The shutdown itself lives in `./server/shutdown`, where a
216
- * test can reach it — this module runs its entry point on import.
217
- *
218
- * Written once because there were three copies and they had drifted: the two
219
- * here handled SIGINT and SIGTERM and guarded nothing, while the client handled
220
- * SIGHUP as well and guarded re-entry. So closing a terminal (SIGHUP) killed
221
- * `roomyx serve` outright, skipping deregistration and leaving a stale registry
222
- * entry — which a recycled port then resurrects as a live room.
223
- *
224
- * `cleanup` runs *after* the close resolves, not before. Deregistering first
225
- * meant a shutdown that hung — and it hung whenever a client was attached —
226
- * removed the room from the registry while the process kept running and kept
227
- * the port. The room became invisible while still being served.
228
- */
229
- function runUntilSignal(close: () => Promise<void>, cleanup: () => void = () => undefined): void {
230
- const shutdown = createServerShutdown(close, cleanup);
231
- for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, shutdown);
232
- }
233
-
234
- interface Command {
235
- usage: string;
236
- summary: string;
237
- /** Extra lines under the flag table. */
238
- notes?: string;
239
- flags: FlagSpecs;
240
- run: (args: ParsedArgs) => Promise<void>;
241
- }
242
-
243
-
244
- /**
245
- * The live room serving this log, or a refusal that says what to do.
246
- *
247
- * Shared by the three commands that talk to a room's own MCP server. They need
248
- * a port, and the registry is the only place a room's port is written down —
249
- * which is exactly why these tools had no caller before: there is no way to
250
- * reach a room without going through here first.
251
- */
252
- async function servingRoomFor(absoluteLog: string, registryPath: string) {
253
- const serving = findRoomServing(absoluteLog, await listRoomsWithLiveness(registryPath, { prune: false }));
254
- if (serving === undefined) {
255
- throw new ArgError(
256
- `No live room is serving ${absoluteLog}. These commands read from the room's own server, ` +
257
- `so the room has to be running: start it with \`roomyx serve ${absoluteLog} --port 0\`.`,
258
- );
259
- }
260
- return serving;
261
- }
262
-
263
28
  const COMMANDS: Record<string, Command> = {
264
- init: {
265
- usage: "roomyx init [flags]",
266
- summary: "scaffold .roomyx/, then set up skills, MCP and git for this project",
267
- notes:
268
- "Interactive when the terminal allows it: tick what you want, see every\n path before agreeing to it, and nothing is written until you submit.\n Through a pipe or in CI it scaffolds .roomyx/ and asks nothing, so it can\n never hang waiting for a keypress nobody is there to make.",
269
- flags: {
270
- yes: { type: "boolean", describe: "Apply the default selection without asking" },
271
- "no-interactive": { type: "boolean", describe: "Scaffold .roomyx/ only" },
272
- },
273
- run: async ({ flags }) => {
274
- const cwd = process.cwd();
275
- const result = init({ cwd, bundledSkillPath: bundledSkillPath() });
276
- console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
277
- for (const warning of result.skillWarnings ?? []) {
278
- // Said out loud rather than swallowed: the staged copy is now known to
279
- // differ from the bundled skill, and whoever sees this decides what to
280
- // do about it.
281
- console.log(` ! ${warning}`);
282
- }
283
-
284
- const { buildPlan, selectedItems } = await import("./installer/init-plan");
285
- const { applyPlan } = await import("./installer/init-apply");
286
-
287
- const plan = buildPlan({ cwd, personaFiles: personaCount(bundledPersonasPath()) });
288
- // A terminal on both ends or nothing to ask. `--yes` overrides, because
289
- // a script that has decided already should not be refused for lacking a
290
- // tty — but the default must never block a pipeline on a prompt.
291
- const interactive = process.stdout.isTTY === true && process.stdin.isTTY === true;
292
- if (flags["no-interactive"] === true || (!interactive && flags.yes !== true)) {
293
- console.log("");
294
- console.log("Nothing else was written. To install the skill and register the MCP server:");
295
- console.log(" roomyx init --yes # the default selection, no prompt");
296
- console.log(" roomyx init # pick, in a terminal");
297
- return;
298
- }
299
-
300
- let chosen = plan;
301
- if (flags.yes !== true) {
302
- const { runInitPicker } = await import("./client/init-screen");
303
- const picked = await runInitPicker(plan);
304
- if (picked === null) {
305
- console.log("Cancelled — nothing else was written.");
306
- return;
307
- }
308
- chosen = picked;
309
- }
310
-
311
- const results = applyPlan(selectedItems(chosen), {
312
- cwd,
313
- bundledSkillPath: bundledSkillPath(),
314
- bundledPersonasPath: bundledPersonasPath(),
315
- configPath: join(cwd, ".roomyx", "config.json"),
316
- });
317
-
318
- console.log("");
319
- for (const line of results) {
320
- console.log(`${line.ok ? " ok " : " !! "} ${line.label}`);
321
- console.log(` ${line.path} — ${line.message}`);
322
- }
323
-
324
- const failed = results.filter((line) => !line.ok).length;
325
- if (failed > 0) console.log(`\n${failed} item(s) failed. Everything else was applied.`);
326
- if (results.some((line) => line.ok && line.id.startsWith("skill:"))) {
327
- // The one thing an operator reliably forgets, and the symptom is
328
- // "roomyx installed the skill and my agent still cannot see it".
329
- console.log("\nRestart your agent — skills are discovered at startup.");
330
- }
331
- console.log("\nNext: roomyx room new .roomyx/rooms/logs/<name>.jsonl --goal \"<what the room is for>\"");
332
- },
333
- },
334
-
335
- "room new": {
336
- usage: "roomyx room new <path> --goal <statement> [flags]",
337
- summary: "create a room log",
338
- notes: "Refuses to overwrite an existing log — a room log is append-only.",
339
- flags: {
340
- goal: { type: "string", describe: "Required. What the room is for, in one sentence" },
341
- criteria: { type: "string", describe: "Success criteria, stored in the goal contract" },
342
- roster: { type: "string", describe: "Participants, as id:Name,id2:Name2" },
343
- },
344
- run: async ({ positionals, flags }) => {
345
- const path = positionals[0];
346
- if (!path) throw new ArgError("Missing <path>.");
347
- const goalStatement = flags.goal;
348
- if (typeof goalStatement !== "string") {
349
- throw new ArgError("Missing --goal. A room without a stated goal has nothing to converge on.");
350
- }
351
- const absolute = resolve(path);
352
- createRoomLog(absolute, {
353
- goalStatement,
354
- criteria: typeof flags.criteria === "string" ? flags.criteria : undefined,
355
- roster: typeof flags.roster === "string" ? parseRoster(flags.roster) : [],
356
- });
357
- console.log(`Created ${absolute}`);
358
- console.log(`serve it with \`roomyx serve ${path}\``);
359
- },
360
- },
361
-
362
- "room append": {
363
- usage: "roomyx room append <path> (--from <id> --body <text> | --json <envelope> | --body-file <file> | --many) [flags]",
364
- summary: "append a message to a room log",
365
- notes:
366
- "Refuses only when the room is live AND something is writing into it: a\n live room with no dispatcher has no writer to race, so appending to it\n needs no flag at all (D-01a, D-18). A lease that has expired means the\n writer stopped without saying so — taking over then is a deliberate act,\n --take-over, and it is recorded in the log.",
367
- flags: {
368
- from: { type: "string", describe: "Participant id" },
369
- body: { type: "string", describe: "The message" },
370
- json: { type: "string", describe: "A whole envelope: {from, body, kind?, in_reply_to?}" },
371
- "body-file": { type: "string", describe: "Read the body from a file, or - for stdin" },
372
- many: { type: "boolean", describe: "Read a JSONL batch of envelopes from stdin; all of them or none" },
373
- kind: { type: "string", describe: "Message kind, e.g. challenge" },
374
- "in-reply-to": { type: "number", describe: "seq of the message replied to" },
375
- "take-over": { type: "boolean", describe: "Write when the room is live but its writer is gone" },
376
- registry: REGISTRY_FLAG,
377
- },
378
- run: async ({ positionals, flags }) => {
379
- const path = positionals[0];
380
- if (!path) throw new ArgError("Missing <path>.");
381
- const absolute = resolve(path);
382
-
383
- const takeOver = flags["take-over"] === true;
384
-
385
- // Absolute, because the lease lives beside the registry and this process's
386
- // cwd is not the next process's: a relative `--registry` made the lease
387
- // land in a different directory depending on where the command was run.
388
- const absoluteRegistry = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
389
- const leasePath = writerLeasePathFor(absoluteRegistry, absolute);
390
-
391
- // Across BOTH lists: an entry whose first probe timed out is `unconfirmed`,
392
- // and it may still have a dispatcher attached — which is the evidence this
393
- // guard needs. Searching only the confirmed list is how "the machine was
394
- // busy" turns into "nothing is writing into this log".
395
- const serving = findRoomServing(absolute, await listRoomsWithLiveness(absoluteRegistry));
396
-
397
- // Read the lease BEFORE the probe, and independently of its outcome. A
398
- // liveness probe that times out says "could not reach it", which is not
399
- // "nothing is writing into it" — and reading the lease only once the probe
400
- // succeeded meant a busy machine wrote into a room whose dispatcher was
401
- // perfectly alive.
402
- const lease = readWriterLease(leasePath);
403
- const dispatched = serving !== undefined ? ((await probeRoomState(serving))?.dispatcherAttached ?? undefined) : undefined;
404
-
405
- // Two independent pieces of evidence that someone else is writing: a live
406
- // dispatcher, and a lease somebody is refreshing. The second exists because
407
- // the first only holds for a server that was started with a lease path.
408
- const writerPresent = lease.held || dispatched === true;
409
- const writerWasThere = !writerPresent && lease.reason === "stale";
410
-
411
- if (writerPresent) {
412
- // Two different reasons to refuse, and they need different advice: a
413
- // lease that is merely stale will expire by itself, while a room that
414
- // reports a dispatcher will keep reporting one until the server is
415
- // stopped — waiting would be advice that never comes true.
416
- const advice =
417
- dispatched === true
418
- ? `Stop the server that is running the room; once it is gone, --take-over will let you write to this log.`
419
- : `Wait for that lease to expire (a writer that is running refreshes it), or stop the process holding it.`;
420
- throw new ArgError(
421
- `A writer is live in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`}` +
422
- `${lease.held ? ` — pid ${lease.lease.pid}` : " — the room reports a dispatcher attached"}. ` +
423
- `Two writers into one append-only log is the race D-01 exists to prevent, and nothing overrides a writer ` +
424
- `that is still there. ${advice}`,
425
- );
426
- }
427
- if (writerWasThere && !takeOver) {
428
- throw new ArgError(
429
- `A writer was in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`} and is gone — ` +
430
- `nothing holds the lease now. Writing means taking ownership from a room that looks supervised. ` +
431
- `Pass --take-over to do that deliberately; the log will record it.`,
432
- );
433
- }
434
-
435
- // A live room, and no evidence of a writer — say so rather than drop it.
436
- //
437
- // `serving` was already computed for the refusal above and, when nothing
438
- // holds a lease, was silently discarded. That silence is wrong in exactly
439
- // the case that matters: an agent dispatcher runs `roomyx serve` and
440
- // writes with `roomyx room append`, a fresh process each time, so it
441
- // never holds a lease and the room never reports a dispatcher. Every
442
- // append into a room an agent is running therefore looks, from here, like
443
- // an append into an unattended log.
444
- //
445
- // A note, not a refusal: there is nothing here that can tell a dispatcher
446
- // from a stranger, so refusing would block the legitimate writer — which
447
- // was tried and reverted. The log itself is safe either way; `seq`
448
- // allocation is under a lock and that is tested. What is at risk is the
449
- // conversation reading as one when it was two, and a line on stderr is
450
- // what lets a second writer notice before adding to it.
451
- //
452
- // stderr, because stdout carries `Appended seq N from X` and is parsed.
453
- if (serving !== undefined && !writerPresent && !writerWasThere) {
454
- console.error(
455
- `Note: room ${serving.id} is serving ${absolute}. Nothing holds the writer lease, so this append is ` +
456
- `allowed — but roomyx cannot see whether an agent is dispatching that room. If one is, you are writing ` +
457
- `into a conversation it is also writing into.`,
458
- );
459
- }
460
-
461
- // Parsed only after the refusal: an operator whose command is going to be
462
- // rejected should not be made to pipe a batch in first, and a reader that
463
- // blocks on stdin while holding a decision helps nobody.
464
- const pending = pendingAppends(flags);
465
-
466
- const displaced = takeOver || writerWasThere ? stateBefore(lease) : undefined;
467
- const takingOver = takeOver || writerWasThere;
468
-
469
- // One batch, one lock section: the take-over trace goes in WITH the
470
- // messages it describes. Written as a second call it could fail on its
471
- // own, and a room written by hand while its writer was absent would read
472
- // afterwards as supervised — the one thing the trace exists to prevent.
473
- const written = writeAll(absolute, [
474
- ...pending,
475
- ...(takingOver
476
- ? [
477
- {
478
- from: "owner",
479
- kind: "status" as const,
480
- body:
481
- `--take-over: ${pending.length} message(s) appended to ${absolute}` +
482
- `${serving === undefined ? "" : ` while room ${serving.id} was live`} with no live writer` +
483
- `${displaced === undefined ? " (no lease was held)" : ` (took over from pid ${displaced.pid})`}`,
484
- },
485
- ]
486
- : []),
487
- ]);
488
-
489
- if (takingOver) {
490
- // The lease is replaced with a new token, so a writer that was merely
491
- // paused cannot revive the one it lost by refreshing it — the whole
492
- // reason a take-over is not just a flag on the write.
493
- acquireWriterLease(leasePath, { pid: process.pid, ...(displaced === undefined ? {} : { takeOverFrom: displaced }) });
494
- }
495
-
496
- for (const message of written) console.log(`Appended seq ${message.seq} from ${message.from}.`);
497
- },
498
- },
499
-
500
- "room delta": {
501
- usage: "roomyx room delta <logPath> --for <agentId> [flags]",
502
- summary: "what a participant has not seen yet",
503
- notes:
504
- "Reads the room's own server, so the room must be running. This is the\n arithmetic a dispatcher used to redo in its own context every turn — the\n server computes it, and reports which cursor it used so an empty delta is\n distinguishable from a wrong one.",
505
- flags: {
506
- for: { type: "string", describe: "Required. Participant id" },
507
- since: { type: "number", describe: "Cursor to use instead of that participant's last message" },
508
- registry: REGISTRY_FLAG,
509
- },
510
- run: async ({ positionals, flags }) => {
511
- const path = positionals[0];
512
- if (!path) throw new ArgError("Missing <logPath>.");
513
- const agentId = flags.for;
514
- if (typeof agentId !== "string" || agentId === "") throw new ArgError("Missing --for <agentId>.");
515
- const absolute = resolve(path);
516
- const registryPath = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
517
- const room = await servingRoomFor(absolute, registryPath);
518
- const args: Record<string, unknown> = { agent_id: agentId };
519
- if (typeof flags.since === "number") args.since_seq = flags.since;
520
- console.log(JSON.stringify(await callRoomTool(room, "room.get_delta_for", args), null, 2));
521
- },
522
- },
523
-
524
- "room commands": {
525
- usage: "roomyx room commands <logPath> [flags]",
526
- summary: "owner commands waiting for the dispatcher",
527
- notes:
528
- "The owner posts these from the TUI and nothing pushes them — a dispatcher\n has to look. Poll between turns, then settle each one with `room ack`.",
529
- flags: { registry: REGISTRY_FLAG },
530
- run: async ({ positionals, flags }) => {
531
- const path = positionals[0];
532
- if (!path) throw new ArgError("Missing <logPath>.");
533
- const absolute = resolve(path);
534
- const registryPath = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
535
- const room = await servingRoomFor(absolute, registryPath);
536
- console.log(JSON.stringify(await callRoomTool(room, "room.get_pending_owner_commands", {}), null, 2));
537
- },
538
- },
539
-
540
- "room ack": {
541
- usage: "roomyx room ack <logPath> <commandId> [flags]",
542
- summary: "say an owner command has been dealt with",
543
- notes:
544
- "Without this, `pending` grows forever and stops meaning \"not yet handled\".",
545
- flags: { registry: REGISTRY_FLAG },
546
- run: async ({ positionals, flags }) => {
547
- const path = positionals[0];
548
- const id = positionals[1];
549
- if (!path) throw new ArgError("Missing <logPath>.");
550
- if (!id) throw new ArgError("Missing <commandId>. `roomyx room commands <logPath>` lists them.");
551
- const absolute = resolve(path);
552
- const registryPath = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
553
- const room = await servingRoomFor(absolute, registryPath);
554
- console.log(JSON.stringify(await callRoomTool(room, "room.ack_owner_command", { id }), null, 2));
555
- },
556
- },
557
-
558
- serve: {
559
- usage: "roomyx serve <logPath> [flags]",
560
- summary: "serve a room log over MCP",
561
- flags: {
562
- port: { type: "number", describe: "Listen port (default 4319; 0 picks an ephemeral one)" },
563
- host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
564
- "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
565
- registry: REGISTRY_FLAG,
566
- },
567
- run: async ({ positionals, flags }) => {
568
- const logPath = positionals[0];
569
- if (!logPath) throw new ArgError("Missing <logPath>.");
570
-
571
- // Absolute, because the registry outlives this process's working
572
- // directory: `roomyx-client` resolves rooms from wherever the person
573
- // happened to run it, and a relative logPath means nothing there.
574
- const absoluteLogPath = resolve(logPath);
575
- // Resolved before binding: the writer lease lives beside the registry, and
576
- // a server that acquires one after it starts answering would leave a
577
- // window where a live dispatcher looks like no writer at all.
578
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
579
- const handle = await serve(absoluteLogPath, {
580
- port: typeof flags.port === "number" ? flags.port : undefined,
581
- host: typeof flags.host === "string" ? flags.host : undefined,
582
- acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
583
- // No `writerLeasePath`, deliberately, and this is worth stating because
584
- // it was passed here and silently discarded on every serve.
585
- //
586
- // `serve()` takes the lease only when a dispatcher is attached, and
587
- // "attached" means an *embedder* supplied an `onOwnerCommand` callback.
588
- // `roomyx serve` never supplies one — an agent dispatcher has no
589
- // callback to give; it reads `room.get_pending_owner_commands` instead.
590
- // So the argument could never be used, while reading like a lease was
591
- // being taken.
592
- //
593
- // Making the CLI declare a dispatcher was tried and is WRONG: the lease
594
- // would be held by the server process, while the writer is the agent
595
- // running `roomyx room append` in a different process each time — so
596
- // the dispatcher would be locked out of its own room. Two dispatcher
597
- // models exist (embedder writes in-process; agent writes by CLI) and
598
- // only the first is expressible today. Recorded rather than patched.
599
- });
600
-
601
- const entry = registerRoom(registryPath, {
602
- port: handle.port,
603
- logPath: absoluteLogPath,
604
- pid: process.pid,
605
- });
606
-
607
- console.log(`roomyx serving ${absoluteLogPath} at ${handle.url}`);
608
- console.log(`room ID: ${entry.id} — attach with \`roomyx-client --room ${entry.id}\``);
609
-
610
- runUntilSignal(
611
- () => handle.close(),
612
- () => {
613
- // Archive before deregistering, not after: `archiveRoom` reads the
614
- // log to summarise it, and it reads better while the entry that says
615
- // where the log is still exists. The order also means a crash
616
- // between the two leaves the room recorded in history and still in
617
- // the registry, which the next prune resolves — rather than gone
618
- // from both.
619
- archiveRoom(defaultHistoryPath(registryPath), entry);
620
- deregisterRoom(registryPath, entry.id);
621
- },
622
- );
623
- },
624
- },
625
-
626
- "rooms list": {
627
- usage: "roomyx rooms list [flags]",
628
- summary: "live rooms, confirmed by a real call rather than by the file",
629
- flags: { registry: REGISTRY_FLAG },
630
- run: async ({ flags }) => {
631
- // `--registry` used to be accepted here and silently ignored: this
632
- // command took no arguments at all and read the default path, so
633
- // `rooms list --registry /nonexistent.json` printed "No live rooms"
634
- // about a different file.
635
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
636
- const { live, unconfirmed } = await listRoomsWithLiveness(registryPath);
637
- if (live.length === 0 && unconfirmed.length === 0) {
638
- // An empty registry and a registry whose rooms did not answer are
639
- // different facts, and the second used to print this same sentence —
640
- // which is how a serving room came to look like no room at all.
641
- console.log("No live rooms.");
642
- return;
643
- }
644
- for (const room of live) {
645
- console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
646
- }
647
- for (const room of unconfirmed) {
648
- // Kept in the registry, not claimed live: the probe did not answer, and
649
- // "did not answer" is not permission to delete a room that may be
650
- // serving. Named so the reader knows what to re-check.
651
- console.log(
652
- `${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt} did not answer — still registered`,
653
- );
654
- }
655
- },
656
- },
657
-
658
- setup: {
659
- usage: "roomyx setup [flags]",
660
- summary: "set this machine up, without touching the current project",
661
- notes:
662
- "The same picker `roomyx init` shows, narrowed to the rows that land on\n the machine: the skill for each agent runtime you use, and the persona\n library under ~/.roomyx. Nothing is created in the current directory, so\n this is what to run right after installing from npm — an npm lifecycle\n script cannot ask, because npm runs one with no terminal (CI, `npm ci`,\n Docker) and skips it entirely under --ignore-scripts.",
663
- flags: {
664
- yes: { type: "boolean", describe: "Apply the default selection without asking" },
665
- },
666
- run: async ({ flags }) => {
667
- const home = homedir();
668
- const cwd = process.cwd();
669
- // Its own config, under the home directory: `syncSkill` records the hash
670
- // of what it wrote so a later sync can tell "unchanged since we wrote it"
671
- // from "edited by someone", and a machine-wide install has no project
672
- // config to record into. Created here rather than demanded, because the
673
- // whole point of this command is that there is no project yet.
674
- const configPath = join(home, ".roomyx", "config.json");
675
- if (!existsSync(configPath)) {
676
- mkdirSync(join(home, ".roomyx"), { recursive: true });
677
- writeFileSync(configPath, JSON.stringify({ schemaVersion: 1 }, null, 2));
678
- }
679
-
680
- const { buildPlan, machineItems, selectedItems } = await import("./installer/init-plan");
681
- const { applyPlan } = await import("./installer/init-apply");
682
- const plan = machineItems(buildPlan({ cwd, personaFiles: personaCount(bundledPersonasPath()) }));
683
- // Ticked here, unticked in `init`, and the difference is the point. In a
684
- // project the machine-wide library is a second copy of one the project
685
- // already gets and the skill prefers. Here there is no project copy — so
686
- // leaving it off would set a machine up with a skill that casts its room
687
- // from personas that are nowhere on disk, which is the unfinished
688
- // installer this whole command exists to avoid.
689
- for (const item of plan) {
690
- if (item.id === "personas:user" && item.done === undefined) item.selected = true;
691
- }
692
-
693
- const interactive = process.stdout.isTTY === true && process.stdin.isTTY === true;
694
- if (!interactive && flags.yes !== true) {
695
- console.log("Not a terminal, so nothing was asked and nothing was written.");
696
- console.log(" roomyx setup --yes # the default selection, no prompt");
697
- return;
698
- }
699
-
700
- let chosen = plan;
701
- if (flags.yes !== true) {
702
- const { runInitPicker } = await import("./client/init-screen");
703
- const picked = await runInitPicker(plan);
704
- if (picked === null) {
705
- console.log("Cancelled — nothing was written.");
706
- return;
707
- }
708
- chosen = picked;
709
- }
710
-
711
- const results = applyPlan(selectedItems(chosen), {
712
- cwd,
713
- bundledSkillPath: bundledSkillPath(),
714
- bundledPersonasPath: bundledPersonasPath(),
715
- configPath,
716
- });
717
-
718
- for (const line of results) {
719
- console.log(`${line.ok ? " ok " : " !! "} ${line.label}`);
720
- console.log(` ${line.path} — ${line.message}`);
721
- }
722
- if (results.some((line) => line.ok)) {
723
- console.log("\nRestart your agent — skills are discovered at startup.");
724
- }
725
- console.log("\nNext, in a project: roomyx init");
726
- },
727
- },
728
-
729
- personas: {
730
- usage: "roomyx personas [flags]",
731
- summary: "install the bundled persona library into this project",
732
- notes:
733
- "Fifty interview personas, plus founder, technical and panel roles, plus\n a fifty-question interview questionnaire. A room is built out of these.\n\n The skill looks in .roomyx/personas first and falls back to\n ~/.roomyx/personas, so a project copy overrides the machine-wide one.\n\n Files that already exist are skipped, never overwritten: a persona is a\n file you are meant to edit.",
734
- flags: {
735
- target: { type: "string", describe: "Directory (default .roomyx/personas)" },
736
- global: { type: "boolean", describe: "Install for every project, into ~/.roomyx/personas" },
737
- force: { type: "boolean", describe: "Replace the library, moving the existing directory aside first" },
738
- },
739
- run: async ({ flags }) => {
740
- if (typeof flags.target === "string" && flags.global === true) {
741
- throw new ArgError("Pass either --target or --global, not both — they name different directories.");
742
- }
743
- const target =
744
- typeof flags.target === "string"
745
- ? resolve(flags.target)
746
- : flags.global === true
747
- ? join(homedir(), ".roomyx", "personas")
748
- : defaultPersonasPath();
749
- const result = installPersonas(bundledPersonasPath(), target, { force: flags.force === true });
750
-
751
- if (result.movedAside) console.log(`Moved the previous library to ${result.movedAside}`);
752
- console.log(`${result.written} file(s) written to ${result.targetDir}`);
753
- if (result.skipped > 0) {
754
- console.log(`${result.skipped} left as they were (already present — pass --force to replace the library)`);
755
- }
756
- },
757
- },
758
-
759
- "rooms history": {
760
- usage: "roomyx rooms history [flags]",
761
- summary: "rooms that have closed, newest first",
762
- notes:
763
- "History records what a room was and where its log is — it does not copy\n the log. Reopen one read-only with `roomyx-client --open <logPath>`, or\n pick from the list with `roomyx-client --archive`.",
764
- flags: { registry: REGISTRY_FLAG },
765
- run: async ({ flags }) => {
766
- const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
767
- const { rooms, unreadable } = readHistory(defaultHistoryPath(registryPath));
768
- if (rooms.length === 0) {
769
- console.log("No closed rooms recorded yet.");
770
- }
771
- for (const room of rooms) {
772
- const when = room.closedAt.slice(0, 16).replace("T", " ");
773
- const goal = room.goal === "" ? "(goal unavailable)" : room.goal;
774
- console.log(
775
- `${room.id} closed=${when} messages=${room.messages} participants=${room.participants} ${goal}`,
776
- );
777
- // The path on its own line: it is the argument to --open, and a goal
778
- // statement is long enough that putting them on one line means the
779
- // thing you have to copy is the thing that gets wrapped.
780
- console.log(` ${room.logPath}${room.logExists ? "" : " (log no longer at this path)"}`);
781
- }
782
- if (unreadable > 0) {
783
- console.log(`\n${unreadable} history line(s) could not be read and were skipped.`);
784
- }
785
- },
786
- },
787
-
788
- client: {
789
- usage: "roomyx client [flags]",
790
- summary: "attach the terminal UI (same as the roomyx-client binary)",
791
- flags: CLIENT_FLAGS,
792
- run: async ({ flags }) => {
793
- const { runClient } = await import("./client/index");
794
- await runClient(flags);
795
- },
796
- },
797
-
798
- mcp: {
799
- usage: "roomyx mcp [flags]",
800
- summary: "start the management MCP server",
801
- notes: "Default port 4320, so it does not collide with `roomyx serve`.",
802
- flags: {
803
- stdio: { type: "boolean", describe: "Speak MCP over stdin/stdout instead of HTTP (what an MCP client spawns)" },
804
- port: { type: "number", describe: "Listen port (default 4320; 0 picks an ephemeral one)" },
805
- host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
806
- "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
807
- registry: REGISTRY_FLAG,
808
- config: { type: "string", describe: "Config file (default .roomyx/config.json)" },
809
- },
810
- run: async ({ flags }) => {
811
- const managementOptions = {
812
- registryPath: typeof flags.registry === "string" ? flags.registry : defaultRegistryPath(),
813
- bundledSkillPath: bundledSkillPath(),
814
- configPath: typeof flags.config === "string" ? flags.config : defaultConfigPath(),
815
- };
816
-
817
- if (flags.stdio === true) {
818
- // The transport an MCP client actually wants: it spawns the process and
819
- // owns its lifetime, so there is no port to pick, nothing to leave
820
- // running, and no registration that points at something not started
821
- // yet. This is what `roomyx init` writes into `.mcp.json`.
822
- //
823
- // **Nothing may be printed to stdout here** — stdout is the protocol
824
- // channel, and one stray line of greeting is a parse error at the far
825
- // end. The HTTP branch below prints because it has a stdout to itself.
826
- const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
827
- const { createManagementMcpServer } = await import("./mcp-management/server");
828
- const server = createManagementMcpServer(managementOptions);
829
- await server.connect(new StdioServerTransport());
830
- // The client closes the pipe when it is done; there is no port to
831
- // release, so the signal handlers the HTTP branch installs would have
832
- // nothing to do.
833
- return;
834
- }
835
-
836
- const handle = await serveManagement(managementOptions, {
837
- port: typeof flags.port === "number" ? flags.port : undefined,
838
- host: typeof flags.host === "string" ? flags.host : undefined,
839
- acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
840
- });
841
-
842
- console.log(`roomyx mcp listening at ${handle.url}`);
843
- console.log("tools: roomyx.rooms.list, roomyx.skills.sync");
844
-
845
- runUntilSignal(() => handle.close());
846
- },
847
- },
848
-
849
- "skills sync": {
850
- usage: "roomyx skills sync --target <runtime|all|path> [flags]",
851
- summary: "install the bundled startup-room skill",
852
- notes:
853
- "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.",
854
- flags: {
855
- target: { type: "string", describe: `Required. ${NAMED_TARGETS.join(", ")}, all, or a literal path` },
856
- yes: { type: "boolean", describe: "Actually write" },
857
- "dry-run": { type: "boolean", describe: "Report only (the default)" },
858
- config: { type: "string", describe: "Config file the sync records hashes in" },
859
- },
860
- run: async ({ flags }) => {
861
- const target = flags.target;
862
- if (typeof target !== "string") {
863
- throw new ArgError(`Missing --target. Expected one of ${NAMED_TARGETS.join(", ")}, all, or a path.`);
864
- }
865
-
866
- const yes = flags.yes === true;
867
- // The gate itself lives in `syncSkill` now, computed once for every
868
- // surface — this line only forwards what the operator typed.
869
- const dryRun = flags["dry-run"] === true;
870
- const configPath = typeof flags.config === "string" ? flags.config : defaultConfigPath();
871
- if (!existsSync(configPath)) {
872
- throw new ArgError(`No ${configPath}. Run \`roomyx init\` first.`);
873
- }
874
-
875
- for (const { name, path } of resolveTargets(target)) {
876
- const result = syncSkillBundle({
877
- bundledSkillPath: bundledSkillPath(),
878
- targetPath: path,
879
- configPath,
880
- dryRun,
881
- yes,
882
- });
883
- console.log(name === path ? path : `${name}: ${path}`);
884
- for (const warning of result.warnings) console.log(` warning: ${warning}`);
885
- if (result.upToDate) {
886
- console.log(" already in sync — nothing written, no backup made");
887
- } else if (result.written) {
888
- console.log(result.backedUpTo ? ` written (backup: ${result.backedUpTo})` : " written");
889
- } else {
890
- // "not written" was the message whenever `dryRun` was false, which
891
- // after the gate moved into syncSkill meant the ordinary
892
- // no-flags run reported a bare refusal instead of the sentence that
893
- // says how to proceed. Branch on why nothing was written, not on
894
- // which flag was passed.
895
- console.log(result.wouldWrite ? " would write (pass --yes to apply)" : " not written");
896
- }
897
- }
898
- },
899
- },
29
+ init: initCommand,
30
+ "room new": roomNew,
31
+ "room append": roomAppend,
32
+ "room delta": roomDelta,
33
+ "room commands": roomCommands,
34
+ "room ack": roomAck,
35
+ serve: serveCommand,
36
+ "rooms list": roomsList,
37
+ setup: setupCommand,
38
+ personas: personasCommand,
39
+ "rooms history": roomsHistory,
40
+ client: clientCommand,
41
+ mcp: mcpCommand,
42
+ "skills sync": skillsSync,
43
+ "experiment plan": experimentPlan,
44
+ "experiment new": experimentNew,
900
45
  };
901
46
 
902
47
  /** package.json ships in the tarball (see `files`), so this resolves for an installed copy too. */