@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.
- package/README.md +58 -29
- package/package.json +3 -2
- package/src/chat-session.ts +325 -104
- package/src/chat-view.ts +14 -14
- package/src/directory-network.ts +416 -0
- package/src/external.d.ts +14 -0
- package/src/identity.ts +41 -1
- package/src/menu.ts +118 -28
- package/src/network.ts +15 -16
- package/src/pi-chat.ts +93 -5
- package/src/protocol.ts +250 -70
- package/src/public-room-directory.ts +386 -0
- package/src/settings.ts +26 -9
- package/src/widget.ts +7 -8
package/src/menu.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { MenuDefinition } from "@narumitw/pi-tui-kit";
|
|
|
3
3
|
import type { ChatSnapshot } from "./chat-session.js";
|
|
4
4
|
import { normalizeNickname } from "./identity.js";
|
|
5
5
|
import { createPublicRoom, parseInvite, type RoomDescriptor } from "./protocol.js";
|
|
6
|
+
import { type PublicRoomBrowseResult, sortDirectoryRooms } from "./public-room-directory.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:
|
|
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: "
|
|
141
|
-
lines: state.snapshot?.
|
|
142
|
-
? ["Select
|
|
143
|
-
: ["No
|
|
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?.
|
|
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
|
-
`
|
|
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
|
-
"
|
|
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:
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
: []),
|
package/src/network.ts
CHANGED
|
@@ -22,13 +22,19 @@ interface ActiveConnection {
|
|
|
22
22
|
peer: TransportPeer;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
export const MAX_DIRECT_NEIGHBORS = 8;
|
|
26
|
+
|
|
27
|
+
export function directNeighborLimit(requested?: number): number {
|
|
28
|
+
if (!Number.isSafeInteger(requested) || (requested ?? 0) <= 0) return MAX_DIRECT_NEIGHBORS;
|
|
29
|
+
return Math.min(requested ?? MAX_DIRECT_NEIGHBORS, MAX_DIRECT_NEIGHBORS);
|
|
30
|
+
}
|
|
31
|
+
|
|
25
32
|
export class HyperswarmTransport implements ChatTransport {
|
|
26
33
|
private readonly options: HyperswarmTransportOptions;
|
|
27
34
|
private swarm: Hyperswarm | undefined;
|
|
28
35
|
private discovery: PeerDiscovery | undefined;
|
|
29
36
|
private listener: ChatTransportListener | undefined;
|
|
30
37
|
private readonly connections = new Map<Duplex, ActiveConnection>();
|
|
31
|
-
private readonly directPeers = new Map<string, Buffer>();
|
|
32
38
|
private readonly refreshTimers = new Set<NodeJS.Timeout>();
|
|
33
39
|
private stopPromise: Promise<void> | undefined;
|
|
34
40
|
|
|
@@ -40,6 +46,10 @@ export class HyperswarmTransport implements ChatTransport {
|
|
|
40
46
|
return this.connections.size;
|
|
41
47
|
}
|
|
42
48
|
|
|
49
|
+
get connectedPeerKeys(): string[] {
|
|
50
|
+
return [...this.connections.values()].map(({ peer }) => peer.publicKey.toString("hex")).sort();
|
|
51
|
+
}
|
|
52
|
+
|
|
43
53
|
async start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void> {
|
|
44
54
|
if (this.swarm) throw new Error("Hyperswarm transport has already started.");
|
|
45
55
|
const startupSignal = signal
|
|
@@ -47,12 +57,13 @@ export class HyperswarmTransport implements ChatTransport {
|
|
|
47
57
|
: AbortSignal.timeout(15_000);
|
|
48
58
|
startupSignal.throwIfAborted();
|
|
49
59
|
this.listener = listener;
|
|
60
|
+
const maxPeers = directNeighborLimit(this.options.maxPeers);
|
|
50
61
|
const swarm = new Hyperswarm({
|
|
51
62
|
keyPair: {
|
|
52
63
|
publicKey: this.options.identity.publicKey,
|
|
53
64
|
secretKey: this.options.identity.secretKey,
|
|
54
65
|
},
|
|
55
|
-
maxPeers
|
|
66
|
+
maxPeers,
|
|
56
67
|
...(this.options.dht ? { dht: this.options.dht } : {}),
|
|
57
68
|
...(this.options.bootstrap ? { bootstrap: this.options.bootstrap } : {}),
|
|
58
69
|
});
|
|
@@ -63,7 +74,7 @@ export class HyperswarmTransport implements ChatTransport {
|
|
|
63
74
|
const discovery = swarm.join(this.options.room.topic, {
|
|
64
75
|
server: true,
|
|
65
76
|
client: true,
|
|
66
|
-
limit:
|
|
77
|
+
limit: maxPeers,
|
|
67
78
|
});
|
|
68
79
|
this.discovery = discovery;
|
|
69
80
|
await raceAbort(discovery.flushed(), startupSignal);
|
|
@@ -75,14 +86,6 @@ export class HyperswarmTransport implements ChatTransport {
|
|
|
75
86
|
}
|
|
76
87
|
}
|
|
77
88
|
|
|
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
89
|
stop(): Promise<void> {
|
|
87
90
|
if (this.stopPromise) return this.stopPromise;
|
|
88
91
|
this.stopPromise = this.stopOwned();
|
|
@@ -110,7 +113,7 @@ export class HyperswarmTransport implements ChatTransport {
|
|
|
110
113
|
}
|
|
111
114
|
|
|
112
115
|
private accept(socket: Duplex, info: PeerInfo): void {
|
|
113
|
-
if (!this.swarm || !this.listener) {
|
|
116
|
+
if (!this.swarm || !this.listener || this.connections.size >= MAX_DIRECT_NEIGHBORS) {
|
|
114
117
|
socket.destroy();
|
|
115
118
|
return;
|
|
116
119
|
}
|
|
@@ -168,10 +171,6 @@ export class HyperswarmTransport implements ChatTransport {
|
|
|
168
171
|
for (const { socket } of this.connections.values()) socket.destroy();
|
|
169
172
|
this.connections.clear();
|
|
170
173
|
const swarm = this.swarm;
|
|
171
|
-
if (swarm) {
|
|
172
|
-
for (const publicKey of this.directPeers.values()) swarm.leavePeer(publicKey);
|
|
173
|
-
}
|
|
174
|
-
this.directPeers.clear();
|
|
175
174
|
this.swarm = undefined;
|
|
176
175
|
this.listener = undefined;
|
|
177
176
|
if (swarm) await swarm.destroy().catch(() => undefined);
|
package/src/pi-chat.ts
CHANGED
|
@@ -7,9 +7,23 @@ import type {
|
|
|
7
7
|
import type { ChatSnapshot, ChatTransport } from "./chat-session.js";
|
|
8
8
|
import { ChatSession } from "./chat-session.js";
|
|
9
9
|
import { ChatView } from "./chat-view.js";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
HyperswarmDirectoryTransport,
|
|
12
|
+
type PublicRoomDirectory,
|
|
13
|
+
PublicRoomDirectorySession,
|
|
14
|
+
} from "./directory-network.js";
|
|
15
|
+
import {
|
|
16
|
+
type ChatIdentity,
|
|
17
|
+
createIdentity,
|
|
18
|
+
deriveScopedIdentity,
|
|
19
|
+
formatIdentityLabel,
|
|
20
|
+
} from "./identity.js";
|
|
11
21
|
import { type ChatMenuSource, type JoinRoomOptions, showChatMenu } from "./menu.js";
|
|
12
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
HyperswarmTransport,
|
|
24
|
+
type HyperswarmTransportOptions,
|
|
25
|
+
MAX_DIRECT_NEIGHBORS,
|
|
26
|
+
} from "./network.js";
|
|
13
27
|
import {
|
|
14
28
|
createPrivateRoom,
|
|
15
29
|
createPublicRoom,
|
|
@@ -32,7 +46,7 @@ import { renderChatWidget } from "./widget.js";
|
|
|
32
46
|
const CHAT_UI_KEY = "chat";
|
|
33
47
|
const EXPERIMENTAL_WARNING =
|
|
34
48
|
"Pi Chat is experimental. Peer identity, networking, and interaction behavior may change.";
|
|
35
|
-
const USAGE = "Usage: /chat, /chat <pichat:v1:invite>, or /chat #<public-slug>";
|
|
49
|
+
const USAGE = "Usage: /chat, /chat <pichat:v1-or-v2:invite>, or /chat #<public-slug>";
|
|
36
50
|
const PRIVATE_ROOM_OPTIONS = [
|
|
37
51
|
"Join and remember — Save the bearer invite privately and restore this room",
|
|
38
52
|
"Join once — Do not save the bearer invite",
|
|
@@ -48,10 +62,16 @@ const DISPLAY_OPTIONS: ReadonlyArray<{ label: string; mode: WidgetMode }> = [
|
|
|
48
62
|
{ label: "Hidden — Show no persistent room widget", mode: "off" },
|
|
49
63
|
];
|
|
50
64
|
|
|
65
|
+
export interface PiChatDirectoryOptions {
|
|
66
|
+
identity: ChatIdentity;
|
|
67
|
+
advertisedSlug?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
51
70
|
export interface PiChatDependencies {
|
|
52
71
|
settingsPath: string;
|
|
53
72
|
randomBytes(size: number): Buffer;
|
|
54
73
|
createTransport(options: HyperswarmTransportOptions): ChatTransport;
|
|
74
|
+
createDirectory(options: PiChatDirectoryOptions): PublicRoomDirectory;
|
|
55
75
|
updateSettings: typeof updateChatSettingsFile;
|
|
56
76
|
}
|
|
57
77
|
|
|
@@ -63,6 +83,13 @@ export function createPiChatExtension(
|
|
|
63
83
|
randomBytes: dependencies.randomBytes ?? nodeRandomBytes,
|
|
64
84
|
createTransport:
|
|
65
85
|
dependencies.createTransport ?? ((options) => new HyperswarmTransport(options)),
|
|
86
|
+
createDirectory:
|
|
87
|
+
dependencies.createDirectory ??
|
|
88
|
+
((options) =>
|
|
89
|
+
new PublicRoomDirectorySession({
|
|
90
|
+
...options,
|
|
91
|
+
transport: new HyperswarmDirectoryTransport({ identity: options.identity }),
|
|
92
|
+
})),
|
|
66
93
|
updateSettings: dependencies.updateSettings ?? updateChatSettingsFile,
|
|
67
94
|
};
|
|
68
95
|
const updateChatSettings = deps.updateSettings;
|
|
@@ -74,6 +101,7 @@ export function createPiChatExtension(
|
|
|
74
101
|
let activeContext: ExtensionContext | undefined;
|
|
75
102
|
let settings: ChatSettings = {};
|
|
76
103
|
let chatSession: ChatSession | undefined;
|
|
104
|
+
let roomDirectory: PublicRoomDirectory | undefined;
|
|
77
105
|
let latestSnapshot: ChatSnapshot | undefined;
|
|
78
106
|
let chatDraft = "";
|
|
79
107
|
let restoreError: string | undefined;
|
|
@@ -168,10 +196,12 @@ export function createPiChatExtension(
|
|
|
168
196
|
|
|
169
197
|
const disconnectRoom = async (): Promise<void> => {
|
|
170
198
|
const owned = chatSession;
|
|
199
|
+
const ownedDirectory = roomDirectory;
|
|
171
200
|
chatSession = undefined;
|
|
201
|
+
roomDirectory = undefined;
|
|
172
202
|
latestSnapshot = undefined;
|
|
173
203
|
chatDraft = "";
|
|
174
|
-
|
|
204
|
+
await Promise.allSettled([owned?.leave(), ownedDirectory?.stop()]);
|
|
175
205
|
if (activeContext) clearUi(activeContext);
|
|
176
206
|
};
|
|
177
207
|
|
|
@@ -234,6 +264,41 @@ export function createPiChatExtension(
|
|
|
234
264
|
return createIdentity(Buffer.from(seed, "base64url"));
|
|
235
265
|
};
|
|
236
266
|
|
|
267
|
+
const startPublicRoomDirectory = (
|
|
268
|
+
room: RoomDescriptor,
|
|
269
|
+
identity: ChatIdentity,
|
|
270
|
+
ctx: ExtensionContext,
|
|
271
|
+
owner: unknown,
|
|
272
|
+
ownerGeneration: number,
|
|
273
|
+
): void => {
|
|
274
|
+
if (room.kind !== "public" || !room.slug) return;
|
|
275
|
+
const directory = deps.createDirectory({
|
|
276
|
+
identity: deriveScopedIdentity(identity, `directory:#${room.slug}`),
|
|
277
|
+
advertisedSlug: room.slug,
|
|
278
|
+
});
|
|
279
|
+
roomDirectory = directory;
|
|
280
|
+
void trackTask(
|
|
281
|
+
directory.start(controller.signal).catch(async (error) => {
|
|
282
|
+
const ownsDirectory = roomDirectory === directory;
|
|
283
|
+
if (ownsDirectory) roomDirectory = undefined;
|
|
284
|
+
await directory.stop();
|
|
285
|
+
if (
|
|
286
|
+
ownsDirectory &&
|
|
287
|
+
isCurrent(owner, ownerGeneration) &&
|
|
288
|
+
chatSession?.snapshot().room.id === room.id
|
|
289
|
+
) {
|
|
290
|
+
notifySafely(
|
|
291
|
+
ctx,
|
|
292
|
+
`Pi Chat public-room discovery is unavailable: ${sanitizeSingleLine(
|
|
293
|
+
error instanceof Error ? error.message : String(error),
|
|
294
|
+
)}. Chat remains connected.`,
|
|
295
|
+
"warning",
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
}),
|
|
299
|
+
);
|
|
300
|
+
};
|
|
301
|
+
|
|
237
302
|
const joinRoom = async (
|
|
238
303
|
room: RoomDescriptor,
|
|
239
304
|
ctx: ExtensionContext,
|
|
@@ -267,7 +332,11 @@ export function createPiChatExtension(
|
|
|
267
332
|
if (!identity || !isCurrent(owner, ownerGeneration) || signal.aborted) return false;
|
|
268
333
|
const nickname = settings.nickname;
|
|
269
334
|
if (!nickname) throw new Error("Pi Chat nickname is unavailable.");
|
|
270
|
-
const transport = deps.createTransport({
|
|
335
|
+
const transport = deps.createTransport({
|
|
336
|
+
room,
|
|
337
|
+
identity,
|
|
338
|
+
maxPeers: MAX_DIRECT_NEIGHBORS,
|
|
339
|
+
});
|
|
271
340
|
const session = new ChatSession({
|
|
272
341
|
room,
|
|
273
342
|
identity,
|
|
@@ -307,6 +376,7 @@ export function createPiChatExtension(
|
|
|
307
376
|
restoreError = undefined;
|
|
308
377
|
latestSnapshot = session.snapshot();
|
|
309
378
|
updateUi(ctx, latestSnapshot);
|
|
379
|
+
startPublicRoomDirectory(room, identity, ctx, owner, ownerGeneration);
|
|
310
380
|
return true;
|
|
311
381
|
} catch (error) {
|
|
312
382
|
if (chatSession === session) chatSession = undefined;
|
|
@@ -432,6 +502,24 @@ export function createPiChatExtension(
|
|
|
432
502
|
getSnapshot: () => chatSession?.snapshot(),
|
|
433
503
|
getRestoreError: () => restoreError,
|
|
434
504
|
createPrivateRoom: () => createPrivateRoom(deps.randomBytes(32)),
|
|
505
|
+
browsePublicRooms: async (signal) => {
|
|
506
|
+
if (!ownsMenu()) throw new Error("Pi Chat session is stale.");
|
|
507
|
+
const activeDirectory = roomDirectory;
|
|
508
|
+
const directory =
|
|
509
|
+
activeDirectory ??
|
|
510
|
+
deps.createDirectory({ identity: createIdentity(deps.randomBytes(32)) });
|
|
511
|
+
const temporary = activeDirectory ? undefined : directory;
|
|
512
|
+
const browseSignal = AbortSignal.any([signal, controller.signal]);
|
|
513
|
+
try {
|
|
514
|
+
const result = await directory.browse(browseSignal);
|
|
515
|
+
if (!ownsMenu() || browseSignal.aborted) {
|
|
516
|
+
throw browseSignal.reason ?? new DOMException("Aborted", "AbortError");
|
|
517
|
+
}
|
|
518
|
+
return result;
|
|
519
|
+
} finally {
|
|
520
|
+
if (temporary) await temporary.stop();
|
|
521
|
+
}
|
|
522
|
+
},
|
|
435
523
|
joinRoom,
|
|
436
524
|
openChat: async (commandCtx) => {
|
|
437
525
|
if (ownsMenu()) await openChat(commandCtx);
|