@alexsun-top/opencode-chat-room 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -0
- package/README.zh-CN.md +121 -0
- package/cli.ts +5 -0
- package/index.ts +9 -0
- package/package.json +47 -0
- package/plugin.ts +487 -0
- package/server/chat-server.ts +554 -0
- package/server/chat.html +1856 -0
- package/src/center-client.ts +530 -0
- package/src/room-service.ts +169 -0
- package/src/store.ts +237 -0
package/src/store.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// ponytail: shared primitives for the chat room plugin — file persistence
|
|
2
|
+
// (rooms + registry), identity, and formatting. Used by plugin.ts (standalone
|
|
3
|
+
// mode) and server/chat-server.ts (central mode).
|
|
4
|
+
import { promises as fs } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import RoomService, { type Message, type Room } from "./room-service";
|
|
8
|
+
|
|
9
|
+
export function statePath(): string {
|
|
10
|
+
// ponytail: shared mount for multi-host rooms (NFS/sshfs); default is local
|
|
11
|
+
if (process.env.CHAT_ROOM_STATE_DIR) {
|
|
12
|
+
return path.join(process.env.CHAT_ROOM_STATE_DIR, "rooms.json");
|
|
13
|
+
}
|
|
14
|
+
const base =
|
|
15
|
+
process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config");
|
|
16
|
+
return path.join(base, "opencode", "chat-room", "rooms.json");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// ponytail: in-process serialization of load->mutate->save; cross-process
|
|
20
|
+
// concurrent writers are still last-writer-wins (unique tmp name below makes
|
|
21
|
+
// the failure clean instead of mis-assigned)
|
|
22
|
+
let storeQueue: Promise<unknown> = Promise.resolve();
|
|
23
|
+
|
|
24
|
+
export function enqueue<T>(fn: () => Promise<T>): Promise<T> {
|
|
25
|
+
const run = storeQueue.then(fn);
|
|
26
|
+
storeQueue = run.catch(() => {});
|
|
27
|
+
return run;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function loadRooms(): Promise<Room[]> {
|
|
31
|
+
const file = statePath();
|
|
32
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
33
|
+
let raw: string;
|
|
34
|
+
try {
|
|
35
|
+
raw = await fs.readFile(file, "utf8");
|
|
36
|
+
} catch (err) {
|
|
37
|
+
const code = (err as { code?: unknown } | undefined)?.code;
|
|
38
|
+
if (code === "ENOENT") {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
throw err;
|
|
42
|
+
}
|
|
43
|
+
let data: unknown;
|
|
44
|
+
try {
|
|
45
|
+
data = JSON.parse(raw);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
// ponytail: corrupt file -> back it up and start fresh instead of bricking the tool
|
|
48
|
+
await fs.rename(file, `${file}.corrupt-${Date.now()}`).catch(() => {});
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
if (!Array.isArray(data)) {
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
return data.flatMap((entry): Room[] => {
|
|
55
|
+
if (entry === null || typeof entry !== "object") {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
const r = entry as Record<string, unknown>;
|
|
59
|
+
const room: Room = {
|
|
60
|
+
id: String(r.id ?? ""),
|
|
61
|
+
name: String(r.name ?? ""),
|
|
62
|
+
ownerId: String(r.ownerId ?? ""),
|
|
63
|
+
createdAt: Number(r.createdAt ?? 0),
|
|
64
|
+
participants: new Map(),
|
|
65
|
+
messages: [],
|
|
66
|
+
};
|
|
67
|
+
if (!room.id) {
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
if (Array.isArray(r.participants)) {
|
|
71
|
+
for (const p of r.participants) {
|
|
72
|
+
if (p && typeof p.id === "string" && typeof p.name === "string") {
|
|
73
|
+
room.participants.set(p.id, p);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (Array.isArray(r.messages)) {
|
|
78
|
+
// ponytail: keep only well-formed entries so one corrupt message
|
|
79
|
+
// can't crash formatting (or lose a pending send)
|
|
80
|
+
room.messages = (r.messages as Message[]).filter(
|
|
81
|
+
(m) =>
|
|
82
|
+
m !== null &&
|
|
83
|
+
typeof m === "object" &&
|
|
84
|
+
typeof m.id === "string" &&
|
|
85
|
+
typeof m.roomId === "string" &&
|
|
86
|
+
typeof m.senderId === "string" &&
|
|
87
|
+
typeof m.text === "string" &&
|
|
88
|
+
typeof m.createdAt === "number",
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
return [room];
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function saveRooms(svc: RoomService): Promise<void> {
|
|
96
|
+
const file = statePath();
|
|
97
|
+
const data = svc.listRooms().map((r) => ({
|
|
98
|
+
id: r.id,
|
|
99
|
+
name: r.name,
|
|
100
|
+
ownerId: r.ownerId,
|
|
101
|
+
createdAt: r.createdAt,
|
|
102
|
+
participants: [...r.participants.values()],
|
|
103
|
+
messages: r.messages,
|
|
104
|
+
}));
|
|
105
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
106
|
+
await fs.writeFile(tmp, JSON.stringify(data, null, 2), "utf8");
|
|
107
|
+
await fs.rename(tmp, file);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export type RegistryEntry = {
|
|
111
|
+
serverUrl: string;
|
|
112
|
+
apiPrefix: string;
|
|
113
|
+
name: string;
|
|
114
|
+
lastReadTs?: number;
|
|
115
|
+
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行;web 条目不填
|
|
116
|
+
host?: string;
|
|
117
|
+
};
|
|
118
|
+
export type Registry = Record<string, Record<string, RegistryEntry>>;
|
|
119
|
+
|
|
120
|
+
function registryPath(): string {
|
|
121
|
+
return path.join(path.dirname(statePath()), "registry.json");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function loadRegistry(): Promise<Registry> {
|
|
125
|
+
const file = registryPath();
|
|
126
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
127
|
+
let raw: string;
|
|
128
|
+
try {
|
|
129
|
+
raw = await fs.readFile(file, "utf8");
|
|
130
|
+
} catch (err) {
|
|
131
|
+
const code = (err as { code?: unknown } | undefined)?.code;
|
|
132
|
+
if (code === "ENOENT") {
|
|
133
|
+
return {};
|
|
134
|
+
}
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
let data: unknown;
|
|
138
|
+
try {
|
|
139
|
+
data = JSON.parse(raw);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
// ponytail: corrupt file -> back it up and start fresh instead of bricking the tool
|
|
142
|
+
await fs.rename(file, `${file}.corrupt-${Date.now()}`).catch(() => {});
|
|
143
|
+
return {};
|
|
144
|
+
}
|
|
145
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) {
|
|
146
|
+
return {};
|
|
147
|
+
}
|
|
148
|
+
// ponytail: null-proto at both levels so hostile keys ("__proto__",
|
|
149
|
+
// "constructor") can't touch Object.prototype or shadow lookups
|
|
150
|
+
const reg = Object.assign(Object.create(null), data);
|
|
151
|
+
for (const key of Object.keys(reg)) {
|
|
152
|
+
const room = reg[key] as Record<string, unknown> | undefined;
|
|
153
|
+
if (room !== null && typeof room === "object" && !Array.isArray(room)) {
|
|
154
|
+
reg[key] = Object.assign(Object.create(null), room);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return reg as Registry;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function saveRegistry(reg: Registry): Promise<void> {
|
|
161
|
+
const file = registryPath();
|
|
162
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
163
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
164
|
+
await fs.writeFile(tmp, JSON.stringify(reg, null, 2), "utf8");
|
|
165
|
+
await fs.rename(tmp, file);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function identity(name?: string): string {
|
|
169
|
+
// ponytail: cap the resolved identity so long-hostname defaults can't hit
|
|
170
|
+
// the central server's 64-char name limit on a path the user never typed
|
|
171
|
+
return (name || `${os.userInfo().username}@${os.hostname()}`).slice(0, 64);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ponytail: shared trailing instruction for push notifications
|
|
175
|
+
export const NOTIFY_INSTRUCTION =
|
|
176
|
+
"This is an automatic chat-room notification. Do NOT reply, do NOT call any tools, do NOT interrupt your current work, unless you are explicitly addressed (mentioned by name) or genuinely need to respond.";
|
|
177
|
+
|
|
178
|
+
// ponytail: 唤醒已退出 session 的消息(serve /session/:id/message 的 parts
|
|
179
|
+
// 文本)——客户端(center-client)与服务器(chat-server)共享
|
|
180
|
+
export const SERVE_WAKE_PROMPT =
|
|
181
|
+
"You were woken because you were mentioned (@) in the chat room. Use the room tool to poll the room(s) you are a member of, read the new messages, and reply to anything addressed to you. Then report what you did.";
|
|
182
|
+
|
|
183
|
+
// ponytail: oversize protection for push payloads — truncate long texts and
|
|
184
|
+
// cap the number of unread lines per notification
|
|
185
|
+
const MAX_LINE = 300;
|
|
186
|
+
const MAX_LINES = 20;
|
|
187
|
+
|
|
188
|
+
// Display lines for a push. `capped` means older unread messages were folded
|
|
189
|
+
// into a count line — callers must NOT advance the recipient's read
|
|
190
|
+
// watermark when capped, so uncapped poll remains the lossless catch-up path.
|
|
191
|
+
export function formatNotificationLines(
|
|
192
|
+
items: ReadonlyArray<{ createdAt: number; senderId: string; text: string }>,
|
|
193
|
+
): { lines: string[]; capped: boolean } {
|
|
194
|
+
const capped = items.length > MAX_LINES;
|
|
195
|
+
const lines = items.slice(-MAX_LINES).map((it) => {
|
|
196
|
+
const text =
|
|
197
|
+
it.text.length > MAX_LINE ? `${it.text.slice(0, MAX_LINE)}\u2026` : it.text;
|
|
198
|
+
return `- [${timeOf(it.createdAt)}] ${it.senderId}: ${text}`;
|
|
199
|
+
});
|
|
200
|
+
if (capped) {
|
|
201
|
+
lines.unshift(`\u2026 and ${items.length - MAX_LINES} earlier messages`);
|
|
202
|
+
}
|
|
203
|
+
return { lines, capped };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function authHeader(): string {
|
|
207
|
+
const pwd = process.env.OPENCODE_SERVER_PASSWORD;
|
|
208
|
+
if (!pwd) {
|
|
209
|
+
return "";
|
|
210
|
+
}
|
|
211
|
+
return `Basic ${Buffer.from(
|
|
212
|
+
`${process.env.OPENCODE_SERVER_USERNAME ?? "opencode"}:${pwd}`,
|
|
213
|
+
).toString("base64")}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function timeOf(ts: number): string {
|
|
217
|
+
return new Date(ts).toLocaleTimeString("en-US", { hour12: false });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function senderName(svc: RoomService, m: Message): string {
|
|
221
|
+
return (
|
|
222
|
+
svc.getParticipants(m.roomId).find((p) => p.id === m.senderId)?.name ??
|
|
223
|
+
m.senderId
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function formatRoom(svc: RoomService, room: Room): string {
|
|
228
|
+
const members = svc
|
|
229
|
+
.getParticipants(room.id)
|
|
230
|
+
.map((p) => p.name)
|
|
231
|
+
.join(", ");
|
|
232
|
+
const lines = [`Room ${room.id} (${room.name}) \u2014 members: ${members}`];
|
|
233
|
+
for (const m of room.messages.slice(-5)) {
|
|
234
|
+
lines.push(`[${timeOf(m.createdAt)}] ${senderName(svc, m)}: ${m.text}`);
|
|
235
|
+
}
|
|
236
|
+
return lines.join("\n");
|
|
237
|
+
}
|