@mrciphersmith/roomyx 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -45,7 +45,7 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
45
45
  description: "Rooms currently registered and confirmed live (liveness-checked, not just registry presence).",
46
46
  },
47
47
  async () => ({
48
- content: [{ type: "text", text: JSON.stringify(await listLiveRooms(options.registryPath)) }],
48
+ content: [{ type: "text", text: JSON.stringify(await listLiveRooms(options.registryPath, { prune: false })) }],
49
49
  }),
50
50
  );
51
51
 
@@ -63,11 +63,15 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
63
63
  // escape hatch, because that is the operator on their own machine;
64
64
  // the network surface does not get one.
65
65
  target: z.enum([...NAMED_TARGETS, "all"]).describe("A runtime by name, or `all`."),
66
- dryRun: z.boolean().optional(),
67
- yes: z.boolean().optional(),
68
66
  },
69
67
  },
70
- async ({ target, dryRun, yes }) => {
68
+ // No `yes`, and no `dryRun`. `yes` is what D-02's overwrite guard turns
69
+ // off, and on the CLI it is an operator's keystroke; over MCP it would be a
70
+ // boolean the caller sets for itself, which is not a guard. This tool
71
+ // reports what a sync *would* do — the deciding is the operator's, at the
72
+ // CLI, where `--yes` means a person decided. Same reasoning that removed
73
+ // `targetPath` from this schema.
74
+ async ({ target }) => {
71
75
  const targets = resolveTargets(target, options.cwd);
72
76
  const results = targets.map(({ name, path }) => ({
73
77
  target: name,
@@ -76,8 +80,7 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
76
80
  bundledSkillPath: options.bundledSkillPath,
77
81
  targetPath: path,
78
82
  configPath: options.configPath,
79
- dryRun,
80
- yes,
83
+ dryRun: true,
81
84
  }),
82
85
  }));
83
86
  return { content: [{ type: "text", text: JSON.stringify(results) }] };
@@ -89,12 +92,6 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
89
92
 
90
93
  export type ManagementHandle = McpHttpTransportHandle;
91
94
 
92
- export interface ManagementServeOptions {
93
- /** Defaults to 4320 so it does not collide with `roomyx serve` (4319). 0 selects an ephemeral port. */
94
- port?: number;
95
- host?: string;
96
- acknowledgeNonLoopback?: boolean;
97
- }
98
95
 
99
96
  /**
100
97
  * Serves the management tools over the shared loopback HTTP transport. The
@@ -1,4 +1,5 @@
1
1
  import { createServer as createHttpServer } from "node:http";
2
+ import type { IncomingMessage } from "node:http";
2
3
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
4
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
5
 
@@ -54,13 +55,45 @@ export async function serveMcpOverHttp(
54
55
  );
55
56
  }
56
57
 
57
- const sessions = new Map<string, StreamableHTTPServerTransport>();
58
+ /**
59
+ * Live sessions, with the time each was last used.
60
+ *
61
+ * A session used to leave this map only via `onsessionclosed`, which the SDK
62
+ * fires on an HTTP DELETE — and nothing in roomyx sends one. `Client.close()`
63
+ * aborts the local controller; `terminateSession()` is the method that sends
64
+ * the DELETE, and it had no callers. So every session the process ever
65
+ * accepted was retained for the life of the process, at roughly 70-78 KB
66
+ * each, fed by ordinary use: one per `rooms list`, one per `room append`, one
67
+ * per client start, one per reconnect. Each abandoned id also stayed a fully
68
+ * routable handle to the room — three clients closed, then a raw POST
69
+ * replaying their recorded ids still returned a full `tools/list`.
70
+ */
71
+ const sessions = new Map<string, { transport: StreamableHTTPServerTransport; lastSeenMs: number }>();
58
72
 
59
73
  // Filled in after listen(). Sessions are only ever created while handling a
60
74
  // request, so by the time createSession runs this is the real bound port —
61
75
  // which matters because the allowlists below cannot be built without it.
62
76
  let boundPort = 0;
63
77
 
