@mrciphersmith/roomyx 0.7.1 → 0.8.0
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 +84 -0
- package/package.json +1 -1
- package/src/bundled-skills/startup-room/SKILL.md +17 -6
- package/src/cli.ts +241 -52
- package/src/client/components/message-row.ts +18 -7
- package/src/client/screens/chat-view.ts +19 -0
- package/src/client/transcript.ts +57 -4
- package/src/installer/registry.ts +46 -27
- package/src/log/types.ts +11 -0
- package/src/log/write.ts +53 -5
- package/src/server/index.ts +11 -1
- package/src/server/serve.ts +59 -1
- package/src/server/tools/get-state.ts +11 -3
- package/src/writer-lease.ts +149 -0
package/CHANGELOG.md
CHANGED
|
@@ -13,6 +13,90 @@ patch and never a minor. The rule, the reason, and an audit of the four of seven
|
|
|
13
13
|
releases that followed it are in
|
|
14
14
|
[`docs/roomyx/versioning.md`](docs/roomyx/versioning.md) and decision D-13.
|
|
15
15
|
|
|
16
|
+
## [0.8.0] — 2026-09-10
|
|
17
|
+
|
|
18
|
+
A minor, because it is breaking: `roomyx room append --force` is gone. In `0.x`
|
|
19
|
+
the minor position is the breaking position (D-13), and this one removes a flag
|
|
20
|
+
from a documented workflow.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **`room append` refuses only when a writer is actually there.** The old guard
|
|
25
|
+
treated "a room answers on this path" as "someone is writing into it", which
|
|
26
|
+
is false for every room served by bare `roomyx serve` — so `--force` was the
|
|
27
|
+
documented way to do ordinary work, and the guard guarded nothing.
|
|
28
|
+
`room.get_state` now reports `dispatcherAttached`, and a server with a
|
|
29
|
+
dispatcher holds a writer lease beside the registry. A live room with no
|
|
30
|
+
writer needs no flag; a live room with a live writer cannot be overridden at
|
|
31
|
+
all, and the refusal names its pid.
|
|
32
|
+
|
|
33
|
+
### Removed
|
|
34
|
+
|
|
35
|
+
- **`roomyx room append --force`.** Replaced by `--take-over`, which writes only
|
|
36
|
+
when the room is live but its writer is gone (its lease is stale or absent) —
|
|
37
|
+
the one case the old flag was really for — and records the take-over in the
|
|
38
|
+
log as a `status` message, because a room written by hand while its writer was
|
|
39
|
+
absent must not read afterwards as supervised. The bundled `startup-room` skill
|
|
40
|
+
no longer teaches any override.
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **`room append --json <envelope>`** writes one whole envelope, so a body
|
|
45
|
+
containing quotes or newlines no longer depends on the caller assembling JSON
|
|
46
|
+
by hand. An unknown key is refused rather than ignored: `seq` is the writer's.
|
|
47
|
+
- **`room append --body-file <path|->`** reads the body from a file, or stdin.
|
|
48
|
+
- **`room append --many`** writes a JSONL batch from stdin with consecutive
|
|
49
|
+
`seq`, all of it or none of it — half a batch would silently drop a turn from
|
|
50
|
+
the middle of a conversation.
|
|
51
|
+
- **`room.get_state.dispatcherAttached`** states whether anything is dispatching
|
|
52
|
+
into the room. Optional, so an older server's absence is not mistaken for a
|
|
53
|
+
`false`.
|
|
54
|
+
|
|
55
|
+
### Notes
|
|
56
|
+
|
|
57
|
+
- The room log's format is unchanged: the take-over trace uses the existing
|
|
58
|
+
`status` kind, and the lease is a separate file that lives beside the registry
|
|
59
|
+
rather than beside the log, which travels with the repository. One lease per
|
|
60
|
+
**room**, keyed by the log's path: a project runs several rooms at once, and a
|
|
61
|
+
single shared lease made the first room's writer refuse writes to the second's
|
|
62
|
+
log.
|
|
63
|
+
- `--take-over` does not displace a live writer. A room that reports a dispatcher
|
|
64
|
+
attached refuses until that server is stopped, because "the writer's loop hung
|
|
65
|
+
while its server kept answering" is not distinguishable from "the writer is
|
|
66
|
+
working" from outside — and guessing in that direction is what the old `--force`
|
|
67
|
+
did. The refusal says which of the two reasons applies and what to do.
|
|
68
|
+
- The server still never writes the log. This release gives it a lease, not a pen.
|
|
69
|
+
|
|
70
|
+
## [0.7.2] — 2026-09-10
|
|
71
|
+
|
|
72
|
+
A patch. Found by reading a real room log: the reply structure the log schema
|
|
73
|
+
exists to record was, in the pane that displays it, a number.
|
|
74
|
+
|
|
75
|
+
### Fixed
|
|
76
|
+
|
|
77
|
+
- **A reply names the participant it answers, instead of a sequence number.**
|
|
78
|
+
The tag read `answer re #4` — a number the client never resolved to a speaker,
|
|
79
|
+
neither in the pane nor in the file `w` writes out. In the log this was
|
|
80
|
+
measured against, four of nine messages reply and two of them answer the same
|
|
81
|
+
message, so two rows rendered as identical, unresolvable tags. The pointer now
|
|
82
|
+
reads `answer -> Inés "..."`, carrying a short clipped quote of the parent.
|
|
83
|
+
- **The kind and the reply pointer no longer vanish when a header is
|
|
84
|
+
collapsed.** Both were drawn inside the header, which is suppressed for
|
|
85
|
+
consecutive turns by one speaker, so a second turn looked exactly like a plain
|
|
86
|
+
continuation. Because the run was computed over the visible list, filtering to
|
|
87
|
+
one participant could also *hide* a tag that was there unfiltered.
|
|
88
|
+
- **`/` finds a row by the text its pointer shows.** The tag is on screen and
|
|
89
|
+
the search haystack did not include it.
|
|
90
|
+
|
|
91
|
+
### Notes
|
|
92
|
+
|
|
93
|
+
- Rendering only: no MCP tool surface, CLI flag or room-log format changed.
|
|
94
|
+
- The pointer uses an ASCII `->` and `...` rather than `→` and `…`, which are
|
|
95
|
+
East-Asian-ambiguous: their width depends on the reader's terminal, and a
|
|
96
|
+
wrong guess shifts the whole wrapped row.
|
|
97
|
+
- The tripwire in `test/client/wrap-defect.test.ts` is untouched and still
|
|
98
|
+
failing as designed.
|
|
99
|
+
|
|
16
100
|
## [0.7.1] — 2026-09-10
|
|
17
101
|
|
|
18
102
|
A patch. Found while writing setup prompts for an operator: following the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mrciphersmith/roomyx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "MCP server + terminal UI for startup-room: live room status, chat, per-agent modal, an installable room registry, and skill-sync.",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -136,15 +136,26 @@ roomyx serve .roomyx/rooms/logs/<topic>.jsonl --port 0
|
|
|
136
136
|
Then append each participant's turn verbatim as it arrives:
|
|
137
137
|
|
|
138
138
|
```bash
|
|
139
|
-
roomyx room append .roomyx/rooms/logs/<topic>.jsonl
|
|
139
|
+
roomyx room append .roomyx/rooms/logs/<topic>.jsonl \
|
|
140
140
|
--from ann --kind pitch --body "<their actual words>"
|
|
141
141
|
```
|
|
142
142
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
writer
|
|
146
|
-
|
|
147
|
-
|
|
143
|
+
**No override flag, and that is the point.** `append` refuses only when the
|
|
144
|
+
room is live *and* something is writing into it — a live room with no dispatcher
|
|
145
|
+
has no writer to race, so this succeeds as written. The guard used to require
|
|
146
|
+
`--force` here because roomyx could not tell the two apart from outside; the
|
|
147
|
+
server now reports whether a dispatcher is attached, and the writer holds a
|
|
148
|
+
lease, so the case that needed an override no longer arises. If something else
|
|
149
|
+
really is writing (you will be told its pid), the only honest move is to stop it
|
|
150
|
+
— do not look for a flag that overrides a live writer, because there is none.
|
|
151
|
+
|
|
152
|
+
`--take-over` is for a room whose writer is **provably gone** — its server has
|
|
153
|
+
stopped, or the lease it left behind has expired without being refreshed. It
|
|
154
|
+
records the take-over in the log, naming whose lease it took. It does not
|
|
155
|
+
displace a writer that is still there: a room that reports a dispatcher attached
|
|
156
|
+
keeps refusing until that server is stopped, and the refusal will tell you so.
|
|
157
|
+
Use it when you know you are the last writer, never to get past a refusal you do
|
|
158
|
+
not understand.
|
|
148
159
|
|
|
149
160
|
`--kind` is one of `pitch`, `question`, `challenge`, `answer`, `vote`, `status`,
|
|
150
161
|
`research`; `--in-reply-to <seq>` records who was being answered. Both are
|
package/src/cli.ts
CHANGED
|
@@ -4,16 +4,19 @@ import { join, resolve } from "node:path";
|
|
|
4
4
|
import { serve } from "./server/serve";
|
|
5
5
|
import { createServerShutdown } from "./server/shutdown";
|
|
6
6
|
import { init } from "./installer/init";
|
|
7
|
-
import { registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
|
|
7
|
+
import { probeRoomState, registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
|
|
8
8
|
import { archiveRoom, defaultHistoryPath, readHistory } from "./installer/history";
|
|
9
9
|
import { syncSkill } from "./installer/skill-sync";
|
|
10
|
-
import {
|
|
10
|
+
import { appendMessages, createRoomLog, LEGAL_KINDS, parseRoster } from "./log/write";
|
|
11
|
+
import type { AppendMessageOptions } from "./log/write";
|
|
12
|
+
import { acquireWriterLease, readWriterLease, writerLeasePathFor } from "./writer-lease";
|
|
11
13
|
import { MESSAGE_KINDS } from "./log/schema";
|
|
14
|
+
import { LogWriteError } from "./log/write";
|
|
12
15
|
import type { MessageEnvelope } from "./log/types";
|
|
13
16
|
import { NAMED_TARGETS, resolveTargets } from "./installer/skill-targets";
|
|
14
17
|
import { serveManagement } from "./mcp-management/server";
|
|
15
18
|
import { ArgError, parseArgs, renderFlags } from "./cli/args";
|
|
16
|
-
import type { FlagSpecs, ParsedArgs } from "./cli/args";
|
|
19
|
+
import type { FlagSpecs, FlagValues, ParsedArgs } from "./cli/args";
|
|
17
20
|
import { CLIENT_FLAGS } from "./cli/specs";
|
|
18
21
|
|
|
19
22
|
/**
|
|
@@ -35,6 +38,147 @@ function defaultConfigPath(): string {
|
|
|
35
38
|
return join(process.cwd(), ".roomyx", "config.json");
|
|
36
39
|
}
|
|
37
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Turns the flags into the messages to write, or refuses.
|
|
43
|
+
*
|
|
44
|
+
* Four ways in, and they do not compose: an envelope says everything, so a
|
|
45
|
+
* `--from` beside it is an ambiguity rather than an override — and guessing
|
|
46
|
+
* which one the caller meant is how a body goes into the wrong speaker's mouth.
|
|
47
|
+
*/
|
|
48
|
+
function pendingAppends(flags: FlagValues): AppendMessageOptions[] {
|
|
49
|
+
// Two different things are being chosen here, and conflating them was wrong:
|
|
50
|
+
// `--json` and `--many` carry a whole envelope (speaker included), while
|
|
51
|
+
// `--body` and `--body-file` carry only the body and still need `--from`.
|
|
52
|
+
// Refusing `--body-file --from b` refused a combination that has no ambiguity
|
|
53
|
+
// in it at all.
|
|
54
|
+
const envelopeSources = [flags.json !== undefined, flags.many === true].filter(Boolean).length;
|
|
55
|
+
if (envelopeSources > 1) throw new ArgError("Use one of --json or --many, not both.");
|
|
56
|
+
const bodySources = [flags.body !== undefined, flags["body-file"] !== undefined].filter(Boolean).length;
|
|
57
|
+
if (bodySources > 1) throw new ArgError("Use one of --body or --body-file, not both.");
|
|
58
|
+
|
|
59
|
+
if (envelopeSources === 1) {
|
|
60
|
+
const conflicting = ["from", "body", "body-file", "kind", "in-reply-to"].filter((f) => flags[f] !== undefined);
|
|
61
|
+
if (conflicting.length > 0) {
|
|
62
|
+
// An envelope says everything. Silently preferring one source is how a
|
|
63
|
+
// body ends up in the log under a speaker nobody chose.
|
|
64
|
+
throw new ArgError(
|
|
65
|
+
`--json/--many carry the whole envelope, so --${conflicting.join(", --")} cannot be combined with them.`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
return flags.many === true ? parseBatch(readStdin()) : [envelopeFrom(flags.json as string)];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const from = flags.from;
|
|
72
|
+
if (typeof from !== "string" || from === "") {
|
|
73
|
+
throw new ArgError("Both --from and --body are required (or pass --json, --body-file or --many).");
|
|
74
|
+
}
|
|
75
|
+
const body = typeof flags["body-file"] === "string" ? bodyFromFile(flags["body-file"]) : flags.body;
|
|
76
|
+
if (typeof body !== "string") throw new ArgError("Both --from and --body are required.");
|
|
77
|
+
|
|
78
|
+
const kind = typeof flags.kind === "string" ? flags.kind : undefined;
|
|
79
|
+
if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
|
|
80
|
+
throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
|
|
81
|
+
}
|
|
82
|
+
const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
|
|
83
|
+
if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
|
|
84
|
+
throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
|
|
85
|
+
}
|
|
86
|
+
return [{ from, body, kind: kind as MessageEnvelope["kind"], inReplyTo }];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function readStdin(): string {
|
|
90
|
+
if (process.stdin.isTTY === true) {
|
|
91
|
+
// Reading fd 0 from a terminal blocks until Ctrl-D, which reads as a hang.
|
|
92
|
+
throw new ArgError("This flag reads the message from stdin, and stdin is a terminal. Pipe the text in, or use --body.");
|
|
93
|
+
}
|
|
94
|
+
return readFileSync(0, "utf8");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function bodyFromFile(file: string): string {
|
|
98
|
+
// A trailing newline is what every editor and every `echo` adds; it is not
|
|
99
|
+
// part of what the speaker said, and it would land inside the quoted body.
|
|
100
|
+
const raw = file === "-" ? readStdin() : readFileSync(resolve(file), "utf8");
|
|
101
|
+
return raw.replace(/\r?\n$/, "");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const ENVELOPE_KEYS = ["from", "body", "kind", "in_reply_to"] as const;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Parses one envelope, refusing keys that would silently vanish.
|
|
108
|
+
*
|
|
109
|
+
* An unknown key is a refusal rather than something ignored: `seq` and `type`
|
|
110
|
+
* are assigned by the writer, and a caller who passes one believes they chose
|
|
111
|
+
* it — so accepting the envelope while dropping their value is the one answer
|
|
112
|
+
* that cannot be discovered from the log.
|
|
113
|
+
*/
|
|
114
|
+
function envelopeFrom(text: string): AppendMessageOptions {
|
|
115
|
+
let parsed: unknown;
|
|
116
|
+
try {
|
|
117
|
+
parsed = JSON.parse(text) as unknown;
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw new ArgError(`--json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
120
|
+
}
|
|
121
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
122
|
+
throw new ArgError("--json must be a JSON object.");
|
|
123
|
+
}
|
|
124
|
+
const envelope = parsed as Record<string, unknown>;
|
|
125
|
+
for (const key of Object.keys(envelope)) {
|
|
126
|
+
if (!(ENVELOPE_KEYS as readonly string[]).includes(key)) {
|
|
127
|
+
throw new ArgError(`--json has an unknown key "${key}". Allowed: ${ENVELOPE_KEYS.join(", ")}.`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const { from, body, kind, in_reply_to: inReplyTo } = envelope;
|
|
131
|
+
if (typeof from !== "string" || from === "") throw new ArgError('--json needs a non-empty "from".');
|
|
132
|
+
if (typeof body !== "string") throw new ArgError('--json needs a string "body".');
|
|
133
|
+
if (kind !== undefined && (typeof kind !== "string" || !(MESSAGE_KINDS as readonly string[]).includes(kind))) {
|
|
134
|
+
throw new ArgError(`--json "kind" must be one of: ${LEGAL_KINDS}.`);
|
|
135
|
+
}
|
|
136
|
+
if (inReplyTo !== undefined && (typeof inReplyTo !== "number" || !Number.isInteger(inReplyTo) || inReplyTo < 1)) {
|
|
137
|
+
throw new ArgError('--json "in_reply_to" must be a whole number of at least 1.');
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
from,
|
|
141
|
+
body,
|
|
142
|
+
kind: kind as MessageEnvelope["kind"],
|
|
143
|
+
inReplyTo: inReplyTo as number | undefined,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function parseBatch(text: string): AppendMessageOptions[] {
|
|
148
|
+
const lines = text.split("\n").filter((line) => line.trim().length > 0);
|
|
149
|
+
if (lines.length === 0) throw new ArgError("--many read no envelopes from stdin.");
|
|
150
|
+
return lines.map((line, index) => {
|
|
151
|
+
try {
|
|
152
|
+
return envelopeFrom(line);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
throw new ArgError(`--many line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Writes the batch, or none of it. `appendMessages` allocates consecutive `seq`
|
|
161
|
+
* and validates every envelope before the first byte, so a refused batch leaves
|
|
162
|
+
* the log exactly as it was.
|
|
163
|
+
*/
|
|
164
|
+
function writeAll(path: string, pending: AppendMessageOptions[]) {
|
|
165
|
+
try {
|
|
166
|
+
return appendMessages(path, pending);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (error instanceof LogWriteError) throw new ArgError(error.message);
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The holder a take-over displaced, when there was one. */
|
|
174
|
+
function stateBefore(lease: import("./writer-lease").LeaseState): { pid: number; at: number } | undefined {
|
|
175
|
+
if (lease.held) return { pid: lease.lease.pid, at: lease.lease.at };
|
|
176
|
+
// A stale lease still identifies the writer that stopped: recording it is the
|
|
177
|
+
// difference between a log that says "someone took this over" and one that
|
|
178
|
+
// says who from.
|
|
179
|
+
return lease.reason === "stale" ? { pid: lease.last.pid, at: lease.last.at } : undefined;
|
|
180
|
+
}
|
|
181
|
+
|
|
38
182
|
function bundledSkillPath(): string {
|
|
39
183
|
return join(import.meta.dir, "bundled-skills", "startup-room", "SKILL.md");
|
|
40
184
|
}
|
|
@@ -163,69 +307,110 @@ const COMMANDS: Record<string, Command> = {
|
|
|
163
307
|
},
|
|
164
308
|
|
|
165
309
|
"room append": {
|
|
166
|
-
usage: "roomyx room append <path> --from <id> --body <text> [flags]",
|
|
310
|
+
usage: "roomyx room append <path> (--from <id> --body <text> | --json <envelope> | --body-file <file> | --many) [flags]",
|
|
167
311
|
summary: "append a message to a room log",
|
|
168
312
|
notes:
|
|
169
|
-
"Refuses when
|
|
313
|
+
"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.",
|
|
170
314
|
flags: {
|
|
171
|
-
from: { type: "string", describe: "
|
|
172
|
-
body: { type: "string", describe: "
|
|
315
|
+
from: { type: "string", describe: "Participant id" },
|
|
316
|
+
body: { type: "string", describe: "The message" },
|
|
317
|
+
json: { type: "string", describe: "A whole envelope: {from, body, kind?, in_reply_to?}" },
|
|
318
|
+
"body-file": { type: "string", describe: "Read the body from a file, or - for stdin" },
|
|
319
|
+
many: { type: "boolean", describe: "Read a JSONL batch of envelopes from stdin; all of them or none" },
|
|
173
320
|
kind: { type: "string", describe: "Message kind, e.g. challenge" },
|
|
174
321
|
"in-reply-to": { type: "number", describe: "seq of the message replied to" },
|
|
175
|
-
|
|
322
|
+
"take-over": { type: "boolean", describe: "Write when the room is live but its writer is gone" },
|
|
176
323
|
registry: REGISTRY_FLAG,
|
|
177
324
|
},
|
|
178
325
|
run: async ({ positionals, flags }) => {
|
|
179
326
|
const path = positionals[0];
|
|
180
327
|
if (!path) throw new ArgError("Missing <path>.");
|
|
181
|
-
const from = flags.from;
|
|
182
|
-
const body = flags.body;
|
|
183
|
-
if (typeof from !== "string" || typeof body !== "string") {
|
|
184
|
-
throw new ArgError("Both --from and --body are required.");
|
|
185
|
-
}
|
|
186
|
-
|
|
187
328
|
const absolute = resolve(path);
|
|
188
|
-
if (flags.force !== true) {
|
|
189
|
-
const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
|
|
190
|
-
const serving = (await listLiveRooms(registryPath)).find((room) => room.logPath === absolute);
|
|
191
|
-
if (serving) {
|
|
192
|
-
// The old wording ended "Pass --force if you know it isn't" — it asked
|
|
193
|
-
// the operator to assert the room is gone. But the common case for
|
|
194
|
-
// reaching this message is a room served by bare `roomyx serve`, where
|
|
195
|
-
// the room is genuinely live and simply has no dispatcher attached, so
|
|
196
|
-
// there is no second writer to race. The flag was the right escape
|
|
197
|
-
// hatch behind a claim that was false exactly when you needed it.
|
|
198
|
-
//
|
|
199
|
-
// roomyx cannot tell the two apart: the registry records that a room
|
|
200
|
-
// serves this path, not whether anything is dispatching into it. So
|
|
201
|
-
// say what is known and let the operator judge, rather than making
|
|
202
|
-
// --force mean something untrue.
|
|
203
|
-
throw new ArgError(
|
|
204
|
-
`A live room (${serving.id}) is serving this log. If it has a dispatcher, that dispatcher is the log's single writer (D-01a) and appending here races it. Pass --force to append anyway.`,
|
|
205
|
-
);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
329
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
//
|
|
212
|
-
//
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
330
|
+
const takeOver = flags["take-over"] === true;
|
|
331
|
+
|
|
332
|
+
// Absolute, because the lease lives beside the registry and this process's
|
|
333
|
+
// cwd is not the next process's: a relative `--registry` made the lease
|
|
334
|
+
// land in a different directory depending on where the command was run.
|
|
335
|
+
const absoluteRegistry = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
|
|
336
|
+
const leasePath = writerLeasePathFor(absoluteRegistry, absolute);
|
|
337
|
+
|
|
338
|
+
const serving = (await listLiveRooms(absoluteRegistry)).find((room) => room.logPath === absolute);
|
|
339
|
+
|
|
340
|
+
// Read the lease BEFORE the probe, and independently of its outcome. A
|
|
341
|
+
// liveness probe that times out says "could not reach it", which is not
|
|
342
|
+
// "nothing is writing into it" — and reading the lease only once the probe
|
|
343
|
+
// succeeded meant a busy machine wrote into a room whose dispatcher was
|
|
344
|
+
// perfectly alive.
|
|
345
|
+
const lease = readWriterLease(leasePath);
|
|
346
|
+
const dispatched = serving !== undefined ? ((await probeRoomState(serving))?.dispatcherAttached ?? undefined) : undefined;
|
|
347
|
+
|
|
348
|
+
// Two independent pieces of evidence that someone else is writing: a live
|
|
349
|
+
// dispatcher, and a lease somebody is refreshing. The second exists because
|
|
350
|
+
// the first only holds for a server that was started with a lease path.
|
|
351
|
+
const writerPresent = lease.held || dispatched === true;
|
|
352
|
+
const writerWasThere = !writerPresent && lease.reason === "stale";
|
|
353
|
+
|
|
354
|
+
if (writerPresent) {
|
|
355
|
+
// Two different reasons to refuse, and they need different advice: a
|
|
356
|
+
// lease that is merely stale will expire by itself, while a room that
|
|
357
|
+
// reports a dispatcher will keep reporting one until the server is
|
|
358
|
+
// stopped — waiting would be advice that never comes true.
|
|
359
|
+
const advice =
|
|
360
|
+
dispatched === true
|
|
361
|
+
? `Stop the server that is running the room; once it is gone, --take-over will let you write to this log.`
|
|
362
|
+
: `Wait for that lease to expire (a writer that is running refreshes it), or stop the process holding it.`;
|
|
363
|
+
throw new ArgError(
|
|
364
|
+
`A writer is live in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`}` +
|
|
365
|
+
`${lease.held ? ` — pid ${lease.lease.pid}` : " — the room reports a dispatcher attached"}. ` +
|
|
366
|
+
`Two writers into one append-only log is the race D-01 exists to prevent, and nothing overrides a writer ` +
|
|
367
|
+
`that is still there. ${advice}`,
|
|
368
|
+
);
|
|
216
369
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
370
|
+
if (writerWasThere && !takeOver) {
|
|
371
|
+
throw new ArgError(
|
|
372
|
+
`A writer was in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`} and is gone — ` +
|
|
373
|
+
`nothing holds the lease now. Writing means taking ownership from a room that looks supervised. ` +
|
|
374
|
+
`Pass --take-over to do that deliberately; the log will record it.`,
|
|
375
|
+
);
|
|
220
376
|
}
|
|
221
377
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
378
|
+
// Parsed only after the refusal: an operator whose command is going to be
|
|
379
|
+
// rejected should not be made to pipe a batch in first, and a reader that
|
|
380
|
+
// blocks on stdin while holding a decision helps nobody.
|
|
381
|
+
const pending = pendingAppends(flags);
|
|
382
|
+
|
|
383
|
+
const displaced = takeOver || writerWasThere ? stateBefore(lease) : undefined;
|
|
384
|
+
const takingOver = takeOver || writerWasThere;
|
|
385
|
+
|
|
386
|
+
// One batch, one lock section: the take-over trace goes in WITH the
|
|
387
|
+
// messages it describes. Written as a second call it could fail on its
|
|
388
|
+
// own, and a room written by hand while its writer was absent would read
|
|
389
|
+
// afterwards as supervised — the one thing the trace exists to prevent.
|
|
390
|
+
const written = writeAll(absolute, [
|
|
391
|
+
...pending,
|
|
392
|
+
...(takingOver
|
|
393
|
+
? [
|
|
394
|
+
{
|
|
395
|
+
from: "owner",
|
|
396
|
+
kind: "status" as const,
|
|
397
|
+
body:
|
|
398
|
+
`--take-over: ${pending.length} message(s) appended to ${absolute}` +
|
|
399
|
+
`${serving === undefined ? "" : ` while room ${serving.id} was live`} with no live writer` +
|
|
400
|
+
`${displaced === undefined ? " (no lease was held)" : ` (took over from pid ${displaced.pid})`}`,
|
|
401
|
+
},
|
|
402
|
+
]
|
|
403
|
+
: []),
|
|
404
|
+
]);
|
|
405
|
+
|
|
406
|
+
if (takingOver) {
|
|
407
|
+
// The lease is replaced with a new token, so a writer that was merely
|
|
408
|
+
// paused cannot revive the one it lost by refreshing it — the whole
|
|
409
|
+
// reason a take-over is not just a flag on the write.
|
|
410
|
+
acquireWriterLease(leasePath, { pid: process.pid, ...(displaced === undefined ? {} : { takeOverFrom: displaced }) });
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
for (const message of written) console.log(`Appended seq ${message.seq} from ${message.from}.`);
|
|
229
414
|
},
|
|
230
415
|
},
|
|
231
416
|
|
|
@@ -246,13 +431,17 @@ const COMMANDS: Record<string, Command> = {
|
|
|
246
431
|
// directory: `roomyx-client` resolves rooms from wherever the person
|
|
247
432
|
// happened to run it, and a relative logPath means nothing there.
|
|
248
433
|
const absoluteLogPath = resolve(logPath);
|
|
434
|
+
// Resolved before binding: the writer lease lives beside the registry, and
|
|
435
|
+
// a server that acquires one after it starts answering would leave a
|
|
436
|
+
// window where a live dispatcher looks like no writer at all.
|
|
437
|
+
const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
|
|
249
438
|
const handle = await serve(absoluteLogPath, {
|
|
250
439
|
port: typeof flags.port === "number" ? flags.port : undefined,
|
|
251
440
|
host: typeof flags.host === "string" ? flags.host : undefined,
|
|
252
441
|
acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
|
|
442
|
+
writerLeasePath: writerLeasePathFor(resolve(registryPath), absoluteLogPath),
|
|
253
443
|
});
|
|
254
444
|
|
|
255
|
-
const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
|
|
256
445
|
const entry = registerRoom(registryPath, {
|
|
257
446
|
port: handle.port,
|
|
258
447
|
logPath: absoluteLogPath,
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { BoxRenderable, TextRenderable } from "@opentui/core";
|
|
2
2
|
import type { RenderContext } from "@opentui/core";
|
|
3
|
+
import { messageTag } from "../transcript";
|
|
4
|
+
import type { ReplyTarget } from "../transcript";
|
|
3
5
|
import type { MessageEnvelope } from "../../log/types";
|
|
4
6
|
|
|
5
7
|
/**
|
|
@@ -23,6 +25,14 @@ import type { MessageEnvelope } from "../../log/types";
|
|
|
23
25
|
* The tag stays ASCII on purpose: `↩` and `→` are East-Asian-ambiguous, so
|
|
24
26
|
* their width depends on the reader's terminal, and a wrong guess shifts the
|
|
25
27
|
* whole wrapped row.
|
|
28
|
+
*
|
|
29
|
+
* A third defect lived in this file and is kept written down for the same
|
|
30
|
+
* reason: the tag was added *inside* the header, and the header is suppressed
|
|
31
|
+
* for consecutive turns by one speaker — so the second turn lost its kind and
|
|
32
|
+
* its reply pointer, and two materially different messages rendered
|
|
33
|
+
* identically. Whether a header is drawn is a question about the speaker;
|
|
34
|
+
* whether a tag is drawn is a question about the message, and they are not the
|
|
35
|
+
* same question. See D-17.
|
|
26
36
|
*/
|
|
27
37
|
export const SPEAKER_FG = "#ffffff";
|
|
28
38
|
export const TAG_FG = "#8a8a8a";
|
|
@@ -36,12 +46,8 @@ export interface MessageRowOptions {
|
|
|
36
46
|
showHeader: boolean;
|
|
37
47
|
/** False for the first row, which needs no separating blank line above it. */
|
|
38
48
|
separate: boolean;
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
function tagFor(message: MessageEnvelope): string {
|
|
42
|
-
return [message.kind, message.in_reply_to === undefined ? null : `re #${message.in_reply_to}`]
|
|
43
|
-
.filter((part): part is string => Boolean(part))
|
|
44
|
-
.join(" ");
|
|
49
|
+
/** The turn this one answers, already resolved to a speaker by the caller. */
|
|
50
|
+
replyTo?: ReplyTarget;
|
|
45
51
|
}
|
|
46
52
|
|
|
47
53
|
export function createMessageRow(
|
|
@@ -55,12 +61,17 @@ export function createMessageRow(
|
|
|
55
61
|
marginTop: options.separate ? 1 : 0,
|
|
56
62
|
});
|
|
57
63
|
|
|
64
|
+
const tag = messageTag(message, options.replyTo);
|
|
65
|
+
|
|
58
66
|
if (options.showHeader) {
|
|
59
67
|
const header = new BoxRenderable(ctx, { flexDirection: "row", height: 1 });
|
|
60
68
|
header.add(new TextRenderable(ctx, { content: fromName, fg: SPEAKER_FG, attributes: 1, height: 1 }));
|
|
61
|
-
const tag = tagFor(message);
|
|
62
69
|
if (tag) header.add(new TextRenderable(ctx, { content: ` ${tag}`, fg: TAG_FG, height: 1 }));
|
|
63
70
|
row.add(header);
|
|
71
|
+
} else if (tag) {
|
|
72
|
+
// Its own indented line, because there is no header to sit in. The kind and
|
|
73
|
+
// the pointer must not be collapsible with the speaker's name.
|
|
74
|
+
row.add(new TextRenderable(ctx, { content: tag, fg: TAG_FG, height: 1, marginLeft: 2 }));
|
|
64
75
|
}
|
|
65
76
|
|
|
66
77
|
row.add(
|
|
@@ -37,6 +37,12 @@ export class ChatView {
|
|
|
37
37
|
private readonly scroll: ScrollBoxRenderable;
|
|
38
38
|
private readonly ctx: RenderContext;
|
|
39
39
|
private rosterById = new Map<string, RosterEntry>();
|
|
40
|
+
/**
|
|
41
|
+
* Every message seen so far, by `seq`, so a reply pointer can name its
|
|
42
|
+
* parent. Kept here rather than in `Transcript` because the roster — the
|
|
43
|
+
* thing that turns an id into a name — is here too.
|
|
44
|
+
*/
|
|
45
|
+
private messagesBySeq = new Map<number, MessageEnvelope>();
|
|
40
46
|
private rows: Renderable[] = [];
|
|
41
47
|
private readonly rosterVisible: boolean;
|
|
42
48
|
|
|
@@ -112,11 +118,23 @@ export class ChatView {
|
|
|
112
118
|
|
|
113
119
|
appendMessages(messages: MessageEnvelope[]): void {
|
|
114
120
|
for (const message of messages) {
|
|
121
|
+
// Resolved before this message is recorded, so a pointer can only ever
|
|
122
|
+
// name an *earlier* turn — the log is append-only and the parent is
|
|
123
|
+
// always already here. That is what lets a tag be known when the row is
|
|
124
|
+
// built and keeps rendering incremental: no drawn row is ever amended.
|
|
125
|
+
const parent =
|
|
126
|
+
message.in_reply_to === undefined ? undefined : this.messagesBySeq.get(message.in_reply_to);
|
|
127
|
+
const replyTo =
|
|
128
|
+
parent === undefined
|
|
129
|
+
? undefined
|
|
130
|
+
: { name: this.rosterById.get(parent.from)?.name ?? parent.from, body: parent.body };
|
|
115
131
|
this.appendEntry({
|
|
116
132
|
kind: "message",
|
|
117
133
|
message,
|
|
118
134
|
fromName: this.rosterById.get(message.from)?.name ?? message.from,
|
|
135
|
+
...(replyTo === undefined ? {} : { replyTo }),
|
|
119
136
|
});
|
|
137
|
+
this.messagesBySeq.set(message.seq, message);
|
|
120
138
|
}
|
|
121
139
|
}
|
|
122
140
|
|
|
@@ -206,6 +224,7 @@ export class ChatView {
|
|
|
206
224
|
// changed.
|
|
207
225
|
showHeader: this.transcript.startsRun(index),
|
|
208
226
|
separate,
|
|
227
|
+
...(entry.replyTo === undefined ? {} : { replyTo: entry.replyTo }),
|
|
209
228
|
});
|
|
210
229
|
|
|
211
230
|
this.rows.push(row);
|
package/src/client/transcript.ts
CHANGED
|
@@ -25,6 +25,13 @@ export interface MessageEntry {
|
|
|
25
25
|
message: MessageEnvelope;
|
|
26
26
|
/** Resolved display name, so the model can be searched by what is on screen. */
|
|
27
27
|
fromName: string;
|
|
28
|
+
/**
|
|
29
|
+
* The turn this one answers, resolved to a speaker by whoever built the
|
|
30
|
+
* entry. Absent when the message answers nothing, or answers a `seq` this
|
|
31
|
+
* log does not contain — and absent means nothing is drawn, which is the
|
|
32
|
+
* point: the number it replaced named nobody (D-17).
|
|
33
|
+
*/
|
|
34
|
+
replyTo?: ReplyTarget;
|
|
28
35
|
}
|
|
29
36
|
|
|
30
37
|
export type Entry = MessageEntry | SystemEntry;
|
|
@@ -75,7 +82,7 @@ export class Transcript {
|
|
|
75
82
|
const haystack =
|
|
76
83
|
entry.kind === "system"
|
|
77
84
|
? entry.text
|
|
78
|
-
: `${entry.fromName} ${entry.message.
|
|
85
|
+
: `${entry.fromName} ${messageTag(entry.message, entry.replyTo)} ${entry.message.body}`;
|
|
79
86
|
return haystack.toLowerCase().includes(needle) ? index : -1;
|
|
80
87
|
})
|
|
81
88
|
.filter((index) => index >= 0);
|
|
@@ -114,11 +121,57 @@ export class Transcript {
|
|
|
114
121
|
return this.visible()
|
|
115
122
|
.map((entry) => {
|
|
116
123
|
if (entry.kind === "system") return `— ${entry.text} —`;
|
|
117
|
-
const tag =
|
|
118
|
-
.filter((part): part is string => Boolean(part))
|
|
119
|
-
.join(" ");
|
|
124
|
+
const tag = messageTag(entry.message, entry.replyTo);
|
|
120
125
|
return `${entry.fromName}${tag ? ` ${tag}` : ""}\n ${entry.message.body}`;
|
|
121
126
|
})
|
|
122
127
|
.join("\n\n");
|
|
123
128
|
}
|
|
124
129
|
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* How much of the parent's body the pointer quotes, in code units.
|
|
133
|
+
*
|
|
134
|
+
* A budget rather than a proportion of the pane: the tag sits on one
|
|
135
|
+
* `height: 1` line beside a name, and anything that has to be measured against
|
|
136
|
+
* a live width would make the tag's text depend on the terminal it is drawn in.
|
|
137
|
+
* Code units, not display cells — the same deferral `clip.ts` records for the
|
|
138
|
+
* same reason.
|
|
139
|
+
*/
|
|
140
|
+
const QUOTE_CELLS = 24;
|
|
141
|
+
|
|
142
|
+
export interface ReplyTarget {
|
|
143
|
+
/** The parent's resolved display name. Never a sequence number: a number names nobody. */
|
|
144
|
+
name: string;
|
|
145
|
+
/** The parent's body, for the short quote. */
|
|
146
|
+
body: string;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Cut to size in ASCII.
|
|
151
|
+
*
|
|
152
|
+
* `clip()` — the client's other cutter — marks a cut with `…`, and this line
|
|
153
|
+
* must not: U+2026 is East-Asian-ambiguous, so its width depends on the
|
|
154
|
+
* reader's terminal, and the tag is laid out against the same pane the body
|
|
155
|
+
* wraps in. A quote is context, not content; it does not get to move where a
|
|
156
|
+
* sentence breaks.
|
|
157
|
+
*/
|
|
158
|
+
function quote(body: string): string {
|
|
159
|
+
// Whitespace is flattened first: a parent's newline would otherwise put a
|
|
160
|
+
// second line under a tag that is `height: 1`.
|
|
161
|
+
const flat = body.replace(/\s+/g, " ").trim();
|
|
162
|
+
if (flat.length <= QUOTE_CELLS) return flat;
|
|
163
|
+
return `${flat.slice(0, QUOTE_CELLS - 3).trimEnd()}...`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The one place the kind and reply tag is spelled.
|
|
168
|
+
*
|
|
169
|
+
* It used to be assembled twice — in `message-row.ts` for the pane, and inline
|
|
170
|
+
* in `toText()` for the export — so the two could disagree about what a message
|
|
171
|
+
* said, and neither was visible to `matches()`. The tag is drawn on screen,
|
|
172
|
+
* which is the whole test of whether a search has to find it.
|
|
173
|
+
*/
|
|
174
|
+
export function messageTag(message: MessageEnvelope, replyTo?: ReplyTarget): string {
|
|
175
|
+
const pointer = replyTo === undefined ? "" : `-> ${replyTo.name} "${quote(replyTo.body)}"`;
|
|
176
|
+
return [message.kind, pointer].filter((part): part is string => Boolean(part)).join(" ");
|
|
177
|
+
}
|
|
@@ -179,46 +179,65 @@ function isPidAlive(pid: number): boolean {
|
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Asks a registered room what it is, or `undefined` when nothing answers.
|
|
184
|
+
*
|
|
185
|
+
* Extracted from `isRoomLive` so the CLI can reach the same answer for the same
|
|
186
|
+
* reason: whether a room is live and whether anything is *writing* into it come
|
|
187
|
+
* from one reply, and two probes could disagree.
|
|
188
|
+
*/
|
|
189
|
+
/**
|
|
190
|
+
* The loopback address this probe dials.
|
|
191
|
+
*
|
|
192
|
+
* Assembled from its octets rather than written as a literal on purpose. Text
|
|
193
|
+
* that passes through this repository's tooling has IP literals replaced with a
|
|
194
|
+
* redaction marker, and a marker written into a source file is a syntax-level
|
|
195
|
+
* runtime failure — `new URL()` throws — that no unit test catches, because the
|
|
196
|
+
* tests build their URLs from the same constant. It cost one debugging round to
|
|
197
|
+
* find; it costs nothing to avoid.
|
|
198
|
+
*/
|
|
199
|
+
const LOOPBACK_HOST = [127, 0, 0, 1].join(".");
|
|
193
200
|
|
|
201
|
+
export async function probeRoomState(
|
|
202
|
+
room: RoomRegistryEntry,
|
|
203
|
+
timeoutMs = 500,
|
|
204
|
+
): Promise<{ log_path?: string; dispatcherAttached?: boolean } | undefined> {
|
|
205
|
+
if (!isPidAlive(room.pid)) return undefined;
|
|
194
206
|
const client = new Client({ name: "roomyx-registry-check", version: "0.1.0" });
|
|
195
|
-
const transport = new StreamableHTTPClientTransport(new URL(`http
|
|
207
|
+
const transport = new StreamableHTTPClientTransport(new URL(`http://${LOOPBACK_HOST}:${room.port}/mcp`));
|
|
196
208
|
const timeout = new Promise<never>((_, reject) => {
|
|
197
209
|
setTimeout(() => reject(new Error("liveness check timed out")), timeoutMs);
|
|
198
210
|
});
|
|
199
211
|
try {
|
|
200
212
|
await Promise.race([client.connect(transport), timeout]);
|
|
201
|
-
// Connecting proves something MCP-speaking answers on that port. Asking it
|
|
202
|
-
// which log it serves is what proves it is *this* room — the pid check
|
|
203
|
-
// above narrows the window and does not close it, because a pid can be
|
|
204
|
-
// recycled and every serve defaults to the same port.
|
|
205
213
|
const result = await Promise.race([client.callTool({ name: "room.get_state", arguments: {} }), timeout]);
|
|
206
214
|
const content = result.content as Array<{ type: string; text: string }> | undefined;
|
|
207
215
|
const text = content?.[0]?.text;
|
|
208
|
-
if (text === undefined) return
|
|
209
|
-
|
|
210
|
-
// An older server that predates `log_path` answers without it. Treat that
|
|
211
|
-
// as "cannot be shown to be a different room" rather than as dead: failing
|
|
212
|
-
// toward the previous behaviour is the safe direction here, because the
|
|
213
|
-
// cost of wrongly pruning a live room is higher than of keeping a stale one.
|
|
214
|
-
return state.log_path === undefined || state.log_path === room.logPath;
|
|
216
|
+
if (text === undefined) return undefined;
|
|
217
|
+
return JSON.parse(text) as { log_path?: string; dispatcherAttached?: boolean };
|
|
215
218
|
} catch {
|
|
216
|
-
return
|
|
219
|
+
return undefined;
|
|
217
220
|
} finally {
|
|
218
|
-
// This probe runs for every registered room on every `rooms list`, every
|
|
219
|
-
// `room append` and every client start. Closing without terminating left
|
|
220
|
-
// one abandoned server-side session behind each time.
|
|
221
221
|
await transport.terminateSession().catch(() => undefined);
|
|
222
222
|
await client.close().catch(() => undefined);
|
|
223
223
|
}
|
|
224
224
|
}
|
|
225
|
+
|
|
226
|
+
async function isRoomLive(room: RoomRegistryEntry, timeoutMs = 500): Promise<boolean> {
|
|
227
|
+
// The probe below proves that *something* MCP-speaking answers on that port,
|
|
228
|
+
// never that it is this room. Every `roomyx serve` defaults to 4319, so a
|
|
229
|
+
// room that died without deregistering was resurrected as live by the next
|
|
230
|
+
// room to bind the port — and then `roomyx-client --room <dead-id>` silently
|
|
231
|
+
// rendered a different room's transcript under the dead room's id, while
|
|
232
|
+
// `room append` refused a log nothing was serving.
|
|
233
|
+
//
|
|
234
|
+
// The pid has been in the registry all along and was never read. Checking it
|
|
235
|
+
// first also skips a 500 ms network probe per dead entry.
|
|
236
|
+
const state = await probeRoomState(room, timeoutMs);
|
|
237
|
+
if (state === undefined) return false;
|
|
238
|
+
// An older server that predates `log_path` answers without it. Treat that
|
|
239
|
+
// as "cannot be shown to be a different room" rather than as dead: failing
|
|
240
|
+
// toward the previous behaviour is the safe direction here, because the
|
|
241
|
+
// cost of wrongly pruning a live room is higher than of keeping a stale one.
|
|
242
|
+
return state.log_path === undefined || state.log_path === room.logPath;
|
|
243
|
+
}
|
package/src/log/types.ts
CHANGED
|
@@ -47,6 +47,17 @@ export interface RoomState {
|
|
|
47
47
|
* what an older server returns.
|
|
48
48
|
*/
|
|
49
49
|
log_path?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Whether anything is dispatching into the room this server is serving —
|
|
52
|
+
* i.e. whether the process that embedded this server supplied an
|
|
53
|
+
* owner-command handler.
|
|
54
|
+
*
|
|
55
|
+
* Optional, for the same D-13 reason as `log_path`: making it required would
|
|
56
|
+
* break every construction of a `RoomState`, which is a minor bump on its own.
|
|
57
|
+
* A consumer that reads an absent value must treat it as "cannot be shown to
|
|
58
|
+
* be dispatching", never as `false` — the two are different claims.
|
|
59
|
+
*/
|
|
60
|
+
dispatcherAttached?: boolean;
|
|
50
61
|
}
|
|
51
62
|
|
|
52
63
|
export type AgentDetail =
|
package/src/log/write.ts
CHANGED
|
@@ -74,6 +74,42 @@ export function nextSeq(path: string): number {
|
|
|
74
74
|
return seqs.length > 0 ? Math.max(...seqs) + 1 : 1;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Writes several messages as one unit: either every one of them lands with
|
|
79
|
+
* consecutive `seq`, or none does.
|
|
80
|
+
*
|
|
81
|
+
* Half a batch is worse than a refused one. A dispatcher posting a turn's
|
|
82
|
+
* messages gets no second chance to notice a gap — the log is append-only and
|
|
83
|
+
* the transcript is read as the record of what was said, so a batch that wrote
|
|
84
|
+
* its first two lines and rejected the third has silently dropped a turn from
|
|
85
|
+
* the middle of a conversation.
|
|
86
|
+
*/
|
|
87
|
+
export function appendMessages(
|
|
88
|
+
path: string,
|
|
89
|
+
batch: AppendMessageOptions[],
|
|
90
|
+
): (MessageEnvelope & { type: "message" })[] {
|
|
91
|
+
if (batch.length === 0) return [];
|
|
92
|
+
return withLock(path, () => {
|
|
93
|
+
if (!existsSync(path)) {
|
|
94
|
+
throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
|
|
95
|
+
}
|
|
96
|
+
// Allocated and validated as one set, before a single byte is written.
|
|
97
|
+
const base = nextSeq(path);
|
|
98
|
+
const built = batch.map((options, index) => buildMessage(base + index, options));
|
|
99
|
+
for (const message of built) validate(message);
|
|
100
|
+
// All-or-nothing covers every failure this function can SEE: a bad envelope
|
|
101
|
+
// in the batch throws before the first byte. It does NOT cover an I/O failure
|
|
102
|
+
// partway through the appends below — a full disk or a signal mid-loop leaves
|
|
103
|
+
// the earlier lines written. Making that atomic would mean writing a
|
|
104
|
+
// temporary file and renaming it, which the append-only contract rules out:
|
|
105
|
+
// the log is appended to in place by design, and a rename would replace the
|
|
106
|
+
// file a live reader has open. Stated rather than left implied, because
|
|
107
|
+
// "atomic" without a stated bound is the claim a later reader would trust.
|
|
108
|
+
for (const message of built) appendFileSync(path, JSON.stringify(message) + "\n");
|
|
109
|
+
return built;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
77
113
|
export function appendMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
|
|
78
114
|
if (!existsSync(path)) {
|
|
79
115
|
throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
|
|
@@ -91,6 +127,22 @@ export function appendMessage(path: string, options: AppendMessageOptions): Mess
|
|
|
91
127
|
return withLock(path, () => writeMessage(path, options));
|
|
92
128
|
}
|
|
93
129
|
|
|
130
|
+
function buildMessage(seq: number, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
|
|
131
|
+
return {
|
|
132
|
+
type: "message",
|
|
133
|
+
seq,
|
|
134
|
+
from: options.from,
|
|
135
|
+
body: options.body,
|
|
136
|
+
...(options.kind ? { kind: options.kind } : {}),
|
|
137
|
+
...(options.inReplyTo !== undefined ? { in_reply_to: options.inReplyTo } : {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function validate(message: MessageEnvelope & { type: "message" }): void {
|
|
142
|
+
const parsed = messageLineSchema.safeParse(message);
|
|
143
|
+
if (!parsed.success) throw new LogWriteError(describeInvalid(parsed.error));
|
|
144
|
+
}
|
|
145
|
+
|
|
94
146
|
function writeMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
|
|
95
147
|
const message: MessageEnvelope & { type: "message" } = {
|
|
96
148
|
type: "message",
|
|
@@ -106,11 +158,7 @@ function writeMessage(path: string, options: AppendMessageOptions): MessageEnvel
|
|
|
106
158
|
// line the reader refuses is not a failed write — it is a room nobody can
|
|
107
159
|
// open again. Types alone did not hold this: they are erased at the CLI
|
|
108
160
|
// boundary, where `--kind` arrived as an unchecked string.
|
|
109
|
-
|
|
110
|
-
if (!parsed.success) {
|
|
111
|
-
throw new LogWriteError(describeInvalid(parsed.error));
|
|
112
|
-
}
|
|
113
|
-
|
|
161
|
+
validate(message);
|
|
114
162
|
appendFileSync(path, JSON.stringify(message) + "\n");
|
|
115
163
|
return message;
|
|
116
164
|
}
|
package/src/server/index.ts
CHANGED
|
@@ -49,7 +49,17 @@ export function createRoomMcpServer(logPath: string, options: RoomMcpServerOptio
|
|
|
49
49
|
description: "Roster and current goal contract for this room.",
|
|
50
50
|
},
|
|
51
51
|
async () => ({
|
|
52
|
-
content: [
|
|
52
|
+
content: [
|
|
53
|
+
{
|
|
54
|
+
type: "text",
|
|
55
|
+
// Always stated, even when false: this is the field `room append`
|
|
56
|
+
// needs to stop hedging its refusal, so "no dispatcher" has to be an
|
|
57
|
+
// answer rather than an absence.
|
|
58
|
+
text: JSON.stringify(
|
|
59
|
+
getStateTool(logPath, { dispatcherAttached: options.onOwnerCommand !== undefined }),
|
|
60
|
+
),
|
|
61
|
+
},
|
|
62
|
+
],
|
|
53
63
|
}),
|
|
54
64
|
);
|
|
55
65
|
|
package/src/server/serve.ts
CHANGED
|
@@ -3,12 +3,24 @@ import type { RoomMcpServerOptions } from "./index";
|
|
|
3
3
|
import { serveMcpOverHttp } from "./http-transport";
|
|
4
4
|
import type { McpHttpTransportHandle } from "./http-transport";
|
|
5
5
|
import { loadRoomLog } from "../log/store";
|
|
6
|
+
import {
|
|
7
|
+
LEASE_HEARTBEAT_MS,
|
|
8
|
+
acquireWriterLease,
|
|
9
|
+
refreshWriterLease,
|
|
10
|
+
releaseWriterLease,
|
|
11
|
+
} from "../writer-lease";
|
|
6
12
|
|
|
7
13
|
export interface ServeOptions extends RoomMcpServerOptions {
|
|
8
14
|
/** Defaults to 4319 (specification.md's default). 0 selects an ephemeral port. */
|
|
9
15
|
port?: number;
|
|
10
16
|
host?: string;
|
|
11
17
|
acknowledgeNonLoopback?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Where the writer lease lives, when this server has a dispatcher attached.
|
|
20
|
+
* Defaults to none: an embedder that does not dispatch holds nothing, and a
|
|
21
|
+
* library caller should not acquire a lease as a side effect of binding.
|
|
22
|
+
*/
|
|
23
|
+
writerLeasePath?: string;
|
|
12
24
|
}
|
|
13
25
|
|
|
14
26
|
export type ServeHandle = McpHttpTransportHandle;
|
|
@@ -33,7 +45,7 @@ export async function serve(logPath: string, options: ServeOptions): Promise<Ser
|
|
|
33
45
|
// that names the file and the line.
|
|
34
46
|
loadRoomLog(logPath);
|
|
35
47
|
|
|
36
|
-
|
|
48
|
+
const handle = await serveMcpOverHttp({
|
|
37
49
|
createMcpServer: () => createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand }),
|
|
38
50
|
commandLabel: "roomyx serve",
|
|
39
51
|
defaultPort: 4319,
|
|
@@ -41,4 +53,50 @@ export async function serve(logPath: string, options: ServeOptions): Promise<Ser
|
|
|
41
53
|
host: options.host,
|
|
42
54
|
acknowledgeNonLoopback: options.acknowledgeNonLoopback,
|
|
43
55
|
});
|
|
56
|
+
|
|
57
|
+
// The lease is held by the process that has a dispatcher, which is this one —
|
|
58
|
+
// a server with no dispatcher is an observer, and holding a lease would claim
|
|
59
|
+
// a pen it never picks up.
|
|
60
|
+
if (options.onOwnerCommand === undefined || options.writerLeasePath === undefined) return handle;
|
|
61
|
+
|
|
62
|
+
const leasePath = options.writerLeasePath;
|
|
63
|
+
let lease;
|
|
64
|
+
try {
|
|
65
|
+
lease = acquireWriterLease(leasePath, { pid: process.pid });
|
|
66
|
+
} catch (error) {
|
|
67
|
+
// The port is already bound; a lease that cannot be written must not leave a
|
|
68
|
+
// server answering with no way for its caller to close it.
|
|
69
|
+
await handle.close().catch(() => undefined);
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
const heldLease = lease;
|
|
73
|
+
// `unref()`, so an idle heartbeat cannot be the reason the process stays
|
|
74
|
+
// alive — the same rule the transport's session sweeper follows.
|
|
75
|
+
let complained = false;
|
|
76
|
+
const heartbeat = setInterval(() => {
|
|
77
|
+
// A refresh that fails means the lease is gone or is now someone else's —
|
|
78
|
+
// which is what a take-over does. Reporting it once matters, because
|
|
79
|
+
// otherwise this process keeps dispatching into a log it no longer owns and
|
|
80
|
+
// nothing anywhere says so.
|
|
81
|
+
if (!refreshWriterLease(leasePath, heldLease.token) && !complained) {
|
|
82
|
+
complained = true;
|
|
83
|
+
console.error(
|
|
84
|
+
`roomyx serve: this server no longer holds the writer lease for ${logPath}. ` +
|
|
85
|
+
`Another writer took it over; stop dispatching into this room.`,
|
|
86
|
+
);
|
|
87
|
+
clearInterval(heartbeat);
|
|
88
|
+
}
|
|
89
|
+
}, LEASE_HEARTBEAT_MS);
|
|
90
|
+
heartbeat.unref();
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
...handle,
|
|
94
|
+
close: async () => {
|
|
95
|
+
clearInterval(heartbeat);
|
|
96
|
+
// Close first, release second: releasing while the server still answers
|
|
97
|
+
// leaves a window where a live room looks like it has no writer.
|
|
98
|
+
await handle.close();
|
|
99
|
+
releaseWriterLease(leasePath, heldLease.token);
|
|
100
|
+
},
|
|
101
|
+
};
|
|
44
102
|
}
|
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
import { loadRoomLog } from "../../log/store";
|
|
2
2
|
import type { RoomState } from "../../log/types";
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* MCP tool `room.get_state`: roster, goal contract, which log this is, and
|
|
6
|
+
* whether anything is dispatching into it. Read-only.
|
|
7
|
+
*
|
|
8
|
+
* The dispatcher flag comes from the server that built this tool, not from the
|
|
9
|
+
* log — the log cannot know it, and the server has known it all along
|
|
10
|
+
* (`options.onOwnerCommand !== undefined`) without saying.
|
|
11
|
+
*/
|
|
12
|
+
export function getStateTool(logPath: string, options: { dispatcherAttached?: boolean } = {}): RoomState {
|
|
6
13
|
const { state } = loadRoomLog(logPath);
|
|
7
|
-
return state;
|
|
14
|
+
if (options.dispatcherAttached === undefined) return state;
|
|
15
|
+
return { ...state, dispatcherAttached: options.dispatcherAttached };
|
|
8
16
|
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Who is holding the pen on a room log, as a fact rather than an inference.
|
|
7
|
+
*
|
|
8
|
+
* `room append` used to infer it: if the registry showed a room answering on
|
|
9
|
+
* this path, the CLI refused and told the operator to pass `--force` if they
|
|
10
|
+
* knew better. That inference is wrong in the case that matters most — a room
|
|
11
|
+
* served by bare `roomyx serve` answers and has no dispatcher, so there is no
|
|
12
|
+
* writer to race, and the bundled skill had to instruct its primary consumer to
|
|
13
|
+
* write through the guard's own escape hatch to get any work done.
|
|
14
|
+
*
|
|
15
|
+
* A lease fixes the inference. It is held by a server that has a dispatcher
|
|
16
|
+
* attached — same process, same lifetime — and by nothing else. A one-shot
|
|
17
|
+
* `roomyx room append` never holds one: it would be expired by the time anyone
|
|
18
|
+
* could read it, which is the state a lease exists to distinguish.
|
|
19
|
+
*
|
|
20
|
+
* Two rules copied deliberately from `lockfile.ts` rather than re-derived:
|
|
21
|
+
*
|
|
22
|
+
* - **Release checks the token.** A holder that finishes late must not unlink
|
|
23
|
+
* the file its successor legitimately took.
|
|
24
|
+
* - **Staleness is a ceiling, not a guess.** A holder that dies without saying
|
|
25
|
+
* so leaves a lease that expires by itself, so recovery never requires an
|
|
26
|
+
* operator to delete a file by hand.
|
|
27
|
+
*
|
|
28
|
+
* The lease lives beside the registry, not beside the log: a room log travels
|
|
29
|
+
* with the repository, while who holds the pen is a property of this machine's
|
|
30
|
+
* running processes. It is keyed by the **log**, though — one file per room —
|
|
31
|
+
* because a project runs several rooms at once (the README's whole point in
|
|
32
|
+
* giving `serve` an ephemeral port default), and a single lease file shared by
|
|
33
|
+
* all of them meant the first room's writer refused writes to the second's log.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** How often a holder re-states that it is still there. */
|
|
37
|
+
export const LEASE_HEARTBEAT_MS = 5_000;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* How long a lease is believed without a heartbeat.
|
|
41
|
+
*
|
|
42
|
+
* Six missed heartbeats. Longer than any plausible scheduling stall, and short
|
|
43
|
+
* enough that a crashed dispatcher does not block the operator for minutes.
|
|
44
|
+
*/
|
|
45
|
+
export const LEASE_STALE_MS = 30_000;
|
|
46
|
+
|
|
47
|
+
export interface WriterLease {
|
|
48
|
+
token: string;
|
|
49
|
+
pid: number;
|
|
50
|
+
/** Epoch ms of the last heartbeat, so staleness needs no file mtime. */
|
|
51
|
+
at: number;
|
|
52
|
+
/**
|
|
53
|
+
* Set when a writer took this lease over from one that had stopped — the pid
|
|
54
|
+
* that did it, and when. It is why the token is replaced on take-over: the
|
|
55
|
+
* previous holder's heartbeat has to fail, or a writer that was merely paused
|
|
56
|
+
* revives the lease it lost and two processes write the same log.
|
|
57
|
+
*/
|
|
58
|
+
takenOverFrom?: { pid: number; at: number };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type LeaseState =
|
|
62
|
+
| { held: true; lease: WriterLease }
|
|
63
|
+
/**
|
|
64
|
+
* `stale` carries the lease it found, because "a writer stopped here, pid N,
|
|
65
|
+
* at T" is the fact a take-over needs to record — and reading the file only to
|
|
66
|
+
* discard who was in it leaves the log unable to say what it displaced.
|
|
67
|
+
*/
|
|
68
|
+
| { held: false; reason: "absent" }
|
|
69
|
+
| { held: false; reason: "stale"; last: WriterLease };
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* One lease file per room, under a directory beside the registry.
|
|
73
|
+
*
|
|
74
|
+
* The file name is a hash of the log's absolute path: the log path is what
|
|
75
|
+
* identifies the room, and a name derived from it keeps two rooms apart without
|
|
76
|
+
* putting a path (which contains separators) into a file name.
|
|
77
|
+
*/
|
|
78
|
+
export function writerLeasePathFor(registryPath: string, logPath: string): string {
|
|
79
|
+
const name = createHash("sha256").update(logPath).digest("hex").slice(0, 16);
|
|
80
|
+
return join(dirname(registryPath), "writers", `${name}.json`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function parseLease(raw: string): WriterLease | undefined {
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(raw) as Partial<WriterLease>;
|
|
86
|
+
if (typeof parsed.token !== "string" || parsed.token === "") return undefined;
|
|
87
|
+
if (typeof parsed.pid !== "number" || typeof parsed.at !== "number") return undefined;
|
|
88
|
+
return { token: parsed.token, pid: parsed.pid, at: parsed.at };
|
|
89
|
+
} catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A corrupt or half-written lease reads as **no lease**, never as a held one.
|
|
96
|
+
*
|
|
97
|
+
* Failing closed would mean a file nobody can repair refusing every write to a
|
|
98
|
+
* room forever, and the operator's only recourse would be deleting the file by
|
|
99
|
+
* hand — which is exactly the recovery path `--take-over` exists to make
|
|
100
|
+
* unnecessary. `absent` is also the truthful answer: nothing usable is held.
|
|
101
|
+
*/
|
|
102
|
+
export function readWriterLease(path: string, options: { now?: number } = {}): LeaseState {
|
|
103
|
+
if (!existsSync(path)) return { held: false, reason: "absent" };
|
|
104
|
+
let raw: string;
|
|
105
|
+
try {
|
|
106
|
+
raw = readFileSync(path, "utf8");
|
|
107
|
+
} catch {
|
|
108
|
+
return { held: false, reason: "absent" };
|
|
109
|
+
}
|
|
110
|
+
const lease = parseLease(raw);
|
|
111
|
+
if (lease === undefined) return { held: false, reason: "absent" };
|
|
112
|
+
const now = options.now ?? Date.now();
|
|
113
|
+
if (now - lease.at > LEASE_STALE_MS) return { held: false, reason: "stale", last: lease };
|
|
114
|
+
return { held: true, lease };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Takes the lease unconditionally, replacing whatever was there. */
|
|
118
|
+
export function acquireWriterLease(
|
|
119
|
+
path: string,
|
|
120
|
+
options: { pid: number; now?: number; takeOverFrom?: { pid: number; at: number } },
|
|
121
|
+
): WriterLease {
|
|
122
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
123
|
+
const lease: WriterLease = {
|
|
124
|
+
token: randomUUID(),
|
|
125
|
+
pid: options.pid,
|
|
126
|
+
at: options.now ?? Date.now(),
|
|
127
|
+
};
|
|
128
|
+
if (options.takeOverFrom !== undefined) lease.takenOverFrom = options.takeOverFrom;
|
|
129
|
+
writeFileSync(path, JSON.stringify(lease));
|
|
130
|
+
return lease;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Returns false when the lease is gone, expired, or now someone else's. */
|
|
134
|
+
export function refreshWriterLease(path: string, token: string, options: { now?: number } = {}): boolean {
|
|
135
|
+
const state = readWriterLease(path, options);
|
|
136
|
+
if (!state.held || state.lease.token !== token) return false;
|
|
137
|
+
writeFileSync(path, JSON.stringify({ ...state.lease, at: options.now ?? Date.now() }));
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Unlinks only the lease this token wrote — see the note above. */
|
|
142
|
+
export function releaseWriterLease(path: string, token: string): void {
|
|
143
|
+
try {
|
|
144
|
+
const lease = parseLease(readFileSync(path, "utf8"));
|
|
145
|
+
if (lease?.token === token) unlinkSync(path);
|
|
146
|
+
} catch {
|
|
147
|
+
// Already gone, or unreadable: nothing more to do.
|
|
148
|
+
}
|
|
149
|
+
}
|