@alexsun-top/opencode-chat-room 0.1.0 → 0.1.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/README.md +16 -8
- package/README.zh-CN.md +16 -8
- package/cli.ts +95 -1
- package/package.json +2 -1
- package/plugin.ts +230 -73
- package/server/chat-server.ts +149 -43
- package/server/chat.html +350 -95
- package/src/center-client.ts +324 -122
- package/src/queue.ts +186 -0
- package/src/room-service.ts +11 -4
- package/src/store.ts +18 -6
package/README.md
CHANGED
|
@@ -53,16 +53,21 @@ Push notifications travel over each session's embedded HTTP server. On one machi
|
|
|
53
53
|
|
|
54
54
|
For several machines: run one central server, point every client at it. This is the only per-client configuration.
|
|
55
55
|
|
|
56
|
-
On the server machine,
|
|
56
|
+
On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute the package; the CLI itself runs on Bun. CLI options override environment variables.
|
|
57
57
|
|
|
58
58
|
```bash
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
bunx @alexsun-top/opencode-chat-room
|
|
59
|
+
# Show CLI options:
|
|
60
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --help
|
|
62
61
|
|
|
63
|
-
#
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
# Start the local central server (choose any one runner):
|
|
63
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
|
|
64
|
+
pnpx --package=@alexsun-top/opencode-chat-room@0.1.2 opencode-chat-room --host 0.0.0.0 --port 4399
|
|
65
|
+
bunx @alexsun-top/opencode-chat-room@0.1.2 --host 0.0.0.0 --port 4399 --token secret
|
|
66
|
+
|
|
67
|
+
# Environment variables also work; CLI options take precedence:
|
|
68
|
+
CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
|
|
69
|
+
CHAT_ROOM_SERVER_TOKEN=secret \
|
|
70
|
+
bunx @alexsun-top/opencode-chat-room@0.1.2
|
|
66
71
|
|
|
67
72
|
# Local checkout:
|
|
68
73
|
bun install
|
|
@@ -86,7 +91,10 @@ Then start opencode normally. Room state lives on the central server. Clients on
|
|
|
86
91
|
|---|---|---|---|
|
|
87
92
|
| `CHAT_ROOM_SERVER_URL` | client | Central server URL; when set, central mode is active | unset (standalone) |
|
|
88
93
|
| `CHAT_ROOM_SERVER_TOKEN` | both | Bearer token for the central server (optional) | none (open) |
|
|
89
|
-
| `
|
|
94
|
+
| `CHAT_ROOM_SERVER_HOST` | server | Bind hostname; takes precedence over `HOST` | `0.0.0.0` |
|
|
95
|
+
| `HOST` | server | Host alias, used when `CHAT_ROOM_SERVER_HOST` is unset | unset |
|
|
96
|
+
| `CHAT_ROOM_SERVER_PORT` | server | Central server listen port; takes precedence over `PORT` | `4399` |
|
|
97
|
+
| `PORT` | server | Port alias, used when `CHAT_ROOM_SERVER_PORT` is unset | unset |
|
|
90
98
|
| `CHAT_ROOM_STATE_DIR` | standalone | Directory for `rooms.json`/`registry.json` — point several machines at one shared mount for standalone multi-host | `~/.config/opencode/chat-room/` |
|
|
91
99
|
| `OPENCODE_SERVER_PASSWORD` | both | opencode server password; used for Basic auth on cross-session pushes | none |
|
|
92
100
|
|
package/README.zh-CN.md
CHANGED
|
@@ -53,16 +53,21 @@
|
|
|
53
53
|
|
|
54
54
|
多台机器时:跑一个中心服务器,所有客户端指向它。**每个客户端只需要这一个环境变量**。
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
在服务器机器上请先安装 Bun。`npx`、`pnpx`、`bunx` 只是包执行器,CLI 本身运行在 Bun 上;CLI 参数优先于环境变量。
|
|
57
57
|
|
|
58
58
|
```bash
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
bunx @alexsun-top/opencode-chat-room
|
|
59
|
+
# 查看 CLI 选项:
|
|
60
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --help
|
|
62
61
|
|
|
63
|
-
#
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
# 启动本地中心服务器(三选一):
|
|
63
|
+
npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
|
|
64
|
+
pnpx --package=@alexsun-top/opencode-chat-room@0.1.2 opencode-chat-room --host 0.0.0.0 --port 4399
|
|
65
|
+
bunx @alexsun-top/opencode-chat-room@0.1.2 --host 0.0.0.0 --port 4399 --token secret
|
|
66
|
+
|
|
67
|
+
# 也可以使用环境变量;CLI 参数优先:
|
|
68
|
+
CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
|
|
69
|
+
CHAT_ROOM_SERVER_TOKEN=secret \
|
|
70
|
+
bunx @alexsun-top/opencode-chat-room@0.1.2
|
|
66
71
|
|
|
67
72
|
# 本地 checkout:
|
|
68
73
|
bun install
|
|
@@ -86,7 +91,10 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
|
|
|
86
91
|
|---|---|---|---|
|
|
87
92
|
| `CHAT_ROOM_SERVER_URL` | 客户端 | 中心服务器地址;设置后即进入中心模式 | 未设置(单机模式) |
|
|
88
93
|
| `CHAT_ROOM_SERVER_TOKEN` | 双端 | 中心服务器的 Bearer 认证令牌(可选) | 无(开放) |
|
|
89
|
-
| `
|
|
94
|
+
| `CHAT_ROOM_SERVER_HOST` | 服务器 | 监听主机名;优先于 `HOST` | `0.0.0.0` |
|
|
95
|
+
| `HOST` | 服务器 | 主机名别名,仅在未设置 `CHAT_ROOM_SERVER_HOST` 时使用 | 未设置 |
|
|
96
|
+
| `CHAT_ROOM_SERVER_PORT` | 服务器 | 中心服务器监听端口;优先于 `PORT` | `4399` |
|
|
97
|
+
| `PORT` | 服务器 | 端口别名,仅在未设置 `CHAT_ROOM_SERVER_PORT` 时使用 | 未设置 |
|
|
90
98
|
| `CHAT_ROOM_STATE_DIR` | 单机模式 | `rooms.json`/`registry.json` 所在目录——多主机单机模式可指向同一共享挂载 | `~/.config/opencode/chat-room/` |
|
|
91
99
|
| `OPENCODE_SERVER_PASSWORD` | 双端 | opencode 服务器密码;跨会话推送时用作 Basic 认证 | 无 |
|
|
92
100
|
|
package/cli.ts
CHANGED
|
@@ -1,5 +1,99 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
const usage = `Usage: opencode-chat-room [options]
|
|
4
4
|
|
|
5
|
+
Options:
|
|
6
|
+
-h, --help Show this help
|
|
7
|
+
-v, --version Show the package version
|
|
8
|
+
-H, --host <host> Bind hostname
|
|
9
|
+
-p, --port <port> Bind port (1-65535)
|
|
10
|
+
-t, --token <token> Enable bearer token authentication`;
|
|
11
|
+
|
|
12
|
+
type ValueOption = "host" | "port" | "token";
|
|
13
|
+
const values: Partial<Record<ValueOption, string>> = {};
|
|
14
|
+
let help = false;
|
|
15
|
+
let version = false;
|
|
16
|
+
|
|
17
|
+
function fail(message: string): never {
|
|
18
|
+
console.error(`Error: ${message}\n\n${usage}`);
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function setValue(name: ValueOption, value: string | undefined): void {
|
|
23
|
+
if (value === undefined || value === "") {
|
|
24
|
+
fail(`Missing value for --${name}`);
|
|
25
|
+
}
|
|
26
|
+
values[name] = value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function validatePort(value: string): void {
|
|
30
|
+
const port = Number(value);
|
|
31
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
32
|
+
fail(`Invalid port "${value}": expected an integer from 1 to 65535`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const args = process.argv.slice(2);
|
|
37
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
38
|
+
const arg = args[i]!;
|
|
39
|
+
if (arg === "-h" || arg === "--help") {
|
|
40
|
+
help = true;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (arg === "-v" || arg === "--version") {
|
|
44
|
+
version = true;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const equals = arg.match(/^--(host|port|token)=(.*)$/);
|
|
49
|
+
if (equals) {
|
|
50
|
+
const name = equals[1] as ValueOption;
|
|
51
|
+
setValue(name, equals[2]);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const name =
|
|
56
|
+
arg === "-H" || arg === "--host"
|
|
57
|
+
? "host"
|
|
58
|
+
: arg === "-p" || arg === "--port"
|
|
59
|
+
? "port"
|
|
60
|
+
: arg === "-t" || arg === "--token"
|
|
61
|
+
? "token"
|
|
62
|
+
: undefined;
|
|
63
|
+
if (name) {
|
|
64
|
+
const value = args[++i];
|
|
65
|
+
if (value?.startsWith("-") && !(name === "port" && /^-\d+$/.test(value))) {
|
|
66
|
+
fail(`Missing value for --${name}`);
|
|
67
|
+
}
|
|
68
|
+
setValue(name, value);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
fail(`Unknown option: ${arg}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (help) {
|
|
75
|
+
console.log(usage);
|
|
76
|
+
process.exit(0);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (version) {
|
|
80
|
+
const packageJson = (await Bun.file(
|
|
81
|
+
new URL("./package.json", import.meta.url),
|
|
82
|
+
).json()) as { version?: string };
|
|
83
|
+
console.log(packageJson.version ?? "unknown");
|
|
84
|
+
process.exit(0);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (values.port !== undefined) {
|
|
88
|
+
validatePort(values.port);
|
|
89
|
+
process.env.CHAT_ROOM_SERVER_PORT = values.port;
|
|
90
|
+
}
|
|
91
|
+
if (values.host !== undefined) {
|
|
92
|
+
process.env.CHAT_ROOM_SERVER_HOST = values.host;
|
|
93
|
+
}
|
|
94
|
+
if (values.token !== undefined) {
|
|
95
|
+
process.env.CHAT_ROOM_SERVER_TOKEN = values.token;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const { default: server } = await import("./server/chat-server");
|
|
5
99
|
Bun.serve(server);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexsun-top/opencode-chat-room",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "A chat-room plugin and central server for OpenCode.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@opencode-ai/plugin": "^1.18.16",
|
|
45
|
+
"@opencode-ai/sdk": "1.18.16",
|
|
45
46
|
"zod": "4.1.8"
|
|
46
47
|
}
|
|
47
48
|
}
|
package/plugin.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { tool } from "@opencode-ai/plugin";
|
|
1
|
+
import { tool, type PluginInput } from "@opencode-ai/plugin";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { promises as fs } from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import RoomService, { RoomError, type Message } from "./src/room-service";
|
|
6
6
|
import {
|
|
7
|
-
authHeader,
|
|
8
7
|
enqueue,
|
|
9
8
|
formatNotificationLines,
|
|
10
9
|
formatRoom,
|
|
@@ -20,10 +19,25 @@ import {
|
|
|
20
19
|
type Registry,
|
|
21
20
|
type RegistryEntry,
|
|
22
21
|
} from "./src/store";
|
|
23
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
centerAction,
|
|
24
|
+
checkCenterInbox,
|
|
25
|
+
createQueueTransport,
|
|
26
|
+
sendQueue,
|
|
27
|
+
wakeSessions,
|
|
28
|
+
type QueueTransport,
|
|
29
|
+
} from "./src/center-client";
|
|
30
|
+
import {
|
|
31
|
+
clearPendingAdmission,
|
|
32
|
+
getOrCreatePendingAdmission,
|
|
33
|
+
markPendingAdmissionAdmitted,
|
|
34
|
+
rejectPendingAdmission,
|
|
35
|
+
} from "./src/queue";
|
|
24
36
|
|
|
25
37
|
// captured once at server start; registry push notifications route to it
|
|
26
38
|
let selfServerUrl = "";
|
|
39
|
+
let selfDirectory = "";
|
|
40
|
+
let queueTransport: QueueTransport = createQueueTransport();
|
|
27
41
|
|
|
28
42
|
// ponytail: central-mode in-process wake timer (see server() below)
|
|
29
43
|
let wakeTimer: ReturnType<typeof setInterval> | null = null;
|
|
@@ -32,7 +46,7 @@ let wakeTimer: ReturnType<typeof setInterval> | null = null;
|
|
|
32
46
|
// central server); unset = standalone local-file mode
|
|
33
47
|
const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
|
|
34
48
|
const centerToken = process.env.CHAT_ROOM_SERVER_TOKEN ?? "";
|
|
35
|
-
const centerOpts = { center: centerUrl, token: centerToken };
|
|
49
|
+
const centerOpts = { center: centerUrl, token: centerToken, directory: "" };
|
|
36
50
|
// ponytail: optional常驻 opencode serve 地址——配置了才能对已退出 session
|
|
37
51
|
// 做进程内唤起;未配置则不唤起(用户要求)
|
|
38
52
|
const serveWakeUrl = process.env.CHAT_ROOM_WAKE_SERVE_URL ?? "";
|
|
@@ -67,16 +81,22 @@ async function registerSelf(
|
|
|
67
81
|
return enqueue(async () => {
|
|
68
82
|
try {
|
|
69
83
|
const reg = await loadRegistry();
|
|
84
|
+
const latestMessageTs =
|
|
85
|
+
(await loadRooms()).find((room) => room.id === roomId)?.messages.at(-1)
|
|
86
|
+
?.createdAt ?? 0;
|
|
70
87
|
const regRoom = (reg[roomId] =
|
|
71
88
|
reg[roomId] ?? Object.create(null) as Record<string, RegistryEntry>);
|
|
72
89
|
regRoom[sessionID] = {
|
|
73
90
|
serverUrl: selfServerUrl,
|
|
74
91
|
apiPrefix: "/api",
|
|
75
92
|
name,
|
|
93
|
+
directory: selfDirectory || undefined,
|
|
76
94
|
// ponytail: re-join must not rewind the read watermark (unread
|
|
77
95
|
// messages before the re-join would be silently dropped); a first
|
|
78
96
|
// join starts reading at join time
|
|
79
|
-
lastReadTs:
|
|
97
|
+
lastReadTs:
|
|
98
|
+
regRoom[sessionID]?.lastReadTs ??
|
|
99
|
+
Math.max(Date.now(), latestMessageTs),
|
|
80
100
|
};
|
|
81
101
|
await saveRegistry(reg);
|
|
82
102
|
} catch {
|
|
@@ -115,9 +135,12 @@ async function logNotify(
|
|
|
115
135
|
): Promise<void> {
|
|
116
136
|
const lines = results.map((r) => {
|
|
117
137
|
const head = `[${timeOf(Date.now())}] room=${roomId}`;
|
|
118
|
-
|
|
138
|
+
if (r.status === "rejected") {
|
|
139
|
+
return `${head} FAIL ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`;
|
|
140
|
+
}
|
|
141
|
+
return r.value.status >= 200 && r.value.status < 300
|
|
119
142
|
? `${head} OK ${r.value.status} ${r.value.url}`
|
|
120
|
-
: `${head} FAIL ${r.
|
|
143
|
+
: `${head} FAIL ${r.value.status} ${r.value.url}`;
|
|
121
144
|
});
|
|
122
145
|
await fs
|
|
123
146
|
.appendFile(notifyPath(), lines.join("\n") + "\n", "utf8")
|
|
@@ -129,7 +152,7 @@ async function bumpLastRead(
|
|
|
129
152
|
roomId: string,
|
|
130
153
|
sessionID: string,
|
|
131
154
|
ts: number,
|
|
132
|
-
): Promise<
|
|
155
|
+
): Promise<boolean> {
|
|
133
156
|
return enqueue(async () => {
|
|
134
157
|
try {
|
|
135
158
|
const reg = await loadRegistry();
|
|
@@ -138,9 +161,13 @@ async function bumpLastRead(
|
|
|
138
161
|
// never rewind: an older in-flight push must not lower the watermark
|
|
139
162
|
entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
|
|
140
163
|
await saveRegistry(reg);
|
|
164
|
+
clearPendingAdmission(sessionID, roomId, ts);
|
|
165
|
+
return true;
|
|
141
166
|
}
|
|
167
|
+
return false;
|
|
142
168
|
} catch {
|
|
143
169
|
// best-effort: an unpromoted read position only means poll repeats
|
|
170
|
+
return false;
|
|
144
171
|
}
|
|
145
172
|
});
|
|
146
173
|
}
|
|
@@ -148,69 +175,191 @@ async function bumpLastRead(
|
|
|
148
175
|
// ponytail: one push carries EVERY unread message for the target (not just
|
|
149
176
|
// the latest), so advancing the watermark on success never skips a message
|
|
150
177
|
// whose earlier push failed. Event-only pushes (empty messages) don't bump.
|
|
151
|
-
|
|
178
|
+
type NotifyBatch = {
|
|
179
|
+
roomId: string;
|
|
180
|
+
roomName: string;
|
|
181
|
+
messages: Message[];
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
type NotifyAttempt = { url: string; status: number };
|
|
185
|
+
|
|
186
|
+
type NotifyTargetQueue = {
|
|
187
|
+
latest: NotifyBatch | undefined;
|
|
188
|
+
latestTs: number;
|
|
189
|
+
running: Promise<NotifyAttempt[]>;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const notifyQueues = new Map<string, NotifyTargetQueue>();
|
|
193
|
+
|
|
194
|
+
function notifyBatchMaxTs(batch: NotifyBatch): number {
|
|
195
|
+
return batch.messages.reduce(
|
|
196
|
+
(maxTs, message) => Math.max(maxTs, message.createdAt),
|
|
197
|
+
0,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function notifyTarget(
|
|
202
|
+
sessionID: string,
|
|
203
|
+
batch: NotifyBatch,
|
|
204
|
+
): Promise<NotifyAttempt | undefined> {
|
|
205
|
+
const reg = await loadRegistry();
|
|
206
|
+
const entry = reg[batch.roomId]?.[sessionID];
|
|
207
|
+
if (!entry?.serverUrl) {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
const unread = batch.messages.filter(
|
|
211
|
+
(m) =>
|
|
212
|
+
m.createdAt > (entry.lastReadTs ?? 0) &&
|
|
213
|
+
(m.senderSessionID !== undefined
|
|
214
|
+
? m.senderSessionID !== sessionID
|
|
215
|
+
: m.senderId !== entry.name),
|
|
216
|
+
);
|
|
217
|
+
const { lines, capped } = formatNotificationLines(unread);
|
|
218
|
+
const prompt =
|
|
219
|
+
unread.length > 0
|
|
220
|
+
? `<notification>\nNew messages in room ${batch.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`
|
|
221
|
+
: `<notification>\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
222
|
+
const maxTs = unread.reduce(
|
|
223
|
+
(mx, message) => Math.max(mx, message.createdAt),
|
|
224
|
+
0,
|
|
225
|
+
);
|
|
226
|
+
const admissionItems = unread.length > 0 ? unread : batch.messages.slice(-1);
|
|
227
|
+
const admission = getOrCreatePendingAdmission(
|
|
228
|
+
sessionID,
|
|
229
|
+
batch.roomId,
|
|
230
|
+
admissionItems,
|
|
231
|
+
prompt,
|
|
232
|
+
maxTs,
|
|
233
|
+
capped,
|
|
234
|
+
);
|
|
235
|
+
const base = new URL(entry.serverUrl);
|
|
236
|
+
const prefix = (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "");
|
|
237
|
+
const url = `${base.origin}/${prefix}/session/${sessionID}/prompt`;
|
|
238
|
+
if (admission.state === "admitted") {
|
|
239
|
+
if (admission.capped) {
|
|
240
|
+
if (maxTs <= admission.maxTs) {
|
|
241
|
+
return { url, status: 200 };
|
|
242
|
+
}
|
|
243
|
+
} else {
|
|
244
|
+
if (admission.maxTs <= 0) {
|
|
245
|
+
return { url, status: 200 };
|
|
246
|
+
}
|
|
247
|
+
await bumpLastRead(batch.roomId, sessionID, admission.maxTs);
|
|
248
|
+
return { url, status: 200 };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const result = await sendQueue(
|
|
252
|
+
{
|
|
253
|
+
...queueTransport,
|
|
254
|
+
serverUrl: entry.serverUrl,
|
|
255
|
+
directory: entry.directory ?? queueTransport.directory,
|
|
256
|
+
},
|
|
257
|
+
sessionID,
|
|
258
|
+
admission.prompt,
|
|
259
|
+
admission.id,
|
|
260
|
+
);
|
|
261
|
+
if (result !== "delivered") {
|
|
262
|
+
if (result === "rejected") {
|
|
263
|
+
rejectPendingAdmission(sessionID, batch.roomId, admission.id);
|
|
264
|
+
}
|
|
265
|
+
return { url, status: result === "unreachable" ? 0 : 400 };
|
|
266
|
+
}
|
|
267
|
+
markPendingAdmissionAdmitted(sessionID, batch.roomId, admission.id);
|
|
268
|
+
if (admission.maxTs > 0 && !admission.capped) {
|
|
269
|
+
await bumpLastRead(batch.roomId, sessionID, admission.maxTs);
|
|
270
|
+
}
|
|
271
|
+
return { url, status: 200 };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function queueNotifyTarget(
|
|
275
|
+
sessionID: string,
|
|
276
|
+
batch: NotifyBatch,
|
|
277
|
+
): Promise<NotifyAttempt[]> {
|
|
278
|
+
const key = JSON.stringify([batch.roomId, sessionID]);
|
|
279
|
+
const existing = notifyQueues.get(key);
|
|
280
|
+
if (existing) {
|
|
281
|
+
const maxTs = notifyBatchMaxTs(batch);
|
|
282
|
+
if (maxTs > existing.latestTs) {
|
|
283
|
+
existing.latest = batch;
|
|
284
|
+
existing.latestTs = maxTs;
|
|
285
|
+
}
|
|
286
|
+
return existing.running;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const state: NotifyTargetQueue = {
|
|
290
|
+
latest: batch,
|
|
291
|
+
latestTs: notifyBatchMaxTs(batch),
|
|
292
|
+
running: Promise.resolve([] as NotifyAttempt[]),
|
|
293
|
+
};
|
|
294
|
+
const running = (async (): Promise<NotifyAttempt[]> => {
|
|
295
|
+
const attempts: NotifyAttempt[] = [];
|
|
296
|
+
let failed = false;
|
|
297
|
+
let firstError: unknown;
|
|
298
|
+
while (state.latest) {
|
|
299
|
+
const current = state.latest;
|
|
300
|
+
state.latest = undefined;
|
|
301
|
+
try {
|
|
302
|
+
const attempt = await notifyTarget(sessionID, current);
|
|
303
|
+
if (attempt) {
|
|
304
|
+
attempts.push(attempt);
|
|
305
|
+
}
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (!failed) {
|
|
308
|
+
firstError = error;
|
|
309
|
+
failed = true;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (failed) {
|
|
314
|
+
throw firstError;
|
|
315
|
+
}
|
|
316
|
+
return attempts;
|
|
317
|
+
})();
|
|
318
|
+
state.running = running;
|
|
319
|
+
notifyQueues.set(key, state);
|
|
320
|
+
const cleanup = () => {
|
|
321
|
+
if (notifyQueues.get(key) === state) {
|
|
322
|
+
notifyQueues.delete(key);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
void running.then(cleanup, cleanup);
|
|
326
|
+
return running;
|
|
327
|
+
}
|
|
328
|
+
|
|
152
329
|
async function notifyRoom(
|
|
153
330
|
roomId: string,
|
|
154
331
|
roomName: string,
|
|
155
|
-
|
|
332
|
+
_body: string,
|
|
156
333
|
selfSessionID: string,
|
|
157
334
|
messages: Message[],
|
|
158
335
|
): Promise<void> {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
headers: {
|
|
181
|
-
"Content-Type": "application/json",
|
|
182
|
-
...(auth ? { Authorization: auth } : {}),
|
|
183
|
-
},
|
|
184
|
-
body: JSON.stringify({ prompt, delivery: "queue" }),
|
|
185
|
-
});
|
|
186
|
-
return {
|
|
187
|
-
url,
|
|
188
|
-
status: res.status,
|
|
189
|
-
sessionID,
|
|
190
|
-
// ponytail: a capped push must not advance the watermark — the
|
|
191
|
-
// folded-out messages would become permanently unreadable
|
|
192
|
-
maxTs:
|
|
193
|
-
unread.length > 0 && !capped
|
|
194
|
-
? Math.max(...unread.map((m) => m.createdAt))
|
|
195
|
-
: undefined,
|
|
196
|
-
};
|
|
197
|
-
}),
|
|
198
|
-
);
|
|
199
|
-
// mark pushed messages as read only on 2xx; a failed push stays unread
|
|
200
|
-
// so the receiver's next poll picks it up
|
|
201
|
-
for (const r of results) {
|
|
202
|
-
if (
|
|
203
|
-
r.status === "fulfilled" &&
|
|
204
|
-
r.value.status >= 200 &&
|
|
205
|
-
r.value.status < 300 &&
|
|
206
|
-
r.value.maxTs !== undefined
|
|
207
|
-
) {
|
|
208
|
-
void bumpLastRead(roomId, r.value.sessionID, r.value.maxTs);
|
|
336
|
+
const reg = await loadRegistry();
|
|
337
|
+
const targets = Object.entries(reg[roomId] ?? {}).filter(
|
|
338
|
+
([sessionID, entry]) => sessionID !== selfSessionID && entry.serverUrl,
|
|
339
|
+
);
|
|
340
|
+
const batch: NotifyBatch = { roomId, roomName, messages };
|
|
341
|
+
const results = await Promise.allSettled(
|
|
342
|
+
targets.map(([sessionID]) => queueNotifyTarget(sessionID, batch)),
|
|
343
|
+
);
|
|
344
|
+
const logResults: PromiseSettledResult<NotifyAttempt>[] = [];
|
|
345
|
+
let failed = false;
|
|
346
|
+
let firstError: unknown;
|
|
347
|
+
for (const result of results) {
|
|
348
|
+
if (result.status === "fulfilled") {
|
|
349
|
+
for (const attempt of result.value) {
|
|
350
|
+
logResults.push({ status: "fulfilled", value: attempt });
|
|
351
|
+
}
|
|
352
|
+
} else {
|
|
353
|
+
logResults.push({ status: "rejected", reason: result.reason });
|
|
354
|
+
if (!failed) {
|
|
355
|
+
firstError = result.reason;
|
|
356
|
+
failed = true;
|
|
209
357
|
}
|
|
210
358
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
359
|
+
}
|
|
360
|
+
await logNotify(roomId, logResults);
|
|
361
|
+
if (failed) {
|
|
362
|
+
throw firstError;
|
|
214
363
|
}
|
|
215
364
|
}
|
|
216
365
|
|
|
@@ -232,7 +381,7 @@ const room = tool({
|
|
|
232
381
|
// (skipped for poll: poll itself pulls the inbox, so racing the
|
|
233
382
|
// fire-and-forget check would read the position it just advanced)
|
|
234
383
|
if (args.action !== "poll") {
|
|
235
|
-
void checkCenterInbox(centerOpts, context.sessionID,
|
|
384
|
+
void checkCenterInbox(centerOpts, context.sessionID, queueTransport);
|
|
236
385
|
}
|
|
237
386
|
return await centerAction(centerOpts, args, context.sessionID);
|
|
238
387
|
}
|
|
@@ -316,7 +465,7 @@ const room = tool({
|
|
|
316
465
|
NOTIFY_INSTRUCTION,
|
|
317
466
|
context.sessionID,
|
|
318
467
|
room.messages,
|
|
319
|
-
);
|
|
468
|
+
).catch(() => {});
|
|
320
469
|
}
|
|
321
470
|
return formatRoom(svc, room);
|
|
322
471
|
}
|
|
@@ -338,7 +487,7 @@ const room = tool({
|
|
|
338
487
|
NOTIFY_INSTRUCTION,
|
|
339
488
|
context.sessionID,
|
|
340
489
|
room.messages,
|
|
341
|
-
);
|
|
490
|
+
).catch(() => {});
|
|
342
491
|
}
|
|
343
492
|
leftRoomId = args.roomId;
|
|
344
493
|
return `left room ${args.roomId}`;
|
|
@@ -371,7 +520,12 @@ const room = tool({
|
|
|
371
520
|
if (!args.text?.trim()) {
|
|
372
521
|
return "error: text is required";
|
|
373
522
|
}
|
|
374
|
-
const msg = svc.sendMessage(
|
|
523
|
+
const msg = svc.sendMessage(
|
|
524
|
+
args.roomId,
|
|
525
|
+
selfName,
|
|
526
|
+
args.text,
|
|
527
|
+
context.sessionID,
|
|
528
|
+
);
|
|
375
529
|
const room = svc.getRoom(args.roomId);
|
|
376
530
|
void notifyRoom(
|
|
377
531
|
args.roomId,
|
|
@@ -379,7 +533,7 @@ const room = tool({
|
|
|
379
533
|
NOTIFY_INSTRUCTION,
|
|
380
534
|
context.sessionID,
|
|
381
535
|
room.messages,
|
|
382
|
-
);
|
|
536
|
+
).catch(() => {});
|
|
383
537
|
return `sent: ${args.text}\n${formatRoom(svc, room)}`;
|
|
384
538
|
}
|
|
385
539
|
case "poll": {
|
|
@@ -446,8 +600,11 @@ async function config(cfg: any) {
|
|
|
446
600
|
|
|
447
601
|
export default {
|
|
448
602
|
id: "chat-room",
|
|
449
|
-
server: async (input:
|
|
450
|
-
|
|
603
|
+
server: async (input: PluginInput) => {
|
|
604
|
+
queueTransport = createQueueTransport(input);
|
|
605
|
+
selfServerUrl = queueTransport.serverUrl ?? "";
|
|
606
|
+
selfDirectory = input.directory;
|
|
607
|
+
centerOpts.directory = selfDirectory;
|
|
451
608
|
if (centerUrl) {
|
|
452
609
|
// ponytail: in-process wake watcher — sweep the central server every
|
|
453
610
|
// 10s and self-push queue notifications to any session (including
|
|
@@ -457,9 +614,9 @@ export default {
|
|
|
457
614
|
if (wakeTimer) {
|
|
458
615
|
clearInterval(wakeTimer); // HMR/reload must not accumulate timers
|
|
459
616
|
}
|
|
460
|
-
void wakeSessions(centerOpts,
|
|
617
|
+
void wakeSessions(centerOpts, queueTransport, serveWakeUrl);
|
|
461
618
|
wakeTimer = setInterval(() => {
|
|
462
|
-
void wakeSessions(centerOpts,
|
|
619
|
+
void wakeSessions(centerOpts, queueTransport, serveWakeUrl);
|
|
463
620
|
}, 10000);
|
|
464
621
|
}
|
|
465
622
|
return {
|
|
@@ -477,7 +634,7 @@ export default {
|
|
|
477
634
|
void checkCenterInbox(
|
|
478
635
|
centerOpts,
|
|
479
636
|
input.sessionID,
|
|
480
|
-
|
|
637
|
+
queueTransport,
|
|
481
638
|
);
|
|
482
639
|
},
|
|
483
640
|
}
|