@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
@@ -47,6 +47,7 @@ export async function runClient(flags: FlagValues): Promise<void> {
47
47
  const resolved = await resolveConnectionUrl({
48
48
  connect: typeof flags.connect === "string" ? flags.connect : undefined,
49
49
  room: typeof flags.room === "string" ? flags.room : undefined,
50
+ token: typeof flags.token === "string" ? flags.token : undefined,
50
51
  registryPath,
51
52
  });
52
53
 
@@ -68,11 +69,23 @@ export async function runClient(flags: FlagValues): Promise<void> {
68
69
  process.exit(1);
69
70
  }
70
71
 
71
- await runLive(resolved.url);
72
+ // Said out loud rather than left to a spinner. Without a token the room
73
+ // answers 401, the client reports `disconnected` and retries with backoff —
74
+ // which is indistinguishable, on screen, from a room that is not running. The
75
+ // one way to reach this is `--connect` against a room this registry does not
76
+ // know, so the sentence names the flag that fixes it.
77
+ if (resolved.token === undefined) {
78
+ console.error(
79
+ "No room token found for this address. A roomyx room requires the per-room token recorded in its " +
80
+ "registry entry; pass it with --token <token>, or attach by --room <id> so it is looked up for you.",
81
+ );
82
+ }
83
+
84
+ await runLive(resolved.url, resolved.token);
72
85
  }
73
86
 
74
87
  /** Attached to a room that is still running: polling, owner commands, liveness. */
