@narumitw/pi-chat 0.1.5 → 0.1.7

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.
Files changed (49) hide show
  1. package/README.md +47 -64
  2. package/dist/chunks/{chat-view-EZ24L3LM.js → chat-view-7OBZGYZM.ts} +2 -2
  3. package/dist/chunks/chat-view-7OBZGYZM.ts.map +7 -0
  4. package/dist/chunks/{chunk-ZR2JESR5.js → chunk-7FD7DDSU.ts} +6 -36
  5. package/dist/chunks/chunk-7FD7DDSU.ts.map +7 -0
  6. package/dist/chunks/{chunk-XYZZR6DW.js → chunk-EOZIFFAD.ts} +6 -23
  7. package/dist/chunks/chunk-EOZIFFAD.ts.map +7 -0
  8. package/dist/chunks/{chunk-UE3UAOJX.js → chunk-LN3NAZRC.ts} +1 -1
  9. package/dist/chunks/{chunk-UE3UAOJX.js.map → chunk-LN3NAZRC.ts.map} +1 -1
  10. package/dist/chunks/{chunk-OQLAKS7O.js → chunk-MHSYNYS3.ts} +4 -7
  11. package/dist/chunks/chunk-MHSYNYS3.ts.map +7 -0
  12. package/dist/chunks/{chunk-UQPD3L6X.js → chunk-WUCSLYAK.ts} +1 -1
  13. package/dist/chunks/chunk-WUCSLYAK.ts.map +7 -0
  14. package/dist/chunks/{directory-network-EWFZFLGK.js → directory-network-6OPGA4EH.ts} +7 -19
  15. package/dist/chunks/directory-network-6OPGA4EH.ts.map +7 -0
  16. package/dist/chunks/{menu-2XYZAYXF.js → menu-S7MZCVYM.ts} +7 -7
  17. package/dist/chunks/menu-S7MZCVYM.ts.map +7 -0
  18. package/dist/chunks/{network-MXCIGGQ2.js → network-Y4Z4JJ5J.ts} +3 -3
  19. package/dist/chunks/network-Y4Z4JJ5J.ts.map +7 -0
  20. package/dist/chunks/{widget-4OBABJDY.js → widget-QT53EBN6.ts} +4 -10
  21. package/dist/chunks/widget-QT53EBN6.ts.map +7 -0
  22. package/dist/index.ts +21 -69
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +54 -58
  25. package/src/chat-session.ts +571 -594
  26. package/src/chat-view.ts +221 -226
  27. package/src/directory-network.ts +347 -365
  28. package/src/external.d.ts +56 -66
  29. package/src/identity.ts +74 -88
  30. package/src/menu.ts +535 -541
  31. package/src/network-contract.ts +5 -5
  32. package/src/network.ts +154 -157
  33. package/src/nickname.ts +6 -6
  34. package/src/pi-chat.ts +700 -777
  35. package/src/protocol.ts +296 -335
  36. package/src/public-room-directory.ts +276 -310
  37. package/src/room.ts +54 -58
  38. package/src/settings.ts +234 -259
  39. package/src/text.ts +57 -57
  40. package/src/widget.ts +56 -72
  41. package/dist/chunks/chat-view-EZ24L3LM.js.map +0 -7
  42. package/dist/chunks/chunk-OQLAKS7O.js.map +0 -7
  43. package/dist/chunks/chunk-UQPD3L6X.js.map +0 -7
  44. package/dist/chunks/chunk-XYZZR6DW.js.map +0 -7
  45. package/dist/chunks/chunk-ZR2JESR5.js.map +0 -7
  46. package/dist/chunks/directory-network-EWFZFLGK.js.map +0 -7
  47. package/dist/chunks/menu-2XYZAYXF.js.map +0 -7
  48. package/dist/chunks/network-MXCIGGQ2.js.map +0 -7
  49. package/dist/chunks/widget-4OBABJDY.js.map +0 -7
