@alexsun-top/opencode-chat-room 0.2.3 → 0.3.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.
@@ -4,21 +4,26 @@ import type { Message } from "./room-service";
4
4
  import {
5
5
  formatNotificationLines,
6
6
  loadRegistry,
7
+ loadRooms,
7
8
  NOTIFY_INSTRUCTION,
8
9
  statePath,
9
10
  timeOf,
10
11
  } from "./store";
11
- import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
12
- import { explicitlyMentions } from "./mentions";
12
+ import { backgroundResult, backgroundServiceKey, sendAsyncNotification, sendQueue, type BackgroundResult, type QueueTransport } from "./queue-transport";
13
+ import { explicitlyAddresses } from "./mentions";
14
+ import { claimBackgroundAttempt } from "./receiver-state";
13
15
  import { serializeSessionPush } from "./center-inbox";
14
16
  import {
15
17
  getOrCreatePendingAdmission,
18
+ clearPendingAdmission,
16
19
  markPendingAdmissionAdmitted,
17
20
  pendingAdmission,
18
21
  rejectPendingAdmission,
22
+ prunePendingAdmission,
23
+ type QueueItem,
19
24
  } from "./queue";
20
25
 
21
- type NotifyBatch = { roomId: string; roomName: string; messages: Message[] };
26
+ type NotifyBatch = { roomId: string; roomName: string; roomKind?: "group" | "direct"; messages: Message[] };
22
27
  type NotifyAttempt = { url: string; status: number };
23
28
  type TargetQueue = { latest?: NotifyBatch; latestTs: number; running: Promise<NotifyAttempt[]> };
24
29
 
