@alexsun-top/opencode-chat-room 0.7.2 → 0.7.4

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 (77) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +11 -4
  3. package/README.zh-CN.md +11 -4
  4. package/cli.ts +26 -6
  5. package/dist/cli.js +7804 -0
  6. package/package.json +19 -6
  7. package/plugin.ts +7 -4
  8. package/server/admin-auth.ts +1 -1
  9. package/server/admin-routes.ts +2 -2
  10. package/server/admin-state.ts +2 -1
  11. package/server/assets/chat/admin.js +43 -3
  12. package/server/assets/chat/announcements.js +5 -3
  13. package/server/assets/chat/confirm-dialog.js +12 -2
  14. package/server/assets/chat/create-room-dialog.js +5 -3
  15. package/server/assets/chat/events.js +32 -7
  16. package/server/assets/chat/files.js +368 -0
  17. package/server/assets/chat/index.js +6 -0
  18. package/server/assets/chat/locales/de.js +17 -1
  19. package/server/assets/chat/locales/es.js +17 -1
  20. package/server/assets/chat/locales/fr.js +17 -1
  21. package/server/assets/chat/locales/it.js +17 -1
  22. package/server/assets/chat/locales/ja.js +17 -1
  23. package/server/assets/chat/locales/ko.js +17 -1
  24. package/server/assets/chat/markdown.js +10 -3
  25. package/server/assets/chat/message-polling.js +61 -6
  26. package/server/assets/chat/message-window.js +28 -0
  27. package/server/assets/chat/messages.js +29 -4
  28. package/server/assets/chat/palette.js +384 -0
  29. package/server/assets/chat/rooms.js +8 -3
  30. package/server/assets/chat/search.js +137 -0
  31. package/server/assets/chat/settings.js +11 -5
  32. package/server/assets/chat/state.js +34 -2
  33. package/server/assets/code-highlight.css +2 -5
  34. package/server/assets/edit-room.css +77 -0
  35. package/server/assets/files.css +237 -0
  36. package/server/assets/palette.css +277 -0
  37. package/server/assets/responsive.css +3 -2
  38. package/server/assets/room-create.css +42 -43
  39. package/server/assets/settings.css +6 -3
  40. package/server/chat-server.ts +46 -29
  41. package/server/chat.html +129 -33
  42. package/server/http-server.ts +182 -0
  43. package/server/join-requests.ts +5 -4
  44. package/server/manifest.webmanifest +1 -1
  45. package/server/member-routes.ts +3 -3
  46. package/server/message-recall-routes.ts +1 -1
  47. package/server/newrooms.ts +4 -4
  48. package/server/resource-routes.ts +19 -4
  49. package/server/room-join.ts +8 -3
  50. package/server/room-payload.ts +1 -1
  51. package/server/sw.js +3 -0
  52. package/server/wake.ts +1 -1
  53. package/skills/chatroom/SKILL.md +1 -1
  54. package/src/README.md +4 -2
  55. package/src/config/file-config.ts +294 -0
  56. package/src/rooms/resource-read.ts +2 -1
  57. package/src/rooms/resource-upload.ts +6 -3
  58. package/src/rooms/resources.ts +7 -2
  59. package/src/runtime/v2-plugin.ts +2 -2
  60. package/src/runtime/watch.ts +13 -8
  61. package/src/state/receiver-state.ts +3 -5
  62. package/src/state/sqlite-state.ts +11 -7
  63. package/src/state/sqlite.ts +80 -0
  64. package/src/state/store.ts +1 -0
  65. package/src/tui/app.mjs +417 -0
  66. package/src/tui/config.mjs +194 -0
  67. package/src/tui/http.mjs +103 -0
  68. package/src/tui/main.mjs +176 -0
  69. package/src/tui/messages.mjs +67 -0
  70. package/src/tui/palette-app.mjs +265 -0
  71. package/src/tui/palette.mjs +101 -0
  72. package/src/tui/session.mjs +40 -0
  73. package/src/tui/ui-content.mjs +426 -0
  74. package/src/tui/ui-theme.mjs +60 -0
  75. package/src/tui/ui-view.mjs +452 -0
  76. package/src/tui/ui.mjs +262 -0
  77. package/src/tests/announcement-board.ts +0 -186
