@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.
- package/CHANGELOG.md +91 -0
- package/README.md +84 -4
- package/package.json +11 -10
- package/src/bin/launch.mjs +1 -1
- package/src/bundled-personas/groups.md +3 -3
- package/src/bundled-skills/startup-room/reference/roomyx.md +5 -0
- package/src/cli/client.ts +12 -0
- package/src/cli/experiment.ts +67 -0
- package/src/cli/init.ts +149 -0
- package/src/cli/mcp.ts +54 -0
- package/src/cli/personas.ts +40 -0
- package/src/cli/room-append.ts +357 -0
- package/src/cli/room.ts +91 -0
- package/src/cli/rooms.ts +65 -0
- package/src/cli/serve.ts +84 -0
- package/src/cli/shared.ts +71 -0
- package/src/cli/skills.ts +58 -0
- package/src/cli/specs.ts +1 -0
- package/src/cli.ts +29 -884
- package/src/client/index.ts +16 -3
- package/src/client/mcp-client.ts +106 -7
- package/src/client/shutdown.ts +29 -6
- package/src/experiment/manifest.ts +151 -0
- package/src/installer/init-apply.ts +38 -7
- package/src/installer/init.ts +5 -2
- package/src/installer/registry.ts +38 -6
- package/src/installer/resolve-connection.ts +54 -8
- package/src/installer/room-tool.ts +6 -3
- package/src/installer/skill-sync.ts +86 -3
- package/src/installer/skill-targets.ts +7 -3
- package/src/lockfile.ts +13 -2
- package/src/log/schema.ts +108 -38
- package/src/log/store.ts +1 -0
- package/src/log/types.ts +8 -1
- package/src/log/write.ts +115 -6
- package/src/mcp-management/server.ts +30 -4
- package/src/room-token.ts +129 -0
- package/src/server/http-transport.ts +43 -0
- package/src/server/index.ts +76 -3
- package/src/server/log-watcher.ts +80 -0
- package/src/server/owner-queue.ts +7 -1
- package/src/server/serve.ts +112 -30
- package/src/server/shutdown.ts +33 -7
- package/src/writer-lease.ts +161 -14
|
@@ -19,6 +19,12 @@ export interface ManagementOptions {
|
|
|
19
19
|
* the exception.
|
|
20
20
|
*/
|
|
21
21
|
cwd?: string;
|
|
22
|
+
/**
|
|
23
|
+
* The home directory user-scoped targets resolve against. Defaults to the
|
|
24
|
+
* process's. A parameter because `os.homedir()` is fixed when the process
|
|
25
|
+
* starts, so a test cannot redirect it by setting `HOME`.
|
|
26
|
+
*/
|
|
27
|
+
home?: string;
|
|
22
28
|
}
|
|
23
29
|
|
|
24
30
|
export interface ManagementServeOptions {
|
|
@@ -44,9 +50,29 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
|
|
|
44
50
|
title: "List live rooms",
|
|
45
51
|
description: "Rooms currently registered and confirmed live (liveness-checked, not just registry presence).",
|
|
46
52
|
},
|
|
47
|
-
async () =>
|
|
48
|
-
|
|
49
|
-
|
|
53
|
+
async () => {
|
|
54
|
+
const rooms = await listLiveRooms(options.registryPath, { prune: false });
|
|
55
|
+
// The per-room token is stripped, field by field, and this is not a
|
|
56
|
+
// nicety: this server takes no credential of its own, so echoing the
|
|
57
|
+
// rooms' tokens here would hand every room's credential to exactly the
|
|
58
|
+
// caller the token was introduced to bound — an unauthenticated loopback
|
|
59
|
+
// request, which is the request the audit made with `curl`. The token would
|
|
60
|
+
// have travelled out of here for free simply because the registry entry it
|
|
61
|
+
// lives in is what this tool serialises.
|
|
62
|
+
//
|
|
63
|
+
// Allow-listed rather than deleted (`{ token, ...rest }`): a field added to
|
|
64
|
+
// the registry entry later must not appear on this surface by default. The
|
|
65
|
+
// whole point of the D-07 shared-transport lesson is that a second thing
|
|
66
|
+
// getting the same treatment silently is the failure, not the exception.
|
|
67
|
+
const listed = rooms.map((room) => ({
|
|
68
|
+
id: room.id,
|
|
69
|
+
port: room.port,
|
|
70
|
+
logPath: room.logPath,
|
|
71
|
+
pid: room.pid,
|
|
72
|
+
startedAt: room.startedAt,
|
|
73
|
+
}));
|
|
74
|
+
return { content: [{ type: "text", text: JSON.stringify(listed) }] };
|
|
75
|
+
},
|
|
50
76
|
);
|
|
51
77
|
|
|
52
78
|
server.registerTool(
|
|
@@ -74,7 +100,7 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
|
|
|
74
100
|
// CLI, where `--yes` means a person decided. Same reasoning that removed
|
|
75
101
|
// `targetPath` from this schema.
|
|
76
102
|
async ({ target }) => {
|
|
77
|
-
const targets = resolveTargets(target, options.cwd);
|
|
103
|
+
const targets = resolveTargets(target, options.cwd, options.home);
|
|
78
104
|
const results = targets.map(({ name, path }) => ({
|
|
79
105
|
target: name,
|
|
80
106
|
path,
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The per-room token: one wire format, one place.
|
|
6
|
+
*
|
|
7
|
+
* ## Why this module exists at all
|
|
8
|
+
*
|
|
9
|
+
* D-06 shipped the room transport with no credential, on the argument that the
|
|
10
|
+
* threat was bounded by the local machine. D-06a amended that for browsers and
|
|
11
|
+
* said plainly what the rebinding guards do and do not do: they stop a *page*
|
|
12
|
+
* and they do not stop a *neighbouring process*, because a local program sends
|
|
13
|
+
* no `Origin` and walks straight past the check. What changed since is what is
|
|
14
|
+
* behind the port. The room now carries `room.post_owner_command`, so reach to
|
|
15
|
+
* the endpoint is not only read access to the whole transcript — it is
|
|
16
|
+
* instruction access to an agent that is holding tools. The audit walked that
|
|
17
|
+
* chain with `curl` and no credential of any kind.
|
|
18
|
+
*
|
|
19
|
+
* ## What it is, and what it is not
|
|
20
|
+
*
|
|
21
|
+
* It is **not authentication of a person**, and calling it that would repeat the
|
|
22
|
+
* mistake D-06a was written to avoid. Nobody signs in; there is no identity and
|
|
23
|
+
* no audit trail. What it does is bound *which local processes can drive the
|
|
24
|
+
* room* to the ones that were told the room exists — the ones that can read the
|
|
25
|
+
* registry entry. A process that only knows a port is no longer enough.
|
|
26
|
+
*
|
|
27
|
+
* ## Why one module rather than a header at each call site
|
|
28
|
+
*
|
|
29
|
+
* Four in-tree callers reach a room — `RoomClient`, `callRoomTool`,
|
|
30
|
+
* `probeRoomState` and the liveness probe on top of it — plus every test that
|
|
31
|
+
* connects to a real `serve()`. D-06a records the failure mode of spreading that
|
|
32
|
+
* out: `allowedHosts` was set correctly in the abstract and silently refused
|
|
33
|
+
* roomyx's own client, because the client's own path was never exercised. The
|
|
34
|
+
* symptom there was not a red test; it was a room answering "did not answer".
|
|
35
|
+
* So there is exactly one function that builds a client transport
|
|
36
|
+
* (`roomTransport`) and exactly one that judges an incoming request
|
|
37
|
+
* (`roomTokenRejection`). A change to the wire format that breaks one caller
|
|
38
|
+
* cannot leave another one working.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 32 hex characters — 128 bits out of `node:crypto`.
|
|
43
|
+
*
|
|
44
|
+
* `randomBytes`, not `Math.random()`: the registry is written 0600, so the
|
|
45
|
+
* token's job is not to be unguessable *to the operator's own user* — it is to
|
|
46
|
+
* be unguessable to anything that has only the port. (A registry written by an
|
|
47
|
+
* older version stays world-readable until its next write.) A predictable value
|
|
48
|
+
* would hand that back.
|
|
49
|
+
*/
|
|
50
|
+
export function mintRoomToken(): string {
|
|
51
|
+
return randomBytes(16).toString("hex");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The header a caller presents. A plain `Authorization: Bearer <token>` rather
|
|
56
|
+
* than a bespoke `X-Roomyx-*` name or a query parameter: it is what every HTTP
|
|
57
|
+
* client, proxy and log redactor already knows to treat as a credential, and a
|
|
58
|
+
* query parameter would end up in shell history and access logs.
|
|
59
|
+
*/
|
|
60
|
+
export function roomTokenHeaders(token: string): Record<string, string> {
|
|
61
|
+
return { Authorization: `Bearer ${token}` };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A client transport that presents the room's token — the one helper every
|
|
66
|
+
* caller goes through.
|
|
67
|
+
*
|
|
68
|
+
* `requestInit.headers` rather than the SDK's `authProvider`, and this is worth
|
|
69
|
+
* stating because `authProvider` looks like the obvious fit. It is an OAuth
|
|
70
|
+
* client: a 401 makes it start a discovery-and-redirect flow that has no
|
|
71
|
+
* counterpart here, and its tokens are refreshable, which this one is not.
|
|
72
|
+
* Measured against the pinned SDK: `requestInit.headers` is merged into
|
|
73
|
+
* `_commonHeaders()`, which is used by all three request paths the transport
|
|
74
|
+
* makes — the POST, the GET that opens the SSE stream, and the DELETE that
|
|
75
|
+
* `terminateSession()` sends. That last one matters: a DELETE refused with 401
|
|
76
|
+
* would leak a server-side session on every close, which is the leak the session
|
|
77
|
+
* bookkeeping in `http-transport` exists to prevent.
|
|
78
|
+
*
|
|
79
|
+
* `token` is allowed to be `undefined` so that the one path which genuinely has
|
|
80
|
+
* no token — `roomyx-client --connect <url>` against a room this machine did not
|
|
81
|
+
* register — fails as a 401 from the server rather than as a type error miles
|
|
82
|
+
* away. Every other caller has a token and must pass it.
|
|
83
|
+
*/
|
|
84
|
+
export function roomTransport(url: string | URL, token: string | undefined): StreamableHTTPClientTransport {
|
|
85
|
+
const target = typeof url === "string" ? new URL(url) : url;
|
|
86
|
+
if (token === undefined) return new StreamableHTTPClientTransport(target);
|
|
87
|
+
return new StreamableHTTPClientTransport(target, { requestInit: { headers: roomTokenHeaders(token) } });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The server side of `roomTokenHeaders`: the token a request presented, if any. */
|
|
91
|
+
export function parseBearerToken(authorization: string | string[] | undefined): string | undefined {
|
|
92
|
+
// node:http gives `string | string[] | undefined`. A repeated Authorization
|
|
93
|
+
// header is not something any legitimate client sends, and picking one of them
|
|
94
|
+
// would be a guess, so it is treated as absent.
|
|
95
|
+
if (typeof authorization !== "string") return undefined;
|
|
96
|
+
const match = /^Bearer[ \t]+(\S+)$/i.exec(authorization.trim());
|
|
97
|
+
return match?.[1];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* What a refused request is told. Two sentences, because "you sent nothing" and
|
|
102
|
+
* "you sent the wrong thing" are different things to debug — and neither one
|
|
103
|
+
* reveals anything about the expected value, which is the property that matters.
|
|
104
|
+
* The presented value is not echoed either: it would land in whatever log the
|
|
105
|
+
* caller keeps, and a credential in a log is a credential leaked.
|
|
106
|
+
*/
|
|
107
|
+
const MISSING =
|
|
108
|
+
"Unauthorized: this room requires its per-room token, presented as `Authorization: Bearer <token>`. " +
|
|
109
|
+
"The token is recorded in the room's registry entry, beside the port.";
|
|
110
|
+
const MISMATCHED = "Unauthorized: the token presented is not this room's token.";
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* `null` to proceed, or the sentence to refuse with. The comparison is
|
|
114
|
+
* `timingSafeEqual`, not `===`.
|
|
115
|
+
*
|
|
116
|
+
* A length check before it is not a leak worth worrying about: `mintRoomToken`
|
|
117
|
+
* makes one length and only one, so the length is public. What it prevents is
|
|
118
|
+
* `timingSafeEqual` throwing on unequal buffers, which would surface as a 500
|
|
119
|
+
* and hand a caller a way to tell a wrong-length guess from a wrong-value one by
|
|
120
|
+
* status code.
|
|
121
|
+
*/
|
|
122
|
+
export function roomTokenRejection(expected: string, headers: { authorization?: string | string[] }): string | null {
|
|
123
|
+
const presented = parseBearerToken(headers.authorization);
|
|
124
|
+
if (presented === undefined) return MISSING;
|
|
125
|
+
const a = Buffer.from(expected, "utf8");
|
|
126
|
+
const b = Buffer.from(presented, "utf8");
|
|
127
|
+
if (a.length !== b.length) return MISMATCHED;
|
|
128
|
+
return timingSafeEqual(a, b) ? null : MISMATCHED;
|
|
129
|
+
}
|
|
@@ -2,6 +2,7 @@ import { createServer as createHttpServer } from "node:http";
|
|
|
2
2
|
import type { IncomingMessage } from "node:http";
|
|
3
3
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
4
|
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
|
+
import { roomTokenRejection } from "../room-token";
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* The loopback HTTP transport both roomyx servers bind to.
|
|
@@ -31,6 +32,19 @@ export interface McpHttpTransportOptions {
|
|
|
31
32
|
port?: number;
|
|
32
33
|
host?: string;
|
|
33
34
|
acknowledgeNonLoopback?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* When set, every request must present this token as `Authorization: Bearer
|
|
37
|
+
* <token>`; anything else is 401 before the MCP layer sees it.
|
|
38
|
+
*
|
|
39
|
+
* An **option**, not a property of the transport, and that is D-07's doing:
|
|
40
|
+
* one module serves both MCP servers, and only the per-room one has a token.
|
|
41
|
+
* `roomyx serve` passes it, `roomyx mcp` does not — the management server has a
|
|
42
|
+
* different surface, no owner-command queue, and D-11 already closed its one
|
|
43
|
+
* dangerous path by removing `yes` from `skills.sync`. Leaving it unset keeps
|
|
44
|
+
* that server exactly as it was rather than forcing a second decision into this
|
|
45
|
+
* one's change.
|
|
46
|
+
*/
|
|
47
|
+
requiredToken?: string;
|
|
34
48
|
}
|
|
35
49
|
|
|
36
50
|
export interface McpHttpTransportHandle {
|
|
@@ -200,6 +214,35 @@ export async function serveMcpOverHttp(
|
|
|
200
214
|
}
|
|
201
215
|
|
|
202
216
|
const httpServer = createHttpServer((req, res) => {
|
|
217
|
+
// FIRST, before the session lookup and before any transport exists.
|
|
218
|
+
//
|
|
219
|
+
// Every other branch below is downstream of this one on purpose. An
|
|
220
|
+
// uncredentialled request must not be able to create a session, continue
|
|
221
|
+
// one, learn whether a session id exists, or reach `handleRequest` — which
|
|
222
|
+
// is where the SDK's own Host/Origin guard lives, so a request refused here
|
|
223
|
+
// is refused before the MCP layer sees it at all.
|
|
224
|
+
//
|
|
225
|
+
// The consequence for the rebinding guard is deliberate and worth naming: a
|
|
226
|
+
// request with a forged `Host` and no token now gets 401 rather than the
|
|
227
|
+
// SDK's 403. The guard is not weaker for it — a credentialled request with a
|
|
228
|
+
// forged Host still gets its 403, which is what the rebinding tests assert,
|
|
229
|
+
// now of a request that got past the credential. The two guards answer
|
|
230
|
+
// different questions and the cheaper, more total one goes first.
|
|
231
|
+
if (options.requiredToken !== undefined) {
|
|
232
|
+
const rejection = roomTokenRejection(options.requiredToken, req.headers);
|
|
233
|
+
if (rejection !== null) {
|
|
234
|
+
res.writeHead(401, {
|
|
235
|
+
"content-type": "application/json",
|
|
236
|
+
// `Bearer` with no realm and no `resource_metadata`: a 401 without a
|
|
237
|
+
// challenge violates RFC 9110, and a challenge that advertised OAuth
|
|
238
|
+
// metadata would invite a discovery flow this server does not have.
|
|
239
|
+
"www-authenticate": "Bearer",
|
|
240
|
+
});
|
|
241
|
+
res.end(JSON.stringify({ error: rejection }));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
203
246
|
const sessionIdHeader = req.headers["mcp-session-id"];
|
|
204
247
|
const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
|
|
205
248
|
const existing = sessionId ? sessions.get(sessionId) : undefined;
|
package/src/server/index.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { SubscribeRequestSchema, UnsubscribeRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2
3
|
import { z } from "zod";
|
|
4
|
+
import type { LogWatcher } from "./log-watcher";
|
|
3
5
|
import { getStateTool } from "./tools/get-state";
|
|
4
6
|
import { OWNER_COMMAND_KINDS, OwnerCommandQueue } from "./owner-queue";
|
|
5
7
|
import type { OwnerCommand, OwnerCommandEnvelope, OwnerCommandKind } from "./owner-queue";
|
|
8
|
+
import { loadRoomLog } from "../log/store";
|
|
6
9
|
import { getTranscriptTool } from "./tools/get-transcript";
|
|
7
10
|
import { getAgentDeltaTool } from "./tools/get-agent-delta";
|
|
8
11
|
import { getAgentDetailTool } from "./tools/get-agent-detail";
|
|
@@ -33,7 +36,18 @@ export interface OwnerCommandResult {
|
|
|
33
36
|
reason?: string;
|
|
34
37
|
}
|
|
35
38
|
|
|
39
|
+
/** The one resource a client can subscribe to: "the log grew, ask again" (D-23). */
|
|
40
|
+
export const LOG_RESOURCE_URI = "room://log";
|
|
41
|
+
|
|
36
42
|
export interface RoomMcpServerOptions {
|
|
43
|
+
/**
|
|
44
|
+
* Shared by every session of one room. Present, the server advertises
|
|
45
|
+
* `resources.subscribe` and pushes `notifications/resources/updated` for
|
|
46
|
+
* `room://log` when the log grows; absent, it advertises nothing and a client
|
|
47
|
+
* polls as it always did. Optional for the same reason `ownerQueue` is: a unit
|
|
48
|
+
* test or an embedder can build a server without one.
|
|
49
|
+
*/
|
|
50
|
+
logWatcher?: LogWatcher;
|
|
37
51
|
/**
|
|
38
52
|
* The room's owner-command queue, shared by every session.
|
|
39
53
|
*
|
|
@@ -110,7 +124,7 @@ export function createRoomMcpServer(logPath: string, options: RoomMcpServerOptio
|
|
|
110
124
|
"pass next_seq back as since_seq to continue.",
|
|
111
125
|
inputSchema: {
|
|
112
126
|
since_seq: z.number().int().min(0),
|
|
113
|
-
limit: z.number().int().min(
|
|
127
|
+
limit: z.number().int().min(1).optional(),
|
|
114
128
|
},
|
|
115
129
|
},
|
|
116
130
|
async ({ since_seq, limit }) => ({
|
|
@@ -194,8 +208,20 @@ export function createRoomMcpServer(logPath: string, options: RoomMcpServerOptio
|
|
|
194
208
|
// is the answer — and it SETTLES the entry, because delivering the same
|
|
195
209
|
// veto twice (once to the handler, once to whoever reads the queue) is
|
|
196
210
|
// worse than one delivery to a stub the embedder wrote itself.
|
|
197
|
-
|
|
198
|
-
|
|
211
|
+
//
|
|
212
|
+
// The `ack` lives in `finally`, not after the `await`: a handler that
|
|
213
|
+
// throws still settled the entry — it just settled it badly — and
|
|
214
|
+
// leaving the slot held is a second veto lost in a new way, this time
|
|
215
|
+
// silently. Rethrowing (implicit here — nothing catches) is what tells
|
|
216
|
+
// the operator who posted it that their command was never acted on;
|
|
217
|
+
// the SDK turns the throw into an error result the same way
|
|
218
|
+
// `room.ack_owner_command` already relies on below.
|
|
219
|
+
let verdict: { status: Exclude<OwnerCommandStatus, "queued">; reason?: string };
|
|
220
|
+
try {
|
|
221
|
+
verdict = await options.onOwnerCommand({ kind, body, id: queued.id });
|
|
222
|
+
} finally {
|
|
223
|
+
queue.ack(queued.id);
|
|
224
|
+
}
|
|
199
225
|
const settled: OwnerCommandResult = { id: queued.id, status: verdict.status };
|
|
200
226
|
if (verdict.reason !== undefined) settled.reason = verdict.reason;
|
|
201
227
|
return { content: [{ type: "text", text: JSON.stringify(settled) }] };
|
|
@@ -237,6 +263,53 @@ export function createRoomMcpServer(logPath: string, options: RoomMcpServerOptio
|
|
|
237
263
|
},
|
|
238
264
|
);
|
|
239
265
|
|
|
266
|
+
const watcher = options.logWatcher;
|
|
267
|
+
if (watcher !== undefined) {
|
|
268
|
+
// Before any handler: the SDK refuses to set a subscribe handler for a
|
|
269
|
+
// capability that was not declared.
|
|
270
|
+
server.server.registerCapabilities({ resources: { subscribe: true } });
|
|
271
|
+
let subscribed = false;
|
|
272
|
+
let stopListening: (() => void) | undefined;
|
|
273
|
+
const listen = () => {
|
|
274
|
+
stopListening ??= watcher.on(() => {
|
|
275
|
+
if (subscribed) void server.server.sendResourceUpdated({ uri: LOG_RESOURCE_URI }).catch(() => undefined);
|
|
276
|
+
});
|
|
277
|
+
};
|
|
278
|
+
server.server.setRequestHandler(SubscribeRequestSchema, async ({ params }) => {
|
|
279
|
+
if (params.uri !== LOG_RESOURCE_URI) throw new Error(`Only ${LOG_RESOURCE_URI} can be subscribed to, not "${params.uri}".`);
|
|
280
|
+
subscribed = true;
|
|
281
|
+
listen();
|
|
282
|
+
return {};
|
|
283
|
+
});
|
|
284
|
+
server.server.setRequestHandler(UnsubscribeRequestSchema, async ({ params }) => {
|
|
285
|
+
if (params.uri === LOG_RESOURCE_URI) subscribed = false;
|
|
286
|
+
return {};
|
|
287
|
+
});
|
|
288
|
+
// The session going away is what releases the watcher; without this a room
|
|
289
|
+
// keeps a descriptor open for every client that ever subscribed.
|
|
290
|
+
const previousOnClose = server.server.onclose;
|
|
291
|
+
server.server.onclose = () => {
|
|
292
|
+
stopListening?.();
|
|
293
|
+
stopListening = undefined;
|
|
294
|
+
previousOnClose?.();
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
server.registerResource(
|
|
298
|
+
"log",
|
|
299
|
+
LOG_RESOURCE_URI,
|
|
300
|
+
{
|
|
301
|
+
title: "Room log position",
|
|
302
|
+
description:
|
|
303
|
+
"The highest seq in the log. Subscribe to be told when it moves, then read room.get_transcript; " +
|
|
304
|
+
"the notification carries no message text.",
|
|
305
|
+
mimeType: "application/json",
|
|
306
|
+
},
|
|
307
|
+
async (uri) => ({
|
|
308
|
+
contents: [{ uri: uri.href, text: JSON.stringify({ last_seq: loadRoomLog(logPath).messages.reduce((max, m) => Math.max(max, m.seq), 0) }) }],
|
|
309
|
+
}),
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
240
313
|
server.registerResource(
|
|
241
314
|
"owner-queue",
|
|
242
315
|
"room://owner-queue",
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { statSync, watch } from "node:fs";
|
|
2
|
+
import type { FSWatcher } from "node:fs";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Tells listeners that a room log grew (D-23).
|
|
6
|
+
*
|
|
7
|
+
* The log is append-only and written by another process as often as by this one,
|
|
8
|
+
* so the server cannot know a message landed by being the one that wrote it. It
|
|
9
|
+
* looks at the file — once per room, however many clients are attached, which is
|
|
10
|
+
* the whole point: each client used to look every second, one `room.get_transcript`
|
|
11
|
+
* apiece.
|
|
12
|
+
*
|
|
13
|
+
* `fs.watch` is the fast path and an unreliable one (it can be missed on network
|
|
14
|
+
* filesystems and under some container mounts), so a slow `stat` runs beside it.
|
|
15
|
+
* Growth is what is compared, never the event: an append-only file only gets
|
|
16
|
+
* longer, and a duplicate event is then a no-op.
|
|
17
|
+
*
|
|
18
|
+
* Nothing runs while nobody listens — a room with no subscriber holds no
|
|
19
|
+
* descriptor and no timer.
|
|
20
|
+
*/
|
|
21
|
+
export class LogWatcher {
|
|
22
|
+
private readonly listeners = new Set<() => void>();
|
|
23
|
+
private watcher: FSWatcher | undefined;
|
|
24
|
+
private timer: ReturnType<typeof setInterval> | undefined;
|
|
25
|
+
private size = 0;
|
|
26
|
+
|
|
27
|
+
constructor(
|
|
28
|
+
private readonly path: string,
|
|
29
|
+
private readonly fallbackMs = 2000,
|
|
30
|
+
) {}
|
|
31
|
+
|
|
32
|
+
/** Returns the function that stops listening. */
|
|
33
|
+
on(listener: () => void): () => void {
|
|
34
|
+
this.listeners.add(listener);
|
|
35
|
+
if (this.listeners.size === 1) this.start();
|
|
36
|
+
return () => {
|
|
37
|
+
this.listeners.delete(listener);
|
|
38
|
+
if (this.listeners.size === 0) this.stop();
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
close(): void {
|
|
43
|
+
this.listeners.clear();
|
|
44
|
+
this.stop();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private start(): void {
|
|
48
|
+
this.size = this.currentSize();
|
|
49
|
+
try {
|
|
50
|
+
this.watcher = watch(this.path, { persistent: false }, () => this.check());
|
|
51
|
+
this.watcher.on("error", () => undefined);
|
|
52
|
+
} catch {
|
|
53
|
+
// The stat below still sees every append; the watcher only makes it quicker.
|
|
54
|
+
}
|
|
55
|
+
this.timer = setInterval(() => this.check(), this.fallbackMs);
|
|
56
|
+
this.timer.unref();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private stop(): void {
|
|
60
|
+
this.watcher?.close();
|
|
61
|
+
this.watcher = undefined;
|
|
62
|
+
clearInterval(this.timer);
|
|
63
|
+
this.timer = undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private currentSize(): number {
|
|
67
|
+
try {
|
|
68
|
+
return statSync(this.path).size;
|
|
69
|
+
} catch {
|
|
70
|
+
return this.size;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private check(): void {
|
|
75
|
+
const size = this.currentSize();
|
|
76
|
+
if (size <= this.size) return;
|
|
77
|
+
this.size = size;
|
|
78
|
+
for (const listener of [...this.listeners]) listener();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -82,7 +82,13 @@ export class OwnerQueueFullError extends Error {
|
|
|
82
82
|
constructor(readonly waiting: number) {
|
|
83
83
|
super(
|
|
84
84
|
`The owner-command queue is full: ${waiting} command(s) have been posted and none has been acknowledged. ` +
|
|
85
|
-
|
|
85
|
+
// Not "nothing is reading the queue": an embedded `onOwnerCommand`
|
|
86
|
+
// handler settles entries without ever calling
|
|
87
|
+
// `room.get_pending_owner_commands`, so a full queue with a handler
|
|
88
|
+
// attached means it isn't keeping up, not that it is absent. Either
|
|
89
|
+
// way the fix is the same — drain it.
|
|
90
|
+
`A dispatcher reads it with \`room.get_pending_owner_commands\` and settles each one with ` +
|
|
91
|
+
`\`room.ack_owner_command\`, or an embedded \`onOwnerCommand\` handler is falling behind.`,
|
|
86
92
|
);
|
|
87
93
|
}
|
|
88
94
|
}
|
package/src/server/serve.ts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { createRoomMcpServer } from "./index";
|
|
2
|
+
import { LogWatcher } from "./log-watcher";
|
|
2
3
|
import { OwnerCommandQueue } from "./owner-queue";
|
|
3
4
|
import type { RoomMcpServerOptions } from "./index";
|
|
4
5
|
import { serveMcpOverHttp } from "./http-transport";
|
|
5
6
|
import type { McpHttpTransportHandle } from "./http-transport";
|
|
6
7
|
import { loadRoomLog } from "../log/store";
|
|
8
|
+
import { mintRoomToken } from "../room-token";
|
|
7
9
|
import {
|
|
8
10
|
LEASE_HEARTBEAT_MS,
|
|
9
11
|
acquireWriterLease,
|
|
10
|
-
refreshWriterLease,
|
|
11
12
|
releaseWriterLease,
|
|
13
|
+
renewWriterLease,
|
|
12
14
|
} from "../writer-lease";
|
|
15
|
+
import type { WriterLease } from "../writer-lease";
|
|
13
16
|
|
|
14
17
|
export interface ServeOptions extends RoomMcpServerOptions {
|
|
15
18
|
/** Defaults to 4319 (specification.md's default). 0 selects an ephemeral port. */
|
|
@@ -20,11 +23,31 @@ export interface ServeOptions extends RoomMcpServerOptions {
|
|
|
20
23
|
* Where the writer lease lives, when this server has a dispatcher attached.
|
|
21
24
|
* Defaults to none: an embedder that does not dispatch holds nothing, and a
|
|
22
25
|
* library caller should not acquire a lease as a side effect of binding.
|
|
26
|
+
*
|
|
27
|
+
* Passing it means accepting the consequence: if another writer takes this
|
|
28
|
+
* room over, this server **closes itself** rather than keep dispatching into a
|
|
29
|
+
* log it no longer owns. `close()` stays safe to call afterwards.
|
|
23
30
|
*/
|
|
24
31
|
writerLeasePath?: string;
|
|
25
32
|
}
|
|
26
33
|
|
|
27
|
-
export
|
|
34
|
+
export interface ServeHandle extends McpHttpTransportHandle {
|
|
35
|
+
/**
|
|
36
|
+
* The per-room token this server will answer to, minted here.
|
|
37
|
+
*
|
|
38
|
+
* On the handle as well as in the registry because the two have different
|
|
39
|
+
* jobs. The registry entry is how a *separate process* — the TUI, the CLI's
|
|
40
|
+
* room commands, the liveness probe — learns the token, and it is written by
|
|
41
|
+
* whoever registered the room. This field is how the caller that just started
|
|
42
|
+
* the server knows what to write there, and how an embedder that never
|
|
43
|
+
* registers anything can still reach its own room.
|
|
44
|
+
*
|
|
45
|
+
* Per room and per process start: a restart mints a new one, so a token
|
|
46
|
+
* recorded by something that outlived the server it belonged to is worth
|
|
47
|
+
* nothing.
|
|
48
|
+
*/
|
|
49
|
+
token: string;
|
|
50
|
+
}
|
|
28
51
|
|
|
29
52
|
/**
|
|
30
53
|
* Serves one room log over the shared loopback HTTP transport. Everything about
|
|
@@ -52,23 +75,43 @@ export async function serve(logPath: string, options: ServeOptions): Promise<Ser
|
|
|
52
75
|
// the difference between a feature and a feature that passes its tests.
|
|
53
76
|
const ownerQueue = new OwnerCommandQueue();
|
|
54
77
|
|
|
55
|
-
|
|
78
|
+
// Minted before the port is bound, so there is no window in which the room
|
|
79
|
+
// answers and has no credential. Not an option the caller may supply: a token
|
|
80
|
+
// that can be passed in is a token that can be passed in as a constant, and
|
|
81
|
+
// "per room, per process start" is the property that makes a stale one
|
|
82
|
+
// worthless.
|
|
83
|
+
const token = mintRoomToken();
|
|
84
|
+
|
|
85
|
+
const logWatcher = new LogWatcher(logPath);
|
|
86
|
+
|
|
87
|
+
const bound = await serveMcpOverHttp({
|
|
56
88
|
createMcpServer: () =>
|
|
57
|
-
createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand, ownerQueue }),
|
|
89
|
+
createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand, ownerQueue, logWatcher }),
|
|
58
90
|
commandLabel: "roomyx serve",
|
|
59
91
|
defaultPort: 4319,
|
|
60
92
|
port: options.port,
|
|
61
93
|
host: options.host,
|
|
62
94
|
acknowledgeNonLoopback: options.acknowledgeNonLoopback,
|
|
95
|
+
requiredToken: token,
|
|
63
96
|
});
|
|
97
|
+
// The watcher goes down with the transport, on every path that closes it.
|
|
98
|
+
const handle: McpHttpTransportHandle = {
|
|
99
|
+
...bound,
|
|
100
|
+
close: async () => {
|
|
101
|
+
logWatcher.close();
|
|
102
|
+
await bound.close();
|
|
103
|
+
},
|
|
104
|
+
};
|
|
64
105
|
|
|
65
106
|
// The lease is held by the process that has a dispatcher, which is this one —
|
|
66
107
|
// a server with no dispatcher is an observer, and holding a lease would claim
|
|
67
108
|
// a pen it never picks up.
|
|
68
|
-
if (options.onOwnerCommand === undefined || options.writerLeasePath === undefined)
|
|
109
|
+
if (options.onOwnerCommand === undefined || options.writerLeasePath === undefined) {
|
|
110
|
+
return { ...handle, token };
|
|
111
|
+
}
|
|
69
112
|
|
|
70
113
|
const leasePath = options.writerLeasePath;
|
|
71
|
-
let lease;
|
|
114
|
+
let lease: WriterLease;
|
|
72
115
|
try {
|
|
73
116
|
lease = acquireWriterLease(leasePath, { pid: process.pid });
|
|
74
117
|
} catch (error) {
|
|
@@ -77,34 +120,73 @@ export async function serve(logPath: string, options: ServeOptions): Promise<Ser
|
|
|
77
120
|
await handle.close().catch(() => undefined);
|
|
78
121
|
throw error;
|
|
79
122
|
}
|
|
80
|
-
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
// A refresh that fails means the lease is gone or is now someone else's —
|
|
86
|
-
// which is what a take-over does. Reporting it once matters, because
|
|
87
|
-
// otherwise this process keeps dispatching into a log it no longer owns and
|
|
88
|
-
// nothing anywhere says so.
|
|
89
|
-
if (!refreshWriterLease(leasePath, heldLease.token) && !complained) {
|
|
90
|
-
complained = true;
|
|
91
|
-
console.error(
|
|
92
|
-
`roomyx serve: this server no longer holds the writer lease for ${logPath}. ` +
|
|
93
|
-
`Another writer took it over; stop dispatching into this room.`,
|
|
94
|
-
);
|
|
95
|
-
clearInterval(heartbeat);
|
|
96
|
-
}
|
|
97
|
-
}, LEASE_HEARTBEAT_MS);
|
|
98
|
-
heartbeat.unref();
|
|
123
|
+
// The token changes when the heartbeat has to re-acquire a lease that expired
|
|
124
|
+
// under it, so what this process holds is a variable, not the value it started
|
|
125
|
+
// with. Releasing the original token after a re-acquire would leave the current
|
|
126
|
+
// one behind — the exact class of bug the owner-token rule exists to prevent.
|
|
127
|
+
let heldToken = lease.token;
|
|
99
128
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
129
|
+
// One close path, however it is reached. `httpServer.close()` rejects on a
|
|
130
|
+
// server that is already closed, so a displacement that closes the room and an
|
|
131
|
+
// embedder that then calls `close()` itself must not be two closes.
|
|
132
|
+
let closing: Promise<void> | undefined;
|
|
133
|
+
const closeOnce = async (): Promise<void> => {
|
|
134
|
+
closing ??= (async () => {
|
|
103
135
|
clearInterval(heartbeat);
|
|
104
136
|
// Close first, release second: releasing while the server still answers
|
|
105
137
|
// leaves a window where a live room looks like it has no writer.
|
|
106
138
|
await handle.close();
|
|
107
|
-
releaseWriterLease(leasePath,
|
|
108
|
-
}
|
|
139
|
+
releaseWriterLease(leasePath, heldToken);
|
|
140
|
+
})();
|
|
141
|
+
return closing;
|
|
109
142
|
};
|
|
143
|
+
|
|
144
|
+
// `unref()`, so an idle heartbeat cannot be the reason the process stays
|
|
145
|
+
// alive — the same rule the transport's session sweeper follows.
|
|
146
|
+
let reportedStall = false;
|
|
147
|
+
const heartbeat: NodeJS.Timeout = setInterval(() => {
|
|
148
|
+
const renewal = renewWriterLease(leasePath, heldToken, { pid: process.pid });
|
|
149
|
+
|
|
150
|
+
if (renewal.outcome === "refreshed") return;
|
|
151
|
+
|
|
152
|
+
if (renewal.outcome === "reacquired") {
|
|
153
|
+
// We fell behind — suspended machine, stopped container, a long pause —
|
|
154
|
+
// and nobody took the room while we were away. This used to be reported as
|
|
155
|
+
// a take-over and then `clearInterval`'d, so a server that was still the
|
|
156
|
+
// only writer stopped refreshing for good and its room became
|
|
157
|
+
// take-over-able while it was writing. Re-arm and keep going; the
|
|
158
|
+
// heartbeat's job is to state that we are here, and we are.
|
|
159
|
+
heldToken = renewal.lease.token;
|
|
160
|
+
if (!reportedStall) {
|
|
161
|
+
reportedStall = true;
|
|
162
|
+
console.error(
|
|
163
|
+
`roomyx serve: the writer lease for ${logPath} expired while this server was not refreshing it ` +
|
|
164
|
+
`(${Math.round(renewal.staleFor / 1000)}s without a heartbeat) and has been re-acquired. ` +
|
|
165
|
+
`Nobody else had claimed it.`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Displaced, for real: the record on disk belongs to another token. Advice
|
|
172
|
+
// was all this used to do, and advice is enforced by nothing — the process
|
|
173
|
+
// went on dispatching into a log it no longer owned. D-01 allows one writer
|
|
174
|
+
// per live room, so the one that lost the lease stops being a room: the
|
|
175
|
+
// transport closes, and the dispatcher's next call fails loudly instead of
|
|
176
|
+
// succeeding into a conversation someone else now owns.
|
|
177
|
+
console.error(
|
|
178
|
+
`roomyx serve: this server no longer holds the writer lease for ${logPath} — pid ${renewal.by.pid} holds it ` +
|
|
179
|
+
`now${renewal.by.takenOverFrom === undefined ? "" : ` (taken over from pid ${renewal.by.takenOverFrom.pid})`}. ` +
|
|
180
|
+
`Two writers into one append-only log is the race D-01 prevents, so this server is shutting down; stop ` +
|
|
181
|
+
`dispatching into this room.`,
|
|
182
|
+
);
|
|
183
|
+
// The lease is not ours, so there is nothing of ours to release: `closeOnce`
|
|
184
|
+
// checks the token before unlinking, which is what makes that safe.
|
|
185
|
+
void closeOnce().catch((error: unknown) => {
|
|
186
|
+
console.error(`roomyx serve: closing after losing the writer lease failed: ${String(error)}`);
|
|
187
|
+
});
|
|
188
|
+
}, LEASE_HEARTBEAT_MS);
|
|
189
|
+
heartbeat.unref();
|
|
190
|
+
|
|
191
|
+
return { ...handle, token, close: closeOnce };
|
|
110
192
|
}
|