@mrciphersmith/roomyx 0.12.1 → 0.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +129 -0
- package/README.md +140 -12
- 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
package/src/cli/init.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { init } from "../installer/init";
|
|
5
|
+
import { personaCount } from "../installer/personas";
|
|
6
|
+
import { bundledPersonasPath, bundledSkillPath } from "./shared";
|
|
7
|
+
import type { Command } from "./shared";
|
|
8
|
+
|
|
9
|
+
export const initCommand: Command = {
|
|
10
|
+
usage: "roomyx init [flags]",
|
|
11
|
+
summary: "scaffold .roomyx/, then set up skills, MCP and git for this project",
|
|
12
|
+
notes:
|
|
13
|
+
"Interactive when the terminal allows it: tick what you want, see every\n path before agreeing to it, and nothing is written until you submit.\n Through a pipe or in CI it scaffolds .roomyx/ and asks nothing, so it can\n never hang waiting for a keypress nobody is there to make.",
|
|
14
|
+
flags: {
|
|
15
|
+
yes: { type: "boolean", describe: "Apply the default selection without asking" },
|
|
16
|
+
"no-interactive": { type: "boolean", describe: "Scaffold .roomyx/ only" },
|
|
17
|
+
},
|
|
18
|
+
run: async ({ flags }) => {
|
|
19
|
+
const cwd = process.cwd();
|
|
20
|
+
const result = init({ cwd, bundledSkillPath: bundledSkillPath() });
|
|
21
|
+
console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
|
|
22
|
+
for (const warning of result.skillWarnings ?? []) {
|
|
23
|
+
// Said out loud rather than swallowed: the staged copy is now known to
|
|
24
|
+
// differ from the bundled skill, and whoever sees this decides what to
|
|
25
|
+
// do about it.
|
|
26
|
+
console.log(` ! ${warning}`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const { buildPlan, selectedItems } = await import("../installer/init-plan");
|
|
30
|
+
const { applyPlan } = await import("../installer/init-apply");
|
|
31
|
+
|
|
32
|
+
const plan = buildPlan({ cwd, personaFiles: personaCount(bundledPersonasPath()) });
|
|
33
|
+
// A terminal on both ends or nothing to ask. `--yes` overrides, because
|
|
34
|
+
// a script that has decided already should not be refused for lacking a
|
|
35
|
+
// tty — but the default must never block a pipeline on a prompt.
|
|
36
|
+
const interactive = process.stdout.isTTY === true && process.stdin.isTTY === true;
|
|
37
|
+
if (flags["no-interactive"] === true || (!interactive && flags.yes !== true)) {
|
|
38
|
+
console.log("");
|
|
39
|
+
console.log("Nothing else was written. To install the skill and register the MCP server:");
|
|
40
|
+
console.log(" roomyx init --yes # the default selection, no prompt");
|
|
41
|
+
console.log(" roomyx init # pick, in a terminal");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let chosen = plan;
|
|
46
|
+
if (flags.yes !== true) {
|
|
47
|
+
const { runInitPicker } = await import("../client/init-screen");
|
|
48
|
+
const picked = await runInitPicker(plan);
|
|
49
|
+
if (picked === null) {
|
|
50
|
+
console.log("Cancelled — nothing else was written.");
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
chosen = picked;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const results = applyPlan(selectedItems(chosen), {
|
|
57
|
+
cwd,
|
|
58
|
+
bundledSkillPath: bundledSkillPath(),
|
|
59
|
+
bundledPersonasPath: bundledPersonasPath(),
|
|
60
|
+
configPath: join(cwd, ".roomyx", "config.json"),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
console.log("");
|
|
64
|
+
for (const line of results) {
|
|
65
|
+
console.log(`${line.ok ? " ok " : " !! "} ${line.label}`);
|
|
66
|
+
console.log(` ${line.path} — ${line.message}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const failed = results.filter((line) => !line.ok).length;
|
|
70
|
+
if (failed > 0) console.log(`\n${failed} item(s) failed. Everything else was applied.`);
|
|
71
|
+
if (results.some((line) => line.ok && line.id.startsWith("skill:"))) {
|
|
72
|
+
// The one thing an operator reliably forgets, and the symptom is
|
|
73
|
+
// "roomyx installed the skill and my agent still cannot see it".
|
|
74
|
+
console.log("\nRestart your agent — skills are discovered at startup.");
|
|
75
|
+
}
|
|
76
|
+
console.log("\nNext: roomyx room new .roomyx/rooms/logs/<name>.jsonl --goal \"<what the room is for>\"");
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export const setupCommand: Command = {
|
|
81
|
+
usage: "roomyx setup [flags]",
|
|
82
|
+
summary: "set this machine up, without touching the current project",
|
|
83
|
+
notes:
|
|
84
|
+
"The same picker `roomyx init` shows, narrowed to the rows that land on\n the machine: the skill for each agent runtime you use, and the persona\n library under ~/.roomyx. Nothing is created in the current directory, so\n this is what to run right after installing from npm — an npm lifecycle\n script cannot ask, because npm runs one with no terminal (CI, `npm ci`,\n Docker) and skips it entirely under --ignore-scripts.",
|
|
85
|
+
flags: {
|
|
86
|
+
yes: { type: "boolean", describe: "Apply the default selection without asking" },
|
|
87
|
+
},
|
|
88
|
+
run: async ({ flags }) => {
|
|
89
|
+
const home = homedir();
|
|
90
|
+
const cwd = process.cwd();
|
|
91
|
+
// Its own config, under the home directory: `syncSkill` records the hash
|
|
92
|
+
// of what it wrote so a later sync can tell "unchanged since we wrote it"
|
|
93
|
+
// from "edited by someone", and a machine-wide install has no project
|
|
94
|
+
// config to record into. Created here rather than demanded, because the
|
|
95
|
+
// whole point of this command is that there is no project yet.
|
|
96
|
+
const configPath = join(home, ".roomyx", "config.json");
|
|
97
|
+
if (!existsSync(configPath)) {
|
|
98
|
+
mkdirSync(join(home, ".roomyx"), { recursive: true });
|
|
99
|
+
writeFileSync(configPath, JSON.stringify({ schemaVersion: 1 }, null, 2));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const { buildPlan, machineItems, selectedItems } = await import("../installer/init-plan");
|
|
103
|
+
const { applyPlan } = await import("../installer/init-apply");
|
|
104
|
+
const plan = machineItems(buildPlan({ cwd, personaFiles: personaCount(bundledPersonasPath()) }));
|
|
105
|
+
// Ticked here, unticked in `init`, and the difference is the point. In a
|
|
106
|
+
// project the machine-wide library is a second copy of one the project
|
|
107
|
+
// already gets and the skill prefers. Here there is no project copy — so
|
|
108
|
+
// leaving it off would set a machine up with a skill that casts its room
|
|
109
|
+
// from personas that are nowhere on disk, which is the unfinished
|
|
110
|
+
// installer this whole command exists to avoid.
|
|
111
|
+
for (const item of plan) {
|
|
112
|
+
if (item.id === "personas:user" && item.done === undefined) item.selected = true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const interactive = process.stdout.isTTY === true && process.stdin.isTTY === true;
|
|
116
|
+
if (!interactive && flags.yes !== true) {
|
|
117
|
+
console.log("Not a terminal, so nothing was asked and nothing was written.");
|
|
118
|
+
console.log(" roomyx setup --yes # the default selection, no prompt");
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let chosen = plan;
|
|
123
|
+
if (flags.yes !== true) {
|
|
124
|
+
const { runInitPicker } = await import("../client/init-screen");
|
|
125
|
+
const picked = await runInitPicker(plan);
|
|
126
|
+
if (picked === null) {
|
|
127
|
+
console.log("Cancelled — nothing was written.");
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
chosen = picked;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const results = applyPlan(selectedItems(chosen), {
|
|
134
|
+
cwd,
|
|
135
|
+
bundledSkillPath: bundledSkillPath(),
|
|
136
|
+
bundledPersonasPath: bundledPersonasPath(),
|
|
137
|
+
configPath,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
for (const line of results) {
|
|
141
|
+
console.log(`${line.ok ? " ok " : " !! "} ${line.label}`);
|
|
142
|
+
console.log(` ${line.path} — ${line.message}`);
|
|
143
|
+
}
|
|
144
|
+
if (results.some((line) => line.ok)) {
|
|
145
|
+
console.log("\nRestart your agent — skills are discovered at startup.");
|
|
146
|
+
}
|
|
147
|
+
console.log("\nNext, in a project: roomyx init");
|
|
148
|
+
},
|
|
149
|
+
};
|
package/src/cli/mcp.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { serveManagement } from "../mcp-management/server";
|
|
2
|
+
import { REGISTRY_FLAG, bundledSkillPath, defaultConfigPath, defaultRegistryPath, runUntilSignal } from "./shared";
|
|
3
|
+
import type { Command } from "./shared";
|
|
4
|
+
|
|
5
|
+
export const mcpCommand: Command = {
|
|
6
|
+
usage: "roomyx mcp [flags]",
|
|
7
|
+
summary: "start the management MCP server",
|
|
8
|
+
notes: "Default port 4320, so it does not collide with `roomyx serve`.",
|
|
9
|
+
flags: {
|
|
10
|
+
stdio: { type: "boolean", describe: "Speak MCP over stdin/stdout instead of HTTP (what an MCP client spawns)" },
|
|
11
|
+
port: { type: "number", describe: "Listen port (default 4320; 0 picks an ephemeral one)" },
|
|
12
|
+
host: { type: "string", describe: "Bind address (default 127.0.0.1)" },
|
|
13
|
+
"acknowledge-non-loopback": { type: "boolean", describe: "Required to bind a non-loopback host" },
|
|
14
|
+
registry: REGISTRY_FLAG,
|
|
15
|
+
config: { type: "string", describe: "Config file (default .roomyx/config.json)" },
|
|
16
|
+
},
|
|
17
|
+
run: async ({ flags }) => {
|
|
18
|
+
const managementOptions = {
|
|
19
|
+
registryPath: typeof flags.registry === "string" ? flags.registry : defaultRegistryPath(),
|
|
20
|
+
bundledSkillPath: bundledSkillPath(),
|
|
21
|
+
configPath: typeof flags.config === "string" ? flags.config : defaultConfigPath(),
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
if (flags.stdio === true) {
|
|
25
|
+
// The transport an MCP client actually wants: it spawns the process and
|
|
26
|
+
// owns its lifetime, so there is no port to pick, nothing to leave
|
|
27
|
+
// running, and no registration that points at something not started
|
|
28
|
+
// yet. This is what `roomyx init` writes into `.mcp.json`.
|
|
29
|
+
//
|
|
30
|
+
// **Nothing may be printed to stdout here** — stdout is the protocol
|
|
31
|
+
// channel, and one stray line of greeting is a parse error at the far
|
|
32
|
+
// end. The HTTP branch below prints because it has a stdout to itself.
|
|
33
|
+
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
|
34
|
+
const { createManagementMcpServer } = await import("../mcp-management/server");
|
|
35
|
+
const server = createManagementMcpServer(managementOptions);
|
|
36
|
+
await server.connect(new StdioServerTransport());
|
|
37
|
+
// The client closes the pipe when it is done; there is no port to
|
|
38
|
+
// release, so the signal handlers the HTTP branch installs would have
|
|
39
|
+
// nothing to do.
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const handle = await serveManagement(managementOptions, {
|
|
44
|
+
port: typeof flags.port === "number" ? flags.port : undefined,
|
|
45
|
+
host: typeof flags.host === "string" ? flags.host : undefined,
|
|
46
|
+
acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
console.log(`roomyx mcp listening at ${handle.url}`);
|
|
50
|
+
console.log("tools: roomyx.rooms.list, roomyx.skills.sync");
|
|
51
|
+
|
|
52
|
+
runUntilSignal(() => handle.close());
|
|
53
|
+
},
|
|
54
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { installPersonas } from "../installer/personas";
|
|
4
|
+
import { ArgError } from "./args";
|
|
5
|
+
import { bundledPersonasPath } from "./shared";
|
|
6
|
+
import type { Command } from "./shared";
|
|
7
|
+
|
|
8
|
+
function defaultPersonasPath(cwd: string = process.cwd()): string {
|
|
9
|
+
return join(cwd, ".roomyx", "personas");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const personasCommand: Command = {
|
|
13
|
+
usage: "roomyx personas [flags]",
|
|
14
|
+
summary: "install the bundled persona library into this project",
|
|
15
|
+
notes:
|
|
16
|
+
"Fifty interview personas, plus founder, technical and panel roles, plus\n a fifty-question interview questionnaire. A room is built out of these.\n\n The skill looks in .roomyx/personas first and falls back to\n ~/.roomyx/personas, so a project copy overrides the machine-wide one.\n\n Files that already exist are skipped, never overwritten: a persona is a\n file you are meant to edit.",
|
|
17
|
+
flags: {
|
|
18
|
+
target: { type: "string", describe: "Directory (default .roomyx/personas)" },
|
|
19
|
+
global: { type: "boolean", describe: "Install for every project, into ~/.roomyx/personas" },
|
|
20
|
+
force: { type: "boolean", describe: "Replace the library, moving the existing directory aside first" },
|
|
21
|
+
},
|
|
22
|
+
run: async ({ flags }) => {
|
|
23
|
+
if (typeof flags.target === "string" && flags.global === true) {
|
|
24
|
+
throw new ArgError("Pass either --target or --global, not both — they name different directories.");
|
|
25
|
+
}
|
|
26
|
+
const target =
|
|
27
|
+
typeof flags.target === "string"
|
|
28
|
+
? resolve(flags.target)
|
|
29
|
+
: flags.global === true
|
|
30
|
+
? join(homedir(), ".roomyx", "personas")
|
|
31
|
+
: defaultPersonasPath();
|
|
32
|
+
const result = installPersonas(bundledPersonasPath(), target, { force: flags.force === true });
|
|
33
|
+
|
|
34
|
+
if (result.movedAside) console.log(`Moved the previous library to ${result.movedAside}`);
|
|
35
|
+
console.log(`${result.written} file(s) written to ${result.targetDir}`);
|
|
36
|
+
if (result.skipped > 0) {
|
|
37
|
+
console.log(`${result.skipped} left as they were (already present — pass --force to replace the library)`);
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
};
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { findRoomServing, probeRoomState, listRoomsWithLiveness } from "../installer/registry";
|
|
4
|
+
import { appendMessages, LEGAL_KINDS } from "../log/write";
|
|
5
|
+
import type { AppendMessageOptions } from "../log/write";
|
|
6
|
+
import { isLeaseHolderAlive, readWriterLease, tombstoneWriterLease, writerLeasePathFor } from "../writer-lease";
|
|
7
|
+
import { MESSAGE_KINDS } from "../log/schema";
|
|
8
|
+
import { LogWriteError } from "../log/write";
|
|
9
|
+
import type { MessageEnvelope } from "../log/types";
|
|
10
|
+
import { ArgError } from "./args";
|
|
11
|
+
import type { FlagValues } from "./args";
|
|
12
|
+
import { REGISTRY_FLAG, defaultRegistryPath } from "./shared";
|
|
13
|
+
import type { Command } from "./shared";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Turns the flags into the messages to write, or refuses.
|
|
17
|
+
*
|
|
18
|
+
* Four ways in, and they do not compose: an envelope says everything, so a
|
|
19
|
+
* `--from` beside it is an ambiguity rather than an override — and guessing
|
|
20
|
+
* which one the caller meant is how a body goes into the wrong speaker's mouth.
|
|
21
|
+
*/
|
|
22
|
+
function pendingAppends(flags: FlagValues): AppendMessageOptions[] {
|
|
23
|
+
// Two different things are being chosen here, and conflating them was wrong:
|
|
24
|
+
// `--json` and `--many` carry a whole envelope (speaker included), while
|
|
25
|
+
// `--body` and `--body-file` carry only the body and still need `--from`.
|
|
26
|
+
// Refusing `--body-file --from b` refused a combination that has no ambiguity
|
|
27
|
+
// in it at all.
|
|
28
|
+
const envelopeSources = [flags.json !== undefined, flags.many === true].filter(Boolean).length;
|
|
29
|
+
if (envelopeSources > 1) throw new ArgError("Use one of --json or --many, not both.");
|
|
30
|
+
const bodySources = [flags.body !== undefined, flags["body-file"] !== undefined].filter(Boolean).length;
|
|
31
|
+
if (bodySources > 1) throw new ArgError("Use one of --body or --body-file, not both.");
|
|
32
|
+
|
|
33
|
+
if (envelopeSources === 1) {
|
|
34
|
+
const conflicting = ["from", "body", "body-file", "kind", "in-reply-to", "read-through"].filter((f) => flags[f] !== undefined);
|
|
35
|
+
if (conflicting.length > 0) {
|
|
36
|
+
// An envelope says everything. Silently preferring one source is how a
|
|
37
|
+
// body ends up in the log under a speaker nobody chose.
|
|
38
|
+
throw new ArgError(
|
|
39
|
+
`--json/--many carry the whole envelope, so --${conflicting.join(", --")} cannot be combined with them.`,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
return flags.many === true ? parseBatch(readStdin()) : [envelopeFrom(flags.json as string)];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const from = flags.from;
|
|
46
|
+
if (typeof from !== "string" || from === "") {
|
|
47
|
+
throw new ArgError("Both --from and --body are required (or pass --json, --body-file or --many).");
|
|
48
|
+
}
|
|
49
|
+
const body = typeof flags["body-file"] === "string" ? bodyFromFile(flags["body-file"]) : flags.body;
|
|
50
|
+
if (typeof body !== "string") throw new ArgError("Both --from and --body are required.");
|
|
51
|
+
|
|
52
|
+
const kind = typeof flags.kind === "string" ? flags.kind : undefined;
|
|
53
|
+
if (kind !== undefined && !(MESSAGE_KINDS as readonly string[]).includes(kind)) {
|
|
54
|
+
throw new ArgError(`Unknown --kind "${kind}". Known kinds: ${LEGAL_KINDS}.`);
|
|
55
|
+
}
|
|
56
|
+
const inReplyTo = typeof flags["in-reply-to"] === "number" ? flags["in-reply-to"] : undefined;
|
|
57
|
+
if (inReplyTo !== undefined && (!Number.isInteger(inReplyTo) || inReplyTo < 1)) {
|
|
58
|
+
throw new ArgError(`--in-reply-to must be a whole number of at least 1, not ${inReplyTo}.`);
|
|
59
|
+
}
|
|
60
|
+
const readThrough = typeof flags["read-through"] === "number" ? flags["read-through"] : undefined;
|
|
61
|
+
if (readThrough !== undefined && (!Number.isInteger(readThrough) || readThrough < 0)) {
|
|
62
|
+
throw new ArgError(`--read-through must be a whole number of at least 0, not ${readThrough}.`);
|
|
63
|
+
}
|
|
64
|
+
return [{ from, body, kind: kind as MessageEnvelope["kind"], inReplyTo, readThrough }];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function readStdin(): string {
|
|
68
|
+
if (process.stdin.isTTY === true) {
|
|
69
|
+
// Reading fd 0 from a terminal blocks until Ctrl-D, which reads as a hang.
|
|
70
|
+
throw new ArgError("This flag reads the message from stdin, and stdin is a terminal. Pipe the text in, or use --body.");
|
|
71
|
+
}
|
|
72
|
+
return readFileSync(0, "utf8");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function bodyFromFile(file: string): string {
|
|
76
|
+
// A trailing newline is what every editor and every `echo` adds; it is not
|
|
77
|
+
// part of what the speaker said, and it would land inside the quoted body.
|
|
78
|
+
const raw = file === "-" ? readStdin() : readFileSync(resolve(file), "utf8");
|
|
79
|
+
return raw.replace(/\r?\n$/, "");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const ENVELOPE_KEYS = ["from", "body", "kind", "in_reply_to", "change", "read_through"] as const;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Parses one envelope, refusing keys that would silently vanish.
|
|
86
|
+
*
|
|
87
|
+
* An unknown key is a refusal rather than something ignored: `seq` and `type`
|
|
88
|
+
* are assigned by the writer, and a caller who passes one believes they chose
|
|
89
|
+
* it — so accepting the envelope while dropping their value is the one answer
|
|
90
|
+
* that cannot be discovered from the log.
|
|
91
|
+
*/
|
|
92
|
+
function envelopeFrom(text: string): AppendMessageOptions {
|
|
93
|
+
let parsed: unknown;
|
|
94
|
+
try {
|
|
95
|
+
parsed = JSON.parse(text) as unknown;
|
|
96
|
+
} catch (error) {
|
|
97
|
+
throw new ArgError(`--json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
98
|
+
}
|
|
99
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
100
|
+
throw new ArgError("--json must be a JSON object.");
|
|
101
|
+
}
|
|
102
|
+
const envelope = parsed as Record<string, unknown>;
|
|
103
|
+
for (const key of Object.keys(envelope)) {
|
|
104
|
+
if (!(ENVELOPE_KEYS as readonly string[]).includes(key)) {
|
|
105
|
+
throw new ArgError(`--json has an unknown key "${key}". Allowed: ${ENVELOPE_KEYS.join(", ")}.`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const { from, body, kind, in_reply_to: inReplyTo, change, read_through: readThrough } = envelope;
|
|
109
|
+
if (typeof from !== "string" || from === "") throw new ArgError('--json needs a non-empty "from".');
|
|
110
|
+
if (typeof body !== "string") throw new ArgError('--json needs a string "body".');
|
|
111
|
+
if (kind !== undefined && (typeof kind !== "string" || !(MESSAGE_KINDS as readonly string[]).includes(kind))) {
|
|
112
|
+
throw new ArgError(`--json "kind" must be one of: ${LEGAL_KINDS}.`);
|
|
113
|
+
}
|
|
114
|
+
if (inReplyTo !== undefined && (typeof inReplyTo !== "number" || !Number.isInteger(inReplyTo) || inReplyTo < 1)) {
|
|
115
|
+
throw new ArgError('--json "in_reply_to" must be a whole number of at least 1.');
|
|
116
|
+
}
|
|
117
|
+
if (readThrough !== undefined && (typeof readThrough !== "number" || !Number.isInteger(readThrough) || readThrough < 0)) {
|
|
118
|
+
throw new ArgError('--json "read_through" must be a whole number of at least 0.');
|
|
119
|
+
}
|
|
120
|
+
// The change is passed through unexamined here and validated where the rule
|
|
121
|
+
// lives (the log's own schema, imported by the writer). Re-checking its shape
|
|
122
|
+
// in the CLI would be a second copy of a rule the log already owns — and the
|
|
123
|
+
// two copies would drift, which is the failure `src/log/schema.ts` exists to
|
|
124
|
+
// make impossible.
|
|
125
|
+
if (change !== undefined && (typeof change !== "object" || change === null)) {
|
|
126
|
+
throw new ArgError('--json "change" must be an object.');
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
from,
|
|
130
|
+
body,
|
|
131
|
+
kind: kind as MessageEnvelope["kind"],
|
|
132
|
+
inReplyTo: inReplyTo as number | undefined,
|
|
133
|
+
change: change as MessageEnvelope["change"],
|
|
134
|
+
readThrough: readThrough as number | undefined,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function parseBatch(text: string): AppendMessageOptions[] {
|
|
139
|
+
const lines = text.split("\n").filter((line) => line.trim().length > 0);
|
|
140
|
+
if (lines.length === 0) throw new ArgError("--many read no envelopes from stdin.");
|
|
141
|
+
return lines.map((line, index) => {
|
|
142
|
+
try {
|
|
143
|
+
return envelopeFrom(line);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
throw new ArgError(`--many line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Writes the batch, or none of it. `appendMessages` allocates consecutive `seq`
|
|
152
|
+
* and validates every envelope before the first byte, so a refused batch leaves
|
|
153
|
+
* the log exactly as it was.
|
|
154
|
+
*/
|
|
155
|
+
function writeAll(path: string, pending: AppendMessageOptions[]) {
|
|
156
|
+
try {
|
|
157
|
+
return appendMessages(path, pending);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if (error instanceof LogWriteError) throw new ArgError(error.message);
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The holder a take-over displaced, when there was one. */
|
|
165
|
+
function stateBefore(lease: import("../writer-lease").LeaseState): { pid: number; at: number } | undefined {
|
|
166
|
+
if (lease.held) return { pid: lease.lease.pid, at: lease.lease.at };
|
|
167
|
+
// A stale lease still identifies the writer that stopped: recording it is the
|
|
168
|
+
// difference between a log that says "someone took this over" and one that
|
|
169
|
+
// says who from.
|
|
170
|
+
//
|
|
171
|
+
// `released` deliberately displaces nobody. The tombstone already records who
|
|
172
|
+
// was taken over, and naming that pid again in a second take-over's trace
|
|
173
|
+
// would report a writer being displaced twice.
|
|
174
|
+
return lease.reason === "stale" ? { pid: lease.last.pid, at: lease.last.at } : undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export const roomAppend: Command = {
|
|
178
|
+
usage: "roomyx room append <path> (--from <id> --body <text> | --json <envelope> | --body-file <file> | --many) [flags]",
|
|
179
|
+
summary: "append a message to a room log",
|
|
180
|
+
notes:
|
|
181
|
+
"Refuses only when the room is live AND something is writing into it: a\n live room with no dispatcher has no writer to race, so appending to it\n needs no flag at all (D-01a, D-18). A lease that has expired means the\n writer stopped without saying so — taking over then is a deliberate act,\n --take-over, and it is recorded in the log.",
|
|
182
|
+
flags: {
|
|
183
|
+
from: { type: "string", describe: "Participant id" },
|
|
184
|
+
body: { type: "string", describe: "The message" },
|
|
185
|
+
json: { type: "string", describe: "A whole envelope: {from, body, kind?, in_reply_to?}" },
|
|
186
|
+
"body-file": { type: "string", describe: "Read the body from a file, or - for stdin" },
|
|
187
|
+
many: { type: "boolean", describe: "Read a JSONL batch of envelopes from stdin; all of them or none" },
|
|
188
|
+
kind: { type: "string", describe: "Message kind, e.g. challenge" },
|
|
189
|
+
"in-reply-to": { type: "number", describe: "seq of the message replied to" },
|
|
190
|
+
"read-through": { type: "number", describe: "Highest seq the author had seen; refuses if others wrote past it (D-21)" },
|
|
191
|
+
"allow-unread": { type: "boolean", describe: "With --read-through: write even though the author missed messages" },
|
|
192
|
+
"take-over": { type: "boolean", describe: "Write when the room is live but its writer is gone" },
|
|
193
|
+
registry: REGISTRY_FLAG,
|
|
194
|
+
},
|
|
195
|
+
run: async ({ positionals, flags }) => {
|
|
196
|
+
const path = positionals[0];
|
|
197
|
+
if (!path) throw new ArgError("Missing <path>.");
|
|
198
|
+
const absolute = resolve(path);
|
|
199
|
+
|
|
200
|
+
const takeOver = flags["take-over"] === true;
|
|
201
|
+
|
|
202
|
+
// Absolute, because the lease lives beside the registry and this process's
|
|
203
|
+
// cwd is not the next process's: a relative `--registry` made the lease
|
|
204
|
+
// land in a different directory depending on where the command was run.
|
|
205
|
+
const absoluteRegistry = resolve(typeof flags.registry === "string" ? flags.registry : defaultRegistryPath());
|
|
206
|
+
const leasePath = writerLeasePathFor(absoluteRegistry, absolute);
|
|
207
|
+
|
|
208
|
+
// Across BOTH lists: an entry whose first probe timed out is `unconfirmed`,
|
|
209
|
+
// and it may still have a dispatcher attached — which is the evidence this
|
|
210
|
+
// guard needs. Searching only the confirmed list is how "the machine was
|
|
211
|
+
// busy" turns into "nothing is writing into this log".
|
|
212
|
+
const serving = findRoomServing(absolute, await listRoomsWithLiveness(absoluteRegistry));
|
|
213
|
+
|
|
214
|
+
// Read the lease BEFORE the probe, and independently of its outcome. A
|
|
215
|
+
// liveness probe that times out says "could not reach it", which is not
|
|
216
|
+
// "nothing is writing into it" — and reading the lease only once the probe
|
|
217
|
+
// succeeded meant a busy machine wrote into a room whose dispatcher was
|
|
218
|
+
// perfectly alive.
|
|
219
|
+
const lease = readWriterLease(leasePath);
|
|
220
|
+
const dispatched = serving !== undefined ? ((await probeRoomState(serving))?.dispatcherAttached ?? undefined) : undefined;
|
|
221
|
+
|
|
222
|
+
// Two independent pieces of evidence that someone else is writing: a live
|
|
223
|
+
// dispatcher, and a lease somebody is refreshing. The second exists because
|
|
224
|
+
// the first only holds for a server that was started with a lease path.
|
|
225
|
+
//
|
|
226
|
+
// A held lease is only evidence while the process that wrote it exists. It
|
|
227
|
+
// is a claim made by a pid, and checking that pid costs one signal — while
|
|
228
|
+
// not checking it meant a lease left behind by a process that had already
|
|
229
|
+
// gone refused every write for the whole stale window, naming a pid the
|
|
230
|
+
// operator could look up and not find. Nothing that is not running can be
|
|
231
|
+
// writing into this log, so this narrows what counts as a live writer
|
|
232
|
+
// without widening what may write beside one.
|
|
233
|
+
const liveHolder = lease.held && isLeaseHolderAlive(lease.lease.pid) ? lease.lease : undefined;
|
|
234
|
+
const writerPresent = liveHolder !== undefined || dispatched === true;
|
|
235
|
+
// A fresh lease whose holder is gone is NOT the "a writer stopped here"
|
|
236
|
+
// case: that one is `stale`, and it still requires --take-over below. This
|
|
237
|
+
// one is provably nobody, so it is allowed — said out loud on stderr
|
|
238
|
+
// because a recorded lease that the CLI decides to disregard is exactly the
|
|
239
|
+
// kind of thing that should not happen quietly.
|
|
240
|
+
const abandonedHold = lease.held && liveHolder === undefined ? lease.lease : undefined;
|
|
241
|
+
const writerWasThere = !writerPresent && !lease.held && lease.reason === "stale";
|
|
242
|
+
|
|
243
|
+
if (writerPresent) {
|
|
244
|
+
// Two different reasons to refuse, and they need different advice: a
|
|
245
|
+
// lease that is merely stale will expire by itself, while a room that
|
|
246
|
+
// reports a dispatcher will keep reporting one until the server is
|
|
247
|
+
// stopped — waiting would be advice that never comes true.
|
|
248
|
+
const advice =
|
|
249
|
+
dispatched === true
|
|
250
|
+
? `Stop the server that is running the room; once it is gone, --take-over will let you write to this log.`
|
|
251
|
+
: `Wait for that lease to expire (a writer that is running refreshes it), or stop the process holding it.`;
|
|
252
|
+
throw new ArgError(
|
|
253
|
+
`A writer is live in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`}` +
|
|
254
|
+
// `liveHolder`, not `lease.held`: naming a pid is only useful if the
|
|
255
|
+
// pid is findable, and an unfindable one is what made this message
|
|
256
|
+
// untrustworthy.
|
|
257
|
+
`${liveHolder === undefined ? " — the room reports a dispatcher attached" : ` — pid ${liveHolder.pid}`}. ` +
|
|
258
|
+
`Two writers into one append-only log is the race D-01 exists to prevent, and nothing overrides a writer ` +
|
|
259
|
+
`that is still there. ${advice}`,
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
if (writerWasThere && !takeOver) {
|
|
263
|
+
throw new ArgError(
|
|
264
|
+
`A writer was in ${absolute}${serving === undefined ? "" : ` (room ${serving.id})`} and is gone — ` +
|
|
265
|
+
`nothing holds the lease now. Writing means taking ownership from a room that looks supervised. ` +
|
|
266
|
+
`Pass --take-over to do that deliberately; the log will record it.`,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// A live room, and no evidence of a writer — say so rather than drop it.
|
|
271
|
+
//
|
|
272
|
+
// `serving` was already computed for the refusal above and, when nothing
|
|
273
|
+
// holds a lease, was silently discarded. That silence is wrong in exactly
|
|
274
|
+
// the case that matters: an agent dispatcher runs `roomyx serve` and
|
|
275
|
+
// writes with `roomyx room append`, a fresh process each time, so it
|
|
276
|
+
// never holds a lease and the room never reports a dispatcher. Every
|
|
277
|
+
// append into a room an agent is running therefore looks, from here, like
|
|
278
|
+
// an append into an unattended log.
|
|
279
|
+
//
|
|
280
|
+
// A note, not a refusal: there is nothing here that can tell a dispatcher
|
|
281
|
+
// from a stranger, so refusing would block the legitimate writer — which
|
|
282
|
+
// was tried and reverted. The log itself is safe either way; `seq`
|
|
283
|
+
// allocation is under a lock and that is tested. What is at risk is the
|
|
284
|
+
// conversation reading as one when it was two, and a line on stderr is
|
|
285
|
+
// what lets a second writer notice before adding to it.
|
|
286
|
+
//
|
|
287
|
+
// stderr, because stdout carries `Appended seq N from X` and is parsed.
|
|
288
|
+
if (serving !== undefined && !writerPresent && !writerWasThere) {
|
|
289
|
+
console.error(
|
|
290
|
+
`Note: room ${serving.id} is serving ${absolute}. Nothing holds the writer lease, so this append is ` +
|
|
291
|
+
`allowed — but roomyx cannot see whether an agent is dispatching that room. If one is, you are writing ` +
|
|
292
|
+
`into a conversation it is also writing into.`,
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// A lease that is still inside its window but whose holder has exited. Not
|
|
297
|
+
// a refusal — a dead process is not writing anything — but not silence
|
|
298
|
+
// either: this is a writer that stopped without releasing, and the operator
|
|
299
|
+
// should hear which pid it was.
|
|
300
|
+
if (abandonedHold !== undefined) {
|
|
301
|
+
console.error(
|
|
302
|
+
`Note: the writer lease on ${absolute} names pid ${abandonedHold.pid}, which is no longer running. ` +
|
|
303
|
+
`Nothing is writing into this log, so this append is allowed.`,
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Parsed only after the refusal: an operator whose command is going to be
|
|
308
|
+
// rejected should not be made to pipe a batch in first, and a reader that
|
|
309
|
+
// blocks on stdin while holding a decision helps nobody.
|
|
310
|
+
const allowUnread = flags["allow-unread"] === true;
|
|
311
|
+
if (allowUnread && flags["read-through"] === undefined && !flags.json && flags.many !== true) {
|
|
312
|
+
throw new ArgError("--allow-unread only qualifies --read-through; there is nothing to allow without it.");
|
|
313
|
+
}
|
|
314
|
+
const pending = pendingAppends(flags).map((options) => (allowUnread ? { ...options, allowUnread } : options));
|
|
315
|
+
|
|
316
|
+
const displaced = takeOver || writerWasThere ? stateBefore(lease) : undefined;
|
|
317
|
+
const takingOver = takeOver || writerWasThere;
|
|
318
|
+
|
|
319
|
+
// One batch, one lock section: the take-over trace goes in WITH the
|
|
320
|
+
// messages it describes. Written as a second call it could fail on its
|
|
321
|
+
// own, and a room written by hand while its writer was absent would read
|
|
322
|
+
// afterwards as supervised — the one thing the trace exists to prevent.
|
|
323
|
+
const written = writeAll(absolute, [
|
|
324
|
+
...pending,
|
|
325
|
+
...(takingOver
|
|
326
|
+
? [
|
|
327
|
+
{
|
|
328
|
+
from: "owner",
|
|
329
|
+
kind: "status" as const,
|
|
330
|
+
body:
|
|
331
|
+
`--take-over: ${pending.length} message(s) appended to ${absolute}` +
|
|
332
|
+
`${serving === undefined ? "" : ` while room ${serving.id} was live`} with no live writer` +
|
|
333
|
+
`${displaced === undefined ? " (no lease was held)" : ` (took over from pid ${displaced.pid})`}`,
|
|
334
|
+
},
|
|
335
|
+
]
|
|
336
|
+
: []),
|
|
337
|
+
]);
|
|
338
|
+
|
|
339
|
+
if (takingOver) {
|
|
340
|
+
// A tombstone, not a hold. The token is still replaced — that is what
|
|
341
|
+
// stops a writer which was merely paused from refreshing the lease it
|
|
342
|
+
// lost and writing beside whoever displaced it, and it is the whole
|
|
343
|
+
// reason a take-over is not just a flag on the write. What it must not do
|
|
344
|
+
// is claim the pen: this process exits within milliseconds and calls
|
|
345
|
+
// `releaseWriterLease` nowhere, so a hold taken here is a hold nothing
|
|
346
|
+
// ever gives back. Acquiring one turned each deliberate recovery into
|
|
347
|
+
// thirty seconds of "a writer is live — pid <already exited>" followed by
|
|
348
|
+
// a permanent demand to keep recovering.
|
|
349
|
+
tombstoneWriterLease(leasePath, {
|
|
350
|
+
pid: process.pid,
|
|
351
|
+
...(displaced === undefined ? {} : { takeOverFrom: displaced }),
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
for (const message of written) console.log(`Appended seq ${message.seq} from ${message.from}.`);
|
|
356
|
+
},
|
|
357
|
+
};
|