@@ -40,6 +45,21 @@ export function createNotifier(deps: {
40
45
  await fs.appendFile(notifyPath(), lines.join("\n") + "\n", "utf8").catch(() => {});
41
46
  }
42
47
 
48
+ function render(batch: NotifyBatch, name: string, roomKind: "group" | "direct", items: QueueItem[]) {
49
+ const { lines, capped } = formatNotificationLines(items);
50
+ const context = roomKind === "direct" ? `Direct conversation with ${name} in room ${batch.roomName} (${batch.roomId})` : `New messages in room ${batch.roomName} (${batch.roomId})`;
51
+ return { prompt: `<notification>\n${context}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`, capped };
52
+ }
53
+
54
+ async function tryBackground(transport: QueueTransport, sessionID: string) {
55
+ try { return backgroundResult(await transport.backgroundSession!(sessionID)); }
56
+ catch { return { status: "failed" as const, reason: "request-threw" }; }
57
+ }
58
+
59
+ function logBackgroundResult(roomId: string, status: string, reason?: string) {
60
+ if (status !== "done") console.warn(`[chat-room] background ${status} room=${roomId} reason=${reason ?? "unknown"}`);
61
+ }
62
+
43
63
  async function notifyTarget(
44
64
  sessionID: string,
45
65
  batch: NotifyBatch,
@@ -54,25 +74,37 @@ export function createNotifier(deps: {
54
74
  batch: NotifyBatch,
55
75
  transport: QueueTransport,
56
76
  ): Promise<NotifyAttempt | undefined> {
57
- const entry = (await loadRegistry())[batch.roomId]?.[sessionID];
77
+ const [registry, rooms] = await Promise.all([loadRegistry(), loadRooms()]);
78
+ const entry = registry[batch.roomId]?.[sessionID];
79
+ const roomKind = batch.roomKind ?? rooms.find((room) => room.id === batch.roomId)?.kind ?? "group";
58
80
  if (!entry || (entry.protocol !== "v2" && !entry.serverUrl)) return undefined;
81
+ const protocol = entry.protocol ?? "v1";
82
+ if (protocol !== (transport.protocol ?? "v1") && !(transport.protocol === "v2" && protocol === "v1")) return undefined;
59
83
  const mentionOnly = transport.mentionOnlySessions?.has(sessionID) ?? false;
60
- if (transport.protocol === "v2" && entry.receiverOwnerID &&
61
- (entry.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
84
+ if (protocol === "v2" && (transport.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
62
85
  if (mentionOnly && (entry.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
86
+ const targetTransport = {
87
+ ...transport,
88
+ protocol,
89
+ serverUrl: entry.serverUrl,
90
+ directory: entry.directory ?? transport.directory,
91
+ };
92
+ const service = backgroundServiceKey(targetTransport);
93
+ const cutoff = Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0);
94
+ prunePendingAdmission(sessionID, batch.roomId, cutoff, (items) => render(batch, entry.name, roomKind, items));
63
95
  const unread = batch.messages.filter((m) =>
64
- m.createdAt > Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0) &&
65
- (m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== entry.name),
66
- ).slice(0, 20);
67
- if (!unread.length) return undefined;
68
- const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
96
+ m.createdAt > cutoff &&
97
+ (m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== (roomKind === "direct" ? sessionID : entry.name)),
98
+ ).slice(0, 20).map((item) => ({ ...item, roomKind }));
69
99
  const existing = pendingAdmission(sessionID, batch.roomId);
100
+ if (!unread.length && existing?.state !== "pending") return undefined;
101
+ const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
70
102
  const delta = existing?.state === "admitted" && maxTs > existing.maxTs
71
103
  ? unread.filter((m) => m.createdAt > existing.maxTs)
72
104
  : unread;
73
105
  const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
74
- if (mentionOnly && !eligibleItems.some((message) => explicitlyMentions(message, entry.name, sessionID)) &&
75
- !delta.slice(-20).some((message) => explicitlyMentions(message, entry.name, sessionID))) return undefined;
106
+ if (mentionOnly && !eligibleItems.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind)) &&
107
+ !delta.slice(-20).some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))) return undefined;
76
108
  const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
77
109
  const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
78
110
  const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
@@ -82,8 +114,7 @@ export function createNotifier(deps: {
82
114
  if (existing.maxTs > 0) await deps.bumpQueued(batch.roomId, sessionID, existing.maxTs);
83
115
  return { url, status: entry.protocol === "v2" ? 200 : 204 };
84
116
  }
85
- const { lines, capped } = formatNotificationLines(delta);
86
- const prompt = `<notification>\nNew messages in room ${batch.roomName} (${batch.roomId}):\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
117
+ const { prompt, capped } = render(batch, entry.name, roomKind, delta);
87
118
  const deltaTs = delta.reduce((max, m) => Math.max(max, m.createdAt), 0);
88
119
  const admission = getOrCreatePendingAdmission(
89
120
  sessionID, batch.roomId, delta, prompt, deltaTs, capped,
@@ -92,14 +123,29 @@ export function createNotifier(deps: {
92
123
  await deps.bumpQueued(batch.roomId, sessionID, admission.maxTs);
93
124
  return { url, status: entry.protocol === "v2" ? 200 : 204 };
94
125
  }
95
- const targetTransport = {
96
- ...transport,
97
- serverUrl: entry.serverUrl,
98
- directory: entry.directory ?? transport.directory,
99
- };
100
- const mentioned = entry.protocol === "v2" && admission.items.some((message) => explicitlyMentions(message, entry.name, sessionID));
101
- if (mentioned && targetTransport.backgroundSession) {
102
- try { await targetTransport.backgroundSession(sessionID); } catch { /* Steering does not depend on backgrounding. */ }
126
+ const addressedTs = admission.items.filter((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))
127
+ .reduce((max, message) => Math.max(max, message.createdAt), 0);
128
+ if (entry.protocol === "v2" && addressedTs > 0 && targetTransport.backgroundSession && claimBackgroundAttempt(
129
+ sessionID, batch.roomId, service, addressedTs,
130
+ )) {
131
+ const attempt = await tryBackground(targetTransport, sessionID);
132
+ logBackgroundResult(batch.roomId, attempt.status, attempt.reason);
133
+ }
134
+ const [currentRegistry, currentRooms] = await Promise.all([loadRegistry(), loadRooms()]);
135
+ const currentEntry = currentRegistry[batch.roomId]?.[sessionID];
136
+ const currentKind = currentRooms.find((room) => room.id === batch.roomId)?.kind ?? "group";
137
+ if (!currentEntry || (currentEntry.protocol ?? "v1") !== protocol || currentEntry.serverUrl !== entry.serverUrl ||
138
+ currentEntry.directory !== entry.directory ||
139
+ (protocol === "v2" && currentEntry.receiverOwnerID !== transport.receiverOwnerID) || currentKind !== roomKind) {
140
+ rejectPendingAdmission(sessionID, batch.roomId, admission.id);
141
+ clearPendingAdmission(sessionID, batch.roomId, Number.MAX_SAFE_INTEGER);
142
+ return undefined;
143
+ }
144
+ const currentCutoff = Math.max(currentEntry.lastReadTs ?? 0, currentEntry.lastQueuedTs ?? 0);
145
+ const currentAdmission = prunePendingAdmission(sessionID, batch.roomId, currentCutoff,
146
+ (items) => render(batch, entry.name, roomKind, items));
147
+ if (!currentAdmission || currentAdmission.id !== admission.id) {
148
+ return notifyTargetUnlocked(sessionID, batch, transport);
103
149
  }
104
150
  const result = entry.protocol === "v2"
105
151
  ? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id, "steer")
@@ -3,9 +3,10 @@ import { admissionMatches, type QueueBody } from "./queue";
3
3
  import { assertDeliveryLease } from "./session-delivery";
4
4
 
5
5
  export type PushResult = "delivered" | "unreachable" | "rejected";
6
+ export type BackgroundResult = { status: "done" | "failed" | "skip"; reason?: string };
6
7
  export type QueueTransport = {
7
8
  promptQueue?: (sessionID: string, id: string, text: string, delivery: "queue" | "steer") => Promise<unknown>;
8
- backgroundSession?: (sessionID: string) => Promise<boolean>;
9
+ backgroundSession?: (sessionID: string) => Promise<boolean | BackgroundResult>;
9
10
  receiverOwnerID?: string;
10
11
  verifySession?: (sessionID: string) => Promise<string | undefined>;
11
12
  mentionOnlySessions?: ReadonlySet<string>;
@@ -14,6 +15,21 @@ export type QueueTransport = {
14
15
  protocol?: "v1" | "v2";
15
16
  };
16
17
 
18
+ export function backgroundResult(value: boolean | BackgroundResult): BackgroundResult {
19
+ return typeof value === "boolean" ? value ? { status: "done" } : { status: "failed", reason: "unclassified-failure" } : value;
20
+ }
21
+
22
+ export function backgroundServiceKey(transport: QueueTransport, serviceURL = transport.serverUrl ?? ""): string {
23
+ let origin = serviceURL;
24
+ try {
25
+ if (serviceURL) {
26
+ const url = new URL(serviceURL);
27
+ origin = `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
28
+ }
29
+ } catch { /* Keep non-URL identifiers distinct. */ }
30
+ return JSON.stringify([transport.receiverOwnerID ?? "", origin]);
31
+ }
32
+
17
33
  export function createQueueTransport(input: { directory?: string; serverUrl?: URL | string } = {}): QueueTransport {
18
34
  const serverUrl = String(input.serverUrl ?? "").trim();
19
35
  return { serverUrl: serverUrl || undefined, protocol: "v1", directory: input.directory };
package/src/queue.ts CHANGED
@@ -8,6 +8,7 @@ export type QueueItem = {
8
8
  senderSessionID?: string;
9
9
  text: string;
10
10
  createdAt: number;
11
+ roomKind?: "group" | "direct";
11
12
  };
12
13
 
13
14
  export type QueueBody = {
@@ -19,6 +20,7 @@ export type QueueBody = {
19
20
 
20
21
  export type PendingAdmission = {
21
22
  id: string;
23
+ createdAt: number;
22
24
  prompt: string;
23
25
  itemCount: number;
24
26
  maxTs: number;
@@ -29,7 +31,8 @@ export type PendingAdmission = {
29
31
 
30
32
  const PENDING_TTL_MS = 5 * 60_000;
31
33
  function save(sessionID: string, roomID: string, admission: PendingAdmission, now: number): void {
32
- savePendingAdmission(sessionID, roomID, admission, now + PENDING_TTL_MS, now);
34
+ admission.createdAt ??= now;
35
+ savePendingAdmission(sessionID, roomID, admission, admission.createdAt + PENDING_TTL_MS, now);
33
36
  }
34
37
 
35
38
  export function queueAdmissionId(
@@ -45,8 +48,10 @@ export function queueAdmissionId(
45
48
  items: items.map((item) => [
46
49
  item.id ?? "",
47
50
  item.senderId,
51
+ item.senderSessionID ?? "",
48
52
  item.text,
49
53
  item.createdAt,
54
+ item.roomKind ?? "",
50
55
  ]),
51
56
  });
52
57
  return `msg_${createHash("sha256").update(fingerprint).digest("hex")}`;
@@ -56,7 +61,13 @@ export function pendingAdmission(
56
61
  sessionID: string,
57
62
  roomId: string,
58
63
  ): PendingAdmission | undefined {
59
- return readPendingAdmission<PendingAdmission>(sessionID, roomId, Date.now());
64
+ const now = Date.now();
65
+ const admission = readPendingAdmission<PendingAdmission>(sessionID, roomId, now);
66
+ if (admission && !Number.isFinite(admission.createdAt)) {
67
+ admission.createdAt = now;
68
+ save(sessionID, roomId, admission, now);
69
+ }
70
+ return admission;
60
71
  }
61
72
 
62
73
  export function getOrCreatePendingAdmission(
@@ -77,6 +88,7 @@ export function getOrCreatePendingAdmission(
77
88
  }
78
89
  const admission: PendingAdmission = {
79
90
  id: queueAdmissionId(sessionID, roomId, items, prompt),
91
+ createdAt: now,
80
92
  prompt,
81
93
  itemCount: items.length,
82
94
  maxTs,
@@ -90,6 +102,28 @@ export function getOrCreatePendingAdmission(
90
102
  return admission;
91
103
  }
92
104
 
105
+ export function prunePendingAdmission(
106
+ sessionID: string,
107
+ roomId: string,
108
+ throughTs: number,
109
+ rebuild: (items: QueueItem[]) => { prompt: string; capped: boolean },
110
+ ): PendingAdmission | undefined {
111
+ const existing = pendingAdmission(sessionID, roomId);
112
+ if (!existing) return undefined;
113
+ if (existing.state === "admitted") {
114
+ if (existing.maxTs <= throughTs) deletePendingAdmission(sessionID, roomId);
115
+ return existing.maxTs <= throughTs ? undefined : existing;
116
+ }
117
+ const items = existing.items.filter((item) => item.createdAt > throughTs);
118
+ if (items.length === existing.items.length) return existing;
119
+ if (!items.length) { deletePendingAdmission(sessionID, roomId); return undefined; }
120
+ const { prompt, capped } = rebuild(items);
121
+ const admission = { ...existing, id: queueAdmissionId(sessionID, roomId, items, prompt), prompt,
122
+ itemCount: items.length, maxTs: Math.max(...items.map((item) => item.createdAt)), capped, items };
123
+ save(sessionID, roomId, admission, Date.now());
124
+ return admission;
125
+ }
126
+
93
127
  export function rejectPendingAdmission(
94
128
  sessionID: string,
95
129
  roomId: string,
@@ -5,6 +5,56 @@ import path from "node:path";
5
5
 
6
6
  const databases = new Map<string, Database>();
7
7
  const pause = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
+ function initialize(db: Database): void {
9
+ for (let attempt = 0; ; attempt++) {
10
+ try {
11
+ db.exec("PRAGMA journal_mode=WAL; BEGIN IMMEDIATE; 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 background_attempted_through(session_id TEXT NOT NULL,room_id TEXT NOT NULL,service TEXT NOT NULL,through_ts INTEGER NOT NULL,PRIMARY KEY(session_id,room_id,service)); CREATE TABLE IF NOT EXISTS watcher_claims(identity TEXT PRIMARY KEY,instance_id TEXT NOT NULL,pid INTEGER NOT NULL);");
12
+ migrateLegacyBackgroundAttempts(db);
13
+ db.exec("COMMIT");
14
+ return;
15
+ } catch (error) {
16
+ try { db.exec("ROLLBACK"); } catch { /* No transaction remained open. */ }
17
+ const err = error as { code?: string };
18
+ if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
19
+ pause(Math.min(20 * 2 ** attempt, 250));
20
+ }
21
+ }
22
+ }
23
+
24
+ function migrateLegacyBackgroundAttempts(db: Database): void {
25
+ const tables = db.query("SELECT name FROM sqlite_master WHERE type='table'").all() as Array<{ name: string }>;
26
+ const names = new Set(tables.map((table) => table.name));
27
+ if (names.has("background_attempts")) {
28
+ const rows = db.query("SELECT session_id,room_id,service,admission_id FROM background_attempts").all() as Array<{ session_id: string; room_id: string; service: string; admission_id: string }>;
29
+ for (const row of rows) {
30
+ const pending = db.query("SELECT admission FROM pending_admissions WHERE session_id=? AND room_id=?").get(row.session_id, row.room_id) as { admission: string } | null;
31
+ let through = Number.MAX_SAFE_INTEGER;
32
+ try {
33
+ const value = pending ? JSON.parse(pending.admission) as { id?: string; maxTs?: number } : undefined;
34
+ if (value?.id === row.admission_id && Number.isSafeInteger(value.maxTs) && value.maxTs! > 0) through = value.maxTs!;
35
+ } catch { /* Ambiguous old claims stay fail-closed. */ }
36
+ saveBackgroundWatermark(db, row.session_id, row.room_id, row.service, through);
37
+ }
38
+ db.exec("DROP TABLE background_attempts");
39
+ }
40
+ if (names.has("background_retries")) {
41
+ const columns = db.query("PRAGMA table_info(background_retries)").all() as Array<{ name: string }>;
42
+ const hasTrigger = columns.some((column) => column.name === "trigger_ts");
43
+ const query = hasTrigger
44
+ ? "SELECT session_id,room_id,service,trigger_ts AS trigger FROM background_retries"
45
+ : "SELECT session_id,room_id,service,0 AS trigger FROM background_retries";
46
+ const rows = db.query(query).all() as Array<{ session_id: string; room_id: string; service: string; trigger: number }>;
47
+ for (const row of rows) saveBackgroundWatermark(db, row.session_id, row.room_id, row.service,
48
+ Number.isSafeInteger(row.trigger) && row.trigger > 0 ? row.trigger : Number.MAX_SAFE_INTEGER);
49
+ db.exec("DROP TABLE background_retries");
50
+ }
51
+ }
52
+
53
+ function saveBackgroundWatermark(db: Database, sessionID: string, roomID: string, service: string, throughTs: number): void {
54
+ db.query("INSERT INTO background_attempted_through VALUES(?,?,?,?) ON CONFLICT(session_id,room_id,service) DO UPDATE SET through_ts=max(through_ts,excluded.through_ts)")
55
+ .run(sessionID, roomID, service, throughTs);
56
+ }
57
+
8
58
  export function receiverStateDirectory(): string {
9
59
  const configured = process.env.XDG_STATE_HOME;
10
60
  const base = configured && path.isAbsolute(configured) ? configured : path.join(os.homedir(), ".local", "state");
@@ -18,7 +68,8 @@ function database(): Database {
18
68
  chmodSync(path.dirname(file), 0o700);
19
69
  db = new Database(file, { create: true });
20
70
  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);");
71
+ try { db.exec("PRAGMA busy_timeout=100"); initialize(db); }
72
+ catch (error) { db.close(); throw error; }
22
73
  databases.set(file, db);
23
74
  return db;
24
75
  }
@@ -53,6 +104,12 @@ export function deletePendingAdmission(sessionID: string, roomID: string): void
53
104
  immediate((db) => db.query("DELETE FROM pending_admissions WHERE session_id=? AND room_id=?").run(sessionID, roomID));
54
105
  }
55
106
 
107
+ export function claimBackgroundAttempt(sessionID: string, roomID: string, service: string, throughTs: number): boolean {
108
+ return immediate((db) => Number.isSafeInteger(throughTs) && throughTs > 0 &&
109
+ db.query("INSERT INTO background_attempted_through VALUES(?,?,?,?) ON CONFLICT(session_id,room_id,service) DO UPDATE SET through_ts=excluded.through_ts WHERE excluded.through_ts>background_attempted_through.through_ts")
110
+ .run(sessionID, roomID, service, throughTs).changes === 1);
111
+ }
112
+
56
113
  export function acquireDeliveryLease(sessionID: string, holder: string, now: number, expiresAt: number): boolean {
57
114
  return immediate((db) => {
58
115
  db.query("DELETE FROM delivery_leases WHERE expires_at<=?").run(now);
@@ -22,12 +22,16 @@ export type Room = {
22
22
  participants: Map<string, Participant>;
23
23
  messages: Message[];
24
24
  createdAt: number;
25
+ kind?: "group" | "direct";
26
+ directSessionIDs?: string[];
27
+ directPair?: string;
25
28
  };
26
29
 
27
30
  export type RoomErrorCode =
28
31
  | "ROOM_NOT_FOUND"
29
32
  | "NOT_JOINED"
30
- | "EMPTY_MESSAGE";
33
+ | "EMPTY_MESSAGE"
34
+ | "DIRECT_ROOM_FULL";
31
35
 
32
36
  export class RoomError extends Error {
33
37
  readonly code: RoomErrorCode;
@@ -71,6 +75,15 @@ export default class RoomService {
71
75
  return room;
72
76
  }
73
77
 
78
+ createDirectRoom(name: string, ownerId: string, sessions: [string, string]): Room {
79
+ const pair = JSON.stringify([...sessions].sort());
80
+ const existing = [...this.rooms.values()].find((room) => room.directPair === pair);
81
+ if (existing) return existing;
82
+ const room: Room = { id: randomUUID(), name, ownerId, participants: new Map(), messages: [], createdAt: Date.now(), kind: "direct", directSessionIDs: sessions, directPair: pair };
83
+ this.rooms.set(room.id, room);
84
+ return room;
85
+ }
86
+
74
87
  getRoom(roomId: string): Room {
75
88
  const room = this.rooms.get(roomId);
76
89
  if (!room) {
@@ -88,6 +101,7 @@ export default class RoomService {
88
101
  participant: { id: string; name: string },
89
102
  ): Participant {
90
103
  const room = this.getRoom(roomId);
104
+ if (room.kind === "direct" && !room.directSessionIDs?.includes(participant.id)) throw new RoomError("DIRECT_ROOM_FULL");
91
105
  // ponytail: the same identity from another session is the same member —
92
106
  // a second window on the same machine must not be locked out
93
107
  const existing = room.participants.get(participant.id);
@@ -171,4 +185,8 @@ export default class RoomService {
171
185
  containsParticipant(roomId: string, participantId: string): boolean {
172
186
  return this.rooms.get(roomId)?.participants.has(participantId) ?? false;
173
187
  }
188
+
189
+ deleteRoom(roomId: string): void {
190
+ if (!this.rooms.delete(roomId)) throw new RoomError("ROOM_NOT_FOUND", `room not found: ${roomId}`);
191
+ }
174
192
  }
@@ -27,12 +27,13 @@ async function initialize(file: string): Promise<Database> {
27
27
  try {
28
28
  db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; PRAGMA foreign_keys=ON;");
29
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);
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,kind TEXT NOT NULL DEFAULT 'group',direct_sessions TEXT,direct_pair TEXT UNIQUE);
31
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
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
33
  CREATE INDEX IF NOT EXISTS messages_room_seq ON messages(room_id,seq DESC);
34
34
  CREATE INDEX IF NOT EXISTS messages_room_time ON messages(room_id,created_at,seq);
35
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 ensureRoomColumns(db);
36
37
  await migrate(db, file);
37
38
  return db;
38
39
  } catch (error) {
@@ -43,6 +44,16 @@ async function initialize(file: string): Promise<Database> {
43
44
  } catch (error) { db.close(); throw error; }
44
45
  }
45
46
 
47
+ async function ensureRoomColumns(db: Database): Promise<void> {
48
+ await immediate(db, () => {
49
+ const columns = db.query("PRAGMA table_info(rooms)").all() as Array<{ name: string }>;
50
+ if (!columns.some((column) => column.name === "kind")) db.exec("ALTER TABLE rooms ADD COLUMN kind TEXT NOT NULL DEFAULT 'group'");
51
+ if (!columns.some((column) => column.name === "direct_sessions")) db.exec("ALTER TABLE rooms ADD COLUMN direct_sessions TEXT");
52
+ if (!columns.some((column) => column.name === "direct_pair")) db.exec("ALTER TABLE rooms ADD COLUMN direct_pair TEXT");
53
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS rooms_direct_pair ON rooms(direct_pair) WHERE direct_pair IS NOT NULL");
54
+ });
55
+ }
56
+
46
57
  function readLegacy(file: string): unknown | undefined {
47
58
  try { return JSON.parse(readFileSync(file, "utf8")); }
48
59
  catch (error) {
@@ -139,7 +150,7 @@ function validateRegistry(value: unknown): Registry {
139
150
  }
140
151
 
141
152
  function insertRoom(db: Database, room: Room): void {
142
- db.query("INSERT INTO rooms VALUES(?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt);
153
+ db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair) VALUES(?,?,?,?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null);
143
154
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
144
155
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
145
156
  const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
@@ -156,12 +167,16 @@ function replaceRegistry(db: Database, registry: Registry): void {
156
167
  }
157
168
 
158
169
  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");
170
+ const roomRow = db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at,kind=excluded.kind,direct_sessions=excluded.direct_sessions,direct_pair=excluded.direct_pair");
160
171
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
161
172
  const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
162
173
  const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
174
+ const keep = new Set(rooms.map((room) => room.id));
175
+ const existing = db.query("SELECT id FROM rooms").all() as Array<{ id: string }>;
176
+ const deleteRoom = db.query("DELETE FROM rooms WHERE id=?");
177
+ for (const row of existing) if (!keep.has(row.id)) deleteRoom.run(row.id);
163
178
  for (const room of rooms) {
164
- roomRow.run(room.id, room.name, room.ownerId, room.createdAt);
179
+ roomRow.run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null);
165
180
  removeParticipants.run(room.id);
166
181
  for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
167
182
  for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
@@ -170,14 +185,14 @@ function persistState(db: Database, rooms: Room[], registry: Registry): void {
170
185
  }
171
186
 
172
187
  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>>;
188
+ const roomRows = db.query("SELECT id,name,owner_id,created_at,kind,direct_sessions,direct_pair FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number | null>>;
174
189
  const rooms = roomRows.map((r): Room => {
175
190
  const participants = new Map<string, Participant>();
176
191
  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
192
  participants.set(String(p.id), { id: String(p.id), name: String(p.name), joinedAt: Number(p.joined_at) });
178
193
  }
179
194
  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,
195
+ return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), kind: r.kind === "direct" ? "direct" : "group", ...(r.direct_sessions ? { directSessionIDs: JSON.parse(String(r.direct_sessions)) as string[] } : {}), ...(r.direct_pair ? { directPair: String(r.direct_pair) } : {}), participants,
181
196
  messages: messages.reverse().map((m) => ({ id: String(m.id), roomId: String(m.room_id), senderId: String(m.sender_id),
182
197
  text: String(m.text), createdAt: Number(m.created_at), ...(m.sender_session_id ? { senderSessionID: String(m.sender_session_id) } : {}) })) };
183
198
  });
@@ -230,7 +245,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
230
245
  return db.transaction(() => {
231
246
  const take = Math.min(200, Math.max(1, limit));
232
247
  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
248
+ 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,r.kind AS room_kind
234
249
  FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
235
250
  WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
236
251
  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
@@ -239,8 +254,8 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
239
254
  excludeSelf ? 1 : 0, sessionID, take + 1) as Array<Record<string, string | number | null>>;
240
255
  const hasMore = rows.length > take;
241
256
  const items = rows.slice(0, take).map((row) => {
242
- const { senderSessionID: _sessionID, ...message } = rowMessage(row);
243
- return { ...message, roomName: String(row.room_name) };
257
+ const message = rowMessage(row);
258
+ return { ...message, roomName: String(row.room_name), roomKind: (row.room_kind === "direct" ? "direct" : "group") as "direct" | "group" };
244
259
  });
245
260
  const queuedTs = Object.fromEntries(members.map((member) => [member.room_id, member.last_queued_ts ?? 0]));
246
261
  return { member: members.length > 0, items, queuedTs, hasMore };