@alexsun-top/opencode-chat-room 0.8.0 → 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 (161) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +2 -2
  3. package/README.md +38 -6
  4. package/README.zh-CN.md +38 -6
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +5074 -3212
  7. package/package.json +23 -3
  8. package/packages/chat-room-channeld/README.md +98 -25
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
  10. package/packages/chat-room-channeld/src/adapter.ts +36 -2
  11. package/packages/chat-room-channeld/src/config.ts +63 -1
  12. package/packages/chat-room-channeld/src/delivery.ts +6 -1
  13. package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
  14. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  15. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  16. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  17. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  18. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  19. package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
  20. package/packages/chat-room-channeld/src/host.ts +120 -2
  21. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  22. package/packages/chat-room-channeld/src/state.ts +17 -0
  23. package/packages/chat-room-channeld/src/stats.ts +43 -1
  24. package/server/admin-state.ts +13 -13
  25. package/server/app.ts +95 -0
  26. package/server/assets/NOTICE.txt +2 -1
  27. package/server/assets/base.css +15 -9
  28. package/server/assets/chat/announcements.js +70 -7
  29. package/server/assets/chat/doc-preview.js +184 -35
  30. package/server/assets/chat/events.js +3 -0
  31. package/server/assets/chat/files.js +46 -4
  32. package/server/assets/chat/index.js +2 -0
  33. package/server/assets/chat/integration-editor.js +163 -0
  34. package/server/assets/chat/integration-values.js +124 -0
  35. package/server/assets/chat/integrations.js +498 -0
  36. package/server/assets/chat/locales/de.js +40 -4
  37. package/server/assets/chat/locales/es.js +40 -4
  38. package/server/assets/chat/locales/fr.js +40 -4
  39. package/server/assets/chat/locales/it.js +40 -4
  40. package/server/assets/chat/locales/ja.js +40 -4
  41. package/server/assets/chat/locales/ko.js +40 -4
  42. package/server/assets/chat/markdown.js +22 -8
  43. package/server/assets/chat/messages.js +5 -5
  44. package/server/assets/chat/office-preview.js +69 -0
  45. package/server/assets/chat/panels.js +36 -0
  46. package/server/assets/chat/recall.js +58 -7
  47. package/server/assets/chat/receipts.js +15 -3
  48. package/server/assets/chat/reminders.js +69 -8
  49. package/server/assets/chat/resource-format.js +11 -0
  50. package/server/assets/chat/settings.js +30 -2
  51. package/server/assets/chat/side-pane.js +1 -2
  52. package/server/assets/chat/state.js +93 -10
  53. package/server/assets/chat/system-events.js +32 -0
  54. package/server/assets/chat/system-messages.js +23 -14
  55. package/server/assets/chat/task-row.js +0 -6
  56. package/server/assets/chat/tasks.js +121 -33
  57. package/server/assets/code-highlight.css +55 -32
  58. package/server/assets/conversation.css +123 -23
  59. package/server/assets/doc-preview.css +35 -3
  60. package/server/assets/files.css +5 -0
  61. package/server/assets/fluent-icons.svg +2 -0
  62. package/server/assets/monaco/LICENSE +21 -0
  63. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  64. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  65. package/server/assets/monaco/editor.worker.js +45 -0
  66. package/server/assets/monaco/integration-rules.css +1 -0
  67. package/server/assets/monaco/integration-rules.js +1297 -0
  68. package/server/assets/monaco/json.worker.js +77 -0
  69. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  70. package/server/assets/office/docx.bundle.js +33 -0
  71. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  72. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  73. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  74. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  75. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  76. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  77. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  78. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  79. package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
  80. package/server/assets/office/pptx.bundle.js +104 -0
  81. package/server/assets/office/xlsx.bundle.js +141 -0
  82. package/server/assets/recall.css +5 -4
  83. package/server/assets/responsive.css +50 -11
  84. package/server/assets/settings.css +73 -1
  85. package/server/assets/tasks.css +57 -7
  86. package/server/channel-integration.ts +519 -0
  87. package/server/channel-settings.ts +77 -0
  88. package/server/channels.ts +261 -18
  89. package/server/chat-server.ts +32 -580
  90. package/server/chat.html +187 -21
  91. package/server/http-server.ts +3 -182
  92. package/server/resource-routes.ts +16 -16
  93. package/server/routes/inbox.ts +100 -0
  94. package/server/routes/pages.ts +83 -0
  95. package/server/routes/questions.ts +39 -0
  96. package/server/routes/room-actions.ts +162 -0
  97. package/server/routes/rooms.ts +160 -0
  98. package/server/startup.ts +84 -0
  99. package/server/sw.js +4 -0
  100. package/server/task-routes.ts +1 -1
  101. package/src/center/center-client.ts +2 -10
  102. package/src/config/file-config.ts +7 -54
  103. package/src/platform/http-server.ts +182 -0
  104. package/src/protocol/addressing.ts +21 -0
  105. package/src/protocol/config.ts +58 -0
  106. package/src/protocol/room.ts +51 -0
  107. package/src/rooms/resources.ts +26 -16
  108. package/src/rooms/room-service.ts +2 -48
  109. package/src/rooms/storage.ts +329 -0
  110. package/src/rooms/tasks.ts +21 -5
  111. package/src/runtime/watch.ts +1 -1
  112. package/src/state/pg-database.ts +183 -0
  113. package/src/state/pg-migrate.ts +175 -0
  114. package/src/state/pg-sql.mjs +175 -0
  115. package/src/state/pg-worker.mjs +148 -0
  116. package/src/state/sqlite-announcements.ts +25 -0
  117. package/src/state/sqlite-database.ts +121 -0
  118. package/src/state/sqlite-legacy.ts +90 -0
  119. package/src/state/sqlite-members.ts +155 -0
  120. package/src/state/sqlite-messages.ts +288 -0
  121. package/src/state/sqlite-resources.ts +39 -0
  122. package/src/state/sqlite-rooms.ts +87 -0
  123. package/src/state/sqlite-schema.ts +80 -0
  124. package/src/state/sqlite-state-store.ts +33 -0
  125. package/src/state/sqlite-state.ts +15 -897
  126. package/src/state/sqlite-tasks.ts +65 -0
  127. package/src/state/sqlite-transaction.ts +13 -0
  128. package/src/state/sqlite.ts +21 -1
  129. package/src/state/store.ts +5 -1
  130. package/src/tui/app.mjs +32 -19
  131. package/src/tui/config.mjs +12 -4
  132. package/src/tui/i18n.mjs +38 -0
  133. package/src/tui/info-app.mjs +50 -51
  134. package/src/tui/info-content.mjs +79 -44
  135. package/src/tui/join-app.mjs +9 -9
  136. package/src/tui/locales/en.mjs +349 -0
  137. package/src/tui/locales/zh-CN.mjs +349 -0
  138. package/src/tui/main.mjs +85 -37
  139. package/src/tui/markdown.mjs +3 -2
  140. package/src/tui/mentions.mjs +3 -1
  141. package/src/tui/message-app.mjs +22 -21
  142. package/src/tui/message-view.mjs +2 -1
  143. package/src/tui/palette-app.mjs +9 -8
  144. package/src/tui/palette.mjs +30 -24
  145. package/src/tui/prefs.mjs +92 -0
  146. package/src/tui/reminder-app.mjs +18 -17
  147. package/src/tui/room-settings-app.mjs +30 -28
  148. package/src/tui/settings-app.mjs +153 -0
  149. package/src/tui/ui-content.mjs +65 -86
  150. package/src/tui/ui-help.mjs +73 -0
  151. package/src/tui/ui-overlay-view.mjs +23 -7
  152. package/src/tui/ui-suggest.mjs +6 -5
  153. package/src/tui/ui-theme.mjs +37 -33
  154. package/src/tui/ui-view.mjs +22 -7
  155. package/src/tui/ui.mjs +15 -3
  156. package/src/web/editor.worker.ts +1 -0
  157. package/src/web/integration-rules-editor.ts +439 -0
  158. package/src/web/integration-rules.ts +22 -0
  159. package/src/web/integration-schema.ts +228 -0
  160. package/src/web/json.worker.ts +1 -0
  161. package/src/web/office-viewer.ts +221 -0
