@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.
@@ -0,0 +1,92 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, mkdirSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ const databases = new Map<string, Database>();
7
+ const pause = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
+ export function receiverStateDirectory(): string {
9
+ const configured = process.env.XDG_STATE_HOME;
10
+ const base = configured && path.isAbsolute(configured) ? configured : path.join(os.homedir(), ".local", "state");
11
+ return path.join(base, "opencode", "chat-room");
12
+ }
13
+ function database(): Database {
14
+ const file = path.join(receiverStateDirectory(), "receiver.sqlite");
15
+ let db = databases.get(file);
16
+ if (db) return db;
17
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
18
+ chmodSync(path.dirname(file), 0o700);
19
+ db = new Database(file, { create: true });
20
+ chmodSync(file, 0o600);
21
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=100; CREATE TABLE IF NOT EXISTS delivery_leases(session_id TEXT PRIMARY KEY,holder TEXT NOT NULL,expires_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS pending_admissions(session_id TEXT NOT NULL,room_id TEXT NOT NULL,admission TEXT NOT NULL,expires_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(session_id,room_id)); CREATE INDEX IF NOT EXISTS pending_admissions_expiry ON pending_admissions(expires_at); CREATE TABLE IF NOT EXISTS watcher_claims(identity TEXT PRIMARY KEY,instance_id TEXT NOT NULL,pid INTEGER NOT NULL);");
22
+ databases.set(file, db);
23
+ return db;
24
+ }
25
+ function immediate<T>(fn: (db: Database) => T): T {
26
+ const db = database();
27
+ for (let attempt = 0; ; attempt++) {
28
+ try { return db.transaction(() => fn(db)).immediate(); }
29
+ catch (error) {
30
+ const err = error as { code?: string };
31
+ if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
32
+ pause(Math.min(20 * 2 ** attempt, 250));
33
+ }
34
+ }
35
+ }
36
+
37
+ export function readPendingAdmission<T>(sessionID: string, roomID: string, now: number): T | undefined {
38
+ return immediate((db) => {
39
+ db.query("DELETE FROM pending_admissions WHERE expires_at<=?").run(now);
40
+ const row = db.query("SELECT admission FROM pending_admissions WHERE session_id=? AND room_id=?").get(sessionID, roomID) as { admission: string } | null;
41
+ return row ? JSON.parse(row.admission) as T : undefined;
42
+ });
43
+ }
44
+ export function savePendingAdmission(sessionID: string, roomID: string, value: unknown, expiresAt: number, now: number): void {
45
+ immediate((db) => {
46
+ db.query("DELETE FROM pending_admissions WHERE expires_at<=?").run(now);
47
+ db.query("INSERT INTO pending_admissions VALUES(?,?,?,?,?) ON CONFLICT(session_id,room_id) DO UPDATE SET admission=excluded.admission,expires_at=excluded.expires_at,updated_at=excluded.updated_at")
48
+ .run(sessionID, roomID, JSON.stringify(value), expiresAt, now);
49
+ db.query("DELETE FROM pending_admissions WHERE rowid IN (SELECT rowid FROM pending_admissions ORDER BY updated_at DESC LIMIT -1 OFFSET 1024)").run();
50
+ });
51
+ }
52
+ export function deletePendingAdmission(sessionID: string, roomID: string): void {
53
+ immediate((db) => db.query("DELETE FROM pending_admissions WHERE session_id=? AND room_id=?").run(sessionID, roomID));
54
+ }
55
+
56
+ export function acquireDeliveryLease(sessionID: string, holder: string, now: number, expiresAt: number): boolean {
57
+ return immediate((db) => {
58
+ db.query("DELETE FROM delivery_leases WHERE expires_at<=?").run(now);
59
+ return db.query("INSERT INTO delivery_leases VALUES(?,?,?) ON CONFLICT(session_id) DO UPDATE SET holder=excluded.holder,expires_at=excluded.expires_at WHERE delivery_leases.expires_at<=?")
60
+ .run(sessionID, holder, expiresAt, now).changes === 1;
61
+ });
62
+ }
63
+ export function renewDeliveryLease(sessionID: string, holder: string, now: number, expiresAt: number): boolean {
64
+ return immediate((db) => db.query("UPDATE delivery_leases SET expires_at=? WHERE session_id=? AND holder=? AND expires_at>?")
65
+ .run(expiresAt, sessionID, holder, now).changes === 1);
66
+ }
67
+ export function ownsDeliveryLease(sessionID: string, holder: string, now: number): boolean {
68
+ const row = database().query("SELECT 1 AS owned FROM delivery_leases WHERE session_id=? AND holder=? AND expires_at>?").get(sessionID, holder, now);
69
+ return Boolean(row);
70
+ }
71
+ export function releaseDeliveryLease(sessionID: string, holder: string): void {
72
+ immediate((db) => db.query("DELETE FROM delivery_leases WHERE session_id=? AND holder=?").run(sessionID, holder));
73
+ }
74
+ export function watcherProcessMayExist(pid: number): boolean {
75
+ try { process.kill(pid, 0); return true; }
76
+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
77
+ }
78
+ export function claimWatcher(identity: string, instanceID: string, pid: number): boolean {
79
+ return immediate((db) => {
80
+ const row = db.query("SELECT instance_id,pid FROM watcher_claims WHERE identity=?").get(identity) as { instance_id: string; pid: number } | null;
81
+ if (row && row.instance_id !== instanceID && watcherProcessMayExist(row.pid)) return false;
82
+ db.query("INSERT INTO watcher_claims VALUES(?,?,?) ON CONFLICT(identity) DO UPDATE SET instance_id=excluded.instance_id,pid=excluded.pid")
83
+ .run(identity, instanceID, pid);
84
+ return true;
85
+ });
86
+ }
87
+ export function releaseWatcherClaim(identity: string, instanceID: string): void {
88
+ immediate((db) => db.query("DELETE FROM watcher_claims WHERE identity=? AND instance_id=?").run(identity, instanceID));
89
+ }
90
+ export function closeReceiverState(): void {
91
+ for (const [file, db] of databases) { db.close(); databases.delete(file); }
92
+ }
@@ -42,14 +42,12 @@ export class RoomError extends Error {
42
42
  export default class RoomService {
43
43
  private rooms: Map<string, Room> = new Map();
44
44
 
45
- // ponytail: per-room history ceiling — everything above the watermark is
46
- // unreachable anyway; this bounds rooms.json and every serialized response
45
+ // Keep only a working window in memory; SQLite retains the full message history.
47
46
  static readonly MAX_MESSAGES = 500;
48
47
 
49
48
  hydrate(rooms: Room[]): void {
50
49
  for (const room of rooms) {
51
- // ponytail: cap pre-existing rooms.json files on load so an old
52
- // oversized file doesn't stay heavy until the next event
50
+ // Hydrated message arrays are only the in-memory working window.
53
51
  this.trimMessages(room);
54
52
  this.rooms.set(room.id, room);
55
53
  }
@@ -0,0 +1,51 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomUUID } from "node:crypto";
3
+ import { acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease, renewDeliveryLease } from "./receiver-state";
4
+
5
+ const LEASE_MS = 15_000;
6
+ const active = new AsyncLocalStorage<{ sessionID: string; holder: string; lost: boolean }>();
7
+ const queues = new Map<string, Promise<unknown>>();
8
+
9
+ async function withLease<T>(sessionID: string, task: () => Promise<T>): Promise<T | undefined> {
10
+ const holder = randomUUID();
11
+ const now = Date.now();
12
+ if (!acquireDeliveryLease(sessionID, holder, now, now + LEASE_MS)) return undefined;
13
+ const lease = { sessionID, holder, lost: false };
14
+ const timer = setInterval(() => {
15
+ if (lease.lost) return;
16
+ const at = Date.now();
17
+ try {
18
+ if (!renewDeliveryLease(sessionID, holder, at, at + LEASE_MS)) lease.lost = true;
19
+ } catch {
20
+ lease.lost = true;
21
+ }
22
+ if (lease.lost) clearInterval(timer);
23
+ }, LEASE_MS / 3);
24
+ timer.unref?.();
25
+ try { return await active.run(lease, task); }
26
+ finally {
27
+ lease.lost = true;
28
+ clearInterval(timer);
29
+ try { releaseDeliveryLease(sessionID, holder); } catch { /* Expiry lets another process reclaim a locked row. */ }
30
+ }
31
+ }
32
+
33
+ export function assertDeliveryLease(): void {
34
+ const lease = active.getStore();
35
+ if (!lease) return;
36
+ if (lease.lost) throw new Error("session delivery lease was lost");
37
+ try {
38
+ if (ownsDeliveryLease(lease.sessionID, lease.holder, Date.now())) return;
39
+ } catch { lease.lost = true; }
40
+ lease.lost = true;
41
+ throw new Error("session delivery lease was lost");
42
+ }
43
+
44
+ export function serializeSessionPush<T>(sessionID: string, task: () => Promise<T>): Promise<T | undefined> {
45
+ const previous = queues.get(sessionID) ?? Promise.resolve();
46
+ const run = previous.catch(() => {}).then(() => withLease(sessionID, task));
47
+ let current: Promise<T | undefined>;
48
+ current = run.finally(() => { if (queues.get(sessionID) === current) queues.delete(sessionID); });
49
+ queues.set(sessionID, current);
50
+ return current;
51
+ }
@@ -0,0 +1,265 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, mkdirSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import RoomService, { type Message, type Room, type Participant } from "./room-service";
5
+ import type { Registry, RegistryEntry } from "./store";
6
+
7
+ type State = { rooms: Room[]; registry: Registry };
8
+ type Page<T> = { items: T[]; hasMore: boolean };
9
+ const databases = new Map<string, Promise<Database>>();
10
+
11
+ function open(file: string): Promise<Database> {
12
+ const known = databases.get(file);
13
+ if (known) return known;
14
+ const pending = initialize(file);
15
+ databases.set(file, pending);
16
+ void pending.catch(() => databases.delete(file));
17
+ return pending;
18
+ }
19
+
20
+ async function initialize(file: string): Promise<Database> {
21
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
22
+ chmodSync(path.dirname(file), 0o700);
23
+ const db = new Database(file, { create: true });
24
+ chmodSync(file, 0o600);
25
+ try {
26
+ for (let attempt = 0; ; attempt++) {
27
+ try {
28
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; PRAGMA foreign_keys=ON;");
29
+ db.exec(`CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
30
+ CREATE TABLE IF NOT EXISTS rooms(id TEXT PRIMARY KEY,name TEXT NOT NULL,owner_id TEXT NOT NULL,created_at INTEGER NOT NULL);
31
+ CREATE TABLE IF NOT EXISTS participants(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,id TEXT NOT NULL,name TEXT NOT NULL,joined_at INTEGER NOT NULL,PRIMARY KEY(room_id,id));
32
+ CREATE TABLE IF NOT EXISTS messages(seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,sender_id TEXT NOT NULL,sender_session_id TEXT,text TEXT NOT NULL,created_at INTEGER NOT NULL);
33
+ CREATE INDEX IF NOT EXISTS messages_room_seq ON messages(room_id,seq DESC);
34
+ CREATE INDEX IF NOT EXISTS messages_room_time ON messages(room_id,created_at,seq);
35
+ CREATE TABLE IF NOT EXISTS registry(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,server_url TEXT NOT NULL,api_prefix TEXT NOT NULL,protocol TEXT,name TEXT NOT NULL,last_read_ts INTEGER,last_queued_ts INTEGER,directory TEXT,host TEXT,receiver_owner_id TEXT,PRIMARY KEY(room_id,session_id));`);
36
+ await migrate(db, file);
37
+ return db;
38
+ } catch (error) {
39
+ if (!isBusy(error) || attempt >= 7) throw error;
40
+ await pause(Math.min(20 * 2 ** attempt, 250));
41
+ }
42
+ }
43
+ } catch (error) { db.close(); throw error; }
44
+ }
45
+
46
+ function readLegacy(file: string): unknown | undefined {
47
+ try { return JSON.parse(readFileSync(file, "utf8")); }
48
+ catch (error) {
49
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
55
+ function isBusy(error: unknown): boolean {
56
+ const err = error as { code?: string; message?: string };
57
+ return err.code === "SQLITE_BUSY" || err.code === "SQLITE_LOCKED" || /database is locked/i.test(err.message ?? "");
58
+ }
59
+
60
+ async function immediate<T>(db: Database, fn: () => T): Promise<T> {
61
+ for (let attempt = 0; ; attempt++) {
62
+ try { return db.transaction(fn).immediate(); }
63
+ catch (error) {
64
+ if (!isBusy(error) || attempt >= 7) throw error;
65
+ await pause(Math.min(20 * 2 ** attempt, 250));
66
+ }
67
+ }
68
+ }
69
+
70
+ async function migrate(db: Database, file: string): Promise<void> {
71
+ if (db.query("SELECT value FROM meta WHERE key='json-migration'").get()) return;
72
+ const oldRooms = readLegacy(path.join(path.dirname(file), "rooms.json"));
73
+ const oldRegistry = readLegacy(path.join(path.dirname(file), "registry.json"));
74
+ const rooms = validateRooms(oldRooms);
75
+ const registry = validateRegistry(oldRegistry);
76
+ await immediate(db, () => {
77
+ if (db.query("SELECT value FROM meta WHERE key='json-migration'").get()) return;
78
+ for (const room of rooms) insertRoom(db, room);
79
+ replaceRegistry(db, registry);
80
+ db.query("INSERT INTO meta(key,value) VALUES('json-migration','done')").run();
81
+ });
82
+ }
83
+
84
+ function record(value: unknown): value is Record<string, unknown> {
85
+ return typeof value === "object" && value !== null && !Array.isArray(value);
86
+ }
87
+ function timestamp(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value) && value >= 0; }
88
+
89
+ function validateRooms(value: unknown): Room[] {
90
+ if (value === undefined) return [];
91
+ if (!Array.isArray(value)) throw new Error("Legacy rooms.json must contain an array");
92
+ return value.map((item) => {
93
+ if (!record(item) || typeof item.id !== "string" || !item.id || typeof item.name !== "string" ||
94
+ typeof item.ownerId !== "string" || !timestamp(item.createdAt) || !Array.isArray(item.participants) || !Array.isArray(item.messages)) {
95
+ throw new Error("Legacy rooms.json contains an invalid room");
96
+ }
97
+ const participants = new Map<string, Participant>();
98
+ for (const p of item.participants) {
99
+ if (!record(p) || typeof p.id !== "string" || typeof p.name !== "string" || !timestamp(p.joinedAt)) throw new Error("Legacy rooms.json contains an invalid participant");
100
+ participants.set(p.id, { id: p.id, name: p.name, joinedAt: p.joinedAt });
101
+ }
102
+ let previousTs = -1;
103
+ const messages = item.messages.map((m): Message => {
104
+ if (!record(m) || typeof m.id !== "string" || typeof m.roomId !== "string" || m.roomId !== item.id ||
105
+ typeof m.senderId !== "string" || typeof m.text !== "string" || !timestamp(m.createdAt) ||
106
+ m.createdAt <= previousTs || (m.senderSessionID !== undefined && typeof m.senderSessionID !== "string")) throw new Error("Legacy rooms.json contains an invalid message");
107
+ previousTs = m.createdAt;
108
+ return { id: m.id, roomId: m.roomId, senderId: m.senderId, text: m.text, createdAt: m.createdAt,
109
+ ...(m.senderSessionID !== undefined ? { senderSessionID: m.senderSessionID } : {}) };
110
+ });
111
+ return { id: item.id, name: item.name, ownerId: item.ownerId, createdAt: item.createdAt, participants, messages };
112
+ });
113
+ }
114
+
115
+ function validateRegistry(value: unknown): Registry {
116
+ if (value === undefined) return {};
117
+ if (!record(value)) throw new Error("Legacy registry.json must contain an object");
118
+ const result: Registry = Object.create(null);
119
+ for (const [roomId, members] of Object.entries(value)) {
120
+ if (!roomId || !record(members)) throw new Error("Legacy registry.json contains an invalid room");
121
+ result[roomId] = Object.create(null);
122
+ for (const [sessionID, raw] of Object.entries(members)) {
123
+ if (!sessionID || !record(raw) || typeof raw.serverUrl !== "string" || typeof raw.apiPrefix !== "string" ||
124
+ typeof raw.name !== "string" || (raw.protocol !== undefined && raw.protocol !== "v1" && raw.protocol !== "v2") ||
125
+ (["lastReadTs", "lastQueuedTs"].some((key) => raw[key] !== undefined && !timestamp(raw[key]))) ||
126
+ (["directory", "host", "receiverOwnerID"].some((key) => raw[key] !== undefined && typeof raw[key] !== "string"))) {
127
+ throw new Error("Legacy registry.json contains an invalid entry");
128
+ }
129
+ result[roomId]![sessionID] = { serverUrl: raw.serverUrl, apiPrefix: raw.apiPrefix, name: raw.name,
130
+ ...(raw.protocol ? { protocol: raw.protocol } : {}),
131
+ ...(timestamp(raw.lastReadTs) ? { lastReadTs: raw.lastReadTs } : {}),
132
+ ...(timestamp(raw.lastQueuedTs) ? { lastQueuedTs: raw.lastQueuedTs } : {}),
133
+ ...(typeof raw.directory === "string" ? { directory: raw.directory } : {}),
134
+ ...(typeof raw.host === "string" ? { host: raw.host } : {}),
135
+ ...(typeof raw.receiverOwnerID === "string" ? { receiverOwnerID: raw.receiverOwnerID } : {}) };
136
+ }
137
+ }
138
+ return result;
139
+ }
140
+
141
+ function insertRoom(db: Database, room: Room): void {
142
+ db.query("INSERT INTO rooms VALUES(?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt);
143
+ const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
144
+ for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
145
+ const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
146
+ for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
147
+ }
148
+
149
+ function replaceRegistry(db: Database, registry: Registry): void {
150
+ db.exec("DELETE FROM registry");
151
+ const insert = db.query("INSERT INTO registry VALUES(?,?,?,?,?,?,?,?,?,?,?)");
152
+ for (const [roomID, members] of Object.entries(registry)) for (const [sessionID, r] of Object.entries(members)) {
153
+ insert.run(roomID, sessionID, r.serverUrl, r.apiPrefix, r.protocol ?? null, r.name,
154
+ r.lastReadTs ?? null, r.lastQueuedTs ?? null, r.directory ?? null, r.host ?? null, r.receiverOwnerID ?? null);
155
+ }
156
+ }
157
+
158
+ function persistState(db: Database, rooms: Room[], registry: Registry): void {
159
+ const roomRow = db.query("INSERT INTO rooms VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at");
160
+ const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
161
+ const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
162
+ const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
163
+ for (const room of rooms) {
164
+ roomRow.run(room.id, room.name, room.ownerId, room.createdAt);
165
+ removeParticipants.run(room.id);
166
+ for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
167
+ for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
168
+ }
169
+ replaceRegistry(db, registry);
170
+ }
171
+
172
+ function readState(db: Database): State {
173
+ const roomRows = db.query("SELECT id,name,owner_id,created_at FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number>>;
174
+ const rooms = roomRows.map((r): Room => {
175
+ const participants = new Map<string, Participant>();
176
+ for (const p of db.query("SELECT id,name,joined_at FROM participants WHERE room_id=?").all(String(r.id)) as Array<Record<string, string | number>>) {
177
+ participants.set(String(p.id), { id: String(p.id), name: String(p.name), joinedAt: Number(p.joined_at) });
178
+ }
179
+ const messages = db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 500").all(String(r.id)) as Array<Record<string, string | number | null>>;
180
+ return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), participants,
181
+ messages: messages.reverse().map((m) => ({ id: String(m.id), roomId: String(m.room_id), senderId: String(m.sender_id),
182
+ text: String(m.text), createdAt: Number(m.created_at), ...(m.sender_session_id ? { senderSessionID: String(m.sender_session_id) } : {}) })) };
183
+ });
184
+ const registry: Registry = Object.create(null);
185
+ const rows = db.query("SELECT * FROM registry").all() as Array<Record<string, string | number | null>>;
186
+ for (const r of rows) (registry[String(r.room_id)] ??= Object.create(null))[String(r.session_id)] = {
187
+ serverUrl: String(r.server_url), apiPrefix: String(r.api_prefix), name: String(r.name),
188
+ ...(r.protocol ? { protocol: r.protocol as "v1" | "v2" } : {}),
189
+ ...(r.last_read_ts !== null ? { lastReadTs: Number(r.last_read_ts) } : {}),
190
+ ...(r.last_queued_ts !== null ? { lastQueuedTs: Number(r.last_queued_ts) } : {}),
191
+ ...(r.directory !== null ? { directory: String(r.directory) } : {}), ...(r.host !== null ? { host: String(r.host) } : {}),
192
+ ...(r.receiver_owner_id !== null ? { receiverOwnerID: String(r.receiver_owner_id) } : {}),
193
+ };
194
+ return { rooms, registry };
195
+ }
196
+
197
+ export type HistoryMessage = Message & { seq: number };
198
+ export async function writeSqliteState<T>(file: string, callback: (service: RoomService, registry: Registry) => T): Promise<T> {
199
+ const db = await open(file);
200
+ return immediate(db, () => {
201
+ const state = readState(db);
202
+ const service = new RoomService();
203
+ service.hydrate(state.rooms);
204
+ const result = callback(service, state.registry);
205
+ if (result && typeof (result as { then?: unknown }).then === "function") throw new Error("writeState callback must be synchronous");
206
+ persistState(db, service.listRooms(), state.registry);
207
+ return result;
208
+ });
209
+ }
210
+
211
+ export async function readSqliteState(file: string): Promise<State> {
212
+ const db = await open(file);
213
+ return db.transaction(() => readState(db)).deferred();
214
+ }
215
+
216
+ export async function readUnreadPage(file: string, roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false): Promise<Page<Message>> {
217
+ const db = await open(file);
218
+ const take = Math.min(200, Math.max(1, limit));
219
+ const rows = db.query(`SELECT id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? AND created_at>? AND
220
+ (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
221
+ ORDER BY created_at ${newest ? "DESC" : "ASC"},seq ${newest ? "DESC" : "ASC"} LIMIT ?`)
222
+ .all(roomID, afterTs, sessionID ?? null, sessionID ?? null, senderName ?? "", take + 1) as Array<Record<string, string | number | null>>;
223
+ const hasMore = rows.length > take;
224
+ const items = rows.slice(0, take).map(rowMessage);
225
+ return { items: newest ? items.reverse() : items, hasMore };
226
+ }
227
+
228
+ export async function readInboxPage(file: string, sessionID: string, roomFilter: string | null, excludeSelf: boolean, limit = 100) {
229
+ const db = await open(file);
230
+ return db.transaction(() => {
231
+ const take = Math.min(200, Math.max(1, limit));
232
+ const members = db.query("SELECT room_id,last_queued_ts FROM registry WHERE session_id=? AND (? IS NULL OR room_id=?)").all(sessionID, roomFilter, roomFilter) as Array<{ room_id: string; last_queued_ts: number | null }>;
233
+ const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,r.name AS room_name
234
+ FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
235
+ WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
236
+ m.created_at > CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END AND
237
+ (?=0 OR (m.sender_session_id IS NOT NULL AND m.sender_session_id!=?) OR (m.sender_session_id IS NULL AND m.sender_id!=g.name))
238
+ ORDER BY m.created_at,m.seq LIMIT ?`).all(sessionID, roomFilter, roomFilter, excludeSelf ? 1 : 0,
239
+ excludeSelf ? 1 : 0, sessionID, take + 1) as Array<Record<string, string | number | null>>;
240
+ const hasMore = rows.length > take;
241
+ const items = rows.slice(0, take).map((row) => {
242
+ const { senderSessionID: _sessionID, ...message } = rowMessage(row);
243
+ return { ...message, roomName: String(row.room_name) };
244
+ });
245
+ const queuedTs = Object.fromEntries(members.map((member) => [member.room_id, member.last_queued_ts ?? 0]));
246
+ return { member: members.length > 0, items, queuedTs, hasMore };
247
+ }).deferred();
248
+ }
249
+
250
+ export async function readHistoryPage(file: string, roomID: string, beforeSeq?: number, limit = 100, excludeSessionID?: string, excludeName = ""): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
251
+ const db = await open(file);
252
+ const take = Math.min(200, Math.max(1, limit));
253
+ const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
254
+ (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
255
+ ORDER BY seq DESC LIMIT ?`).all(...(beforeSeq === undefined ? [roomID] : [roomID, beforeSeq]),
256
+ excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1) as Array<Record<string, string | number | null>>;
257
+ const hasMore = rows.length > take;
258
+ const messages = rows.slice(0, take).reverse().map((row) => ({ ...rowMessage(row), seq: Number(row.seq) }));
259
+ return { messages, nextBeforeSeq: hasMore ? messages[0]?.seq ?? null : null, hasMore };
260
+ }
261
+
262
+ function rowMessage(row: Record<string, string | number | null>): Message {
263
+ return { id: String(row.id), roomId: String(row.room_id), senderId: String(row.sender_id), text: String(row.text),
264
+ createdAt: Number(row.created_at), ...(row.sender_session_id !== null ? { senderSessionID: String(row.sender_session_id) } : {}) };
265
+ }
package/src/store.ts CHANGED
@@ -1,112 +1,42 @@
1
- // ponytail: shared primitives for the chat room plugin — file persistence
1
+ // Shared state facade for the standalone SQLite database.
2
2
  // (rooms + registry), identity, and formatting. Used by plugin.ts (standalone
3
3
  // mode) and server/chat-server.ts (central mode).
4
- import { promises as fs } from "node:fs";
5
4
  import path from "node:path";
6
5
  import os from "node:os";
7
6
  import RoomService, { type Message, type Room } from "./room-service";
7
+ import { readHistoryPage, readInboxPage as sqliteInboxPage, readSqliteState, readUnreadPage, writeSqliteState, type HistoryMessage } from "./sqlite-state";
8
8
 
9
9
  export function statePath(): string {
10
- // ponytail: shared mount for multi-host rooms (NFS/sshfs); default is local
10
+ // JSON path remains the migration source; SQLite lives beside it.
11
11
  if (process.env.CHAT_ROOM_STATE_DIR) {
12
12
  return path.join(process.env.CHAT_ROOM_STATE_DIR, "rooms.json");
13
13
  }
14
- const base =
15
- process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config");
14
+ const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
16
15
  return path.join(base, "opencode", "chat-room", "rooms.json");
17
16
  }
18
17
 
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;
18
+ export function databasePath(): string { return path.join(path.dirname(statePath()), "chat-room.sqlite"); }
19
+ export function writeState<T>(callback: (service: RoomService, registry: Registry) => T): Promise<T> {
20
+ return writeSqliteState(databasePath(), callback);
28
21
  }
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
- (m.senderSessionID === undefined ||
90
- typeof m.senderSessionID === "string"),
91
- );
92
- }
93
- return [room];
94
- });
22
+ export async function readState<T>(callback: (service: RoomService, registry: Registry) => T): Promise<T> {
23
+ const state = await readSqliteState(databasePath());
24
+ const service = new RoomService();
25
+ service.hydrate(state.rooms);
26
+ return callback(service, state.registry);
27
+ }
28
+ export async function readUnreadMessages(roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false) {
29
+ return readUnreadPage(databasePath(), roomID, afterTs, limit, sessionID, senderName, newest);
30
+ }
31
+ export async function readInboxMessages(sessionID: string, roomID: string | null, excludeSelf: boolean, limit = 100) {
32
+ return sqliteInboxPage(databasePath(), sessionID, roomID, excludeSelf, limit);
33
+ }
34
+ export async function readHistory(roomID: string, beforeSeq?: number, limit = 100, exclude?: { sessionID: string; name: string }): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
35
+ return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
95
36
  }
