@narumitw/pi-chat 0.0.0 → 0.1.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.
package/src/menu.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { MenuDefinition } from "@narumitw/pi-tui-kit";
3
3
  import type { ChatSnapshot } from "./chat-session.js";
4
- import { normalizeNickname } from "./identity.js";
5
- import { createPublicRoom, parseInvite, type RoomDescriptor } from "./protocol.js";
4
+ import { normalizeNickname } from "./nickname.js";
5
+ import { type PublicRoomBrowseResult, sortDirectoryRooms } from "./public-room-directory.js";
6
+ import { createPublicRoom, parseInvite, type RoomDescriptor } from "./room.js";
6
7
  import { type ChatSettings, descriptorFromRememberedRoom, type WidgetMode } from "./settings.js";
7
8
  import { sanitizeSingleLine } from "./text.js";
8
9
 
@@ -16,6 +17,7 @@ export interface ChatMenuSource {
16
17
  getSnapshot(): ChatSnapshot | undefined;
17
18
  getRestoreError(): string | undefined;
18
19
  createPrivateRoom(): RoomDescriptor;
20
+ browsePublicRooms(signal: AbortSignal): Promise<PublicRoomBrowseResult>;
19
21
  joinRoom(
20
22
  room: RoomDescriptor,
21
23
  ctx: ExtensionCommandContext,
@@ -38,6 +40,8 @@ interface ChatMenuState {
38
40
  snapshot?: ChatSnapshot;
39
41
  pendingRoom?: RoomDescriptor;
40
42
  restoreError?: string;
43
+ directoryResult?: PublicRoomBrowseResult;
44
+ directoryError?: string;
41
45
  }
42
46
 
43
47
  type Screen =
@@ -45,6 +49,7 @@ type Screen =
45
49
  | "invite"
46
50
  | "joinInvite"
47
51
  | "joinPublic"
52
+ | "publicRooms"
48
53
  | "joinAnother"
49
54
  | "participants"
50
55
  | "settings"
@@ -60,6 +65,8 @@ type Action =
60
65
  | "joinPending"
61
66
  | "joinInvite"
62
67
  | "joinPublic"
68
+ | "browse"
69
+ | "selectPublicRoom"
63
70
  | "retry"
64
71
  | "forget"
65
72
  | "open"
@@ -71,12 +78,48 @@ type Action =
71
78
 
72
79
  export function createChatMenu(source: ChatMenuSource) {
73
80
  let pendingRoom: RoomDescriptor | undefined;
81
+ let directoryResult: PublicRoomBrowseResult | undefined;
82
+ let directoryError: string | undefined;
74
83
  const getState = async (): Promise<ChatMenuState> => ({
75
84
  settings: source.getSettings(),
76
85
  snapshot: source.getSnapshot(),
77
86
  pendingRoom,
78
87
  ...(source.getRestoreError() ? { restoreError: source.getRestoreError() } : {}),
88
+ ...(directoryResult ? { directoryResult } : {}),
89
+ ...(directoryError ? { directoryError } : {}),
79
90
  });
91
+ const browseRooms = async (signal: AbortSignal) => {
92
+ try {
93
+ const result = await source.browsePublicRooms(signal);
94
+ if (signal.aborted) return { kind: "stay" as const };
95
+ directoryResult = { ...result, rooms: sortDirectoryRooms(result.rooms) };
96
+ directoryError = undefined;
97
+ } catch (error) {
98
+ if (signal.aborted) return { kind: "stay" as const };
99
+ directoryResult = undefined;
100
+ directoryError = sanitizeSingleLine(error instanceof Error ? error.message : String(error));
101
+ }
102
+ return { kind: "to" as const, screen: "publicRooms" as const };
103
+ };
104
+ const joinPublic = async (slug: string, ctx: ExtensionCommandContext, signal: AbortSignal) => {
105
+ let room: RoomDescriptor;
106
+ try {
107
+ room = createPublicRoom(slug.replace(/^#/u, ""));
108
+ } catch (error) {
109
+ return { kind: "rejected" as const, error };
110
+ }
111
+ const confirmed = await ctx.ui.confirm(
112
+ "Join public room?",
113
+ "Anyone can join or record it. DHT and direct peers may observe network metadata.",
114
+ { signal },
115
+ );
116
+ if (!confirmed || signal.aborted) return { kind: "stay" as const };
117
+ if (!(await source.joinRoom(room, ctx, signal, { remember: true })) || signal.aborted) {
118
+ return { kind: "stay" as const };
119
+ }
120
+ await source.openChat(ctx);
121
+ return { kind: "close" as const };
122
+ };
80
123
  const menu: MenuDefinition<ChatMenuState, Screen, Action> = {
81
124
  start: "main",
82
125
  screens: {
@@ -109,10 +152,10 @@ export function createChatMenu(source: ChatMenuSource) {
109
152
  kind: "input",
110
153
  title: "Join with invite",
111
154
  lines: [
112
- "Paste a pichat:v1 invite. It grants access to the private room.",
155
+ "Paste a pichat:v1 or pichat:v2 invite. It grants access to the private room.",
113
156
  "You will choose Join and remember, Join once, or Cancel before networking starts.",
114
157
  ],
115
- placeholder: "pichat:v1:…",
158
+ placeholder: "pichat:v2:…",
116
159
  action: "joinInvite",
117
160
  hint: "back",
118
161
  }),
@@ -124,11 +167,59 @@ export function createChatMenu(source: ChatMenuSource) {
124
167
  action: "joinPublic",
125
168
  hint: "back",
126
169
  }),
170
+ publicRooms: ({ state }) => {
171
+ const rooms = state.directoryResult?.rooms ?? [];
172
+ const lines = state.directoryError
173
+ ? [
174
+ `Discovery failed: ${sanitizeSingleLine(state.directoryError)}`,
175
+ "Retry or enter a known public room slug.",
176
+ ]
177
+ : rooms.length === 0
178
+ ? ["No active public rooms were discovered. Counts are best-effort estimates."]
179
+ : [
180
+ state.directoryResult?.partial
181
+ ? "Estimated active participants · partial discovered results."
182
+ : "Estimated active participants · currently discovered results.",
183
+ "Select a room to review the public-room warning before joining.",
184
+ ];
185
+ return {
186
+ kind: "choice",
187
+ title: "Public rooms",
188
+ lines,
189
+ items: [
190
+ ...rooms.map((room) => ({
191
+ id: `room:${room.slug}`,
192
+ label: `#${room.slug}`,
193
+ description: `~${room.estimatedParticipants} active`,
194
+ details: ["Estimated from recent signed P2P directory presence."],
195
+ })),
196
+ {
197
+ id: "route:refresh",
198
+ label: state.directoryError ? "Retry discovery" : "Refresh discovery",
199
+ description: "Query the P2P directory again",
200
+ },
201
+ {
202
+ id: "route:manual",
203
+ label: "Enter room slug",
204
+ description: "Join a known public room manually",
205
+ },
206
+ ],
207
+ action: "selectPublicRoom",
208
+ viewportSize: 10,
209
+ hint: "back",
210
+ };
211
+ },
127
212
  joinAnother: () => ({
128
213
  kind: "actions",
129
214
  title: "Join another room",
130
215
  lines: ["A successfully remembered join replaces the room restored at startup."],
131
216
  items: [
217
+ {
218
+ id: "browse",
219
+ label: "Browse public rooms",
220
+ action: "browse",
221
+ busyLabel: "Discovering rooms",
222
+ },
132
223
  { id: "public", label: "Join public room", to: "joinPublic" },
133
224
  { id: "invite", label: "Join with invite", to: "joinInvite" },
134
225
  { id: "create", label: "Create private room", action: "createPrivate" },
@@ -137,12 +228,12 @@ export function createChatMenu(source: ChatMenuSource) {
137
228
  }),
138
229
  participants: ({ state }) => ({
139
230
  kind: "choice",
140
- title: "Direct participants",
141
- lines: state.snapshot?.peers.length
142
- ? ["Select a peer to toggle local mute. Full public keys are shown in details."]
143
- : ["No authenticated direct peers are connected."],
231
+ title: "Active participants",
232
+ lines: state.snapshot?.participants.length
233
+ ? ["Select an origin to toggle local mute. Full public keys are shown in details."]
234
+ : ["No other active participants are currently discovered."],
144
235
  items:
145
- state.snapshot?.peers.map((peer) => ({
236
+ state.snapshot?.participants.map((peer) => ({
146
237
  id: peer.publicKey,
147
238
  label: sanitizeSingleLine(peer.label),
148
239
  description: peer.muted ? "Muted locally" : "Receiving messages",
@@ -255,7 +346,8 @@ export function createChatMenu(source: ChatMenuSource) {
255
346
  `State: ${state.snapshot.state}`,
256
347
  `Room: ${sanitizeSingleLine(state.snapshot.room.label)}`,
257
348
  `Identity: ${sanitizeSingleLine(state.snapshot.localLabel)}`,
258
- `Direct peers: ${state.snapshot.peers.length}`,
349
+ `Active participants: ${state.snapshot.participants.length}`,
350
+ `Direct neighbors: ${state.snapshot.directNeighbors}`,
259
351
  `Unread: ${state.snapshot.unread}`,
260
352
  `Restart: ${restartDescription(state.settings)}`,
261
353
  ...(state.snapshot.lastError
@@ -280,7 +372,8 @@ export function createChatMenu(source: ChatMenuSource) {
280
372
  "Chat stays outside Pi sessions, prompts, model context, and repository files.",
281
373
  "Private invites are bearer secrets. Public rooms are guessable.",
282
374
  "Noise encrypts direct streams, but peers and DHT infrastructure may observe network metadata.",
283
- "There is no offline delivery, authoritative room count, or message withdrawal.",
375
+ "Public-room discovery and participant counts are approximate P2P observations.",
376
+ "There is no offline delivery, global ordering, delivery receipt, or message withdrawal.",
284
377
  ],
285
378
  hint: "back",
286
379
  }),
@@ -309,24 +402,15 @@ export function createChatMenu(source: ChatMenuSource) {
309
402
  await source.openChat(ctx);
310
403
  return { kind: "close" };
311
404
  },
312
- joinPublic: async ({ ctx, signal, value }) => {
313
- let room: RoomDescriptor;
314
- try {
315
- room = createPublicRoom((value ?? "").replace(/^#/u, ""));
316
- } catch (error) {
317
- return { kind: "rejected", error };
318
- }
319
- const confirmed = await ctx.ui.confirm(
320
- "Join public room?",
321
- "Anyone can join or record it. DHT and direct peers may observe network metadata.",
322
- { signal },
323
- );
324
- if (!confirmed || signal.aborted) return { kind: "stay" };
325
- if (!(await source.joinRoom(room, ctx, signal, { remember: true })) || signal.aborted) {
326
- return { kind: "stay" };
405
+ joinPublic: ({ ctx, signal, value }) => joinPublic(value ?? "", ctx, signal),
406
+ browse: ({ signal }) => browseRooms(signal),
407
+ selectPublicRoom: async ({ ctx, signal, itemId }) => {
408
+ if (itemId === "route:refresh") return browseRooms(signal);
409
+ if (itemId === "route:manual") return { kind: "to", screen: "joinPublic" };
410
+ if (!itemId.startsWith("room:")) {
411
+ return { kind: "rejected", error: new Error("Public room selection is invalid") };
327
412
  }
328
- await source.openChat(ctx);
329
- return { kind: "close" };
413
+ return joinPublic(itemId.slice("room:".length), ctx, signal);
330
414
  },
331
415
  retry: async ({ ctx, signal }) => {
332
416
  await source.retryRememberedRoom(ctx, signal);
@@ -423,6 +507,12 @@ function mainScreen(state: ChatMenuState) {
423
507
  title: "Pi Chat · disconnected",
424
508
  lines: ["Experimental peer-to-peer chat. Messages never enter model context."],
425
509
  items: [
510
+ {
511
+ id: "browse",
512
+ label: "Browse public rooms",
513
+ action: "browse" as const,
514
+ busyLabel: "Discovering rooms",
515
+ },
426
516
  { id: "public", label: "Join public room", to: "joinPublic" as const },
427
517
  { id: "invite", label: "Join with invite", to: "joinInvite" as const },
428
518
  { id: "create", label: "Create private room", action: "createPrivate" as const },
@@ -438,7 +528,7 @@ function mainScreen(state: ChatMenuState) {
438
528
  kind: "actions" as const,
439
529
  title: `Pi Chat · ${sanitizeSingleLine(state.snapshot.room.label)}`,
440
530
  lines: [
441
- `${state.snapshot.state} · ${state.snapshot.peers.length} direct peers · ${state.snapshot.unread} unread`,
531
+ `${state.snapshot.state} · ${state.snapshot.participants.length} active · ${state.snapshot.directNeighbors} direct neighbors · ${state.snapshot.unread} unread`,
442
532
  `Current input: ${state.snapshot.composerOpen ? state.snapshot.room.label : "Pi/LLM"}`,
443
533
  restoresCurrent
444
534
  ? `Restart: restore this room and ${state.settings.resume?.surface === "chat" ? "open chat" : "stay in Pi/LLM"}`
@@ -451,7 +541,7 @@ function mainScreen(state: ChatMenuState) {
451
541
  label: `Open chat in ${sanitizeSingleLine(state.snapshot.room.label)}`,
452
542
  action: "open" as const,
453
543
  },
454
- { id: "participants", label: "Show participants", to: "participants" as const },
544
+ { id: "participants", label: "Show active participants", to: "participants" as const },
455
545
  ...(state.snapshot.room.invite
456
546
  ? [{ id: "invite", label: "Show room invite", to: "invite" as const }]
457
547
  : []),
@@ -0,0 +1,12 @@
1
+ import type { ChatIdentity } from "./identity.js";
2
+ import type { RoomDescriptor } from "./room.js";
3
+
4
+ export const MAX_DIRECT_NEIGHBORS = 8;
5
+
6
+ export interface HyperswarmTransportOptions {
7
+ room: RoomDescriptor;
8
+ identity: ChatIdentity;
9
+ maxPeers?: number;
10
+ dht?: unknown;
11
+ bootstrap?: unknown[];
12
+ }
package/src/network.ts CHANGED
@@ -1,34 +1,29 @@
1
1
  import type { Duplex } from "node:stream";
2
2
  import Hyperswarm, { type PeerDiscovery, type PeerInfo } from "hyperswarm";
3
3
  import type { ChatTransport, ChatTransportListener, TransportPeer } from "./chat-session.js";
4
- import type { ChatIdentity } from "./identity.js";
5
- import {
6
- encodeFrame,
7
- FrameDecoder,
8
- type ProtocolMessage,
9
- type RoomDescriptor,
10
- } from "./protocol.js";
4
+ import { type HyperswarmTransportOptions, MAX_DIRECT_NEIGHBORS } from "./network-contract.js";
5
+ import { encodeFrame, FrameDecoder, type ProtocolMessage } from "./protocol.js";
11
6
 
12
- export interface HyperswarmTransportOptions {
13
- room: RoomDescriptor;
14
- identity: ChatIdentity;
15
- maxPeers?: number;
16
- dht?: unknown;
17
- bootstrap?: unknown[];
18
- }
7
+ export type { HyperswarmTransportOptions } from "./network-contract.js";
19
8
 
20
9
  interface ActiveConnection {
21
10
  socket: Duplex;
22
11
  peer: TransportPeer;
23
12
  }
24
13
 
14
+ export { MAX_DIRECT_NEIGHBORS } from "./network-contract.js";
15
+
16
+ export function directNeighborLimit(requested?: number): number {
17
+ if (!Number.isSafeInteger(requested) || (requested ?? 0) <= 0) return MAX_DIRECT_NEIGHBORS;
18
+ return Math.min(requested ?? MAX_DIRECT_NEIGHBORS, MAX_DIRECT_NEIGHBORS);
19
+ }
20
+
25
21
  export class HyperswarmTransport implements ChatTransport {
26
22
  private readonly options: HyperswarmTransportOptions;
27
23
  private swarm: Hyperswarm | undefined;
28
24
  private discovery: PeerDiscovery | undefined;
29
25
  private listener: ChatTransportListener | undefined;
30
26
  private readonly connections = new Map<Duplex, ActiveConnection>();
31
- private readonly directPeers = new Map<string, Buffer>();
32
27
  private readonly refreshTimers = new Set<NodeJS.Timeout>();
33
28
  private stopPromise: Promise<void> | undefined;
34
29
 
@@ -40,6 +35,10 @@ export class HyperswarmTransport implements ChatTransport {
40
35
  return this.connections.size;
41
36
  }
42
37
 
38
+ get connectedPeerKeys(): string[] {
39
+ return [...this.connections.values()].map(({ peer }) => peer.publicKey.toString("hex")).sort();
40
+ }
41
+
43
42
  async start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void> {
44
43
  if (this.swarm) throw new Error("Hyperswarm transport has already started.");
45
44
  const startupSignal = signal
@@ -47,12 +46,13 @@ export class HyperswarmTransport implements ChatTransport {
47
46
  : AbortSignal.timeout(15_000);
48
47
  startupSignal.throwIfAborted();
49
48
  this.listener = listener;
49
+ const maxPeers = directNeighborLimit(this.options.maxPeers);
50
50
  const swarm = new Hyperswarm({
51
51
  keyPair: {
52
52
  publicKey: this.options.identity.publicKey,
53
53
  secretKey: this.options.identity.secretKey,
54
54
  },
55
- maxPeers: this.options.maxPeers ?? 16,
55
+ maxPeers,
56
56
  ...(this.options.dht ? { dht: this.options.dht } : {}),
57
57
  ...(this.options.bootstrap ? { bootstrap: this.options.bootstrap } : {}),
58
58
  });
@@ -63,7 +63,7 @@ export class HyperswarmTransport implements ChatTransport {
63
63
  const discovery = swarm.join(this.options.room.topic, {
64
64
  server: true,
65
65
  client: true,
66
- limit: this.options.maxPeers ?? 16,
66
+ limit: maxPeers,
67
67
  });
68
68
  this.discovery = discovery;
69
69
  await raceAbort(discovery.flushed(), startupSignal);
@@ -75,14 +75,6 @@ export class HyperswarmTransport implements ChatTransport {
75
75
  }
76
76
  }
77
77
 
78
- connectPeer(publicKey: Buffer): void {
79
- if (!this.swarm || publicKey.length !== 32 || this.directPeers.size >= 16) return;
80
- const id = publicKey.toString("hex");
81
- if (id === this.options.identity.publicKey.toString("hex") || this.directPeers.has(id)) return;
82
- this.directPeers.set(id, Buffer.from(publicKey));
83
- this.swarm.joinPeer(publicKey);
84
- }
85
-
86
78
  stop(): Promise<void> {
87
79
  if (this.stopPromise) return this.stopPromise;
88
80
  this.stopPromise = this.stopOwned();
@@ -110,7 +102,7 @@ export class HyperswarmTransport implements ChatTransport {
110
102
  }
111
103
 
112
104
  private accept(socket: Duplex, info: PeerInfo): void {
113
- if (!this.swarm || !this.listener) {
105
+ if (!this.swarm || !this.listener || this.connections.size >= MAX_DIRECT_NEIGHBORS) {
114
106
  socket.destroy();
115
107
  return;
116
108
  }
@@ -168,10 +160,6 @@ export class HyperswarmTransport implements ChatTransport {
168
160
  for (const { socket } of this.connections.values()) socket.destroy();
169
161
  this.connections.clear();
170
162
  const swarm = this.swarm;
171
- if (swarm) {
172
- for (const publicKey of this.directPeers.values()) swarm.leavePeer(publicKey);
173
- }
174
- this.directPeers.clear();
175
163
  this.swarm = undefined;
176
164
  this.listener = undefined;
177
165
  if (swarm) await swarm.destroy().catch(() => undefined);
@@ -0,0 +1,11 @@
1
+ const MAX_NICKNAME_GRAPHEMES = 24;
2
+ const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;
3
+
4
+ export function normalizeNickname(value: unknown): string | undefined {
5
+ if (typeof value !== "string") return undefined;
6
+ const normalized = value.normalize("NFKC").trim();
7
+ if (!normalized || /\p{Cc}/u.test(normalized) || BIDI_CONTROLS.test(normalized)) return undefined;
8
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
9
+ if (Array.from(segmenter.segment(normalized)).length > MAX_NICKNAME_GRAPHEMES) return undefined;
10
+ return normalized;
11
+ }