@narumitw/pi-chat 0.1.6 → 0.1.8

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 (49) hide show
  1. package/README.md +17 -34
  2. package/dist/chunks/{chat-view-EZ24L3LM.js → chat-view-7OBZGYZM.ts} +2 -2
  3. package/dist/chunks/chat-view-7OBZGYZM.ts.map +7 -0
  4. package/dist/chunks/{chunk-ZR2JESR5.js → chunk-7FD7DDSU.ts} +6 -36
  5. package/dist/chunks/chunk-7FD7DDSU.ts.map +7 -0
  6. package/dist/chunks/{chunk-XYZZR6DW.js → chunk-EOZIFFAD.ts} +6 -23
  7. package/dist/chunks/chunk-EOZIFFAD.ts.map +7 -0
  8. package/dist/chunks/{chunk-UE3UAOJX.js → chunk-LN3NAZRC.ts} +1 -1
  9. package/dist/chunks/{chunk-UE3UAOJX.js.map → chunk-LN3NAZRC.ts.map} +1 -1
  10. package/dist/chunks/{chunk-OQLAKS7O.js → chunk-MHSYNYS3.ts} +4 -7
  11. package/dist/chunks/chunk-MHSYNYS3.ts.map +7 -0
  12. package/dist/chunks/{chunk-UQPD3L6X.js → chunk-WUCSLYAK.ts} +1 -1
  13. package/dist/chunks/chunk-WUCSLYAK.ts.map +7 -0
  14. package/dist/chunks/{directory-network-EWFZFLGK.js → directory-network-6OPGA4EH.ts} +7 -19
  15. package/dist/chunks/directory-network-6OPGA4EH.ts.map +7 -0
  16. package/dist/chunks/{menu-2KEDM6NJ.js → menu-S7MZCVYM.ts} +5 -5
  17. package/dist/chunks/menu-S7MZCVYM.ts.map +7 -0
  18. package/dist/chunks/{network-MXCIGGQ2.js → network-Y4Z4JJ5J.ts} +3 -3
  19. package/dist/chunks/network-Y4Z4JJ5J.ts.map +7 -0
  20. package/dist/chunks/{widget-4OBABJDY.js → widget-QT53EBN6.ts} +4 -10
  21. package/dist/chunks/widget-QT53EBN6.ts.map +7 -0
  22. package/dist/index.ts +20 -66
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +54 -55
  25. package/src/chat-session.ts +571 -594
  26. package/src/chat-view.ts +221 -226
  27. package/src/directory-network.ts +347 -365
  28. package/src/external.d.ts +56 -66
  29. package/src/identity.ts +74 -88
  30. package/src/menu.ts +535 -541
  31. package/src/network-contract.ts +5 -5
  32. package/src/network.ts +154 -157
  33. package/src/nickname.ts +6 -6
  34. package/src/pi-chat.ts +700 -774
  35. package/src/protocol.ts +296 -335
  36. package/src/public-room-directory.ts +276 -310
  37. package/src/room.ts +54 -58
  38. package/src/settings.ts +234 -259
  39. package/src/text.ts +57 -57
  40. package/src/widget.ts +56 -72
  41. package/dist/chunks/chat-view-EZ24L3LM.js.map +0 -7
  42. package/dist/chunks/chunk-OQLAKS7O.js.map +0 -7
  43. package/dist/chunks/chunk-UQPD3L6X.js.map +0 -7
  44. package/dist/chunks/chunk-XYZZR6DW.js.map +0 -7
  45. package/dist/chunks/chunk-ZR2JESR5.js.map +0 -7
  46. package/dist/chunks/directory-network-EWFZFLGK.js.map +0 -7
  47. package/dist/chunks/menu-2KEDM6NJ.js.map +0 -7
  48. package/dist/chunks/network-MXCIGGQ2.js.map +0 -7
  49. package/dist/chunks/widget-4OBABJDY.js.map +0 -7
package/src/settings.ts CHANGED
@@ -11,332 +11,307 @@ const MAX_SETTINGS_BYTES = 64 * 1024;
11
11
  export type WidgetMode = "dock" | "count" | "latest" | "off";
