wave-code 1.0.0 → 1.0.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.
Files changed (72) hide show
  1. package/dist/cli.js +20 -1
  2. package/dist/components/App.js +7 -0
  3. package/dist/components/BtwDisplay.js +13 -3
  4. package/dist/components/ChatInterface.js +25 -8
  5. package/dist/components/InputBox.d.ts +1 -3
  6. package/dist/components/InputBox.js +12 -9
  7. package/dist/components/LoadingIndicator.d.ts +1 -2
  8. package/dist/components/LoadingIndicator.js +2 -2
  9. package/dist/components/LoginCommand.js +4 -2
  10. package/dist/components/Markdown.js +13 -16
  11. package/dist/components/Notifications.d.ts +7 -0
  12. package/dist/components/Notifications.js +9 -0
  13. package/dist/components/StatusLine.d.ts +0 -4
  14. package/dist/components/StatusLine.js +6 -10
  15. package/dist/components/TaskList.js +2 -1
  16. package/dist/components/ToolDisplay.d.ts +1 -0
  17. package/dist/components/ToolDisplay.js +17 -9
  18. package/dist/constants/commands.js +0 -6
  19. package/dist/contexts/useChat.d.ts +4 -6
  20. package/dist/contexts/useChat.js +253 -110
  21. package/dist/daemon-cli.d.ts +10 -0
  22. package/dist/daemon-cli.js +15 -0
  23. package/dist/hooks/useInputManager.js +99 -22
  24. package/dist/index.js +10 -0
  25. package/dist/managers/inputHandlers.js +50 -22
  26. package/dist/managers/inputReducer.d.ts +12 -2
  27. package/dist/managers/inputReducer.js +57 -9
  28. package/dist/stdio/agentBridge.d.ts +23 -0
  29. package/dist/stdio/agentBridge.js +134 -16
  30. package/dist/stdio/daemonServer.d.ts +67 -0
  31. package/dist/stdio/daemonServer.js +191 -0
  32. package/dist/stdio/index.d.ts +2 -0
  33. package/dist/stdio/index.js +2 -0
  34. package/dist/stdio/jsonRpcConnection.d.ts +30 -0
  35. package/dist/stdio/jsonRpcConnection.js +127 -0
  36. package/dist/stdio/protocol.d.ts +2 -2
  37. package/dist/stdio/stdioServer.d.ts +2 -7
  38. package/dist/stdio/stdioServer.js +9 -100
  39. package/dist/utils/bracketedPaste.d.ts +39 -0
  40. package/dist/utils/bracketedPaste.js +122 -0
  41. package/dist/utils/markdownTable.d.ts +34 -0
  42. package/dist/utils/markdownTable.js +302 -0
  43. package/dist/utils/throttle.d.ts +3 -3
  44. package/package.json +4 -2
  45. package/src/cli.tsx +20 -1
  46. package/src/components/App.tsx +5 -0
  47. package/src/components/BtwDisplay.tsx +36 -12
  48. package/src/components/ChatInterface.tsx +30 -15
  49. package/src/components/InputBox.tsx +25 -24
  50. package/src/components/LoadingIndicator.tsx +1 -4
  51. package/src/components/LoginCommand.tsx +4 -2
  52. package/src/components/Markdown.tsx +15 -18
  53. package/src/components/Notifications.tsx +31 -0
  54. package/src/components/StatusLine.tsx +17 -44
  55. package/src/components/TaskList.tsx +2 -1
  56. package/src/components/ToolDisplay.tsx +17 -6
  57. package/src/constants/commands.ts +0 -6
  58. package/src/contexts/useChat.tsx +326 -140
  59. package/src/daemon-cli.ts +17 -0
  60. package/src/hooks/useInputManager.ts +108 -22
  61. package/src/index.ts +12 -0
  62. package/src/managers/inputHandlers.ts +49 -22
  63. package/src/managers/inputReducer.ts +66 -11
  64. package/src/stdio/agentBridge.ts +196 -17
  65. package/src/stdio/daemonServer.ts +212 -0
  66. package/src/stdio/index.ts +2 -0
  67. package/src/stdio/jsonRpcConnection.ts +160 -0
  68. package/src/stdio/protocol.ts +5 -2
  69. package/src/stdio/stdioServer.ts +14 -120
  70. package/src/utils/bracketedPaste.ts +170 -0
  71. package/src/utils/markdownTable.ts +359 -0
  72. package/src/utils/throttle.ts +8 -8