package/src/chat-view.ts CHANGED
@@ -1,256 +1,251 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
- type Component,
4
- Editor,
5
- type EditorTheme,
6
- type Focusable,
7
- Key,
8
- matchesKey,
9
- sliceByColumn,
10
- type TUI,
11
- truncateToWidth,
12
- visibleWidth,
13
- wrapTextWithAnsi,
3
+ type Component,
4
+ Editor,
5
+ type EditorTheme,
6
+ type Focusable,
7
+ Key,
8
+ matchesKey,
9
+ sliceByColumn,
10
+ type TUI,
11
+ truncateToWidth,
12
+ visibleWidth,
13
+ wrapTextWithAnsi,
14
14
  } from "@earendil-works/pi-tui";
15
15
  import type { ChatSnapshot } from "./chat-session.js";
16
16
  import { sanitizeChatText, sanitizeSingleLine } from "./text.js";
17
17
 
18
18
  export interface ChatViewOptions {
19
- tui: TUI;
20
- theme: Theme;
21
- getSnapshot(): ChatSnapshot;
22
- send(text: string): { id: string; relayedTo: number };
23
- initialDraft?: string;
24
- onDraftChange?(text: string): void;
25
- setViewOpen(open: boolean): void;
26
- subscribe?(listener: () => void): () => void;
27
- signal?: AbortSignal;
28
- onReturnToPi(): void;
29
- onClose(): void;
19
+ tui: TUI;
20
+ theme: Theme;
21
+ getSnapshot(): ChatSnapshot;
22
+ send(text: string): { id: string; relayedTo: number };
23
+ initialDraft?: string;
24
+ onDraftChange?(text: string): void;
25
+ setViewOpen(open: boolean): void;
26
+ subscribe?(listener: () => void): () => void;
27
+ signal?: AbortSignal;
28
+ onReturnToPi(): void;
29
+ onClose(): void;
30
30
  }
31
31
 
