@narumitw/pi-chat 0.1.2 → 0.1.3

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
@@ -1,35 +1,24 @@
1
- # 💬 Pi Chat — Experimental P2P Developer Chat for Pi
1
+ # 💬 Pi Chat — Talk to Peers Without Leaving Pi
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@narumitw/pi-chat)](https://www.npmjs.com/package/@narumitw/pi-chat) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
4
 
5
5
  > [!WARNING]
6
- > Pi Chat is experimental. Its protocol, identity format, networking behavior, and interaction flow
7
- > may change between releases. It is not an anonymous or reliable messaging service.
6
+ > Pi Chat is experimental.
7
+ > Its protocol, identity format, networking behavior, and interaction flow may change between releases.
8
+ > It is not an anonymous or reliable messaging service.
8
9
 
9
- `@narumitw/pi-chat` adds an ephemeral peer-to-peer chat room beside your Pi coding workflow. It uses
10
- Hyperswarm and HyperDHT to discover peers and opens encrypted Noise streams directly between them.
11
- Chat messages remain separate from Pi sessions, prompts, model context, repositories, and agent
12
- output.
10
+ Join ephemeral peer-to-peer chat rooms beside your Pi workflow without putting chat messages into prompts, model context, repositories, or agent output.
11
+
12
+ Pi Chat discovers peers with Hyperswarm and HyperDHT and connects them through encrypted Noise streams.
13
13
 
14
14
  ## ✨ Features
15
15
 
16
- - Creates random private rooms shared through bearer invite codes.
17
- - Browses currently discovered public rooms by estimated active participants, or joins a known
18
- lowercase slug directly.
19
- - Shows every nickname with a stable public-key fingerprint such as
20
- `Mika~7K2P-9D4M-HQ3T`.
21
- - Relays signed chat and presence events through a sparse P2P gossip overlay and suppresses duplicate
22
- display and forwarding inside a bounded deduplication window.
23
- - Keeps an adaptive joined-room dock visible above the Pi editor with explicit input-target status.
24
- - Opens a focused, scrollable full-size chat composer with multiline IME support.
25
- - Preserves chat drafts when returning to Pi or when no direct neighbor can accept a message.
26
- - Restores a remembered room and the last intentional chat/Pi surface when Pi restarts.
27
- - Uses authenticated direct streams, origin signatures, and an invite-derived private-room handshake.
28
- - Limits neighbors, participants, frames, messages, hops, catalogs, transcript entries, reconnect
29
- work, and per-neighbor/per-origin message rates.
30
- - Keeps identity settings local with private permissions and atomic publication.
31
- - Cleans up discovery, sockets, timers, status, and widgets on leave, reload, session replacement,
32
- or shutdown.
16
+ - Creates private rooms with bearer invites or joins discoverable public rooms by slug.
17
+ - Shows stable public-key fingerprints beside nicknames so peers can verify identities.
18
+ - Keeps chat in a dedicated composer and visible dock beside the normal Pi editor.
19
+ - Preserves drafts and optionally restores a remembered room and the last selected surface.
20
+ - Signs and relays bounded events over authenticated encrypted peer connections.
21
+ - Stores identity settings privately and cleans up all networking and UI resources on leave or shutdown.
33
22
 
34
23
  ## 📦 Install
35
24
 
@@ -48,46 +37,43 @@ pi -e npm:@narumitw/pi-chat
48
37
  Try the extension from a local checkout:
49
38
 
50
39
  ```bash
40
+ npm --workspace @narumitw/pi-chat run build
51
41
  pi --no-extensions --no-skills --no-session -e ./packages/pi-chat
52
42
  ```
53
43
 
54
- Load the package only once per Pi process. Repeating `-e ./packages/pi-chat` creates duplicate
55
- extension instances and suffixed commands such as `/chat:1` and `/chat:2`.
44
+ The package declares `dist/index.ts`, so an unbuilt local checkout must be built before Pi loads the package directory.
45
+
46
+ Load the package only once per Pi process.
47
+ Repeating `-e ./packages/pi-chat` creates duplicate extension instances and suffixed commands such as `/chat:1` and `/chat:2`.
56
48
 
57
- Pi extensions execute with your user permissions. Review source before installing third-party
58
- packages.
49
+ Pi extensions execute with your user permissions.
50
+ Review source before installing third-party packages.
59
51
 
60
52
  ## 🚀 Quick start
61
53
 
62
- Run:
54
+ Run `/chat`, choose a public or private room, set a nickname, and start chatting.
55
+ Press `Escape` or `Ctrl+C` to return to the Pi editor without leaving the room or losing the chat draft.
63
56
 
64
- ```text
65
- /chat
66
- ```
57
+ ## 🧭 Rooms and composer
58
+
59
+ The `/chat` menu offers these entry actions:
60
+
61
+ - **Browse public rooms** queries a best-effort P2P directory, sorts discovered rooms by estimated active participants and then slug, and keeps Refresh plus manual slug entry available.
62
+ - **Join public room** accepts a lowercase slug such as `pi-dev`, remembers it after the public-room warning is confirmed, and opens the chat composer.
63
+ - **Join with invite** accepts a private-room invite, then offers **Join and remember**, **Join once**, or **Cancel** before networking starts.
64
+ - **Create private room** generates a random `pichat:v2:…` bearer invite and uses the same explicit persistence choice.
65
+ Existing `pichat:v1` invite text remains accepted as v2 room input.
66
+
67
+ The first join asks for a nickname and joined-room display mode, then previews the generated identity fingerprint and display choice before one atomic save.
68
+ Pi Chat does not read your OS username, Git identity, cwd, repository, or Pi session to fill these values.
69
+ Cancelling creates neither identity settings nor network activity.
70
+
71
+ A successful remembered join stores the room and `chat` surface atomically.
72
+ On the next Pi start, Pi Chat reconnects and reopens the full composer without another command.
73
+ If you intentionally press Escape or Ctrl+C to return to Pi, it remembers the `pi` surface instead: the next start reconnects in the background and leaves the Pi editor focused.
67
74
 
68
- Then choose one of these actions:
69
-
70
- - **Browse public rooms** queries a best-effort P2P directory, sorts discovered rooms by estimated
71
- active participants and then slug, and keeps Refresh plus manual slug entry available.
72
- - **Join public room** accepts a lowercase slug such as `pi-dev`, remembers it after the public-room
73
- warning is confirmed, and opens the chat composer.
74
- - **Join with invite** accepts a private-room invite, then offers **Join and remember**, **Join once**,
75
- or **Cancel** before networking starts.
76
- - **Create private room** generates a random `pichat:v2:…` bearer invite and uses the same explicit
77
- persistence choice. Existing `pichat:v1` invite text remains accepted as v2 room input.
78
-
79
- The first join asks for a nickname and joined-room display mode, then previews the generated
80
- identity fingerprint and display choice before one atomic save. Pi Chat does not read your OS
81
- username, Git identity, cwd, repository, or Pi session to fill these values. Cancelling creates
82
- neither identity settings nor network activity.
83
-
84
- A successful remembered join stores the room and `chat` surface atomically. On the next Pi start,
85
- Pi Chat reconnects and reopens the full composer without another command. If you intentionally press
86
- Escape or Ctrl+C to return to Pi, it remembers the `pi` surface instead: the next start reconnects in
87
- the background and leaves the Pi editor focused.
88
-
89
- While connected, `/chat` opens the state-aware manager. **Open chat in <room>** is selected first,
90
- followed by participants, private invite, settings, status, help, and **Leave and forget room** last.
75
+ While connected, `/chat` opens the state-aware manager.
76
+ **Open chat in <room>** is selected first, followed by participants, private invite, settings, status, help, and **Leave and forget room** last.
91
77
  The persistent dock continues showing room state while the normal Pi editor targets Pi/LLM.
92
78
 
93
79
  Inside the dedicated chat composer:
@@ -98,11 +84,10 @@ Inside the dedicated chat composer:
98
84
  - `PageUp` and `PageDown` scroll transcript history.
99
85
  - `Escape` or `Ctrl+C` returns to Pi/LLM without leaving the room or discarding the chat draft.
100
86
 
101
- The composer retains the draft when no authenticated direct neighbor is available or a relay reaches
102
- zero neighbors. A successful local message reports how many direct neighbors accepted the first
103
- relay; it does not claim room-wide delivery. Signed events may arrive over multiple paths, but each
104
- client displays and forwards one `originPublicKey:eventId` only once while it remains in the bounded
105
- deduplication window. Pi Chat never claims exactly-once delivery, delivery receipts, or offline retry.
87
+ The composer retains the draft when no authenticated direct neighbor is available or a relay reaches zero neighbors.
88
+ A successful local message reports how many direct neighbors accepted the first relay; it does not claim room-wide delivery.
89
+ Signed events may arrive over multiple paths, but each client displays and forwards one `originPublicKey:eventId` only once while it remains in the bounded deduplication window.
90
+ Pi Chat never claims exactly-once delivery, delivery receipts, or offline retry.
106
91
 
107
92
  ## 💬 Commands
108
93
 
@@ -123,18 +108,18 @@ The display format is:
123
108
  nickname~7K2P-9D4M-HQ3T
124
109
  ```
125
110
 
126
- The nickname is editable. The 12-character identity tag is the first 60 bits of the SHA-256 digest
127
- of the authenticated DHT public key, encoded with Crockford Base32 and grouped `4-4-4`. The complete
128
- public key remains the protocol identity. If short tags collide in one room, the UI can extend them;
129
- the short tag is never an authorization boundary.
111
+ The nickname is editable.
112
+ The 12-character identity tag is the first 60 bits of the SHA-256 digest of the authenticated DHT public key, encoded with Crockford Base32 and grouped `4-4-4`.
113
+ The complete public key remains the protocol identity.
114
+ If short tags collide in one room, the UI can extend them.
115
+ The short tag is never an authorization boundary.
130
116
 
131
- A fingerprint establishes continuity for one pseudonymous key. It does **not** prove a person's
132
- real-world identity, prevent a user from creating many identities, or recover trust after the local
133
- identity is reset or lost.
117
+ A fingerprint establishes continuity for one pseudonymous key.
118
+ It does **not** prove a person's real-world identity, prevent a user from creating many identities, or recover trust after the local identity is reset or lost.
134
119
 
135
- Nicknames are NFKC-normalized, trimmed, and limited to 24 grapheme clusters. Terminal, C0/C1, and
136
- bidirectional control characters are rejected. Remote display text is sanitized again before
137
- wrapping or rendering.
120
+ Nicknames are NFKC-normalized, trimmed, and limited to 24 grapheme clusters.
121
+ Terminal, C0/C1, and bidirectional control characters are rejected.
122
+ Remote display text is sanitized again before wrapping or rendering.
138
123
 
139
124
  ## ⚙️ Settings
140
125
 
@@ -144,8 +129,8 @@ Pi Chat uses this user-owned file:
144
129
  <getAgentDir()>/pi-chat.json
145
130
  ```
146
131
 
147
- The usual location is `~/.pi/agent/pi-chat.json`. Pi Chat does not add environment variables or read
148
- project-local settings because the identity material is user-owned and secret.
132
+ The usual location is `~/.pi/agent/pi-chat.json`.
133
+ Pi Chat does not add environment variables or read project-local settings because the identity material is user-owned and secret.
149
134
 
150
135
  Example with a remembered public room:
151
136
 
@@ -168,9 +153,10 @@ Example with a remembered public room:
168
153
  }