78
+ /**
79
+ * The Host values this server will answer to.
80
+ *
81
+ * The loopback three, plus the bound host when the operator has explicitly
82
+ * acknowledged binding a non-loopback one. Without that last part the escape
83
+ * hatch bound the address and the rebinding guard then refused every request
84
+ * that arrived at it — measured, 403 `Invalid Host header` against the very
85
+ * address `--acknowledge-non-loopback` had just permitted. A flag that
86
+ * appears to work and does not is worse than one that refuses.
87
+ *
88
+ * This does not widen the guard for anyone who did not ask: without the flag
89
+ * the server will not bind a non-loopback host at all.
90
+ */
91
+ function allowedHosts(): string[] {
92
+ const loopback = [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`];
93
+ if (LOOPBACK_HOSTS.has(host)) return loopback;
94
+ return [...loopback, `${host}:${boundPort}`];
95
+ }
96
+
64
97
  async function createSession(): Promise<StreamableHTTPServerTransport> {
65
98
  const transport = new StreamableHTTPServerTransport({
66
99
  sessionIdGenerator: () => crypto.randomUUID(),
@@ -83,28 +116,132 @@ export async function serveMcpOverHttp(
83
116
  // the Origin check when the header is absent, so the list below exists
84
117
  // to be matched by nothing.
85
118
  enableDnsRebindingProtection: true,
86
- allowedHosts: [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`],
119
+ allowedHosts: allowedHosts(),
87
120
  allowedOrigins: [`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`],
88
121
  onsessioninitialized: (sessionId) => {
89
- sessions.set(sessionId, transport);
122
+ sessions.set(sessionId, { transport, lastSeenMs: Date.now() });
90
123
  },
91
124
  onsessionclosed: (sessionId) => {
92
125
  sessions.delete(sessionId);
93
126
  },
94
127
  });
128
+ // The DELETE is one way a session can end; the transport closing for its
129
+ // own reasons is another, and only the first was being listened for.
130
+ //
131
+ // Measured, so the scope is not overstated: this does NOT fire when a
132
+ // client simply calls `close()` — such a session still answers 200 after
133
+ // three seconds, because the server never learns the client went away. An
134
+ // abandoned session is the sweeper's job. This is belt-and-braces for a
135
+ // transport that closes itself, and it is deliberately not pinned by a
136
+ // test, because no test can reach it from outside.
137
+ transport.onclose = () => {
138
+ const id = transport.sessionId;
139
+ if (id !== undefined) sessions.delete(id);
140
+ };
95
141
  const mcpServer = options.createMcpServer();
96
142
  await mcpServer.connect(transport);
97
143
  return transport;
98
144
  }
99
145
 