32
32
  export class ChatView implements Component, Focusable {
33
- private readonly editor: Editor;
34
- private readonly tui: TUI;
35
- private readonly theme: Theme;
36
- private readonly options: ChatViewOptions;
37
- private scrollOffset = 0;
38
- private lastContentRows = 0;
39
- private lastViewportRows = 1;
40
- private followBottom = true;
41
- private messageStatus: { kind: "success" | "warning"; text: string } | undefined;
42
- private finished = false;
43
- private _focused = false;
44
- private readonly unsubscribe: () => void;
45
- private removeAbort = () => {};
33
+ private readonly editor: Editor;
34
+ private readonly tui: TUI;
35
+ private readonly theme: Theme;
36
+ private readonly options: ChatViewOptions;
37
+ private scrollOffset = 0;
38
+ private lastContentRows = 0;
39
+ private lastViewportRows = 1;
40
+ private followBottom = true;
41
+ private messageStatus: { kind: "success" | "warning"; text: string } | undefined;
42
+ private finished = false;
43
+ private _focused = false;
44
+ private readonly unsubscribe: () => void;
45
+ private removeAbort = () => {};
46
46
 
47
- constructor(options: ChatViewOptions) {
48
- this.options = options;
49
- this.tui = options.tui;
50
- this.theme = options.theme;
51
- const editorTheme: EditorTheme = {
52
- borderColor: (text) => this.theme.fg("accent", text),
53
- selectList: {
54
- selectedPrefix: (text) => this.theme.fg("accent", text),
55
- selectedText: (text) => this.theme.fg("accent", text),
56
- description: (text) => this.theme.fg("muted", text),
57
- scrollInfo: (text) => this.theme.fg("dim", text),
58
- noMatch: (text) => this.theme.fg("warning", text),
59
- },
60
- };
61
- this.editor = new Editor(this.tui, editorTheme);
62
- if (options.initialDraft) this.editor.setText(options.initialDraft);
63
- this.unsubscribe = options.subscribe?.(() => this.tui.requestRender()) ?? (() => undefined);
64
- this.editor.onChange = () => {
65
- this.messageStatus = undefined;
66
- this.options.onDraftChange?.(this.editor.getExpandedText());
67
- };
68
- this.editor.onSubmit = (text) => {
69
- const message = text.trim();
70
- if (!message) {
71
- this.messageStatus = { kind: "warning", text: "Message cannot be empty" };
72
- this.tui.requestRender();
73
- return;
74
- }
75
- if (this.options.getSnapshot().directNeighbors === 0) {
76
- this.editor.setText(text);
77
- this.messageStatus = {
78
- kind: "warning",
79
- text: "No direct neighbors — message kept. Wait for connection or Esc to return.",
80
- };
81
- this.tui.requestRender();
82
- return;
83
- }
84
- try {
85
- const result = this.options.send(message);
86
- if (result.relayedTo === 0) {
87
- this.editor.setText(text);
88
- this.messageStatus = {
89
- kind: "warning",
90
- text: "No direct neighbors accepted it — message kept for retry.",
91
- };
92
- } else {
93
- this.editor.setText("");
94
- this.followBottom = true;
95
- this.messageStatus = {
96
- kind: "success",
97
- text: `Relayed to ${result.relayedTo} direct neighbor${result.relayedTo === 1 ? "" : "s"}`,
98
- };
99
- }
100
- } catch (error) {
101
- this.editor.setText(text);
102
- this.messageStatus = { kind: "warning", text: safeDisplayError(error) };
103
- }
104
- this.tui.requestRender();
105
- };
106
- this.options.setViewOpen(true);
107
- if (options.signal) {
108
- const abort = () => this.finish(false, true);
109
- options.signal.addEventListener("abort", abort, { once: true });
110
- this.removeAbort = () => options.signal?.removeEventListener("abort", abort);
111
- if (options.signal.aborted) abort();
112
- }
113
- }
47
+ constructor(options: ChatViewOptions) {
48
+ this.options = options;
49
+ this.tui = options.tui;
50
+ this.theme = options.theme;
51
+ const editorTheme: EditorTheme = {
52
+ borderColor: (text) => this.theme.fg("accent", text),
53
+ selectList: {
54
+ selectedPrefix: (text) => this.theme.fg("accent", text),
55
+ selectedText: (text) => this.theme.fg("accent", text),
56
+ description: (text) => this.theme.fg("muted", text),
57
+ scrollInfo: (text) => this.theme.fg("dim", text),
58
+ noMatch: (text) => this.theme.fg("warning", text),
59
+ },
60
+ };
61
+ this.editor = new Editor(this.tui, editorTheme);
62
+ if (options.initialDraft) this.editor.setText(options.initialDraft);
63
+ this.unsubscribe = options.subscribe?.(() => this.tui.requestRender()) ?? (() => undefined);
64
+ this.editor.onChange = () => {
65
+ this.messageStatus = undefined;
66
+ this.options.onDraftChange?.(this.editor.getExpandedText());
67
+ };
68
+ this.editor.onSubmit = (text) => {
69
+ const message = text.trim();
70
+ if (!message) {
71
+ this.messageStatus = { kind: "warning", text: "Message cannot be empty" };
72
+ this.tui.requestRender();
73
+ return;
74
+ }
75
+ if (this.options.getSnapshot().directNeighbors === 0) {
76
+ this.editor.setText(text);
77
+ this.messageStatus = {
78
+ kind: "warning",
79
+ text: "No direct neighbors — message kept. Wait for connection or Esc to return.",
80
+ };
81
+ this.tui.requestRender();
82
+ return;
83
+ }
84
+ try {
85
+ const result = this.options.send(message);
86
+ if (result.relayedTo === 0) {
87
+ this.editor.setText(text);
88
+ this.messageStatus = {
89
+ kind: "warning",
90
+ text: "No direct neighbors accepted it — message kept for retry.",
91
+ };
92
+ } else {
93
+ this.editor.setText("");
94
+ this.followBottom = true;
95
+ this.messageStatus = {
96
+ kind: "success",
97
+ text: `Relayed to ${result.relayedTo} direct neighbor${result.relayedTo === 1 ? "" : "s"}`,
98
+ };
99
+ }
100
+ } catch (error) {
101
+ this.editor.setText(text);
102
+ this.messageStatus = { kind: "warning", text: safeDisplayError(error) };
103
+ }
104
+ this.tui.requestRender();
105
+ };
106
+ this.options.setViewOpen(true);
107
+ if (options.signal) {
108
+ const abort = () => this.finish(false, true);
109
+ options.signal.addEventListener("abort", abort, { once: true });
110
+ this.removeAbort = () => options.signal?.removeEventListener("abort", abort);
111
+ if (options.signal.aborted) abort();
112
+ }
113
+ }
114
114
 
115
- get focused(): boolean {
116
- return this._focused;
117
- }
115
+ get focused(): boolean {
116
+ return this._focused;
117
+ }
118
118
 
119
- set focused(value: boolean) {
120
- this._focused = value;
121
- this.editor.focused = value;
122
- }
119
+ set focused(value: boolean) {
120
+ this._focused = value;
121
+ this.editor.focused = value;
122
+ }
123
123
 
124
- render(width: number): string[] {
125
- const safeWidth = Math.max(1, width);
126
- const snapshot = this.options.getSnapshot();
127
- const editorLines = this.editor.render(safeWidth);
128
- const availableRows = Math.max(3, Math.min(16, Math.floor(this.tui.terminal.rows * 0.75)));
129
- const viewportRows = Math.max(0, availableRows - editorLines.length - 2);
130
- const content = renderTranscript(snapshot, safeWidth, this.theme);
131
- this.lastContentRows = content.length;
132
- this.lastViewportRows = viewportRows;
133
- if (this.followBottom) this.scrollOffset = this.maxScroll();
134
- this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.maxScroll()));
135
- const participantCount = snapshot.participants.length;
136
- const header = truncateToWidth(
137
- this.theme.fg(
138
- "accent",
139
- this.theme.bold(
140
- `CHAT INPUT → ${sanitizeSingleLine(snapshot.room.label)} · ${participantCount} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`,
141
- ),
142
- ),
143
- safeWidth,
144
- );
145
- const footer = truncateToWidth(
146
- this.theme.fg(
147
- this.messageStatus?.kind === "warning"
148
- ? "warning"
149
- : this.messageStatus?.kind === "success"
150
- ? "success"
151
- : "dim",
152
- this.messageStatus?.text ??
153
- "Enter sends · configured newline key inserts a line · Esc returns to Pi/LLM",
154
- ),
155
- safeWidth,
156
- );
157
- const lines = [
158
- header,
159
- ...content.slice(this.scrollOffset, this.scrollOffset + viewportRows),
160
- footer,
161
- ...editorLines,
162
- ];
163
- return lines.slice(-availableRows).map((line) => truncateToWidth(line, safeWidth));
164
- }
124
+ render(width: number): string[] {
125
+ const safeWidth = Math.max(1, width);
126
+ const snapshot = this.options.getSnapshot();
127
+ const editorLines = this.editor.render(safeWidth);
128
+ const availableRows = Math.max(3, Math.min(16, Math.floor(this.tui.terminal.rows * 0.75)));
129
+ const viewportRows = Math.max(0, availableRows - editorLines.length - 2);
130
+ const content = renderTranscript(snapshot, safeWidth, this.theme);
131
+ this.lastContentRows = content.length;
132
+ this.lastViewportRows = viewportRows;
133
+ if (this.followBottom) this.scrollOffset = this.maxScroll();
134
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.maxScroll()));
135
+ const participantCount = snapshot.participants.length;
136
+ const header = truncateToWidth(
137
+ this.theme.fg(
138
+ "accent",
139
+ this.theme.bold(
140
+ `CHAT INPUT → ${sanitizeSingleLine(snapshot.room.label)} · ${participantCount} active · ${snapshot.directNeighbors} direct neighbor${snapshot.directNeighbors === 1 ? "" : "s"}`,
141
+ ),
142
+ ),
143
+ safeWidth,
144
+ );
145
+ const footer = truncateToWidth(
146
+ this.theme.fg(
147
+ this.messageStatus?.kind === "warning" ? "warning" : this.messageStatus?.kind === "success" ? "success" : "dim",
148
+ this.messageStatus?.text ?? "Enter sends · configured newline key inserts a line · Esc returns to Pi/LLM",
149
+ ),
150
+ safeWidth,
151
+ );
152
+ const lines = [
153
+ header,
154
+ ...content.slice(this.scrollOffset, this.scrollOffset + viewportRows),
155
+ footer,
156
+ ...editorLines,
157
+ ];
158
+ return lines.slice(-availableRows).map((line) => truncateToWidth(line, safeWidth));
159
+ }
165
160
 