12
12
 
13
13
  export type RememberedRoom =
14
- | { id: string; kind: "public"; slug: string }
15
- | { id: string; kind: "private"; invite: string };
14
+ | { id: string; kind: "public"; slug: string }
15
+ | { id: string; kind: "private"; invite: string };
16
16
 
17
17
  export interface ChatResumeSettings {
18
- rooms: RememberedRoom[];
19
- activeRoomId: string;
20
- surface: "chat" | "pi";
18
+ rooms: RememberedRoom[];
19
+ activeRoomId: string;
20
+ surface: "chat" | "pi";
21
21
  }
22
22
 
23
23
  export interface ChatSettings {
24
- nickname?: string;
25
- identitySeed?: string;
26
- widgetMode?: WidgetMode;
27
- resume?: ChatResumeSettings;
24
+ nickname?: string;
25
+ identitySeed?: string;
26
+ widgetMode?: WidgetMode;
27
+ resume?: ChatResumeSettings;
28
28
  }
29
29
 
30
30
  export type ChatSettingsPatch = Partial<Omit<ChatSettings, "resume">> & {
31
- resume?: ChatResumeSettings | null;
31
+ resume?: ChatResumeSettings | null;
32
32
  };
33
33
 
34
34
  export type ChatSettingsLoadResult =
35
- | { kind: "missing" }
36
- | { kind: "invalid"; reason: string }
37
- | { kind: "loaded"; settings: ChatSettings };
35
+ | { kind: "missing" }
36
+ | { kind: "invalid"; reason: string }
37
+ | { kind: "loaded"; settings: ChatSettings };
38
38
 
39
39
  export interface UpdateChatSettingsOptions {
40
- settingsPath?: string;
41
- signal?: AbortSignal;
42
- beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
43
- setPrivateMode?: (path: string) => Promise<void>;
40
+ settingsPath?: string;
41
+ signal?: AbortSignal;
42
+ beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
43
+ setPrivateMode?: (path: string) => Promise<void>;
44
44
  }
45
45
 
46
46
  type SettingsDocument = Record<string, unknown>;
47
47
  const queues = new Map<string, Promise<void>>();
48
48
 
49
49
  export function chatSettingsPath(): string {
50
- return join(getAgentDir(), CHAT_SETTINGS_FILE);
50
+ return join(getAgentDir(), CHAT_SETTINGS_FILE);
51
51
  }
52
52
 
53
53
  export function normalizeChatSettings(value: unknown): ChatSettings | undefined {
54
- if (!isRecord(value)) return undefined;
55
- const settings: ChatSettings = {};
56
- if (Object.hasOwn(value, "nickname")) {
57
- const nickname = normalizeNickname(value.nickname);
58
- if (!nickname) return undefined;
59
- settings.nickname = nickname;
60
- }
61
- if (Object.hasOwn(value, "identitySeed")) {
62
- if (typeof value.identitySeed !== "string" || !validSeed(value.identitySeed)) return undefined;
63
- settings.identitySeed = value.identitySeed;
64
- }
65
- if (Object.hasOwn(value, "widgetMode")) {
66
- if (
67
- value.widgetMode !== "dock" &&
68
- value.widgetMode !== "count" &&
69
- value.widgetMode !== "latest" &&
70
- value.widgetMode !== "off"
71
- ) {
72
- return undefined;
73
- }
74
- settings.widgetMode = value.widgetMode;
75
- }
76
- if (Object.hasOwn(value, "resume")) {
77
- const resume = normalizeResumeSettings(value.resume);
78
- if (!resume || !settings.nickname || !settings.identitySeed) return undefined;
79
- settings.resume = resume;
80
- }
81
- return settings;
54
+ if (!isRecord(value)) return undefined;
55
+ const settings: ChatSettings = {};
56
+ if (Object.hasOwn(value, "nickname")) {
57
+ const nickname = normalizeNickname(value.nickname);
58
+ if (!nickname) return undefined;
59
+ settings.nickname = nickname;
60
+ }
61
+ if (Object.hasOwn(value, "identitySeed")) {
62
+ if (typeof value.identitySeed !== "string" || !validSeed(value.identitySeed)) return undefined;
63
+ settings.identitySeed = value.identitySeed;
64
+ }
65
+ if (Object.hasOwn(value, "widgetMode")) {
66
+ if (
67
+ value.widgetMode !== "dock" &&
68
+ value.widgetMode !== "count" &&
69
+ value.widgetMode !== "latest" &&
70
+ value.widgetMode !== "off"
71
+ ) {
72
+ return undefined;
73
+ }
74
+ settings.widgetMode = value.widgetMode;
75
+ }
76
+ if (Object.hasOwn(value, "resume")) {
77
+ const resume = normalizeResumeSettings(value.resume);
78
+ if (!resume || !settings.nickname || !settings.identitySeed) return undefined;
79
+ settings.resume = resume;
80
+ }
81
+ return settings;
82
82
  }
