@mrciphersmith/roomyx 0.4.0 → 0.5.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.
@@ -0,0 +1,80 @@
1
+ import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import type { GoalContract, MessageEnvelope, RosterEntry } from "./types";
5
+
6
+ /**
7
+ * The write side of a room log, which `store.ts` reads.
8
+ *
9
+ * D-01 keeps one writer per *live* room. That constrains the server, not the
10
+ * package — creating a log nobody is serving takes the writer count from zero
11
+ * to one, and there is no race to lose. Appending to a log a dispatcher is
12
+ * actively writing is the case that would break the invariant, so the CLI
13
+ * checks the registry before doing it. See D-01a.
14
+ */
15
+
16
+ export interface CreateRoomLogOptions {
17
+ goalStatement: string;
18
+ criteria?: string;
19
+ roster: RosterEntry[];
20
+ threshold?: GoalContract["threshold"];
21
+ }
22
+
23
+ export interface AppendMessageOptions {
24
+ from: string;
25
+ body: string;
26
+ kind?: MessageEnvelope["kind"];
27
+ inReplyTo?: number;
28
+ }
29
+
30
+ /** Refuses to overwrite: a room log is append-only, and clobbering one loses a session. */
31
+ export function createRoomLog(path: string, options: CreateRoomLogOptions): void {
32
+ if (existsSync(path)) {
33
+ throw new Error(`${path} already exists. A room log is append-only; refusing to overwrite it.`);
34
+ }
35
+ const goalContract: GoalContract = {
36
+ version: 1,
37
+ goal_statement: options.goalStatement,
38
+ criteria: options.criteria ?? "",
39
+ threshold: options.threshold ?? { fail_below: 60, pass_at_or_above: 80 },
40
+ };
41
+ mkdirSync(dirname(path), { recursive: true });
42
+ writeFileSync(path, JSON.stringify({ type: "state", goal_contract: goalContract, roster: options.roster }) + "\n");
43
+ }
44
+
45
+ /** The next `seq`, derived from the log rather than tracked separately. */
46
+ export function nextSeq(path: string): number {
47
+ if (!existsSync(path)) return 1;
48
+ const lines = readFileSync(path, "utf8")
49
+ .split("\n")
50
+ .filter((line) => line.trim().length > 0);
51
+ const seqs = lines.slice(1).map((line) => (JSON.parse(line) as { seq: number }).seq);
52
+ return seqs.length > 0 ? Math.max(...seqs) + 1 : 1;
53
+ }
54
+
55
+ export function appendMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
56
+ if (!existsSync(path)) {
57
+ throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
58
+ }
59
+ const message: MessageEnvelope & { type: "message" } = {
60
+ type: "message",
61
+ seq: nextSeq(path),
62
+ from: options.from,
63
+ body: options.body,
64
+ ...(options.kind ? { kind: options.kind } : {}),
65
+ ...(options.inReplyTo !== undefined ? { in_reply_to: options.inReplyTo } : {}),
66
+ };
67
+ appendFileSync(path, JSON.stringify(message) + "\n");
68
+ return message;
69
+ }
70
+
71
+ /** `id:Name,id2:Name2` — the shape the CLI takes and the log stores. */
72
+ export function parseRoster(spec: string): RosterEntry[] {
73
+ return spec
74
+ .split(",")
75
+ .filter(Boolean)
76
+ .map((pair) => {
77
+ const [id, name] = pair.split(":");
78
+ return { id: id ?? "", name: name ?? id ?? "" };
79
+ });
80
+ }
@@ -1,7 +1,7 @@
1
- import { createServer } from "node:http";
2
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
2
  import { z } from "zod";
3
+ import { serveMcpOverHttp } from "../server/http-transport";
4
+ import type { McpHttpTransportHandle } from "../server/http-transport";
5
5
  import { listLiveRooms } from "../installer/registry";
6
6
  import { syncSkill } from "../installer/skill-sync";
7
7
  import { NAMED_TARGETS, resolveTargets } from "../installer/skill-targets";