166
- handleInput(data: string): void {
167
- if (this.finished) return;
168
- if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
169
- this.close();
170
- return;
171
- }
172
- if (matchesKey(data, Key.pageUp)) {
173
- this.scrollOffset = Math.max(0, this.scrollOffset - this.lastViewportRows);
174
- this.followBottom = false;
175
- this.tui.requestRender();
176
- return;
177
- }
178
- if (matchesKey(data, Key.pageDown)) {
179
- this.scrollOffset = Math.min(this.maxScroll(), this.scrollOffset + this.lastViewportRows);
180
- this.followBottom = this.scrollOffset === this.maxScroll();
181
- this.tui.requestRender();
182
- return;
183
- }
184
- this.editor.handleInput(data);
185
- this.tui.requestRender();
186
- }
161
+ handleInput(data: string): void {
162
+ if (this.finished) return;
163
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
164
+ this.close();
165
+ return;
166
+ }
167
+ if (matchesKey(data, Key.pageUp)) {
168
+ this.scrollOffset = Math.max(0, this.scrollOffset - this.lastViewportRows);
169
+ this.followBottom = false;
170
+ this.tui.requestRender();
171
+ return;
172
+ }
173
+ if (matchesKey(data, Key.pageDown)) {
174
+ this.scrollOffset = Math.min(this.maxScroll(), this.scrollOffset + this.lastViewportRows);
175
+ this.followBottom = this.scrollOffset === this.maxScroll();
176
+ this.tui.requestRender();
177
+ return;
178
+ }
179
+ this.editor.handleInput(data);
180
+ this.tui.requestRender();
181
+ }
187
182
 
