@alexsun-top/opencode-chat-room 0.2.1 → 0.2.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/src/watch.ts ADDED
@@ -0,0 +1,355 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { realpathSync } from "node:fs";
3
+ import { appendFile, chmod, link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { spawn } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { backgroundAtCompatibleRegisteredHost, discoverCompatibleRegisteredHost } from "./background";
9
+ import { receiverOwnerID } from "./receiver-owner";
10
+ import { claimWatcher, closeReceiverState, releaseWatcherClaim, receiverStateDirectory, watcherProcessMayExist } from "./receiver-state";
11
+ import { databasePath, loadRegistry } from "./store";
12
+ import { request, type CenterOpts } from "./center-client";
13
+ import { assertDeliveryLease } from "./session-delivery";
14
+ import type { QueueTransport } from "./queue-transport";
15
+ import { pollOwnedSessions } from "./v2-receiver";
16
+ import { pollKnownSessions } from "../plugin";
17
+
18
+ type WatchRecord = { phase: "starting" | "running"; token: string; nonce: string; instanceID: string; pid: number; port?: number; createdAt?: number };
19
+ function canonicalPath(value: string): string {
20
+ const suffix: string[] = [];
21
+ let current = path.resolve(value);
22
+ for (;;) {
23
+ try { return path.join(realpathSync(current), ...suffix); }
24
+ catch (error) {
25
+ const e = error as NodeJS.ErrnoException;
26
+ if (e.code !== "ENOENT" && e.code !== "ENOTDIR") return path.resolve(value);
27
+ const parent = path.dirname(current);
28
+ if (parent === current) return path.resolve(value);
29
+ suffix.unshift(path.basename(current));
30
+ current = parent;
31
+ }
32
+ }
33
+ }
34
+ const profile = () => {
35
+ const center = process.env.CHAT_ROOM_SERVER_URL ?? "";
36
+ const home = process.env.HOME || os.homedir();
37
+ let target = `standalone:${canonicalPath(databasePath())}`;
38
+ if (center) { try { const url = new URL(center); target = `${url.origin}${url.pathname}`; } catch { target = "invalid-center"; } }
39
+ return createHash("sha256").update(JSON.stringify([os.userInfo().username, home, target])).digest("hex").slice(0, 32);
40
+ };
41
+ const paths = () => {
42
+ const directory = receiverStateDirectory();
43
+ const id = profile();
44
+ return { directory, state: path.join(directory, `watch-${id}.json`), log: path.join(directory, `watch-${id}.log`) };
45
+ };
46
+ export function watcherStatePath(): string { return paths().state; }
47
+ async function privateDirectory(): Promise<void> {
48
+ const { directory } = paths();
49
+ await mkdir(directory, { recursive: true, mode: 0o700 });
50
+ await chmod(directory, 0o700);
51
+ }
52
+ async function logEvent(event: string): Promise<void> {
53
+ try {
54
+ const { log } = paths();
55
+ await appendFile(log, `${new Date().toISOString()} ${event}\n`, { encoding: "utf8", mode: 0o600 });
56
+ await chmod(log, 0o600);
57
+ } catch { /* Logging must not stop message delivery. */ }
58
+ }
59
+ async function readRecord(): Promise<WatchRecord | undefined> {
60
+ try {
61
+ const value = JSON.parse(await readFile(paths().state, "utf8")) as WatchRecord;
62
+ if (!value || !["starting", "running"].includes(value.phase) || typeof value.token !== "string" ||
63
+ typeof value.nonce !== "string" || typeof value.instanceID !== "string" || !Number.isInteger(value.pid) || value.pid! < 1 ||
64
+ (value.phase === "running" && (!Number.isInteger(value.port) || value.port! < 1 || value.port! > 65535))) return undefined;
65
+ return value;
66
+ } catch { return undefined; }
67
+ }
68
+ async function stateFileExists(): Promise<boolean> {
69
+ try { await readFile(paths().state); return true; }
70
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
71
+ }
72
+ async function saveRecord(record: WatchRecord, exclusive = false, beforePublish?: () => Promise<void>): Promise<void> {
73
+ await privateDirectory();
74
+ const temp = `${paths().state}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
75
+ try {
76
+ await writeFile(temp, JSON.stringify(record), { flag: "wx", mode: 0o600 });
77
+ await beforePublish?.();
78
+ if (exclusive) await link(temp, paths().state); else await rename(temp, paths().state);
79
+ await chmod(paths().state, 0o600);
80
+ } finally { await unlink(temp).catch(() => {}); }
81
+ }
82
+ async function removeRecord(token: string, nonce: string): Promise<void> {
83
+ const current = await readRecord();
84
+ if (current?.token === token && current.nonce === nonce) await unlink(paths().state).catch(() => {});
85
+ }
86
+ async function reserveWatcher(record: WatchRecord, beforePublish?: () => Promise<void>): Promise<"claimed" | "existing" | "invalid"> {
87
+ const previous = await readRecord();
88
+ if (!previous && await stateFileExists()) return "invalid";
89
+ if (previous && watcherProcessMayExist(previous.pid)) return "existing";
90
+ if (!claimWatcher(profile(), record.instanceID, record.pid)) return "existing";
91
+ if (previous) {
92
+ const current = await readRecord();
93
+ if (current?.token !== previous.token || current.nonce !== previous.nonce) {
94
+ releaseWatcherClaim(profile(), record.instanceID);
95
+ return "existing";
96
+ }
97
+ await unlink(paths().state).catch(() => {});
98
+ }
99
+ try { await saveRecord(record, true, beforePublish); }
100
+ catch {
101
+ releaseWatcherClaim(profile(), record.instanceID);
102
+ return await stateFileExists() ? "existing" : "invalid";
103
+ }
104
+ return "claimed";
105
+ }
106
+ function authorized(request: Request, token: string): boolean {
107
+ const supplied = request.headers.get("Authorization") ?? "";
108
+ const expected = `Bearer ${token}`;
109
+ const a = Buffer.from(supplied);
110
+ const b = Buffer.from(expected);
111
+ return a.length === b.length && timingSafeEqual(a, b);
112
+ }
113
+
114
+ type Host = NonNullable<Awaited<ReturnType<typeof discoverCompatibleRegisteredHost>>>;
115
+ export type WatchSweepDeps = {
116
+ discover(): Promise<Host | undefined>;
117
+ owner(host: Host): Promise<string | undefined>;
118
+ memberships(ownerID: string): Promise<Set<string>>;
119
+ poll(ids: ReadonlySet<string>, host: Host, ownerID: string): Promise<void>;
120
+ };
121
+ export async function watcherSweep(deps: WatchSweepDeps = defaultSweepDeps()): Promise<boolean> {
122
+ const host = await deps.discover().catch(() => undefined);
123
+ if (!host) return false;
124
+ const ownerID = await deps.owner(host).catch(() => undefined);
125
+ if (!ownerID) return false;
126
+ const ids = await deps.memberships(ownerID).catch(() => undefined);
127
+ if (!ids?.size) return true;
128
+ await deps.poll(ids, host, ownerID);
129
+ return true;
130
+ }
131
+
132
+ function defaultSweepDeps(): WatchSweepDeps {
133
+ const center: CenterOpts = {
134
+ center: process.env.CHAT_ROOM_SERVER_URL ?? "",
135
+ token: process.env.CHAT_ROOM_SERVER_TOKEN ?? "",
136
+ };
137
+ return {
138
+ discover: discoverCompatibleRegisteredHost,
139
+ owner: (host) => receiverOwnerID(host.origin),
140
+ memberships: async (ownerID) => {
141
+ if (center.center) {
142
+ const result = await request(center, `/receiver/memberships?ownerID=${encodeURIComponent(ownerID)}`, "GET") as { sessionIDs?: string[] };
143
+ return new Set(result.sessionIDs ?? []);
144
+ }
145
+ const registry = await loadRegistry();
146
+ return new Set(Object.values(registry).flatMap((entries) => Object.entries(entries)
147
+ .filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id)));
148
+ },
149
+ poll: (ids, host, ownerID) => {
150
+ const transport: QueueTransport = {
151
+ protocol: "v2", receiverOwnerID: ownerID, mentionOnlySessions: ids,
152
+ backgroundSession: (id) => backgroundAtCompatibleRegisteredHost(id, host),
153
+ promptQueue: async (sessionID, id, text, delivery) => {
154
+ const current = await discoverCompatibleRegisteredHost();
155
+ if (!current || current.origin !== host.origin || current.pid !== host.pid || current.version !== host.version) {
156
+ throw Object.assign(new Error("registered OpenCode service changed"), { status: 409 });
157
+ }
158
+ assertDeliveryLease();
159
+ return current.client.session.prompt({ sessionID, id, text, delivery, resume: true }, { signal: AbortSignal.timeout(1500) });
160
+ },
161
+ };
162
+ return pollOwnedSessions(ids, (owned) => pollKnownSessions(owned, transport, center));
163
+ },
164
+ };
165
+ }
166
+
167
+ async function control(record: WatchRecord, stop = false): Promise<boolean> {
168
+ if (record.phase !== "running" || !record.port || !watcherProcessMayExist(record.pid)) return false;
169
+ try {
170
+ const base = `http://127.0.0.1:${record.port}`;
171
+ const headers = { Authorization: `Bearer ${record.token}` };
172
+ const response = await fetch(`${base}/status`, {
173
+ headers,
174
+ signal: AbortSignal.timeout(1500),
175
+ });
176
+ const status = await response.json().catch(() => undefined);
177
+ if (!response.ok || !sameController(status, record, "running")) return false;
178
+ if (!stop) return true;
179
+ const stopped = await fetch(`${base}/stop`, {
180
+ method: "POST",
181
+ headers: { ...headers, "x-watcher-instance": record.instanceID, "x-watcher-nonce": record.nonce, "x-watcher-pid": String(record.pid) },
182
+ signal: AbortSignal.timeout(1500),
183
+ });
184
+ const acknowledgement = await stopped.json().catch(() => undefined);
185
+ return stopped.status === 202 && sameController(acknowledgement, record, "stopping");
186
+ } catch { return false; }
187
+ }
188
+
189
+ function sameController(value: unknown, record: WatchRecord, status: string): boolean {
190
+ if (!value || typeof value !== "object") return false;
191
+ const body = value as Record<string, unknown>;
192
+ return body.status === status && body.pid === record.pid &&
193
+ body.instanceID === record.instanceID && body.nonce === record.nonce;
194
+ }
195
+
196
+ export async function watchStatus(): Promise<"running" | "stopped" | "unavailable" | "starting"> {
197
+ const record = await readRecord();
198
+ if (!record) {
199
+ try { await readFile(paths().state); return "unavailable"; }
200
+ catch { return "stopped"; }
201
+ }
202
+ if (record.phase === "starting") return watcherProcessMayExist(record.pid) && Date.now() - (record.createdAt ?? 0) < 30_000 ? "starting" : "unavailable";
203
+ return await control(record) ? "running" : "unavailable";
204
+ }
205
+
206
+ export async function startWatcher(beforePublish?: () => Promise<void>): Promise<string> {
207
+ await privateDirectory();
208
+ const own: WatchRecord = { phase: "starting", token: randomBytes(32).toString("base64url"), nonce: randomBytes(16).toString("hex"), instanceID: randomBytes(16).toString("hex"), pid: process.pid, createdAt: Date.now() };
209
+ const reservation = await reserveWatcher(own, beforePublish);
210
+ if (reservation !== "claimed") {
211
+ if (reservation === "invalid") throw new Error("watcher state is unreadable; remove the private stale state file manually");
212
+ const existing = await readRecord();
213
+ if (existing?.phase === "running") {
214
+ if (await control(existing)) return "watcher already running";
215
+ throw new Error("watcher control endpoint is unavailable; no process was signaled");
216
+ }
217
+ const deadline = Date.now() + 20_000;
218
+ while (Date.now() < deadline) {
219
+ const current = await readRecord();
220
+ if (current?.phase === "running" && await control(current)) return "watcher already running";
221
+ await new Promise((resolve) => setTimeout(resolve, 100));
222
+ }
223
+ throw new Error("watcher state exists or is starting; no process was signaled");
224
+ }
225
+ const cli = fileURLToPath(new URL("../cli.ts", import.meta.url));
226
+ let childError: Error | undefined;
227
+ const child = spawn(process.execPath, [path.resolve(cli), "watch", "run"], {
228
+ detached: true, stdio: "ignore",
229
+ env: { ...process.env, CHAT_ROOM_WATCH_CONTROL_TOKEN: own.token, CHAT_ROOM_WATCH_START_NONCE: own.nonce, CHAT_ROOM_WATCH_INSTANCE_ID: own.instanceID },
230
+ });
231
+ child.once("error", (error) => { childError = error; });
232
+ child.unref();
233
+ const deadline = Date.now() + 20_000;
234
+ while (Date.now() < deadline) {
235
+ if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
236
+ const record = await readRecord();
237
+ if (record?.token === own.token && record.nonce === own.nonce && record.phase === "running" && await control(record)) {
238
+ return "watcher started";
239
+ }
240
+ if (child.exitCode !== null) {
241
+ await removeRecord(own.token, own.nonce);
242
+ releaseWatcherClaim(profile(), own.instanceID);
243
+ throw new Error("watcher exited before its control endpoint became ready");
244
+ }
245
+ await new Promise((resolve) => setTimeout(resolve, 100));
246
+ }
247
+ throw new Error("watcher did not become ready; its process was not signaled");
248
+ }
249
+
250
+ export async function stopWatcher(): Promise<string> {
251
+ const record = await readRecord();
252
+ if (!record) {
253
+ try { await readFile(paths().state); }
254
+ catch { return "watcher stopped"; }
255
+ throw new Error("watcher state is unreadable; no process was signaled");
256
+ }
257
+ if (record.phase !== "running" || !await control(record, true)) {
258
+ throw new Error("watcher control endpoint is unavailable; no process was signaled");
259
+ }
260
+ const deadline = Date.now() + 10_000;
261
+ while (Date.now() < deadline) {
262
+ const current = await readRecord();
263
+ if (!current || current.nonce !== record.nonce) return "watcher stopped";
264
+ await new Promise((resolve) => setTimeout(resolve, 100));
265
+ }
266
+ throw new Error("watcher accepted stop but has not finished shutdown");
267
+ }
268
+
269
+ export async function runWatcher(): Promise<void> {
270
+ let token = process.env.CHAT_ROOM_WATCH_CONTROL_TOKEN;
271
+ let nonce = process.env.CHAT_ROOM_WATCH_START_NONCE;
272
+ let instanceID = process.env.CHAT_ROOM_WATCH_INSTANCE_ID;
273
+ const managed = typeof token === "string" && typeof nonce === "string" && typeof instanceID === "string";
274
+ let createdAt = Date.now();
275
+ if (!managed) {
276
+ token = randomBytes(32).toString("base64url");
277
+ nonce = randomBytes(16).toString("hex");
278
+ instanceID = randomBytes(16).toString("hex");
279
+ const record: WatchRecord = { phase: "starting", token, nonce, instanceID, pid: process.pid, createdAt };
280
+ if (await reserveWatcher(record) !== "claimed") throw new Error("watcher already running or stale state requires manual cleanup");
281
+ } else {
282
+ const existing = await readRecord();
283
+ if (existing?.phase !== "starting" || existing.token !== token || existing.nonce !== nonce || existing.instanceID !== instanceID) {
284
+ throw new Error(`watcher startup ownership check failed (state=${existing?.phase ?? "missing"})`);
285
+ }
286
+ if (!claimWatcher(profile(), instanceID, process.pid)) throw new Error("watcher ownership transfer failed");
287
+ createdAt = existing.createdAt ?? createdAt;
288
+ await saveRecord({ ...existing, pid: process.pid });
289
+ }
290
+ delete process.env.CHAT_ROOM_WATCH_CONTROL_TOKEN;
291
+ delete process.env.CHAT_ROOM_WATCH_START_NONCE;
292
+ delete process.env.CHAT_ROOM_WATCH_INSTANCE_ID;
293
+
294
+ let shuttingDown = false;
295
+ let interval: ReturnType<typeof setInterval> | undefined;
296
+ let activeSweep: Promise<unknown> | undefined;
297
+ let server: ReturnType<typeof Bun.serve> | undefined;
298
+ let finish!: () => void;
299
+ const done = new Promise<void>((resolve) => { finish = resolve; });
300
+ const stop = async () => {
301
+ if (shuttingDown) return;
302
+ shuttingDown = true;
303
+ if (interval) clearInterval(interval);
304
+ process.off("SIGINT", onSignal);
305
+ process.off("SIGTERM", onSignal);
306
+ await activeSweep?.catch(() => {});
307
+ await logEvent("stopped");
308
+ server?.stop(true);
309
+ await removeRecord(token!, nonce!);
310
+ try { releaseWatcherClaim(profile(), instanceID!); } catch { /* Dead process detection reclaims the row next time. */ }
311
+ closeReceiverState();
312
+ finish();
313
+ };
314
+ const onSignal = () => { void stop(); };
315
+ const controlServer = Bun.serve({
316
+ hostname: "127.0.0.1", port: 0,
317
+ fetch(request) {
318
+ const url = new URL(request.url);
319
+ if (!authorized(request, token!)) return new Response("Unauthorized", { status: 401 });
320
+ if (request.method === "GET" && url.pathname === "/status") {
321
+ return Response.json({ status: "running", pid: process.pid, instanceID, nonce });
322
+ }
323
+ if (request.method === "POST" && url.pathname === "/stop") {
324
+ if (request.headers.get("x-watcher-instance") !== instanceID ||
325
+ request.headers.get("x-watcher-nonce") !== nonce || request.headers.get("x-watcher-pid") !== String(process.pid)) {
326
+ return new Response("Watcher identity mismatch", { status: 409 });
327
+ }
328
+ setTimeout(() => { void stop(); }, 25);
329
+ return Response.json({ status: "stopping", pid: process.pid, instanceID, nonce }, { status: 202 });
330
+ }
331
+ return new Response("Not found", { status: 404 });
332
+ },
333
+ });
334
+ server = controlServer;
335
+ try {
336
+ await saveRecord({ phase: "running", token, nonce, instanceID: instanceID!, pid: process.pid, port: controlServer.port, createdAt });
337
+ } catch (error) {
338
+ controlServer.stop(true);
339
+ await removeRecord(token, nonce);
340
+ releaseWatcherClaim(profile(), instanceID!);
341
+ throw error;
342
+ }
343
+ await logEvent("started");
344
+ process.on("SIGINT", onSignal);
345
+ process.on("SIGTERM", onSignal);
346
+ const sweep = () => {
347
+ if (shuttingDown || activeSweep) return;
348
+ activeSweep = watcherSweep().catch(() => { void logEvent("poll-error"); }).finally(() => { activeSweep = undefined; });
349
+ };
350
+ interval = setInterval(sweep, 5000);
351
+ interval.unref?.();
352
+ sweep();
353
+ console.log("watcher running");
354
+ await done;
355
+ }