169
154
  ```
170
155
 
171
- `resume.rooms` is a bounded catalog designed to permit future multi-room expansion. This release
172
- connects only `activeRoomId`. `surface` is `chat` when the user last kept the composer open and `pi`
173
- after an intentional return to Pi/LLM. Transcripts, drafts, peers, and unread counts are never stored.
156
+ `resume.rooms` is a bounded catalog designed to permit future multi-room expansion.
157
+ This release connects only `activeRoomId`.
158
+ `surface` is `chat` when the user last kept the composer open and `pi` after an intentional return to Pi/LLM.
159
+ Transcripts, drafts, peers, and unread counts are never stored.
174
160
 
175
161
  `widgetMode` accepts:
176
162
 
@@ -179,26 +165,24 @@ after an intentional return to Pi/LLM. Transcripts, drafts, peers, and unread co
179
165
  - `count`: room, direct-peer, and unread status only, without message text.
180
166
  - `off`: hides the persistent widget.
181
167
 
182
- New identities choose a mode before confirmation, with **Room dock** listed first. Existing settings
183
- retain their stored mode; an older document without `widgetMode` continues to default to `count`, so
184
- an upgrade does not expose message text unexpectedly.
168
+ New identities choose a mode before confirmation, with **Room dock** listed first.
169
+ Existing settings retain their stored mode; an older document without `widgetMode` continues to default to `count`, so an upgrade does not expose message text unexpectedly.
185
170
 
186
- Public rooms are remembered only after their existing risk confirmation. A private room is remembered
187
- only when **Join and remember** is selected; this stores its bearer invite in `pi-chat.json`.
188
- **Join once** stores no room material, and Cancel starts neither persistence nor networking. An older
189
- file without `resume` remains disconnected until the next confirmed remembered join. Stored v1 public
190
- or private room ids are normalized to v2 in memory without rewriting the file during load; the next
191
- explicit resume save publishes v2 ids while preserving unknown room and resume fields.
171
+ Public rooms are remembered only after their existing risk confirmation.
172
+ A private room is remembered only when **Join and remember** is selected; this stores its bearer invite in `pi-chat.json`.
173
+ **Join once** stores no room material, and Cancel starts neither persistence nor networking.
174
+ An older file without `resume` remains disconnected until the next confirmed remembered join.
175
+ Stored v1 public or private room ids are normalized to v2 in memory without rewriting the file during load; the next explicit resume save publishes v2 ids while preserving unknown room and resume fields.
192
176
 
193
177
  The identity seed and stored private invites are redacted from UI, notifications, status, and errors.
194
- On POSIX, settings are published with `0600` permissions. A missing file is a side-effect-free read;
195
- it is created only after an explicit first-use confirmation or settings change. Saves are ordered
196
- within one Pi process, preserve unknown top-level and nested resume fields, and use a same-directory
197
- temporary file plus rename. Malformed, invalid, symlinked, non-regular, invalid UTF-8, or oversized
198
- files fail closed and remain unchanged.
178
+ On POSIX, settings are published with `0600` permissions.
179
+ A missing file is a side-effect-free read.
180
+ It is created only after an explicit first-use confirmation or settings change.
181
+ Saves are ordered within one Pi process, preserve unknown top-level and nested resume fields, and use a same-directory temporary file plus rename.
182
+ Malformed, invalid, symlinked, non-regular, invalid UTF-8, or oversized files fail closed and remain unchanged.
199
183
 
200
- **Reset identity** previews the old and candidate fingerprints and requires confirmation. Resetting
201
- changes your fingerprint everywhere, forgets startup restore, and leaves the active room.
184
+ **Reset identity** previews the old and candidate fingerprints and requires confirmation.
185
+ Resetting changes your fingerprint everywhere, forgets startup restore, and leaves the active room.
202
186
 
203
187
  ## 🌐 Network and protocol behavior
204
188
 
@@ -208,64 +192,58 @@ Pi Chat protocol v2 uses one versioned 32-byte discovery topic per room:
208
192
  - A public topic is deterministically derived from the public room slug.
209
193
  - A separate global topic carries only bounded public-room directory presence.
210
194
 
211
- Each peer announces and looks up its topics through HyperDHT. Hyperswarm establishes authenticated,
212
- encrypted Noise streams. The room handshake binds the room proof, nickname, and both neighbor public
213
- keys. Each client keeps at most **8 direct neighbors** instead of completing a full mesh.
195
+ Each peer announces and looks up its topics through HyperDHT.
196
+ Hyperswarm establishes authenticated, encrypted Noise streams.
197
+ The room handshake binds the room proof, nickname, and both neighbor public keys.
198
+ Each client keeps at most **8 direct neighbors** instead of completing a full mesh.
214
199
 
215
- Chat and presence payloads carry the room id, origin public key, event id, issued time, content, and an
216
- Ed25519 signature from the origin identity. A mutable hop budget is decremented at each relay. After
217
- validation, the first copy updates local state and is forwarded to authenticated neighbors other than
218
- the ingress connection; later copies with the same `originPublicKey:eventId` are dropped. Deduplication,
219
- rate-limit, participant, and presence state are all bounded and expire locally.
200
+ Chat and presence payloads carry the room id, origin public key, event id, issued time, content, and an Ed25519 signature from the origin identity.
201
+ A mutable hop budget is decremented at each relay.
202
+ After validation, the first copy updates local state and is forwarded to authenticated neighbors other than the ingress connection; later copies with the same `originPublicKey:eventId` are dropped.
203
+ Deduplication, rate-limit, participant, and presence state are all bounded and expire locally.
220
204
 
221
- The active-participant catalog supports up to **256 remote identities** and expires presence that has
222
- not refreshed for 90 seconds. This is an approximate local view: sparse-overlay partitions, churn,
223
- clock differences, and Sybil identities can change it. Messages are limited to 4 KiB, protocol frames
224
- to 16 KiB, gossip to 8 hops, and the local transcript to 256 entries.
205
+ The active-participant catalog supports up to **256 remote identities** and expires presence that has not refreshed for 90 seconds.
206
+ This is an approximate local view: sparse-overlay partitions, churn, clock differences, and Sybil identities can change it.
207
+ Messages are limited to 4 KiB, protocol frames to 16 KiB, gossip to 8 hops, and the local transcript to 256 entries.
225
208
 
226
- Public-room browsing uses signed room-scoped pseudonyms so honest clients do not expose one stable chat
227
- identity across directory rooms. Directory nodes gossip bounded recent presence and browsers sort
228
- unique scoped origins by estimated count descending, then slug ascending. Results can be empty,
229
- stale, or partial; HyperDHT cannot enumerate every unknown topic, so the UI never calls the list or
230
- count authoritative.
209
+ Public-room browsing uses signed room-scoped pseudonyms so honest clients do not expose one stable chat identity across directory rooms.
210
+ Directory nodes gossip bounded recent presence and browsers sort unique scoped origins by estimated count descending, then slug ascending.
211
+ Results can be empty, stale, or partial; HyperDHT cannot enumerate every unknown topic, so the UI never calls the list or count authoritative.
231
212
 
232
- `pichat:v1` invite text and stored v1 secrets are accepted and mapped to a v2 private room. Newly
233
- created invites use `pichat:v2`. Protocol-v1 full-mesh clients do not interoperate with the v2 gossip
234
- overlay.
213
+ `pichat:v1` invite text and stored v1 secrets are accepted and mapped to a v2 private room.
214
+ Newly created invites use `pichat:v2`.
215
+ Protocol-v1 full-mesh clients do not interoperate with the v2 gossip overlay.
235
216
 
236
- Hyperswarm's default DHT depends on public bootstrap infrastructure. “P2P” does not mean
237
- infrastructure-free. NAT, UDP blocking, enterprise firewalls, bootstrap availability, peer churn, or
238
- a partitioned sparse overlay can prevent connectivity or delivery. Pi Chat performs bounded refresh
239
- and reconnect work but cannot promise a connection or room-wide delivery.
217
+ Hyperswarm's default DHT depends on public bootstrap infrastructure. “P2P” does not mean infrastructure-free.
218
+ NAT, UDP blocking, enterprise firewalls, bootstrap availability, peer churn, or a partitioned sparse overlay can prevent connectivity or delivery.
219
+ Pi Chat performs bounded refresh and reconnect work but cannot promise a connection or room-wide delivery.
240
220
 
241
221
  ## 🔒 Privacy, security, and recovery
242
222
 
243
- - Noise encrypts direct transport, but DHT infrastructure and direct peers may observe IP addresses,
244
- timing, and topic participation metadata. Pi Chat does not provide anonymity.
245
- - Anyone holding a private invite can join. There is no member revocation in the initial protocol;
246
- create a new room after an invite leak.
247
- - Public slugs are guessable. Anyone may join, record, or repost public-room content.
248
- - A local session mute hides one signed origin while still forwarding valid events so a local
249
- preference does not partition the room. It does not stop Sybil identities.
250
- - Remote peers can save or copy messages. Leaving or clearing the local transcript cannot withdraw
251
- copies from their devices.
252
- - Pi Chat never sends cwd, repository data, Git remotes, Pi sessions, prompts, models, files, or agent
253
- output unless a user manually types that information into chat.
223
+ - Noise encrypts direct transport, but DHT infrastructure and direct peers may observe IP addresses, timing, and topic participation metadata.
224
+ Pi Chat does not provide anonymity.
225
+ - Anyone holding a private invite can join.
226
+ There is no member revocation in the initial protocol.
227
+ Create a new room after an invite leak.
228
+ - Public slugs are guessable.
229
+ Anyone may join, record, or repost public-room content.
230
+ - A local session mute hides one signed origin while still forwarding valid events so a local preference does not partition the room.
231
+ It does not stop Sybil identities.
232
+ - Remote peers can save or copy messages.
233
+ Leaving or clearing the local transcript cannot withdraw copies from their devices.
234
+ - Pi Chat never sends cwd, repository data, Git remotes, Pi sessions, prompts, models, files, or agent output unless a user manually types that information into chat.
254
235
  - Chat messages never call Pi message APIs and never enter model context or the main transcript.
255
- - Deleting `pi-chat.json` loses identity continuity and produces a new fingerprint on the next
256
- confirmed join.
236
+ - Deleting `pi-chat.json` loses identity continuity and produces a new fingerprint on the next confirmed join.
257
237
 
258
- If an ordinary join fails, Pi Chat tears down partially opened discovery and sockets and preserves
259
- the previous valid settings. If startup restore fails, the remembered room is kept and `/chat` shows
260
- Retry, Join another room, and Forget recovery actions instead of retrying forever. Invalid settings
261
- must be fixed manually before a save can proceed.
238
+ If an ordinary join fails, Pi Chat tears down partially opened discovery and sockets and preserves the previous valid settings.
239
+ If startup restore fails, the remembered room is kept and `/chat` shows Retry, Join another room, and Forget recovery actions instead of retrying forever.
240
+ Invalid settings must be fixed manually before a save can proceed.
262
241
 
263
- Reloading, replacing the Pi session, or shutting down still releases every session-owned network and
264
- UI resource. A new TUI session then restores the remembered room. Explicit **Leave and forget room**
265
- atomically removes resume state before disconnecting; if that save fails, the room stays connected
266
- and remembered with an actionable error.
242
+ Reloading, replacing the Pi session, or shutting down still releases every session-owned network and UI resource.
243
+ A new TUI session then restores the remembered room.
244
+ Explicit **Leave and forget room** atomically removes resume state before disconnecting; if that save fails, the room stays connected and remembered with an actionable error.
267
245
 
268
- ## 🧪 Experimental limitations
246
+ ## 🚧 Limitations
269
247
 
270
248
  The current experimental release intentionally omits:
271
249
 
@@ -279,19 +257,18 @@ The current experimental release intentionally omits:
279
257
  - more than 256 tracked remote participants or 8 direct neighbors per client;
280
258
  - automatic transfer of chat content into the Pi editor, transcript, or model context.
281
259
 
282
- The joined room uses a persistent read-only widget while the normal Pi view is active. Selecting
283
- **Reply in <room>** temporarily opens the full custom chat view instead of a small floating window.
284
- Closing it returns to Pi and the dock without leaving the room. The dock and composer reduce message
285
- rows before hiding room, connectivity, or input-target status.
260
+ The joined room uses a persistent read-only widget while the normal Pi view is active.
261
+ Selecting **Reply in <room>** temporarily opens the full custom chat view instead of a small floating window.
262
+ Closing it returns to Pi and the dock without leaving the room.
263
+ The dock and composer reduce message rows before hiding room, connectivity, or input-target status.
286
264
 
287
- Pi's public extension widget API does not provide generic mouse hit-testing, so the dock is not
288
- clickable and Pi Chat registers no global shortcut. `/chat` remains the menu-first entrypoint.
265
+ Pi's public extension widget API does not provide generic mouse hit-testing, so the dock is not clickable and Pi Chat registers no global shortcut.
266
+ `/chat` remains the menu-first entrypoint.
289
267
 
290
268
  ## 🧪 Local network smoke
291
269
 
292
270
  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:
271
+ Run the opt-in smoke from a local checkout to exercise real local DHT nodes, sparse relay, retries, process-boundary discovery and delivery, public-room discovery, and resource cleanup:
295
272
 
296
273
  ```bash
