@narumitw/pi-chat 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,386 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ChatIdentity } from "./identity.js";
3
+ import { signIdentityPayload, verifyIdentityPayload } from "./identity.js";
4
+ import {
5
+ createPublicRoom,
6
+ MAX_EVENT_AGE_MS,
7
+ MAX_FRAME_BYTES,
8
+ MAX_GOSSIP_HOPS,
9
+ } from "./protocol.js";
10
+
11
+ const MAX_EVENT_FUTURE_MS = 60_000;
12
+ const DIRECTORY_RECORD_TTL_MS = 90_000;
13
+ const MAX_DIRECTORY_RECORDS = 4_096;
14
+ const MAX_DIRECTORY_ROOMS = 512;
15
+ const MAX_DIRECTORY_SEEN = 16_384;
16
+ const DIRECTORY_SEEN_TTL_MS = 10 * 60_000;
17
+ const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
18
+ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
19
+
20
+ export const PUBLIC_ROOM_DIRECTORY_TOPIC = createHash("sha256")
21
+ .update("pi-chat/public-room-directory/v2", "utf8")
22
+ .digest();
23
+
24
+ export interface DirectoryPresence {
25
+ v: 2;
26
+ kind: "directory-presence";
27
+ slug: string;
28
+ origin: string;
29
+ id: string;
30
+ issuedAt: number;
31
+ status: "online" | "leaving";
32
+ signature: string;
33
+ }
34
+
35
+ export interface DirectoryWireMessage {
36
+ v: 2;
37
+ type: "directory";
38
+ event: DirectoryPresence;
39
+ hops: number;
40
+ partial?: true;
41
+ }
42
+
43
+ export interface PublicRoomListing {
44
+ slug: string;
45
+ estimatedParticipants: number;
46
+ }
47
+
48
+ export interface PublicRoomBrowseResult {
49
+ rooms: PublicRoomListing[];
50
+ partial: boolean;
51
+ }
52
+
53
+ export interface DirectoryCatalogOptions {
54
+ now?: () => number;
55
+ maxRecords?: number;
56
+ maxRooms?: number;
57
+ }
58
+
59
+ interface SeenRecord {
60
+ key: string;
61
+ expiresAt: number;
62
+ }
63
+
64
+ export class DirectoryCatalog {
65
+ private readonly now: () => number;
66
+ private readonly maxRecords: number;
67
+ private readonly maxRooms: number;
68
+ private readonly records = new Map<string, DirectoryPresence>();
69
+ private readonly seen = new Map<string, number>();
70
+ private readonly seenOrder: SeenRecord[] = [];
71
+ private truncated = false;
72
+
73
+ constructor(options: DirectoryCatalogOptions = {}) {
74
+ this.now = options.now ?? Date.now;
75
+ this.maxRecords = positiveBound(options.maxRecords, MAX_DIRECTORY_RECORDS);
76
+ this.maxRooms = positiveBound(options.maxRooms, MAX_DIRECTORY_ROOMS);
77
+ }
78
+
79
+ accept(event: DirectoryPresence): boolean {
80
+ const now = this.now();
81
+ if (!verifyDirectoryPresence(event, now)) return false;
82
+ const seenKey = `${event.origin}:${event.id}`;
83
+ if (this.hasSeen(seenKey)) return false;
84
+ this.remember(seenKey);
85
+ const existing = this.records.get(event.origin);
86
+ if (
87
+ existing &&
88
+ (existing.issuedAt > event.issuedAt ||
89
+ (existing.issuedAt === event.issuedAt && existing.id.localeCompare(event.id) >= 0))
90
+ ) {
91
+ return false;
92
+ }
93
+ if (!existing && this.records.size >= this.maxRecords) {
94
+ this.truncated = true;
95
+ return false;
96
+ }
97
+ const knownSlugs = new Set(
98
+ [...this.records.values()]
99
+ .filter(({ status }) => status === "online")
100
+ .map(({ slug }) => slug),
101
+ );
102
+ if (
103
+ event.status === "online" &&
104
+ !knownSlugs.has(event.slug) &&
105
+ knownSlugs.size >= this.maxRooms
106
+ ) {
107
+ this.truncated = true;
108
+ return false;
109
+ }
110
+ this.records.set(event.origin, event);
111
+ return true;
112
+ }
113
+
114
+ snapshot(): PublicRoomBrowseResult {
115
+ this.prune();
116
+ const counts = new Map<string, number>();
117
+ for (const event of this.records.values()) {
118
+ if (event.status === "online") {
119
+ counts.set(event.slug, (counts.get(event.slug) ?? 0) + 1);
120
+ }
121
+ }
122
+ return {
123
+ rooms: sortDirectoryRooms(
124
+ [...counts].map(([slug, estimatedParticipants]) => ({ slug, estimatedParticipants })),
125
+ ),
126
+ partial: this.truncated,
127
+ };
128
+ }
129
+
130
+ currentEvents(): DirectoryPresence[] {
131
+ this.prune();
132
+ return [...this.records.values()].sort(
133
+ (left, right) => right.issuedAt - left.issuedAt || left.origin.localeCompare(right.origin),
134
+ );
135
+ }
136
+
137
+ markPartial(): void {
138
+ this.truncated = true;
139
+ }
140
+
141
+ private prune(): void {
142
+ const now = this.now();
143
+ for (const [origin, event] of this.records) {
144
+ const ttl = event.status === "leaving" ? MAX_EVENT_AGE_MS : DIRECTORY_RECORD_TTL_MS;
145
+ if (event.issuedAt < now - ttl) this.records.delete(origin);
146
+ }
147
+ this.pruneSeen();
148
+ }
149
+
150
+ private hasSeen(key: string): boolean {
151
+ this.pruneSeen();
152
+ return this.seen.has(key);
153
+ }
154
+
155
+ private remember(key: string): void {
156
+ const expiresAt = this.now() + DIRECTORY_SEEN_TTL_MS;
157
+ this.seen.set(key, expiresAt);
158
+ this.seenOrder.push({ key, expiresAt });
159
+ while (this.seen.size > MAX_DIRECTORY_SEEN) {
160
+ const removed = this.seenOrder.shift();
161
+ if (removed && this.seen.get(removed.key) === removed.expiresAt) {
162
+ this.seen.delete(removed.key);
163
+ }
164
+ }
165
+ }
166
+
167
+ private pruneSeen(): void {
168
+ const now = this.now();
169
+ while (this.seenOrder[0] && this.seenOrder[0].expiresAt <= now) {
170
+ const removed = this.seenOrder.shift();
171
+ if (removed && this.seen.get(removed.key) === removed.expiresAt) {
172
+ this.seen.delete(removed.key);
173
+ }
174
+ }
175
+ }
176
+ }
177
+
178
+ export function createDirectoryPresence(
179
+ identity: ChatIdentity,
180
+ slugValue: string,
181
+ status: DirectoryPresence["status"],
182
+ issuedAt: number,
183
+ id: string,
184
+ ): DirectoryPresence {
185
+ const slug = validatedSlug(slugValue);
186
+ if (!slug) throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
187
+ if (status !== "online" && status !== "leaving") {
188
+ throw new Error("Directory presence state is invalid.");
189
+ }
190
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0) {
191
+ throw new Error("Directory presence timestamp is invalid.");
192
+ }
193
+ if (!validId(id)) throw new Error("Directory presence id is invalid.");
194
+ const unsigned: Omit<DirectoryPresence, "signature"> = {
195
+ v: 2,
196
+ kind: "directory-presence",
197
+ slug,
198
+ origin: identity.publicKey.toString("hex"),
199
+ id,
200
+ issuedAt,
201
+ status,
202
+ };
203
+ return {
204
+ ...unsigned,
205
+ signature: signIdentityPayload(identity, canonicalDirectoryPresence(unsigned)),
206
+ };
207
+ }
208
+
209
+ export function verifyDirectoryPresence(value: DirectoryPresence, now = Date.now()): boolean {
210
+ const event = parseDirectoryPresence(value);
211
+ if (!event) return false;
212
+ if (event.issuedAt < now - MAX_EVENT_AGE_MS || event.issuedAt > now + MAX_EVENT_FUTURE_MS) {
213
+ return false;
214
+ }
215
+ const { signature, ...unsigned } = event;
216
+ return verifyIdentityPayload(
217
+ Buffer.from(event.origin, "hex"),
218
+ canonicalDirectoryPresence(unsigned),
219
+ signature,
220
+ );
221
+ }
222
+
223
+ export function createDirectoryWireMessage(
224
+ event: DirectoryPresence,
225
+ hops = MAX_GOSSIP_HOPS,
226
+ partial = false,
227
+ ): DirectoryWireMessage {
228
+ if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
229
+ throw new Error("Directory gossip hop budget is invalid.");
230
+ }
231
+ return { v: 2, type: "directory", event, hops, ...(partial ? { partial: true as const } : {}) };
232
+ }
233
+
234
+ export function parseDirectoryWireMessage(value: unknown): DirectoryWireMessage | undefined {
235
+ if (
236
+ !isRecord(value) ||
237
+ value.v !== 2 ||
238
+ value.type !== "directory" ||
239
+ !Number.isSafeInteger(value.hops) ||
240
+ (value.hops as number) < 1 ||
241
+ (value.hops as number) > MAX_GOSSIP_HOPS
242
+ ) {
243
+ return undefined;
244
+ }
245
+ if (value.partial !== undefined && value.partial !== true) return undefined;
246
+ const event = parseDirectoryPresence(value.event);
247
+ return event
248
+ ? {
249
+ v: 2,
250
+ type: "directory",
251
+ event,
252
+ hops: value.hops as number,
253
+ ...(value.partial === true ? { partial: true as const } : {}),
254
+ }
255
+ : undefined;
256
+ }
257
+
258
+ export function encodeDirectoryFrame(message: DirectoryWireMessage): Buffer {
259
+ const payload = Buffer.from(JSON.stringify(message), "utf8");
260
+ if (payload.length > MAX_FRAME_BYTES) throw new Error("Directory frame exceeds the size limit.");
261
+ const header = Buffer.allocUnsafe(4);
262
+ header.writeUInt32BE(payload.length);
263
+ return Buffer.concat([header, payload]);
264
+ }
265
+
266
+ export class DirectoryFrameDecoder {
267
+ private buffer = Buffer.alloc(0);
268
+
269
+ push(chunk: Uint8Array): DirectoryWireMessage[] {
270
+ if (chunk.byteLength === 0) return [];
271
+ const incoming = Buffer.from(chunk);
272
+ const messages: DirectoryWireMessage[] = [];
273
+ let offset = 0;
274
+ while (offset < incoming.length) {
275
+ if (this.buffer.length < 4) {
276
+ const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
277
+ this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
278
+ offset += headerBytes;
279
+ if (this.buffer.length < 4) break;
280
+ }
281
+ const length = this.buffer.readUInt32BE(0);
282
+ if (length > MAX_FRAME_BYTES) {
283
+ this.buffer = Buffer.alloc(0);
284
+ throw new Error("Directory frame exceeds the size limit.");
285
+ }
286
+ const frameBytes = length + 4;
287
+ if (this.buffer.length < frameBytes) {
288
+ const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
289
+ this.buffer = Buffer.concat([
290
+ this.buffer,
291
+ incoming.subarray(offset, offset + payloadBytes),
292
+ ]);
293
+ offset += payloadBytes;
294
+ if (this.buffer.length < frameBytes) break;
295
+ }
296
+ const payload = this.buffer.subarray(4, frameBytes);
297
+ this.buffer = Buffer.alloc(0);
298
+ let value: unknown;
299
+ try {
300
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload)) as unknown;
301
+ } catch {
302
+ throw new Error("Directory frame is not valid UTF-8 JSON.");
303
+ }
304
+ const parsed = parseDirectoryWireMessage(value);
305
+ if (!parsed) throw new Error("Directory frame has an invalid message shape.");
306
+ messages.push(parsed);
307
+ }
308
+ return messages;
309
+ }
310
+ }
311
+
312
+ export function sortDirectoryRooms(rooms: readonly PublicRoomListing[]): PublicRoomListing[] {
313
+ return [...rooms].sort(
314
+ (left, right) =>
315
+ right.estimatedParticipants - left.estimatedParticipants ||
316
+ left.slug.localeCompare(right.slug),
317
+ );
318
+ }
319
+
320
+ function parseDirectoryPresence(value: unknown): DirectoryPresence | undefined {
321
+ if (
322
+ !isRecord(value) ||
323
+ value.v !== 2 ||
324
+ value.kind !== "directory-presence" ||
325
+ !validatedSlug(value.slug) ||
326
+ !PUBLIC_KEY.test(String(value.origin)) ||
327
+ !validId(value.id) ||
328
+ !Number.isSafeInteger(value.issuedAt) ||
329
+ (value.issuedAt as number) < 0 ||
330
+ (value.status !== "online" && value.status !== "leaving") ||
331
+ typeof value.signature !== "string" ||
332
+ !SIGNATURE.test(value.signature)
333
+ ) {
334
+ return undefined;
335
+ }
336
+ return {
337
+ v: 2,
338
+ kind: "directory-presence",
339
+ slug: value.slug as string,
340
+ origin: value.origin as string,
341
+ id: value.id,
342
+ issuedAt: value.issuedAt as number,
343
+ status: value.status,
344
+ signature: value.signature,
345
+ };
346
+ }
347
+
348
+ function canonicalDirectoryPresence(event: Omit<DirectoryPresence, "signature">): Buffer {
349
+ return Buffer.from(
350
+ JSON.stringify([
351
+ 2,
352
+ "directory-presence",
353
+ event.slug,
354
+ event.origin,
355
+ event.id,
356
+ event.issuedAt,
357
+ event.status,
358
+ ]),
359
+ "utf8",
360
+ );
361
+ }
362
+
363
+ function validatedSlug(value: unknown): string | undefined {
364
+ if (typeof value !== "string") return undefined;
365
+ try {
366
+ return createPublicRoom(value).slug;
367
+ } catch {
368
+ return undefined;
369
+ }
370
+ }
371
+
372
+ function positiveBound(value: number | undefined, fallback: number): number {
373
+ return Number.isSafeInteger(value) && (value ?? 0) > 0
374
+ ? Math.min(value ?? fallback, fallback)
375
+ : fallback;
376
+ }
377
+
378
+ function validId(value: unknown): value is string {
379
+ return (
380
+ typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value)
381
+ );
382
+ }
383
+
384
+ function isRecord(value: unknown): value is Record<string, unknown> {
385
+ return typeof value === "object" && value !== null && !Array.isArray(value);
386
+ }
package/src/settings.ts CHANGED
@@ -4,7 +4,12 @@ import { chmod, lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promis
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
6
  import { normalizeNickname } from "./identity.js";
7
- import { createPublicRoom, parseInvite, type RoomDescriptor } from "./protocol.js";
7
+ import {
8
+ createPublicRoom,
9
+ isCompatibleRoomId,
10
+ parseInvite,
11
+ type RoomDescriptor,
12
+ } from "./protocol.js";
8
13
 
9
14
  export const CHAT_SETTINGS_FILE = "pi-chat.json";
10
15
  const MAX_SETTINGS_BYTES = 64 * 1024;
@@ -40,6 +45,7 @@ export interface UpdateChatSettingsOptions {
40
45
  settingsPath?: string;
41
46
  signal?: AbortSignal;
42
47
  beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
48
+ setPrivateMode?: (path: string) => Promise<void>;
43
49
  }
44
50
 
45
51
  type SettingsDocument = Record<string, unknown>;
@@ -239,8 +245,11 @@ async function publish(
239
245
  });