83
83
 
84
- export async function readChatSettings(
85
- settingsPath = chatSettingsPath(),
86
- ): Promise<ChatSettingsLoadResult> {
87
- await queues.get(settingsPath);
88
- try {
89
- const contents = await readSettings(settingsPath);
90
- try {
91
- const settings = normalizeChatSettings(JSON.parse(contents) as unknown);
92
- return settings
93
- ? { kind: "loaded", settings }
94
- : { kind: "invalid", reason: `${settingsPath}: invalid settings shape` };
95
- } catch {
96
- return { kind: "invalid", reason: `${settingsPath}: invalid JSON` };
97
- }
98
- } catch (error) {
99
- if (isNodeError(error) && error.code === "ENOENT") return { kind: "missing" };
100
- return { kind: "invalid", reason: `${settingsPath}: ${safeError(error)}` };
101
- }
84
+ export async function readChatSettings(settingsPath = chatSettingsPath()): Promise<ChatSettingsLoadResult> {
85
+ await queues.get(settingsPath);
86
+ try {
87
+ const contents = await readSettings(settingsPath);
88
+ try {
89
+ const settings = normalizeChatSettings(JSON.parse(contents) as unknown);
90
+ return settings
91
+ ? { kind: "loaded", settings }
92
+ : { kind: "invalid", reason: `${settingsPath}: invalid settings shape` };
93
+ } catch {
94
+ return { kind: "invalid", reason: `${settingsPath}: invalid JSON` };
95
+ }
96
+ } catch (error) {
97
+ if (isNodeError(error) && error.code === "ENOENT") return { kind: "missing" };
98
+ return { kind: "invalid", reason: `${settingsPath}: ${safeError(error)}` };
99
+ }
102
100
  }
103
101
 
104
102
  export function updateChatSettings(
105
- patch: ChatSettingsPatch,
106
- options: UpdateChatSettingsOptions = {},
103
+ patch: ChatSettingsPatch,
104
+ options: UpdateChatSettingsOptions = {},
107
105
  ): Promise<ChatSettings> {
108
- const settingsPath = options.settingsPath ?? chatSettingsPath();
109
- return enqueue(settingsPath, async () => {
110
- options.signal?.throwIfAborted();
111
- const current = await readDocumentForUpdate(settingsPath);
112
- const updated: SettingsDocument = { ...current, ...patch };
113
- if (Object.hasOwn(patch, "resume")) {
114
- if (patch.resume === null) delete updated.resume;
115
- else if (patch.resume === undefined) {
116
- if (Object.hasOwn(current, "resume")) updated.resume = current.resume;
117
- else delete updated.resume;
118
- } else updated.resume = mergeResumeDocument(current.resume, patch.resume);
119
- }
120
- const settings = normalizeChatSettings(updated);
121
- if (!settings) throw new Error(`Pi Chat settings at ${settingsPath} have an invalid shape.`);
122
- await publish(settingsPath, updated, options);
123
- return settings;
124
- });
106
+ const settingsPath = options.settingsPath ?? chatSettingsPath();
107
+ return enqueue(settingsPath, async () => {
108
+ options.signal?.throwIfAborted();
109
+ const current = await readDocumentForUpdate(settingsPath);
110
+ const updated: SettingsDocument = { ...current, ...patch };
111
+ if (Object.hasOwn(patch, "resume")) {
112
+ if (patch.resume === null) delete updated.resume;
113
+ else if (patch.resume === undefined) {
114
+ if (Object.hasOwn(current, "resume")) updated.resume = current.resume;
115
+ else delete updated.resume;
116
+ } else updated.resume = mergeResumeDocument(current.resume, patch.resume);
117
+ }
118
+ const settings = normalizeChatSettings(updated);
119
+ if (!settings) throw new Error(`Pi Chat settings at ${settingsPath} have an invalid shape.`);
120
+ await publish(settingsPath, updated, options);
121
+ return settings;
122
+ });
125
123
  }
126
124
 
127
125
  export function rememberedRoomFromDescriptor(room: RoomDescriptor): RememberedRoom {
128
- if (room.kind === "public") {
129
- const slug = room.label.startsWith("#") ? room.label.slice(1) : room.label;
130
- const reconstructed = createPublicRoom(slug);
131
- if (reconstructed.id !== room.id) throw new Error("Public room descriptor is inconsistent.");
132
- return { id: room.id, kind: "public", slug };
133
- }
134
- if (!room.invite || parseInvite(room.invite).id !== room.id) {
135
- throw new Error("Private room descriptor is inconsistent.");
136
- }
137
- return { id: room.id, kind: "private", invite: room.invite };
126
+ if (room.kind === "public") {
127
+ const slug = room.label.startsWith("#") ? room.label.slice(1) : room.label;
128
+ const reconstructed = createPublicRoom(slug);
129
+ if (reconstructed.id !== room.id) throw new Error("Public room descriptor is inconsistent.");
130
+ return { id: room.id, kind: "public", slug };
131
+ }
132
+ if (!room.invite || parseInvite(room.invite).id !== room.id) {
133
+ throw new Error("Private room descriptor is inconsistent.");
134
+ }
135
+ return { id: room.id, kind: "private", invite: room.invite };
138
136
  }
139
137
 
140
138
  export function descriptorFromRememberedRoom(room: RememberedRoom): RoomDescriptor {
141
- const descriptor =
142
- room.kind === "public" ? createPublicRoom(room.slug) : parseInvite(room.invite);
143
- if (descriptor.id !== room.id) throw new Error("Remembered room is inconsistent.");
144
- return descriptor;
139
+ const descriptor = room.kind === "public" ? createPublicRoom(room.slug) : parseInvite(room.invite);
140
+ if (descriptor.id !== room.id) throw new Error("Remembered room is inconsistent.");
141
+ return descriptor;
145
142
  }
146
143
 
147
144
  export async function awaitChatSettingsWrites(settingsPath = chatSettingsPath()): Promise<void> {
148
- await queues.get(settingsPath);
145
+ await queues.get(settingsPath);
149
146
  }
150
147
 
151
148
  function enqueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
152
- const previous = queues.get(path) ?? Promise.resolve();
153
- const result = previous.then(operation, operation);
154
- const settled = result.then(
155
- () => undefined,
156
- () => undefined,
157
- );
158
- queues.set(path, settled);
159
- void settled.finally(() => {
160
- if (queues.get(path) === settled) queues.delete(path);
161
- });
162
- return result;
149
+ const previous = queues.get(path) ?? Promise.resolve();
150
+ const result = previous.then(operation, operation);
151
+ const settled = result.then(
152
+ () => undefined,
153
+ () => undefined,
154
+ );
155
+ queues.set(path, settled);
156
+ void settled.finally(() => {
157
+ if (queues.get(path) === settled) queues.delete(path);
158
+ });
159
+ return result;
163
160
  }
