@mrciphersmith/roomyx 0.12.2 → 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 +91 -0
  2. package/README.md +84 -4
  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
@@ -0,0 +1,40 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve } from "node:path";
3
+ import { installPersonas } from "../installer/personas";
4
+ import { ArgError } from "./args";
5
+ import { bundledPersonasPath } from "./shared";
6
+ import type { Command } from "./shared";
7
+
8
+ function defaultPersonasPath(cwd: string = process.cwd()): string {
9
+ return join(cwd, ".roomyx", "personas");
10
+ }
11
+
12
+ export const personasCommand: Command = {
13
+ usage: "roomyx personas [flags]",
14
+ summary: "install the bundled persona library into this project",
15
+ notes:
16
+ "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.",
17
+ flags: {
18
+ target: { type: "string", describe: "Directory (default .roomyx/personas)" },
19
+ global: { type: "boolean", describe: "Install for every project, into ~/.roomyx/personas" },
20
+ force: { type: "boolean", describe: "Replace the library, moving the existing directory aside first" },
21
+ },
22
+ run: async ({ flags }) => {
23
+ if (typeof flags.target === "string" && flags.global === true) {
24
+ throw new ArgError("Pass either --target or --global, not both — they name different directories.");
25
+ }
26
+ const target =
27
+ typeof flags.target === "string"
28
+ ? resolve(flags.target)
29
+ : flags.global === true
30
+ ? join(homedir(), ".roomyx", "personas")
31
+ : defaultPersonasPath();
32
+ const result = installPersonas(bundledPersonasPath(), target, { force: flags.force === true });
33
+
34
+ if (result.movedAside) console.log(`Moved the previous library to ${result.movedAside}`);
35
+ console.log(`${result.written} file(s) written to ${result.targetDir}`);
36
+ if (result.skipped > 0) {
37
+ console.log(`${result.skipped} left as they were (already present — pass --force to replace the library)`);
38
+ }
39
+ },
40
+ };
@@ -0,0 +1,357 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { findRoomServing, probeRoomState, listRoomsWithLiveness } from "../installer/registry";
4
+ import { appendMessages, LEGAL_KINDS } from "../log/write";
5
+ import type { AppendMessageOptions } from "../log/write";
6
+ import { isLeaseHolderAlive, readWriterLease, tombstoneWriterLease, writerLeasePathFor } from "../writer-lease";
7
+ import { MESSAGE_KINDS } from "../log/schema";
8
+ import { LogWriteError } from "../log/write";
9
+ import type { MessageEnvelope } from "../log/types";
10
+ import { ArgError } from "./args";
11
+ import type { FlagValues } from "./args";
12
+ import { REGISTRY_FLAG, defaultRegistryPath } from "./shared";
13
+ import type { Command } from "./shared";
14
+
15
+ /**
16
+ * Turns the flags into the messages to write, or refuses.
17
+ *
18
+ * Four ways in, and they do not compose: an envelope says everything, so a
19
+ * `--from` beside it is an ambiguity rather than an override — and guessing
20
+ * which one the caller meant is how a body goes into the wrong speaker's mouth.
21
+ */
22
+ function pendingAppends(flags: FlagValues): AppendMessageOptions[] {
23
+ // Two different things are being chosen here, and conflating them was wrong:
24
+ // `--json` and `--many` carry a whole envelope (speaker included), while
25
+ // `--body` and `--body-file` carry only the body and still need `--from`.
26
+ // Refusing `--body-file --from b` refused a combination that has no ambiguity
27
+ // in it at all.
28
+ const envelopeSources = [flags.json !== undefined, flags.many === true].filter(Boolean).length;
29
+ if (envelopeSources > 1) throw new ArgError("Use one of --json or --many, not both.");
30
+ const bodySources = [flags.body !== undefined, flags["body-file"] !== undefined].filter(Boolean).length;
31
+ if (bodySources > 1) throw new ArgError("Use one of --body or --body-file, not both.");
32
+
33
+ if (envelopeSources === 1) {
34
+ const conflicting = ["from", "body", "body-file", "kind", "in-reply-to", "read-through"].filter((f) => flags[f] !== undefined);
35
+ if (conflicting.length > 0) {
36
+ // An envelope says everything. Silently preferring one source is how a
37
+ // body ends up in the log under a speaker nobody chose.
38
+ throw new ArgError(
39
+ `--json/--many carry the whole envelope, so --${conflicting.join(", --")} cannot be combined with them.`,
40
+ );
41
+ }
42
+ return flags.many === true ? parseBatch(readStdin()) : [envelopeFrom(flags.json as string)];
43
+ }
44
+
45
+ const from = flags.from;
46
+ if (typeof from !== "string" || from === "") {
47
+ throw new ArgError("Both --from and --body are required (or pass --json, --body-file or --many).");
48
+ }
49
+ const body = typeof flags["body-file"] === "string" ? bodyFromFile(flags["body-file"]) : flags.body;
50
+ if (typeof body !== "string") throw new ArgError("Both --from and --body are required.");
51
+
52
+ const kind = typeof flags.kind === "string" ? flags.kind : undefined;
53
+ if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
54
+ throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
55
+ }
56
+ const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
57
+ if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
58
+ throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
59
+ }
60
+ const readThrough = typeof flags["read-through"] === "number" ? flags["read-through"] : undefined;
61
+ if (readThrough !== undefined && (!Number.isInteger(readThrough) || readThrough < 0)) {
62
+ throw new ArgError(`--read-through must be a whole number of at least 0, not ${readThrough}.`);
63
+ }
64
+ return [{ from, body, kind: kind as MessageEnvelope["kind"], inReplyTo, readThrough }];
65
+ }
66
+
67
+ function readStdin(): string {
68
+ if (process.stdin.isTTY === true) {
69
+ // Reading fd 0 from a terminal blocks until Ctrl-D, which reads as a hang.
70
+ throw new ArgError("This flag reads the message from stdin, and stdin is a terminal. Pipe the text in, or use --body.");
71
+ }
72
+ return readFileSync(0, "utf8");
73
+ }
74
+
75
+ function bodyFromFile(file: string): string {
76
+ // A trailing newline is what every editor and every `echo` adds; it is not
77
+ // part of what the speaker said, and it would land inside the quoted body.
78
+ const raw = file === "-" ? readStdin() : readFileSync(resolve(file), "utf8");
79
+ return raw.replace(/\r?\n$/, "");
80
+ }
81
+
82
+ const ENVELOPE_KEYS = ["from", "body", "kind", "in_reply_to", "change", "read_through"] as const;
83
+
84
+ /**
85
+ * Parses one envelope, refusing keys that would silently vanish.
86
+ *
87
+ * An unknown key is a refusal rather than something ignored: `seq` and `type`
88
+ * are assigned by the writer, and a caller who passes one believes they chose
89
+ * it — so accepting the envelope while dropping their value is the one answer
90
+ * that cannot be discovered from the log.
91
+ */
92
+ function envelopeFrom(text: string): AppendMessageOptions {
93
+ let parsed: unknown;
94
+ try {
95
+ parsed = JSON.parse(text) as unknown;
96
+ } catch (error) {
97
+ throw new ArgError(`--json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
98
+ }
99
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
100
+ throw new ArgError("--json must be a JSON object.");
101
+ }
102
+ const envelope = parsed as Record<string, unknown>;
103
+ for (const key of Object.keys(envelope)) {
104
+ if (!(ENVELOPE_KEYS as readonly string[]).includes(key)) {
105
+ throw new ArgError(`--json has an unknown key "${key}". Allowed: ${ENVELOPE_KEYS.join(", ")}.`);
106
+ }
107
+ }
108
+ const { from, body, kind, in_reply_to: inReplyTo, change, read_through: readThrough } = envelope;
109
+ if (typeof from !== "string" || from === "") throw new ArgError('--json needs a non-empty "from".');
110
+ if (typeof body !== "string") throw new ArgError('--json needs a string "body".');
111
+ if (kind !== undefined && (typeof kind !== "string" || !(MESSAGE_KINDS as readonly string[]).includes(kind))) {
112
+ throw new ArgError(`--json "kind" must be one of: ${LEGAL_KINDS}.`);
113
+ }
114
+ if (inReplyTo !== undefined && (typeof inReplyTo !== "number" || !Number.isInteger(inReplyTo) || inReplyTo < 1)) {
115
+ throw new ArgError('--json "in_reply_to" must be a whole number of at least 1.');
116
+ }
117
+ if (readThrough !== undefined && (typeof readThrough !== "number" || !Number.isInteger(readThrough) || readThrough < 0)) {
118
+ throw new ArgError('--json "read_through" must be a whole number of at least 0.');
119
+ }
120
+ // The change is passed through unexamined here and validated where the rule
121
+ // lives (the log's own schema, imported by the writer). Re-checking its shape
122
+ // in the CLI would be a second copy of a rule the log already owns — and the
123
+ // two copies would drift, which is the failure `src/log/schema.ts` exists to
124
+ // make impossible.
125
+ if (change !== undefined && (typeof change !== "object" || change === null)) {
126
+ throw new ArgError('--json "change" must be an object.');
127
+ }
128
+ return {
129
+ from,
130
+ body,
131
+ kind: kind as MessageEnvelope["kind"],
132
+ inReplyTo: inReplyTo as number | undefined,
133
+ change: change as MessageEnvelope["change"],
134
+ readThrough: readThrough as number | undefined,
135
+ };
136
+ }
137
+
138
+ function parseBatch(text: string): AppendMessageOptions[] {
139
+ const lines = text.split("\n").filter((line) => line.trim().length > 0);
140
+ if (lines.length === 0) throw new ArgError("--many read no envelopes from stdin.");
141
+ return lines.map((line, index) => {
142
+ try {
143
+ return envelopeFrom(line);
144
+ } catch (error) {
145
+ throw new ArgError(`--many line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
146
+ }
147
+ });
148
+ }
149
+
150
+ /**
151
+ * Writes the batch, or none of it. `appendMessages` allocates consecutive `seq`
152
+ * and validates every envelope before the first byte, so a refused batch leaves
153
+ * the log exactly as it was.
154
+ */
155
+ function writeAll(path: string, pending: AppendMessageOptions[]) {
156
+ try {
157
+ return appendMessages(path, pending);
158
+ } catch (error) {
159
+ if (error instanceof LogWriteError) throw new ArgError(error.message);
160
+ throw error;
161
+ }
162
+ }
163
+
164
+ /** The holder a take-over displaced, when there was one. */
165
+ function stateBefore(lease: import("../writer-lease").LeaseState): { pid: number; at: number } | undefined {
166
+ if (lease.held) return { pid: lease.lease.pid, at: lease.lease.at };
167
+ // A stale lease still identifies the writer that stopped: recording it is the
168
+ // difference between a log that says "someone took this over" and one that
169
+ // says who from.
170
+ //
171
+ // `released` deliberately displaces nobody. The tombstone already records who
172
+ // was taken over, and naming that pid again in a second take-over's trace
173
+ // would report a writer being displaced twice.
174
+ return lease.reason === "stale" ? { pid: lease.last.pid, at: lease.last.at } : undefined;
175
+ }
176
+
177
+ export const roomAppend: Command = {
178
+ usage: "roomyx room append <path> (--from <id> --body <text> | --json <envelope> | --body-file <file> | --many) [flags]",
179
+ summary: "append a message to a room log",
180
+ notes:
181
+ "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.",
182
+ flags: {
183
+ from: { type: "string", describe: "Participant id" },
184
+ body: { type: "string", describe: "The message" },
185
+ json: { type: "string", describe: "A whole envelope: {from, body, kind?, in_reply_to?}" },
186
+ "body-file": { type: "string", describe: "Read the body from a file, or - for stdin" },
187
+ many: { type: "boolean", describe: "Read a JSONL batch of envelopes from stdin; all of them or none" },
188
+ kind: { type: "string", describe: "Message kind, e.g. challenge" },
189
+ "in-reply-to": { type: "number", describe: "seq of the message replied to" },
190
+ "read-through": { type: "number", describe: "Highest seq the author had seen; refuses if others wrote past it (D-21)" },
191
+ "allow-unread": { type: "boolean", describe: "With --read-through: write even though the author missed messages" },
192
+ "take-over": { type: "boolean", describe: "Write when the room is live but its writer is gone" },
193
+ registry: REGISTRY_FLAG,
194
+ },
195
+ run: async ({ positionals, flags }) => {
196
+ const path = positionals[0];
197
+ if (!path) throw new ArgError("Missing <path>.");
198
+ const absolute = resolve(path);
199
+
200
+ const takeOver = flags["take-over"] === true;
201
+
202
+ // Absolute, because the lease lives beside the registry and this process's
203
+ // cwd is not the next process's: a relative `--registry` made the lease
204
+ // land in a different directory depending on where the command was run.
205
+ const absoluteRegistry = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
206
+ const leasePath = writerLeasePathFor(absoluteRegistry, absolute);
207
+
208
+ // Across BOTH lists: an entry whose first probe timed out is `unconfirmed`,
209
+ // and it may still have a dispatcher attached — which is the evidence this
210
+ // guard needs. Searching only the confirmed list is how "the machine was
211
+ // busy" turns into "nothing is writing into this log".
212
+ const serving = findRoomServing(absolute, await listRoomsWithLiveness(absoluteRegistry));
213
+
214
+ // Read the lease BEFORE the probe, and independently of its outcome. A
215
+ // liveness probe that times out says "could not reach it", which is not
216
+ // "nothing is writing into it" — and reading the lease only once the probe
217
+ // succeeded meant a busy machine wrote into a room whose dispatcher was
218
+ // perfectly alive.
219
+ const lease = readWriterLease(leasePath);
220
+ const dispatched = serving !== undefined ? ((await probeRoomState(serving))?.dispatcherAttached ?? undefined) : undefined;
221
+
222
+ // Two independent pieces of evidence that someone else is writing: a live
223
+ // dispatcher, and a lease somebody is refreshing. The second exists because
224
+ // the first only holds for a server that was started with a lease path.
225
+ //
226
+ // A held lease is only evidence while the process that wrote it exists. It
227
+ // is a claim made by a pid, and checking that pid costs one signal — while
228
+ // not checking it meant a lease left behind by a process that had already
229
+ // gone refused every write for the whole stale window, naming a pid the
230
+ // operator could look up and not find. Nothing that is not running can be
231
+ // writing into this log, so this narrows what counts as a live writer
232
+ // without widening what may write beside one.
233
+ const liveHolder = lease.held && isLeaseHolderAlive(lease.lease.pid) ? lease.lease : undefined;
234
+ const writerPresent = liveHolder !== undefined || dispatched === true;
235
+ // A fresh lease whose holder is gone is NOT the "a writer stopped here"
236
+ // case: that one is `stale`, and it still requires --take-over below. This
237
+ // one is provably nobody, so it is allowed — said out loud on stderr
238
+ // because a recorded lease that the CLI decides to disregard is exactly the
239
+ // kind of thing that should not happen quietly.
240
+ const abandonedHold = lease.held && liveHolder === undefined ? lease.lease : undefined;
241
+ const writerWasThere = !writerPresent && !lease.held && lease.reason === "stale";
242
+
243
+ if (writerPresent) {
244
+ // Two different reasons to refuse, and they need different advice: a
245
+ // lease that is merely stale will expire by itself, while a room that
246
+ // reports a dispatcher will keep reporting one until the server is
247
+ // stopped — waiting would be advice that never comes true.
248
+ const advice =
249
+ dispatched === true
250
+ ? `Stop the server that is running the room; once it is gone, --take-over will let you write to this log.`
251
+ : `Wait for that lease to expire (a writer that is running refreshes it), or stop the process holding it.`;
252
+ throw new ArgError(
253
+ `A writer is live in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`}` +
254
+ // `liveHolder`, not `lease.held`: naming a pid is only useful if the
255
+ // pid is findable, and an unfindable one is what made this message
256
+ // untrustworthy.
257
+ `${liveHolder === undefined ? " — the room reports a dispatcher attached" : ` — pid ${liveHolder.pid}`}. ` +
258
+ `Two writers into one append-only log is the race D-01 exists to prevent, and nothing overrides a writer ` +
259
+ `that is still there. ${advice}`,
260
+ );
261
+ }
262
+ if (writerWasThere && !takeOver) {
263
+ throw new ArgError(
264
+ `A writer was in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`} and is gone — ` +
265
+ `nothing holds the lease now. Writing means taking ownership from a room that looks supervised. ` +
266
+ `Pass --take-over to do that deliberately; the log will record it.`,
267
+ );
268
+ }
269
+
270
+ // A live room, and no evidence of a writer — say so rather than drop it.
271
+ //
272
+ // `serving` was already computed for the refusal above and, when nothing
273
+ // holds a lease, was silently discarded. That silence is wrong in exactly
274
+ // the case that matters: an agent dispatcher runs `roomyx serve` and
275
+ // writes with `roomyx room append`, a fresh process each time, so it
276
+ // never holds a lease and the room never reports a dispatcher. Every
277
+ // append into a room an agent is running therefore looks, from here, like
278
+ // an append into an unattended log.
279
+ //
280
+ // A note, not a refusal: there is nothing here that can tell a dispatcher
281
+ // from a stranger, so refusing would block the legitimate writer — which
282
+ // was tried and reverted. The log itself is safe either way; `seq`
283
+ // allocation is under a lock and that is tested. What is at risk is the
284
+ // conversation reading as one when it was two, and a line on stderr is
285
+ // what lets a second writer notice before adding to it.
286
+ //
287
+ // stderr, because stdout carries `Appended seq N from X` and is parsed.
288
+ if (serving !== undefined && !writerPresent && !writerWasThere) {
289
+ console.error(
290
+ `Note: room ${serving.id} is serving ${absolute}. Nothing holds the writer lease, so this append is ` +
291
+ `allowed — but roomyx cannot see whether an agent is dispatching that room. If one is, you are writing ` +
292
+ `into a conversation it is also writing into.`,
293
+ );
294
+ }
295
+
296
+ // A lease that is still inside its window but whose holder has exited. Not
297
+ // a refusal — a dead process is not writing anything — but not silence
298
+ // either: this is a writer that stopped without releasing, and the operator
299
+ // should hear which pid it was.
300
+ if (abandonedHold !== undefined) {
301
+ console.error(
302
+ `Note: the writer lease on ${absolute} names pid ${abandonedHold.pid}, which is no longer running. ` +
303
+ `Nothing is writing into this log, so this append is allowed.`,
304
+ );
305
+ }
306
+
307
+ // Parsed only after the refusal: an operator whose command is going to be
308
+ // rejected should not be made to pipe a batch in first, and a reader that
309
+ // blocks on stdin while holding a decision helps nobody.
310
+ const allowUnread = flags["allow-unread"] === true;
311
+ if (allowUnread && flags["read-through"] === undefined && !flags.json && flags.many !== true) {
312
+ throw new ArgError("--allow-unread only qualifies --read-through; there is nothing to allow without it.");
313
+ }
314
+ const pending = pendingAppends(flags).map((options) => (allowUnread ? { ...options, allowUnread } : options));
315
+
316
+ const displaced = takeOver || writerWasThere ? stateBefore(lease) : undefined;
317
+ const takingOver = takeOver || writerWasThere;
318
+
319
+ // One batch, one lock section: the take-over trace goes in WITH the
320
+ // messages it describes. Written as a second call it could fail on its
321
+ // own, and a room written by hand while its writer was absent would read
322
+ // afterwards as supervised — the one thing the trace exists to prevent.
323
+ const written = writeAll(absolute, [
324
+ ...pending,
325
+ ...(takingOver
326
+ ? [
327
+ {
328
+ from: "owner",
329
+ kind: "status" as const,
330
+ body:
331
+ `--take-over: ${pending.length} message(s) appended to ${absolute}` +
332
+ `${serving === undefined ? "" : ` while room ${serving.id} was live`} with no live writer` +
333
+ `${displaced === undefined ? " (no lease was held)" : ` (took over from pid ${displaced.pid})`}`,
334
+ },
335
+ ]
336
+ : []),
337
+ ]);
338
+
339
+ if (takingOver) {
340
+ // A tombstone, not a hold. The token is still replaced — that is what
341
+ // stops a writer which was merely paused from refreshing the lease it
342
+ // lost and writing beside whoever displaced it, and it is the whole
343
+ // reason a take-over is not just a flag on the write. What it must not do
344
+ // is claim the pen: this process exits within milliseconds and calls
345
+ // `releaseWriterLease` nowhere, so a hold taken here is a hold nothing
346
+ // ever gives back. Acquiring one turned each deliberate recovery into
347
+ // thirty seconds of "a writer is live — pid <already exited>" followed by
348
+ // a permanent demand to keep recovering.
349
+ tombstoneWriterLease(leasePath, {
350
+ pid: process.pid,
351
+ ...(displaced === undefined ? {} : { takeOverFrom: displaced }),
352
+ });
353
+ }
354
+
355
+ for (const message of written) console.log(`Appended seq ${message.seq} from ${message.from}.`);
356
+ },
357
+ };
@@ -0,0 +1,91 @@
1
+ import { resolve } from "node:path";
2
+ import { callRoomTool } from "../installer/room-tool";
3
+ import { createRoomLog, parseRoster } from "../log/write";
4
+ import { ArgError } from "./args";
5
+ import { REGISTRY_FLAG, defaultRegistryPath, servingRoomFor } from "./shared";
6
+ import type { Command } from "./shared";
7
+
8
+ export const roomNew: Command = {
9
+ usage: "roomyx room new <path> --goal <statement> [flags]",
10
+ summary: "create a room log",
11
+ notes: "Refuses to overwrite an existing log — a room log is append-only.",
12
+ flags: {
13
+ goal: { type: "string", describe: "Required. What the room is for, in one sentence" },
14
+ criteria: { type: "string", describe: "Success criteria, stored in the goal contract" },
15
+ roster: { type: "string", describe: "Participants, as id:Name,id2:Name2" },
16
+ },
17
+ run: async ({ positionals, flags }) => {
18
+ const path = positionals[0];
19
+ if (!path) throw new ArgError("Missing <path>.");
20
+ const goalStatement = flags.goal;
21
+ if (typeof goalStatement !== "string") {
22
+ throw new ArgError("Missing --goal. A room without a stated goal has nothing to converge on.");
23
+ }
24
+ const absolute = resolve(path);
25
+ createRoomLog(absolute, {
26
+ goalStatement,
27
+ criteria: typeof flags.criteria === "string" ? flags.criteria : undefined,
28
+ roster: typeof flags.roster === "string" ? parseRoster(flags.roster) : [],
29
+ });
30
+ console.log(`Created ${absolute}`);
31
+ console.log(`serve it with \`roomyx serve ${path}\``);
32
+ },
33
+ };
34
+
35
+ export const roomDelta: Command = {
36
+ usage: "roomyx room delta <logPath> --for <agentId> [flags]",
37
+ summary: "what a participant has not seen yet",
38
+ notes:
39
+ "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.",
40
+ flags: {
41
+ for: { type: "string", describe: "Required. Participant id" },
42
+ since: { type: "number", describe: "Cursor to use instead of that participant's last message" },
43
+ registry: REGISTRY_FLAG,
44
+ },
45
+ run: async ({ positionals, flags }) => {
46
+ const path = positionals[0];
47
+ if (!path) throw new ArgError("Missing <logPath>.");
48
+ const agentId = flags.for;
49
+ if (typeof agentId !== "string" || agentId === "") throw new ArgError("Missing --for <agentId>.");
50
+ const absolute = resolve(path);
51
+ const registryPath = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
52
+ const room = await servingRoomFor(absolute, registryPath);
53
+ const args: Record<string, unknown> = { agent_id: agentId };
54
+ if (typeof flags.since === "number") args.since_seq = flags.since;
55
+ console.log(JSON.stringify(await callRoomTool(room, "room.get_delta_for", args), null, 2));
56
+ },
57
+ };
58
+
59
+ export const roomCommands: Command = {
60
+ usage: "roomyx room commands <logPath> [flags]",
61
+ summary: "owner commands waiting for the dispatcher",
62
+ notes:
63
+ "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`.",
64
+ flags: { registry: REGISTRY_FLAG },
65
+ run: async ({ positionals, flags }) => {
66
+ const path = positionals[0];
67
+ if (!path) throw new ArgError("Missing <logPath>.");
68
+ const absolute = resolve(path);
69
+ const registryPath = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
70
+ const room = await servingRoomFor(absolute, registryPath);
71
+ console.log(JSON.stringify(await callRoomTool(room, "room.get_pending_owner_commands", {}), null, 2));
72
+ },
73
+ };
74
+
75
+ export const roomAck: Command = {
76
+ usage: "roomyx room ack <logPath> <commandId> [flags]",
77
+ summary: "say an owner command has been dealt with",
78
+ notes:
79
+ "Without this, `pending` grows forever and stops meaning \"not yet handled\".",
80
+ flags: { registry: REGISTRY_FLAG },
81
+ run: async ({ positionals, flags }) => {
82
+ const path = positionals[0];
83
+ const id = positionals[1];
84
+ if (!path) throw new ArgError("Missing <logPath>.");
85
+ if (!id) throw new ArgError("Missing <commandId>. `roomyx room commands <logPath>` lists them.");
86
+ const absolute = resolve(path);
87
+ const registryPath = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
88
+ const room = await servingRoomFor(absolute, registryPath);
89
+ console.log(JSON.stringify(await callRoomTool(room, "room.ack_owner_command", { id }), null, 2));
90
+ },
91
+ };
@@ -0,0 +1,65 @@
1
+ import { listRoomsWithLiveness } from "../installer/registry";
2
+ import { defaultHistoryPath, readHistory } from "../installer/history";
3
+ import { REGISTRY_FLAG, defaultRegistryPath } from "./shared";
4
+ import type { Command } from "./shared";
5
+
6
+ export const roomsList: Command = {
7
+ usage: "roomyx rooms list [flags]",
8
+ summary: "live rooms, confirmed by a real call rather than by the file",
9
+ flags: { registry: REGISTRY_FLAG },
10
+ run: async ({ flags }) => {
11
+ // `--registry` used to be accepted here and silently ignored: this
12
+ // command took no arguments at all and read the default path, so
13
+ // `rooms list --registry /nonexistent.json` printed "No live rooms"
14
+ // about a different file.
15
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
16
+ const { live, unconfirmed } = await listRoomsWithLiveness(registryPath);
17
+ if (live.length === 0 && unconfirmed.length === 0) {
18
+ // An empty registry and a registry whose rooms did not answer are
19
+ // different facts, and the second used to print this same sentence —
20
+ // which is how a serving room came to look like no room at all.
21
+ console.log("No live rooms.");
22
+ return;
23
+ }
24
+ for (const room of live) {
25
+ console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
26
+ }
27
+ for (const room of unconfirmed) {
28
+ // Kept in the registry, not claimed live: the probe did not answer, and
29
+ // "did not answer" is not permission to delete a room that may be
30
+ // serving. Named so the reader knows what to re-check.
31
+ console.log(
32
+ `${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt} did not answer — still registered`,
33
+ );
34
+ }
35
+ },
36
+ };
37
+
38
+ export const roomsHistory: Command = {
39
+ usage: "roomyx rooms history [flags]",
40
+ summary: "rooms that have closed, newest first",
41
+ notes:
42
+ "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`.",
43
+ flags: { registry: REGISTRY_FLAG },
44
+ run: async ({ flags }) => {
45
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
46
+ const { rooms, unreadable } = readHistory(defaultHistoryPath(registryPath));
47
+ if (rooms.length === 0) {
48
+ console.log("No closed rooms recorded yet.");
49
+ }
50
+ for (const room of rooms) {
51
+ const when = room.closedAt.slice(0, 16).replace("T", " ");
52
+ const goal = room.goal === "" ? "(goal unavailable)" : room.goal;
53
+ console.log(
54
+ `${room.id} closed=${when} messages=${room.messages} participants=${room.participants} ${goal}`,
55
+ );
56
+ // The path on its own line: it is the argument to --open, and a goal
57
+ // statement is long enough that putting them on one line means the
58
+ // thing you have to copy is the thing that gets wrapped.
59
+ console.log(` ${room.logPath}${room.logExists ? "" : " (log no longer at this path)"}`);
60
+ }
61
+ if (unreadable > 0) {
62
+ console.log(`\n${unreadable} history line(s) could not be read and were skipped.`);
63
+ }
64
+ },
65
+ };
@@ -0,0 +1,84 @@
1
+ import { resolve } from "node:path";
2
+ import { serve } from "../server/serve";
3
+ import { registerRoom, deregisterRoom } from "../installer/registry";
4
+ import { archiveRoom, defaultHistoryPath } from "../installer/history";
5
+ import { ArgError } from "./args";
6
+ import { REGISTRY_FLAG, defaultRegistryPath, runUntilSignal } from "./shared";
7
+ import type { Command } from "./shared";
8
+
9
+ export const serveCommand: Command = {
10
+ usage: "roomyx serve <logPath> [flags]",
11
+ summary: "serve a room log over MCP",
12
+ flags: {
13
+ port: { type: "number", describe: "Listen port (default 4319; 0 picks an ephemeral one)" },
14
+ host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
15
+ "acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
16
+ registry: REGISTRY_FLAG,
17
+ },
18
+ run: async ({ positionals, flags }) => {
19
+ const logPath = positionals[0];
20
+ if (!logPath) throw new ArgError("Missing <logPath>.");
21
+
22
+ // Absolute, because the registry outlives this process's working
23
+ // directory: `roomyx-client` resolves rooms from wherever the person
24
+ // happened to run it, and a relative logPath means nothing there.
25
+ const absoluteLogPath = resolve(logPath);
26
+ // Resolved before binding: the writer lease lives beside the registry, and
27
+ // a server that acquires one after it starts answering would leave a
28
+ // window where a live dispatcher looks like no writer at all.
29
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
30
+ const handle = await serve(absoluteLogPath, {
31
+ port: typeof flags.port === "number" ? flags.port : undefined,
32
+ host: typeof flags.host === "string" ? flags.host : undefined,
33
+ acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
34
+ // No `writerLeasePath`, deliberately, and this is worth stating because
35
+ // it was passed here and silently discarded on every serve.
36
+ //
37
+ // `serve()` takes the lease only when a dispatcher is attached, and
38
+ // "attached" means an *embedder* supplied an `onOwnerCommand` callback.
39
+ // `roomyx serve` never supplies one — an agent dispatcher has no
40
+ // callback to give; it reads `room.get_pending_owner_commands` instead.
41
+ // So the argument could never be used, while reading like a lease was
42
+ // being taken.
43
+ //
44
+ // Making the CLI declare a dispatcher was tried and is WRONG: the lease
45
+ // would be held by the server process, while the writer is the agent
46
+ // running `roomyx room append` in a different process each time — so
47
+ // the dispatcher would be locked out of its own room. Two dispatcher
48
+ // models exist (embedder writes in-process; agent writes by CLI) and
49
+ // only the first is expressible today. Recorded rather than patched.
50
+ });
51
+
52
+ const entry = registerRoom(registryPath, {
53
+ port: handle.port,
54
+ logPath: absoluteLogPath,
55
+ pid: process.pid,
56
+ // The token goes where the port goes. Anything that can find this room
57
+ // can find its credential, and nothing else has to be told — which is the
58
+ // whole of how `roomyx-client`, `rooms list` and the room commands keep
59
+ // working without a new argument between them.
60
+ token: handle.token,
61
+ });
62
+
63
+ // Deliberately NOT printed. The port and the room id are the two things a
64
+ // person needs and the two things they paste into a terminal, an issue or a
65
+ // chat; the token is a credential, and stdout is a scrollback, a CI log and
66
+ // a `tee`. Whoever needs it reads the registry entry.
67
+ console.log(`roomyx serving ${absoluteLogPath} at ${handle.url}`);
68
+ console.log(`room ID: ${entry.id} — attach with \`roomyx-client --room ${entry.id}\``);
69
+
70
+ runUntilSignal(
71
+ () => handle.close(),
72
+ () => {
73
+ // Archive before deregistering, not after: `archiveRoom` reads the
74
+ // log to summarise it, and it reads better while the entry that says
75
+ // where the log is still exists. The order also means a crash
76
+ // between the two leaves the room recorded in history and still in
77
+ // the registry, which the next prune resolves — rather than gone
78
+ // from both.
79
+ archiveRoom(defaultHistoryPath(registryPath), entry);
80
+ deregisterRoom(registryPath, entry.id);
81
+ },
82
+ );
83
+ },
84
+ };