@alexsun-top/opencode-chat-room 0.7.8 → 0.8.1

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.
Files changed (183) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/LICENSE +21 -0
  3. package/README.md +77 -36
  4. package/README.zh-CN.md +82 -41
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +6905 -2764
  7. package/package.json +33 -3
  8. package/packages/chat-room-channeld/README.md +315 -0
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
  10. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  11. package/packages/chat-room-channeld/src/adapter.ts +509 -0
  12. package/packages/chat-room-channeld/src/cli.ts +124 -0
  13. package/packages/chat-room-channeld/src/config.ts +269 -0
  14. package/packages/chat-room-channeld/src/delivery.ts +163 -0
  15. package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
  16. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  17. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  18. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  19. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  20. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  21. package/packages/chat-room-channeld/src/framing.ts +128 -0
  22. package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
  23. package/packages/chat-room-channeld/src/host.ts +627 -0
  24. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  25. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  26. package/packages/chat-room-channeld/src/log.ts +26 -0
  27. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  28. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  29. package/packages/chat-room-channeld/src/published.ts +37 -0
  30. package/packages/chat-room-channeld/src/rules.ts +127 -0
  31. package/packages/chat-room-channeld/src/state.ts +502 -0
  32. package/packages/chat-room-channeld/src/stats.ts +209 -0
  33. package/plugin.ts +22 -5
  34. package/server/addressing-routes.ts +130 -0
  35. package/server/admin-state.ts +13 -13
  36. package/server/app.ts +95 -0
  37. package/server/assets/NOTICE.txt +3 -2
  38. package/server/assets/SHIKI-LICENSE +22 -0
  39. package/server/assets/base.css +24 -10
  40. package/server/assets/chat/announcements.js +70 -7
  41. package/server/assets/chat/doc-preview.js +187 -39
  42. package/server/assets/chat/events.js +3 -0
  43. package/server/assets/chat/files.js +46 -4
  44. package/server/assets/chat/forward.js +69 -0
  45. package/server/assets/chat/index.js +4 -0
  46. package/server/assets/chat/integration-editor.js +163 -0
  47. package/server/assets/chat/integration-values.js +124 -0
  48. package/server/assets/chat/integrations.js +498 -0
  49. package/server/assets/chat/locales/de.js +45 -4
  50. package/server/assets/chat/locales/es.js +45 -4
  51. package/server/assets/chat/locales/fr.js +45 -4
  52. package/server/assets/chat/locales/it.js +45 -4
  53. package/server/assets/chat/locales/ja.js +45 -4
  54. package/server/assets/chat/locales/ko.js +45 -4
  55. package/server/assets/chat/markdown-footnotes.js +115 -0
  56. package/server/assets/chat/markdown.js +46 -43
  57. package/server/assets/chat/messages.js +5 -5
  58. package/server/assets/chat/office-preview.js +69 -0
  59. package/server/assets/chat/palette.js +1 -1
  60. package/server/assets/chat/panels.js +36 -0
  61. package/server/assets/chat/recall.js +58 -7
  62. package/server/assets/chat/receipts.js +15 -3
  63. package/server/assets/chat/reminders.js +69 -8
  64. package/server/assets/chat/replies.js +7 -1
  65. package/server/assets/chat/resource-format.js +11 -0
  66. package/server/assets/chat/settings.js +30 -2
  67. package/server/assets/chat/shiki.js +87 -0
  68. package/server/assets/chat/side-pane.js +9 -3
  69. package/server/assets/chat/state.js +107 -11
  70. package/server/assets/chat/system-events.js +32 -0
  71. package/server/assets/chat/system-messages.js +23 -12
  72. package/server/assets/chat/task-row.js +0 -6
  73. package/server/assets/chat/tasks.js +121 -33
  74. package/server/assets/code-highlight.css +74 -62
  75. package/server/assets/conversation.css +126 -25
  76. package/server/assets/doc-preview.css +36 -3
  77. package/server/assets/files.css +5 -0
  78. package/server/assets/fluent-icons.svg +2 -0
  79. package/server/assets/monaco/LICENSE +21 -0
  80. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  81. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  82. package/server/assets/monaco/editor.worker.js +45 -0
  83. package/server/assets/monaco/integration-rules.css +1 -0
  84. package/server/assets/monaco/integration-rules.js +1297 -0
  85. package/server/assets/monaco/json.worker.js +77 -0
  86. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  87. package/server/assets/office/docx.bundle.js +33 -0
  88. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  89. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  90. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  91. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  92. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  93. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  94. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  95. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  96. package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
  97. package/server/assets/office/pptx.bundle.js +104 -0
  98. package/server/assets/office/xlsx.bundle.js +141 -0
  99. package/server/assets/recall.css +5 -4
  100. package/server/assets/responsive.css +52 -8
  101. package/server/assets/settings.css +73 -1
  102. package/server/assets/shiki.bundle.js +152 -0
  103. package/server/assets/tasks.css +57 -7
  104. package/server/channel-integration.ts +519 -0
  105. package/server/channel-settings.ts +77 -0
  106. package/server/channels.ts +557 -0
  107. package/server/chat-server.ts +33 -558
  108. package/server/chat.html +195 -22
  109. package/server/http-server.ts +3 -182
  110. package/server/resource-routes.ts +16 -16
  111. package/server/routes/inbox.ts +100 -0
  112. package/server/routes/pages.ts +83 -0
  113. package/server/routes/questions.ts +39 -0
  114. package/server/routes/room-actions.ts +162 -0
  115. package/server/routes/rooms.ts +160 -0
  116. package/server/startup.ts +84 -0
  117. package/server/sw.js +5 -2
  118. package/server/task-routes.ts +1 -1
  119. package/skills/chatroom/SKILL.md +1 -1
  120. package/src/center/center-client.ts +71 -1
  121. package/src/config/file-config.ts +29 -42
  122. package/src/platform/http-server.ts +182 -0
  123. package/src/protocol/addressing.ts +21 -0
  124. package/src/protocol/config.ts +58 -0
  125. package/src/protocol/room.ts +51 -0
  126. package/src/rooms/resources.ts +26 -16
  127. package/src/rooms/room-service.ts +2 -48
  128. package/src/rooms/storage.ts +329 -0
  129. package/src/rooms/tasks.ts +21 -5
  130. package/src/runtime/v2-plugin.ts +8 -2
  131. package/src/runtime/watch.ts +4 -3
  132. package/src/state/pg-database.ts +183 -0
  133. package/src/state/pg-migrate.ts +175 -0
  134. package/src/state/pg-sql.mjs +175 -0
  135. package/src/state/pg-worker.mjs +148 -0
  136. package/src/state/sqlite-announcements.ts +25 -0
  137. package/src/state/sqlite-database.ts +121 -0
  138. package/src/state/sqlite-legacy.ts +90 -0
  139. package/src/state/sqlite-members.ts +155 -0
  140. package/src/state/sqlite-messages.ts +288 -0
  141. package/src/state/sqlite-resources.ts +39 -0
  142. package/src/state/sqlite-rooms.ts +87 -0
  143. package/src/state/sqlite-schema.ts +80 -0
  144. package/src/state/sqlite-state-store.ts +33 -0
  145. package/src/state/sqlite-state.ts +15 -866
  146. package/src/state/sqlite-tasks.ts +65 -0
  147. package/src/state/sqlite-transaction.ts +13 -0
  148. package/src/state/sqlite.ts +21 -1
  149. package/src/state/store.ts +13 -3
  150. package/src/tui/app.mjs +32 -19
  151. package/src/tui/config.mjs +12 -4
  152. package/src/tui/http.mjs +16 -2
  153. package/src/tui/i18n.mjs +38 -0
  154. package/src/tui/info-app.mjs +50 -51
  155. package/src/tui/info-content.mjs +79 -44
  156. package/src/tui/join-app.mjs +9 -9
  157. package/src/tui/locales/en.mjs +349 -0
  158. package/src/tui/locales/zh-CN.mjs +349 -0
  159. package/src/tui/main.mjs +85 -37
  160. package/src/tui/markdown.mjs +3 -2
  161. package/src/tui/mentions.mjs +3 -1
  162. package/src/tui/message-app.mjs +22 -21
  163. package/src/tui/message-view.mjs +2 -1
  164. package/src/tui/palette-app.mjs +9 -8
  165. package/src/tui/palette.mjs +30 -24
  166. package/src/tui/prefs.mjs +92 -0
  167. package/src/tui/reminder-app.mjs +18 -17
  168. package/src/tui/room-settings-app.mjs +30 -28
  169. package/src/tui/settings-app.mjs +153 -0
  170. package/src/tui/ui-content.mjs +65 -86
  171. package/src/tui/ui-help.mjs +73 -0
  172. package/src/tui/ui-overlay-view.mjs +23 -7
  173. package/src/tui/ui-suggest.mjs +6 -5
  174. package/src/tui/ui-theme.mjs +37 -33
  175. package/src/tui/ui-view.mjs +22 -7
  176. package/src/tui/ui.mjs +15 -3
  177. package/src/web/editor.worker.ts +1 -0
  178. package/src/web/integration-rules-editor.ts +439 -0
  179. package/src/web/integration-rules.ts +22 -0
  180. package/src/web/integration-schema.ts +228 -0
  181. package/src/web/json.worker.ts +1 -0
  182. package/src/web/office-viewer.ts +221 -0
  183. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,183 @@