164
161
 
165
162
  async function readDocumentForUpdate(path: string): Promise<SettingsDocument> {
166
- let contents: string;
167
- try {
168
- contents = await readSettings(path);
169
- } catch (error) {
170
- if (isNodeError(error) && error.code === "ENOENT") return {};
171
- throw new Error(`Pi Chat settings at ${path} are invalid: ${safeError(error)}`);
172
- }
173
- let value: unknown;
174
- try {
175
- value = JSON.parse(contents) as unknown;
176
- } catch {
177
- throw new Error(`Pi Chat settings at ${path} are invalid: invalid JSON`);
178
- }
179
- if (!isRecord(value) || !normalizeChatSettings(value)) {
180
- throw new Error(`Pi Chat settings at ${path} are invalid: invalid settings shape`);
181
- }
182
- return value;
163
+ let contents: string;
164
+ try {
165
+ contents = await readSettings(path);
166
+ } catch (error) {
167
+ if (isNodeError(error) && error.code === "ENOENT") return {};
168
+ throw new Error(`Pi Chat settings at ${path} are invalid: ${safeError(error)}`);
169
+ }
170
+ let value: unknown;
171
+ try {
172
+ value = JSON.parse(contents) as unknown;
173
+ } catch {
174
+ throw new Error(`Pi Chat settings at ${path} are invalid: invalid JSON`);
175
+ }
176
+ if (!isRecord(value) || !normalizeChatSettings(value)) {
177
+ throw new Error(`Pi Chat settings at ${path} are invalid: invalid settings shape`);
178
+ }
179
+ return value;
183
180
  }