297
274
  npm run smoke:chat-network
@@ -321,8 +298,9 @@ packages/pi-chat/
321
298
  │ ├── chat-view.ts # Loaded on the first composer request
322
299
  │ ├── widget.ts # Loaded before the first room joins
323
300
  │ └── text.ts
324
- ├── scripts/ # Opt-in real local network smoke and child fixture
325
- ├── test/ # Deterministic tests with mocked network boundaries
301
+ ├── dist/ # Generated source-mapped Jiti runtime and lazy feature chunks
302
+ ├── scripts/ # Runtime builder plus opt-in real local network smoke and fixture
303
+ ├── test/ # Deterministic behavior, builder, and mocked network coverage
326
304
  ├── README.md
327
305
  ├── LICENSE
328
306
  ├── package.json
@@ -332,9 +310,9 @@ packages/pi-chat/
332
310
 
333
311
  ## 🔎 Keywords
334
312
 
335
- Pi extension, Pi coding agent, peer-to-peer chat, P2P developer chat, Hyperswarm, HyperDHT, terminal
336
- chat, TypeScript Pi package.
313
+ Pi extension, Pi coding agent, peer-to-peer chat, P2P developer chat, Hyperswarm, HyperDHT, terminal chat, TypeScript Pi package.
337
314
 
