@narumitw/pi-chat 0.1.0 โ†’ 0.1.2

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 CHANGED
@@ -287,6 +287,19 @@ rows before hiding room, connectivity, or input-target status.
287
287
  Pi's public extension widget API does not provide generic mouse hit-testing, so the dock is not
288
288
  clickable and Pi Chat registers no global shortcut. `/chat` remains the menu-first entrypoint.
289
289
 
290
+ ## ๐Ÿงช Local network smoke
291
+
292
+ The normal repository test suite mocks Pi Chat's network transports and does not open DHT sockets.
293
+ Run the opt-in smoke from a local checkout to exercise real local DHT nodes, sparse relay, retries,
294
+ process-boundary discovery and delivery, public-room discovery, and resource cleanup:
295
+
296
+ ```bash
297
+ npm run smoke:chat-network
298
+ ```
299
+
300
+ The equivalent Just command is `just smoke-chat-network`.
301
+ This smoke is intentionally excluded from `npm test` and CI because local UDP scheduling can be nondeterministic under parallel load.
302
+
290
303
  ## ๐Ÿ—‚๏ธ Package layout
291
304
 
292
305
  ```text
@@ -295,21 +308,26 @@ packages/pi-chat/
295
308
  โ”‚ โ”œโ”€โ”€ index.ts
296
309
  โ”‚ โ”œโ”€โ”€ pi-chat.ts
297
310
  โ”‚ โ”œโ”€โ”€ chat-session.ts
298
- โ”‚ โ”œโ”€โ”€ network.ts
311
+ โ”‚ โ”œโ”€โ”€ network-contract.ts
312
+ โ”‚ โ”œโ”€โ”€ network.ts # Loaded only when a room needs a transport
299
313
  โ”‚ โ”œโ”€โ”€ public-room-directory.ts
300
- โ”‚ โ”œโ”€โ”€ directory-network.ts
301
- โ”‚ โ”œโ”€โ”€ protocol.ts
302
- โ”‚ โ”œโ”€โ”€ identity.ts
314
+ โ”‚ โ”œโ”€โ”€ directory-network.ts # Loaded only for public-room discovery
315
+ โ”‚ โ”œโ”€โ”€ room.ts # Lightweight invite and room descriptor compatibility
316
+ โ”‚ โ”œโ”€โ”€ protocol.ts # Signed wire messages and framing
317
+ โ”‚ โ”œโ”€โ”€ nickname.ts # Lightweight nickname normalization
318
+ โ”‚ โ”œโ”€โ”€ identity.ts # Loads DHT and sodium implementations on first cryptographic use
303
319
  โ”‚ โ”œโ”€โ”€ settings.ts
304
- โ”‚ โ”œโ”€โ”€ menu.ts
305
- โ”‚ โ”œโ”€โ”€ chat-view.ts
306
- โ”‚ โ”œโ”€โ”€ widget.ts
320
+ โ”‚ โ”œโ”€โ”€ menu.ts # Loaded on the first menu request
321
+ โ”‚ โ”œโ”€โ”€ chat-view.ts # Loaded on the first composer request
322
+ โ”‚ โ”œโ”€โ”€ widget.ts # Loaded before the first room joins
307
323
  โ”‚ โ””โ”€โ”€ text.ts
308
- โ”œโ”€โ”€ test/
324
+ โ”œโ”€โ”€ scripts/ # Opt-in real local network smoke and child fixture
325
+ โ”œโ”€โ”€ test/ # Deterministic tests with mocked network boundaries
309
326
  โ”œโ”€โ”€ README.md
310
327
  โ”œโ”€โ”€ LICENSE
311
328
  โ”œโ”€โ”€ package.json
312
- โ””โ”€โ”€ tsconfig.json
329
+ โ”œโ”€โ”€ tsconfig.json
330
+ โ””โ”€โ”€ tsconfig.network-smoke.json
313
331
  ```
314
332
 
315
333
  ## ๐Ÿ”Ž Keywords
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-chat",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Experimental peer-to-peer chat extension for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@narumitw/pi-tui-kit": "^0.49.1",
36
- "hyperdht": "6.33.0",
36
+ "hyperdht": "6.33.1",
37
37
  "hyperswarm": "4.17.0",
38
38
  "sodium-universal": "5.0.1"
39
39
  },
@@ -42,10 +42,10 @@
42
42
  "@earendil-works/pi-tui": "*"
43
43
  },