184
181
 
185
182
  async function readSettings(path: string): Promise<string> {
186
- const pathStats = await lstat(path);
187
- if (pathStats.isSymbolicLink() || !pathStats.isFile()) {
188
- throw new Error("settings path is not a regular file");
189
- }
190
- const noFollow = constants.O_NOFOLLOW ?? 0;
191
- const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
192
- try {
193
- const stats = await handle.stat();
194
- if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
195
- throw new Error("settings path changed while opening");
196
- }
197
- if (stats.size > MAX_SETTINGS_BYTES) {
198
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
199
- }
200
- const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
201
- let offset = 0;
202
- while (offset < buffer.length) {
203
- const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
204
- if (bytesRead === 0) break;
205
- offset += bytesRead;
206
- }
207
- if (offset > MAX_SETTINGS_BYTES)
208
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
209
- try {
210
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
211
- buffer.subarray(0, offset),
212
- );
213
- } catch {
214
- throw new Error("settings file is not valid UTF-8");
215
- }
216
- } finally {
217
- await handle.close();
218
- }
183
+ const pathStats = await lstat(path);
184
+ if (pathStats.isSymbolicLink() || !pathStats.isFile()) {
185
+ throw new Error("settings path is not a regular file");
186
+ }
187
+ const noFollow = constants.O_NOFOLLOW ?? 0;
188
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
189
+ try {
190
+ const stats = await handle.stat();
191
+ if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
192
+ throw new Error("settings path changed while opening");
193
+ }
194
+ if (stats.size > MAX_SETTINGS_BYTES) {
195
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
196
+ }
197
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
198
+ let offset = 0;
199
+ while (offset < buffer.length) {
200
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
201
+ if (bytesRead === 0) break;
202
+ offset += bytesRead;
203
+ }
204
+ if (offset > MAX_SETTINGS_BYTES) throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
205
+ try {
206
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));
207
+ } catch {
208
+ throw new Error("settings file is not valid UTF-8");
209
+ }
210
+ } finally {
211
+ await handle.close();
212
+ }
219
213
  }
220
214
 
