@mrciphersmith/roomyx 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MrCipherSmith
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # roomyx
2
+
3
+ MCP server + terminal UI for `startup-room`: live room status, chat, per-agent
4
+ modal, an installable room registry, and skill-sync. See
5
+ `docs/roomyx/specification.md` and `docs/roomyx-installer/specification.md`
6
+ for the full architecture; this README documents only the concrete on-disk
7
+ log format the tests in this package assume, since it isn't fully pinned down
8
+ by the JSON Schemas alone (those describe one message and one goal contract
9
+ shape, not the log file as a whole).
10
+
11
+ ## Room log format (JSONL)
12
+
13
+ One JSON object per line (`\n`-terminated). The **first line** is a `state`
14
+ record; every subsequent line is a `message` record.
15
+
16
+ ```jsonl
17
+ {"type":"state","goal_contract":{"version":1,"goal_statement":"...","criteria":"...","threshold":{"fail_below":300,"pass_at_or_above":325}},"roster":[{"id":"yuki","name":"Юки"}]}
18
+ {"type":"message","seq":1,"from":"yuki","body":"..."}
19
+ {"type":"message","seq":2,"from":"omar","in_reply_to":1,"kind":"challenge","body":"..."}
20
+ ```
21
+
22
+ - `state.goal_contract` matches the `goal-contract` schema from the
23
+ `startup-room` framework's specification (arena project).
24
+ - Each `message` record matches that framework's `message-envelope` schema
25
+ (plus the literal `"type":"message"` discriminator, which is a log-format
26
+ detail, not part of the envelope schema itself).
27
+ - `roster` entries are `{ id, name }` — `id` is what `room.get_agent_detail`
28
+ takes as `agent_id`; `name` is the display name used in `from`.
29
+
30
+ This format is this package's own design choice (not dictated by either JSON
31
+ Schema) — see `docs/roomyx/specification.md`'s Manifest/Config Shape section,
32
+ which defers the on-disk representation to implementation.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ npm install -g @mrciphersmith/roomyx
38
+ ```
39
+
40
+ ## CLI
41
+
42
+ ```bash
43
+ roomyx init # scaffold .roomyx/ in the current project
44
+ roomyx serve <logPath> [--port N] # start an MCP server for one room log
45
+ roomyx rooms list # list live rooms from the local registry
46
+ roomyx client [--room <id>] # attach the terminal UI (auto-attaches if exactly one room is live)
47
+ ```
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@mrciphersmith/roomyx",
3
+ "version": "0.1.0",
4
+ "description": "MCP server + terminal UI for startup-room: live room status, chat, per-agent modal, an installable room registry, and skill-sync.",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+ssh://git@github.com/MrCipherSmith/roomyx.git"
13
+ },
14
+ "keywords": [
15
+ "mcp",
16
+ "model-context-protocol",
17
+ "terminal-ui",
18
+ "tui",
19
+ "claude-code",
20
+ "codex",
21
+ "keryx",
22
+ "bun",
23
+ "cli"
24
+ ],
25
+ "bin": {
26
+ "roomyx": "./src/cli.ts"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "LICENSE",
31
+ "README.md",
32
+ "package.json"
33
+ ],
34
+ "scripts": {
35
+ "test": "bun test",
36
+ "typecheck": "tsc --noEmit",
37
+ "lint": "eslint src test",
38
+ "check": "bun run lint && bun run typecheck && bun test"
39
+ },
40
+ "dependencies": {
41
+ "@modelcontextprotocol/sdk": "^1.0.0",
42
+ "@opentui/core": "^0.5.11",
43
+ "zod": "^4.5.4"
44
+ },
45
+ "devDependencies": {
46
+ "@types/bun": "^1.4.2",
47
+ "eslint": "^10.10.0",
48
+ "typescript": "^5.6.0",
49
+ "typescript-eslint": "^8.0.0"
50
+ },
51
+ "engines": {
52
+ "bun": ">=1.1.0"
53
+ }
54
+ }
@@ -0,0 +1,12 @@
1
+ # startup-room (roomyx-bundled placeholder)
2
+
3
+ **This is a placeholder, not the real, live `startup-room` skill content.**
4
+
5
+ Authoring the actual auto-launch-enabled skill text — the version that will
6
+ eventually replace `~/.claude/skills/startup-room/SKILL.md` — is explicitly
7
+ out of scope for `roomyx-installer` flow 003 (see
8
+ `docs/requirements/roomyx-installer/description.md` and `decisions.md` D-02).
9
+ This file exists only so `roomyx init` and `roomyx skills sync` have a real
10
+ file to stage/copy/diff while the mechanism itself is built and tested.
11
+
12
+ Do not sync this placeholder over a real skill file.
@@ -0,0 +1,73 @@
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
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env bun
2
+ import { join } from "node:path";
3
+ import { serve } from "./server/serve";
4
+ import { init } from "./installer/init";
5
+ import { registerRoom, deregisterRoom, listLiveRooms } from "./installer/registry";
6
+
7
+ /**
8
+ * `roomyx init` / `roomyx serve <logPath> [...]` / `roomyx rooms list`.
9
+ * `roomyx client [...]` is a separate entry point (src/client/index.ts) —
10
+ * the orchestrator and the TUI are independent processes by design
11
+ * (decisions.md D-06), so they are separate binaries, not subcommands of
12
+ * one process that would tie their lifetimes together.
13
+ */
14
+
15
+ function parseFlags(args: string[]): Record<string, string | boolean> {
16
+ const flags: Record<string, string | boolean> = {};
17
+ for (let i = 0; i < args.length; i++) {
18
+ const arg = args[i];
19
+ if (arg?.startsWith("--")) {
20
+ const key = arg.slice(2);
21
+ const next = args[i + 1];
22
+ if (next !== undefined && !next.startsWith("--")) {
23
+ flags[key] = next;
24
+ i++;
25
+ } else {
26
+ flags[key] = true;
27
+ }
28
+ }
29
+ }
30
+ return flags;
31
+ }
32
+
33
+ function defaultRegistryPath(): string {
34
+ return join(process.cwd(), ".roomyx", "rooms", "registry.json");
35
+ }
36
+
37
+ async function runInit(): Promise<void> {
38
+ const bundledSkillPath = join(import.meta.dir, "bundled-skills", "startup-room", "SKILL.md");
39
+ const result = init({ cwd: process.cwd(), bundledSkillPath });
40
+ console.log(result.created ? `Created ${result.roomyxDir}` : `${result.roomyxDir} already initialized`);
41
+ }
42
+
43
+ async function runServe(logPath: string | undefined, rest: string[]): Promise<void> {
44
+ if (!logPath) {
45
+ console.error("Missing <logPath>. Usage: roomyx serve <logPath> [--port N]");
46
+ process.exit(1);
47
+ }
48
+ const flags = parseFlags(rest);
49
+ const handle = await serve(logPath, {
50
+ port: flags.port !== undefined ? Number(flags.port) : undefined,
51
+ host: typeof flags.host === "string" ? flags.host : undefined,
52
+ acknowledgeNonLoopback: flags["acknowledge-non-loopback"] === true,
53
+ });
54
+
55
+ const registryPath = typeof flags.registry === "string" ? flags.registry : defaultRegistryPath();
56
+ const entry = registerRoom(registryPath, { port: handle.port, logPath, pid: process.pid });
57
+
58
+ console.log(`roomyx serving ${logPath} at ${handle.url}`);
59
+ console.log(`room ID: ${entry.id} — attach with \`roomyx client --room ${entry.id}\``);
60
+
61
+ const shutdown = () => {
62
+ deregisterRoom(registryPath, entry.id);
63
+ void handle.close().then(() => process.exit(0));
64
+ };
65
+ process.on("SIGINT", shutdown);
66
+ process.on("SIGTERM", shutdown);
67
+ }
68
+
69
+ async function runRoomsList(): Promise<void> {
70
+ const rooms = await listLiveRooms(defaultRegistryPath());
71
+ if (rooms.length === 0) {
72
+ console.log("No live rooms.");
73
+ return;
74
+ }
75
+ for (const room of rooms) {
76
+ console.log(`${room.id} port=${room.port} log=${room.logPath} started=${room.startedAt}`);
77
+ }
78
+ }
79
+
80
+ async function main(): Promise<void> {
81
+ const [command, ...rest] = process.argv.slice(2);
82
+
83
+ if (command === "init") {
84
+ await runInit();
85
+ } else if (command === "serve") {
86
+ await runServe(rest[0], rest.slice(1));
87
+ } else if (command === "rooms" && rest[0] === "list") {
88
+ await runRoomsList();
89
+ } else {
90
+ console.error("Usage: roomyx <init|serve <logPath>|rooms list>");
91
+ process.exit(1);
92
+ }
93
+ }
94
+
95
+ main().catch((error) => {
96
+ console.error(error instanceof Error ? error.message : String(error));
97
+ process.exit(1);
98
+ });
@@ -0,0 +1,11 @@
1
+ import { TextRenderable } from "@opentui/core";
2
+ import type { RenderContext } from "@opentui/core";
3
+ import type { MessageEnvelope } from "../../log/types";
4
+
5
+ /** One chat message as its own Renderable row (see roster-sidebar.ts's header comment for why per-row, not one blob). */
6
+ export function createMessageRow(ctx: RenderContext, message: MessageEnvelope, fromName: string): TextRenderable {
7
+ return new TextRenderable(ctx, {
8
+ content: `${fromName}: ${message.body}`,
9
+ height: 1,
10
+ });
11
+ }
@@ -0,0 +1,57 @@
1
+ import { BoxRenderable, TextRenderable } from "@opentui/core";
2
+ import type { RenderContext } from "@opentui/core";
3
+ import type { RosterEntry } from "../../log/types";
4
+
5
+ /**
6
+ * Roster list — one Renderable row per participant, not a single joined-text
7
+ * blob (per-row rows are required for OpenTUI mouse targeting and keep the
8
+ * selection highlight isolated to one row's own state).
9
+ */
10
+ export class RosterSidebar {
11
+ readonly node: BoxRenderable;
12
+ private roster: RosterEntry[] = [];
13
+ private rows: TextRenderable[] = [];
14
+ private selectedIndex = 0;
15
+ private onSelect: ((agent: RosterEntry) => void) | undefined;
16
+
17
+ constructor(
18
+ private readonly ctx: RenderContext,
19
+ options: { width: number; onSelect?: (agent: RosterEntry) => void },
20
+ ) {
21
+ this.node = new BoxRenderable(ctx, { width: options.width, flexDirection: "column" });
22
+ this.onSelect = options.onSelect;
23
+ }
24
+
25
+ setRoster(roster: RosterEntry[]): void {
26
+ this.roster = roster;
27
+ for (const row of this.rows) this.node.remove(row);
28
+ this.rows = roster.map((agent, index) => {
29
+ const row = new TextRenderable(this.ctx, { content: this.rowLabel(agent, index), height: 1 });
30
+ this.node.add(row);
31
+ return row;
32
+ });
33
+ this.highlightSelected();
34
+ }
35
+
36
+ moveSelection(delta: 1 | -1): void {
37
+ if (this.roster.length === 0) return;
38
+ this.selectedIndex = (this.selectedIndex + delta + this.roster.length) % this.roster.length;
39
+ this.highlightSelected();
40
+ }
41
+
42
+ confirmSelection(): void {
43
+ const agent = this.roster[this.selectedIndex];
44
+ if (agent) this.onSelect?.(agent);
45
+ }
46
+
47
+ private rowLabel(agent: RosterEntry, index: number): string {
48
+ return `${index === this.selectedIndex ? "> " : " "}${agent.name}`;
49
+ }
50
+
51
+ private highlightSelected(): void {
52
+ this.rows.forEach((row, index) => {
53
+ const agent = this.roster[index];
54
+ if (agent) row.content = this.rowLabel(agent, index);
55
+ });
56
+ }
57
+ }
@@ -0,0 +1,33 @@
1
+ import { TextRenderable } from "@opentui/core";
2
+ import type { RenderContext } from "@opentui/core";
3
+ import type { ConnectionStatus } from "../mcp-client";
4
+ import type { GoalContract } from "../../log/types";
5
+
6
+ /** One-line status bar: goal statement + connection status. */
7
+ export class StatusBar {
8
+ readonly node: TextRenderable;
9
+ private goalStatement = "";
10
+ private status: ConnectionStatus = "connecting";
11
+
12
+ constructor(ctx: RenderContext) {
13
+ this.node = new TextRenderable(ctx, { content: "", height: 1 });
14
+ this.render();
15
+ }
16
+
17
+ setGoalContract(goal: GoalContract): void {
18
+ this.goalStatement = goal.goal_statement;
19
+ this.render();
20
+ }
21
+
22
+ setConnectionStatus(status: ConnectionStatus): void {
23
+ this.status = status;
24
+ this.render();
25
+ }
26
+
27
+ private render(): void {
28
+ const statusLabel = { connecting: "connecting…", connected: "connected", disconnected: "disconnected — retrying" }[
29
+ this.status
30
+ ];
31
+ this.node.content = `[${statusLabel}] ${this.goalStatement}`;
32
+ }
33
+ }
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env bun
2
+ import { join } from "node:path";
3
+ import { createCliRenderer } from "@opentui/core";
4
+ import { RoomClient } from "./mcp-client";
5
+ import { ChatView } from "./screens/chat-view";
6
+ import { AgentModal } from "./screens/agent-modal";
7
+ import type { RosterEntry } from "../log/types";
8
+ import { resolveConnectionUrl } from "../installer/resolve-connection";
9
+
10
+ function parseFlags(args: string[]): Record<string, string> {
11
+ const flags: Record<string, string> = {};
12
+ for (let i = 0; i < args.length; i++) {
13
+ const arg = args[i];
14
+ if (arg?.startsWith("--")) {
15
+ flags[arg.slice(2)] = args[i + 1] ?? "";
16
+ i++;
17
+ }
18
+ }
19
+ return flags;
20
+ }
21
+
22
+ async function main(): Promise<void> {
23
+ const flags = parseFlags(process.argv.slice(2));
24
+ const registryPath = flags["registry"] ?? join(process.cwd(), ".roomyx", "rooms", "registry.json");
25
+
26
+ const resolved = await resolveConnectionUrl({
27
+ connect: flags.connect,
28
+ room: flags.room,
29
+ registryPath,
30
+ });
31
+
32
+ if (!resolved.ok) {
33
+ if (resolved.reason === "no-rooms") {
34
+ console.error("No live roomyx rooms found. Start one with `roomyx serve <logPath>` first.");
35
+ } else if (resolved.reason === "room-not-found") {
36
+ console.error(`No live room with id "${flags.room}". Run \`roomyx rooms list\` to see what's running.`);
37
+ } else {
38
+ const ids = (resolved.candidates ?? []).map((r) => r.id).join(", ");
39
+ console.error(`Multiple live rooms found (${ids}). Pick one with --room <id>.`);
40
+ }
41
+ process.exit(1);
42
+ }
43
+ const url = resolved.url;
44
+
45
+ const renderer = await createCliRenderer({ targetFps: 30 });
46
+
47
+ const modal = new AgentModal(renderer, {
48
+ width: Math.floor(renderer.terminalWidth * 0.7),
49
+ height: Math.floor(renderer.terminalHeight * 0.7),
50
+ });
51
+
52
+ const chatView = new ChatView(renderer, {
53
+ width: renderer.terminalWidth,
54
+ height: renderer.terminalHeight,
55
+ onSelectAgent: (agent: RosterEntry) => {
56
+ void roomClient.getAgentDetail(agent.id).then((detail) => modal.show(detail));
57
+ },
58
+ });
59
+
60
+ renderer.root.add(chatView.node);
61
+ renderer.root.add(modal.node);
62
+
63
+ const roomClient = new RoomClient(
64
+ { url },
65
+ {
66
+ onConnectionChange: (status) => chatView.setConnectionStatus(status),
67
+ onStateUpdate: (state) => {
68
+ chatView.setGoalContract(state.goal_contract);
69
+ chatView.setRoster(state.roster);
70
+ },
71
+ onNewMessages: (messages) => chatView.appendMessages(messages),
72
+ },
73
+ );
74
+ roomClient.start();
75
+
76
+ renderer.keyInput.on("keypress", (event) => {
77
+ if (modal.isVisible()) {
78
+ if (event.name === "escape") modal.hide();
79
+ return;
80
+ }
81
+ if (event.name === "up") chatView.roster.moveSelection(-1);
82
+ else if (event.name === "down") chatView.roster.moveSelection(1);
83
+ else if (event.name === "return") chatView.roster.confirmSelection();
84
+ else if (event.name === "q" || (event.name === "c" && event.ctrl)) {
85
+ void roomClient.stop().finally(() => {
86
+ renderer.destroy();
87
+ process.exit(0);
88
+ });
89
+ }
90
+ });
91
+ }
92
+
93
+ main().catch((error) => {
94
+ console.error(error);
95
+ process.exit(1);
96
+ });
@@ -0,0 +1,149 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
+ import type { MessageEnvelope, RoomState } from "../log/types";
4
+
5
+ export type ConnectionStatus = "connecting" | "connected" | "disconnected";
6
+
7
+ export interface RoomClientOptions {
8
+ url: string;
9
+ /** How often to poll room.get_state. Roster/goal contract change rarely. */
10
+ stateIntervalMs?: number;
11
+ /** How often to poll room.get_transcript. */
12
+ transcriptIntervalMs?: number;
13
+ }
14
+
15
+ export interface RoomClientEvents {
16
+ onStateUpdate?(state: RoomState): void;
17
+ onNewMessages?(messages: MessageEnvelope[]): void;
18
+ onConnectionChange?(status: ConnectionStatus): void;
19
+ }
20
+
21
+ /**
22
+ * Polls a roomyx MCP server over HTTP for state and transcript updates.
23
+ * Deliberately polling, not a push subscription — mirrors the server's own
24
+ * "re-read on every call, no fs-watch" simplicity (see roomyx/README.md).
25
+ * Tracks `since_seq` locally so a reconnect never re-delivers old messages.
26
+ */
27
+ export class RoomClient {
28
+ private readonly url: string;
29
+ private readonly stateIntervalMs: number;
30
+ private readonly transcriptIntervalMs: number;
31
+ private readonly events: RoomClientEvents;
32
+
33
+ private client: Client | undefined;
34
+ private status: ConnectionStatus = "connecting";
35
+ private sinceSeq = 0;
36
+ private stopped = false;
37
+ private stateTimer: ReturnType<typeof setTimeout> | undefined;
38
+ private transcriptTimer: ReturnType<typeof setTimeout> | undefined;
39
+
40
+ constructor(options: RoomClientOptions, events: RoomClientEvents) {
41
+ this.url = options.url;
42
+ this.stateIntervalMs = options.stateIntervalMs ?? 3000;
43
+ this.transcriptIntervalMs = options.transcriptIntervalMs ?? 1000;
44
+ this.events = events;
45
+ }
46
+
47
+ start(): void {
48
+ this.stopped = false;
49
+ this.scheduleConnect(0);
50
+ }
51
+
52
+ async stop(): Promise<void> {
53
+ this.stopped = true;
54
+ clearTimeout(this.stateTimer);
55
+ clearTimeout(this.transcriptTimer);
56
+ await this.client?.close().catch(() => undefined);
57
+ this.client = undefined;
58
+ }
59
+
60
+ getLastSeenSeq(): number {
61
+ return this.sinceSeq;
62
+ }
63
+
64
+ /** On-demand call for the agent modal — not part of the poll loop. */
65
+ async getAgentDetail(agentId: string): Promise<import("../log/types").AgentDetail> {
66
+ return this.callTool("room.get_agent_detail", { agent_id: agentId });
67
+ }
68
+
69
+ private setStatus(status: ConnectionStatus): void {
70
+ if (this.status === status) return;
71
+ this.status = status;
72
+ this.events.onConnectionChange?.(status);
73
+ }
74
+
75
+ private scheduleConnect(delayMs: number): void {
76
+ if (this.stopped) return;
77
+ setTimeout(() => {
78
+ void this.connect();
79
+ }, delayMs);
80
+ }
81
+
82
+ private async connect(): Promise<void> {
83
+ if (this.stopped) return;
84
+ this.setStatus("connecting");
85
+ try {
86
+ const client = new Client({ name: "roomyx-client", version: "0.1.0" });
87
+ await client.connect(new StreamableHTTPClientTransport(new URL(this.url)));
88
+ if (this.stopped) {
89
+ // stop() ran while this connection was in flight; this.client was
90
+ // still undefined for it to close, so close the one it never saw.
91
+ await client.close().catch(() => undefined);
92
+ return;
93
+ }
94
+ this.client = client;
95
+ this.setStatus("connected");
96
+ this.pollState();
97
+ this.pollTranscript();
98
+ } catch {
99
+ this.setStatus("disconnected");
100
+ this.scheduleConnect(this.transcriptIntervalMs);
101
+ }
102
+ }
103
+
104
+ private async callTool<T>(name: string, args: Record<string, unknown>): Promise<T> {
105
+ if (!this.client) throw new Error("not connected");
106
+ const result = await this.client.callTool({ name, arguments: args });
107
+ const content = result.content as Array<{ type: string; text: string }>;
108
+ return JSON.parse(content[0]?.text ?? "null") as T;
109
+ }
110
+
111
+ private pollState(): void {
112
+ if (this.stopped) return;
113
+ this.callTool<RoomState>("room.get_state", {})
114
+ .then((state) => {
115
+ if (this.stopped) return;
116
+ this.events.onStateUpdate?.(state);
117
+ this.stateTimer = setTimeout(() => this.pollState(), this.stateIntervalMs);
118
+ })
119
+ .catch(() => {
120
+ if (this.stopped) return;
121
+ this.handleDisconnect();
122
+ });
123
+ }
124
+
125
+ private pollTranscript(): void {
126
+ if (this.stopped) return;
127
+ this.callTool<MessageEnvelope[]>("room.get_transcript", { since_seq: this.sinceSeq })
128
+ .then((messages) => {
129
+ if (this.stopped) return;
130
+ if (messages.length > 0) {
131
+ this.sinceSeq = Math.max(this.sinceSeq, ...messages.map((m) => m.seq));
132
+ this.events.onNewMessages?.(messages);
133
+ }
134
+ this.transcriptTimer = setTimeout(() => this.pollTranscript(), this.transcriptIntervalMs);
135
+ })
136
+ .catch(() => {
137
+ if (this.stopped) return;
138
+ this.handleDisconnect();
139
+ });
140
+ }
141
+
142
+ private handleDisconnect(): void {
143
+ if (this.stopped) return;
144
+ clearTimeout(this.stateTimer);
145
+ clearTimeout(this.transcriptTimer);
146
+ this.setStatus("disconnected");
147
+ this.scheduleConnect(this.transcriptIntervalMs);
148
+ }
149
+ }