44
44
  "devDependencies": {
45
- "@biomejs/biome": "2.5.7",
46
- "@earendil-works/pi-coding-agent": "0.84.1",
47
- "@earendil-works/pi-tui": "0.84.1",
48
- "@types/node": "26.1.2",
45
+ "@biomejs/biome": "2.5.8",
46
+ "@earendil-works/pi-coding-agent": "0.84.2",
47
+ "@earendil-works/pi-tui": "0.84.2",
48
+ "@types/node": "26.2.0",
49
49
  "typescript": "7.0.2"
50
50
  },
51
51
  "repository": {
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import type { Duplex } from "node:stream";
3
3
  import Hyperswarm, { type PeerDiscovery, type PeerInfo } from "hyperswarm";
4
4
  import type { ChatIdentity } from "./identity.js";
5
- import { MAX_DIRECT_NEIGHBORS } from "./network.js";
5
+ import { MAX_DIRECT_NEIGHBORS } from "./network-contract.js";
6
6
  import { PeerRateLimiter } from "./protocol.js";
7
7
  import {
8
8
  createDirectoryPresence,
package/src/identity.ts CHANGED
@@ -1,10 +1,25 @@
1
1
  import { createHash, hkdfSync } from "node:crypto";
2
- import HyperDHT from "hyperdht";
3
- import sodium from "sodium-universal";
2
+ import { createRequire } from "node:module";
3
+
4
+ export { normalizeNickname } from "./nickname.js";
5
+
6
+ const require = createRequire(import.meta.url);
7
+ type HyperDht = typeof import("hyperdht")["default"];
8
+ type Sodium = typeof import("sodium-universal")["default"];
9
+ let hyperDhtImplementation: HyperDht | undefined;
10
+ let sodiumImplementation: Sodium | undefined;
11
+
12
+ function hyperDht(): HyperDht {
13
+ hyperDhtImplementation ??= require("hyperdht") as HyperDht;
14
+ return hyperDhtImplementation;
15
+ }
16
+
17
+ function sodium(): Sodium {
18
+ sodiumImplementation ??= require("sodium-universal") as Sodium;
19
+ return sodiumImplementation;
20
+ }
4
21
 
5
22
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
6
- const MAX_NICKNAME_GRAPHEMES = 24;
7
- const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;
8
23
 
9
24
  export interface ChatIdentity {
10
25
  seed: string;
@@ -13,19 +28,10 @@ export interface ChatIdentity {
13
28
  tag: string;
14
29
  }
15
30
 
16
- export function normalizeNickname(value: unknown): string | undefined {
17
- if (typeof value !== "string") return undefined;
18
- const normalized = value.normalize("NFKC").trim();
19
- if (!normalized || /\p{Cc}/u.test(normalized) || BIDI_CONTROLS.test(normalized)) return undefined;
20
- const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
21
- if (Array.from(segmenter.segment(normalized)).length > MAX_NICKNAME_GRAPHEMES) return undefined;
22
- return normalized;
23
- }
24
-
25
31
  export function createIdentity(seed: Uint8Array): ChatIdentity {
26
32
  if (seed.byteLength !== 32) throw new Error("Pi Chat identity seed must be exactly 32-byte.");
27
33
  const stableSeed = Buffer.from(seed);
28
- const keyPair = HyperDHT.keyPair(stableSeed);
34
+ const keyPair = hyperDht().keyPair(stableSeed);
29
35
  return {
30
36
  seed: stableSeed.toString("base64url"),
31
37
  publicKey: Buffer.from(keyPair.publicKey),
@@ -53,8 +59,9 @@ export function deriveScopedIdentity(identity: ChatIdentity, scope: string): Cha
53
59
  }
54
60
 
55
61
  export function signIdentityPayload(identity: ChatIdentity, payload: Uint8Array): string {
56
- const signature = Buffer.alloc(sodium.crypto_sign_BYTES);
57
- sodium.crypto_sign_detached(signature, payload, identity.secretKey);
62
+ const implementation = sodium();
63
+ const signature = Buffer.alloc(implementation.crypto_sign_BYTES);
64
+ implementation.crypto_sign_detached(signature, payload, identity.secretKey);
58
65
  return signature.toString("base64url");
59
66
  }
60
67
 
@@ -65,9 +72,10 @@ export function verifyIdentityPayload(
65
72
  ): boolean {
66
73
  if (publicKey.byteLength !== 32 || !/^[A-Za-z0-9_-]{86}$/u.test(signatureValue)) return false;
67
74
  const signature = Buffer.from(signatureValue, "base64url");
68
- if (signature.byteLength !== sodium.crypto_sign_BYTES) return false;
75
+ const implementation = sodium();
76
+ if (signature.byteLength !== implementation.crypto_sign_BYTES) return false;
69
77
  try {
70
- return sodium.crypto_sign_verify_detached(signature, payload, publicKey);
78
+ return implementation.crypto_sign_verify_detached(signature, payload, publicKey);
71
79
  } catch {
72
80
  return false;
73
81
  }
package/src/menu.ts CHANGED
@@ -1,9 +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";
6
5
  import { type PublicRoomBrowseResult, sortDirectoryRooms } from "./public-room-directory.js";
6
+ import { createPublicRoom, parseInvite, type RoomDescriptor } from "./room.js";
7
7
  import { type ChatSettings, descriptorFromRememberedRoom, type WidgetMode } from "./settings.js";
8
8
  import { sanitizeSingleLine } from "./text.js";
9
9
 
@@ -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,28 +1,17 @@
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
 
25
- export const MAX_DIRECT_NEIGHBORS = 8;
14
+ export { MAX_DIRECT_NEIGHBORS } from "./network-contract.js";
26
15
 
27
16
  export function directNeighborLimit(requested?: number): number {
28
17
  if (!Number.isSafeInteger(requested) || (requested ?? 0) <= 0) return MAX_DIRECT_NEIGHBORS;
@@ -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
+ }
package/src/pi-chat.ts CHANGED
@@ -6,30 +6,16 @@ import type {
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import type { ChatSnapshot, ChatTransport } from "./chat-session.js";
8
8
  import { ChatSession } from "./chat-session.js";
9
- import { ChatView } from "./chat-view.js";
10
- import {
11
- HyperswarmDirectoryTransport,
12
- type PublicRoomDirectory,
13
- PublicRoomDirectorySession,
14
- } from "./directory-network.js";
9
+ import type { PublicRoomDirectory } from "./directory-network.js";
15
10
  import {
16
11
  type ChatIdentity,
17
12
  createIdentity,
18
13
  deriveScopedIdentity,
19
14
  formatIdentityLabel,
20
15
  } from "./identity.js";
21
- import { type ChatMenuSource, type JoinRoomOptions, showChatMenu } from "./menu.js";
22
- import {
23
- HyperswarmTransport,
24
- type HyperswarmTransportOptions,
25
- MAX_DIRECT_NEIGHBORS,
26
- } from "./network.js";
27
- import {
28
- createPrivateRoom,
29
- createPublicRoom,
30
- parseInvite,
31
- type RoomDescriptor,
32
- } from "./protocol.js";
16
+ import type { ChatMenuSource, JoinRoomOptions } from "./menu.js";
17
+ import { type HyperswarmTransportOptions, MAX_DIRECT_NEIGHBORS } from "./network-contract.js";
18
+ import { createPrivateRoom, createPublicRoom, parseInvite, type RoomDescriptor } from "./room.js";
33
19
  import {
34
20
  awaitChatSettingsWrites,
35
21
  type ChatSettings,
@@ -41,7 +27,6 @@ import {
41
27
  type WidgetMode,
42
28
  } from "./settings.js";
43
29
  import { sanitizeSingleLine } from "./text.js";
44
- import { renderChatWidget } from "./widget.js";
45
30
 
46
31
  const CHAT_UI_KEY = "chat";
47
32
  const EXPERIMENTAL_WARNING =
@@ -67,30 +52,52 @@ export interface PiChatDirectoryOptions {
67
52
  advertisedSlug?: string;
68
53
  }
69
54
 
55
+ type Awaitable<Value> = Value | Promise<Value>;
56
+ type ChatMenuModule = Pick<typeof import("./menu.js"), "showChatMenu">;
57
+ type ChatViewModule = Pick<typeof import("./chat-view.js"), "ChatView">;
58
+ type ChatWidgetModule = Pick<typeof import("./widget.js"), "renderChatWidget">;
59
+
70
60
  export interface PiChatDependencies {
71
61
  settingsPath: string;
72
62
  randomBytes(size: number): Buffer;
73
- createTransport(options: HyperswarmTransportOptions): ChatTransport;
74
- createDirectory(options: PiChatDirectoryOptions): PublicRoomDirectory;
63
+ createTransport(options: HyperswarmTransportOptions): Awaitable<ChatTransport>;
64
+ createDirectory(options: PiChatDirectoryOptions): Awaitable<PublicRoomDirectory>;
75
65
  updateSettings: typeof updateChatSettingsFile;
66
+ loadChatMenu(): Promise<ChatMenuModule>;
67
+ loadChatView(): Promise<ChatViewModule>;
68
+ loadChatWidget(): Promise<ChatWidgetModule>;
76
69
  }
77
70
 
78
71
  export function createPiChatExtension(
79
72
  dependencies: Partial<PiChatDependencies> = {},
80
73
  ): (pi: ExtensionAPI) => void {
74
+ const loadNetwork = cachedModuleLoader(() => import("./network.js"));
75
+ const loadDirectoryNetwork = cachedModuleLoader(() => import("./directory-network.js"));
81
76
  const deps: PiChatDependencies = {
82
77
  settingsPath: dependencies.settingsPath ?? chatSettingsPath(),
83
78
  randomBytes: dependencies.randomBytes ?? nodeRandomBytes,
84
79
  createTransport:
85
- dependencies.createTransport ?? ((options) => new HyperswarmTransport(options)),
80
+ dependencies.createTransport ??
81
+ (async (options) => {
82
+ const { HyperswarmTransport } = await loadNetwork();
83
+ return new HyperswarmTransport(options);
84
+ }),
86
85
  createDirectory:
87
86
  dependencies.createDirectory ??
88
- ((options) =>
89
- new PublicRoomDirectorySession({
87
+ (async (options) => {
88
+ const { HyperswarmDirectoryTransport, PublicRoomDirectorySession } =
89
+ await loadDirectoryNetwork();
90
+ return new PublicRoomDirectorySession({
90
91
  ...options,
91
92
  transport: new HyperswarmDirectoryTransport({ identity: options.identity }),
92
- })),
93
+ });
94
+ }),
93
95
  updateSettings: dependencies.updateSettings ?? updateChatSettingsFile,
96
+ loadChatMenu: cachedModuleLoader(dependencies.loadChatMenu ?? (() => import("./menu.js"))),
97
+ loadChatView: cachedModuleLoader(dependencies.loadChatView ?? (() => import("./chat-view.js"))),
98
+ loadChatWidget: cachedModuleLoader(
99
+ dependencies.loadChatWidget ?? (() => import("./widget.js")),
100
+ ),
94
101
  };
95
102
  const updateChatSettings = deps.updateSettings;
96
103
 
@@ -106,7 +113,9 @@ export function createPiChatExtension(
106
113
  let chatDraft = "";
107
114
  let restoreError: string | undefined;
108
115
  let restoringRoomId: string | undefined;
116
+ let joinOwner: { sessionManager: unknown; generation: number; token: symbol } | undefined;
109
117
  const ownedTasks = new Set<Promise<unknown>>();
118
+ let renderChatWidget: ChatWidgetModule["renderChatWidget"] | undefined;
110
119
  let widgetRender: (() => void) | undefined;
111
120
  let widgetInstalled = false;
112
121
 
@@ -128,13 +137,15 @@ export function createPiChatExtension(
128
137
  while (ownedTasks.size > 0) await Promise.allSettled([...ownedTasks]);
129
138
  };
130
139
 
131
- const clearUi = (ctx: ExtensionContext): void => {
140
+ const clearUi = (ctx: ExtensionContext, ownerGeneration = generation): void => {
132
141
  try {
133
142
  ctx.ui.setWidget(CHAT_UI_KEY, undefined);
134
143
  ctx.ui.setStatus(CHAT_UI_KEY, undefined);
135
144
  } catch {
136
145
  // Session replacement may invalidate an old UI immediately.
137
146
  }
147
+ if (ctx.sessionManager !== activeSessionManager || generation !== ownerGeneration) return;
148
+ renderChatWidget = undefined;
138
149
  widgetRender = undefined;
139
150
  widgetInstalled = false;
140
151
  };
@@ -165,6 +176,8 @@ export function createPiChatExtension(
165
176
  widgetRender = undefined;
166
177
  return;
167
178
  }
179
+ const renderWidget = renderChatWidget;
180
+ if (!renderWidget) return;
168
181
  if (!widgetInstalled) {
169
182
  ctx.ui.setWidget(CHAT_UI_KEY, (tui, theme) => {
170
183
  const requestRender = () => tui.requestRender();
@@ -172,7 +185,7 @@ export function createPiChatExtension(
172
185
  return {
173
186
  render: (width: number) =>
174
187
  latestSnapshot
175
- ? renderChatWidget(
188
+ ? renderWidget(
176
189
  latestSnapshot,
177
190
  settings.widgetMode ?? "count",
178
191
  width,
@@ -197,12 +210,14 @@ export function createPiChatExtension(
197
210
  const disconnectRoom = async (): Promise<void> => {
198
211
  const owned = chatSession;
199
212
  const ownedDirectory = roomDirectory;
213
+ const uiContext = activeContext;
214
+ const uiGeneration = generation;
200
215
  chatSession = undefined;
201
216
  roomDirectory = undefined;
202
217
  latestSnapshot = undefined;
203
218
  chatDraft = "";
204
219
  await Promise.allSettled([owned?.leave(), ownedDirectory?.stop()]);
205
- if (activeContext) clearUi(activeContext);
220
+ if (uiContext) clearUi(uiContext, uiGeneration);
206
221
  };
207
222
 
208
223
  const ensureIdentity = async (
@@ -267,39 +282,54 @@ export function createPiChatExtension(
267
282
  const startPublicRoomDirectory = (
268
283
  room: RoomDescriptor,
269
284
  identity: ChatIdentity,
285
+ session: ChatSession,
270
286
  ctx: ExtensionContext,
271
287
  owner: unknown,
272
288
  ownerGeneration: number,
273
289
  ): void => {
274
290
  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
291
  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
- );
292
+ (async () => {
293
+ let directory: PublicRoomDirectory | undefined;
294
+ try {
295
+ directory = await deps.createDirectory({
296
+ identity: deriveScopedIdentity(identity, `directory:#${room.slug}`),
297
+ advertisedSlug: room.slug,
298
+ });
299
+ if (
300
+ !isCurrent(owner, ownerGeneration) ||
301
+ controller.signal.aborted ||
302
+ chatSession !== session
303
+ ) {
304
+ await directory.stop();
305
+ return;
306
+ }
307
+ roomDirectory = directory;
308
+ await directory.start(controller.signal);
309
+ } catch (error) {
310
+ const ownsDirectory = !directory || roomDirectory === directory;
311
+ if (directory && roomDirectory === directory) roomDirectory = undefined;
312
+ if (directory) await Promise.allSettled([directory.stop()]);
313
+ if (
314
+ ownsDirectory &&
315
+ isCurrent(owner, ownerGeneration) &&
316
+ chatSession === session &&
317
+ session.snapshot().room.id === room.id
318
+ ) {
319
+ notifySafely(
320
+ ctx,
321
+ `Pi Chat public-room discovery is unavailable: ${sanitizeSingleLine(
322
+ error instanceof Error ? error.message : String(error),
323
+ )}. Chat remains connected.`,
324
+ "warning",
325
+ );
326
+ }
297
327
  }
298
- }),
328
+ })(),
299
329
  );
300
330
  };
301
331
 
302
- const joinRoom = async (
332
+ const joinRoomOwned = async (
303
333
  room: RoomDescriptor,
304
334
  ctx: ExtensionContext,
305
335
  signal: AbortSignal,
@@ -332,11 +362,27 @@ export function createPiChatExtension(
332
362
  if (!identity || !isCurrent(owner, ownerGeneration) || signal.aborted) return false;
333
363
  const nickname = settings.nickname;
334
364
  if (!nickname) throw new Error("Pi Chat nickname is unavailable.");
335
- const transport = deps.createTransport({
336
- room,
337
- identity,
338
- maxPeers: MAX_DIRECT_NEIGHBORS,
339
- });
365
+ const widgetModule = await loadOwnedModule(
366
+ deps.loadChatWidget,
367
+ () => isCurrent(owner, ownerGeneration) && !signal.aborted,
368
+ );
369
+ if (!widgetModule) return false;
370
+ let transport: ChatTransport;
371
+ try {
372
+ transport = await deps.createTransport({
373
+ room,
374
+ identity,
375
+ maxPeers: MAX_DIRECT_NEIGHBORS,
376
+ });
377
+ } catch (error) {
378
+ if (!isCurrent(owner, ownerGeneration) || signal.aborted) return false;
379
+ throw error;
380
+ }
381
+ if (!isCurrent(owner, ownerGeneration) || signal.aborted) {
382
+ await transport.stop();
383
+ return false;
384
+ }
385
+ renderChatWidget = widgetModule.renderChatWidget;
340
386
  const session = new ChatSession({
341
387
  room,
342
388
  identity,
@@ -376,17 +422,31 @@ export function createPiChatExtension(
376
422
  restoreError = undefined;
377
423
  latestSnapshot = session.snapshot();
378
424
  updateUi(ctx, latestSnapshot);
379
- startPublicRoomDirectory(room, identity, ctx, owner, ownerGeneration);
425
+ startPublicRoomDirectory(room, identity, session, ctx, owner, ownerGeneration);
380
426
  return true;
381
427
  } catch (error) {
382
428
  if (chatSession === session) chatSession = undefined;
383
429
  await session.leave();
384
- clearUi(ctx);
430
+ clearUi(ctx, ownerGeneration);
385
431
  if (!signal.aborted && isCurrent(owner, ownerGeneration)) throw error;
386
432
  return false;
387
433
  }
388
434
  };
389
435
 
436
+ const joinRoom: typeof joinRoomOwned = async (room, ctx, signal, options) => {
437
+ const existing = joinOwner;
438
+ if (existing?.sessionManager === ctx.sessionManager && existing.generation === generation) {
439
+ throw new Error("A Pi Chat room join is already in progress.");
440
+ }
441
+ const token = Symbol("chat-join");
442
+ joinOwner = { sessionManager: ctx.sessionManager, generation, token };
443
+ try {
444
+ return await joinRoomOwned(room, ctx, signal, options);
445
+ } finally {
446
+ if (joinOwner?.token === token) joinOwner = undefined;
447
+ }
448
+ };
449
+
390
450
  const updateRememberedSurface = async (
391
451
  surface: "chat" | "pi",
392
452
  ctx: ExtensionContext,
@@ -429,6 +489,12 @@ export function createPiChatExtension(
429
489
  const ownerSignal = controller.signal;
430
490
  await updateRememberedSurface("chat", ctx, owner, ownerGeneration, session);
431
491
  if (!isCurrent(owner, ownerGeneration) || chatSession !== session) return;
492
+ const viewModule = await loadOwnedModule(
493
+ deps.loadChatView,
494
+ () => isCurrent(owner, ownerGeneration) && chatSession === session,
495
+ );
496
+ if (!viewModule) return;
497
+ const { ChatView } = viewModule;
432
498
  await ctx.ui.custom<void>(
433
499
  (tui, theme, _keybindings, done) =>
434
500
  new ChatView({
@@ -507,9 +573,13 @@ export function createPiChatExtension(
507
573
  const activeDirectory = roomDirectory;
508
574
  const directory =
509
575
  activeDirectory ??
510
- deps.createDirectory({ identity: createIdentity(deps.randomBytes(32)) });
576
+ (await deps.createDirectory({ identity: createIdentity(deps.randomBytes(32)) }));
511
577
  const temporary = activeDirectory ? undefined : directory;
512
578
  const browseSignal = AbortSignal.any([signal, controller.signal]);
579
+ if (!ownsMenu() || browseSignal.aborted) {
580
+ if (temporary) await temporary.stop();
581
+ throw browseSignal.reason ?? new DOMException("Aborted", "AbortError");
582
+ }
513
583
  try {
514
584
  const result = await directory.browse(browseSignal);
515
585
  if (!ownsMenu() || browseSignal.aborted) {
@@ -624,6 +694,11 @@ export function createPiChatExtension(
624
694
  if (!isCurrent(owner, ownerGeneration)) throw new Error("Pi Chat session is stale.");
625
695
  const input = args.trim();
626
696
  if (!input) {
697
+ const menuModule = await loadOwnedModule(deps.loadChatMenu, () =>
698
+ isCurrent(owner, ownerGeneration),
699
+ );
700
+ if (!menuModule) return;
701
+ const { showChatMenu } = menuModule;
627
702
  await showChatMenu(ctx, menuSource(ctx), {
628
703
  signal: controller.signal,
629
704
  isCurrent: () => isCurrent(owner, ownerGeneration),
@@ -732,4 +807,30 @@ function notifySafely(
732
807
  }
733
808
  }
734
809
 
810
+ async function loadOwnedModule<Module>(
811
+ load: () => Promise<Module>,
812
+ isCurrent: () => boolean,
813
+ ): Promise<Module | undefined> {
814
+ try {
815
+ const module = await load();
816
+ return isCurrent() ? module : undefined;
817
+ } catch (error) {
818
+ if (!isCurrent()) return undefined;
819
+ throw error;
820
+ }
821
+ }
822
+
823
+ function cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {
824
+ let pending: Promise<Module> | undefined;
825
+ return () => {
826
+ if (!pending) {
827
+ pending = load().catch((error) => {
828
+ pending = undefined;
829
+ throw error;
830
+ });
831
+ }
832
+ return pending;
833
+ };
834
+ }
835
+
735
836
  export default createPiChatExtension();
package/src/protocol.ts CHANGED
@@ -1,6 +1,17 @@
1
- import { createHash, createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
2
  import type { ChatIdentity } from "./identity.js";
3
- import { normalizeNickname, signIdentityPayload, verifyIdentityPayload } from "./identity.js";
3
+ import { signIdentityPayload, verifyIdentityPayload } from "./identity.js";
4
+ import { normalizeNickname } from "./nickname.js";
5
+ import type { RoomDescriptor } from "./room.js";
6
+
7
+ export {
8
+ createPrivateRoom,
9
+ createPublicRoom,
10
+ isCompatibleRoomId,
11
+ legacyRoomId,
12
+ parseInvite,
13
+ type RoomDescriptor,
14
+ } from "./room.js";
4
15
 
5
16
  export const PROTOCOL_VERSION = 2;
6
17
  export const MAX_FRAME_BYTES = 16 * 1024;
@@ -8,20 +19,9 @@ export const MAX_MESSAGE_BYTES = 4 * 1024;
8
19
  export const MAX_GOSSIP_HOPS = 8;
9
20
  export const MAX_EVENT_AGE_MS = 5 * 60_000;
10
21
  const MAX_EVENT_FUTURE_MS = 60_000;
11
- const PUBLIC_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/u;
12
22
  const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
13
23
  const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
14
24
 
15
- export interface RoomDescriptor {
16
- kind: "private" | "public";
17
- label: string;
18
- id: string;
19
- topic: Buffer;
20
- key: Buffer;
21
- invite?: string;
22
- slug?: string;
23
- }
24
-
25
25
  export interface HelloMessage {
26
26
  v: 2;
27
27
  type: "hello";
@@ -72,63 +72,6 @@ export interface GoodbyeMessage {
72
72
 
73
73
  export type ProtocolMessage = HelloMessage | GossipMessage | GoodbyeMessage;
74
74
 
75
- export function createPrivateRoom(secret: Uint8Array): RoomDescriptor {
76
- if (secret.byteLength !== 32) throw new Error("Private room secrets must be 32 bytes.");
77
- const bytes = Buffer.from(secret);
78
- const topic = domainHash("pi-chat/discovery/private/v2", bytes);
79
- return {
80
- kind: "private",
81
- label: `private ${shortRoomId(topic)}`,
82
- id: topic.toString("base64url"),
83
- topic,
84
- key: deriveRoomKey(bytes),
85
- invite: `pichat:v2:${bytes.toString("base64url")}`,
86
- };
87
- }
88
-
89
- export function parseInvite(value: string): RoomDescriptor {
90
- const match = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(value.trim());
91
- const encodedSecret = match?.[1];
92
- if (!encodedSecret) throw new Error("This is not a valid Pi Chat invite.");
93
- const secret = Buffer.from(encodedSecret, "base64url");
94
- if (secret.length !== 32) throw new Error("This is not a valid Pi Chat invite.");
95
- return createPrivateRoom(secret);
96
- }
97
-
98
- export function createPublicRoom(slug: string): RoomDescriptor {
99
- if (!PUBLIC_SLUG.test(slug)) {
100
- throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
101
- }
102
- const material = Buffer.from(`pi-chat/public/v2:${slug}`, "utf8");
103
- const topic = createHash("sha256").update(material).digest();
104
- return {
105
- kind: "public",
106
- label: `#${slug}`,
107
- id: topic.toString("base64url"),
108
- topic,
109
- key: deriveRoomKey(material),
110
- slug,
111
- };
112
- }
113
-
114
- export function legacyRoomId(room: RoomDescriptor): string | undefined {
115
- if (room.kind === "public" && room.slug) {
116
- return createHash("sha256")
117
- .update(Buffer.from(`pi-chat/public/v1:${room.slug}`, "utf8"))
118
- .digest("base64url");
119
- }
120
- const encodedSecret = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(room.invite ?? "")?.[1];
121
- if (!encodedSecret) return undefined;
122
- const secret = Buffer.from(encodedSecret, "base64url");
123
- return secret.length === 32
124
- ? domainHash("pi-chat/discovery/private/v1", secret).toString("base64url")
125
- : undefined;
126
- }
127
-
128
- export function isCompatibleRoomId(room: RoomDescriptor, id: string): boolean {
129
- return room.id === id || legacyRoomId(room) === id;
130
- }
131
-
132
75
  export function createHello(
133
76
  room: RoomDescriptor,
134
77
  nicknameValue: string,
@@ -458,24 +401,6 @@ function validateEventFields(issuedAt: number, id: string): void {
458
401
  if (!validId(id)) throw new Error("Message id is invalid.");
459
402
  }
460
403
 
461
- function deriveRoomKey(material: Uint8Array): Buffer {
462
- return Buffer.from(
463
- hkdfSync("sha256", material, Buffer.from("pi-chat/v2"), Buffer.from("room-handshake"), 32),
464
- );
465
- }
466
-
467
- function domainHash(domain: string, material: Uint8Array): Buffer {
468
- return createHash("sha256")
469
- .update(domain)
470
- .update(Buffer.from([0]))
471
- .update(material)
472
- .digest();
473
- }
474
-
475
- function shortRoomId(topic: Uint8Array): string {
476
- return Buffer.from(topic).subarray(0, 5).toString("base64url");
477
- }
478
-
479
404
  function helloProof(
480
405
  room: RoomDescriptor,
481
406
  nickname: string,
package/src/room.ts ADDED
@@ -0,0 +1,88 @@
1
+ import { createHash, hkdfSync } from "node:crypto";
2
+
3
+ const PUBLIC_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/u;
4
+
5
+ export interface RoomDescriptor {
6
+ kind: "private" | "public";
7
+ label: string;
8
+ id: string;
9
+ topic: Buffer;
10
+ key: Buffer;
11
+ invite?: string;
12
+ slug?: string;
13
+ }
14
+
15
+ export function createPrivateRoom(secret: Uint8Array): RoomDescriptor {
16
+ if (secret.byteLength !== 32) throw new Error("Private room secrets must be 32 bytes.");
17
+ const bytes = Buffer.from(secret);
18
+ const topic = domainHash("pi-chat/discovery/private/v2", bytes);
19
+ return {
20
+ kind: "private",
21
+ label: `private ${shortRoomId(topic)}`,
22
+ id: topic.toString("base64url"),
23
+ topic,
24
+ key: deriveRoomKey(bytes),
25
+ invite: `pichat:v2:${bytes.toString("base64url")}`,
26
+ };
27
+ }
28
+
29
+ export function parseInvite(value: string): RoomDescriptor {
30
+ const match = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(value.trim());
31
+ const encodedSecret = match?.[1];
32
+ if (!encodedSecret) throw new Error("This is not a valid Pi Chat invite.");
33
+ const secret = Buffer.from(encodedSecret, "base64url");
34
+ if (secret.length !== 32) throw new Error("This is not a valid Pi Chat invite.");
35
+ return createPrivateRoom(secret);
36
+ }
37
+
38
+ export function createPublicRoom(slug: string): RoomDescriptor {
39
+ if (!PUBLIC_SLUG.test(slug)) {
40
+ throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
41
+ }
42
+ const material = Buffer.from(`pi-chat/public/v2:${slug}`, "utf8");
43
+ const topic = createHash("sha256").update(material).digest();
44
+ return {
45
+ kind: "public",
46
+ label: `#${slug}`,
47
+ id: topic.toString("base64url"),
48
+ topic,
49
+ key: deriveRoomKey(material),
50
+ slug,
51
+ };
52
+ }
53
+
54
+ export function legacyRoomId(room: RoomDescriptor): string | undefined {
55
+ if (room.kind === "public" && room.slug) {
56
+ return createHash("sha256")
57
+ .update(Buffer.from(`pi-chat/public/v1:${room.slug}`, "utf8"))
58
+ .digest("base64url");
59
+ }
60
+ const encodedSecret = /^pichat:v[12]:([A-Za-z0-9_-]{43})$/u.exec(room.invite ?? "")?.[1];
61
+ if (!encodedSecret) return undefined;
62
+ const secret = Buffer.from(encodedSecret, "base64url");
63
+ return secret.length === 32
64
+ ? domainHash("pi-chat/discovery/private/v1", secret).toString("base64url")
65
+ : undefined;
66
+ }
67
+
68
+ export function isCompatibleRoomId(room: RoomDescriptor, id: string): boolean {
69
+ return room.id === id || legacyRoomId(room) === id;
70
+ }
71
+
72
+ function deriveRoomKey(material: Uint8Array): Buffer {
73
+ return Buffer.from(
74
+ hkdfSync("sha256", material, Buffer.from("pi-chat/v2"), Buffer.from("room-handshake"), 32),
75
+ );
76
+ }
77
+
78
+ function domainHash(domain: string, material: Uint8Array): Buffer {
79
+ return createHash("sha256")
80
+ .update(domain)
81
+ .update(Buffer.from([0]))
82
+ .update(material)
83
+ .digest();
84
+ }
85
+
86
+ function shortRoomId(topic: Uint8Array): string {
87
+ return Buffer.from(topic).subarray(0, 5).toString("base64url");
88
+ }
package/src/settings.ts CHANGED
@@ -3,13 +3,8 @@ import { constants } from "node:fs";
3
3
  import { chmod, lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
- import { normalizeNickname } from "./identity.js";
7
- import {
8
- createPublicRoom,
9
- isCompatibleRoomId,
10
- parseInvite,
11
- type RoomDescriptor,
12
- } from "./protocol.js";
6
+ import { normalizeNickname } from "./nickname.js";
7
+ import { createPublicRoom, isCompatibleRoomId, parseInvite, type RoomDescriptor } from "./room.js";
13
8
 
14
9
  export const CHAT_SETTINGS_FILE = "pi-chat.json";
15
10
  const MAX_SETTINGS_BYTES = 64 * 1024;