221
- async function publish(
222
- path: string,
223
- document: SettingsDocument,
224
- options: UpdateChatSettingsOptions,
225
- ): Promise<void> {
226
- options.signal?.throwIfAborted();
227
- const contents = `${JSON.stringify(document, null, 2)}\n`;
228
- if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
229
- throw new Error(`Pi Chat settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
230
- }
231
- const directory = dirname(path);
232
- await mkdir(directory, { recursive: true });
233
- const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
234
- try {
235
- await writeFile(temporaryPath, contents, {
236
- encoding: "utf8",
237
- flag: "wx",
238
- mode: 0o600,
239
- signal: options.signal,
240
- });
241
- await options.beforeRename?.(temporaryPath, path);
242
- options.signal?.throwIfAborted();
243
- if (process.platform !== "win32") {
244
- await (options.setPrivateMode ?? ((target) => chmod(target, 0o600)))(temporaryPath);
245
- options.signal?.throwIfAborted();
246
- }
247
- await rename(temporaryPath, path);
248
- } catch (error) {
249
- await rm(temporaryPath, { force: true }).catch(() => undefined);
250
- throw error;
251
- }
215
+ async function publish(path: string, document: SettingsDocument, options: UpdateChatSettingsOptions): Promise<void> {
216
+ options.signal?.throwIfAborted();
217
+ const contents = `${JSON.stringify(document, null, 2)}\n`;
218
+ if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
219
+ throw new Error(`Pi Chat settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
220
+ }
221
+ const directory = dirname(path);
222
+ await mkdir(directory, { recursive: true });
223
+ const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
224
+ try {
225
+ await writeFile(temporaryPath, contents, {
226
+ encoding: "utf8",
227
+ flag: "wx",
228
+ mode: 0o600,
229
+ signal: options.signal,
230
+ });
231
+ await options.beforeRename?.(temporaryPath, path);
232
+ options.signal?.throwIfAborted();
233
+ if (process.platform !== "win32") {
234
+ await (options.setPrivateMode ?? ((target) => chmod(target, 0o600)))(temporaryPath);
235
+ options.signal?.throwIfAborted();
236
+ }
237
+ await rename(temporaryPath, path);
238
+ } catch (error) {
239
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
240
+ throw error;
241
+ }
252
242
  }
253
243
 
254
244
  function normalizeResumeSettings(value: unknown): ChatResumeSettings | undefined {
255
- if (!isRecord(value) || !Array.isArray(value.rooms)) return undefined;
256
- if (value.rooms.length === 0 || value.rooms.length > 16) return undefined;
257
- if (typeof value.activeRoomId !== "string") return undefined;
258
- if (value.surface !== "chat" && value.surface !== "pi") return undefined;
259
- const rooms: RememberedRoom[] = [];
260
- const ids = new Set<string>();
261
- let activeRoomId: string | undefined;
262
- for (const candidate of value.rooms) {
263
- const room = normalizeRememberedRoom(candidate);
264
- if (!room || ids.has(room.id)) return undefined;
265
- ids.add(room.id);
266
- rooms.push(room);
267
- if (
268
- isRecord(candidate) &&
269
- (candidate.id === value.activeRoomId || room.id === value.activeRoomId)
270
- ) {
271
- activeRoomId = room.id;
272
- }
273
- }
274
- if (!activeRoomId || !ids.has(activeRoomId)) return undefined;
275
- return { rooms, activeRoomId, surface: value.surface };
245
+ if (!isRecord(value) || !Array.isArray(value.rooms)) return undefined;
246
+ if (value.rooms.length === 0 || value.rooms.length > 16) return undefined;
247
+ if (typeof value.activeRoomId !== "string") return undefined;
248
+ if (value.surface !== "chat" && value.surface !== "pi") return undefined;
249
+ const rooms: RememberedRoom[] = [];
250
+ const ids = new Set<string>();
251
+ let activeRoomId: string | undefined;
252
+ for (const candidate of value.rooms) {
253
+ const room = normalizeRememberedRoom(candidate);
254
+ if (!room || ids.has(room.id)) return undefined;
255
+ ids.add(room.id);
256
+ rooms.push(room);
257
+ if (isRecord(candidate) && (candidate.id === value.activeRoomId || room.id === value.activeRoomId)) {
258
+ activeRoomId = room.id;
259
+ }
260
+ }
261
+ if (!activeRoomId || !ids.has(activeRoomId)) return undefined;
262
+ return { rooms, activeRoomId, surface: value.surface };
276
263
  }
277
264
 
278
265
  function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