188
- invalidate(): void {
189
- this.editor.invalidate();
190
- }
183
+ invalidate(): void {
184
+ this.editor.invalidate();
185
+ }
191
186
 
192
- dispose(): void {
193
- this.finish(false, false);
194
- }
187
+ dispose(): void {
188
+ this.finish(false, false);
189
+ }
195
190
 
196
- private maxScroll(): number {
197
- return Math.max(0, this.lastContentRows - this.lastViewportRows);
198
- }
191
+ private maxScroll(): number {
192
+ return Math.max(0, this.lastContentRows - this.lastViewportRows);
193
+ }
199
194
 
200
- private close(): void {
201
- this.finish(true, true);
202
- }
195
+ private close(): void {
196
+ this.finish(true, true);
197
+ }
203
198
 
204
- private finish(returnedToPi: boolean, closeHost: boolean): void {
205
- if (this.finished) return;
206
- this.finished = true;
207
- this.removeAbort();
208
- this.removeAbort = () => {};
209
- this.unsubscribe();
210
- this.options.setViewOpen(false);
211
- if (returnedToPi) this.options.onReturnToPi();
212
- if (closeHost) this.options.onClose();
213
- }
199
+ private finish(returnedToPi: boolean, closeHost: boolean): void {
200
+ if (this.finished) return;
201
+ this.finished = true;
202
+ this.removeAbort();
203
+ this.removeAbort = () => {};
204
+ this.unsubscribe();
205
+ this.options.setViewOpen(false);
206
+ if (returnedToPi) this.options.onReturnToPi();
207
+ if (closeHost) this.options.onClose();
208
+ }
214
209
  }