@@ -1,6 +1,7 @@
1
1
  // Shared state facade for the standalone SQLite database.
2
2
  // (rooms + registry), identity, and formatting. Used by plugin.ts (standalone
3
3
  // mode) and server/chat-server.ts (central mode).
4
+ import { Buffer } from "node:buffer";
4
5
  import path from "node:path";
5
6
  import os from "node:os";
6
7
  import RoomService, { type Message, type Room } from "../rooms/room-service.ts";
@@ -0,0 +1,417 @@
1
+ // Headless chat state for the TUI. Kept free of terminal and palette code so
2
+ // the reducer can be tested against a fake api. Palette methods are attached
3
+ // from palette-app.mjs.
4
+ import { attachPalette } from "./palette-app.mjs";
5
+ import { mergeMessages, messageStamp, oldestSeq } from "./messages.mjs";
6
+
7
+ const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];
8
+
9
+ const errorText = (error) => (error instanceof Error ? error.message : String(error ?? "unknown error"));
10
+
11
+ const normalizeRoom = (room) => ({
12
+ id: String(room.id ?? ""),
13
+ name: String(room.name ?? room.id ?? "room"),
14
+ participants: Array.isArray(room.participants) ? room.participants : [],
15
+ joined: room.joined === true,
16
+ });
17
+
18
+ export class ChatApp {
19
+ constructor({ api, sessionID, participant, host = "", autoPoll = true, schedule = (fn, ms) => setTimeout(fn, ms) }) {
20
+ this.api = api;
21
+ this.sessionID = sessionID;
22
+ this.participant = participant;
23
+ this.autoPoll = autoPoll;
24
+ this.schedule = schedule;
25
+ this.closed = false;
26
+ this.pollToken = 0;
27
+ this.timers = new Set();
28
+ this.pollAbort = null;
29
+ this.cache = new Map();
30
+ this.historyCursor = new Map();
31
+ this.historyMore = new Map();
32
+ this.historyPages = new Map();
33
+ this.historyInflight = new Set();
34
+ this.listeners = new Set();
35
+ this.state = {
36
+ host,
37
+ participant,
38
+ connection: "connecting",
39
+ rooms: [],
40
+ selected: 0,
41
+ current: null,
42
+ joined: false,
43
+ messages: [],
44
+ pending: null,
45
+ focus: "rooms",
46
+ draft: "",
47
+ highlight: null,
48
+ help: false,
49
+ status: "",
50
+ statusKind: "info",
51
+ palette: null,
52
+ quit: false,
53
+ };
54
+ }
55
+
56
+ subscribe(listener) {
57
+ this.listeners.add(listener);
58
+ return () => this.listeners.delete(listener);
59
+ }
60
+
61
+ touch() {
62
+ for (const listener of this.listeners) listener(this.state);
63
+ }
64
+
65
+ later(fn, ms) {
66
+ if (this.closed) return undefined;
67
+ let timer;
68
+ const run = () => {
69
+ if (timer !== undefined) this.timers.delete(timer);
70
+ return fn();
71
+ };
72
+ timer = this.schedule(run, ms);
73
+ if (timer !== undefined) this.timers.add(timer);
74
+ return timer;
75
+ }
76
+
77
+ setStatus(text, kind = "info") {
78
+ this.state.status = text;
79
+ this.state.statusKind = kind;
80
+ this.touch();
81
+ }
82
+
83
+ async init() {
84
+ await this.refreshRooms(true);
85
+ }
86
+
87
+ async refreshRooms(quiet = false) {
88
+ try {
89
+ const list = await this.api.listRooms(this.sessionID);
90
+ const rooms = (Array.isArray(list) ? list : []).map(normalizeRoom);
91
+ const selectedID = this.state.rooms[this.state.selected]?.id;
92
+ this.state.rooms = rooms;
93
+ const found = selectedID ? rooms.findIndex((room) => room.id === selectedID) : -1;
94
+ this.state.selected = found >= 0 ? found : Math.min(this.state.selected, Math.max(0, rooms.length - 1));
95
+ this.state.connection = "online";
96
+ if (!quiet) {
97
+ this.state.status = "room list refreshed";
98
+ this.state.statusKind = "info";
99
+ }
100
+ this.touch();
101
+ return true;
102
+ } catch (error) {
103
+ this.state.connection = "offline";
104
+ this.state.status = `could not refresh rooms: ${errorText(error)}`;
105
+ this.state.statusKind = "error";
106
+ this.touch();
107
+ return false;
108
+ }
109
+ }
110
+
111
+ isCurrent(roomID) {
112
+ return this.state.current?.id === roomID;
113
+ }
114
+
115
+ async openSelected() {
116
+ return this.openRoom(this.state.selected);
117
+ }
118
+
119
+ async openRoom(indexOrRoom) {
120
+ const index = typeof indexOrRoom === "number" ? indexOrRoom : this.state.rooms.indexOf(indexOrRoom);
121
+ const summary = this.state.rooms[index];
122
+ if (!summary) return;
123
+ this.state.selected = index;
124
+ this.stopPolling();
125
+ this.state.current = { id: summary.id, name: summary.name, participants: summary.participants };
126
+ this.state.joined = summary.joined;
127
+ this.state.messages = [];
128
+ this.state.pending = null;
129
+ this.state.highlight = null;
130
+ this.state.status = `opening #${summary.name}`;
131
+ this.state.statusKind = "info";
132
+ this.touch();
133
+ if (summary.joined) await this.loadRoom(summary.id);
134
+ else await this.joinRoom(summary.id);
135
+ }
136
+
137
+ async joinRoom(roomID) {
138
+ try {
139
+ const result = await this.api.join(roomID, this.sessionID, this.participant);
140
+ if (!this.isCurrent(roomID)) return;
141
+ if (result?.pending) {
142
+ const message = String(result.message ?? "join request pending; waiting for approval");
143
+ this.state.pending = { roomId: roomID, message };
144
+ this.state.joined = false;
145
+ this.state.status = message;
146
+ this.state.statusKind = "info";
147
+ this.touch();
148
+ this.later(() => this.checkJoin(roomID), 1500);
149
+ return;
150
+ }
151
+ this.enterRoom(result?.room ?? result, roomID, true);
152
+ } catch (error) {
153
+ if (this.isCurrent(roomID)) this.setStatus(`could not join: ${errorText(error)}`, "error");
154
+ }
155
+ }
156
+
157
+ async checkJoin(roomID) {
158
+ if (this.closed || !this.isCurrent(roomID) || this.state.pending?.roomId !== roomID) return;
159
+ try {
160
+ const result = await this.api.joinStatus(roomID, this.sessionID);
161
+ if (!this.isCurrent(roomID) || this.state.pending?.roomId !== roomID) return;
162
+ const status = typeof result === "string" ? result : result?.status;
163
+ if (status === "joined") {
164
+ this.state.pending = null;
165
+ this.setStatus("join request approved", "success");
166
+ await this.loadRoom(roomID);
167
+ return;
168
+ }
169
+ if (status === "pending") {
170
+ this.later(() => this.checkJoin(roomID), 1500);
171
+ return;
172
+ }
173
+ this.state.pending = null;
174
+ this.setStatus("join request is no longer pending - press Enter to try again", "error");
175
+ } catch {
176
+ this.later(() => this.checkJoin(roomID), 1500);
177
+ }
178
+ }
179
+
180
+ async loadRoom(roomID) {
181
+ try {
182
+ const room = await this.api.getRoom(roomID);
183
+ if (!this.isCurrent(roomID) || !room) return;
184
+ if (room.joined === false) {
185
+ this.notJoined(roomID, "not a member of this room");
186
+ return;
187
+ }
188
+ this.enterRoom(room, roomID, false);
189
+ } catch (error) {
190
+ if (this.isCurrent(roomID)) this.setStatus(`could not open room: ${errorText(error)}`, "error");
191
+ }
192
+ }
193
+
194
+ enterRoom(room, roomID, joinedNow) {
195
+ if (!room || typeof room !== "object") {
196
+ this.setStatus("room data is missing", "error");
197
+ return;
198
+ }
199
+ const summary = this.state.rooms.find((item) => item.id === roomID);
200
+ if (summary) {
201
+ summary.joined = true;
202
+ summary.name = String(room.name ?? summary.name);
203
+ if (Array.isArray(room.participants)) summary.participants = room.participants;
204
+ }
205
+ const cache = this.historyList(roomID);
206
+ mergeMessages(cache, room.messages);
207
+ this.state.current = {
208
+ id: roomID,
209
+ name: String(room.name ?? summary?.name ?? roomID),
210
+ participants: Array.isArray(room.participants) ? room.participants : summary?.participants ?? [],
211
+ };
212
+ this.state.joined = true;
213
+ this.state.pending = null;
214
+ this.state.messages = cache;
215
+ this.state.connection = "online";
216
+ this.state.status = joinedNow ? `joined #${this.state.current.name}` : "";
217
+ this.state.statusKind = "success";
218
+ if (typeof room.hasMore === "boolean") this.historyMore.set(roomID, room.hasMore);
219
+ const oldest = oldestSeq(cache);
220
+ if (oldest !== undefined) this.historyCursor.set(roomID, oldest);
221
+ this.touch();
222
+ this.markRead();
223
+ if (this.autoPoll) this.startPolling();
224
+ }
225
+
226
+ historyList(roomID) {
227
+ let list = this.cache.get(roomID);
228
+ if (!list) {
229
+ list = [];
230
+ this.cache.set(roomID, list);
231
+ }
232
+ return list;
233
+ }
234
+
235
+ merge(items) {
236
+ mergeMessages(this.state.messages, items);
237
+ }
238
+
239
+ lastTs() {
240
+ return this.state.messages.reduce((max, message) => Math.max(max, messageStamp(message)), 0);
241
+ }
242
+
243
+ async pollOnce() {
244
+ const room = this.state.current;
245
+ if (!room || !this.state.joined) return false;
246
+ const roomID = room.id;
247
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
248
+ this.pollAbort = controller;
249
+ try {
250
+ const result = await this.api.poll(
251
+ roomID,
252
+ this.sessionID,
253
+ this.lastTs(),
254
+ controller ? { signal: controller.signal } : undefined,
255
+ );
256
+ if (!this.isCurrent(roomID)) return false;
257
+ if (!result || result.member === false) {
258
+ this.notJoined(roomID, "you are no longer a member of this room");
259
+ return false;
260
+ }
261
+ const wasOffline = this.state.connection !== "online";
262
+ this.merge(result.items);
263
+ this.state.connection = "online";
264
+ if (wasOffline) {
265
+ this.state.status = "reconnected";
266
+ this.state.statusKind = "success";
267
+ }
268
+ this.touch();
269
+ this.markRead();
270
+ return true;
271
+ } catch (error) {
272
+ if (controller?.signal.aborted) return false;
273
+ this.state.connection = "reconnecting";
274
+ this.state.status = `connection lost: ${errorText(error)} - retrying`;
275
+ this.state.statusKind = "error";
276
+ this.touch();
277
+ return false;
278
+ } finally {
279
+ if (this.pollAbort === controller) this.pollAbort = null;
280
+ }
281
+ }
282
+
283
+ startPolling() {
284
+ const token = ++this.pollToken;
285
+ let delay = 0;
286
+ const step = async () => {
287
+ if (this.closed || token !== this.pollToken || !this.state.joined) return;
288
+ const ok = await this.pollOnce();
289
+ if (this.closed || token !== this.pollToken || !this.state.joined) return;
290
+ delay = ok ? 0 : Math.min(delay ? delay * 2 : BACKOFF_MS[0], BACKOFF_MS.at(-1));
291
+ this.later(step, delay);
292
+ };
293
+ step();
294
+ }
295
+
296
+ stopPolling() {
297
+ this.pollToken += 1;
298
+ this.pollAbort?.abort();
299
+ }
300
+
301
+ notJoined(roomID, message) {
302
+ if (!this.isCurrent(roomID)) return;
303
+ this.state.joined = false;
304
+ const summary = this.state.rooms.find((room) => room.id === roomID);
305
+ if (summary) summary.joined = false;
306
+ this.setStatus(message, "error");
307
+ }
308
+
309
+ markRead() {
310
+ const room = this.state.current;
311
+ const newest = this.lastTs();
312
+ if (!room || !newest) return;
313
+ try {
314
+ const result = this.api.markRead?.(room.id, this.sessionID, newest);
315
+ if (result && typeof result.catch === "function") result.catch(() => {});
316
+ } catch {
317
+ // A read receipt failure must not interrupt the UI.
318
+ }
319
+ }
320
+
321
+ async send() {
322
+ const text = String(this.state.draft ?? "").trim();
323
+ if (!text) return;
324
+ const room = this.state.current;
325
+ if (!room || !this.state.joined) {
326
+ this.setStatus("join a room before sending", "error");
327
+ return;
328
+ }
329
+ this.state.draft = "";
330
+ this.touch();
331
+ try {
332
+ const result = await this.api.send(room.id, this.sessionID, text);
333
+ if (!this.isCurrent(room.id)) return;
334
+ if (Array.isArray(result?.messages)) this.merge(result.messages);
335
+ else if (result?.id) this.merge([result]);
336
+ this.state.highlight = null;
337
+ this.state.connection = "online";
338
+ this.setStatus("sent", "success");
339
+ this.markRead();
340
+ } catch (error) {
341
+ if (!this.state.draft) this.state.draft = text;
342
+ this.setStatus(`send failed: ${errorText(error)}`, "error");
343
+ }
344
+ }
345
+
346
+ setDraft(text) {
347
+ this.state.draft = String(text ?? "");
348
+ }
349
+
350
+ appendDraft(text) {
351
+ this.state.draft += String(text ?? "");
352
+ this.state.focus = "composer";
353
+ this.state.help = false;
354
+ this.touch();
355
+ }
356
+
357
+ moveSelection(delta) {
358
+ if (!this.state.rooms.length) return;
359
+ this.state.selected = Math.min(
360
+ this.state.rooms.length - 1,
361
+ Math.max(0, this.state.selected + delta),
362
+ );
363
+ this.state.highlight = null;
364
+ this.touch();
365
+ }
366
+
367
+ selectRoom(index) {
368
+ if (!this.state.rooms[index]) return;
369
+ this.state.selected = index;
370
+ this.state.highlight = null;
371
+ this.touch();
372
+ }
373
+
374
+ toggleFocus() {
375
+ this.state.focus = this.state.focus === "rooms" ? "composer" : "rooms";
376
+ if (this.state.focus === "composer") this.state.help = false;
377
+ this.touch();
378
+ }
379
+
380
+ toggleHelp() {
381
+ this.state.help = !this.state.help;
382
+ this.touch();
383
+ }
384
+
385
+ clearOrBlur() {
386
+ this.state.draft = "";
387
+ this.state.focus = "rooms";
388
+ this.state.highlight = null;
389
+ this.touch();
390
+ }
391
+
392
+ clearHighlight() {
393
+ if (!this.state.highlight) return;
394
+ this.state.highlight = null;
395
+ this.touch();
396
+ }
397
+
398
+ quit() {
399
+ this.state.quit = true;
400
+ this.close();
401
+ this.touch();
402
+ }
403
+
404
+ close() {
405
+ this.closed = true;
406
+ this.pollToken += 1;
407
+ this.pollAbort?.abort();
408
+ for (const timer of this.timers) clearTimeout(timer);
409
+ this.timers.clear();
410
+ }
411
+ }
412
+
413
+ attachPalette(ChatApp);
414
+
415
+ export function createApp(options) {
416
+ return new ChatApp(options);
417
+ }
@@ -0,0 +1,194 @@
1
+ // Runtime-neutral chatroom config loader for the TUI: JSON, JSONC and YAML,
2
+ // with environment variables overriding file values.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { parse as parseYaml } from "yaml";
7
+
8
+ export const FILE_NAMES = ["chatroom.json", "chatroom.jsonc", "chatroom.yaml", "chatroom.yml"];
9
+ export const DEFAULT_PARTICIPANT = "chatroom-tui";
10
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 10000;
11
+
12
+ const URL_HINT = "set CHAT_ROOM_SERVER_URL or client.url in your chatroom config";
13
+
14
+ function asRecord(value, where) {
15
+ if (value === undefined) return undefined;
16
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
17
+ throw new Error(`chatroom TUI: ${where} must be an object`);
18
+ }
19
+ return value;
20
+ }
21
+
22
+ function optionalString(value, where) {
23
+ if (value === undefined) return undefined;
24
+ if (typeof value !== "string") throw new Error(`chatroom TUI: ${where} must be a string`);
25
+ return value;
26
+ }
27
+
28
+ function optionalNumber(value, where) {
29
+ if (value === undefined) return undefined;
30
+ if (typeof value !== "number" || !Number.isFinite(value)) {
31
+ throw new Error(`chatroom TUI: ${where} must be a finite number`);
32
+ }
33
+ return value;
34
+ }
35
+
36
+ function parseClient(value) {
37
+ const raw = asRecord(value, "client");
38
+ if (!raw) return undefined;
39
+ const requestTimeoutMs = optionalNumber(raw.requestTimeoutMs, "client.requestTimeoutMs");
40
+ if (requestTimeoutMs !== undefined && requestTimeoutMs <= 0) {
41
+ throw new Error("chatroom TUI: client.requestTimeoutMs must be greater than zero");
42
+ }
43
+ return {
44
+ url: optionalString(raw.url, "client.url"),
45
+ token: optionalString(raw.token, "client.token"),
46
+ participant: optionalString(raw.participant, "client.participant"),
47
+ requestTimeoutMs,
48
+ };
49
+ }
50
+
51
+ function parseConfig(value) {
52
+ const raw = asRecord(value, "root");
53
+ if (!raw) return {};
54
+ return {
55
+ url: optionalString(raw.url, "url"),
56
+ token: optionalString(raw.token, "token"),
57
+ client: parseClient(raw.client),
58
+ };
59
+ }
60
+
61
+ /** Remove comments and trailing commas without touching quoted strings. */
62
+ function stripJsonc(source) {
63
+ let out = "";
64
+ let quote = "";
65
+ let escaped = false;
66
+ let comma = -1;
67
+ for (let i = 0; i < source.length; i++) {
68
+ const char = source[i];
69
+ const next = source[i + 1];
70
+ if (quote) {
71
+ out += char;
72
+ if (escaped) escaped = false;
73
+ else if (char === "\\") escaped = true;
74
+ else if (char === quote) quote = "";
75
+ continue;
76
+ }
77
+ if (char === '"') {
78
+ quote = char;
79
+ comma = -1;
80
+ out += char;
81
+ continue;
82
+ }
83
+ if (char === "/" && next === "/") {
84
+ while (i < source.length && source[i] !== "\n") i++;
85
+ out += "\n";
86
+ continue;
87
+ }
88
+ if (char === "/" && next === "*") {
89
+ i += 2;
90
+ while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i++;
91
+ i++;
92
+ continue;
93
+ }
94
+ if (char === ",") {
95
+ comma = out.length;
96
+ out += char;
97
+ continue;
98
+ }
99
+ if (char === "}" || char === "]") {
100
+ if (comma >= 0) out = out.slice(0, comma) + out.slice(comma + 1);
101
+ comma = -1;
102
+ out += char;
103
+ continue;
104
+ }
105
+ if (!/\s/.test(char)) comma = -1;
106
+ out += char;
107
+ }
108
+ return out;
109
+ }
110
+
111
+ function parseFile(file) {
112
+ let text;
113
+ try {
114
+ text = readFileSync(file, "utf8");
115
+ } catch {
116
+ throw new Error(`chatroom TUI: cannot read ${file}`);
117
+ }
118
+ const extension = path.extname(file).toLowerCase();
119
+ try {
120
+ if (extension === ".yaml" || extension === ".yml") return parseConfig(parseYaml(text));
121
+ if (extension === ".jsonc") return parseConfig(JSON.parse(stripJsonc(text)));
122
+ if (extension === ".json") return parseConfig(JSON.parse(text));
123
+ try {
124
+ return parseConfig(JSON.parse(text));
125
+ } catch {
126
+ return parseConfig(parseYaml(text));
127
+ }
128
+ } catch (error) {
129
+ if (error instanceof SyntaxError || error?.name === "YAMLParseError") {
130
+ // Never include parser source text: a malformed file may contain a token.
131
+ throw new Error(`chatroom TUI: ${file} is not valid JSON/YAML`);
132
+ }
133
+ throw error;
134
+ }
135
+ }
136
+
137
+ function expandHome(value, home) {
138
+ return value.startsWith("~/") ? path.join(home, value.slice(2)) : value;
139
+ }
140
+
141
+ /** Resolve the config path; an explicit CHAT_ROOM_CONFIG must exist. */
142
+ export function findTuiConfigFile(env = process.env, cwd = process.cwd()) {
143
+ const home = env.HOME || os.homedir();
144
+ const explicit = env.CHAT_ROOM_CONFIG?.trim();
145
+ if (explicit) {
146
+ const file = path.resolve(cwd, expandHome(explicit, home));
147
+ if (!existsSync(file)) throw new Error(`chatroom TUI: CHAT_ROOM_CONFIG file does not exist: ${file}`);
148
+ return file;
149
+ }
150
+ const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
151
+ for (const dir of [...new Set([cwd, path.join(configHome, "chatroom")])]) {
152
+ for (const name of FILE_NAMES) {
153
+ const file = path.join(dir, name);
154
+ if (existsSync(file)) return file;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ export function loadTuiConfig(env = process.env, cwd = process.cwd()) {
161
+ const file = findTuiConfigFile(env, cwd);
162
+ return file ? parseFile(file) : null;
163
+ }
164
+
165
+ function envValue(env, key) {
166
+ const value = env[key];
167
+ return value === undefined || value === "" ? undefined : value;
168
+ }
169
+
170
+ function stateFile(env, cwd, home) {
171
+ const explicit = envValue(env, "CHAT_ROOM_TUI_STATE");
172
+ if (explicit) return path.resolve(cwd, expandHome(explicit, home));
173
+ const stateHome = env.XDG_STATE_HOME || path.join(home, ".local", "state");
174
+ return path.join(stateHome, "chatroom-tui", "session.json");
175
+ }
176
+
177
+ export function resolveTuiConfig(env = process.env, cwd = process.cwd()) {
178
+ const file = loadTuiConfig(env, cwd);
179
+ const home = env.HOME || os.homedir();
180
+ const url = (envValue(env, "CHAT_ROOM_SERVER_URL") ?? file?.client?.url ?? file?.url ?? "")
181
+ .trim().replace(/\/+$/, "");
182
+ if (!url) throw new Error(`chatroom TUI: server URL is not set; ${URL_HINT}`);
183
+ if (!/^https?:\/\/[^/]+/i.test(url)) {
184
+ throw new Error(`chatroom TUI: server URL must be an http(s) URL; ${URL_HINT}`);
185
+ }
186
+ const name = envValue(env, "CHAT_ROOM_TUI_NAME") ?? file?.client?.participant ?? DEFAULT_PARTICIPANT;
187
+ return {
188
+ url,
189
+ token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.client?.token ?? file?.token ?? "",
190
+ participant: name.trim().slice(0, 64) || DEFAULT_PARTICIPANT,
191
+ requestTimeoutMs: file?.client?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
192
+ stateFile: stateFile(env, cwd, home),
193
+ };
194
+ }