338
315
  ## 📄 License
339
316
 
340
- MIT. See [`LICENSE`](./LICENSE).
317
+ MIT.
318
+ See [`LICENSE`](./LICENSE).
@@ -0,0 +1,222 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ sanitizeChatText,
5
+ sanitizeSingleLine
6
+ } from "./chunk-IVUX27XD.js";
7
+
8
+ // src/chat-view.ts
9
+ import {
10
+ Editor,
11
+ Key,
12
+ matchesKey,
13
+ sliceByColumn,
14
+ truncateToWidth,
15
+ visibleWidth,
16
+ wrapTextWithAnsi
17
+ } from "@earendil-works/pi-tui";
18
+ var ChatView = class {
19
+ editor;
20
+ tui;
21
+ theme;
22
+ options;
23
+ scrollOffset = 0;
24
+ lastContentRows = 0;
25
+ lastViewportRows = 1;
26
+ followBottom = true;
27
+ messageStatus;
28
+ finished = false;
29
+ _focused = false;
30
+ unsubscribe;
31
+ removeAbort = () => {
32
+ };
33
+ constructor(options) {
34
+ this.options = options;
35
+ this.tui = options.tui;
36
+ this.theme = options.theme;
37
+ const editorTheme = {
38
+ borderColor: (text) => this.theme.fg("accent", text),
39
+ selectList: {
40
+ selectedPrefix: (text) => this.theme.fg("accent", text),
41
+ selectedText: (text) => this.theme.fg("accent", text),
42
+ description: (text) => this.theme.fg("muted", text),
43
+ scrollInfo: (text) => this.theme.fg("dim", text),
44
+ noMatch: (text) => this.theme.fg("warning", text)
45
+ }
46
+ };
47
+ this.editor = new Editor(this.tui, editorTheme);
48
+ if (options.initialDraft) this.editor.setText(options.initialDraft);
49
+ this.unsubscribe = options.subscribe?.(() => this.tui.requestRender()) ?? (() => void 0);
50
+ this.editor.onChange = () => {
51
+ this.messageStatus = void 0;
52
+ this.options.onDraftChange?.(this.editor.getExpandedText());
53
+ };
54
+ this.editor.onSubmit = (text) => {
55
+ const message = text.trim();
56
+ if (!message) {
57
+ this.messageStatus = { kind: "warning", text: "Message cannot be empty" };
58
+ this.tui.requestRender();
59
+ return;
60
+ }
61
+ if (this.options.getSnapshot().directNeighbors === 0) {
62
+ this.editor.setText(text);
63
+ this.messageStatus = {
64
+ kind: "warning",
65
+ text: "No direct neighbors \u2014 message kept. Wait for connection or Esc to return."
66
+ };
67
+ this.tui.requestRender();
68
+ return;
69
+ }
70
+ try {
71
+ const result = this.options.send(message);
72
+ if (result.relayedTo === 0) {
73
+ this.editor.setText(text);
74
+ this.messageStatus = {
75
+ kind: "warning",
76
+ text: "No direct neighbors accepted it \u2014 message kept for retry."
77
+ };
78
+ } else {
79
+ this.editor.setText("");
80
+ this.followBottom = true;
81
+ this.messageStatus = {
82
+ kind: "success",
83
+ text: `Relayed to ${result.relayedTo} direct neighbor${result.relayedTo === 1 ? "" : "s"}`
84
+ };
85
+ }
86
+ } catch (error) {
87
+ this.editor.setText(text);
88
+ this.messageStatus = { kind: "warning", text: safeDisplayError(error) };
89
+ }
90
+ this.tui.requestRender();
91
+ };
92
+ this.options.setViewOpen(true);
93
+ if (options.signal) {
94
+ const abort = () => this.finish(false, true);
95
+ options.signal.addEventListener("abort", abort, { once: true });
96
+ this.removeAbort = () => options.signal?.removeEventListener("abort", abort);
97
+ if (options.signal.aborted) abort();
98
+ }
99
+ }
100
+ get focused() {
101
+ return this._focused;
102
+ }
103
+ set focused(value) {
104
+ this._focused = value;
105
+ this.editor.focused = value;
106
+ }
107
+ render(width) {
108
+ const safeWidth = Math.max(1, width);
109
+ const snapshot = this.options.getSnapshot();
110
+ const editorLines = this.editor.render(safeWidth);
111
+ const availableRows = Math.max(3, Math.min(16, Math.floor(this.tui.terminal.rows * 0.75)));
112
+ const viewportRows = Math.max(0, availableRows - editorLines.length - 2);
113
+ const content = renderTranscript(snapshot, safeWidth, this.theme);
114
+ this.lastContentRows = content.length;
115
+ this.lastViewportRows = viewportRows;
116
+ if (this.followBottom) this.scrollOffset = this.maxScroll();
117
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.maxScroll()));
118
+ const participantCount = snapshot.participants.length;
119
+ const header = truncateToWidth(
120
+ this.theme.fg(
121
+ "accent",
122
+ this.theme.bold(
123
+ `CHAT INPUT \u2192 ${sanitizeSingleLine(snapshot.room.label)} \xB7 ${participantCount} active \xB7 ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`
124
+ )
125
+ ),
126
+ safeWidth
127
+ );
128
+ const footer = truncateToWidth(
129
+ this.theme.fg(
130
+ this.messageStatus?.kind === "warning" ? "warning" : this.messageStatus?.kind === "success" ? "success" : "dim",
131
+ this.messageStatus?.text ?? "Enter sends \xB7 configured newline key inserts a line \xB7 Esc returns to Pi/LLM"
132
+ ),
133
+ safeWidth
134
+ );
135
+ const lines = [
136
+ header,
137
+ ...content.slice(this.scrollOffset, this.scrollOffset + viewportRows),
138
+ footer,
139
+ ...editorLines
140
+ ];
141
+ return lines.slice(-availableRows).map((line) => truncateToWidth(line, safeWidth));
142
+ }
143
+ handleInput(data) {
144
+ if (this.finished) return;
145
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
146
+ this.close();
147
+ return;
148
+ }
149
+ if (matchesKey(data, Key.pageUp)) {
150
+ this.scrollOffset = Math.max(0, this.scrollOffset - this.lastViewportRows);
151
+ this.followBottom = false;
152
+ this.tui.requestRender();
153
+ return;
154
+ }
155
+ if (matchesKey(data, Key.pageDown)) {
156
+ this.scrollOffset = Math.min(this.maxScroll(), this.scrollOffset + this.lastViewportRows);
157
+ this.followBottom = this.scrollOffset === this.maxScroll();
158
+ this.tui.requestRender();
159
+ return;
160
+ }
161
+ this.editor.handleInput(data);
162
+ this.tui.requestRender();
163
+ }
164
+ invalidate() {
165
+ this.editor.invalidate();
166
+ }
167
+ dispose() {
168
+ this.finish(false, false);
169
+ }
170
+ maxScroll() {
171
+ return Math.max(0, this.lastContentRows - this.lastViewportRows);
172
+ }
173
+ close() {
174
+ this.finish(true, true);
175
+ }
176
+ finish(returnedToPi, closeHost) {
177
+ if (this.finished) return;
178
+ this.finished = true;
179
+ this.removeAbort();
180
+ this.removeAbort = () => {
181
+ };
182
+ this.unsubscribe();
183
+ this.options.setViewOpen(false);
184
+ if (returnedToPi) this.options.onReturnToPi();
185
+ if (closeHost) this.options.onClose();
186
+ }
187
+ };
188
+ function renderTranscript(snapshot, width, theme) {
189
+ if (snapshot.transcript.length === 0) {
190
+ const empty = snapshot.participants.length === 0 ? "No other active participants discovered yet." : "No messages yet. Start the conversation below.";
191
+ return wrapTextWithAnsi(theme.fg("muted", empty), width);
192
+ }
193
+ const lines = [];
194
+ for (const entry of snapshot.transcript) {
195
+ const label = sanitizeSingleLine(entry.label);
196
+ const delivery = entry.author === "local" && entry.delivery === "not-relayed" ? " \xB7 not relayed" : entry.author === "local" && entry.relayedTo !== void 0 ? ` \xB7 relayed to ${entry.relayedTo}` : "";
197
+ lines.push(...wrapTextWithAnsi(theme.fg("accent", `${label}${delivery}`), width));
198
+ for (const rawLine of sanitizeChatText(entry.text).split("\n")) {
199
+ for (const line of hardWrapExact(rawLine, Math.max(1, width - 2))) {
200
+ lines.push(truncateToWidth(` ${line}`, width));
201
+ }
202
+ }
203
+ }
204
+ return lines;
205
+ }
206
+ function hardWrapExact(value, width) {
207
+ if (!value) return [" "];
208
+ const columns = visibleWidth(value);
209
+ const lines = [];
210
+ for (let column = 0; column < columns; column += width) {
211
+ lines.push(sliceByColumn(value, column, width));
212
+ }
213
+ return lines.length > 0 ? lines : [" "];
214
+ }
215
+ function safeDisplayError(error) {
216
+ const message = error instanceof Error ? error.message : String(error);
217
+ return sanitizeSingleLine(message).slice(0, 200);
218
+ }
219
+ export {
220
+ ChatView
221
+ };
222
+ //# sourceMappingURL=chat-view-QEAZMMXC.ts.map