1
+ import { existsSync } from "node:fs";
2
+ import { MessageChannel, receiveMessageOnPort, Worker, type MessagePort } from "node:worker_threads";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { QueryStatement, SQLQueryBindings, StateDatabase, Transaction } from "./sqlite.ts";
5
+
6
+ // Synchronous facade over a PostgreSQL connection. Every call blocks the
7
+ // calling thread on a SharedArrayBuffer while a worker thread performs the
8
+ // network I/O. The state layer is synchronous by design, so this preserves its
9
+ // transaction boundaries without turning 100+ call sites into async code.
10
+ //
11
+ // PostgreSQL support is experimental and single-instance in 0.8.1: the worker
12
+ // holds a session advisory lock for the lifetime of the connection, and a
13
+ // second process fails startup instead of writing concurrently.
14
+
15
+ type Reply = {
16
+ id: number;
17
+ ok: boolean;
18
+ rows?: unknown[];
19
+ row?: unknown;
20
+ changes?: number;
21
+ lastInsertRowid?: number;
22
+ error?: Record<string, unknown>;
23
+ };
24
+
25
+ type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
26
+
27
+ function workerURL(): URL {
28
+ const beside = new URL("./pg-worker.mjs", import.meta.url);
29
+ if (existsSync(fileURLToPath(beside))) return beside;
30
+ // Bundled CLI: dist/cli.js -> src/state/pg-worker.mjs in the package.
31
+ return new URL("../src/state/pg-worker.mjs", import.meta.url);
32
+ }
33
+
34
+ function databaseError(error: Record<string, unknown> | undefined): Error {
35
+ const result = new Error(String(error?.message ?? "PostgreSQL query failed"));
36
+ Object.assign(result, error);
37
+ return result;
38
+ }
39
+
40
+ export class PgDatabase implements StateDatabase {
41
+ readonly #worker: Worker;
42
+ readonly #port: MessagePort;
43
+ readonly #timeout: number;
44
+ readonly #lockTimeout: number;
45
+ #nextID = 1;
46
+ #depth = 0;
47
+ #savepoints = 0;
48
+ #broken: Error | undefined;
49
+ #closed = false;
50
+
51
+ constructor(connectionString: string, options: { timeout?: number } = {}) {
52
+ if (!connectionString) throw new Error("PostgreSQL connection string is empty");
53
+ this.#timeout = options.timeout ?? 5_000;
54
+ this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
55
+ const ready = new SharedArrayBuffer(4);
56
+ const { port1, port2 } = new MessageChannel();
57
+ this.#port = port1;
58
+ this.#worker = new Worker(workerURL());
59
+ this.#worker.unref();
60
+ this.#port.unref();
61
+ try {
62
+ // No workerData: some Bun versions break `pg` when a worker starts with
63
+ // any workerData. The default worker channel carries one init message
64
+ // and transfers the request port.
65
+ this.#worker.postMessage({
66
+ type: "init",
67
+ connectionString,
68
+ ready,
69
+ statementTimeout: Math.max(1, this.#timeout - 500),
70
+ port: port2,
71
+ }, [port2]);
72
+ } catch (error) {
73
+ void this.#worker.terminate();
74
+ this.#port.close();
75
+ throw error;
76
+ }
77
+ const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
78
+ if (status === "timed-out") {
79
+ void this.#worker.terminate();
80
+ throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
81
+ }
82
+ const message = receiveMessageOnPort(this.#port)?.message as ReadyMessage | undefined;
83
+ if (message?.type === "fatal") {
84
+ void this.#worker.terminate();
85
+ throw databaseError(message.error);
86
+ }
87
+ }
88
+
89
+ query(sql: string): QueryStatement {
90
+ return {
91
+ all: (...params: SQLQueryBindings[]) => this.#request("all", sql, params).rows as unknown[],
92
+ get: (...params: SQLQueryBindings[]) => this.#request("get", sql, params).row as unknown,
93
+ run: (...params: SQLQueryBindings[]) => {
94
+ const result = this.#request("run", sql, params);
95
+ return { changes: result.changes ?? 0, lastInsertRowid: result.lastInsertRowid ?? 0 };
96
+ },
97
+ };
98
+ }
99
+
100
+ prepare(sql: string): QueryStatement { return this.query(sql); }
101
+
102
+ exec(sql: string): void { this.#request("exec", sql, []); }
103
+
104
+ transaction<T>(fn: () => T): Transaction<T> {
105
+ const run = (immediate: boolean) => this.#run(fn, immediate);
106
+ return Object.assign(() => run(false), {
107
+ deferred: () => run(false),
108
+ immediate: () => run(true),
109
+ });
110
+ }
111
+
112
+ close(): void {
113
+ if (this.#closed) return;
114
+ this.#closed = true;
115
+ const signal = new SharedArrayBuffer(4);
116
+ try {
117
+ this.#port.postMessage({ type: "close", signal });
118
+ // Give client.end() a chance to release the session advisory lock before
119
+ // a caller opens the next connection (migration and restart tests rely on it).
120
+ Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
121
+ } catch { /* worker already gone */ }
122
+ this.#port.close();
123
+ void this.#worker.terminate();
124
+ }
125
+
126
+ #run<T>(fn: () => T, immediate: boolean): T {
127
+ const nested = this.#depth > 0;
128
+ const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
129
+ if (nested) {
130
+ this.exec(`SAVEPOINT ${savepoint}`);
131
+ } else {
132
+ // Deferred reads need one stable snapshot; immediate writers are
133
+ // serialized by the transaction-level advisory lock.
134
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
135
+ if (immediate) {
136
+ try {
137
+ this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('chat-room-state')); SET LOCAL lock_timeout = 0`);
138
+ } catch (error) {
139
+ try { this.exec("ROLLBACK"); } catch { /* keep the original error */ }
140
+ throw error;
141
+ }
142
+ }
143
+ }
144
+ this.#depth++;
145
+ try {
146
+ const result = fn();
147
+ this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
148
+ return result;
149
+ } catch (error) {
150
+ try {
151
+ this.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
152
+ } catch { /* keep the original error */ }
153
+ throw error;
154
+ } finally {
155
+ this.#depth--;
156
+ }
157
+ }
158
+
159
+ #request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
160
+ if (this.#broken) throw this.#broken;
161
+ if (this.#closed) throw new Error("PostgreSQL database is closed");
162
+ const id = this.#nextID++;
163
+ const signal = new SharedArrayBuffer(4);
164
+ this.#port.postMessage({ id, mode, sql, params, signal });
165
+ const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
166
+ if (status === "timed-out") {
167
+ // The worker may still be inside the query. Its connection and queue are
168
+ // no longer trustworthy, so fail closed rather than desynchronize later calls.
169
+ this.#broken = Object.assign(
170
+ new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`),
171
+ { code: "PG_BRIDGE_TIMEOUT" },
172
+ );
173
+ throw this.#broken;
174
+ }
175
+ const message = receiveMessageOnPort(this.#port)?.message as Reply | undefined;
176
+ if (!message || message.id !== id) {
177
+ this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
178
+ throw this.#broken;
179
+ }
180
+ if (!message.ok) throw databaseError(message.error);
181
+ return message;
182
+ }
183
+ }
@@ -0,0 +1,175 @@
1
+ import { existsSync } from "node:fs";
2
+ import { PgDatabase } from "./pg-database.ts";
3
+ import { Database, type SQLQueryBindings } from "./sqlite.ts";
4
+ import { closeStateDatabases, initializeAdminSchema, initializeReminderSchema, openStateDatabase } from "./sqlite-state.ts";
5
+
6
+ // One-shot SQLite -> PostgreSQL copy. PostgreSQL support is experimental and
7
+ // single-instance in 0.8.1; the target connection holds the same session lock
8
+ // as the server, so a running server makes this command fail before writing.
9
+
10
+ export type MigrationOptions = {
11
+ sourcePath: string;
12
+ assumeYes?: boolean;
13
+ log?: (line: string) => void;
14
+ };
15
+
16
+ export type MigrationReport = { tables: Array<{ table: string; rows: number }>; messages: number };
17
+
18
+ const quote = (name: string) => `"${name.replace(/"/g, '""')}"`;
19
+
20
+ function backupGuidance(sourcePath: string): string[] {
21
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
22
+ return [
23
+ "PostgreSQL state is experimental and single-instance in 0.8.1.",
24
+ "Stop the chat-room server before migrating; this command takes a SQLite write lock,",
25
+ "but only --yes confirms that the server is actually stopped.",
26
+ "",
27
+ "Make a WAL-safe SQLite backup first (do not copy only chat-room.sqlite while WAL is active):",
28
+ ` sqlite3 ${JSON.stringify(sourcePath)} ".backup '${sourcePath}.backup-${stamp}'"`,
29
+ "",
30
+ "Rollback: unset CHAT_ROOM_DATABASE_URL and start the old server again. Messages written",
31
+ "while PostgreSQL was active are not copied back to SQLite.",
32
+ ];
33
+ }
34
+
35
+ function orderTables(tables: string[], parents: Map<string, Set<string>>): string[] {
36
+ const remaining = new Set(tables);
37
+ const ordered: string[] = [];
38
+ while (remaining.size) {
39
+ let progressed = false;
40
+ for (const table of [...remaining]) {
41
+ const blockers = [...(parents.get(table) ?? [])].filter((parent) => parent !== table && remaining.has(parent));
42
+ if (blockers.length) continue;
43
+ ordered.push(table);
44
+ remaining.delete(table);
45
+ progressed = true;
46
+ }
47
+ if (!progressed) throw new Error(`cannot migrate: foreign key cycle among ${[...remaining].join(", ")}`);
48
+ }
49
+ return ordered;
50
+ }
51
+
52
+ function copyTable(
53
+ source: Database,
54
+ target: Awaited<ReturnType<typeof openStateDatabase>>,
55
+ table: string,
56
+ columns: string[],
57
+ ): number {
58
+ if (!columns.length) return 0;
59
+ const batch = Math.max(1, Math.min(500, Math.floor(2_000 / columns.length)));
60
+ const selection = columns.map(quote).join(",");
61
+ const insert = `INSERT INTO ${quote(table)} (${selection}) VALUES `;
62
+ let lastRowid = 0;
63
+ let copied = 0;
64
+ for (;;) {
65
+ const rows = source.query(`SELECT rowid AS __rowid,${selection} FROM ${quote(table)} WHERE rowid>? ORDER BY rowid LIMIT ?`)
66
+ .all(lastRowid, batch) as Array<Record<string, unknown>>;
67
+ if (!rows.length) break;
68
+ lastRowid = Number(rows[rows.length - 1]!.__rowid);
69
+ const placeholders = `(${columns.map(() => "?").join(",")})`;
70
+ const values: unknown[] = [];
71
+ for (const row of rows) for (const column of columns) values.push(row[column]);
72
+ target.query(`${insert}${Array.from({ length: rows.length }, () => placeholders).join(",")}`)
73
+ .run(...(values as SQLQueryBindings[]));
74
+ copied += rows.length;
75
+ }
76
+ return copied;
77
+ }
78
+
79
+ export async function migrateToPostgres(options: MigrationOptions): Promise<MigrationReport> {
80
+ const log = options.log ?? console.log;
81
+ const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
82
+ if (!url) throw new Error("CHAT_ROOM_DATABASE_URL is required; point it at an empty PostgreSQL database");
83
+ if (!existsSync(options.sourcePath)) throw new Error(`SQLite state database not found: ${options.sourcePath}`);
84
+ for (const line of backupGuidance(options.sourcePath)) log(line);
85
+ if (!options.assumeYes) throw new Error("refusing to migrate without --yes after stopping the server and making a backup");
86
+
87
+ const source = new Database(options.sourcePath, { create: false });
88
+ source.exec("PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;");
89
+ let report: MigrationReport | undefined;
90
+ try {
91
+ // Probe before any schema/administration migration can touch the target.
92
+ const probe = new PgDatabase(url);
93
+ try {
94
+ const nonEmpty: string[] = [];
95
+ const existing = probe.query("SELECT table_name FROM information_schema.tables WHERE table_schema=current_schema()").all() as Array<{ table_name: string }>;
96
+ for (const { table_name: table } of existing) {
97
+ const count = Number((probe.query(`SELECT COUNT(*) AS count FROM ${quote(table)}`).get() as { count: number }).count);
98
+ if (count > 0) nonEmpty.push(`${table} (${count})`);
99
+ }
100
+ if (nonEmpty.length) throw new Error(`target database is not empty: ${nonEmpty.join(", ")}; migrate into a fresh database`);
101
+ } finally {
102
+ probe.close();
103
+ }
104
+
105
+ // Opening the PostgreSQL state database also acquires the process-wide
106
+ // single-instance lock, so a running server blocks the migration here.
107
+ const target = await openStateDatabase(options.sourcePath);
108
+ await initializeAdminSchema(options.sourcePath);
109
+ await initializeReminderSchema(options.sourcePath);
110
+ target.exec("CREATE TABLE IF NOT EXISTS server_admin_migrations(version INTEGER PRIMARY KEY,applied_at INTEGER NOT NULL)");
111
+
112
+ const targetColumns = new Map<string, Set<string>>();
113
+ for (const row of target.query("SELECT table_name,column_name FROM information_schema.columns WHERE table_schema=current_schema() ORDER BY ordinal_position")
114
+ .all() as Array<{ table_name: string; column_name: string }>) {
115
+ const columns = targetColumns.get(row.table_name) ?? new Set<string>();
116
+ columns.add(row.column_name);
117
+ targetColumns.set(row.table_name, columns);
118
+ }
119
+
120
+ // Keep one read snapshot and stop SQLite writers for the duration of the copy.
121
+ source.transaction(() => {
122
+ const tables = (source.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all() as Array<{ name: string }>)
123
+ .map((row) => row.name);
124
+ const parents = new Map<string, Set<string>>();
125
+ for (const table of tables) {
126
+ const rows = source.query(`PRAGMA foreign_key_list(${quote(table)})`).all() as Array<{ table: string }>;
127
+ parents.set(table, new Set(rows.map((row) => row.table).filter((parent) => tables.includes(parent))));
128
+ }
129
+ const ordered = orderTables(tables, parents);
130
+
131
+ const counts = new Map<string, number>();
132
+ for (const table of tables) counts.set(table, Number((source.query(`SELECT COUNT(*) AS count FROM ${quote(table)}`).get() as { count: number }).count));
133
+ const copied: Array<{ table: string; rows: number }> = [];
134
+
135
+ target.transaction(() => {
136
+ for (const table of ordered) {
137
+ const available = targetColumns.get(table);
138
+ if (!available) {
139
+ log(` skip ${table}: table does not exist in PostgreSQL`);
140
+ continue;
141
+ }
142
+ const sourceColumns = (source.query(`PRAGMA table_info(${quote(table)})`).all() as Array<{ name: string }>).map((row) => row.name);
143
+ const columns = sourceColumns.filter((column) => available.has(column));
144
+ if (columns.length !== sourceColumns.length) {
145
+ log(` ${table}: ignoring source-only columns ${sourceColumns.filter((column) => !available.has(column)).join(", ")}`);
146
+ }
147
+ const rows = copyTable(source, target, table, columns);
148
+ copied.push({ table, rows });
149
+ log(` ${table}: ${rows} rows`);
150
+ }
151
+
152
+ // Explicit seq values bypass the identity sequence; move it past the
153
+ // largest copied value so the next insert continues the history.
154
+ target.query("SELECT setval(pg_get_serial_sequence('messages','seq'),COALESCE(MAX(seq),0)+1,false) AS value FROM messages").get();
155
+
156
+ for (const { table, rows } of copied) {
157
+ const expected = counts.get(table) ?? 0;
158
+ const actual = Number((target.query(`SELECT COUNT(*) AS count FROM ${quote(table)}`).get() as { count: number }).count);
159
+ if (actual !== expected || rows !== expected) {
160
+ throw new Error(`row count mismatch for ${table}: source ${expected}, copied ${rows}, target ${actual}`);
161
+ }
162
+ }
163
+ return copied;
164
+ }).immediate();
165
+
166
+ report = { tables: copied, messages: counts.get("messages") ?? 0 };
167
+ }).immediate();
168
+ } finally {
169
+ source.close();
170
+ await closeStateDatabases();
171
+ }
172
+ if (!report) throw new Error("migration did not complete");
173
+ log(`migrated ${report.messages} messages across ${report.tables.length} tables`);
174
+ return report;
175
+ }
@@ -0,0 +1,175 @@
1
+ // SQLite -> PostgreSQL translation for the chat-room state SQL. The app's SQL
2
+ // uses ? placeholders, SQLite DDL, a few pragmas and a handful of scalar
3
+ // functions; everything else is deliberately passed through unchanged.
4
+ //
5
+ // This is intentionally not a general SQLite translator. Keep the dialect
6
+ // narrow and add a test when the state layer starts using a new construct.
7
+
8
+ const PRAGMA_TABLE_INFO = /PRAGMA\s+table_info\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi;
9
+
10
+ function pragmaTableInfo(table) {
11
+ const tableName = table.replace(/'/g, "''");
12
+ return `SELECT c.column_name AS name,c.data_type AS type,` +
13
+ `CASE WHEN c.is_nullable='NO' THEN 1 ELSE 0 END AS "notnull",` +
14
+ `c.column_default AS dflt_value,` +
15
+ `CASE WHEN EXISTS (SELECT 1 FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=ANY(i.indkey) ` +
16
+ `WHERE i.indrelid=(quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass AND i.indisprimary AND a.attname=c.column_name) ` +
17
+ `THEN 1 ELSE 0 END AS pk ` +
18
+ `FROM information_schema.columns c WHERE c.table_schema=current_schema() AND c.table_name='${tableName}' ORDER BY c.ordinal_position`;
19
+ }
20
+
21
+ const isIdentStart = (ch) => !!ch && /[A-Za-z_]/.test(ch);
22
+ const isIdentChar = (ch) => !!ch && /[A-Za-z0-9_$]/.test(ch);
23
+
24
+ function skipQuoted(sql, index) {
25
+ const quote = sql[index];
26
+ let i = index + 1;
27
+ while (i < sql.length) {
28
+ if (sql[i] === quote) {
29
+ if (sql[i + 1] === quote) { i += 2; continue; }
30
+ return i + 1;
31
+ }
32
+ i++;
33
+ }
34
+ return i;
35
+ }
36
+
37
+ function skipComment(sql, index) {
38
+ if (sql[index + 1] === "-") {
39
+ const end = sql.indexOf("\n", index + 2);
40
+ return end < 0 ? sql.length : end;
41
+ }
42
+ const end = sql.indexOf("*/", index + 2);
43
+ return end < 0 ? sql.length : end + 2;
44
+ }
45
+
46
+ function hasTopLevelComma(sql, openIndex) {
47
+ let depth = 0;
48
+ for (let i = openIndex; i < sql.length; i++) {
49
+ const ch = sql[i];
50
+ if (ch === "'" || ch === '"') { i = skipQuoted(sql, i) - 1; continue; }
51
+ if (ch === "-" && sql[i + 1] === "-") { i = skipComment(sql, i) - 1; continue; }
52
+ if (ch === "/" && sql[i + 1] === "*") { i = skipComment(sql, i) - 1; continue; }
53
+ if (ch === "(") depth++;
54
+ else if (ch === ")") { depth--; if (depth === 0) return false; }
55
+ else if (ch === "," && depth === 1) return true;
56
+ }
57
+ return false;
58
+ }
59
+
60
+ function wordBefore(sql, index) {
61
+ let i = index - 1;
62
+ while (i >= 0 && /\s/.test(sql[i])) i--;
63
+ const end = i + 1;
64
+ while (i >= 0 && isIdentChar(sql[i])) i--;
65
+ return sql.slice(i + 1, end).toLowerCase();
66
+ }
67
+
68
+ function wordAfter(sql, index) {
69
+ let i = index + 1;
70
+ while (i < sql.length && /\s/.test(sql[i])) i++;
71
+ const start = i;
72
+ while (i < sql.length && isIdentChar(sql[i])) i++;
73
+ return sql.slice(start, i).toLowerCase();
74
+ }
75
+
76
+ function scan(sql) {
77
+ let out = "";
78
+ let index = 0;
79
+ let parameter = 0;
80
+ while (index < sql.length) {
81
+ const ch = sql[index];
82
+ if (ch === "'" || ch === '"') {
83
+ const end = skipQuoted(sql, index);
84
+ out += sql.slice(index, end);
85
+ index = end;
86
+ continue;
87
+ }
88
+ if (ch === "-" && sql[index + 1] === "-") {
89
+ const end = skipComment(sql, index);
90
+ out += sql.slice(index, end);
91
+ index = end;
92
+ continue;
93
+ }
94
+ if (ch === "/" && sql[index + 1] === "*") {
95
+ const end = skipComment(sql, index);
96
+ out += sql.slice(index, end);
97
+ index = end;
98
+ continue;
99
+ }
100
+ if (ch === "?") {
101
+ // CASE WHEN ? needs a boolean; a bare `? IS NULL` has no type to infer.
102
+ const nextWord = wordAfter(sql, index);
103
+ const cast = (wordBefore(sql, index) === "when" && nextWord === "then") || nextWord === "is";
104
+ out += `$${++parameter}${cast ? (nextWord === "is" ? "::text" : "::boolean") : ""}`;
105
+ index++;
106
+ continue;
107
+ }
108
+ if (isIdentStart(ch)) {
109
+ let end = index + 1;
110
+ while (isIdentChar(sql[end])) end++;
111
+ const word = sql.slice(index, end);
112
+ const lower = word.toLowerCase();
113
+ // SQLite's scalar max(a,b)/min(a,b); the one-argument aggregate forms stay.
114
+ if (lower === "max" || lower === "min") {
115
+ let next = end;
116
+ while (next < sql.length && /\s/.test(sql[next])) next++;
117
+ if (sql[next] === "(" && hasTopLevelComma(sql, next)) {
118
+ out += lower === "max" ? "GREATEST" : "LEAST";
119
+ index = end;
120
+ continue;
121
+ }
122
+ }
123
+ // Preserve camelCase result aliases: PostgreSQL folds unquoted identifiers.
124
+ if (lower === "as") {
125
+ const previous = wordBefore(sql, index);
126
+ let next = end;
127
+ while (next < sql.length && /\s/.test(sql[next])) next++;
128
+ if (isIdentStart(sql[next])) {
129
+ let aliasEnd = next + 1;
130
+ while (isIdentChar(sql[aliasEnd])) aliasEnd++;
131
+ const alias = sql.slice(next, aliasEnd);
132
+ if (/[A-Z]/.test(alias) && previous !== "default" && alias.toLowerCase() !== "identity") {
133
+ out += `AS "${alias}"`;
134
+ index = aliasEnd;
135
+ continue;
136
+ }
137
+ }
138
+ }
139
+ out += word;
140
+ index = end;
141
+ continue;
142
+ }
143
+ out += ch;
144
+ index++;
145
+ }
146
+ return out;
147
+ }
148
+
149
+ function appendOnConflictDoNothing(sql) {
150
+ return `${sql.replace(/[\s;]+$/, "")} ON CONFLICT DO NOTHING`;
151
+ }
152
+
153
+ export function translate(sql) {
154
+ let text = String(sql);
155
+ // Connection tuning pragmas have no PostgreSQL equivalent; foreign keys are
156
+ // always enforced and concurrency is handled by advisory locks.
157
+ text = text.replace(/PRAGMA\s+(?:busy_timeout|journal_mode|foreign_keys)\s*(?:=\s*[^;]+)?\s*;?/gi, "");
158
+ text = text.replace(PRAGMA_TABLE_INFO, (_, table) => pragmaTableInfo(table));
159
+ // SQLite INTEGER is 64-bit; PostgreSQL INTEGER is 32-bit and epoch
160
+ // milliseconds overflow it.
161
+ text = text.replace(/\bINTEGER\b/gi, "BIGINT");
162
+ text = text.replace(/\bBIGINT\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/gi, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
163
+ // Manual `BEGIN IMMEDIATE` appears inside receiver-state's schema script.
164
+ text = text.replace(/\bBEGIN\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE)\b/gi, "BEGIN");
165
+ if (/\bINSERT\s+OR\s+IGNORE\b/i.test(text)) {
166
+ text = text.replace(/\bINSERT\s+OR\s+IGNORE\b/gi, "INSERT");
167
+ if (!/\bON\s+CONFLICT\b/i.test(text)) text = appendOnConflictDoNothing(text);
168
+ }
169
+ // SQLite treats 1/0 as booleans; PostgreSQL needs an explicit cast.
170
+ return scan(text).trim();
171
+ }
172
+
173
+ export function hasSql(text) {
174
+ return text.replace(/[;\s]/g, "").length > 0;
175
+ }
@@ -0,0 +1,148 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import pg from "pg";
3
+ import { hasSql, translate } from "./pg-sql.mjs";
4
+
5
+ // One pg.Client per worker: transactions and the process-wide advisory lock
6
+ // belong to a single session, so a pool would be incorrect here.
7
+ //
8
+ // The worker deliberately starts with no workerData. Some Bun versions fail to
9
+ // load `pg` in a worker that received any workerData at startup. The main
10
+ // thread sends one init message over the default worker channel instead; that
11
+ // message also transfers the request MessagePort and the ready SharedArrayBuffer.
12
+
13
+ const SINGLE_INSTANCE_KEY = "opencode-chat-room:state-writer";
14
+ const SINGLE_INSTANCE_ERROR =
15
+ "PostgreSQL backend is experimental and single-instance: another chat-room process already holds the database writer lock. " +
16
+ "Multi-instance support is planned for 0.8.2. Stop the other process, or unset CHAT_ROOM_DATABASE_URL to return to SQLite.";
17
+
18
+ let client;
19
+ let port;
20
+ let readyFlag;
21
+ let statementTimeout = 4_500;
22
+ let connected = false;
23
+ let draining = false;
24
+ let closing = false;
25
+ const queue = [];
26
+
27
+ // SQLite returns all integers as JS numbers; int8 is a string in node-postgres
28
+ // by default and COUNT(*) / BIGINT columns must stay numbers.
29
+ pg.types.setTypeParser(20, (value) => Number(value));
30
+ pg.types.setTypeParser(1700, (value) => Number(value));
31
+
32
+ function normalize(params) {
33
+ return params.map((value) =>
34
+ value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
35
+ }
36
+
37
+ function serialize(error) {
38
+ return {
39
+ name: error?.name,
40
+ message: error?.message ?? String(error),
41
+ code: error?.code,
42
+ detail: error?.detail,
43
+ hint: error?.hint,
44
+ severity: error?.severity,
45
+ position: error?.position,
46
+ constraint: error?.constraint,
47
+ table: error?.table,
48
+ column: error?.column,
49
+ dataType: error?.dataType,
50
+ };
51
+ }
52
+
53
+ function signalReady() {
54
+ Atomics.store(readyFlag, 0, 1);
55
+ Atomics.notify(readyFlag, 0);
56
+ }
57
+
58
+ function reply(request, payload) {
59
+ port.postMessage({ id: request.id, ...payload });
60
+ const flag = new Int32Array(request.signal);
61
+ Atomics.store(flag, 0, 1);
62
+ Atomics.notify(flag, 0);
63
+ }
64
+
65
+ async function handle(request) {
66
+ try {
67
+ const text = translate(request.sql);
68
+ if (!hasSql(text)) return reply(request, { ok: true, rows: [], row: null, changes: 0 });
69
+ const params = normalize(request.params ?? []);
70
+ // exec without params uses the simple-query protocol so multi-statement
71
+ // schema scripts (and BEGIN/COMMIT) run in one round trip.
72
+ const result = request.mode === "exec" && params.length === 0
73
+ ? await client.query(text)
74
+ : await client.query({ text, values: params });
75
+ if (request.mode === "get") return reply(request, { ok: true, row: result.rows?.[0] ?? null });
76
+ if (request.mode === "all") return reply(request, { ok: true, rows: result.rows ?? [] });
77
+ const last = Array.isArray(result) ? result[result.length - 1] : result;
78
+ // Identity columns are never read through Database.run in the state layer;
79
+ // keep the API shape without pretending to know an insert id.
80
+ return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
81
+ } catch (error) {
82
+ return reply(request, { ok: false, error: serialize(error) });
83
+ }
84
+ }
85
+
86
+ async function drain() {
87
+ draining = true;
88
+ while (queue.length && !closing) await handle(queue.shift());
89
+ draining = false;
90
+ }
91
+
92
+ async function shutdown(signal) {
93
+ closing = true;
94
+ try { await client.end(); } catch { /* connection already gone */ }
95
+ try { port.close(); } catch { /* already closed */ }
96
+ if (signal) {
97
+ const flag = new Int32Array(signal);
98
+ Atomics.store(flag, 0, 1);
99
+ Atomics.notify(flag, 0);
100
+ }
101
+ }
102
+
103
+ function handlePortMessage(message) {
104
+ if (message?.type === "close") {
105
+ void shutdown(message.signal);
106
+ return;
107
+ }
108
+ queue.push(message);
109
+ if (connected && !draining) void drain();
110
+ }
111
+
112
+ async function startup(connectionString, ready, timeout) {
113
+ readyFlag = new Int32Array(ready);
114
+ statementTimeout = timeout;
115
+ try {
116
+ client = new pg.Client({
117
+ connectionString,
118
+ application_name: "opencode-chat-room",
119
+ statement_timeout: statementTimeout,
120
+ });
121
+ await client.connect();
122
+ const guard = await client.query(
123
+ "SELECT pg_try_advisory_lock(hashtext($1), 1) AS locked",
124
+ [SINGLE_INSTANCE_KEY],
125
+ );
126
+ if (!guard.rows[0]?.locked) {
127
+ port.postMessage({ type: "fatal", error: { code: "PG_SINGLE_INSTANCE", message: SINGLE_INSTANCE_ERROR } });
128
+ signalReady();
129
+ try { await client.end(); } catch { /* main will terminate this worker */ }
130
+ return;
131
+ }
132
+ connected = true;
133
+ port.postMessage({ type: "ready" });
134
+ signalReady();
135
+ if (queue.length && !draining) void drain();
136
+ } catch (error) {
137
+ port.postMessage({ type: "fatal", error: serialize(error) });
138
+ signalReady();
139
+ }
140
+ }
141
+
142
+ parentPort.on("message", (message) => {
143
+ if (message?.type !== "init" || client) return;
144
+ port = message.port;
145
+ port.on("message", handlePortMessage);
146
+ parentPort.close();
147
+ void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
148
+ });