96
37
 
97
- export async function saveRooms(svc: RoomService): Promise<void> {
98
- const file = statePath();
99
- const data = svc.listRooms().map((r) => ({
100
- id: r.id,
101
- name: r.name,
102
- ownerId: r.ownerId,
103
- createdAt: r.createdAt,
104
- participants: [...r.participants.values()],
105
- messages: r.messages,
106
- }));
107
- const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
108
- await fs.writeFile(tmp, JSON.stringify(data, null, 2), "utf8");
109
- await fs.rename(tmp, file);
38
+ export async function loadRooms(): Promise<Room[]> {
39
+ return (await readSqliteState(databasePath())).rooms;
110
40
  }
111
41
 
112
42
  export type RegistryEntry = {
@@ -119,55 +49,12 @@ export type RegistryEntry = {
119
49
  directory?: string;
120
50
  // ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行;web 条目不填
121
51
  host?: string;
52
+ receiverOwnerID?: string;
122
53
  };
123
54
  export type Registry = Record<string, Record<string, RegistryEntry>>;
124
55
 
125
- function registryPath(): string {
126
- return path.join(path.dirname(statePath()), "registry.json");
127
- }
128
-
129
56
  export async function loadRegistry(): Promise<Registry> {
130
- const file = registryPath();
131
- await fs.mkdir(path.dirname(file), { recursive: true });
132
- let raw: string;
133
- try {
134
- raw = await fs.readFile(file, "utf8");
135
- } catch (err) {
136
- const code = (err as { code?: unknown } | undefined)?.code;
137
- if (code === "ENOENT") {
138
- return {};
139
- }
140
- throw err;
141
- }
142
- let data: unknown;
143
- try {
144
- data = JSON.parse(raw);
145
- } catch (err) {
146
- // ponytail: corrupt file -> back it up and start fresh instead of bricking the tool
147
- await fs.rename(file, `${file}.corrupt-${Date.now()}`).catch(() => {});
148
- return {};
149
- }
150
- if (data === null || typeof data !== "object" || Array.isArray(data)) {
151
- return {};
152
- }
153
- // ponytail: null-proto at both levels so hostile keys ("__proto__",
154
- // "constructor") can't touch Object.prototype or shadow lookups
155
- const reg = Object.assign(Object.create(null), data);
156
- for (const key of Object.keys(reg)) {
157
- const room = reg[key] as Record<string, unknown> | undefined;
158
- if (room !== null && typeof room === "object" && !Array.isArray(room)) {
159
- reg[key] = Object.assign(Object.create(null), room);
160
- }
161
- }
162
- return reg as Registry;
163
- }
164
-
165
- export async function saveRegistry(reg: Registry): Promise<void> {
166
- const file = registryPath();
167
- await fs.mkdir(path.dirname(file), { recursive: true });
168
- const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
169
- await fs.writeFile(tmp, JSON.stringify(reg, null, 2), "utf8");
170
- await fs.rename(tmp, file);
57
+ return (await readSqliteState(databasePath())).registry;
171
58
  }
172
59
 
173
60
  export function identity(name?: string): string {