@alexsun-top/opencode-chat-room 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/README.md +20 -13
- package/README.zh-CN.md +18 -13
- package/cli.ts +26 -1
- package/package.json +4 -1
- package/plugin.ts +111 -135
- package/server/chat-server.ts +48 -328
- package/server/history-route.ts +25 -0
- package/server/inbox.ts +9 -0
- package/server/wake.ts +91 -0
- package/src/background.ts +67 -8
- package/src/center-client.ts +8 -2
- package/src/center-inbox.ts +93 -15
- package/src/plugin-notifications.ts +8 -2
- package/src/queue-transport.ts +6 -0
- package/src/queue.ts +17 -55
- package/src/receiver-owner.ts +37 -0
- package/src/receiver-state.ts +92 -0
- package/src/room-service.ts +2 -4
- package/src/session-delivery.ts +51 -0
- package/src/sqlite-state.ts +265 -0
- package/src/store.ts +25 -138
- package/src/v2-plugin.ts +17 -32
- package/src/v2-receiver.ts +109 -0
- package/src/watch.ts +355 -0
package/src/v2-plugin.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import type { QueueTransport } from "./center-client";
|
|
4
|
-
import { backgroundOwnSession } from "./background";
|
|
4
|
+
import { backgroundOwnSession, discoverVerifiedHost, verifyHostSession } from "./background";
|
|
5
|
+
import { receiverOwnerID } from "./receiver-owner";
|
|
6
|
+
import { attachV2Receiver } from "./v2-receiver";
|
|
5
7
|
|
|
6
|
-
type CenterOptions = { center: string; token: string; directory
|
|
8
|
+
type CenterOptions = { center: string; token: string; directory?: string };
|
|
7
9
|
export type V2Runtime = {
|
|
8
10
|
protocol: "v1" | "v2";
|
|
9
11
|
selfServerUrl: string;
|
|
@@ -18,16 +20,19 @@ export function createV2Setup(deps: {
|
|
|
18
20
|
execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string): Promise<string>;
|
|
19
21
|
observe(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
20
22
|
poll(sessions: ReadonlySet<string>, transport: QueueTransport, center: CenterOptions): Promise<void>;
|
|
21
|
-
wake(center: CenterOptions, transport: QueueTransport, sessions: ReadonlySet<string>): Promise<void>;
|
|
22
|
-
central: boolean;
|
|
23
23
|
}) {
|
|
24
24
|
return async (context: Plugin.Context): Promise<() => Promise<void>> => {
|
|
25
25
|
const sessions = new Set<string>();
|
|
26
26
|
const directory = context.location.directory;
|
|
27
|
+
const version = context.app?.version ?? "";
|
|
28
|
+
const host = version ? await discoverVerifiedHost(version).catch(() => undefined) : undefined;
|
|
29
|
+
const ownerID = host ? await receiverOwnerID(host.origin) : undefined;
|
|
27
30
|
const transport: QueueTransport = {
|
|
28
31
|
directory,
|
|
29
32
|
protocol: "v2",
|
|
30
|
-
|
|
33
|
+
receiverOwnerID: ownerID,
|
|
34
|
+
verifySession: (sessionID) => verifyHostSession(sessionID, version),
|
|
35
|
+
backgroundSession: (sessionID) => backgroundOwnSession(sessionID, version),
|
|
31
36
|
promptQueue: (sessionID, id, text, delivery) => context.session.prompt({
|
|
32
37
|
sessionID, id, text, delivery, resume: true,
|
|
33
38
|
}),
|
|
@@ -36,21 +41,7 @@ export function createV2Setup(deps: {
|
|
|
36
41
|
let toolRegistration: { dispose(): Promise<void> } | undefined;
|
|
37
42
|
let commandRegistration: { dispose(): Promise<void> } | undefined;
|
|
38
43
|
let promptRegistration: { dispose(): Promise<void> } | undefined;
|
|
39
|
-
let
|
|
40
|
-
let wakeTimer: ReturnType<typeof setInterval> | undefined;
|
|
41
|
-
let polling = false;
|
|
42
|
-
let stopped = false;
|
|
43
|
-
const poll = async () => {
|
|
44
|
-
if (stopped || polling) return;
|
|
45
|
-
polling = true;
|
|
46
|
-
try {
|
|
47
|
-
await deps.run(runtime, () => deps.poll(sessions, transport, runtime.center));
|
|
48
|
-
} catch {
|
|
49
|
-
// Retry transient polling failures on the next interval.
|
|
50
|
-
} finally {
|
|
51
|
-
polling = false;
|
|
52
|
-
}
|
|
53
|
-
};
|
|
44
|
+
let releaseReceiver: (() => void) | undefined;
|
|
54
45
|
|
|
55
46
|
try {
|
|
56
47
|
promptRegistration = await context.session.hook("prompt", async (input) => {
|
|
@@ -86,23 +77,17 @@ export function createV2Setup(deps: {
|
|
|
86
77
|
});
|
|
87
78
|
},
|
|
88
79
|
}));
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
wakeTimer = setInterval(() => void wake(), 10000);
|
|
94
|
-
}
|
|
80
|
+
releaseReceiver = attachV2Receiver({
|
|
81
|
+
sessions, version, transport, center: runtime.center,
|
|
82
|
+
poll: (ids, target, center) => deps.run(runtime, () => deps.poll(ids, target, center)),
|
|
83
|
+
});
|
|
95
84
|
} catch (error) {
|
|
96
|
-
|
|
97
|
-
if (pollTimer) clearInterval(pollTimer);
|
|
98
|
-
if (wakeTimer) clearInterval(wakeTimer);
|
|
85
|
+
releaseReceiver?.();
|
|
99
86
|
await dispose(toolRegistration, commandRegistration, promptRegistration);
|
|
100
87
|
throw error;
|
|
101
88
|
}
|
|
102
89
|
return async () => {
|
|
103
|
-
|
|
104
|
-
if (pollTimer) clearInterval(pollTimer);
|
|
105
|
-
if (wakeTimer) clearInterval(wakeTimer);
|
|
90
|
+
releaseReceiver?.();
|
|
106
91
|
await dispose(toolRegistration, commandRegistration, promptRegistration);
|
|
107
92
|
};
|
|
108
93
|
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { backgroundOwnSession, discoverVerifiedHost } from "./background";
|
|
2
|
+
import { receiverOwnerID } from "./receiver-owner";
|
|
3
|
+
import { loadRegistry } from "./store";
|
|
4
|
+
import { request, type CenterOpts } from "./center-client";
|
|
5
|
+
import type { QueueTransport } from "./queue-transport";
|
|
6
|
+
|
|
7
|
+
type Attachment = {
|
|
8
|
+
sessions: ReadonlySet<string>;
|
|
9
|
+
version: string;
|
|
10
|
+
transport: QueueTransport;
|
|
11
|
+
center: CenterOpts;
|
|
12
|
+
poll(ids: ReadonlySet<string>, transport: QueueTransport, center: CenterOpts): Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
const attached = new Set<Attachment>();
|
|
15
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
16
|
+
let sweeping = false;
|
|
17
|
+
|
|
18
|
+
export function receiverState() { return { attachments: attached.size, timerRunning: timer !== undefined }; }
|
|
19
|
+
|
|
20
|
+
export function attachV2Receiver(value: Attachment): () => void {
|
|
21
|
+
attached.add(value);
|
|
22
|
+
if (!timer) timer = setInterval(() => void sweep(), 5000);
|
|
23
|
+
return () => {
|
|
24
|
+
attached.delete(value);
|
|
25
|
+
if (!attached.size && timer) { clearInterval(timer); timer = undefined; }
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function sweep(): Promise<void> {
|
|
30
|
+
if (sweeping || !attached.size) return;
|
|
31
|
+
sweeping = true;
|
|
32
|
+
let values = [...attached];
|
|
33
|
+
let observedPolled = false;
|
|
34
|
+
try {
|
|
35
|
+
values = [...attached];
|
|
36
|
+
const host = await discoverVerifiedHost(values[0]!.version);
|
|
37
|
+
if (!host) { await pollObserved(values, new Set()); observedPolled = true; return; }
|
|
38
|
+
const ownerID = await receiverOwnerID(host.origin);
|
|
39
|
+
if (!ownerID) { await pollObserved(values, new Set()); observedPolled = true; return; }
|
|
40
|
+
const primary = values.find((value) => attached.has(value));
|
|
41
|
+
if (!primary) return;
|
|
42
|
+
await pollWithMembershipFallback(async () => {
|
|
43
|
+
const owned = new Set<string>();
|
|
44
|
+
for (const value of values) {
|
|
45
|
+
if (!attached.has(value)) continue;
|
|
46
|
+
if (value.center.center) {
|
|
47
|
+
const result = await request(value.center, `/receiver/memberships?ownerID=${encodeURIComponent(ownerID)}`, "GET") as { sessionIDs?: string[] };
|
|
48
|
+
for (const id of result.sessionIDs ?? []) owned.add(id);
|
|
49
|
+
} else {
|
|
50
|
+
const registry = await loadRegistry();
|
|
51
|
+
for (const entries of Object.values(registry)) for (const [id, entry] of Object.entries(entries)) {
|
|
52
|
+
if (entry.protocol === "v2" && entry.receiverOwnerID === ownerID) owned.add(id);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return owned;
|
|
57
|
+
}, async (owned) => {
|
|
58
|
+
const observed = new Set(values.flatMap((item) => [...item.sessions]));
|
|
59
|
+
const restored = new Set([...owned].filter((id) => !observed.has(id)));
|
|
60
|
+
if (!attached.size) return;
|
|
61
|
+
const target: QueueTransport = {
|
|
62
|
+
...primary.transport,
|
|
63
|
+
directory: undefined,
|
|
64
|
+
receiverOwnerID: ownerID,
|
|
65
|
+
backgroundSession: (id) => backgroundOwnSession(id, primary.version),
|
|
66
|
+
promptQueue: async (sessionID, id, text, delivery) => {
|
|
67
|
+
const info = await host.client.server.info({ signal: AbortSignal.timeout(1500) });
|
|
68
|
+
if (info.pid !== process.pid || info.version !== primary.version) throw Error("OpenCode service changed");
|
|
69
|
+
return host.client.session.prompt({ sessionID, id, text, delivery, resume: true }, { signal: AbortSignal.timeout(1500) });
|
|
70
|
+
},
|
|
71
|
+
mentionOnlySessions: restored,
|
|
72
|
+
};
|
|
73
|
+
await pollOwnedSessions(owned, (ids) => attached.has(primary)
|
|
74
|
+
? primary.poll(ids, target, primary.center) : Promise.resolve());
|
|
75
|
+
}, async (owned) => pollObserved(values, owned), async () => pollObserved(values, new Set()));
|
|
76
|
+
observedPolled = true;
|
|
77
|
+
} catch {
|
|
78
|
+
if (!observedPolled) await pollObserved(values, new Set()).catch(() => {});
|
|
79
|
+
} finally { sweeping = false; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function pollOwnedSessions(
|
|
83
|
+
ids: ReadonlySet<string>, poll: (ids: ReadonlySet<string>) => Promise<void>,
|
|
84
|
+
): Promise<void> {
|
|
85
|
+
if (ids.size) await poll(ids);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function pollWithMembershipFallback(
|
|
89
|
+
memberships: () => Promise<Set<string>>,
|
|
90
|
+
restore: (ids: Set<string>) => Promise<void>,
|
|
91
|
+
observed: (ids: ReadonlySet<string>) => Promise<void>,
|
|
92
|
+
onMembershipFailure: () => Promise<void>,
|
|
93
|
+
): Promise<void> {
|
|
94
|
+
let ids: Set<string>;
|
|
95
|
+
try { ids = await memberships(); }
|
|
96
|
+
catch { await onMembershipFailure(); return; }
|
|
97
|
+
try { if (ids.size) await restore(ids); } catch { /* Observed polling remains independent. */ }
|
|
98
|
+
await observed(ids);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function pollObserved(values: Attachment[], owned: ReadonlySet<string>): Promise<void> {
|
|
102
|
+
const seen = new Set<string>();
|
|
103
|
+
for (const value of values) {
|
|
104
|
+
if (!attached.has(value)) continue;
|
|
105
|
+
const local = new Set([...value.sessions].filter((id) => !owned.has(id) && !seen.has(id)));
|
|
106
|
+
local.forEach((id) => seen.add(id));
|
|
107
|
+
if (local.size) await value.poll(local, value.transport, value.center);
|
|
108
|
+
}
|
|
109
|
+
}
|
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
|
+
}
|