146
+ /**
147
+ * Closes sessions nothing has touched for a long time.
148
+ *
149
+ * The first version of this used a minute, reasoning that a well-behaved
150
+ * client polls every second or three. That is true of roomyx's own TUI and
151
+ * false of every other consumer: `roomyx mcp` is documented for Claude Code,
152
+ * Codex and keryx, whose clients call a tool when a model decides to, and a
153
+ * minute of think-time is ordinary. Measured — connect, call a tool, idle 95
154
+ * seconds, and the next call fails permanently, because the SDK client never
155
+ * clears its session id on a 404 and never re-initializes. So the fix broke
156
+ * the product's primary integration surface: `roomyx mcp` worked once and was
157
+ * dead for the rest of the host's lifetime.
158
+ *
159
+ * **Eviction is one-way, so the window has to mean "certainly gone", not
160
+ * "probably gone".** Thirty minutes is past any plausible think-time while
161
+ * still bounding what a crashed client can leave behind. The ordinary case is
162
+ * not this sweeper's job at all — it is `terminateSession()` at every client
163
+ * close and `transport.onclose`; this only catches a client that died without
164
+ * being able to say so.
165
+ *
166
+ * `unref()` so an idle sweeper cannot be the reason a process stays alive.
167
+ */
168
+ const IDLE_SESSION_MS = 30 * 60_000;
169
+ const sweeper = setInterval(() => {
170
+ const cutoff = Date.now() - IDLE_SESSION_MS;
171
+ for (const [id, entry] of sessions) {
172
+ if (entry.lastSeenMs < cutoff) {
173
+ sessions.delete(id);
174
+ void entry.transport.close().catch(() => undefined);
175
+ }
176
+ }
177
+ }, IDLE_SESSION_MS / 2);
178
+ sweeper.unref();
179
+
180
+ /**
181
+ * The same Host/Origin decision the SDK makes, applied to the one response we
182
+ * write ourselves. Returns the rejection message, or null to proceed.
183
+ *
184
+ * Deliberately mirrors rather than reuses: the SDK's check is private to the
185
+ * transport, and a transport is exactly what this branch exists to avoid
186
+ * creating.
187
+ */
188
+ function rebindingRejection(req: IncomingMessage): string | null {
189
+ const origin = req.headers.origin;
190
+ if (typeof origin === "string" && origin.length > 0) {
191
+ if (![`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`].includes(origin)) {
192
+ return `Invalid Origin header: ${origin}`;
193
+ }
194
+ }
195
+ const hostHeader = req.headers.host;
196
+ if (typeof hostHeader === "string" && !allowedHosts().includes(hostHeader)) {
197
+ return `Invalid Host header: ${hostHeader}`;
198
+ }
199
+ return null;
200
+ }
201
+
100
202
  const httpServer = createHttpServer((req, res) => {
101
203
  const sessionIdHeader = req.headers["mcp-session-id"];
102
204
  const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
103
205
  const existing = sessionId ? sessions.get(sessionId) : undefined;
206
+ if (existing) existing.lastSeenMs = Date.now();
104
207
 
105
- const transportPromise = existing ? Promise.resolve(existing) : createSession();
208
+ // A request naming a session that does not exist is answered, not granted a
209
+ // new one. Minting a transport for an unknown id created one that never
210
+ // entered `sessions`, so it could not be closed even by `closeSessions` on
211
+ // shutdown — a leak reachable by anyone sending a random header.
212
+ if (sessionId !== undefined && existing === undefined) {
213
+ // Validated first. `handleRequest` is where the SDK checks Host and
214
+ // Origin, so returning before it made this the one response path the
215
+ // rebinding guard never saw: measured, `Host: evil.example` alone got
216
+ // 403 and the same Host plus an unknown session id got a roomyx-authored
217
+ // 404. Nothing was exploitable — session ids are 122-bit random, so the
218
+ // oracle is worthless — but "every path except one" is the property that
219
+ // stops being true quietly the next time a branch is added up here.
220
+ const rejection = rebindingRejection(req);
221
+ if (rejection) {
222
+ res.writeHead(403, { "content-type": "application/json" });
223
+ res.end(JSON.stringify({ error: rejection }));
224
+ return;
225
+ }
226
+ res.writeHead(404, { "content-type": "application/json" });
227
+ res.end(JSON.stringify({ error: `Unknown session ${sessionId}` }));
228
+ return;
229
+ }
230
+
231
+ const transportPromise = existing ? Promise.resolve(existing.transport) : createSession();
106
232
  transportPromise
107
- .then((transport) => transport.handleRequest(req, res))
233
+ .then(async (transport) => {
234
+ await transport.handleRequest(req, res);
235
+ // The 404 above closed one half of this class and the comment claimed
236
+ // both. A request carrying *no* session id still reaches `createSession`
237
+ // — it has to, because that is how `initialize` arrives — but if it was
238
+ // not an initialize, `onsessioninitialized` never fires and the
239
+ // transport never enters `sessions`: unsweepable, and invisible to
240
+ // `closeSessions` on shutdown. Measured: 15 session-less `tools/list`
241
+ // POSTs minted 15 transports and tracked 0. Anything that did not
242
+ // become a session is closed here.
243
+ if (transport.sessionId === undefined) await transport.close().catch(() => undefined);
244
+ })
108
245
  .catch((error) => {
109
246
  if (!res.headersSent) {
110
247
  res.writeHead(500, { "content-type": "application/json" });
@@ -120,6 +257,7 @@ export async function serveMcpOverHttp(
120
257
  httpServer.listen(port, host, () => resolve());
121
258
  });
122
259
  } catch (error) {
260
+ clearInterval(sweeper);
123
261
  await closeSessions(sessions);
124
262
  throw error;
125
263
  }
@@ -131,19 +269,36 @@ export async function serveMcpOverHttp(
131
269
  return {
132
270
  url: `http://${host}:${actualPort}/mcp`,
133
271
  port: actualPort,
134
- close: () =>
135
- new Promise<void>((resolve, reject) => {
136
- httpServer.close(async (error) => {
137
- // The management server used to skip this, so its sessions outlived
138
- // the process that owned them. One implementation, one behaviour.
139
- await closeSessions(sessions);
272
+ close: async () => {
273
+ // Order matters and it used to be inverted. `httpServer.close()`'s
274
+ // callback fires only once every connection has ended, and the code that
275
+ // ends them — `closeSessions` — was *inside* that callback. An MCP client
276
+ // holds a keep-alive socket, so with anyone attached the callback never
277
+ // fired: `roomyx serve` did not exit on SIGTERM at all, the port stayed
278
+ // bound, and the only way out was SIGKILL. Measured with a control: with
279
+ // a client attached, still running after 12s; with none, clean.
280
+ //
281
+ // The management server used to skip closing sessions entirely, so its
282
+ // sessions outlived the process. One implementation, one behaviour.
283
+ clearInterval(sweeper);
284
+ await closeSessions(sessions);
285
+
286
+ await new Promise<void>((resolve, reject) => {
287
+ httpServer.close((error) => {
140
288
  if (error) reject(error);
141
289
  else resolve();
142
290
  });
143
- }),
291
+ // A client that ignores the stream ending must not be able to pin the
292
+ // process open. Closing sessions first is the polite half; this is the
293
+ // half that means shutdown is bounded whatever the client does.
294
+ httpServer.closeAllConnections();
295
+ });
296
+ },
144
297
  };
145
298
  }
146
299
 
147
- function closeSessions(sessions: Map<string, StreamableHTTPServerTransport>): Promise<unknown[]> {
148
- return Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
300
+ function closeSessions(
301
+ sessions: Map<string, { transport: StreamableHTTPServerTransport; lastSeenMs: number }>,
302
+ ): Promise<unknown[]> {
303
+ return Promise.all([...sessions.values()].map((entry) => entry.transport.close().catch(() => undefined)));
149
304
  }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A long-lived server's ordered exit, as a unit that can be tested.
3
+ *
4
+ * It lived in `cli.ts`, which no test can import: that module runs its entry
5
+ * point on import and prints usage. The consequence was measured rather than
6
+ * suspected — a post-fix verifier deleted the re-entry guard below and all 265
7
+ * tests stayed green, including the subprocess case written to pin it. From
8
+ * outside the process the two behaviours are identical: without the guard the
9
+ * teardown simply runs three times and the first `exit` wins, so three
10
+ * deregistrations of one room look exactly like one.
11
+ *
12
+ * Two properties, and both were once wrong in one of the three copies of this
13
+ * logic that existed before it was written down once:
14
+ *
15
+ * - **Re-entry.** A second signal arriving mid-teardown must not start another.
16
+ * - **Order.** `cleanup` runs *after* the close resolves. Deregistering first
17
+ * meant a shutdown that hung — and it hung whenever a client was attached —
18
+ * removed the room from the registry while the process kept running and kept
19
+ * the port. The room became invisible while still being served.
20
+ */
21
+ export function createServerShutdown(
22
+ close: () => Promise<void>,
23
+ cleanup: () => void = () => undefined,
24
+ exit: (code: number) => void = (code) => process.exit(code),
25
+ ): () => void {
26
+ let shuttingDown = false;
27
+ return (): void => {
28
+ if (shuttingDown) return;
29
+ shuttingDown = true;
30
+ void close()
31
+ .catch((error: unknown) => {
32
+ console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
33
+ })
34
+ .finally(() => {
35
+ cleanup();
36
+ exit(0);
37
+ });
38
+ };
39
+ }
@@ -1,7 +1,7 @@
1
1
  import { loadRoomLog } from "../../log/store";
2
2
  import type { RoomState } from "../../log/types";
3
3
 
4
- /** MCP tool `room.get_state`: roster + current goal contract. Read-only. */
4
+ /** MCP tool `room.get_state`: roster, goal contract, and which log this is. Read-only. */
5
5
  export function getStateTool(logPath: string): RoomState {
6
6
  const { state } = loadRoomLog(logPath);
7
7
  return state;
@@ -1,59 +0,0 @@
1
- import { BoxRenderable, ScrollBoxRenderable, TextRenderable } from "@opentui/core";
2
- import type { RenderContext } from "@opentui/core";
3
- import { createMessageRow } from "../components/message-row";
4
- import type { AgentDetail } from "../../log/types";
5
-
6
- /**
7
- * Modal overlay for one participant's own messages (R4 / AC2 — shows only
8
- * that participant's data, not the full transcript). Drawn over the chat
9
- * view, not a screen replacement, matching the pattern observed in keryx's
10
- * own mcp-inspector.ts (background stays visible, modal on top).
11
- */
12
- export class AgentModal {
13
- readonly node: BoxRenderable;
14
- private readonly title: TextRenderable;
15
- private readonly scroll: ScrollBoxRenderable;
16
- private readonly ctx: RenderContext;
17
-
18
- constructor(ctx: RenderContext, options: { width: number; height: number }) {
19
- this.ctx = ctx;
20
- this.node = new BoxRenderable(ctx, {
21
- width: options.width,
22
- height: options.height,
23
- flexDirection: "column",
24
- border: true,
25
- visible: false,
26
- position: "absolute",
27
- top: 2,
28
- left: 2,
29
- zIndex: 10,
30
- backgroundColor: "#000000",
31
- });
32
- this.title = new TextRenderable(ctx, { content: "", height: 1 });
33
- this.node.add(this.title);
34
- this.scroll = new ScrollBoxRenderable(ctx, { flexGrow: 1 });
35
- this.node.add(this.scroll);
36
- }
37
-
38
- show(detail: AgentDetail): void {
39
- for (const child of this.scroll.getChildren()) this.scroll.remove(child);
40
- if (!detail.found) {
41
- this.title.content = "Agent not found";
42
- this.node.visible = true;
43
- return;
44
- }
45
- this.title.content = `${detail.agent.name} — last seen at seq ${detail.lastSeenSeq}`;
46
- for (const message of detail.messages) {
47
- this.scroll.add(createMessageRow(this.ctx, message, detail.agent.name));
48
- }
49
- this.node.visible = true;
50
- }
51
-
52
- hide(): void {
53
- this.node.visible = false;
54
- }
55
-
56
- isVisible(): boolean {
57
- return this.node.visible;
58
- }
59
- }