@@ -0,0 +1,359 @@
1
+ import type { Token, Tokens } from "marked";
2
+ import stringWidth from "string-width";
3
+ import wrapAnsi from "wrap-ansi";
4
+ import { stripAnsiColors } from "wave-agent-sdk";
5
+
6
+ /**
7
+ * Accounts for parent indentation (e.g. message prefix) and terminal
8
+ * resize races. Without enough margin the table overflows its layout box
9
+ * and Ink's clip truncates differently on alternating frames.
10
+ */
11
+ const SAFETY_MARGIN = 4;
12
+
13
+ /** Minimum column width to prevent degenerate layouts */
14
+ const MIN_COLUMN_WIDTH = 3;
15
+
16
+ /**
17
+ * Maximum number of lines per row before switching to vertical format.
18
+ * When wrapping would make rows taller than this, vertical (key-value)
19
+ * format provides better readability.
20
+ */
21
+ const MAX_ROW_LINES = 4;
22
+
23
+ /** ANSI escape codes for text formatting */
24
+ const ANSI_BOLD_START = "\x1b[1m";
25
+ const ANSI_BOLD_END = "\x1b[22m";
26
+
27
+ export type CellAlign = "left" | "center" | "right" | null;
28
+
29
+ /**
30
+ * Wrap text to fit within a given width, returning array of lines.
31
+ * ANSI-aware: preserves styling across line breaks.
32
+ *
33
+ * @param hard - If true, break words that exceed width (needed when columns
34
+ * are narrower than the longest word). Default false.
35
+ */
36
+ export function wrapText(
37
+ text: string,
38
+ width: number,
39
+ options?: { hard?: boolean },
40
+ ): string[] {
41
+ if (width <= 0) return [text];
42
+ // Strip trailing whitespace/newlines before wrapping, otherwise extra
43
+ // blank lines would appear in table cells.
44
+ const trimmedText = text.trimEnd();
45
+ const wrapped = wrapAnsi(trimmedText, width, {
46
+ hard: options?.hard ?? false,
47
+ trim: false,
48
+ wordWrap: true,
49
+ });
50
+ // Filter out empty lines that result from trailing newlines or
51
+ // multiple consecutive newlines in the source content.
52
+ const lines = wrapped.split("\n").filter((line) => line.length > 0);
53
+ // Ensure we always return at least one line (empty string for empty cells)
54
+ return lines.length > 0 ? lines : [""];
55
+ }
56
+
57
+ /**
58
+ * Pad `content` to `targetWidth` according to alignment. `displayWidth` is the
59
+ * visible width of `content` (caller computes this, e.g. via stringWidth on
60
+ * ANSI-stripped text, so ANSI codes in `content` don't affect padding).
61
+ */
62
+ export function padAligned(
63
+ content: string,
64
+ displayWidth: number,
65
+ targetWidth: number,
66
+ align: CellAlign | undefined,
67
+ ): string {
68
+ const padding = Math.max(0, targetWidth - displayWidth);
69
+ if (align === "center") {
70
+ const leftPad = Math.floor(padding / 2);
71
+ return " ".repeat(leftPad) + content + " ".repeat(padding - leftPad);
72
+ }
73
+ if (align === "right") {
74
+ return " ".repeat(padding) + content;
75
+ }
76
+ return content + " ".repeat(padding);
77
+ }
78
+
79
+ /**
80
+ * Render a markdown table to a box-drawing ANSI string for the terminal.
81
+ * Handles terminal width by:
82
+ * 1. Calculating minimum column widths based on longest word
83
+ * 2. Distributing available space proportionally
84
+ * 3. Wrapping text within cells (no truncation)
85
+ * 4. Falling back to a vertical key-value format when rows would be too
86
+ * tall or the table still overflows the terminal width
87
+ *
88
+ * @param token - marked table token
89
+ * @param columns - terminal width
90
+ * @param formatInline - formats inline tokens to an ANSI string (the caller
91
+ * binds its marked parser so this module stays
92
+ * parser-agnostic and directly testable)
93
+ */
94
+ export function renderMarkdownTable(
95
+ token: Tokens.Table,
96
+ columns: number,
97
+ formatInline: (tokens: Token[]) => string,
98
+ ): string {
99
+ // Format cell content to ANSI string
100
+ function formatCell(tokens: Token[] | undefined): string {
101
+ return tokens && tokens.length > 0 ? formatInline(tokens) : "";
102
+ }
103
+
104
+ // Get plain text (stripped of ANSI codes)
105
+ function getPlainText(tokens: Token[] | undefined): string {
106
+ return stripAnsiColors(formatCell(tokens));
107
+ }
108
+
109
+ // Get the longest word width in a cell (minimum width to avoid breaking words)
110
+ function getMinWidth(tokens: Token[] | undefined): number {
111
+ const text = getPlainText(tokens);
112
+ const words = text.split(/\s+/).filter((w) => w.length > 0);
113
+ if (words.length === 0) return MIN_COLUMN_WIDTH;
114
+ return Math.max(...words.map((w) => stringWidth(w)), MIN_COLUMN_WIDTH);
115
+ }
116
+
117
+ // Get ideal width (full content without wrapping)
118
+ function getIdealWidth(tokens: Token[] | undefined): number {
119
+ return Math.max(stringWidth(getPlainText(tokens)), MIN_COLUMN_WIDTH);
120
+ }
121
+
122
+ // Step 1: Get minimum (longest word) and ideal (full content) widths
123
+ const minWidths = token.header.map((header, colIndex) => {
124
+ let maxMinWidth = getMinWidth(header.tokens);
125
+ for (const row of token.rows) {
126
+ maxMinWidth = Math.max(maxMinWidth, getMinWidth(row[colIndex]?.tokens));
127
+ }
128
+ return maxMinWidth;
129
+ });
130
+ const idealWidths = token.header.map((header, colIndex) => {
131
+ let maxIdeal = getIdealWidth(header.tokens);
132
+ for (const row of token.rows) {
133
+ maxIdeal = Math.max(maxIdeal, getIdealWidth(row[colIndex]?.tokens));
134
+ }
135
+ return maxIdeal;
136
+ });
137
+
138
+ // Step 2: Calculate available space
139
+ // Border overhead: │ content │ content │ = 1 + (width + 3) per column
140
+ const numCols = token.header.length;
141
+ const borderOverhead = 1 + numCols * 3; // │ + (2 padding + 1 border) per col
142
+ // Account for SAFETY_MARGIN to avoid triggering the fallback safety check
143
+ const availableWidth = Math.max(
144
+ columns - borderOverhead - SAFETY_MARGIN,
145
+ numCols * MIN_COLUMN_WIDTH,
146
+ );
147
+
148
+ // Step 3: Calculate column widths that fit available space
149
+ const totalMin = minWidths.reduce((sum, w) => sum + w, 0);
150
+ const totalIdeal = idealWidths.reduce((sum, w) => sum + w, 0);
151
+
152
+ // Track whether columns are narrower than longest words (needs hard wrap)
153
+ let needsHardWrap = false;
154
+ let columnWidths: number[];
155
+ if (totalIdeal <= availableWidth) {
156
+ // Everything fits - use ideal widths
157
+ columnWidths = idealWidths;
158
+ } else if (totalMin <= availableWidth) {
159
+ // Need to shrink - give each column its min, distribute remaining space
160
+ const extraSpace = availableWidth - totalMin;
161
+ const overflows = idealWidths.map((ideal, i) => ideal - minWidths[i]!);
162
+ const totalOverflow = overflows.reduce((sum, o) => sum + o, 0);
163
+ columnWidths = minWidths.map((min, i) => {
164
+ if (totalOverflow === 0) return min;
165
+ const extra = Math.floor((overflows[i]! / totalOverflow) * extraSpace);
166
+ return min + extra;
167
+ });
168
+ } else {
169
+ // Table wider than terminal at minimum widths
170
+ // Shrink columns proportionally to fit allowing word breaks
171
+ needsHardWrap = true;
172
+ const scaleFactor = availableWidth / totalMin;
173
+ columnWidths = minWidths.map((w) =>
174
+ Math.max(Math.floor(w * scaleFactor), MIN_COLUMN_WIDTH),
175
+ );
176
+ }
177
+
178
+ // Step 4: Calculate max row lines to determine if vertical format is needed
179
+ function calculateMaxRowLines(): number {
180
+ let maxLines = 1;
181
+ // Check header
182
+ for (let i = 0; i < token.header.length; i++) {
183
+ const content = formatCell(token.header[i]!.tokens);
184
+ const wrapped = wrapText(content, columnWidths[i]!, {
185
+ hard: needsHardWrap,
186
+ });
187
+ maxLines = Math.max(maxLines, wrapped.length);
188
+ }
189
+ // Check rows
190
+ for (const row of token.rows) {
191
+ for (let i = 0; i < row.length; i++) {
192
+ const content = formatCell(row[i]?.tokens);
193
+ const wrapped = wrapText(content, columnWidths[i]!, {
194
+ hard: needsHardWrap,
195
+ });
196
+ maxLines = Math.max(maxLines, wrapped.length);
197
+ }
198
+ }
199
+ return maxLines;
200
+ }
201
+
202
+ // Use vertical format if wrapping would make rows too tall
203
+ const maxRowLines = calculateMaxRowLines();
204
+ const useVerticalFormat = maxRowLines > MAX_ROW_LINES;
205
+
206
+ // Render a single row with potential multi-line cells
207
+ // Returns an array of strings, one per line of the row
208
+ function renderRowLines(
209
+ cells: Array<{ tokens?: Token[] }>,
210
+ isHeader: boolean,
211
+ ): string[] {
212
+ // Get wrapped lines for each cell (preserving ANSI formatting)
213
+ const cellLines = cells.map((cell, colIndex) => {
214
+ const formattedText = formatCell(cell.tokens);
215
+ const width = columnWidths[colIndex]!;
216
+ return wrapText(formattedText, width, { hard: needsHardWrap });
217
+ });
218
+
219
+ // Find max number of lines in this row
220
+ const maxLines = Math.max(...cellLines.map((lines) => lines.length), 1);
221
+
222
+ // Calculate vertical offset for each cell (to center vertically)
223
+ const verticalOffsets = cellLines.map((lines) =>
224
+ Math.floor((maxLines - lines.length) / 2),
225
+ );
226
+
227
+ // Build each line of the row as a single string
228
+ const result: string[] = [];
229
+ for (let lineIdx = 0; lineIdx < maxLines; lineIdx++) {
230
+ let line = "│";
231
+ for (let colIndex = 0; colIndex < cells.length; colIndex++) {
232
+ const lines = cellLines[colIndex]!;
233
+ const offset = verticalOffsets[colIndex]!;
234
+ const contentLineIdx = lineIdx - offset;
235
+ const lineText =
236
+ contentLineIdx >= 0 && contentLineIdx < lines.length
237
+ ? lines[contentLineIdx]!
238
+ : "";
239
+ const width = columnWidths[colIndex]!;
240
+ // Headers always centered; data uses table alignment
241
+ const align = isHeader
242
+ ? "center"
243
+ : ((token.align?.[colIndex] as CellAlign | undefined) ?? "left");
244
+ line +=
245
+ " " +
246
+ padAligned(lineText, stringWidth(lineText), width, align) +
247
+ " │";
248
+ }
249
+ result.push(line);
250
+ }
251
+ return result;
252
+ }
253
+
254
+ // Render horizontal border as a single string
255
+ function renderBorderLine(type: "top" | "middle" | "bottom"): string {
256
+ const [left, mid, cross, right] = {
257
+ top: ["┌", "─", "┬", "┐"],
258
+ middle: ["├", "─", "┼", "┤"],
259
+ bottom: ["└", "─", "┴", "┘"],
260
+ }[type] as [string, string, string, string];
261
+ let line = left;
262
+ columnWidths.forEach((width, colIndex) => {
263
+ line += mid.repeat(width + 2);
264
+ line += colIndex < columnWidths.length - 1 ? cross : right;
265
+ });
266
+ return line;
267
+ }
268
+
269
+ // Render vertical format (key-value pairs) for extra-narrow terminals
270
+ function renderVerticalFormat(): string {
271
+ const lines: string[] = [];
272
+ const headers = token.header.map((h) => getPlainText(h.tokens));
273
+ const separatorWidth = Math.min(columns - 1, 40);
274
+ const separator = "─".repeat(separatorWidth);
275
+ // Small indent for wrapped lines (just 2 spaces)
276
+ const wrapIndent = " ";
277
+ token.rows.forEach((row, rowIndex) => {
278
+ if (rowIndex > 0) {
279
+ lines.push(separator);
280
+ }
281
+ row.forEach((cell, colIndex) => {
282
+ const label = headers[colIndex] || `Column ${colIndex + 1}`;
283
+ // Clean value: trim, remove extra internal whitespace/newlines
284
+ const rawValue = formatCell(cell.tokens).trimEnd();
285
+ const value = rawValue.replace(/\n+/g, " ").replace(/\s+/g, " ").trim();
286
+
287
+ // Wrap value to fit terminal, accounting for label on first line
288
+ const firstLineWidth = columns - stringWidth(label) - 3;
289
+ const subsequentLineWidth = columns - wrapIndent.length - 1;
290
+
291
+ // Two-pass wrap: first line is narrower (label takes space),
292
+ // continuation lines get the full width minus indent.
293
+ const firstPassLines = wrapText(value, Math.max(firstLineWidth, 10));
294
+ const firstLine = firstPassLines[0] || "";
295
+ let wrappedValue: string[];
296
+ if (
297
+ firstPassLines.length <= 1 ||
298
+ subsequentLineWidth <= firstLineWidth
299
+ ) {
300
+ wrappedValue = firstPassLines;
301
+ } else {
302
+ // Re-join remaining text and re-wrap to the wider continuation width
303
+ const remainingText = firstPassLines
304
+ .slice(1)
305
+ .map((l) => l.trim())
306
+ .join(" ");
307
+ const rewrapped = wrapText(remainingText, subsequentLineWidth);
308
+ wrappedValue = [firstLine, ...rewrapped];
309
+ }
310
+
311
+ // First line: bold label + value
312
+ lines.push(
313
+ `${ANSI_BOLD_START}${label}:${ANSI_BOLD_END} ${wrappedValue[0] || ""}`,
314
+ );
315
+
316
+ // Subsequent lines with small indent (skip empty lines)
317
+ for (let i = 1; i < wrappedValue.length; i++) {
318
+ const line = wrappedValue[i]!;
319
+ if (!line.trim()) continue;
320
+ lines.push(`${wrapIndent}${line}`);
321
+ }
322
+ });
323
+ });
324
+ return lines.join("\n");
325
+ }
326
+
327
+ // Choose format based on available width
328
+ if (useVerticalFormat) {
329
+ return renderVerticalFormat();
330
+ }
331
+
332
+ // Build the complete horizontal table as an array of strings
333
+ const tableLines: string[] = [];
334
+ tableLines.push(renderBorderLine("top"));
335
+ tableLines.push(...renderRowLines(token.header, true));
336
+ tableLines.push(renderBorderLine("middle"));
337
+ token.rows.forEach((row, rowIndex) => {
338
+ tableLines.push(...renderRowLines(row, false));
339
+ if (rowIndex < token.rows.length - 1) {
340
+ tableLines.push(renderBorderLine("middle"));
341
+ }
342
+ });
343
+ tableLines.push(renderBorderLine("bottom"));
344
+
345
+ // Safety check: verify no line exceeds terminal width.
346
+ // This catches edge cases during terminal resize where calculations
347
+ // were based on a different width than the current render target.
348
+ const maxLineWidth = Math.max(
349
+ ...tableLines.map((line) => stringWidth(stripAnsiColors(line))),
350
+ );
351
+
352
+ // If we're within SAFETY_MARGIN characters of the edge, use vertical format
353
+ // to account for terminal resize race conditions.
354
+ if (maxLineWidth > columns - SAFETY_MARGIN) {
355
+ return renderVerticalFormat();
356
+ }
357
+
358
+ return tableLines.join("\n");
359
+ }
@@ -3,8 +3,8 @@ export interface ThrottleOptions {
3
3
  trailing?: boolean;
4
4
  }