@@ -10,6 +10,15 @@ export interface ManagementOptions {
10
10
  registryPath: string;
11
11
  bundledSkillPath: string;
12
12
  configPath: string;
13
+ /**
14
+ * The project a project-scoped target resolves against — `keryx` keeps its
15
+ * skills in `<project>/.metaproject/project-skills/`. Defaults to
16
+ * `process.cwd()`, which is right for `roomyx mcp` and wrong for a
17
+ * long-lived embedded server whose working directory is somebody else's.
18
+ * Every other path this server touches is already explicit; this one was
19
+ * the exception.
20
+ */
21
+ cwd?: string;
13
22
  }
14
23
 
15
24
  export interface ManagementServeOptions {
@@ -45,33 +54,21 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
45
54
  {
46
55
  title: "Sync the bundled startup-room skill",
47
56
  description:
48
- "Diffs/backs-up/writes the bundled skill into a target (see decisions.md D-02 for safety rules).",
57
+ "Diffs/backs-up/writes the bundled skill into a named runtime's skill location (see decisions.md D-02 for safety rules).",
49
58
  inputSchema: {
50
- target: z
51
- .enum([...NAMED_TARGETS, "all"])
52
- .optional()
53
- .describe("A runtime by name, or `all`. Use targetPath instead for a literal path."),
54
- targetPath: z.string().min(1).optional().describe("A literal path. Takes precedence over target."),
59
+ // Named targets only. This tool used to accept a literal `targetPath`,
60
+ // which made it an arbitrary-path file writer reachable over a loopback
61
+ // port with no authentication — a browser on any page the operator
62
+ // visits could drive it cross-origin. The CLI keeps the literal-path
63
+ // escape hatch, because that is the operator on their own machine;
64
+ // the network surface does not get one.
65
+ target: z.enum([...NAMED_TARGETS, "all"]).describe("A runtime by name, or `all`."),
55
66
  dryRun: z.boolean().optional(),
56
67
  yes: z.boolean().optional(),
57
68
  },
58
69
  },
59
- async ({ target, targetPath, dryRun, yes }) => {
60
- // One of the two is required, and neither can be marked required in the
61
- // schema without excluding the other.
62
- if (!target && !targetPath) {
63
- return {
64
- content: [
65
- {
66
- type: "text",
67
- text: JSON.stringify({
68
- error: `Pass either target (${[...NAMED_TARGETS, "all"].join(", ")}) or targetPath.`,
69
- }),
70
- },
71
- ],
72
- };
73
- }
74
- const targets = targetPath ? [{ name: targetPath, path: targetPath }] : resolveTargets(target as string);
70
+ async ({ target, dryRun, yes }) => {
71
+ const targets = resolveTargets(target, options.cwd);
75
72
  const results = targets.map(({ name, path }) => ({
76
73
  target: name,
77
74
  path,
@@ -90,86 +87,30 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
90
87
  return server;
91
88
  }
92
89
 
93
- export interface ManagementHandle {
94
- url: string;
95
- port: number;
96
- close(): Promise<void>;
97
- }
90
+ export type ManagementHandle = McpHttpTransportHandle;
98
91
 
99
- const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
92
+ export interface ManagementServeOptions {
93
+ /** Defaults to 4320 so it does not collide with `roomyx serve` (4319). 0 selects an ephemeral port. */
94
+ port?: number;
95
+ host?: string;
96
+ acknowledgeNonLoopback?: boolean;
97
+ }
100
98
 
101
99
  /**
102
- * Binds createManagementMcpServer() to a loopback HTTP transport, same
103
- * multi-session pattern as ../server/serve.ts: one StreamableHTTP transport
104
- * only ever completes a single initialize handshake, so each new session
105
- * gets its own transport + McpServer pair.
100
+ * Serves the management tools over the shared loopback HTTP transport. The
101
+ * session, binding and shutdown behaviour is `../server/http-transport`'s —
102
+ * this file used to carry its own copy, and the copies had already drifted.
106
103
  */
107
104
  export async function serveManagement(
108
105
  options: ManagementOptions,
109
106
  serveOptions: ManagementServeOptions,
110
107
  ): Promise<ManagementHandle> {
111
- const host = serveOptions.host ?? "127.0.0.1";
112
- if (!LOOPBACK_HOSTS.has(host) && !serveOptions.acknowledgeNonLoopback) {
113
- throw new Error(
114
- `Refusing to bind roomyx mcp to non-loopback host "${host}" without --acknowledge-non-loopback.`,
115
- );
116
- }
117
-
118
- const sessions = new Map<string, StreamableHTTPServerTransport>();
119
-
120
- async function createSession(): Promise<StreamableHTTPServerTransport> {
121
- const transport = new StreamableHTTPServerTransport({
122
- sessionIdGenerator: () => crypto.randomUUID(),
123
- onsessioninitialized: (sessionId) => {
124
- sessions.set(sessionId, transport);
125
- },
126
- onsessionclosed: (sessionId) => {
127
- sessions.delete(sessionId);
128
- },
129
- });
130
- const mcpServer = createManagementMcpServer(options);
131
- await mcpServer.connect(transport);
132
- return transport;
133
- }
134
-
135
- const httpServer = createServer((req, res) => {
136
- const sessionIdHeader = req.headers["mcp-session-id"];
137
- const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
138
- const existing = sessionId ? sessions.get(sessionId) : undefined;
139
-
140
- const transportPromise = existing ? Promise.resolve(existing) : createSession();
141
- transportPromise
142
- .then((transport) => transport.handleRequest(req, res))
143
- .catch((error) => {
144
- if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
145
- res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
146
- });
108
+ return serveMcpOverHttp({
109
+ createMcpServer: () => createManagementMcpServer(options),
110
+ commandLabel: "roomyx mcp",
111
+ defaultPort: 4320,
112
+ port: serveOptions.port,
113
+ host: serveOptions.host,
114
+ acknowledgeNonLoopback: serveOptions.acknowledgeNonLoopback,
147
115
  });
148
-
149
- const port = serveOptions.port ?? 4320;
150
- try {
151
- await new Promise<void>((resolve, reject) => {
152
- httpServer.once("error", reject);
153
- httpServer.listen(port, host, () => resolve());
154
- });
155
- } catch (error) {
156
- await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
157
- throw error;
158
- }
159
-
160
- const address = httpServer.address();
161
- const actualPort = typeof address === "object" && address !== null ? address.port : port;
162
-
163
- return {
164
- url: `http://${host}:${actualPort}/mcp`,
165
- port: actualPort,
166
- close: () =>
167
- new Promise<void>((resolve, reject) => {
168
- httpServer.close(async (error) => {
169
- await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
170
- if (error) reject(error);
171
- else resolve();
172
- });
173
- }),
174
- };
175
116
  }
@@ -0,0 +1,149 @@
1
+ import { createServer as createHttpServer } from "node:http";
2
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+
5
+ /**
6
+ * The loopback HTTP transport both roomyx servers bind to.
7
+ *
8
+ * It was written twice — once for the per-room server, once for the management
9
+ * server — and the copies had drifted: only one of them closed its sessions on
10
+ * shutdown. Two servers meant every transport-level fix had to be applied
11
+ * twice, and a signed tarball is a poor place to discover that the second one
12
+ * was missed. There is one now.
13
+ *
14
+ * A single `StreamableHTTPServerTransport` only ever completes ONE `initialize`
15
+ * handshake for its whole lifetime — an independent review reproduced this
16
+ * concretely: a second client, even a short-lived liveness check, gets "Server
17
+ * already initialized" and the transport is permanently unusable afterward. So
18
+ * each session (a request with no `mcp-session-id`) gets its own transport and
19
+ * its own `McpServer`, tracked by session id, and later requests carrying that
20
+ * header are routed to the pair that already exists.
21
+ */
22
+
23
+ export interface McpHttpTransportOptions {
24
+ /** Called once per session. Each session gets its own server instance. */
25
+ createMcpServer: () => McpServer;
26
+ /** Used in the refusal message when a non-loopback host is asked for without acknowledgement. */
27
+ commandLabel: string;
28
+ /** `roomyx serve` uses 4319, `roomyx mcp` 4320 — they must not collide. 0 selects an ephemeral port. */
29
+ defaultPort: number;
30
+ port?: number;
31
+ host?: string;
32
+ acknowledgeNonLoopback?: boolean;
33
+ }
34
+
35
+ export interface McpHttpTransportHandle {
36
+ url: string;
37
+ port: number;
38
+ close(): Promise<void>;
39
+ }
40
+
41
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
42
+
43
+ /**
44
+ * Refuses non-loopback hosts unless explicitly acknowledged, mirroring `keryx
45
+ * serve`'s convention — same reasoning, recorded as D-06.
46
+ */
47
+ export async function serveMcpOverHttp(
48
+ options: McpHttpTransportOptions,
49
+ ): Promise<McpHttpTransportHandle> {
50
+ const host = options.host ?? "127.0.0.1";
51
+ if (!LOOPBACK_HOSTS.has(host) && !options.acknowledgeNonLoopback) {
52
+ throw new Error(
53
+ `Refusing to bind ${options.commandLabel} to non-loopback host "${host}" without --acknowledge-non-loopback.`,
54
+ );
55
+ }
56
+
57
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
58
+
59
+ // Filled in after listen(). Sessions are only ever created while handling a
60
+ // request, so by the time createSession runs this is the real bound port —
61
+ // which matters because the allowlists below cannot be built without it.
62
+ let boundPort = 0;
63
+
64
+ async function createSession(): Promise<StreamableHTTPServerTransport> {
65
+ const transport = new StreamableHTTPServerTransport({
66
+ sessionIdGenerator: () => crypto.randomUUID(),
67
+ // Both guards, built lazily, from the port we actually bound.
68
+ //
69
+ // `allowedHosts` is an exact match against the whole `Host` header,
70
+ // port included: a port-less allowlist returns 403 to roomyx's own
71
+ // client. And with `--port 0` the port is not knowable until listen()
72
+ // resolves, so an allowlist written at option-construction time would be
73
+ // wrong by construction.
74
+ //
75
+ // Both lists are required because they stop different attacks. A page at
76
+ // http://127.0.0.1:<port>/mcp sends a legitimate Host, so only
77
+ // `allowedOrigins` refuses it. A DNS-rebound page sends
78
+ // `Host: attacker.example` and, post-rebind, a same-origin Origin — so
79
+ // only `allowedHosts` refuses that one.
80
+ //
81
+ // Nothing legitimate sends an Origin at all: roomyx's own client, the
82
+ // liveness probe and every MCP client are not browsers. The SDK skips
83
+ // the Origin check when the header is absent, so the list below exists
84
+ // to be matched by nothing.
85
+ enableDnsRebindingProtection: true,
86
+ allowedHosts: [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`],
87
+ allowedOrigins: [`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`],
88
+ onsessioninitialized: (sessionId) => {
89
+ sessions.set(sessionId, transport);
90
+ },
91
+ onsessionclosed: (sessionId) => {
92
+ sessions.delete(sessionId);
93
+ },
94
+ });
95
+ const mcpServer = options.createMcpServer();
96
+ await mcpServer.connect(transport);
97
+ return transport;
98
+ }
99
+
100
+ const httpServer = createHttpServer((req, res) => {
101
+ const sessionIdHeader = req.headers["mcp-session-id"];
102
+ const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
103
+ const existing = sessionId ? sessions.get(sessionId) : undefined;
104
+
105
+ const transportPromise = existing ? Promise.resolve(existing) : createSession();
106
+ transportPromise
107
+ .then((transport) => transport.handleRequest(req, res))
108
+ .catch((error) => {
109
+ if (!res.headersSent) {
110
+ res.writeHead(500, { "content-type": "application/json" });
111
+ }
112
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
113
+ });
114
+ });
115
+
116
+ const port = options.port ?? options.defaultPort;
117
+ try {
118
+ await new Promise<void>((resolve, reject) => {
119
+ httpServer.once("error", reject);
120
+ httpServer.listen(port, host, () => resolve());
121
+ });
122
+ } catch (error) {
123
+ await closeSessions(sessions);
124
+ throw error;
125
+ }
126
+
127
+ const address = httpServer.address();
128
+ const actualPort = typeof address === "object" && address !== null ? address.port : port;
129
+ boundPort = actualPort;
130
+
131
+ return {
132
+ url: `http://${host}:${actualPort}/mcp`,
133
+ port: actualPort,
134
+ close: () =>
135
+ new Promise<void>((resolve, reject) => {
136
+ httpServer.close(async (error) => {
137
+ // The management server used to skip this, so its sessions outlived
138
+ // the process that owned them. One implementation, one behaviour.
139
+ await closeSessions(sessions);
140
+ if (error) reject(error);
141
+ else resolve();
142
+ });
143
+ }),
144
+ };
145
+ }
146
+
147
+ function closeSessions(sessions: Map<string, StreamableHTTPServerTransport>): Promise<unknown[]> {
148
+ return Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
149
+ }
@@ -1,9 +1,7 @@
1
- import { createServer } from "node:http";
2
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
1
  import { createRoomMcpServer } from "./index";
4
2
  import type { RoomMcpServerOptions } from "./index";
5
-
6
- const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
3
+ import { serveMcpOverHttp } from "./http-transport";
4
+ import type { McpHttpTransportHandle } from "./http-transport";
7
5
 
8
6
  export interface ServeOptions extends RoomMcpServerOptions {
9
7
  /** Defaults to 4319 (specification.md's default). 0 selects an ephemeral port. */
@@ -12,91 +10,20 @@ export interface ServeOptions extends RoomMcpServerOptions {
12
10
  acknowledgeNonLoopback?: boolean;
13
11
  }
14
12
 
15
- export interface ServeHandle {
16
- url: string;
17
- port: number;
18
- close(): Promise<void>;
19
- }
13
+ export type ServeHandle = McpHttpTransportHandle;
20
14
 
21
15
  /**
22
- * Binds `createRoomMcpServer(logPath)` to a loopback HTTP transport
23
- * (StreamableHTTP). Supports multiple, fully independent client sessions
24
- * against one long-lived server process — a single `StreamableHTTPServerTransport`
25
- * only ever completes ONE `initialize` handshake for its whole lifetime (an
26
- * independent review reproduced this concretely: a second client, even a
27
- * short-lived liveness check, gets "Server already initialized" and the
28
- * transport is permanently unusable afterward). Each new session (a request
29
- * with no `mcp-session-id` header) gets its own transport + `McpServer` pair,
30
- * tracked by session id via `onsessioninitialized`/`onsessionclosed`;
31
- * subsequent requests carrying that header are routed to the existing pair.
32
- * Refuses non-loopback hosts unless explicitly acknowledged (mirrors `keryx
33
- * serve`'s own convention — see docs/requirements/roomyx/decisions.md D-06).
16
+ * Serves one room log over the shared loopback HTTP transport. Everything about
17
+ * sessions, binding and shutdown lives in `./http-transport`; what belongs here
18
+ * is which server a session gets and which port it defaults to.
34
19
  */
35
20
  export async function serve(logPath: string, options: ServeOptions): Promise<ServeHandle> {
36
- const host = options.host ?? "127.0.0.1";
37
- if (!LOOPBACK_HOSTS.has(host) && !options.acknowledgeNonLoopback) {
38
- throw new Error(
39
- `Refusing to bind roomyx serve to non-loopback host "${host}" without --acknowledge-non-loopback.`,
40
- );
41
- }
42
-
43
- const sessions = new Map<string, StreamableHTTPServerTransport>();
44
-
45
- async function createSession(): Promise<StreamableHTTPServerTransport> {
46
- const transport = new StreamableHTTPServerTransport({
47
- sessionIdGenerator: () => crypto.randomUUID(),
48
- onsessioninitialized: (sessionId) => {
49
- sessions.set(sessionId, transport);
50
- },
51
- onsessionclosed: (sessionId) => {
52
- sessions.delete(sessionId);
53
- },
54
- });
55
- const mcpServer = createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand });
56
- await mcpServer.connect(transport);
57
- return transport;
58
- }
59
-
60
- const httpServer = createServer((req, res) => {
61
- const sessionIdHeader = req.headers["mcp-session-id"];
62
- const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
63
- const existing = sessionId ? sessions.get(sessionId) : undefined;
64
-
65
- const transportPromise = existing ? Promise.resolve(existing) : createSession();
66
- transportPromise
67
- .then((transport) => transport.handleRequest(req, res))
68
- .catch((error) => {
69
- if (!res.headersSent) {
70
- res.writeHead(500, { "content-type": "application/json" });
71
- }
72
- res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
73
- });
21
+ return serveMcpOverHttp({
22
+ createMcpServer: () => createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand }),
23
+ commandLabel: "roomyx serve",
24
+ defaultPort: 4319,
25
+ port: options.port,
26
+ host: options.host,
27
+ acknowledgeNonLoopback: options.acknowledgeNonLoopback,
74
28
  });
75
-
76
- const port = options.port ?? 4319;
77
- try {
78
- await new Promise<void>((resolve, reject) => {
79
- httpServer.once("error", reject);
80
- httpServer.listen(port, host, () => resolve());
81
- });
82
- } catch (error) {
83
- await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
84
- throw error;
85
- }
86
-
87
- const address = httpServer.address();
88
- const actualPort = typeof address === "object" && address !== null ? address.port : port;
89
-
90
- return {
91
- url: `http://${host}:${actualPort}/mcp`,
92
- port: actualPort,
93
- close: () =>
94
- new Promise<void>((resolve, reject) => {
95
- httpServer.close(async (error) => {
96
- await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
97
- if (error) reject(error);
98
- else resolve();
99
- });
100
- }),
101
- };
102
29
  }
package/src/cli/seed.ts DELETED
@@ -1,73 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import type { GoalContract, MessageEnvelope, RosterEntry } from "../log/types";
4
-
5
- /**
6
- * Manual-testing helper: initializes a room log with a state header, or
7
- * appends one message to an existing log. Not part of the MCP server itself
8
- * (D-01 in docs/requirements/roomyx/decisions.md — only the dispatcher
9
- * writes the real log; this is a standalone fixture-seeding tool for local
10
- * development, not a live dispatcher integration).
11
- *
12
- * Usage:
13
- * bun src/cli/seed.ts init <path> --goal "<goal_statement>" --roster id1:Name1,id2:Name2
14
- * bun src/cli/seed.ts append <path> --from <id> --body "<text>" [--kind pitch] [--in-reply-to N]
15
- */
16
-
17
- function parseFlags(args: string[]): Record<string, string> {
18
- const flags: Record<string, string> = {};
19
- for (let i = 0; i < args.length; i++) {
20
- const arg = args[i];
21
- if (arg?.startsWith("--")) {
22
- flags[arg.slice(2)] = args[i + 1] ?? "";
23
- i++;
24
- }
25
- }
26
- return flags;
27
- }
28
-
29
- function nextSeq(path: string): number {
30
- if (!existsSync(path)) return 1;
31
- const lines = readFileSync(path, "utf8")
32
- .split("\n")
33
- .filter((l) => l.trim().length > 0);
34
- const messageSeqs = lines
35
- .slice(1)
36
- .map((l) => (JSON.parse(l) as { seq: number }).seq);
37
- return messageSeqs.length > 0 ? Math.max(...messageSeqs) + 1 : 1;
38
- }
39
-
40
- const [command, path, ...rest] = process.argv.slice(2);
41
- const flags = parseFlags(rest);
42
-
43
- if (command === "init" && path) {
44
- const roster: RosterEntry[] = (flags.roster ?? "")
45
- .split(",")
46
- .filter(Boolean)
47
- .map((pair) => {
48
- const [id, name] = pair.split(":");
49
- return { id: id ?? "", name: name ?? id ?? "" };
50
- });
51
- const goalContract: GoalContract = {
52
- version: 1,
53
- goal_statement: flags.goal ?? "Untitled room",
54
- criteria: flags.criteria ?? "",
55
- threshold: { fail_below: 60, pass_at_or_above: 80 },
56
- };
57
- writeFileSync(path, JSON.stringify({ type: "state", goal_contract: goalContract, roster }) + "\n");
58
- console.log(`Initialized ${path} with ${roster.length} roster entries.`);
59
- } else if (command === "append" && path) {
60
- const message: MessageEnvelope & { type: "message" } = {
61
- type: "message",
62
- seq: nextSeq(path),
63
- from: flags.from ?? "unknown",
64
- body: flags.body ?? "",
65
- ...(flags.kind ? { kind: flags.kind as MessageEnvelope["kind"] } : {}),
66
- ...(flags["in-reply-to"] ? { in_reply_to: Number(flags["in-reply-to"]) } : {}),
67
- };
68
- appendFileSync(path, JSON.stringify(message) + "\n");
69
- console.log(`Appended seq ${message.seq} from ${message.from} to ${path}.`);
70
- } else {
71
- console.error("Usage: bun src/cli/seed.ts init|append <path> [--flags...]");
72
- process.exit(1);
73
- }