@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 +21 -0
- package/README.md +47 -0
- package/package.json +54 -0
- package/src/bundled-skills/startup-room/SKILL.md +12 -0
- package/src/cli/seed.ts +73 -0
- package/src/cli.ts +98 -0
- package/src/client/components/message-row.ts +11 -0
- package/src/client/components/roster-sidebar.ts +57 -0
- package/src/client/components/status-bar.ts +33 -0
- package/src/client/index.ts +96 -0
- package/src/client/mcp-client.ts +149 -0
- package/src/client/screens/agent-modal.ts +59 -0
- package/src/client/screens/chat-view.ts +59 -0
- package/src/installer/init.ts +47 -0
- package/src/installer/registry.ts +202 -0
- package/src/installer/resolve-connection.ts +39 -0
- package/src/installer/skill-sync.ts +94 -0
- package/src/log/store.ts +102 -0
- package/src/log/types.ts +35 -0
- package/src/mcp-management/server.ts +113 -0
- package/src/server/index.ts +52 -0
- package/src/server/serve.ts +101 -0
- package/src/server/tools/get-agent-detail.ts +8 -0
- package/src/server/tools/get-state.ts +8 -0
- package/src/server/tools/get-transcript.ts +8 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { BoxRenderable, ScrollBoxRenderable, TextRenderable } from "@opentui/core";
|
|
2
|
+
import type { RenderContext } from "@opentui/core";
|
|
3
|
+
import { createMessageRow } from "../components/message-row";
|
|
4
|
+
import type { AgentDetail } from "../../log/types";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Modal overlay for one participant's own messages (R4 / AC2 — shows only
|
|
8
|
+
* that participant's data, not the full transcript). Drawn over the chat
|
|
9
|
+
* view, not a screen replacement, matching the pattern observed in keryx's
|
|
10
|
+
* own mcp-inspector.ts (background stays visible, modal on top).
|
|
11
|
+
*/
|
|
12
|
+
export class AgentModal {
|
|
13
|
+
readonly node: BoxRenderable;
|
|
14
|
+
private readonly title: TextRenderable;
|
|
15
|
+
private readonly scroll: ScrollBoxRenderable;
|
|
16
|
+
private readonly ctx: RenderContext;
|
|
17
|
+
|
|
18
|
+
constructor(ctx: RenderContext, options: { width: number; height: number }) {
|
|
19
|
+
this.ctx = ctx;
|
|
20
|
+
this.node = new BoxRenderable(ctx, {
|
|
21
|
+
width: options.width,
|
|
22
|
+
height: options.height,
|
|
23
|
+
flexDirection: "column",
|
|
24
|
+
border: true,
|
|
25
|
+
visible: false,
|
|
26
|
+
position: "absolute",
|
|
27
|
+
top: 2,
|
|
28
|
+
left: 2,
|
|
29
|
+
zIndex: 10,
|
|
30
|
+
backgroundColor: "#000000",
|
|
31
|
+
});
|
|
32
|
+
this.title = new TextRenderable(ctx, { content: "", height: 1 });
|
|
33
|
+
this.node.add(this.title);
|
|
34
|
+
this.scroll = new ScrollBoxRenderable(ctx, { flexGrow: 1 });
|
|
35
|
+
this.node.add(this.scroll);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
show(detail: AgentDetail): void {
|
|
39
|
+
for (const child of this.scroll.getChildren()) this.scroll.remove(child);
|
|
40
|
+
if (!detail.found) {
|
|
41
|
+
this.title.content = "Agent not found";
|
|
42
|
+
this.node.visible = true;
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
this.title.content = `${detail.agent.name} — last seen at seq ${detail.lastSeenSeq}`;
|
|
46
|
+
for (const message of detail.messages) {
|
|
47
|
+
this.scroll.add(createMessageRow(this.ctx, message, detail.agent.name));
|
|
48
|
+
}
|
|
49
|
+
this.node.visible = true;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
hide(): void {
|
|
53
|
+
this.node.visible = false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
isVisible(): boolean {
|
|
57
|
+
return this.node.visible;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { BoxRenderable, ScrollBoxRenderable } from "@opentui/core";
|
|
2
|
+
import type { RenderContext } from "@opentui/core";
|
|
3
|
+
import type { GoalContract, MessageEnvelope, RosterEntry } from "../../log/types";
|
|
4
|
+
import { StatusBar } from "../components/status-bar";
|
|
5
|
+
import { RosterSidebar } from "../components/roster-sidebar";
|
|
6
|
+
import { createMessageRow } from "../components/message-row";
|
|
7
|
+
import type { ConnectionStatus } from "../mcp-client";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Main screen: StatusBar on top, RosterSidebar on the left, a scrolling
|
|
11
|
+
* message stream on the right. Uses ScrollBoxRenderable's built-in
|
|
12
|
+
* `stickyScroll`/`stickyStart: "bottom"` for AC8 (don't yank the view when
|
|
13
|
+
* the user has scrolled up to read history) instead of hand-rolling
|
|
14
|
+
* scroll-position math.
|
|
15
|
+
*/
|
|
16
|
+
export class ChatView {
|
|
17
|
+
readonly node: BoxRenderable;
|
|
18
|
+
readonly statusBar: StatusBar;
|
|
19
|
+
readonly roster: RosterSidebar;
|
|
20
|
+
private readonly scroll: ScrollBoxRenderable;
|
|
21
|
+
private readonly ctx: RenderContext;
|
|
22
|
+
private rosterById = new Map<string, RosterEntry>();
|
|
23
|
+
|
|
24
|
+
constructor(ctx: RenderContext, options: { width: number; height: number; onSelectAgent?: (agent: RosterEntry) => void }) {
|
|
25
|
+
this.ctx = ctx;
|
|
26
|
+
this.node = new BoxRenderable(ctx, { width: options.width, height: options.height, flexDirection: "column" });
|
|
27
|
+
this.statusBar = new StatusBar(ctx);
|
|
28
|
+
this.node.add(this.statusBar.node);
|
|
29
|
+
|
|
30
|
+
const body = new BoxRenderable(ctx, { flexDirection: "row", flexGrow: 1 });
|
|
31
|
+
this.node.add(body);
|
|
32
|
+
|
|
33
|
+
this.roster = new RosterSidebar(ctx, { width: 24, onSelect: options.onSelectAgent });
|
|
34
|
+
body.add(this.roster.node);
|
|
35
|
+
|
|
36
|
+
this.scroll = new ScrollBoxRenderable(ctx, { flexGrow: 1, stickyScroll: true, stickyStart: "bottom" });
|
|
37
|
+
body.add(this.scroll);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
setConnectionStatus(status: ConnectionStatus): void {
|
|
41
|
+
this.statusBar.setConnectionStatus(status);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
setGoalContract(goal: GoalContract): void {
|
|
45
|
+
this.statusBar.setGoalContract(goal);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
setRoster(roster: RosterEntry[]): void {
|
|
49
|
+
this.rosterById = new Map(roster.map((agent) => [agent.id, agent]));
|
|
50
|
+
this.roster.setRoster(roster);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
appendMessages(messages: MessageEnvelope[]): void {
|
|
54
|
+
for (const message of messages) {
|
|
55
|
+
const fromName = this.rosterById.get(message.from)?.name ?? message.from;
|
|
56
|
+
this.scroll.add(createMessageRow(this.ctx, message, fromName));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
export interface InitOptions {
|
|
5
|
+
cwd: string;
|
|
6
|
+
bundledSkillPath: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface InitResult {
|
|
10
|
+
/** false when .roomyx/rooms/registry.json already existed and was left untouched. */
|
|
11
|
+
created: boolean;
|
|
12
|
+
roomyxDir: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEFAULT_CONFIG = {
|
|
16
|
+
schemaVersion: 1,
|
|
17
|
+
defaultPort: 4319,
|
|
18
|
+
roomLogDir: ".roomyx/rooms/logs",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Creates `.roomyx/` in `cwd`: config.json, an empty room registry, and a
|
|
23
|
+
* staged copy of the bundled skill. Never overwrites an existing, non-empty
|
|
24
|
+
* registry (D-01 in decisions.md: explicit, never-clobbering init).
|
|
25
|
+
*/
|
|
26
|
+
export function init(options: InitOptions): InitResult {
|
|
27
|
+
const roomyxDir = join(options.cwd, ".roomyx");
|
|
28
|
+
const registryPath = join(roomyxDir, "rooms", "registry.json");
|
|
29
|
+
const configPath = join(roomyxDir, "config.json");
|
|
30
|
+
const skillDir = join(roomyxDir, "skills", "startup-room");
|
|
31
|
+
|
|
32
|
+
mkdirSync(join(roomyxDir, "rooms"), { recursive: true });
|
|
33
|
+
mkdirSync(skillDir, { recursive: true });
|
|
34
|
+
|
|
35
|
+
const registryAlreadyHasRooms =
|
|
36
|
+
existsSync(registryPath) && (JSON.parse(readFileSync(registryPath, "utf8")).rooms?.length ?? 0) > 0;
|
|
37
|
+
|
|
38
|
+
if (!existsSync(configPath)) {
|
|
39
|
+
writeFileSync(configPath, JSON.stringify(DEFAULT_CONFIG, null, 2));
|
|
40
|
+
}
|
|
41
|
+
if (!existsSync(registryPath)) {
|
|
42
|
+
writeFileSync(registryPath, JSON.stringify({ schemaVersion: 1, rooms: [] }, null, 2));
|
|
43
|
+
}
|
|
44
|
+
copyFileSync(options.bundledSkillPath, join(skillDir, "SKILL.md"));
|
|
45
|
+
|
|
46
|
+
return { created: !registryAlreadyHasRooms, roomyxDir };
|
|
47
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { existsSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
4
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
|
+
|
|
6
|
+
const registryEntrySchema = z.object({
|
|
7
|
+
id: z.string().min(1),
|
|
8
|
+
port: z.number().int().min(0),
|
|
9
|
+
logPath: z.string().min(1),
|
|
10
|
+
pid: z.number().int(),
|
|
11
|
+
startedAt: z.string().min(1),
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const registryFileSchema = z.object({
|
|
15
|
+
schemaVersion: z.literal(1),
|
|
16
|
+
rooms: z.array(registryEntrySchema),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export type RoomRegistryEntry = z.infer<typeof registryEntrySchema>;
|
|
20
|
+
|
|
21
|
+
/** A lock older than this could only mean its holder crashed — the critical
|
|
22
|
+
* sections here are a few synchronous file ops, never anywhere close to 30s. */
|
|
23
|
+
const STALE_LOCK_MS = 30_000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Blocks (synchronously) until an exclusive lockfile can be created, runs
|
|
27
|
+
* `fn`, then always releases the lock. Reproduced concretely by an
|
|
28
|
+
* independent review: without this, concurrent `roomyx serve` processes
|
|
29
|
+
* lose registrations (read-modify-write race) and can crash each other with
|
|
30
|
+
* a JSON parse error on a torn read of a non-atomic write. `Atomics.wait` is
|
|
31
|
+
* used for the retry backoff because registerRoom/deregisterRoom are
|
|
32
|
+
* synchronous APIs (matching how cli.ts already calls them) — an async lock
|
|
33
|
+
* would leak into every caller's signature for no benefit here.
|
|
34
|
+
*
|
|
35
|
+
* A process that crashes mid-critical-section leaves the lockfile behind
|
|
36
|
+
* forever — a second independent review caught that this would otherwise
|
|
37
|
+
* block the registry permanently for every future caller, not just the one
|
|
38
|
+
* racing the crash. A lock older than STALE_LOCK_MS is reclaimed instead of
|
|
39
|
+
* waited on.
|
|
40
|
+
*
|
|
41
|
+
* The lockfile's content is an owner token (pid + random), not empty: a
|
|
42
|
+
* third review caught that reclaiming by mtime alone is not enough — if the
|
|
43
|
+
* original holder was merely slow (not crashed) and finishes after being
|
|
44
|
+
* reclaimed, its unconditional release would delete whichever *other*
|
|
45
|
+
* process's lock now legitimately occupies that path. Release only unlinks
|
|
46
|
+
* when the file still holds the token this call itself wrote.
|
|
47
|
+
*/
|
|
48
|
+
/** Exported narrowly so the ownership check can be unit-tested directly,
|
|
49
|
+
* without needing to choreograph real inter-process timing to hit it. */
|
|
50
|
+
export function releaseLockIfOwned(lockPath: string, token: string): void {
|
|
51
|
+
try {
|
|
52
|
+
if (readFileSync(lockPath, "utf8") === token) {
|
|
53
|
+
unlinkSync(lockPath);
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
// Already gone, or unreadable — nothing more to do.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function withLock<T>(registryPath: string, fn: () => T): T {
|
|
61
|
+
const lockPath = `${registryPath}.lock`;
|
|
62
|
+
const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
63
|
+
const deadline = Date.now() + 5000;
|
|
64
|
+
for (;;) {
|
|
65
|
+
try {
|
|
66
|
+
writeFileSync(lockPath, token, { flag: "wx" });
|
|
67
|
+
break;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
70
|
+
try {
|
|
71
|
+
if (Date.now() - statSync(lockPath).mtimeMs > STALE_LOCK_MS) {
|
|
72
|
+
try {
|
|
73
|
+
unlinkSync(lockPath);
|
|
74
|
+
} catch {
|
|
75
|
+
// Another process already reclaimed it first; just retry.
|
|
76
|
+
}
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
} catch {
|
|
80
|
+
// Lock vanished between the failed open and this stat; retry.
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (Date.now() > deadline) {
|
|
84
|
+
throw new Error(`Timed out waiting for the room registry lock at ${lockPath}`);
|
|
85
|
+
}
|
|
86
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
return fn();
|
|
91
|
+
} finally {
|
|
92
|
+
releaseLockIfOwned(lockPath, token);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function readRegistryUnlocked(path: string): { schemaVersion: 1; rooms: RoomRegistryEntry[] } {
|
|
97
|
+
if (!existsSync(path)) {
|
|
98
|
+
return { schemaVersion: 1, rooms: [] };
|
|
99
|
+
}
|
|
100
|
+
const parsed = registryFileSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
|
|
101
|
+
if (!parsed.success) {
|
|
102
|
+
throw new Error(`Invalid room registry at ${path}: ${parsed.error.message}`);
|
|
103
|
+
}
|
|
104
|
+
return parsed.data;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Write-to-temp-then-rename: a reader never observes a partially-written file. */
|
|
108
|
+
function writeRegistryUnlocked(path: string, rooms: RoomRegistryEntry[]): void {
|
|
109
|
+
const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
110
|
+
writeFileSync(tmpPath, JSON.stringify({ schemaVersion: 1, rooms }, null, 2));
|
|
111
|
+
renameSync(tmpPath, path);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function generateRoomId(): string {
|
|
115
|
+
return `r-${Math.random().toString(36).slice(2, 8)}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Adds a new room to the registry, generating its id. */
|
|
119
|
+
export function registerRoom(
|
|
120
|
+
registryPath: string,
|
|
121
|
+
info: { port: number; logPath: string; pid: number },
|
|
122
|
+
): RoomRegistryEntry {
|
|
123
|
+
return withLock(registryPath, () => {
|
|
124
|
+
const registry = readRegistryUnlocked(registryPath);
|
|
125
|
+
const entry: RoomRegistryEntry = {
|
|
126
|
+
id: generateRoomId(),
|
|
127
|
+
port: info.port,
|
|
128
|
+
logPath: info.logPath,
|
|
129
|
+
pid: info.pid,
|
|
130
|
+
startedAt: new Date().toISOString(),
|
|
131
|
+
};
|
|
132
|
+
writeRegistryUnlocked(registryPath, [...registry.rooms, entry]);
|
|
133
|
+
return entry;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Removes one room by id. No-op if the id isn't present. */
|
|
138
|
+
export function deregisterRoom(registryPath: string, id: string): void {
|
|
139
|
+
withLock(registryPath, () => {
|
|
140
|
+
const registry = readRegistryUnlocked(registryPath);
|
|
141
|
+
writeRegistryUnlocked(
|
|
142
|
+
registryPath,
|
|
143
|
+
registry.rooms.filter((r) => r.id !== id),
|
|
144
|
+
);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** All registered rooms, live or not. Empty array if the file doesn't exist. */
|
|
149
|
+
export function listRooms(registryPath: string): RoomRegistryEntry[] {
|
|
150
|
+
return withLock(registryPath, () => readRegistryUnlocked(registryPath).rooms);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Rooms confirmed live by an actual MCP round-trip (not just "the registry
|
|
155
|
+
* says so" — a crashed process leaves a registry entry a dead port never
|
|
156
|
+
* answers). Dead entries are pruned from the persisted file, not just
|
|
157
|
+
* omitted from the returned list.
|
|
158
|
+
*/
|
|
159
|
+
export async function listLiveRooms(registryPath: string): Promise<RoomRegistryEntry[]> {
|
|
160
|
+
const rooms = withLock(registryPath, () => readRegistryUnlocked(registryPath).rooms);
|
|
161
|
+
const checks = await Promise.all(
|
|
162
|
+
rooms.map(async (room) => {
|
|
163
|
+
const alive = await isRoomLive(room);
|
|
164
|
+
return { room, alive };
|
|
165
|
+
}),
|
|
166
|
+
);
|
|
167
|
+
const live = checks.filter((c) => c.alive).map((c) => c.room);
|
|
168
|
+
if (live.length !== rooms.length) {
|
|
169
|
+
// Re-take the lock for the write: another process may have registered or
|
|
170
|
+
// deregistered a room while the (network) liveness checks above were in
|
|
171
|
+
// flight. Re-read under the lock and only remove entries this pass
|
|
172
|
+
// actually confirmed dead, instead of blindly overwriting with the
|
|
173
|
+
// stale `live` list computed before the re-read.
|
|
174
|
+
withLock(registryPath, () => {
|
|
175
|
+
const current = readRegistryUnlocked(registryPath).rooms;
|
|
176
|
+
const deadIds = new Set(checks.filter((c) => !c.alive).map((c) => c.room.id));
|
|
177
|
+
writeRegistryUnlocked(
|
|
178
|
+
registryPath,
|
|
179
|
+
current.filter((r) => !deadIds.has(r.id)),
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return live;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function isRoomLive(room: RoomRegistryEntry, timeoutMs = 500): Promise<boolean> {
|
|
187
|
+
const client = new Client({ name: "roomyx-registry-check", version: "0.1.0" });
|
|
188
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
189
|
+
setTimeout(() => reject(new Error("liveness check timed out")), timeoutMs);
|
|
190
|
+
});
|
|
191
|
+
try {
|
|
192
|
+
await Promise.race([
|
|
193
|
+
client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${room.port}/mcp`))),
|
|
194
|
+
timeout,
|
|
195
|
+
]);
|
|
196
|
+
return true;
|
|
197
|
+
} catch {
|
|
198
|
+
return false;
|
|
199
|
+
} finally {
|
|
200
|
+
await client.close().catch(() => undefined);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { listLiveRooms, type RoomRegistryEntry } from "./registry";
|
|
2
|
+
|
|
3
|
+
export interface ResolveConnectionOptions {
|
|
4
|
+
connect?: string;
|
|
5
|
+
room?: string;
|
|
6
|
+
registryPath: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type ResolveConnectionResult =
|
|
10
|
+
| { ok: true; url: string }
|
|
11
|
+
| { ok: false; reason: "no-rooms" | "multiple-rooms" | "room-not-found"; candidates?: RoomRegistryEntry[] };
|
|
12
|
+
|
|
13
|
+
function urlFor(room: RoomRegistryEntry): string {
|
|
14
|
+
return `http://127.0.0.1:${room.port}/mcp`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Decides which roomyx server `roomyx client` should connect to.
|
|
19
|
+
* `--connect` always wins outright (explicit URL, registry not consulted).
|
|
20
|
+
* `--room <id>` looks up that specific room among the LIVE ones (a
|
|
21
|
+
* registered-but-dead id is treated the same as unknown, not a stale
|
|
22
|
+
* false-positive). No args: auto-attach only when exactly one room is live.
|
|
23
|
+
*/
|
|
24
|
+
export async function resolveConnectionUrl(options: ResolveConnectionOptions): Promise<ResolveConnectionResult> {
|
|
25
|
+
if (options.connect) {
|
|
26
|
+
return { ok: true, url: options.connect };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const live = await listLiveRooms(options.registryPath);
|
|
30
|
+
|
|
31
|
+
if (options.room) {
|
|
32
|
+
const match = live.find((r) => r.id === options.room);
|
|
33
|
+
return match ? { ok: true, url: urlFor(match) } : { ok: false, reason: "room-not-found" };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (live.length === 0) return { ok: false, reason: "no-rooms" };
|
|
37
|
+
if (live.length > 1) return { ok: false, reason: "multiple-rooms", candidates: live };
|
|
38
|
+
return { ok: true, url: urlFor(live[0] as RoomRegistryEntry) };
|
|
39
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { copyFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
export interface SyncOptions {
|
|
5
|
+
bundledSkillPath: string;
|
|
6
|
+
targetPath: string;
|
|
7
|
+
/** .roomyx/config.json — stores the "last synced" hash per target path. */
|
|
8
|
+
configPath: string;
|
|
9
|
+
dryRun?: boolean;
|
|
10
|
+
/** Required to proceed when the target has independent changes since the last sync. */
|
|
11
|
+
yes?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SyncResult {
|
|
15
|
+
wouldWrite: boolean;
|
|
16
|
+
written: boolean;
|
|
17
|
+
backedUpTo: string | null;
|
|
18
|
+
warnings: string[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function hashOf(content: string): string {
|
|
22
|
+
return createHash("sha256").update(content).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface SyncConfig {
|
|
26
|
+
schemaVersion: number;
|
|
27
|
+
lastSyncedHashes?: Record<string, string>;
|
|
28
|
+
[key: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function readConfig(configPath: string): SyncConfig {
|
|
32
|
+
return JSON.parse(readFileSync(configPath, "utf8")) as SyncConfig;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function writeConfig(configPath: string, config: SyncConfig): void {
|
|
36
|
+
writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Diffs the bundled skill against a target path, backs up before
|
|
41
|
+
* overwriting, and refuses to write without `yes: true` when the target has
|
|
42
|
+
* been hand-edited since the last recorded sync (docs/requirements/
|
|
43
|
+
* roomyx-installer/decisions.md D-02 — never silently discard hand edits).
|
|
44
|
+
*/
|
|
45
|
+
export function syncSkill(options: SyncOptions): SyncResult {
|
|
46
|
+
const bundledContent = readFileSync(options.bundledSkillPath, "utf8");
|
|
47
|
+
const config = readConfig(options.configPath);
|
|
48
|
+
const lastSyncedHash = config.lastSyncedHashes?.[options.targetPath];
|
|
49
|
+
|
|
50
|
+
const targetExists = existsSync(options.targetPath);
|
|
51
|
+
const targetContent = targetExists ? readFileSync(options.targetPath, "utf8") : null;
|
|
52
|
+
// Two distinct "don't touch this blindly" cases, both requiring --yes:
|
|
53
|
+
// (a) we synced before and the target has since been hand-edited, or
|
|
54
|
+
// (b) the target already existed with content we have no record of ever
|
|
55
|
+
// having written — a bug found by an independent review: treating "no
|
|
56
|
+
// recorded hash" as "safe to overwrite" silently clobbered pre-existing,
|
|
57
|
+
// never-bundled content on the very first sync to a given target.
|
|
58
|
+
const neverSyncedButPreExisting = targetExists && lastSyncedHash === undefined;
|
|
59
|
+
const handEditedSinceLastSync =
|
|
60
|
+
targetExists && lastSyncedHash !== undefined && hashOf(targetContent as string) !== lastSyncedHash;
|
|
61
|
+
const targetHasIndependentChanges = neverSyncedButPreExisting || handEditedSinceLastSync;
|
|
62
|
+
|
|
63
|
+
const warnings: string[] = [];
|
|
64
|
+
if (neverSyncedButPreExisting) {
|
|
65
|
+
warnings.push(
|
|
66
|
+
`${options.targetPath} already exists but roomyx has never synced it before — refusing to overwrite unrecorded content without --yes.`,
|
|
67
|
+
);
|
|
68
|
+
} else if (handEditedSinceLastSync) {
|
|
69
|
+
warnings.push(
|
|
70
|
+
`${options.targetPath} has changed since the last sync (hand-edited?) — refusing to overwrite without --yes.`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (options.dryRun) {
|
|
75
|
+
return { wouldWrite: true, written: false, backedUpTo: null, warnings };
|
|
76
|
+
}
|
|
77
|
+
if (targetHasIndependentChanges && !options.yes) {
|
|
78
|
+
return { wouldWrite: true, written: false, backedUpTo: null, warnings };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
let backedUpTo: string | null = null;
|
|
82
|
+
if (targetExists) {
|
|
83
|
+
backedUpTo = `${options.targetPath}.bak-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
|
84
|
+
copyFileSync(options.targetPath, backedUpTo);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
writeFileSync(options.targetPath, bundledContent);
|
|
88
|
+
writeConfig(options.configPath, {
|
|
89
|
+
...config,
|
|
90
|
+
lastSyncedHashes: { ...config.lastSyncedHashes, [options.targetPath]: hashOf(bundledContent) },
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
return { wouldWrite: true, written: true, backedUpTo, warnings };
|
|
94
|
+
}
|
package/src/log/store.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { AgentDetail, MessageEnvelope, RoomState, RosterEntry } from "./types";
|
|
4
|
+
|
|
5
|
+
const rosterEntrySchema = z.object({ id: z.string(), name: z.string() });
|
|
6
|
+
|
|
7
|
+
const goalContractSchema = z.object({
|
|
8
|
+
version: z.number().int().min(1),
|
|
9
|
+
updated_in_round: z.number().int().min(0).optional(),
|
|
10
|
+
updated_by: z.literal("owner").optional(),
|
|
11
|
+
goal_statement: z.string(),
|
|
12
|
+
criteria: z.string(),
|
|
13
|
+
threshold: z.object({
|
|
14
|
+
fail_below: z.number(),
|
|
15
|
+
pass_at_or_above: z.number(),
|
|
16
|
+
}),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const messageKindSchema = z.enum([
|
|
20
|
+
"pitch",
|
|
21
|
+
"question",
|
|
22
|
+
"challenge",
|
|
23
|
+
"answer",
|
|
24
|
+
"vote",
|
|
25
|
+
"status",
|
|
26
|
+
"research",
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
const stateLineSchema = z.object({
|
|
30
|
+
type: z.literal("state"),
|
|
31
|
+
goal_contract: goalContractSchema,
|
|
32
|
+
roster: z.array(rosterEntrySchema),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const messageLineSchema = z.object({
|
|
36
|
+
type: z.literal("message"),
|
|
37
|
+
seq: z.number().int().min(1),
|
|
38
|
+
from: z.string().min(1),
|
|
39
|
+
in_reply_to: z.number().int().min(1).optional(),
|
|
40
|
+
kind: messageKindSchema.optional(),
|
|
41
|
+
body: z.string(),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Reads the room log (see roomyx/README.md for the on-disk format) without
|
|
46
|
+
* ever writing to it. The first line is the state header; every following
|
|
47
|
+
* line is a message.
|
|
48
|
+
*/
|
|
49
|
+
export function loadRoomLog(path: string): { state: RoomState; messages: MessageEnvelope[] } {
|
|
50
|
+
const raw = readFileSync(path, "utf8");
|
|
51
|
+
const lines = raw.split("\n").filter((line) => line.trim().length > 0);
|
|
52
|
+
|
|
53
|
+
if (lines.length === 0) {
|
|
54
|
+
throw new Error(`Room log at ${path} is empty; expected a state header line.`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const [headerLine, ...rest] = lines as [string, ...string[]];
|
|
58
|
+
const headerResult = stateLineSchema.safeParse(JSON.parse(headerLine));
|
|
59
|
+
if (!headerResult.success) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Room log at ${path} must start with a valid "state" line: ${headerResult.error.message}`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const state: RoomState = {
|
|
66
|
+
goal_contract: headerResult.data.goal_contract,
|
|
67
|
+
roster: headerResult.data.roster,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const messages: MessageEnvelope[] = rest.map((line, index) => {
|
|
71
|
+
const result = messageLineSchema.safeParse(JSON.parse(line));
|
|
72
|
+
if (!result.success) {
|
|
73
|
+
// +2: 1-indexed lines, plus the header line already consumed.
|
|
74
|
+
throw new Error(`Invalid "message" line ${index + 2} in ${path}: ${result.error.message}`);
|
|
75
|
+
}
|
|
76
|
+
const { type: _type, ...envelope } = result.data;
|
|
77
|
+
return envelope;
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
return { state, messages };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Messages with seq strictly greater than sinceSeq, in log order. */
|
|
84
|
+
export function getTranscript(messages: MessageEnvelope[], sinceSeq: number): MessageEnvelope[] {
|
|
85
|
+
return messages.filter((m) => m.seq > sinceSeq);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** A single participant's messages and last-seen seq, or an explicit not-found result. */
|
|
89
|
+
export function getAgentDetail(
|
|
90
|
+
messages: MessageEnvelope[],
|
|
91
|
+
roster: RosterEntry[],
|
|
92
|
+
agentId: string,
|
|
93
|
+
): AgentDetail {
|
|
94
|
+
const agent = roster.find((r) => r.id === agentId);
|
|
95
|
+
if (!agent) {
|
|
96
|
+
return { found: false };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const own = messages.filter((m) => m.from === agentId);
|
|
100
|
+
const lastSeenSeq = own.length > 0 ? Math.max(...own.map((m) => m.seq)) : 0;
|
|
101
|
+
return { found: true, agent, messages: own, lastSeenSeq };
|
|
102
|
+
}
|
package/src/log/types.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface MessageEnvelope {
|
|
2
|
+
seq: number;
|
|
3
|
+
from: string;
|
|
4
|
+
in_reply_to?: number;
|
|
5
|
+
kind?: "pitch" | "question" | "challenge" | "answer" | "vote" | "status" | "research";
|
|
6
|
+
body: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface RosterEntry {
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface GoalContractThreshold {
|
|
15
|
+
fail_below: number;
|
|
16
|
+
pass_at_or_above: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface GoalContract {
|
|
20
|
+
version: number;
|
|
21
|
+
updated_in_round?: number;
|
|
22
|
+
updated_by?: "owner";
|
|
23
|
+
goal_statement: string;
|
|
24
|
+
criteria: string;
|
|
25
|
+
threshold: GoalContractThreshold;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RoomState {
|
|
29
|
+
goal_contract: GoalContract;
|
|
30
|
+
roster: RosterEntry[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type AgentDetail =
|
|
34
|
+
| { found: true; agent: RosterEntry; messages: MessageEnvelope[]; lastSeenSeq: number }
|
|
35
|
+
| { found: false };
|