5
5
 
6
- export interface ThrottledFunction<T extends (...args: unknown[]) => void> {
7
- (...args: Parameters<T>): void;
6
+ export interface ThrottledFunction<A extends unknown[]> {
7
+ (...args: A): void;
8
8
  cancel: () => void;
9
9
  flush: () => void;
10
10
  }
@@ -13,13 +13,13 @@ export interface ThrottledFunction<T extends (...args: unknown[]) => void> {
13
13
  * Creates a throttled function that only invokes `func` at most once per
14
14
  * every `wait` milliseconds.
15
15
  */
16
- export function throttle<T extends (...args: unknown[]) => void>(
17
- func: T,
16
+ export function throttle<A extends unknown[]>(
17
+ func: (...args: A) => void,
18
18
  wait: number,
19
19
  options: ThrottleOptions = { leading: true, trailing: true },
20
- ): ThrottledFunction<T> {
20
+ ): ThrottledFunction<A> {
21
21
  let timeoutId: NodeJS.Timeout | null = null;
22
- let lastArgs: Parameters<T> | null = null;
22
+ let lastArgs: A | null = null;
23
23
  let lastCallTime = 0;
24
24
 
25
25
  const invokeFunc = () => {
@@ -30,7 +30,7 @@ export function throttle<T extends (...args: unknown[]) => void>(
30
30
  }
31
31
  };
32
32
 
33
- const throttled = (...args: Parameters<T>) => {
33
+ const throttled = (...args: A) => {
34
34
  const now = Date.now();
35
35
  const remaining = wait - (now - lastCallTime);
36
36
 
@@ -71,5 +71,5 @@ export function throttle<T extends (...args: unknown[]) => void>(
71
71
  invokeFunc();
72
72
  };
73
73
 
74
- return throttled as ThrottledFunction<T>;
74
+ return throttled as ThrottledFunction<A>;
75
75
  }