240
246
  await options.beforeRename?.(temporaryPath, path);
241
247
  options.signal?.throwIfAborted();
248
+ if (process.platform !== "win32") {
249
+ await (options.setPrivateMode ?? ((target) => chmod(target, 0o600)))(temporaryPath);
250
+ options.signal?.throwIfAborted();
251
+ }
242
252
  await rename(temporaryPath, path);
243
- if (process.platform !== "win32") await chmod(path, 0o600);
244
253
  } catch (error) {
245
254
  await rm(temporaryPath, { force: true }).catch(() => undefined);
246
255
  throw error;
@@ -254,14 +263,21 @@ function normalizeResumeSettings(value: unknown): ChatResumeSettings | undefined
254
263
  if (value.surface !== "chat" && value.surface !== "pi") return undefined;
255
264
  const rooms: RememberedRoom[] = [];
256
265
  const ids = new Set<string>();
266
+ let activeRoomId: string | undefined;
257
267
  for (const candidate of value.rooms) {
258
268
  const room = normalizeRememberedRoom(candidate);
259
269
  if (!room || ids.has(room.id)) return undefined;
260
270
  ids.add(room.id);
261
271
  rooms.push(room);
272
+ if (
273
+ isRecord(candidate) &&
274
+ (candidate.id === value.activeRoomId || room.id === value.activeRoomId)
275
+ ) {
276
+ activeRoomId = room.id;
277
+ }
262
278
  }
263
- if (!ids.has(value.activeRoomId)) return undefined;
264
- return { rooms, activeRoomId: value.activeRoomId, surface: value.surface };
279
+ if (!activeRoomId || !ids.has(activeRoomId)) return undefined;
280
+ return { rooms, activeRoomId, surface: value.surface };
265
281
  }