75
- async function runLive(url: string): Promise<void> {
88
+ async function runLive(url: string, token: string | undefined): Promise<void> {
76
89
  const renderer = await createCliRenderer({ targetFps: 30 });
77
90
 
78
91
  let messageCount = 0;
@@ -127,7 +140,7 @@ async function runLive(url: string): Promise<void> {
127
140
  }
128
141
 
129
142
  const roomClient = new RoomClient(
130
- { url },
143
+ { url, ...(token === undefined ? {} : { token }) },
131
144
  {
132
145
  onConnectionChange: (status) => {
133
146
  const previous = connection;
@@ -1,17 +1,42 @@
1
1
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
2
+ import type { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
+ import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
4
+ import { roomTransport } from "../room-token";
3
5
  import type { MessageEnvelope, RoomState } from "../log/types";
4
6
  import type { TranscriptPage } from "../server/tools/get-transcript";
5
7
  import type { OwnerCommandResult } from "../server/index";
8
+ import { LOG_RESOURCE_URI } from "../server/index";
6
9
 
7
10
  export type ConnectionStatus = "connecting" | "connected" | "disconnected";
8
11
 
9
12
  export interface RoomClientOptions {
10
13
  url: string;
14
+ /**
15
+ * The room's per-room token, from the registry entry the URL was resolved
16
+ * from. Presented on every request — including the DELETE that ends the
17
+ * session, without which a close would be refused and leak a session server
18
+ * side.
19
+ *
20
+ * Optional only because `--connect <url>` can name a room this machine never
21
+ * registered. A room that refuses the connection reports `disconnected` and the
22
+ * client keeps retrying with backoff, so a missing token looks like a room that
23
+ * is not there — which is why the CLI says so out loud rather than leaving the
24
+ * reader to infer it from a spinner.
25
+ */
26
+ token?: string;
11
27
  /** How often to poll room.get_state. Roster/goal contract change rarely. */
12
28
  stateIntervalMs?: number;
13
29
  /** How often to poll room.get_transcript. */
14
30
  transcriptIntervalMs?: number;
31
+ /**
32
+ * Ask the room to say when its log grows, instead of asking it every second
33
+ * (D-23). On by default and harmless against a room that cannot: the client
34
+ * checks what the server advertises and polls exactly as before when it does
35
+ * not, or when the subscription is refused.
36
+ */
37
+ subscribe?: boolean;
38
+ /** How often to poll anyway while subscribed — a backstop for a missed notification, not the mechanism. */
39
+ subscribedPollMs?: number;
15
40
  }
16
41
 
17
42
  export interface RoomClientEvents {
@@ -56,15 +81,21 @@ async function endSession(
56
81
  }
57
82
 
58
83
  /**
59
- * Polls a roomyx MCP server over HTTP for state and transcript updates.
60
- * Deliberately polling, not a push subscription — mirrors the server's own
61
- * "re-read on every call, no fs-watch" simplicity (see roomyx/README.md).
84
+ * Follows a roomyx MCP server over HTTP for state and transcript updates.
85
+ *
86
+ * Polls, and — when the server says it can (D-23) — also subscribes to
87
+ * `room://log` and polls the moment it is told the log grew, which turns the
88
+ * poll into a backstop. Polling stays the mechanism that works against every
89
+ * server, so a missing or refused subscription costs latency, never correctness.
62
90
  * Tracks `since_seq` locally so a reconnect never re-delivers old messages.
63
91
  */
64
92
  export class RoomClient {
65
93
  private readonly url: string;
94
+ private readonly token: string | undefined;
66
95
  private readonly stateIntervalMs: number;
67
96
  private readonly transcriptIntervalMs: number;
97
+ private readonly subscribe: boolean;
98
+ private readonly subscribedPollMs: number;
68
99
  private readonly events: RoomClientEvents;
69
100
 
70
101
  private client: Client | undefined;
@@ -75,6 +106,18 @@ export class RoomClient {
75
106
  private stateTimer: ReturnType<typeof setTimeout> | undefined;
76
107
  private transcriptTimer: ReturnType<typeof setTimeout> | undefined;
77
108
  private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
109
+ /** This connection has a live subscription, so the polls are a backstop rather than the mechanism. */
110
+ private pushed = false;
111
+ /**
112
+ * A poll is on the wire / a notification arrived while it was. The second is
113
+ * what keeps a wake from starting a second loop beside the first — the
114
+ * doubling this class's `generation` exists to prevent — by making the running
115
+ * loop come round again at once instead.
116
+ */
117
+ private stateBusy = false;
118
+ private transcriptBusy = false;
119
+ private stateWake = false;
120
+ private transcriptWake = false;
78
121
  private backoffMs: number;
79
122
  /**
80
123
  * Bumped on every disconnect. Each poll loop captures the generation it was
@@ -92,8 +135,11 @@ export class RoomClient {
92
135
 
93
136
  constructor(options: RoomClientOptions, events: RoomClientEvents) {
94
137
  this.url = options.url;
138
+ this.token = options.token;
95
139
  this.stateIntervalMs = options.stateIntervalMs ?? 3000;
96
140
  this.transcriptIntervalMs = options.transcriptIntervalMs ?? 1000;
141
+ this.subscribe = options.subscribe ?? true;
142
+ this.subscribedPollMs = options.subscribedPollMs ?? 15_000;
97
143
  this.backoffMs = this.transcriptIntervalMs;
98
144
  this.events = events;
99
145
  }
@@ -143,7 +189,7 @@ export class RoomClient {
143
189
  this.setStatus("connecting");
144
190
  try {
145
191
  const client = new Client({ name: "roomyx-client", version: "0.1.0" });
146
- const transport = new StreamableHTTPClientTransport(new URL(this.url));
192
+ const transport = roomTransport(this.url, this.token);
147
193
  await client.connect(transport);
148
194
  if (this.stopped) {
149
195
  // stop() ran while this connection was in flight; this.client was
@@ -162,6 +208,11 @@ export class RoomClient {
162
208
  this.backoffMs = this.transcriptIntervalMs;
163
209
  this.setStatus("connected");
164
210
  const generation = this.generation;
211
+ this.stateBusy = this.transcriptBusy = this.stateWake = this.transcriptWake = false;
212
+ // Subscribed BEFORE the first poll: a message landing between the two would
213
+ // otherwise be seen by neither.
214
+ this.pushed = await this.trySubscribe(client, generation);
215
+ if (this.isStale(generation)) return;
165
216
  this.pollState(generation);
166
217
  this.pollTranscript(generation);
167
218
  } catch {
@@ -171,6 +222,44 @@ export class RoomClient {
171
222
  }
172
223
  }
173
224
 
225
+ /**
226
+ * Subscribes to "the log grew". Any failure is "not subscribed", never a lost
227
+ * connection: an older room has no such resource, and the polls still work.
228
+ */
229
+ private async trySubscribe(client: Client, generation: number): Promise<boolean> {
230
+ if (!this.subscribe || client.getServerCapabilities()?.resources?.subscribe !== true) return false;
231
+ try {
232
+ client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => {
233
+ if (notification.params.uri === LOG_RESOURCE_URI) this.wake(generation);
234
+ });
235
+ await client.subscribeResource({ uri: LOG_RESOURCE_URI });
236
+ // The slow backstop must not make a dead server slow to notice. A transport
237
+ // error (the push stream dropped) brings a real request forward; that request
238
+ // is what fails, and the existing poll path turns it into a disconnect.
239
+ client.onerror = () => this.wake(generation);
240
+ return true;
241
+ } catch {
242
+ return false;
243
+ }
244
+ }
245
+
246
+ /** Brings the next poll of each loop forward to now. State rides along because an edit arrives as a message. */
247
+ private wake(generation: number): void {
248
+ if (this.isStale(generation)) return;
249
+ if (this.transcriptBusy) this.transcriptWake = true;
250
+ else if (this.transcriptTimer !== undefined) {
251
+ clearTimeout(this.transcriptTimer);
252
+ this.transcriptTimer = undefined;
253
+ this.pollTranscript(generation);
254
+ }
255
+ if (this.stateBusy) this.stateWake = true;
256
+ else if (this.stateTimer !== undefined) {
257
+ clearTimeout(this.stateTimer);
258
+ this.stateTimer = undefined;
259
+ this.pollState(generation);
260
+ }
261
+ }
262
+
174
263
  /**
175
264
  * Sends an owner command to the room. Not a write to the log — the server holds
176
265
  * it in the room's queue, or hands it to an embedded dispatcher and reports
@@ -228,8 +317,13 @@ export class RoomClient {
228
317
 
229
318
  private pollState(generation: number): void {
230
319
  if (this.isStale(generation)) return;
320
+ this.stateTimer = undefined;
321
+ this.stateBusy = true;
231
322
  const again = () => {
232
- this.stateTimer = setTimeout(() => this.pollState(generation), this.stateIntervalMs);
323
+ this.stateBusy = false;
324
+ const delay = this.stateWake ? 0 : this.pushed ? this.subscribedPollMs : this.stateIntervalMs;
325
+ this.stateWake = false;
326
+ this.stateTimer = setTimeout(() => this.pollState(generation), delay);
233
327
  };
234
328
  this.callTool<RoomState>("room.get_state", {})
235
329
  .then((state) => {
@@ -247,8 +341,13 @@ export class RoomClient {
247
341
 
248
342
  private pollTranscript(generation: number): void {
249
343
  if (this.isStale(generation)) return;
344
+ this.transcriptTimer = undefined;
345
+ this.transcriptBusy = true;
250
346
  const again = () => {
251
- this.transcriptTimer = setTimeout(() => this.pollTranscript(generation), this.transcriptIntervalMs);
347
+ this.transcriptBusy = false;
348
+ const delay = this.transcriptWake ? 0 : this.pushed ? this.subscribedPollMs : this.transcriptIntervalMs;
349
+ this.transcriptWake = false;
350
+ this.transcriptTimer = setTimeout(() => this.pollTranscript(generation), delay);
252
351
  };
253
352
  // No `limit`: the poll asks for what has arrived since the last one, which is
254
353
  // normally nothing to a couple of messages. The server's default only
@@ -16,6 +16,24 @@
16
16
  *
17
17
  * Idempotence is the other half: a second signal arriving mid-teardown must not
18
18
  * start a second one.
19
+ *
20
+ * Two more properties, matching the server's `createServerShutdown`:
21
+ *
22
+ * - **A throwing `destroyRenderer` must not swallow `exit`.** It used to run
23
+ * inside the same `.finally()` as `exit`, so a throw there replaced the
24
+ * `exit()` call — and @opentui's `destroy()` is exactly the call that throws
25
+ * when the renderer is already half torn down. The result was a TUI that was
26
+ * asked to quit and did not: the terminal stuck in the alternate screen with
27
+ * mouse tracking on. `destroyRenderer` now runs in its own try/catch that
28
+ * logs and falls through to `exit` regardless.
29
+ * - **A rejected `stopClient` must not report the clean exit code it was
30
+ * asked for.** The exit code is what a supervising dispatcher reads. A
31
+ * client that could not stop its poller — the MCP session still open, the
32
+ * room still has an attached reader — exiting 0 tells that dispatcher the
33
+ * session closed cleanly when it did not. When `stopClient` rejects and the
34
+ * caller asked for `0`, the process exits `1` instead; a non-zero code the
35
+ * caller asked for is passed through unchanged, since it already reports
36
+ * failure.
19
37
  */
20
38
  export interface ShutdownSteps {
21
39
  stopClient: () => Promise<void>;
@@ -28,12 +46,17 @@ export function createShutdown(steps: ShutdownSteps): (code: number) => void {
28
46
  return (code: number): void => {
29
47
  if (shuttingDown) return;
30
48
  shuttingDown = true;
31
- void steps
32
- .stopClient()
33
- .catch(() => undefined)
34
- .finally(() => {
49
+ const finish = (finalCode: number): void => {
50
+ try {
35
51
  steps.destroyRenderer();
36
- steps.exit(code);
37
- });
52
+ } catch (error: unknown) {
53
+ console.error(`renderer teardown failed: ${error instanceof Error ? error.message : String(error)}`);
54
+ }
55
+ steps.exit(finalCode);
56
+ };
57
+ void steps.stopClient().then(
58
+ () => finish(code),
59
+ () => finish(code === 0 ? 1 : code),
60
+ );
38
61
  };
39
62
  }
@@ -0,0 +1,151 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { z } from "zod";
4
+ import { experimentSchema } from "../log/schema";
5
+ import type { ExperimentHeader } from "../log/types";
6
+
7
+ /**
8
+ * D-22: an experiment is a manifest and a grid of rooms.
9
+ *
10
+ * roomyx does not run agents — a dispatcher does — so this module stops where
11
+ * roomyx's job stops: it turns one manifest into the rooms a dispatcher should
12
+ * run, each carrying, in its own header, exactly which variables made it. A
13
+ * finished room is then a reproducible record rather than a directory whose
14
+ * name someone has to remember.
15
+ */
16
+
17
+ /** A grid bigger than this is almost always a typo (three lists of ten, not three of a hundred). */
18
+ export const MAX_CELLS = 500;
19
+
20
+ const scalarSchema = z.union([z.string(), z.number(), z.boolean()]);
21
+
22
+ const rosterEntrySchema = z.union([
23
+ z.object({ id: z.string().min(1), name: z.string().min(1) }),
24
+ z
25
+ .string()
26
+ .regex(/^[^:]+(:.+)?$/, "a roster entry is `id` or `id:Name`")
27
+ .transform((spec) => {
28
+ const [id = "", name] = spec.split(":");
29
+ return { id, name: name ?? id };
30
+ }),
31
+ ]);
32
+
33
+ export const manifestSchema = z
34
+ .object({
35
+ name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "name becomes a file name: letters, digits, `.`, `_` and `-`"),
36
+ goal: z.string().min(1),
37
+ criteria: z.string().optional(),
38
+ roster: z.array(rosterEntrySchema).default([]),
39
+ /** Recorded, never acted on: roomyx does not call a model. */
40
+ model: z.string().optional(),
41
+ /** Recorded; with `repeats`, the cell's seed is `seed + repeat`. */
42
+ seed: z.number().int().optional(),
43
+ repeats: z.number().int().min(1).default(1),
44
+ /** A list is a grid axis; a scalar is held constant in every cell. */
45
+ variables: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), z.union([scalarSchema, z.array(scalarSchema).min(1)])).default({}),
46
+ })
47
+ .strict();
48
+
49
+ export type Manifest = z.infer<typeof manifestSchema>;
50
+
51
+ export class ManifestError extends Error {}
52
+
53
+ export interface Cell {
54
+ /** Zero-based position in the grid, stable for a given manifest. */
55
+ index: number;
56
+ /** The room's file name without extension, e.g. `pricing-003`. */
57
+ id: string;
58
+ goal: string;
59
+ criteria: string | undefined;
60
+ header: ExperimentHeader;
61
+ }
62
+
63
+ /** `Bun.YAML` arrived in Bun 1.2.21; the floor in `engines` is lower, and raising it is a minor bump (D-13). */
64
+ function parseYaml(text: string): unknown {
65
+ const yaml = (globalThis as { Bun?: { YAML?: { parse(input: string): unknown } } }).Bun?.YAML;
66
+ if (yaml === undefined) {
67
+ throw new ManifestError("reading a .yaml manifest needs Bun 1.2.21 or newer; write the manifest as .json, or upgrade Bun");
68
+ }
69
+ return yaml.parse(text);
70
+ }
71
+
72
+ /** Reads a manifest from a `.yaml`/`.yml`/`.json` file; the extension picks the grammar. */
73
+ export function loadManifest(path: string): { manifest: Manifest; digest: string } {
74
+ let text: string;
75
+ try {
76
+ text = readFileSync(path, "utf8");
77
+ } catch (error) {
78
+ throw new ManifestError(`cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);
79
+ }
80
+ let raw: unknown;
81
+ try {
82
+ raw = path.endsWith(".json") ? JSON.parse(text) : parseYaml(text);
83
+ } catch (error) {
84
+ if (error instanceof ManifestError) throw error;
85
+ throw new ManifestError(`${path} is not valid ${path.endsWith(".json") ? "JSON" : "YAML"}: ${error instanceof Error ? error.message : String(error)}`);
86
+ }
87
+ const parsed = manifestSchema.safeParse(raw);
88
+ if (!parsed.success) {
89
+ const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "manifest"}: ${i.message}`).join("; ");
90
+ throw new ManifestError(`${path}: ${issues}`);
91
+ }
92
+ return { manifest: parsed.data, digest: createHash("sha256").update(text).digest("hex") };
93
+ }
94
+
95
+ /** `{{name}}` → the cell's value. An unknown name is an error, not an empty string. */
96
+ function substitute(text: string, values: Record<string, string | number | boolean>, where: string): string {
97
+ return text.replace(/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g, (_match, key: string) => {
98
+ if (!(key in values)) throw new ManifestError(`${where} uses {{${key}}}, but variables has no "${key}"`);
99
+ return String(values[key]);
100
+ });
101
+ }
102
+
103
+ /**
104
+ * The full grid: the product of every list-valued variable, times `repeats`.
105
+ *
106
+ * Axes vary in the order the manifest declares them, last fastest, so cell
107
+ * numbers do not move when a value is appended to the *last* axis — and a cell
108
+ * is identified by its `index`, not by a hash, so two runs of one manifest
109
+ * produce the same file names.
110
+ */
111
+ export function expand(manifest: Manifest, digest: string): Cell[] {
112
+ const axes = Object.entries(manifest.variables).filter(([, v]) => Array.isArray(v)) as [string, (string | number | boolean)[]][];
113
+ const constants = Object.entries(manifest.variables).filter(([, v]) => !Array.isArray(v)) as [string, string | number | boolean][];
114
+
115
+ const size = axes.reduce((n, [, values]) => n * values.length, 1) * manifest.repeats;
116
+ if (size > MAX_CELLS) {
117
+ throw new ManifestError(`the grid has ${size} cells, over the limit of ${MAX_CELLS}; narrow a variable or lower repeats`);
118
+ }
119
+
120
+ const combos: Record<string, string | number | boolean>[] = [Object.fromEntries(constants)];
121
+ const grown = axes.reduce<Record<string, string | number | boolean>[]>(
122
+ (acc, [key, values]) => acc.flatMap((combo) => values.map((value) => ({ ...combo, [key]: value }))),
123
+ combos,
124
+ );
125
+
126
+ const width = String(size - 1).length;
127
+ const cells: Cell[] = [];
128
+ for (const variables of grown) {
129
+ for (let repeat = 0; repeat < manifest.repeats; repeat++) {
130
+ const index = cells.length;
131
+ const header: ExperimentHeader = experimentSchema.parse({
132
+ name: manifest.name,
133
+ cell: index,
134
+ cells: size,
135
+ manifest_sha256: digest,
136
+ variables,
137
+ ...(manifest.model !== undefined ? { model: manifest.model } : {}),
138
+ ...(manifest.seed !== undefined ? { seed: manifest.seed + repeat } : {}),
139
+ ...(manifest.repeats > 1 ? { repeat } : {}),
140
+ });
141
+ cells.push({
142
+ index,
143
+ id: `${manifest.name}-${String(index).padStart(width, "0")}`,
144
+ goal: substitute(manifest.goal, variables, "goal"),
145
+ criteria: manifest.criteria === undefined ? undefined : substitute(manifest.criteria, variables, "criteria"),
146
+ header,
147
+ });
148
+ }
149
+ }
150
+ return cells;
151
+ }
@@ -1,6 +1,7 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { join } from "node:path";
4
+ import { z } from "zod";
4
5
  import { syncSkillBundle } from "./skill-sync";
5
6
  import { installPersonas } from "./personas";
6
7
  import type { PlanItem } from "./init-plan";
@@ -76,7 +77,7 @@ function applyOne(item: PlanItem, context: ApplyContext): string {
76
77
 
77
78
  case "logs":
78
79
  mkdirSync(item.path, { recursive: true });
79
- return "created";
80
+ return "created (room logs are committed with the repo, not ignored: add this path to .gitignore if a transcript could hold anything private)";
80
81
 
81
82
  case "gitignore":
82
83
  return ensureGitignore(context.cwd);
@@ -108,9 +109,20 @@ function ensureGitignore(cwd: string): string {
108
109
  return `added ${missing.length} line(s)`;
109
110
  }
110
111
 
111
- interface McpConfig {
112
- mcpServers?: Record<string, unknown>;
113
- }
112
+ /**
113
+ * A plain object, optionally with an `mcpServers` object of its own. Not an
114
+ * array, not `null`, not a config whose `mcpServers` is some other shape —
115
+ * `z.object` already rejects anything whose parsed type isn't "object" (that
116
+ * covers arrays and `null`), and `.catchall(z.unknown())` keeps whatever other
117
+ * top-level keys the operator's file has instead of discarding them.
118
+ */
119
+ const mcpConfigSchema = z
120
+ .object({
121
+ mcpServers: z.record(z.string(), z.unknown()).optional(),
122
+ })
123
+ .catchall(z.unknown());
124
+
125
+ type McpConfig = z.infer<typeof mcpConfigSchema>;
114
126
 
115
127
  /**
116
128
  * Adds a `roomyx` entry to an MCP config, merging rather than replacing.
@@ -132,8 +144,9 @@ function ensureMcpServer(path: string, createDir: boolean): string {
132
144
  if (existsSync(path)) {
133
145
  const text = readFileSync(path, "utf8").trim();
134
146
  if (text !== "") {
147
+ let parsed: unknown;
135
148
  try {
136
- config = JSON.parse(text) as McpConfig;
149
+ parsed = JSON.parse(text);
137
150
  } catch (error) {
138
151
  // Refused rather than overwritten. A file we cannot parse may still be
139
152
  // a file someone is relying on.
@@ -141,6 +154,17 @@ function ensureMcpServer(path: string, createDir: boolean): string {
141
154
  `${path} is not valid JSON — ${error instanceof Error ? error.message : String(error)}. Left untouched.`,
142
155
  );
143
156
  }
157
+ const shape = mcpConfigSchema.safeParse(parsed);
158
+ if (!shape.success) {
159
+ // Same courtesy as the unparseable-JSON case above, for JSON that
160
+ // parses but isn't the shape this function assumes: an array, `null`,
161
+ // or an `mcpServers` that isn't itself an object. Reported, not
162
+ // guessed at and overwritten.
163
+ throw new Error(
164
+ `${path} is not a valid MCP config — ${shape.error.issues.map((issue) => issue.message).join("; ")}. Left untouched.`,
165
+ );
166
+ }
167
+ config = shape.data;
144
168
  }
145
169
  }
146
170
 
@@ -148,6 +172,13 @@ function ensureMcpServer(path: string, createDir: boolean): string {
148
172
  if (servers.roomyx !== undefined) return "already registered — left as it is";
149
173
 
150
174
  config.mcpServers = { ...servers, roomyx: { command: "roomyx", args: ["mcp", "--stdio"] } };
151
- writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, "utf8");
175
+ writeConfigFile(path, config);
152
176
  return "registered";
153
177
  }
178
+
179
+ /** Write-to-temp-then-rename, matching `registry.ts`: a reader never observes a partially-written file. */
180
+ function writeConfigFile(path: string, config: McpConfig): void {
181
+ const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
182
+ writeFileSync(tmpPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
183
+ renameSync(tmpPath, path);
184
+ }
@@ -39,7 +39,10 @@ export function init(options: InitOptions): InitResult {
39
39
  const configPath = join(roomyxDir, "config.json");
40
40
  const skillDir = join(roomyxDir, "skills", "startup-room");
41
41
 
42
- mkdirSync(join(roomyxDir, "rooms"), { recursive: true });
42
+ mkdirSync(roomyxDir, { recursive: true });
43
+ // The registry holds each room's bearer token, so its directory and file are
44
+ // private from the moment `init` creates them, as `registerRoom` makes them.
45
+ mkdirSync(join(roomyxDir, "rooms"), { recursive: true, mode: 0o700 });
43
46
  mkdirSync(skillDir, { recursive: true });
44
47
 
45
48
  const registryAlreadyHasRooms =
@@ -49,7 +52,7 @@ export function init(options: InitOptions): InitResult {
49
52
  writeFileSync(configPath, JSON.stringify(DEFAULT_CONFIG, null, 2));
50
53
  }
51
54
  if (!existsSync(registryPath)) {
52
- writeFileSync(registryPath, JSON.stringify({ schemaVersion: 1, rooms: [] }, null, 2));
55
+ writeFileSync(registryPath, JSON.stringify({ schemaVersion: 1, rooms: [] }, null, 2), { mode: 0o600 });
53
56
  }
54
57
  // Staged through `syncSkill`, not copied.
55
58
  //
@@ -2,8 +2,8 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
2
2
  import { dirname } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
5
  import { withLock } from "../lockfile";
6
+ import { roomTransport } from "../room-token";
7
7
  import { archiveRoom, defaultHistoryPath } from "./history";
8
8
 
9
9
  /** Re-exported: the registry's own tests reach for it, and it lives in ../lockfile now. */
@@ -15,6 +15,20 @@ const registryEntrySchema = z.object({
15
15
  logPath: z.string().min(1),
16
16
  pid: z.number().int(),
17
17
  startedAt: z.string().min(1),
18
+ /**
19
+ * The room's per-room token, written here because this entry is already the
20
+ * only place a room's port is recorded: whoever can find the port can find the
21
+ * token, and nobody else has to be told twice.
22
+ *
23
+ * **Optional on read, required on write.** `registerRoom` always writes one —
24
+ * the parameter type makes forgetting it a type error rather than a room
25
+ * nothing can reach. But an entry left behind by a roomyx from before this
26
+ * change has no token, and refusing to parse it would turn every `rooms list`
27
+ * on an existing machine into "Invalid room registry" instead of a room that
28
+ * answers 401. Reading permissively and failing at the door is the same shape
29
+ * AC5 settled for the log: a stale record must not make the file unreadable.
30
+ */
31
+ token: z.string().min(1).optional(),
18
32
  });
19
33
 
20
34
  const registryFileSchema = z.object({
@@ -52,10 +66,16 @@ function readRegistryUnlocked(path: string): { schemaVersion: 1; rooms: RoomRegi
52
66
  return parsed.data;
53
67
  }
54
68
 
55
- /** Write-to-temp-then-rename: a reader never observes a partially-written file. */
69
+ /**
70
+ * Write-to-temp-then-rename: a reader never observes a partially-written file.
71
+ *
72
+ * The temp file is created 0600, and rename keeps that mode, so the per-room
73
+ * token in here is readable only by the owning user. A registry written by an
74
+ * older version stays 0666 until its next write replaces it with a new file.
75
+ */
56
76
  function writeRegistryUnlocked(path: string, rooms: RoomRegistryEntry[]): void {
57
77
  const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
58
- writeFileSync(tmpPath, JSON.stringify({ schemaVersion: 1, rooms }, null, 2));
78
+ writeFileSync(tmpPath, JSON.stringify({ schemaVersion: 1, rooms }, null, 2), { mode: 0o600 });
59
79
  renameSync(tmpPath, path);
60
80
  }
61
81
 
@@ -73,9 +93,14 @@ function generateRoomId(): string {
73
93
  */
74
94
  export function registerRoom(
75
95
  registryPath: string,
76
- info: { port: number; logPath: string; pid: number },
96
+ // `token` is required rather than optional, and that is the point of taking it
97
+ // here at all: a registered room with no token is a room every in-tree client
98
+ // resolves to and then cannot talk to, and the failure shows up as `unknown`
99
+ // liveness rather than as an error. A required parameter makes the omission a
100
+ // type error at the one call site that can make it.
101
+ info: { port: number; logPath: string; pid: number; token: string },
77
102
  ): RoomRegistryEntry {
78
- mkdirSync(dirname(registryPath), { recursive: true });
103
+ mkdirSync(dirname(registryPath), { recursive: true, mode: 0o700 });
79
104
  return withLock(registryPath, () => {
80
105
  const registry = readRegistryUnlocked(registryPath);
81
106
  const entry: RoomRegistryEntry = {
@@ -84,6 +109,7 @@ export function registerRoom(
84
109
  logPath: info.logPath,
85
110
  pid: info.pid,
86
111
  startedAt: new Date().toISOString(),
112
+ token: info.token,
87
113
  };
88
114
  writeRegistryUnlocked(registryPath, [...registry.rooms, entry]);
89
115
  return entry;
@@ -287,7 +313,13 @@ export async function probeRoomState(
287
313
  ): Promise<{ log_path?: string; dispatcherAttached?: boolean } | undefined> {
288
314
  if (!isPidAlive(room.pid)) return undefined;
289
315
  const client = new Client({ name: "roomyx-registry-check", version: "0.1.0" });
290
- const transport = new StreamableHTTPClientTransport(new URL(`http://${LOOPBACK_HOST}:${room.port}/mcp`));
316
+ // Through `roomTransport`, with the token off the entry being probed. This is
317
+ // the call site D-06a's precedent points at: the probe is the only in-tree
318
+ // caller whose failure is silent, because a refused probe is reported as
319
+ // `unknown` liveness and `unknown` is an ordinary answer. A hand-assembled
320
+ // header here that drifted from the server's expectation would read as a busy
321
+ // machine, not as a bug.
322
+ const transport = roomTransport(`http://${LOOPBACK_HOST}:${room.port}/mcp`, room.token);
291
323
  const timeout = new Promise<never>((_, reject) => {
292
324
  setTimeout(() => reject(new Error("liveness check timed out")), timeoutMs);
293
325
  });