@alexsun-top/opencode-chat-room 0.1.2 → 0.2.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/CHANGELOG.md +15 -0
- package/README.md +17 -12
- package/README.zh-CN.md +17 -12
- package/index.ts +2 -0
- package/package.json +9 -4
- package/plugin.ts +147 -301
- package/server/chat-server.ts +128 -41
- package/src/center-client.ts +24 -528
- package/src/center-inbox.ts +106 -0
- package/src/center-wake.ts +118 -0
- package/src/plugin-notifications.ts +163 -0
- package/src/queue-transport.ts +129 -0
- package/src/queue.ts +14 -9
- package/src/store.ts +2 -0
- package/src/v1-plugin.ts +55 -0
- package/src/v2-plugin.ts +120 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { formatNotificationLines, NOTIFY_INSTRUCTION } from "./store";
|
|
2
|
+
import {
|
|
3
|
+
admissionMatches,
|
|
4
|
+
clearPendingAdmission,
|
|
5
|
+
getOrCreatePendingAdmission,
|
|
6
|
+
markPendingAdmissionAdmitted,
|
|
7
|
+
pendingAdmission,
|
|
8
|
+
rejectPendingAdmission,
|
|
9
|
+
type QueueItem,
|
|
10
|
+
} from "./queue";
|
|
11
|
+
import { request, markQueued, type CenterOpts } from "./center-client";
|
|
12
|
+
import {
|
|
13
|
+
sendAsyncNotification,
|
|
14
|
+
sendQueue,
|
|
15
|
+
type PushResult,
|
|
16
|
+
type QueueTransport,
|
|
17
|
+
} from "./queue-transport";
|
|
18
|
+
|
|
19
|
+
export type InboxItem = QueueItem & { roomId: string; roomName: string };
|
|
20
|
+
const inboxChecks = new Set<string>();
|
|
21
|
+
const sessionPushes = new Map<string, Promise<void>>();
|
|
22
|
+
|
|
23
|
+
export function serializeSessionPush(sessionID: string, task: () => Promise<void>): Promise<void> {
|
|
24
|
+
const previous = sessionPushes.get(sessionID) ?? Promise.resolve();
|
|
25
|
+
const run = previous.catch(() => {}).then(task);
|
|
26
|
+
let current: Promise<void>;
|
|
27
|
+
current = run.finally(() => {
|
|
28
|
+
if (sessionPushes.get(sessionID) === current) sessionPushes.delete(sessionID);
|
|
29
|
+
});
|
|
30
|
+
sessionPushes.set(sessionID, current);
|
|
31
|
+
return current;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function checkCenterInbox(
|
|
35
|
+
opts: CenterOpts,
|
|
36
|
+
sessionID: string,
|
|
37
|
+
transport: QueueTransport,
|
|
38
|
+
): Promise<void> {
|
|
39
|
+
if (inboxChecks.has(sessionID)) return;
|
|
40
|
+
inboxChecks.add(sessionID);
|
|
41
|
+
try {
|
|
42
|
+
await serializeSessionPush(sessionID, async () => {
|
|
43
|
+
const result = await request(opts, `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`, "GET") as {
|
|
44
|
+
items?: InboxItem[];
|
|
45
|
+
queuedTs?: Record<string, number>;
|
|
46
|
+
};
|
|
47
|
+
const queued = result.queuedTs ?? {};
|
|
48
|
+
const items = (Array.isArray(result.items) ? result.items : []).filter(
|
|
49
|
+
(item) => item.createdAt > (queued[item.roomId] ?? 0),
|
|
50
|
+
);
|
|
51
|
+
if (items.length) await pushItemsToSession(opts, sessionID, items, transport, queued);
|
|
52
|
+
});
|
|
53
|
+
} catch {
|
|
54
|
+
// The next inbox poll retries failed delivery.
|
|
55
|
+
} finally {
|
|
56
|
+
inboxChecks.delete(sessionID);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function pushItemsToSession(
|
|
61
|
+
opts: CenterOpts,
|
|
62
|
+
sessionID: string,
|
|
63
|
+
items: InboxItem[],
|
|
64
|
+
transport: QueueTransport,
|
|
65
|
+
queuedTs: Readonly<Record<string, number>> = {},
|
|
66
|
+
): Promise<PushResult> {
|
|
67
|
+
const rooms = new Map<string, InboxItem[]>();
|
|
68
|
+
for (const item of items) {
|
|
69
|
+
if (item.createdAt <= (queuedTs[item.roomId] ?? 0)) continue;
|
|
70
|
+
const group = rooms.get(item.roomId) ?? [];
|
|
71
|
+
group.push(item);
|
|
72
|
+
rooms.set(item.roomId, group);
|
|
73
|
+
}
|
|
74
|
+
let worst: PushResult = "delivered";
|
|
75
|
+
for (const [roomId, batch] of rooms) {
|
|
76
|
+
const maxTs = batch.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
77
|
+
const existing = pendingAdmission(sessionID, roomId);
|
|
78
|
+
const delta = existing?.state === "admitted" && maxTs > existing.maxTs
|
|
79
|
+
? batch.filter((item) => item.createdAt > existing.maxTs)
|
|
80
|
+
: batch;
|
|
81
|
+
if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
|
|
82
|
+
if (existing.maxTs > 0 && await markQueued(opts, roomId, sessionID, existing.maxTs)) {
|
|
83
|
+
clearPendingAdmission(sessionID, roomId, existing.maxTs);
|
|
84
|
+
}
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const deltaTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
88
|
+
const { lines, capped } = formatNotificationLines(delta);
|
|
89
|
+
const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
90
|
+
const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, deltaTs, capped);
|
|
91
|
+
const result = transport.protocol === "v1"
|
|
92
|
+
? await sendAsyncNotification(transport, sessionID, admission.prompt)
|
|
93
|
+
: await sendQueue(transport, sessionID, admission.prompt, admission.id);
|
|
94
|
+
if (result !== "delivered") {
|
|
95
|
+
if (result === "rejected") rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
96
|
+
if (result === "rejected" || worst === "delivered") worst = result;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
|
|
100
|
+
void request(opts, "/active", "POST", { sessionID }).catch(() => {});
|
|
101
|
+
if (admission.maxTs > 0 && await markQueued(opts, roomId, sessionID, admission.maxTs)) {
|
|
102
|
+
clearPendingAdmission(sessionID, roomId, admission.maxTs);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return worst;
|
|
106
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import {
|
|
3
|
+
formatNotificationLines,
|
|
4
|
+
formatServeWakePrompt,
|
|
5
|
+
} from "./store";
|
|
6
|
+
import {
|
|
7
|
+
clearPendingAdmission,
|
|
8
|
+
getOrCreatePendingAdmission,
|
|
9
|
+
markPendingAdmissionAdmitted,
|
|
10
|
+
pendingAdmission,
|
|
11
|
+
rejectPendingAdmission,
|
|
12
|
+
type PendingAdmission,
|
|
13
|
+
} from "./queue";
|
|
14
|
+
import { markQueued, request, type CenterOpts } from "./center-client";
|
|
15
|
+
import { pushItemsToSession, serializeSessionPush, type InboxItem } from "./center-inbox";
|
|
16
|
+
import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
|
|
17
|
+
|
|
18
|
+
const checking = new WeakSet<QueueTransport>();
|
|
19
|
+
|
|
20
|
+
async function wakeViaServe(
|
|
21
|
+
serveUrl: string,
|
|
22
|
+
sessionID: string,
|
|
23
|
+
roomId: string,
|
|
24
|
+
opts: CenterOpts,
|
|
25
|
+
transport: QueueTransport,
|
|
26
|
+
admission: PendingAdmission,
|
|
27
|
+
): Promise<boolean> {
|
|
28
|
+
try {
|
|
29
|
+
const response = await fetch(`${opts.center}/wake-claim`, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: { "Content-Type": "application/json", ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}) },
|
|
32
|
+
body: JSON.stringify({ sessionID }),
|
|
33
|
+
signal: AbortSignal.timeout(10_000),
|
|
34
|
+
});
|
|
35
|
+
const claim = await response.json().catch(() => ({})) as { ok?: boolean };
|
|
36
|
+
if (!claim.ok) return false;
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
const target: QueueTransport = { serverUrl: serveUrl, directory: transport.directory, protocol: transport.protocol };
|
|
41
|
+
const result = transport.protocol === "v1"
|
|
42
|
+
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
43
|
+
: await sendQueue(target, sessionID, admission.prompt, admission.id);
|
|
44
|
+
if (result === "delivered") {
|
|
45
|
+
void request(opts, "/active", "POST", { sessionID }).catch(() => {});
|
|
46
|
+
markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
|
|
47
|
+
if (admission.maxTs > 0 && await markQueued(opts, roomId, sessionID, admission.maxTs)) {
|
|
48
|
+
clearPendingAdmission(sessionID, roomId, admission.maxTs);
|
|
49
|
+
}
|
|
50
|
+
} else if (result === "rejected") {
|
|
51
|
+
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
52
|
+
}
|
|
53
|
+
return result === "delivered";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function wakeSessions(
|
|
57
|
+
opts: CenterOpts,
|
|
58
|
+
transport: QueueTransport,
|
|
59
|
+
serveUrl = "",
|
|
60
|
+
eligibleSessions?: ReadonlySet<string>,
|
|
61
|
+
): Promise<void> {
|
|
62
|
+
if (checking.has(transport)) return;
|
|
63
|
+
checking.add(transport);
|
|
64
|
+
try {
|
|
65
|
+
const rooms = await request(opts, "/rooms/summary", "GET") as unknown as Array<{ id: string; latestMsgTs: number }>;
|
|
66
|
+
if (!Array.isArray(rooms)) return;
|
|
67
|
+
for (const room of rooms) {
|
|
68
|
+
try {
|
|
69
|
+
const roomId = String(room.id ?? "");
|
|
70
|
+
const latest = Number(room.latestMsgTs ?? 0);
|
|
71
|
+
if (!roomId || latest === 0) continue;
|
|
72
|
+
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, {
|
|
73
|
+
name: string; lastReadTs?: number; lastQueuedTs?: number; host?: string; directory?: string;
|
|
74
|
+
}>;
|
|
75
|
+
for (const [sessionID, entry] of Object.entries(registry)) {
|
|
76
|
+
if (eligibleSessions && !eligibleSessions.has(sessionID)) continue;
|
|
77
|
+
if (!entry.host || entry.host !== os.hostname()) continue;
|
|
78
|
+
if (latest <= Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0)) continue;
|
|
79
|
+
await serializeSessionPush(sessionID, async () => {
|
|
80
|
+
const inbox = await request(opts,
|
|
81
|
+
`/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(roomId)}&excludeSelf=1&timeout=0`,
|
|
82
|
+
"GET") as { items?: InboxItem[]; queuedTs?: Record<string, number> };
|
|
83
|
+
const queuedTs = Math.max(entry.lastQueuedTs ?? 0, inbox.queuedTs?.[roomId] ?? 0);
|
|
84
|
+
const items = (Array.isArray(inbox.items) ? inbox.items : []).filter(
|
|
85
|
+
(item) => item.roomId === roomId && item.createdAt > queuedTs,
|
|
86
|
+
);
|
|
87
|
+
if (!items.length) return;
|
|
88
|
+
const target = { ...transport, directory: entry.directory ?? transport.directory };
|
|
89
|
+
const pushed = await pushItemsToSession(opts, sessionID, items, target, inbox.queuedTs);
|
|
90
|
+
if (pushed !== "unreachable" || !serveUrl) return;
|
|
91
|
+
const mentioned = items.some((item) => {
|
|
92
|
+
if (item.text.includes(`<at>@${entry.name}</at>`)) return true;
|
|
93
|
+
const escaped = entry.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
94
|
+
return new RegExp(`@${escaped}(?![\\p{L}\\p{N}_])`, "u").test(item.text);
|
|
95
|
+
});
|
|
96
|
+
if (!mentioned) return;
|
|
97
|
+
const currentMax = items.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
98
|
+
const existing = pendingAdmission(sessionID, roomId);
|
|
99
|
+
const delta = existing?.state === "admitted" && currentMax > existing.maxTs
|
|
100
|
+
? items.filter((item) => item.createdAt > existing.maxTs) : items;
|
|
101
|
+
if (existing?.state === "admitted" && (currentMax <= existing.maxTs || !delta.length)) return;
|
|
102
|
+
const { lines, capped } = formatNotificationLines(delta);
|
|
103
|
+
const prompt = formatServeWakePrompt(delta[0]!.roomName, lines);
|
|
104
|
+
const maxTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
105
|
+
const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, maxTs, capped);
|
|
106
|
+
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
// A failing room is retried on the next wake sweep.
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
// The next wake sweep retries center failures.
|
|
115
|
+
} finally {
|
|
116
|
+
checking.delete(transport);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { Message } from "./room-service";
|
|
4
|
+
import {
|
|
5
|
+
formatNotificationLines,
|
|
6
|
+
loadRegistry,
|
|
7
|
+
NOTIFY_INSTRUCTION,
|
|
8
|
+
saveRegistry,
|
|
9
|
+
statePath,
|
|
10
|
+
timeOf,
|
|
11
|
+
} from "./store";
|
|
12
|
+
import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
|
|
13
|
+
import {
|
|
14
|
+
getOrCreatePendingAdmission,
|
|
15
|
+
markPendingAdmissionAdmitted,
|
|
16
|
+
pendingAdmission,
|
|
17
|
+
rejectPendingAdmission,
|
|
18
|
+
} from "./queue";
|
|
19
|
+
|
|
20
|
+
type NotifyBatch = { roomId: string; roomName: string; messages: Message[] };
|
|
21
|
+
type NotifyAttempt = { url: string; status: number };
|
|
22
|
+
type TargetQueue = { latest?: NotifyBatch; latestTs: number; running: Promise<NotifyAttempt[]> };
|
|
23
|
+
|
|
24
|
+
export function createNotifier(deps: {
|
|
25
|
+
transport(): QueueTransport;
|
|
26
|
+
bumpQueued(roomId: string, sessionID: string, ts: number): Promise<boolean>;
|
|
27
|
+
}) {
|
|
28
|
+
const queues = new Map<string, TargetQueue>();
|
|
29
|
+
const notifyPath = () => path.join(path.dirname(statePath()), "notify.log");
|
|
30
|
+
|
|
31
|
+
async function log(roomId: string, results: PromiseSettledResult<NotifyAttempt>[]) {
|
|
32
|
+
const lines = results.map((r) => {
|
|
33
|
+
const head = `[${timeOf(Date.now())}] room=${roomId}`;
|
|
34
|
+
if (r.status === "rejected") return `${head} FAIL ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`;
|
|
35
|
+
return r.value.status >= 200 && r.value.status < 300
|
|
36
|
+
? `${head} OK ${r.value.status} ${r.value.url}`
|
|
37
|
+
: `${head} FAIL ${r.value.status} ${r.value.url}`;
|
|
38
|
+
});
|
|
39
|
+
await fs.appendFile(notifyPath(), lines.join("\n") + "\n", "utf8").catch(() => {});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function notifyTarget(
|
|
43
|
+
sessionID: string,
|
|
44
|
+
batch: NotifyBatch,
|
|
45
|
+
transport: QueueTransport = deps.transport(),
|
|
46
|
+
): Promise<NotifyAttempt | undefined> {
|
|
47
|
+
const entry = (await loadRegistry())[batch.roomId]?.[sessionID];
|
|
48
|
+
if (!entry || (entry.protocol !== "v2" && !entry.serverUrl)) return undefined;
|
|
49
|
+
const unread = batch.messages.filter((m) =>
|
|
50
|
+
m.createdAt > Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0) &&
|
|
51
|
+
(m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== entry.name),
|
|
52
|
+
);
|
|
53
|
+
if (!unread.length) return undefined;
|
|
54
|
+
const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
|
|
55
|
+
const existing = pendingAdmission(sessionID, batch.roomId);
|
|
56
|
+
const delta = existing?.state === "admitted" && maxTs > existing.maxTs
|
|
57
|
+
? unread.filter((m) => m.createdAt > existing.maxTs)
|
|
58
|
+
: unread;
|
|
59
|
+
const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
|
|
60
|
+
const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
|
|
61
|
+
const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
|
|
62
|
+
const path = `${prefix ? `/${prefix}` : ""}/session/${encodeURIComponent(sessionID)}/${endpoint}`;
|
|
63
|
+
const url = base ? `${base.origin}${path}` : `opencode://session/${sessionID}/${endpoint}`;
|
|
64
|
+
if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
|
|
65
|
+
if (existing.maxTs > 0) await deps.bumpQueued(batch.roomId, sessionID, existing.maxTs);
|
|
66
|
+
return { url, status: entry.protocol === "v2" ? 200 : 204 };
|
|
67
|
+
}
|
|
68
|
+
const { lines, capped } = formatNotificationLines(delta);
|
|
69
|
+
const prompt = `<notification>\nNew messages in room ${batch.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
70
|
+
const deltaTs = delta.reduce((max, m) => Math.max(max, m.createdAt), 0);
|
|
71
|
+
const admission = getOrCreatePendingAdmission(
|
|
72
|
+
sessionID, batch.roomId, delta, prompt, deltaTs, capped,
|
|
73
|
+
);
|
|
74
|
+
if (admission.state === "admitted" && deltaTs <= admission.maxTs) {
|
|
75
|
+
await deps.bumpQueued(batch.roomId, sessionID, admission.maxTs);
|
|
76
|
+
return { url, status: entry.protocol === "v2" ? 200 : 204 };
|
|
77
|
+
}
|
|
78
|
+
const targetTransport = {
|
|
79
|
+
...transport,
|
|
80
|
+
serverUrl: entry.serverUrl,
|
|
81
|
+
directory: entry.directory ?? transport.directory,
|
|
82
|
+
};
|
|
83
|
+
const result = entry.protocol === "v2"
|
|
84
|
+
? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id)
|
|
85
|
+
: await sendAsyncNotification(targetTransport, sessionID, admission.prompt);
|
|
86
|
+
if (result !== "delivered") {
|
|
87
|
+
if (result === "rejected") rejectPendingAdmission(sessionID, batch.roomId, admission.id);
|
|
88
|
+
return { url, status: result === "unreachable" ? 0 : 400 };
|
|
89
|
+
}
|
|
90
|
+
markPendingAdmissionAdmitted(sessionID, batch.roomId, admission.id);
|
|
91
|
+
if (admission.maxTs > 0) await deps.bumpQueued(batch.roomId, sessionID, admission.maxTs);
|
|
92
|
+
return { url, status: entry.protocol === "v2" ? 200 : 204 };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function batchMax(batch: NotifyBatch) {
|
|
96
|
+
return batch.messages.reduce((max, message) => Math.max(max, message.createdAt), 0);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function queueTarget(sessionID: string, batch: NotifyBatch): Promise<NotifyAttempt[]> {
|
|
100
|
+
const key = JSON.stringify([batch.roomId, sessionID]);
|
|
101
|
+
const existing = queues.get(key);
|
|
102
|
+
if (existing) {
|
|
103
|
+
const max = batchMax(batch);
|
|
104
|
+
if (max > existing.latestTs) {
|
|
105
|
+
existing.latest = batch;
|
|
106
|
+
existing.latestTs = max;
|
|
107
|
+
}
|
|
108
|
+
return existing.running;
|
|
109
|
+
}
|
|
110
|
+
const state: TargetQueue = { latest: batch, latestTs: batchMax(batch), running: Promise.resolve([]) };
|
|
111
|
+
const running = (async () => {
|
|
112
|
+
const attempts: NotifyAttempt[] = [];
|
|
113
|
+
let firstError: unknown;
|
|
114
|
+
while (state.latest) {
|
|
115
|
+
const current = state.latest;
|
|
116
|
+
state.latest = undefined;
|
|
117
|
+
try {
|
|
118
|
+
const attempt = await notifyTarget(sessionID, current);
|
|
119
|
+
if (attempt) attempts.push(attempt);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
firstError ??= error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (firstError !== undefined) throw firstError;
|
|
125
|
+
return attempts;
|
|
126
|
+
})();
|
|
127
|
+
state.running = running;
|
|
128
|
+
queues.set(key, state);
|
|
129
|
+
const clean = () => { if (queues.get(key) === state) queues.delete(key); };
|
|
130
|
+
void running.then(clean, clean);
|
|
131
|
+
return running;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function notifyRoom(
|
|
135
|
+
roomId: string,
|
|
136
|
+
roomName: string,
|
|
137
|
+
_body: string,
|
|
138
|
+
selfSessionID: string,
|
|
139
|
+
messages: Message[],
|
|
140
|
+
) {
|
|
141
|
+
const registry = await loadRegistry();
|
|
142
|
+
const targets = Object.entries(registry[roomId] ?? {}).filter(
|
|
143
|
+
([id, entry]) => id !== selfSessionID && entry.protocol !== "v2" && entry.serverUrl,
|
|
144
|
+
);
|
|
145
|
+
const results = await Promise.allSettled(targets.map(([id]) =>
|
|
146
|
+
queueTarget(id, { roomId, roomName, messages }),
|
|
147
|
+
));
|
|
148
|
+
const attempts: PromiseSettledResult<NotifyAttempt>[] = [];
|
|
149
|
+
let failure: unknown;
|
|
150
|
+
for (const result of results) {
|
|
151
|
+
if (result.status === "fulfilled") {
|
|
152
|
+
attempts.push(...result.value.map((value) => ({ status: "fulfilled", value } as const)));
|
|
153
|
+
} else {
|
|
154
|
+
attempts.push(result);
|
|
155
|
+
failure ??= result.reason;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
await log(roomId, attempts);
|
|
159
|
+
if (failure !== undefined) throw failure;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { notifyRoom, notifyTarget };
|
|
163
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { authHeader } from "./store";
|
|
2
|
+
import { admissionMatches, type QueueBody } from "./queue";
|
|
3
|
+
|
|
4
|
+
export type PushResult = "delivered" | "unreachable" | "rejected";
|
|
5
|
+
export type QueueTransport = {
|
|
6
|
+
promptQueue?: (sessionID: string, id: string, text: string) => Promise<unknown>;
|
|
7
|
+
serverUrl?: string;
|
|
8
|
+
directory?: string;
|
|
9
|
+
protocol?: "v1" | "v2";
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export function createQueueTransport(input: { directory?: string; serverUrl?: URL | string } = {}): QueueTransport {
|
|
13
|
+
const serverUrl = String(input.serverUrl ?? "").trim();
|
|
14
|
+
return { serverUrl: serverUrl || undefined, protocol: "v1", directory: input.directory };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
18
|
+
return typeof value === "object" && value !== null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function statusOf(value: unknown): number | undefined {
|
|
22
|
+
if (!isRecord(value)) return undefined;
|
|
23
|
+
if (typeof value.status === "number") return value.status;
|
|
24
|
+
if (isRecord(value.response) && typeof value.response.status === "number") return value.response.status;
|
|
25
|
+
if (isRecord(value.cause) && typeof value.cause.status === "number") return value.cause.status;
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function headers(transport: QueueTransport): Record<string, string> {
|
|
30
|
+
const auth = authHeader();
|
|
31
|
+
return {
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
...(auth ? { Authorization: auth } : {}),
|
|
34
|
+
...(transport.directory ? { "x-opencode-directory": encodeURIComponent(transport.directory) } : {}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function sendQueueInProcess(
|
|
39
|
+
transport: QueueTransport,
|
|
40
|
+
sessionID: string,
|
|
41
|
+
body: QueueBody,
|
|
42
|
+
): Promise<PushResult> {
|
|
43
|
+
let result: unknown;
|
|
44
|
+
try {
|
|
45
|
+
result = await transport.promptQueue!(sessionID, body.id, body.prompt.text);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
const status = statusOf(error);
|
|
48
|
+
return status === undefined || status === 404 ? "unreachable" : "rejected";
|
|
49
|
+
}
|
|
50
|
+
if (!isRecord(result)) return "unreachable";
|
|
51
|
+
if (!isRecord(result.response)) return admissionMatches(result, body, sessionID) ? "delivered" : "rejected";
|
|
52
|
+
const status = result.response.status;
|
|
53
|
+
if (typeof status !== "number" || status === 404) return "unreachable";
|
|
54
|
+
if (status < 200 || status >= 300) return "rejected";
|
|
55
|
+
return admissionMatches(result.data, body, sessionID) ? "delivered" : "rejected";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function sendQueueHttp(
|
|
59
|
+
transport: QueueTransport,
|
|
60
|
+
sessionID: string,
|
|
61
|
+
body: QueueBody,
|
|
62
|
+
): Promise<PushResult> {
|
|
63
|
+
if (!transport.serverUrl) return "unreachable";
|
|
64
|
+
let response: Response;
|
|
65
|
+
try {
|
|
66
|
+
response = await fetch(`${transport.serverUrl.replace(/\/+$/, "")}/api/session/${encodeURIComponent(sessionID)}/prompt`, {
|
|
67
|
+
method: "POST",
|
|
68
|
+
headers: headers(transport),
|
|
69
|
+
body: JSON.stringify({
|
|
70
|
+
id: body.id,
|
|
71
|
+
text: body.prompt.text,
|
|
72
|
+
delivery: body.delivery,
|
|
73
|
+
resume: body.resume,
|
|
74
|
+
}),
|
|
75
|
+
signal: AbortSignal.timeout(10_000),
|
|
76
|
+
});
|
|
77
|
+
} catch {
|
|
78
|
+
return "unreachable";
|
|
79
|
+
}
|
|
80
|
+
const data = await response.json().catch(() => undefined);
|
|
81
|
+
if (response.status === 404) return "unreachable";
|
|
82
|
+
if (!response.ok) return "rejected";
|
|
83
|
+
return admissionMatches(data, body, sessionID) ? "delivered" : "rejected";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function sendAsyncNotification(
|
|
87
|
+
transport: QueueTransport,
|
|
88
|
+
sessionID: string,
|
|
89
|
+
text: string,
|
|
90
|
+
): Promise<PushResult> {
|
|
91
|
+
if (!transport.serverUrl) return "unreachable";
|
|
92
|
+
let response: Response;
|
|
93
|
+
let base: string;
|
|
94
|
+
try {
|
|
95
|
+
base = new URL(transport.serverUrl).origin;
|
|
96
|
+
} catch {
|
|
97
|
+
return "unreachable";
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
response = await fetch(`${base}/session/${encodeURIComponent(sessionID)}/prompt_async`, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
headers: headers(transport),
|
|
103
|
+
body: JSON.stringify({ parts: [{ type: "text", text }] }),
|
|
104
|
+
signal: AbortSignal.timeout(10_000),
|
|
105
|
+
});
|
|
106
|
+
} catch {
|
|
107
|
+
return "unreachable";
|
|
108
|
+
}
|
|
109
|
+
return response.status === 204 ? "delivered" : response.status === 404 ? "unreachable" : "rejected";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function sendQueue(
|
|
113
|
+
transport: QueueTransport,
|
|
114
|
+
sessionID: string,
|
|
115
|
+
text: string,
|
|
116
|
+
admissionID: string,
|
|
117
|
+
): Promise<PushResult> {
|
|
118
|
+
const body: QueueBody = {
|
|
119
|
+
id: admissionID,
|
|
120
|
+
prompt: { text },
|
|
121
|
+
delivery: "queue",
|
|
122
|
+
resume: true,
|
|
123
|
+
};
|
|
124
|
+
if (transport.promptQueue) {
|
|
125
|
+
const result = await sendQueueInProcess(transport, sessionID, body);
|
|
126
|
+
if (result !== "unreachable") return result;
|
|
127
|
+
}
|
|
128
|
+
return sendQueueHttp(transport, sessionID, body);
|
|
129
|
+
}
|
package/src/queue.ts
CHANGED
|
@@ -174,13 +174,18 @@ export function admissionMatches(
|
|
|
174
174
|
return false;
|
|
175
175
|
}
|
|
176
176
|
const record = value as Record<string, unknown>;
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
177
|
+
if (
|
|
178
|
+
record.id === body.id &&
|
|
179
|
+
record.sessionID === sessionID &&
|
|
180
|
+
record.delivery === "queue"
|
|
181
|
+
) {
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
return isRecord(record.data)
|
|
185
|
+
? admissionMatches(record.data, body, sessionID)
|
|
186
|
+
: false;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
190
|
+
return typeof value === "object" && value !== null;
|
|
186
191
|
}
|
package/src/store.ts
CHANGED
|
@@ -112,8 +112,10 @@ export async function saveRooms(svc: RoomService): Promise<void> {
|
|
|
112
112
|
export type RegistryEntry = {
|
|
113
113
|
serverUrl: string;
|
|
114
114
|
apiPrefix: string;
|
|
115
|
+
protocol?: "v1" | "v2";
|
|
115
116
|
name: string;
|
|
116
117
|
lastReadTs?: number;
|
|
118
|
+
lastQueuedTs?: number;
|
|
117
119
|
directory?: string;
|
|
118
120
|
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行;web 条目不填
|
|
119
121
|
host?: string;
|
package/src/v1-plugin.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Config, Plugin, PluginInput, ToolDefinition } from "@opencode-ai/plugin";
|
|
2
|
+
import type { V2Runtime } from "./v2-plugin";
|
|
3
|
+
import type { QueueTransport } from "./queue-transport";
|
|
4
|
+
|
|
5
|
+
export function createV1Server(deps: {
|
|
6
|
+
runtime(input: PluginInput, transport: QueueTransport): V2Runtime;
|
|
7
|
+
run<T>(runtime: V2Runtime, callback: () => T): T;
|
|
8
|
+
room: ToolDefinition;
|
|
9
|
+
observe(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
10
|
+
checkInbox(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
11
|
+
wake(runtime: V2Runtime, sessions: ReadonlySet<string>): Promise<void>;
|
|
12
|
+
central: boolean;
|
|
13
|
+
}) : Plugin {
|
|
14
|
+
return async (input) => {
|
|
15
|
+
const sessions = new Set<string>();
|
|
16
|
+
const transport = {
|
|
17
|
+
serverUrl: String(input.serverUrl),
|
|
18
|
+
directory: input.directory,
|
|
19
|
+
protocol: "v1" as const,
|
|
20
|
+
};
|
|
21
|
+
const runtime = deps.runtime(input, transport);
|
|
22
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
23
|
+
if (deps.central) {
|
|
24
|
+
void deps.run(runtime, () => deps.wake(runtime, sessions));
|
|
25
|
+
timer = setInterval(() => void deps.run(runtime, () => deps.wake(runtime, sessions)), 10000);
|
|
26
|
+
}
|
|
27
|
+
const room = {
|
|
28
|
+
...deps.room,
|
|
29
|
+
execute: (args: Parameters<ToolDefinition["execute"]>[0], context: Parameters<ToolDefinition["execute"]>[1]) =>
|
|
30
|
+
deps.run(runtime, async () => {
|
|
31
|
+
sessions.add(context.sessionID);
|
|
32
|
+
await deps.observe(runtime, context.sessionID);
|
|
33
|
+
return deps.room.execute(args, context);
|
|
34
|
+
}),
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
tool: { room },
|
|
38
|
+
config: async (cfg: Config) => {
|
|
39
|
+
cfg.command = cfg.command ?? {};
|
|
40
|
+
cfg.command.room = {
|
|
41
|
+
description: "Chat room: create/join/leave/list rooms, send and poll messages",
|
|
42
|
+
template: "Use the room tool to handle the chat room command. Arguments: $ARGUMENTS",
|
|
43
|
+
};
|
|
44
|
+
},
|
|
45
|
+
dispose: async () => { if (timer) clearInterval(timer); },
|
|
46
|
+
"chat.message": async (event: { sessionID: string }) => {
|
|
47
|
+
sessions.add(event.sessionID);
|
|
48
|
+
await deps.run(runtime, async () => {
|
|
49
|
+
await deps.observe(runtime, event.sessionID);
|
|
50
|
+
if (deps.central) void deps.checkInbox(runtime, event.sessionID).catch(() => {});
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
}
|