279
- if (!isRecord(value) || typeof value.id !== "string") return undefined;
280
- try {
281
- if (
282
- value.kind === "public" &&
283
- typeof value.slug === "string" &&
284
- !Object.hasOwn(value, "invite")
285
- ) {
286
- const room = createPublicRoom(value.slug);
287
- return isCompatibleRoomId(room, value.id)
288
- ? { id: room.id, kind: "public", slug: value.slug }
289
- : undefined;
290
- }
291
- if (
292
- value.kind === "private" &&
293
- typeof value.invite === "string" &&
294
- !Object.hasOwn(value, "slug")
295
- ) {
296
- const room = parseInvite(value.invite);
297
- return isCompatibleRoomId(room, value.id)
298
- ? { id: room.id, kind: "private", invite: value.invite }
299
- : undefined;
300
- }
301
- } catch {
302
- return undefined;
303
- }
304
- return undefined;
266
+ if (!isRecord(value) || typeof value.id !== "string") return undefined;
267
+ try {
268
+ if (value.kind === "public" && typeof value.slug === "string" && !Object.hasOwn(value, "invite")) {
269
+ const room = createPublicRoom(value.slug);
270
+ return isCompatibleRoomId(room, value.id) ? { id: room.id, kind: "public", slug: value.slug } : undefined;
271
+ }
272
+ if (value.kind === "private" && typeof value.invite === "string" && !Object.hasOwn(value, "slug")) {
273
+ const room = parseInvite(value.invite);
274
+ return isCompatibleRoomId(room, value.id) ? { id: room.id, kind: "private", invite: value.invite } : undefined;
275
+ }
276
+ } catch {
277
+ return undefined;
278
+ }
279
+ return undefined;
305
280
  }
306
281
 
307
282
  function mergeResumeDocument(current: unknown, next: ChatResumeSettings): SettingsDocument {
308
- const currentResume = isRecord(current) ? current : {};
309
- const existingRooms = new Map<string, SettingsDocument>();
310
- if (Array.isArray(currentResume.rooms)) {
311
- for (const candidate of currentResume.rooms) {
312
- const normalized = normalizeRememberedRoom(candidate);
313
- if (normalized && isRecord(candidate)) existingRooms.set(normalized.id, candidate);
314
- }
315
- }
316
- return {
317
- ...currentResume,
318
- rooms: next.rooms.map((room) => ({ ...existingRooms.get(room.id), ...room })),
319
- activeRoomId: next.activeRoomId,
320
- surface: next.surface,
321
- };
283
+ const currentResume = isRecord(current) ? current : {};
284
+ const existingRooms = new Map<string, SettingsDocument>();
285
+ if (Array.isArray(currentResume.rooms)) {
286
+ for (const candidate of currentResume.rooms) {
287
+ const normalized = normalizeRememberedRoom(candidate);
288
+ if (normalized && isRecord(candidate)) existingRooms.set(normalized.id, candidate);
289
+ }
290
+ }
291
+ return {
292
+ ...currentResume,
293
+ rooms: next.rooms.map((room) => ({ ...existingRooms.get(room.id), ...room })),
294
+ activeRoomId: next.activeRoomId,
295
+ surface: next.surface,
296
+ };
322
297
  }
323
298
 
324
299
  function validSeed(value: string): boolean {
325
- try {
326
- return /^[A-Za-z0-9_-]{43}$/u.test(value) && Buffer.from(value, "base64url").length === 32;
327
- } catch {
328
- return false;
329
- }
300
+ try {
301
+ return /^[A-Za-z0-9_-]{43}$/u.test(value) && Buffer.from(value, "base64url").length === 32;
302
+ } catch {
303
+ return false;
304
+ }
330
305
  }
331
306
 
332
307
  function isRecord(value: unknown): value is SettingsDocument {
333
- return typeof value === "object" && value !== null && !Array.isArray(value);
308
+ return typeof value === "object" && value !== null && !Array.isArray(value);
334
309
  }
335
310
 
336
311
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
337
- return error instanceof Error && "code" in error;
312
+ return error instanceof Error && "code" in error;
338
313
  }
339
314
 
340
315
  function safeError(error: unknown): string {
341
- return error instanceof Error ? error.message : String(error);
316
+ return error instanceof Error ? error.message : String(error);
342
317
  }