266
282
 
267
283
  function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
@@ -273,7 +289,9 @@ function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
273
289
  !Object.hasOwn(value, "invite")
274
290
  ) {
275
291
  const room = createPublicRoom(value.slug);
276
- return room.id === value.id ? { id: room.id, kind: "public", slug: value.slug } : undefined;
292
+ return isCompatibleRoomId(room, value.id)
293
+ ? { id: room.id, kind: "public", slug: value.slug }
294
+ : undefined;
277
295
  }
278
296
  if (
279
297
  value.kind === "private" &&
@@ -281,7 +299,7 @@ function normalizeRememberedRoom(value: unknown): RememberedRoom | undefined {
281
299
  !Object.hasOwn(value, "slug")
282
300
  ) {
283
301
  const room = parseInvite(value.invite);
284
- return room.id === value.id
302
+ return isCompatibleRoomId(room, value.id)
285
303
  ? { id: room.id, kind: "private", invite: value.invite }
286
304
  : undefined;
287
305
  }
@@ -296,9 +314,8 @@ function mergeResumeDocument(current: unknown, next: ChatResumeSettings): Settin
296
314
  const existingRooms = new Map<string, SettingsDocument>();
297
315
  if (Array.isArray(currentResume.rooms)) {
298
316
  for (const candidate of currentResume.rooms) {
299
- if (isRecord(candidate) && typeof candidate.id === "string") {
300
- existingRooms.set(candidate.id, candidate);
301
- }
317
+ const normalized = normalizeRememberedRoom(candidate);
318
+ if (normalized && isRecord(candidate)) existingRooms.set(normalized.id, candidate);
302
319
  }
303
320
  }
304
321
  return {
package/src/widget.ts CHANGED
@@ -15,8 +15,8 @@ export function renderChatWidget(
15
15
  const safeWidth = Math.max(1, width);
16
16
  if (mode === "dock") return renderRoomDock(snapshot, safeWidth, terminalRows, theme);
17
17
 
18
- const peers = snapshot.peers.length;
19
- const presence = peers === 0 ? "alone" : `${peers} direct peer${peers === 1 ? "" : "s"}`;
18
+ const participants = snapshot.participants.length;
19
+ const presence = `${participants} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`;
20
20
  const unread = snapshot.unread > 0 ? `${snapshot.unread} unread · ` : "";
21
21
  const attention = snapshot.state === "degraded" ? " · reconnecting" : "";
22
22
  const header = truncateToWidth(
@@ -42,16 +42,15 @@ function renderRoomDock(
42
42
  terminalRows: number,
43
43
  theme: Theme,
44
44
  ): string[] {
45
- const peers = snapshot.peers.length;
46
- const peerText = `${peers} direct peer${peers === 1 ? "" : "s"}`;
45
+ const participantText = `${snapshot.participants.length} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`;
47
46
  const stateText =
48
47
  snapshot.state === "connecting"
49
48
  ? "joining…"
50
49
  : snapshot.state === "degraded"
51
- ? `reconnecting · ${peerText}`
52
- : peers === 0
53
- ? "waiting for peers"
54
- : peerText;
50
+ ? `reconnecting · ${participantText}`
51
+ : snapshot.directNeighbors === 0
52
+ ? "waiting for neighbors"
53
+ : participantText;
55
54
  const unread = snapshot.unread > 0 ? ` · ${snapshot.unread} unread` : "";
56
55
  const roomTitle = `ROOM ${sanitizeSingleLine(snapshot.room.label)}`;
57
56
  const status = `${stateText}${unread}`;