215
210
 
216
211
  function renderTranscript(snapshot: ChatSnapshot, width: number, theme: Theme): string[] {
217
- if (snapshot.transcript.length === 0) {
218
- const empty =
219
- snapshot.participants.length === 0
220
- ? "No other active participants discovered yet."
221
- : "No messages yet. Start the conversation below.";
222
- return wrapTextWithAnsi(theme.fg("muted", empty), width);
223
- }
224
- const lines: string[] = [];
225
- for (const entry of snapshot.transcript) {
226
- const label = sanitizeSingleLine(entry.label);
227
- const delivery =
228
- entry.author === "local" && entry.delivery === "not-relayed"
229
- ? " · not relayed"
230
- : entry.author === "local" && entry.relayedTo !== undefined
231
- ? ` · relayed to ${entry.relayedTo}`
232
- : "";
233
- lines.push(...wrapTextWithAnsi(theme.fg("accent", `${label}${delivery}`), width));
234
- for (const rawLine of sanitizeChatText(entry.text).split("\n")) {
235
- for (const line of hardWrapExact(rawLine, Math.max(1, width - 2))) {
236
- lines.push(truncateToWidth(` ${line}`, width));
237
- }
238
- }
239
- }
240
- return lines;
212
+ if (snapshot.transcript.length === 0) {
213
+ const empty =
214
+ snapshot.participants.length === 0
215
+ ? "No other active participants discovered yet."
216
+ : "No messages yet. Start the conversation below.";
217
+ return wrapTextWithAnsi(theme.fg("muted", empty), width);
218
+ }
219
+ const lines: string[] = [];
220
+ for (const entry of snapshot.transcript) {
221
+ const label = sanitizeSingleLine(entry.label);
222
+ const delivery =
223
+ entry.author === "local" && entry.delivery === "not-relayed"
224
+ ? " · not relayed"
225
+ : entry.author === "local" && entry.relayedTo !== undefined
226
+ ? ` · relayed to ${entry.relayedTo}`
227
+ : "";
228
+ lines.push(...wrapTextWithAnsi(theme.fg("accent", `${label}${delivery}`), width));
229
+ for (const rawLine of sanitizeChatText(entry.text).split("\n")) {
230
+ for (const line of hardWrapExact(rawLine, Math.max(1, width - 2))) {
231
+ lines.push(truncateToWidth(` ${line}`, width));
232
+ }
233
+ }
234
+ }
235
+ return lines;
241
236
  }
242
237
 
243
238
  function hardWrapExact(value: string, width: number): string[] {
244
- if (!value) return [" "];
245
- const columns = visibleWidth(value);
246
- const lines: string[] = [];
247
- for (let column = 0; column < columns; column += width) {
248
- lines.push(sliceByColumn(value, column, width));
249
- }
250
- return lines.length > 0 ? lines : [" "];
239
+ if (!value) return [" "];
240
+ const columns = visibleWidth(value);
241
+ const lines: string[] = [];
242
+ for (let column = 0; column < columns; column += width) {
243
+ lines.push(sliceByColumn(value, column, width));
244
+ }
245
+ return lines.length > 0 ? lines : [" "];
251
246
  }
252
247
 
253
248
  function safeDisplayError(error: unknown): string {
254
- const message = error instanceof Error ? error.message : String(error);
255
- return sanitizeSingleLine(message).slice(0, 200);
249
+ const message = error instanceof Error ? error.message : String(error);
250
+ return sanitizeSingleLine(message).slice(0, 200);
256
251
  }