@@ -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
+ });
@@ -0,0 +1,25 @@
1
+ import { openStateDatabase } from "./sqlite-database.ts";
2
+ import { immediate } from "./sqlite-transaction.ts";
3
+
4
+ export type Announcement = { roomID: string; name: string; content: string; updatedAt: number };
5
+ export async function listAnnouncements(file: string, roomID: string): Promise<Announcement[]> {
6
+ const db = await openStateDatabase(file);
7
+ if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return [];
8
+ return db.query("SELECT room_id AS roomID,name,content,updated_at AS updatedAt FROM announcements WHERE room_id=? ORDER BY name").all(roomID) as Announcement[];
9
+ }
10
+ export async function getAnnouncement(file: string, roomID: string, name: string): Promise<Announcement | undefined> {
11
+ const db = await openStateDatabase(file);
12
+ return db.query("SELECT room_id AS roomID,name,content,updated_at AS updatedAt FROM announcements WHERE room_id=? AND name=?").get(roomID, name) as Announcement | undefined;
13
+ }
14
+ export async function putAnnouncement(file: string, roomID: string, name: string, content: string, updatedAt: number): Promise<Announcement | undefined> {
15
+ const db = await openStateDatabase(file);
16
+ return immediate(db, () => {
17
+ if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return undefined;
18
+ db.query("INSERT INTO announcements(room_id,name,content,updated_at) VALUES(?,?,?,?) ON CONFLICT(room_id,name) DO UPDATE SET content=excluded.content,updated_at=excluded.updated_at").run(roomID, name, content, updatedAt);
19
+ return { roomID, name, content, updatedAt };
20
+ });
21
+ }
22
+ export async function deleteAnnouncement(file: string, roomID: string, name: string): Promise<boolean> {
23
+ const db = await openStateDatabase(file);
24
+ return immediate(db, () => db.query("DELETE FROM announcements WHERE room_id=? AND name=?").run(roomID, name).changes > 0);
25
+ }
@@ -0,0 +1,121 @@
1
+ import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Database, isBusyError, type StateDatabase } from "./sqlite.ts";
4
+ import { PgDatabase } from "./pg-database.ts";
5
+ import { initializeSchema } from "./sqlite-schema.ts";
6
+ import { migrate } from "./sqlite-legacy.ts";
7
+ import { immediate, pause } from "./sqlite-transaction.ts";
8
+
9
+ const databases = new Map<string, Promise<StateDatabase>>();
10
+
11
+ // Set CHAT_ROOM_DATABASE_URL only on the server process. The PostgreSQL
12
+ // backend is experimental and single-instance in 0.8.1; the PgDatabase worker
13
+ // holds a session advisory lock and a second process fails startup.
14
+ function postgresURL(): string | undefined {
15
+ const value = process.env.CHAT_ROOM_DATABASE_URL?.trim();
16
+ return value || undefined;
17
+ }
18
+
19
+ export function openStateDatabase(file: string): Promise<StateDatabase> {
20
+ const url = postgresURL();
21
+ const key = url ? `postgres:${url}` : `sqlite:${file}`;
22
+ const known = databases.get(key);
23
+ if (known) return known;
24
+ const pending = url ? initializePostgres(url) : initialize(file);
25
+ databases.set(key, pending);
26
+ void pending.catch(() => databases.delete(key));
27
+ return pending;
28
+ }
29
+
30
+ // Test and shutdown hook. PgDatabase.close() waits for client.end() so the
31
+ // single-instance session lock is released before a new connection is opened.
32
+ export async function closeStateDatabases(): Promise<void> {
33
+ const pending = [...databases.values()];
34
+ databases.clear();
35
+ const settled = await Promise.allSettled(pending);
36
+ for (const result of settled) {
37
+ if (result.status === "fulfilled") { try { result.value.close(); } catch { /* already closed */ } }
38
+ }
39
+ }
40
+
41
+ export async function withStateTransaction<T>(file: string, callback: (db: StateDatabase) => T): Promise<T> {
42
+ const db = await openStateDatabase(file);
43
+ return immediate(db, () => callback(db));
44
+ }
45
+
46
+ export async function initializeAdminSchema(file: string): Promise<void> {
47
+ await withStateTransaction(file, db => {
48
+ db.exec(`CREATE TABLE IF NOT EXISTS admin_rooms(room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE,target_room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,receiver_owner_id TEXT NOT NULL,membership_id TEXT NOT NULL,generation INTEGER NOT NULL,enrollment_hash TEXT NOT NULL,enrollment_expires INTEGER NOT NULL,capability_hash TEXT,created_at INTEGER NOT NULL);
49
+ CREATE TABLE IF NOT EXISTS admin_tasks(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,admin_generation INTEGER NOT NULL DEFAULT 1,target_room_id TEXT NOT NULL,target_session_id TEXT NOT NULL,target_owner_id TEXT NOT NULL DEFAULT '',target_membership_id TEXT NOT NULL DEFAULT '',text TEXT NOT NULL,status TEXT NOT NULL,progress TEXT NOT NULL,delivery_token_hash TEXT NOT NULL DEFAULT '',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);
50
+ CREATE TABLE IF NOT EXISTS admin_plans(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,name TEXT NOT NULL,interval_seconds INTEGER NOT NULL,text TEXT NOT NULL,paused INTEGER NOT NULL,next_run_at INTEGER NOT NULL,created_at INTEGER NOT NULL);
51
+ CREATE TABLE IF NOT EXISTS admin_deliveries(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,generation INTEGER NOT NULL,recipient_room_id TEXT NOT NULL DEFAULT '',session_id TEXT NOT NULL,owner_id TEXT NOT NULL,membership_id TEXT NOT NULL,kind TEXT NOT NULL,text TEXT NOT NULL,task_id TEXT,task_token TEXT,admission_id TEXT NOT NULL,created_at INTEGER NOT NULL,acknowledged INTEGER NOT NULL DEFAULT 0,UNIQUE(admin_room_id,kind,task_id));
52
+ CREATE INDEX IF NOT EXISTS admin_delivery_target ON admin_deliveries(session_id,owner_id,acknowledged);`);
53
+ const taskColumns = db.query("PRAGMA table_info(admin_tasks)").all() as Array<{ name: string }>;
54
+ if (!taskColumns.some(column => column.name === "delivery_token_hash")) db.exec("ALTER TABLE admin_tasks ADD COLUMN delivery_token_hash TEXT NOT NULL DEFAULT ''");
55
+ if (!taskColumns.some(column => column.name === "admin_generation")) db.exec("ALTER TABLE admin_tasks ADD COLUMN admin_generation INTEGER NOT NULL DEFAULT 1");
56
+ if (!taskColumns.some(column => column.name === "target_owner_id")) db.exec("ALTER TABLE admin_tasks ADD COLUMN target_owner_id TEXT NOT NULL DEFAULT ''");
57
+ if (!taskColumns.some(column => column.name === "target_membership_id")) db.exec("ALTER TABLE admin_tasks ADD COLUMN target_membership_id TEXT NOT NULL DEFAULT ''");
58
+ const deliveryColumns = db.query("PRAGMA table_info(admin_deliveries)").all() as Array<{ name: string }>;
59
+ if (!deliveryColumns.some(column => column.name === "task_token")) db.exec("ALTER TABLE admin_deliveries ADD COLUMN task_token TEXT");
60
+ if (!deliveryColumns.some(column => column.name === "recipient_room_id")) db.exec("ALTER TABLE admin_deliveries ADD COLUMN recipient_room_id TEXT NOT NULL DEFAULT ''");
61
+ db.exec("UPDATE admin_deliveries SET admission_id='msg_' || substr(admission_id,7) WHERE admission_id LIKE 'admin:%'");
62
+ });
63
+ }
64
+
65
+ export async function initializeReminderSchema(file: string): Promise<void> {
66
+ await withStateTransaction(file, db => db.exec(`CREATE TABLE IF NOT EXISTS room_reminders(
67
+ id TEXT PRIMARY KEY, room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
68
+ creator_session_id TEXT NOT NULL, text TEXT NOT NULL, schedule_type TEXT NOT NULL,
69
+ at TEXT, expression TEXT, timezone TEXT, paused INTEGER NOT NULL DEFAULT 0,
70
+ next_run_at INTEGER NOT NULL, created_at INTEGER NOT NULL, last_error TEXT);`));
71
+ await withStateTransaction(file, db => {
72
+ const columns = db.query("PRAGMA table_info(room_reminders)").all() as Array<{ name: string }>;
73
+ if (!columns.some(column => column.name === "initiator")) db.exec("ALTER TABLE room_reminders ADD COLUMN initiator TEXT NOT NULL DEFAULT ''");
74
+ if (!columns.some(column => column.name === "last_error")) db.exec("ALTER TABLE room_reminders ADD COLUMN last_error TEXT");
75
+ });
76
+ }
77
+
78
+ async function initializePostgres(connectionString: string): Promise<StateDatabase> {
79
+ const db = new PgDatabase(connectionString);
80
+ try {
81
+ await initializeSchema(db);
82
+ // Legacy rooms.json/registry.json migration is SQLite-only. The migrate
83
+ // command copies an existing SQLite state database into PostgreSQL.
84
+ return db;
85
+ } catch (error) {
86
+ db.close();
87
+ throw error;
88
+ }
89
+ }
90
+
91
+ async function initialize(file: string): Promise<StateDatabase> {
92
+ const directory = path.dirname(file);
93
+ const hint = "Make that directory writable by the process user; in Docker use a named volume or chown it to uid 10001.";
94
+ try { mkdirSync(directory, { recursive: true, mode: 0o700 }); }
95
+ catch (error) { throw new Error(`cannot create the state directory ${directory}: ${(error as Error).message}. ${hint}`); }
96
+ // A mounted state directory may belong to another user (Docker bind mount);
97
+ // tightening its mode is best effort, not a reason to refuse to start.
98
+ try { chmodSync(directory, 0o700); } catch { /* keep the mounted permissions */ }
99
+ // Create the file 0600 up front so the default umask never leaves chat history
100
+ // readable by other users, even for the instant before the chmod below runs.
101
+ try { writeFileSync(file, "", { flag: "wx", mode: 0o600 }); }
102
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw new Error(`cannot create the state database ${file}: ${(error as Error).message}. ${hint}`); }
103
+ let db: Database;
104
+ try { db = new Database(file, { create: true }); }
105
+ catch (error) { throw new Error(`cannot open the state database ${file}: ${(error as Error).message}. ${hint}`); }
106
+ try { chmodSync(file, 0o600); } catch { console.warn(`[chat-room] could not tighten permissions on ${file}; check who owns the state directory`); }
107
+ try {
108
+ for (let attempt = 0; ; attempt++) {
109
+ try {
110
+ db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;");
111
+ await initializeSchema(db);
112
+ await migrate(db, file);
113
+ db.exec("PRAGMA busy_timeout=50;");
114
+ return db;
115
+ } catch (error) {
116
+ if (!isBusyError(error) || attempt >= 7) throw error;
117
+ await pause(Math.min(20 * 2 ** attempt, 250));
118
+ }
119
+ }
120
+ } catch (error) { db.close(); throw error; }
121
+ }