@ai-sdk/tui 0.0.0 → 1.0.0-beta.12

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/dist/index.js ADDED
@@ -0,0 +1,1924 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+
10
+ // src/tui/terminal-text.ts
11
+ var ansiEscape = String.fromCharCode(27);
12
+ var ansiPattern = new RegExp(`${ansiEscape}\\[[0-?]*[ -/]*[@-~]`, "g");
13
+ var ansiPrefixPattern = new RegExp(
14
+ `^${ansiEscape}\\[[0-?]*[ -/]*[@-~]`
15
+ );
16
+ function visibleLength(input) {
17
+ let width = 0;
18
+ let index = 0;
19
+ while (index < input.length) {
20
+ const ansiMatch = input.slice(index).match(ansiPrefixPattern);
21
+ if (ansiMatch) {
22
+ index += ansiMatch[0].length;
23
+ continue;
24
+ }
25
+ const codePoint = input.codePointAt(index);
26
+ if (codePoint == null) {
27
+ break;
28
+ }
29
+ const character = String.fromCodePoint(codePoint);
30
+ width += codePointWidth(codePoint);
31
+ index += character.length;
32
+ }
33
+ return width;
34
+ }
35
+ function sliceVisible(input, width) {
36
+ if (width <= 0) {
37
+ return "";
38
+ }
39
+ let output = "";
40
+ let visible = 0;
41
+ let index = 0;
42
+ while (index < input.length && visible < width) {
43
+ const ansiMatch = input.slice(index).match(ansiPrefixPattern);
44
+ if (ansiMatch) {
45
+ output += ansiMatch[0];
46
+ index += ansiMatch[0].length;
47
+ continue;
48
+ }
49
+ const codePoint = input.codePointAt(index);
50
+ if (codePoint == null) {
51
+ break;
52
+ }
53
+ const character = String.fromCodePoint(codePoint);
54
+ const characterWidth = codePointWidth(codePoint);
55
+ if (characterWidth > 0 && visible + characterWidth > width) {
56
+ break;
57
+ }
58
+ output += character;
59
+ index += character.length;
60
+ visible += characterWidth;
61
+ }
62
+ while (index < input.length) {
63
+ const ansiMatch = input.slice(index).match(ansiPrefixPattern);
64
+ if (!ansiMatch) {
65
+ break;
66
+ }
67
+ output += ansiMatch[0];
68
+ index += ansiMatch[0].length;
69
+ }
70
+ return output;
71
+ }
72
+ function codePointWidth(codePoint) {
73
+ if (codePoint === 9) {
74
+ return 4;
75
+ }
76
+ if (codePoint < 32 || codePoint >= 127 && codePoint < 160) {
77
+ return 0;
78
+ }
79
+ if (isZeroWidthCodePoint(codePoint)) {
80
+ return 0;
81
+ }
82
+ return isWideCodePoint(codePoint) ? 2 : 1;
83
+ }
84
+ function isZeroWidthCodePoint(codePoint) {
85
+ return codePoint >= 768 && codePoint <= 879 || codePoint >= 1155 && codePoint <= 1161 || codePoint >= 1425 && codePoint <= 1469 || codePoint === 1471 || codePoint >= 1473 && codePoint <= 1474 || codePoint >= 1476 && codePoint <= 1477 || codePoint === 1479 || codePoint >= 1552 && codePoint <= 1562 || codePoint >= 1611 && codePoint <= 1631 || codePoint === 1648 || codePoint >= 1750 && codePoint <= 1756 || codePoint >= 1759 && codePoint <= 1764 || codePoint >= 1767 && codePoint <= 1768 || codePoint >= 1770 && codePoint <= 1773 || codePoint === 1809 || codePoint >= 1840 && codePoint <= 1866 || codePoint >= 1958 && codePoint <= 1968 || codePoint >= 2027 && codePoint <= 2035 || codePoint >= 2070 && codePoint <= 2073 || codePoint >= 2075 && codePoint <= 2083 || codePoint >= 2085 && codePoint <= 2087 || codePoint >= 2089 && codePoint <= 2093 || codePoint >= 2137 && codePoint <= 2139 || codePoint >= 2259 && codePoint <= 2306 || codePoint === 2362 || codePoint === 2364 || codePoint >= 2369 && codePoint <= 2376 || codePoint === 2381 || codePoint >= 2385 && codePoint <= 2391 || codePoint === 8205 || codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999;
86
+ }
87
+ function isWideCodePoint(codePoint) {
88
+ return codePoint >= 4352 && (codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || codePoint >= 11904 && codePoint <= 42191 && codePoint !== 12351 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65049 || codePoint >= 65072 && codePoint <= 65135 || codePoint >= 65280 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 127744 && codePoint <= 128591 || codePoint >= 129280 && codePoint <= 129535 || codePoint >= 131072 && codePoint <= 262141);
89
+ }
90
+
91
+ // src/tui/markdown.ts
92
+ var ansi = {
93
+ bold: "\x1B[1m",
94
+ boldOff: "\x1B[22m",
95
+ italic: "\x1B[3m",
96
+ italicOff: "\x1B[23m"
97
+ };
98
+ var tableSeparator = "\u2500";
99
+ function renderMarkdown(input) {
100
+ var _a;
101
+ const lines = input.split("\n");
102
+ const output = [];
103
+ for (let index = 0; index < lines.length; index += 1) {
104
+ const table = parseTable(lines, index);
105
+ if (table != null) {
106
+ output.push(...renderTable(table));
107
+ index = table.endIndex - 1;
108
+ continue;
109
+ }
110
+ output.push(renderMarkdownLine((_a = lines[index]) != null ? _a : ""));
111
+ }
112
+ return output.join("\n");
113
+ }
114
+ function renderMarkdownLine(line) {
115
+ if (line.startsWith("### ")) {
116
+ return renderInlineMarkdown(`\u25B6 ${line.slice(4)}`);
117
+ }
118
+ if (line.startsWith("## ")) {
119
+ return renderInlineMarkdown(`\u25A0 ${line.slice(3)}`);
120
+ }
121
+ if (line.startsWith("# ")) {
122
+ return renderInlineMarkdown(`\u2588 ${line.slice(2)}`);
123
+ }
124
+ const unorderedListItem = line.match(/^(\s*)[-+*]\s+(.*)$/);
125
+ if (unorderedListItem) {
126
+ const [, indentation, text = ""] = unorderedListItem;
127
+ return renderInlineMarkdown(
128
+ `${indentation}\u2022${text.length > 0 ? ` ${text}` : ""}`
129
+ );
130
+ }
131
+ if (/^\d+\. /.test(line)) {
132
+ return renderInlineMarkdown(line.replace(/^(\d+)\. /, "$1. "));
133
+ }
134
+ if (line.startsWith("> ")) {
135
+ return renderInlineMarkdown(`\u2502 ${line.slice(2)}`);
136
+ }
137
+ return renderInlineMarkdown(line);
138
+ }
139
+ function renderInlineMarkdown(input) {
140
+ return input.replace(/`([^`]+)`/g, "$1").replace(/\*\*([^*\n]+)\*\*/g, `${ansi.bold}$1${ansi.boldOff}`).replace(/__([^_\n]+)__/g, `${ansi.bold}$1${ansi.boldOff}`).replace(/\*([^*\n]+)\*/g, `${ansi.italic}$1${ansi.italicOff}`).replace(/_([^_\n]+)_/g, `${ansi.italic}$1${ansi.italicOff}`);
141
+ }
142
+ function parseTable(lines, startIndex) {
143
+ var _a, _b, _c;
144
+ const header = parseTableCells((_a = lines[startIndex]) != null ? _a : "");
145
+ if (header == null || header.length < 2) {
146
+ return void 0;
147
+ }
148
+ const separatorCells = parseTableCells((_b = lines[startIndex + 1]) != null ? _b : "");
149
+ if (separatorCells == null || separatorCells.length !== header.length) {
150
+ return void 0;
151
+ }
152
+ const alignments = parseTableAlignments(separatorCells);
153
+ if (alignments == null) {
154
+ return void 0;
155
+ }
156
+ const rows = [];
157
+ let endIndex = startIndex + 2;
158
+ while (endIndex < lines.length) {
159
+ const row = parseTableCells((_c = lines[endIndex]) != null ? _c : "");
160
+ if (row == null) {
161
+ break;
162
+ }
163
+ rows.push(normalizeTableRow(row, header.length));
164
+ endIndex += 1;
165
+ }
166
+ return {
167
+ alignments,
168
+ endIndex,
169
+ header,
170
+ rows
171
+ };
172
+ }
173
+ function parseTableCells(line) {
174
+ if (!line.includes("|")) {
175
+ return void 0;
176
+ }
177
+ let tableLine = line.trim();
178
+ if (tableLine.startsWith("|")) {
179
+ tableLine = tableLine.slice(1);
180
+ }
181
+ if (tableLine.endsWith("|") && !tableLine.endsWith("\\|")) {
182
+ tableLine = tableLine.slice(0, -1);
183
+ }
184
+ const cells = [];
185
+ let cell = "";
186
+ for (let index = 0; index < tableLine.length; index += 1) {
187
+ const character = tableLine[index];
188
+ const nextCharacter = tableLine[index + 1];
189
+ if (character === "\\" && nextCharacter === "|") {
190
+ cell += "|";
191
+ index += 1;
192
+ continue;
193
+ }
194
+ if (character === "|") {
195
+ cells.push(cell.trim());
196
+ cell = "";
197
+ continue;
198
+ }
199
+ cell += character;
200
+ }
201
+ cells.push(cell.trim());
202
+ return cells;
203
+ }
204
+ function parseTableAlignments(cells) {
205
+ const alignments = [];
206
+ for (const cell of cells) {
207
+ const match = cell.match(/^(:)?-{3,}(:)?$/);
208
+ if (match == null) {
209
+ return void 0;
210
+ }
211
+ const [, left, right] = match;
212
+ alignments.push(
213
+ left != null && right != null ? "center" : right != null ? "right" : "left"
214
+ );
215
+ }
216
+ return alignments;
217
+ }
218
+ function normalizeTableRow(row, length) {
219
+ return Array.from({ length }, (_, index) => {
220
+ var _a;
221
+ return (_a = row[index]) != null ? _a : "";
222
+ });
223
+ }
224
+ function renderTable(table) {
225
+ const header = table.header.map(
226
+ (cell) => `${ansi.bold}${renderInlineMarkdown(cell)}${ansi.boldOff}`
227
+ );
228
+ const rows = table.rows.map((row) => row.map(renderInlineMarkdown));
229
+ const tableRows = [header, ...rows];
230
+ const widths = table.alignments.map(
231
+ (_, columnIndex) => Math.max(3, ...tableRows.map((row) => {
232
+ var _a;
233
+ return visibleLength((_a = row[columnIndex]) != null ? _a : "");
234
+ }))
235
+ );
236
+ return [
237
+ formatTableRow(header, widths, table.alignments),
238
+ widths.map((width) => tableSeparator.repeat(width)).join(" "),
239
+ ...rows.map((row) => formatTableRow(row, widths, table.alignments))
240
+ ];
241
+ }
242
+ function formatTableRow(row, widths, alignments) {
243
+ return row.map(
244
+ (cell, index) => {
245
+ var _a, _b;
246
+ return alignTableCell(cell, (_a = widths[index]) != null ? _a : 0, (_b = alignments[index]) != null ? _b : "left");
247
+ }
248
+ ).join(" ");
249
+ }
250
+ function alignTableCell(cell, width, alignment) {
251
+ const paddingWidth = Math.max(0, width - visibleLength(cell));
252
+ if (alignment === "right") {
253
+ return `${" ".repeat(paddingWidth)}${cell}`;
254
+ }
255
+ if (alignment === "center") {
256
+ const leftPadding = Math.floor(paddingWidth / 2);
257
+ const rightPadding = paddingWidth - leftPadding;
258
+ return `${" ".repeat(leftPadding)}${cell}${" ".repeat(rightPadding)}`;
259
+ }
260
+ return `${cell}${" ".repeat(paddingWidth)}`;
261
+ }
262
+
263
+ // src/tui/layout.ts
264
+ var horizontal = "\u2500";
265
+ function renderScreenViewport(state) {
266
+ var _a;
267
+ const width = Math.max(20, state.width);
268
+ const height = Math.max(8, state.height);
269
+ const inputHeight = 3;
270
+ const bodyHeight = height - inputHeight;
271
+ const bodyContentHeight = bodyHeight - 2;
272
+ const visibleBody = state.visibleBodyLines.slice(0, bodyContentHeight);
273
+ while (visibleBody.length < bodyContentHeight) {
274
+ visibleBody.push("");
275
+ }
276
+ const lines = [
277
+ topBorder(width, state.title, state.rightTitle),
278
+ ...visibleBody.map((line) => boxLine(line, width)),
279
+ bottomBorder(width),
280
+ topBorder(width, state.inputActive ? "Input" : "Status"),
281
+ boxLine(
282
+ state.inputActive ? `> ${state.input}${state.inputCursorVisible === false ? " " : "\u2588"}` : (_a = state.status) != null ? _a : "Streaming... \u2191/\u2193 scroll \xB7 Ctrl+C quit",
283
+ width
284
+ ),
285
+ bottomBorder(width)
286
+ ];
287
+ return lines.join("\n");
288
+ }
289
+ function topBorder(width, title, rightTitle) {
290
+ const contentWidth = Math.max(0, width - 2);
291
+ const label = title ? sliceVisible(` ${title} `, contentWidth) : "";
292
+ const rightLabel = rightTitle ? sliceVisible(
293
+ ` ${rightTitle} `,
294
+ Math.max(0, contentWidth - visibleLength(label))
295
+ ) : "";
296
+ const remaining = Math.max(
297
+ 0,
298
+ contentWidth - visibleLength(label) - visibleLength(rightLabel)
299
+ );
300
+ return `\u250C${label}${horizontal.repeat(remaining)}${rightLabel}\u2510`;
301
+ }
302
+ function bottomBorder(width) {
303
+ return `\u2514${horizontal.repeat(width - 2)}\u2518`;
304
+ }
305
+ function boxLine(line, width) {
306
+ const contentWidth = width - 4;
307
+ const visible = sliceVisible(line, contentWidth);
308
+ const padding = " ".repeat(
309
+ Math.max(0, contentWidth - visibleLength(visible))
310
+ );
311
+ return `\u2502 ${visible}${padding} \u2502`;
312
+ }
313
+
314
+ // src/tui/terminal-frame-buffer.ts
315
+ var escape = "\x1B";
316
+ var cursorHome = `${escape}[H`;
317
+ var clearScreen = `${escape}[2J`;
318
+ var clearLine = `${escape}[2K`;
319
+ var synchronizeStart = `${escape}[?2026h`;
320
+ var synchronizeEnd = `${escape}[?2026l`;
321
+ var _useSynchronizedUpdates, _originalWrite, _previousFrame, _isWritingFrame, _externalWriteSinceLastFrame, _TerminalFrameBuffer_instances, writeUpdate_fn;
322
+ var TerminalFrameBuffer = class {
323
+ constructor(output, options) {
324
+ __privateAdd(this, _TerminalFrameBuffer_instances);
325
+ __privateAdd(this, _useSynchronizedUpdates);
326
+ __privateAdd(this, _originalWrite);
327
+ __privateAdd(this, _previousFrame);
328
+ __privateAdd(this, _isWritingFrame, false);
329
+ __privateAdd(this, _externalWriteSinceLastFrame, false);
330
+ var _a;
331
+ __privateSet(this, _originalWrite, output.write.bind(output));
332
+ __privateSet(this, _useSynchronizedUpdates, (_a = options == null ? void 0 : options.useSynchronizedUpdates) != null ? _a : true);
333
+ output.write = ((chunk, encodingOrCallback, callback) => {
334
+ if (!__privateGet(this, _isWritingFrame)) {
335
+ __privateSet(this, _externalWriteSinceLastFrame, true);
336
+ }
337
+ return __privateGet(this, _originalWrite).call(this, chunk, encodingOrCallback, callback);
338
+ });
339
+ }
340
+ present(frame) {
341
+ const nextFrame = snapshotFrame(frame);
342
+ const update = __privateGet(this, _previousFrame) && !__privateGet(this, _externalWriteSinceLastFrame) ? diffFrame(__privateGet(this, _previousFrame), nextFrame) : `${cursorHome}${clearScreen}${frame}`;
343
+ __privateSet(this, _previousFrame, nextFrame);
344
+ __privateSet(this, _externalWriteSinceLastFrame, false);
345
+ if (update.length === 0) {
346
+ return;
347
+ }
348
+ __privateMethod(this, _TerminalFrameBuffer_instances, writeUpdate_fn).call(this, update);
349
+ }
350
+ reset() {
351
+ __privateSet(this, _previousFrame, void 0);
352
+ }
353
+ };
354
+ _useSynchronizedUpdates = new WeakMap();
355
+ _originalWrite = new WeakMap();
356
+ _previousFrame = new WeakMap();
357
+ _isWritingFrame = new WeakMap();
358
+ _externalWriteSinceLastFrame = new WeakMap();
359
+ _TerminalFrameBuffer_instances = new WeakSet();
360
+ writeUpdate_fn = function(update) {
361
+ __privateSet(this, _isWritingFrame, true);
362
+ try {
363
+ if (!__privateGet(this, _useSynchronizedUpdates)) {
364
+ __privateGet(this, _originalWrite).call(this, update);
365
+ return;
366
+ }
367
+ __privateGet(this, _originalWrite).call(this, `${synchronizeStart}${update}${synchronizeEnd}`);
368
+ } finally {
369
+ __privateSet(this, _isWritingFrame, false);
370
+ }
371
+ };
372
+ function snapshotFrame(frame) {
373
+ return { lines: frame.split("\n") };
374
+ }
375
+ function diffFrame(previousFrame, nextFrame) {
376
+ let output = "";
377
+ const lineCount = Math.max(
378
+ previousFrame.lines.length,
379
+ nextFrame.lines.length
380
+ );
381
+ for (let index = 0; index < lineCount; index++) {
382
+ const line = nextFrame.lines[index];
383
+ if (previousFrame.lines[index] === line) {
384
+ continue;
385
+ }
386
+ output += `${escape}[${index + 1};1H${clearLine}${line != null ? line : ""}`;
387
+ }
388
+ return output;
389
+ }
390
+
391
+ // src/tui/terminal-renderer.ts
392
+ import {
393
+ getToolName,
394
+ isToolUIPart,
395
+ readUIMessageStream
396
+ } from "ai";
397
+ var defaultResponseStatistics = "outputTokensPerSecond";
398
+ var colors = {
399
+ reset: "\x1B[0m",
400
+ dim: "\x1B[2m",
401
+ user: "\x1B[96m",
402
+ assistant: "\x1B[92m",
403
+ reasoning: "\x1B[94m",
404
+ tool: "\x1B[95m",
405
+ error: "\x1B[91m"
406
+ };
407
+ var sectionStyles = {
408
+ user: { color: colors.user, border: "\u2500" },
409
+ assistant: { color: colors.assistant, border: "\u2500" },
410
+ reasoning: { color: colors.reasoning, border: "\xB7" },
411
+ tool: { color: colors.tool, border: "\u2500" },
412
+ error: { color: colors.error, border: "\u2500" }
413
+ };
414
+ var inputCursorBlinkMs = 500;
415
+ var activeControls = "\u2191/\u2193 \xB7 PgUp/PgDn \xB7 Esc/Ctrl+C";
416
+ var doneControls = "\u2191/\u2193 \xB7 PgUp/PgDn \xB7 q/Esc/Ctrl+C";
417
+ var processingStatus = `Processing input... ${activeControls}`;
418
+ var processingToolResultsStatus = `Processing tool results... ${activeControls}`;
419
+ var streamingStatus = `Streaming... ${activeControls}`;
420
+ var executingToolsStatus = `Executing tools... ${activeControls}`;
421
+ var _input, _output, _frameBuffer, _tools, _reasoning, _responseStatistics, _defaultContextSize, _sections, _inputText, _inputActive, _scrollOffset, _title, _status, _isInteractive, _interrupted, _totalTokens, _contextSize, _assistantOutputTokens, _assistantOutputTokensPerSecond, _inputCursorVisible, _inputCursorTimer, _onData, _onResize, _resolveStreamInterrupt, _TerminalRenderer_instances, start_fn, stop_fn, attachInput_fn, detachInput_fn, handleStreamingKey_fn, handleScroll_fn, handlePageScroll_fn, startInputCursorBlink_fn, stopInputCursorBlink_fn, showInputCursor_fn, addSubmittedPrompt_fn, addUserSection_fn, renderAssistantMessage_fn, upsertSection_fn, removeStaleAssistantSections_fn, observeUIMessageStream_fn, addErrorSection_fn, paintAfterBodyChange_fn, paint_fn, repaint_fn, visibleBodyLines_fn, clampScrollOffset_fn, bodyLineCount_fn, bodyContentHeight_fn, width_fn, height_fn, waitForExit_fn;
422
+ var TerminalRenderer = class {
423
+ constructor(options) {
424
+ __privateAdd(this, _TerminalRenderer_instances);
425
+ __privateAdd(this, _input);
426
+ __privateAdd(this, _output);
427
+ __privateAdd(this, _frameBuffer);
428
+ __privateAdd(this, _tools);
429
+ __privateAdd(this, _reasoning);
430
+ __privateAdd(this, _responseStatistics);
431
+ __privateAdd(this, _defaultContextSize);
432
+ __privateAdd(this, _sections, []);
433
+ __privateAdd(this, _inputText, "");
434
+ __privateAdd(this, _inputActive, false);
435
+ __privateAdd(this, _scrollOffset, 0);
436
+ __privateAdd(this, _title, "");
437
+ __privateAdd(this, _status, streamingStatus);
438
+ __privateAdd(this, _isInteractive, false);
439
+ __privateAdd(this, _interrupted, false);
440
+ __privateAdd(this, _totalTokens);
441
+ __privateAdd(this, _contextSize);
442
+ __privateAdd(this, _assistantOutputTokens);
443
+ __privateAdd(this, _assistantOutputTokensPerSecond);
444
+ __privateAdd(this, _inputCursorVisible, true);
445
+ __privateAdd(this, _inputCursorTimer);
446
+ __privateAdd(this, _onData);
447
+ __privateAdd(this, _onResize);
448
+ __privateAdd(this, _resolveStreamInterrupt);
449
+ var _a, _b, _c, _d, _e, _f;
450
+ __privateSet(this, _input, (_a = options == null ? void 0 : options.input) != null ? _a : process.stdin);
451
+ __privateSet(this, _output, (_b = options == null ? void 0 : options.output) != null ? _b : process.stdout);
452
+ __privateSet(this, _frameBuffer, (_c = options == null ? void 0 : options.frameBuffer) != null ? _c : new TerminalFrameBuffer(__privateGet(this, _output)));
453
+ __privateSet(this, _tools, (_d = options == null ? void 0 : options.tools) != null ? _d : "auto-collapsed");
454
+ __privateSet(this, _reasoning, (_e = options == null ? void 0 : options.reasoning) != null ? _e : "auto-collapsed");
455
+ __privateSet(this, _responseStatistics, (_f = options == null ? void 0 : options.responseStatistics) != null ? _f : defaultResponseStatistics);
456
+ __privateSet(this, _defaultContextSize, options == null ? void 0 : options.contextSize);
457
+ __privateSet(this, _contextSize, options == null ? void 0 : options.contextSize);
458
+ }
459
+ async readPrompt(options) {
460
+ var _a;
461
+ __privateMethod(this, _TerminalRenderer_instances, start_fn).call(this, options);
462
+ __privateSet(this, _inputActive, true);
463
+ __privateSet(this, _inputText, (_a = options == null ? void 0 : options.initialPrompt) != null ? _a : "");
464
+ __privateSet(this, _status, `Type a prompt and press Enter \xB7 ${activeControls}`);
465
+ __privateMethod(this, _TerminalRenderer_instances, startInputCursorBlink_fn).call(this);
466
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
467
+ return await new Promise((resolve, reject) => {
468
+ __privateSet(this, _onData, (chunk) => {
469
+ const key = parseKey(chunk);
470
+ switch (key.type) {
471
+ case "character":
472
+ __privateSet(this, _inputText, __privateGet(this, _inputText) + key.value);
473
+ __privateMethod(this, _TerminalRenderer_instances, showInputCursor_fn).call(this);
474
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
475
+ break;
476
+ case "backspace":
477
+ __privateSet(this, _inputText, __privateGet(this, _inputText).slice(0, -1));
478
+ __privateMethod(this, _TerminalRenderer_instances, showInputCursor_fn).call(this);
479
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
480
+ break;
481
+ case "enter": {
482
+ const prompt = __privateGet(this, _inputText);
483
+ __privateSet(this, _inputActive, false);
484
+ __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
485
+ __privateSet(this, _status, processingStatus);
486
+ __privateMethod(this, _TerminalRenderer_instances, addUserSection_fn).call(this, prompt);
487
+ __privateSet(this, _inputText, "");
488
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
489
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
490
+ resolve(prompt);
491
+ break;
492
+ }
493
+ case "up":
494
+ case "down":
495
+ __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
496
+ break;
497
+ case "page-up":
498
+ case "page-down":
499
+ __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
500
+ break;
501
+ case "ctrl-l":
502
+ __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
503
+ break;
504
+ case "escape":
505
+ case "ctrl-c":
506
+ __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
507
+ __privateMethod(this, _TerminalRenderer_instances, stop_fn).call(this);
508
+ reject(interruptedError());
509
+ break;
510
+ case "ignore":
511
+ break;
512
+ }
513
+ });
514
+ __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
515
+ });
516
+ }
517
+ async renderStream(result, options) {
518
+ var _a, _b, _c, _d;
519
+ __privateMethod(this, _TerminalRenderer_instances, start_fn).call(this, options);
520
+ __privateSet(this, _inputActive, false);
521
+ __privateSet(this, _status, processingStatus);
522
+ __privateMethod(this, _TerminalRenderer_instances, addSubmittedPrompt_fn).call(this, options == null ? void 0 : options.submittedPrompt);
523
+ __privateSet(this, _interrupted, false);
524
+ __privateSet(this, _totalTokens, void 0);
525
+ __privateSet(this, _assistantOutputTokens, void 0);
526
+ __privateSet(this, _assistantOutputTokensPerSecond, void 0);
527
+ const displayModes = {
528
+ tools: (_a = options == null ? void 0 : options.tools) != null ? _a : __privateGet(this, _tools),
529
+ reasoning: (_b = options == null ? void 0 : options.reasoning) != null ? _b : __privateGet(this, _reasoning),
530
+ responseStatistics: (_c = options == null ? void 0 : options.responseStatistics) != null ? _c : __privateGet(this, _responseStatistics)
531
+ };
532
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
533
+ const streamInterrupted = new Promise((resolve) => {
534
+ __privateSet(this, _resolveStreamInterrupt, resolve);
535
+ });
536
+ __privateSet(this, _onData, (chunk) => __privateMethod(this, _TerminalRenderer_instances, handleStreamingKey_fn).call(this, chunk));
537
+ __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
538
+ let responseMessage;
539
+ const stream = toReadableStream(
540
+ __privateMethod(this, _TerminalRenderer_instances, observeUIMessageStream_fn).call(this, result.uiMessageStream)
541
+ );
542
+ try {
543
+ const messages = readUIMessageStream({
544
+ message: result.message,
545
+ stream,
546
+ onError: (error) => __privateMethod(this, _TerminalRenderer_instances, addErrorSection_fn).call(this, "Error", formatStreamError(error))
547
+ });
548
+ for await (const message of takeUntil(messages, streamInterrupted)) {
549
+ if (__privateGet(this, _interrupted)) {
550
+ break;
551
+ }
552
+ responseMessage = message;
553
+ __privateMethod(this, _TerminalRenderer_instances, renderAssistantMessage_fn).call(this, message, displayModes);
554
+ }
555
+ if (!__privateGet(this, _interrupted) && responseMessage && __privateGet(this, _assistantOutputTokens) != null) {
556
+ __privateMethod(this, _TerminalRenderer_instances, renderAssistantMessage_fn).call(this, responseMessage, displayModes);
557
+ }
558
+ } finally {
559
+ __privateSet(this, _resolveStreamInterrupt, void 0);
560
+ if (__privateGet(this, _interrupted)) {
561
+ (_d = result.abort) == null ? void 0 : _d.call(result);
562
+ }
563
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
564
+ __privateSet(this, _status, __privateGet(this, _interrupted) ? "Interrupted" : (options == null ? void 0 : options.continueSession) ? `Done \xB7 Enter another prompt \xB7 ${activeControls}` : `Done \xB7 ${doneControls}`);
565
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
566
+ await __privateMethod(this, _TerminalRenderer_instances, waitForExit_fn).call(this, options);
567
+ if (__privateGet(this, _interrupted) || !(options == null ? void 0 : options.continueSession)) {
568
+ __privateMethod(this, _TerminalRenderer_instances, stop_fn).call(this);
569
+ }
570
+ }
571
+ if (__privateGet(this, _interrupted)) {
572
+ throw interruptedError();
573
+ }
574
+ return responseMessage;
575
+ }
576
+ async readToolApproval(request, options) {
577
+ __privateMethod(this, _TerminalRenderer_instances, start_fn).call(this, options);
578
+ __privateSet(this, _inputActive, false);
579
+ __privateSet(this, _status, `Approve ${formatToolApprovalTitle(request)}? y/n \xB7 ${activeControls}`);
580
+ __privateSet(this, _interrupted, false);
581
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
582
+ return await new Promise((resolve, reject) => {
583
+ __privateSet(this, _onData, (chunk) => {
584
+ const key = parseKey(chunk);
585
+ switch (key.type) {
586
+ case "character": {
587
+ const value = key.value.toLowerCase();
588
+ if (value === "y") {
589
+ __privateSet(this, _status, `Approved \xB7 ${processingStatus}`);
590
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
591
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
592
+ resolve({ approved: true });
593
+ } else if (value === "n") {
594
+ __privateSet(this, _status, `Denied \xB7 ${processingStatus}`);
595
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
596
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
597
+ resolve({ approved: false, reason: "Denied by user." });
598
+ }
599
+ break;
600
+ }
601
+ case "up":
602
+ case "down":
603
+ __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
604
+ break;
605
+ case "page-up":
606
+ case "page-down":
607
+ __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
608
+ break;
609
+ case "ctrl-l":
610
+ __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
611
+ break;
612
+ case "escape":
613
+ case "ctrl-c":
614
+ __privateSet(this, _interrupted, true);
615
+ __privateMethod(this, _TerminalRenderer_instances, stop_fn).call(this);
616
+ reject(interruptedError());
617
+ break;
618
+ default:
619
+ break;
620
+ }
621
+ });
622
+ __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
623
+ });
624
+ }
625
+ };
626
+ _input = new WeakMap();
627
+ _output = new WeakMap();
628
+ _frameBuffer = new WeakMap();
629
+ _tools = new WeakMap();
630
+ _reasoning = new WeakMap();
631
+ _responseStatistics = new WeakMap();
632
+ _defaultContextSize = new WeakMap();
633
+ _sections = new WeakMap();
634
+ _inputText = new WeakMap();
635
+ _inputActive = new WeakMap();
636
+ _scrollOffset = new WeakMap();
637
+ _title = new WeakMap();
638
+ _status = new WeakMap();
639
+ _isInteractive = new WeakMap();
640
+ _interrupted = new WeakMap();
641
+ _totalTokens = new WeakMap();
642
+ _contextSize = new WeakMap();
643
+ _assistantOutputTokens = new WeakMap();
644
+ _assistantOutputTokensPerSecond = new WeakMap();
645
+ _inputCursorVisible = new WeakMap();
646
+ _inputCursorTimer = new WeakMap();
647
+ _onData = new WeakMap();
648
+ _onResize = new WeakMap();
649
+ _resolveStreamInterrupt = new WeakMap();
650
+ _TerminalRenderer_instances = new WeakSet();
651
+ start_fn = function(options) {
652
+ var _a, _b, _c, _d;
653
+ __privateSet(this, _title, (_a = options == null ? void 0 : options.title) != null ? _a : __privateGet(this, _title));
654
+ __privateSet(this, _contextSize, (_b = options == null ? void 0 : options.contextSize) != null ? _b : __privateGet(this, _defaultContextSize));
655
+ if (__privateGet(this, _isInteractive)) {
656
+ return;
657
+ }
658
+ __privateSet(this, _isInteractive, true);
659
+ __privateGet(this, _frameBuffer).reset();
660
+ __privateGet(this, _output).write("\x1B[?1049h\x1B[?25l");
661
+ if (__privateGet(this, _input).isTTY) {
662
+ (_d = (_c = __privateGet(this, _input)).setRawMode) == null ? void 0 : _d.call(_c, true);
663
+ __privateGet(this, _input).resume();
664
+ }
665
+ __privateSet(this, _onResize, () => __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this));
666
+ __privateGet(this, _output).on("resize", __privateGet(this, _onResize));
667
+ };
668
+ stop_fn = function() {
669
+ var _a, _b;
670
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
671
+ __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
672
+ if (!__privateGet(this, _isInteractive)) {
673
+ return;
674
+ }
675
+ if (__privateGet(this, _input).isTTY) {
676
+ (_b = (_a = __privateGet(this, _input)).setRawMode) == null ? void 0 : _b.call(_a, false);
677
+ __privateGet(this, _input).pause();
678
+ }
679
+ if (__privateGet(this, _onResize)) {
680
+ __privateGet(this, _output).off("resize", __privateGet(this, _onResize));
681
+ __privateSet(this, _onResize, void 0);
682
+ }
683
+ __privateGet(this, _output).write("\x1B[?25h\x1B[?1049l");
684
+ __privateGet(this, _frameBuffer).reset();
685
+ __privateSet(this, _isInteractive, false);
686
+ };
687
+ attachInput_fn = function() {
688
+ if (__privateGet(this, _onData)) {
689
+ __privateGet(this, _input).on("data", __privateGet(this, _onData));
690
+ }
691
+ };
692
+ detachInput_fn = function() {
693
+ if (__privateGet(this, _onData)) {
694
+ __privateGet(this, _input).off("data", __privateGet(this, _onData));
695
+ __privateSet(this, _onData, void 0);
696
+ }
697
+ };
698
+ handleStreamingKey_fn = function(chunk) {
699
+ var _a;
700
+ const key = parseKey(chunk);
701
+ switch (key.type) {
702
+ case "up":
703
+ case "down":
704
+ __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
705
+ break;
706
+ case "page-up":
707
+ case "page-down":
708
+ __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
709
+ break;
710
+ case "ctrl-l":
711
+ __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
712
+ break;
713
+ case "escape":
714
+ case "ctrl-c":
715
+ __privateSet(this, _interrupted, true);
716
+ (_a = __privateGet(this, _resolveStreamInterrupt)) == null ? void 0 : _a.call(this);
717
+ break;
718
+ default:
719
+ break;
720
+ }
721
+ };
722
+ handleScroll_fn = function(direction, lines = 1) {
723
+ const delta = direction === "up" ? lines : -lines;
724
+ __privateSet(this, _scrollOffset, __privateMethod(this, _TerminalRenderer_instances, clampScrollOffset_fn).call(this, __privateGet(this, _scrollOffset) + delta));
725
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
726
+ };
727
+ handlePageScroll_fn = function(direction) {
728
+ __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, direction === "page-up" ? "up" : "down", __privateMethod(this, _TerminalRenderer_instances, bodyContentHeight_fn).call(this));
729
+ };
730
+ startInputCursorBlink_fn = function() {
731
+ var _a, _b;
732
+ __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
733
+ __privateMethod(this, _TerminalRenderer_instances, showInputCursor_fn).call(this);
734
+ __privateSet(this, _inputCursorTimer, setInterval(() => {
735
+ __privateSet(this, _inputCursorVisible, !__privateGet(this, _inputCursorVisible));
736
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
737
+ }, inputCursorBlinkMs));
738
+ (_b = (_a = __privateGet(this, _inputCursorTimer)).unref) == null ? void 0 : _b.call(_a);
739
+ };
740
+ stopInputCursorBlink_fn = function() {
741
+ if (__privateGet(this, _inputCursorTimer)) {
742
+ clearInterval(__privateGet(this, _inputCursorTimer));
743
+ __privateSet(this, _inputCursorTimer, void 0);
744
+ }
745
+ __privateSet(this, _inputCursorVisible, true);
746
+ };
747
+ showInputCursor_fn = function() {
748
+ __privateSet(this, _inputCursorVisible, true);
749
+ };
750
+ addSubmittedPrompt_fn = function(prompt) {
751
+ if (prompt == null) {
752
+ return;
753
+ }
754
+ const section = __privateGet(this, _sections).at(-1);
755
+ if ((section == null ? void 0 : section.kind) === "user" && section.content === prompt) {
756
+ return;
757
+ }
758
+ __privateMethod(this, _TerminalRenderer_instances, addUserSection_fn).call(this, prompt);
759
+ };
760
+ addUserSection_fn = function(prompt) {
761
+ const previousBodyLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
762
+ __privateGet(this, _sections).push({ kind: "user", title: "User", content: prompt });
763
+ __privateMethod(this, _TerminalRenderer_instances, paintAfterBodyChange_fn).call(this, previousBodyLineCount);
764
+ };
765
+ renderAssistantMessage_fn = function(message, displayModes) {
766
+ var _a, _b, _c;
767
+ const previousBodyLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
768
+ const activeSectionIds = /* @__PURE__ */ new Set();
769
+ const metadataStats = extractResponseStatisticsFromMetadata(
770
+ message.metadata
771
+ );
772
+ __privateSet(this, _totalTokens, (_a = metadataStats.totalTokens) != null ? _a : __privateGet(this, _totalTokens));
773
+ __privateSet(this, _assistantOutputTokens, (_b = metadataStats.outputTokens) != null ? _b : __privateGet(this, _assistantOutputTokens));
774
+ __privateSet(this, _assistantOutputTokensPerSecond, (_c = metadataStats.outputTokensPerSecond) != null ? _c : __privateGet(this, _assistantOutputTokensPerSecond));
775
+ for (const [index, part] of message.parts.entries()) {
776
+ const id = sectionId(message.id, index);
777
+ switch (part.type) {
778
+ case "text": {
779
+ const content = part.text.trim();
780
+ if (content.length === 0) {
781
+ break;
782
+ }
783
+ activeSectionIds.add(id);
784
+ __privateMethod(this, _TerminalRenderer_instances, upsertSection_fn).call(this, {
785
+ id,
786
+ kind: "assistant",
787
+ title: "Assistant",
788
+ rightTitle: formatResponseStatistics(
789
+ {
790
+ totalTokens: __privateGet(this, _totalTokens),
791
+ outputTokens: __privateGet(this, _assistantOutputTokens),
792
+ outputTokensPerSecond: __privateGet(this, _assistantOutputTokensPerSecond)
793
+ },
794
+ displayModes.responseStatistics
795
+ ),
796
+ content
797
+ });
798
+ break;
799
+ }
800
+ case "reasoning": {
801
+ const content = part.text.trim();
802
+ if (displayModes.reasoning === "hidden" || content.length === 0) {
803
+ break;
804
+ }
805
+ activeSectionIds.add(id);
806
+ __privateMethod(this, _TerminalRenderer_instances, upsertSection_fn).call(this, {
807
+ id,
808
+ kind: "reasoning",
809
+ title: "Reasoning",
810
+ content,
811
+ collapsed: shouldCollapsePart(
812
+ message,
813
+ index,
814
+ displayModes.reasoning,
815
+ displayModes
816
+ )
817
+ });
818
+ break;
819
+ }
820
+ default:
821
+ if (isToolUIPart(part)) {
822
+ if (displayModes.tools === "hidden") {
823
+ break;
824
+ }
825
+ activeSectionIds.add(id);
826
+ __privateMethod(this, _TerminalRenderer_instances, upsertSection_fn).call(this, {
827
+ id,
828
+ ...renderToolInvocation(part, {
829
+ mode: displayModes.tools,
830
+ collapsed: shouldCollapsePart(
831
+ message,
832
+ index,
833
+ displayModes.tools,
834
+ displayModes
835
+ )
836
+ })
837
+ });
838
+ }
839
+ break;
840
+ }
841
+ }
842
+ __privateMethod(this, _TerminalRenderer_instances, removeStaleAssistantSections_fn).call(this, message.id, activeSectionIds);
843
+ __privateMethod(this, _TerminalRenderer_instances, paintAfterBodyChange_fn).call(this, previousBodyLineCount);
844
+ };
845
+ upsertSection_fn = function(section) {
846
+ const existingSection = section.id ? __privateGet(this, _sections).find((candidate) => candidate.id === section.id) : void 0;
847
+ if (existingSection) {
848
+ const cache = existingSection.cache;
849
+ existingSection.kind = section.kind;
850
+ existingSection.title = section.title;
851
+ existingSection.rightTitle = section.rightTitle;
852
+ existingSection.content = section.content;
853
+ existingSection.collapsed = section.collapsed;
854
+ existingSection.cache = cache && sectionMatchesCache(section, cache) ? cache : void 0;
855
+ return;
856
+ }
857
+ __privateGet(this, _sections).push(section);
858
+ };
859
+ removeStaleAssistantSections_fn = function(messageId, activeSectionIds) {
860
+ const prefix = `${messageId}:`;
861
+ __privateSet(this, _sections, __privateGet(this, _sections).filter(
862
+ (section) => section.id == null || !section.id.startsWith(prefix) || activeSectionIds.has(section.id)
863
+ ));
864
+ };
865
+ observeUIMessageStream_fn = async function* (stream) {
866
+ let hasPendingToolResults = false;
867
+ for await (const chunk of iterateUIMessageStream(stream)) {
868
+ const nextStatus = statusForStreamChunk(chunk, { hasPendingToolResults });
869
+ if (chunk.type === "start-step") {
870
+ hasPendingToolResults = false;
871
+ } else if (finishesToolExecution(chunk)) {
872
+ hasPendingToolResults = true;
873
+ }
874
+ if (nextStatus && __privateGet(this, _status) !== nextStatus) {
875
+ __privateSet(this, _status, nextStatus);
876
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
877
+ } else if (startsVisibleAssistantStream(chunk) && __privateGet(this, _status) !== streamingStatus) {
878
+ __privateSet(this, _status, streamingStatus);
879
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
880
+ }
881
+ if (chunk.type === "error") {
882
+ __privateMethod(this, _TerminalRenderer_instances, addErrorSection_fn).call(this, "Error", chunk.errorText);
883
+ }
884
+ if (chunk.type === "finish") {
885
+ const stats = extractResponseStatistics(chunk);
886
+ __privateSet(this, _totalTokens, stats.totalTokens);
887
+ __privateSet(this, _assistantOutputTokens, stats.outputTokens);
888
+ __privateSet(this, _assistantOutputTokensPerSecond, stats.outputTokensPerSecond);
889
+ }
890
+ yield chunk;
891
+ }
892
+ };
893
+ addErrorSection_fn = function(title, content) {
894
+ const previousBodyLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
895
+ __privateGet(this, _sections).push({ kind: "error", title, content });
896
+ __privateMethod(this, _TerminalRenderer_instances, paintAfterBodyChange_fn).call(this, previousBodyLineCount);
897
+ };
898
+ paintAfterBodyChange_fn = function(previousBodyLineCount) {
899
+ if (__privateGet(this, _scrollOffset) !== 0) {
900
+ const bodyLineDelta = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this) - previousBodyLineCount;
901
+ __privateSet(this, _scrollOffset, __privateMethod(this, _TerminalRenderer_instances, clampScrollOffset_fn).call(this, __privateGet(this, _scrollOffset) + bodyLineDelta));
902
+ }
903
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
904
+ };
905
+ paint_fn = function() {
906
+ const frame = renderScreenViewport({
907
+ width: __privateMethod(this, _TerminalRenderer_instances, width_fn).call(this),
908
+ height: __privateMethod(this, _TerminalRenderer_instances, height_fn).call(this),
909
+ title: __privateGet(this, _title),
910
+ rightTitle: formatTokenCount(__privateGet(this, _totalTokens), __privateGet(this, _contextSize)),
911
+ visibleBodyLines: __privateMethod(this, _TerminalRenderer_instances, visibleBodyLines_fn).call(this),
912
+ input: __privateGet(this, _inputText),
913
+ inputActive: __privateGet(this, _inputActive),
914
+ inputCursorVisible: __privateGet(this, _inputCursorVisible),
915
+ status: __privateGet(this, _status)
916
+ });
917
+ __privateGet(this, _frameBuffer).present(frame);
918
+ };
919
+ repaint_fn = function() {
920
+ __privateGet(this, _frameBuffer).reset();
921
+ __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
922
+ };
923
+ visibleBodyLines_fn = function() {
924
+ if (__privateGet(this, _sections).length === 0) {
925
+ return ["Waiting for input..."];
926
+ }
927
+ const bodyContentHeight = __privateMethod(this, _TerminalRenderer_instances, bodyContentHeight_fn).call(this);
928
+ const totalLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
929
+ const start = Math.max(
930
+ 0,
931
+ totalLineCount - bodyContentHeight - __privateGet(this, _scrollOffset)
932
+ );
933
+ const end = start + bodyContentHeight;
934
+ const visibleLines = [];
935
+ let sectionStart = 0;
936
+ for (const section of __privateGet(this, _sections)) {
937
+ const sectionLines = renderSectionLines(section, __privateMethod(this, _TerminalRenderer_instances, width_fn).call(this) - 4);
938
+ const sectionEnd = sectionStart + sectionLines.length;
939
+ if (sectionEnd > start && sectionStart < end) {
940
+ visibleLines.push(
941
+ ...sectionLines.slice(
942
+ Math.max(0, start - sectionStart),
943
+ end - sectionStart
944
+ )
945
+ );
946
+ }
947
+ if (visibleLines.length >= bodyContentHeight) {
948
+ break;
949
+ }
950
+ sectionStart = sectionEnd;
951
+ }
952
+ return visibleLines;
953
+ };
954
+ clampScrollOffset_fn = function(scrollOffset) {
955
+ const maxScrollOffset = Math.max(
956
+ 0,
957
+ __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this) - __privateMethod(this, _TerminalRenderer_instances, bodyContentHeight_fn).call(this)
958
+ );
959
+ return Math.min(Math.max(0, scrollOffset), maxScrollOffset);
960
+ };
961
+ bodyLineCount_fn = function() {
962
+ if (__privateGet(this, _sections).length === 0) {
963
+ return 1;
964
+ }
965
+ let count = 0;
966
+ for (const section of __privateGet(this, _sections)) {
967
+ count += renderSectionLines(section, __privateMethod(this, _TerminalRenderer_instances, width_fn).call(this) - 4).length;
968
+ }
969
+ return count;
970
+ };
971
+ bodyContentHeight_fn = function() {
972
+ return Math.max(1, __privateMethod(this, _TerminalRenderer_instances, height_fn).call(this) - 5);
973
+ };
974
+ width_fn = function() {
975
+ var _a;
976
+ return Math.max(20, (_a = __privateGet(this, _output).columns) != null ? _a : 80);
977
+ };
978
+ height_fn = function() {
979
+ var _a;
980
+ return Math.max(8, (_a = __privateGet(this, _output).rows) != null ? _a : 24);
981
+ };
982
+ waitForExit_fn = async function(options) {
983
+ if ((options == null ? void 0 : options.waitForExit) === false || !__privateGet(this, _input).isTTY || __privateGet(this, _interrupted)) {
984
+ return;
985
+ }
986
+ await new Promise((resolve) => {
987
+ __privateSet(this, _onData, (chunk) => {
988
+ const key = parseKey(chunk);
989
+ switch (key.type) {
990
+ case "up":
991
+ case "down":
992
+ __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
993
+ break;
994
+ case "page-up":
995
+ case "page-down":
996
+ __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
997
+ break;
998
+ case "ctrl-l":
999
+ __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
1000
+ break;
1001
+ case "escape":
1002
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
1003
+ resolve();
1004
+ break;
1005
+ case "character":
1006
+ if (key.value === "q") {
1007
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
1008
+ resolve();
1009
+ }
1010
+ break;
1011
+ case "ctrl-c":
1012
+ __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
1013
+ process.exitCode = 130;
1014
+ resolve();
1015
+ break;
1016
+ default:
1017
+ break;
1018
+ }
1019
+ });
1020
+ __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
1021
+ });
1022
+ };
1023
+ function interruptedError() {
1024
+ return new Error("Interrupted");
1025
+ }
1026
+ async function* takeUntil(source, stop) {
1027
+ const iterator = source[Symbol.asyncIterator]();
1028
+ const stopped = stop.then(
1029
+ () => ({ done: true, value: void 0 })
1030
+ );
1031
+ while (true) {
1032
+ const nextValue = await Promise.race([iterator.next(), stopped]);
1033
+ if (nextValue.done) {
1034
+ break;
1035
+ }
1036
+ yield nextValue.value;
1037
+ }
1038
+ }
1039
+ function formatStreamError(error) {
1040
+ if (error instanceof Error) {
1041
+ return error.message;
1042
+ }
1043
+ if (typeof error === "string") {
1044
+ return error;
1045
+ }
1046
+ return JSON.stringify(error);
1047
+ }
1048
+ function renderToolInvocation(part, options) {
1049
+ var _a, _b, _c, _d;
1050
+ const toolName = getToolName(part);
1051
+ const title = `Tool \xB7 ${(_a = part.title) != null ? _a : toolName}`;
1052
+ const input = "input" in part ? part.input : void 0;
1053
+ const inputText = input === void 0 ? "Input: (streaming...)" : `Input:
1054
+ ${formatValue(input)}`;
1055
+ const status = toolStatus(part);
1056
+ if (options.collapsed) {
1057
+ return {
1058
+ kind: "tool",
1059
+ title,
1060
+ rightTitle: status,
1061
+ content: "",
1062
+ collapsed: true
1063
+ };
1064
+ }
1065
+ switch (part.state) {
1066
+ case "input-streaming":
1067
+ return {
1068
+ kind: "tool",
1069
+ title,
1070
+ rightTitle: status,
1071
+ content: inputText
1072
+ };
1073
+ case "input-available":
1074
+ return {
1075
+ kind: "tool",
1076
+ title,
1077
+ rightTitle: status,
1078
+ content: inputText
1079
+ };
1080
+ case "approval-requested":
1081
+ return {
1082
+ kind: "tool",
1083
+ title,
1084
+ rightTitle: status,
1085
+ content: inputText
1086
+ };
1087
+ case "approval-responded":
1088
+ return {
1089
+ kind: "tool",
1090
+ title,
1091
+ rightTitle: status,
1092
+ content: inputText
1093
+ };
1094
+ case "output-available":
1095
+ return {
1096
+ kind: "tool",
1097
+ title,
1098
+ rightTitle: status,
1099
+ content: `${inputText}
1100
+
1101
+ Output:
1102
+ ${formatValue(part.output)}`
1103
+ };
1104
+ case "output-error":
1105
+ return {
1106
+ kind: "error",
1107
+ title: `Tool Error \xB7 ${(_b = part.title) != null ? _b : toolName}`,
1108
+ rightTitle: status,
1109
+ content: `${inputText}
1110
+
1111
+ Error:
1112
+ ${part.errorText}`
1113
+ };
1114
+ case "output-denied":
1115
+ return {
1116
+ kind: "error",
1117
+ title: `Tool Denied \xB7 ${(_c = part.title) != null ? _c : toolName}`,
1118
+ rightTitle: status,
1119
+ content: `${inputText}
1120
+
1121
+ Reason: ${(_d = part.approval.reason) != null ? _d : "denied"}`
1122
+ };
1123
+ }
1124
+ }
1125
+ function shouldCollapsePart(message, partIndex, mode, displayModes) {
1126
+ switch (mode) {
1127
+ case "collapsed":
1128
+ return true;
1129
+ case "auto-collapsed":
1130
+ return message.parts.slice(partIndex + 1).some((part) => isVisibleAssistantPart(part, displayModes));
1131
+ case "full":
1132
+ case "hidden":
1133
+ return false;
1134
+ }
1135
+ }
1136
+ function isVisibleAssistantPart(part, displayModes) {
1137
+ switch (part.type) {
1138
+ case "text":
1139
+ return part.text.trim().length > 0;
1140
+ case "reasoning":
1141
+ return displayModes.reasoning !== "hidden" && part.text.trim().length > 0;
1142
+ default:
1143
+ return isToolUIPart(part) && displayModes.tools !== "hidden";
1144
+ }
1145
+ }
1146
+ function startsVisibleAssistantStream(chunk) {
1147
+ switch (chunk.type) {
1148
+ case "text-start":
1149
+ case "text-delta":
1150
+ case "reasoning-start":
1151
+ case "reasoning-delta":
1152
+ case "tool-input-start":
1153
+ case "tool-input-delta":
1154
+ return true;
1155
+ default:
1156
+ return false;
1157
+ }
1158
+ }
1159
+ function statusForStreamChunk(chunk, { hasPendingToolResults }) {
1160
+ switch (chunk.type) {
1161
+ case "start-step":
1162
+ return hasPendingToolResults ? processingToolResultsStatus : processingStatus;
1163
+ case "tool-output-available":
1164
+ case "tool-output-error":
1165
+ case "tool-output-denied":
1166
+ return processingToolResultsStatus;
1167
+ case "tool-input-available":
1168
+ return executingToolsStatus;
1169
+ case "tool-approval-response":
1170
+ return chunk.approved ? executingToolsStatus : void 0;
1171
+ default:
1172
+ return void 0;
1173
+ }
1174
+ }
1175
+ function finishesToolExecution(chunk) {
1176
+ switch (chunk.type) {
1177
+ case "tool-output-available":
1178
+ case "tool-output-error":
1179
+ case "tool-output-denied":
1180
+ return true;
1181
+ default:
1182
+ return false;
1183
+ }
1184
+ }
1185
+ function toolStatus(part) {
1186
+ switch (part.state) {
1187
+ case "input-streaming":
1188
+ return "waiting";
1189
+ case "approval-requested":
1190
+ return "approval requested";
1191
+ case "input-available":
1192
+ return "executing";
1193
+ case "approval-responded":
1194
+ return part.approval.approved ? "executing" : "denied";
1195
+ case "output-available":
1196
+ case "output-error":
1197
+ return "done";
1198
+ case "output-denied":
1199
+ return "denied";
1200
+ }
1201
+ }
1202
+ function formatValue(value) {
1203
+ if (typeof value === "string") {
1204
+ return value;
1205
+ }
1206
+ return JSON.stringify(value, null, 2);
1207
+ }
1208
+ function formatToolApprovalTitle(request) {
1209
+ var _a;
1210
+ return `tool ${(_a = request.title) != null ? _a : request.toolName}`;
1211
+ }
1212
+ function sectionId(messageId, partIndex) {
1213
+ return `${messageId}:${partIndex}`;
1214
+ }
1215
+ function toReadableStream(stream) {
1216
+ if (stream instanceof ReadableStream) {
1217
+ return stream;
1218
+ }
1219
+ return new ReadableStream({
1220
+ async start(controller) {
1221
+ try {
1222
+ for await (const chunk of stream) {
1223
+ controller.enqueue(chunk);
1224
+ }
1225
+ controller.close();
1226
+ } catch (error) {
1227
+ controller.error(error);
1228
+ }
1229
+ }
1230
+ });
1231
+ }
1232
+ async function* iterateUIMessageStream(stream) {
1233
+ if (stream instanceof ReadableStream) {
1234
+ const reader = stream.getReader();
1235
+ try {
1236
+ while (true) {
1237
+ const { done, value } = await reader.read();
1238
+ if (done) {
1239
+ return;
1240
+ }
1241
+ yield value;
1242
+ }
1243
+ } finally {
1244
+ reader.releaseLock();
1245
+ }
1246
+ return;
1247
+ }
1248
+ yield* stream;
1249
+ }
1250
+ function renderSectionLines(section, width) {
1251
+ if (section.cache && sectionMatchesCache(section, section.cache, width)) {
1252
+ return section.cache.lines;
1253
+ }
1254
+ const lines = createSectionLines(section, width);
1255
+ section.cache = {
1256
+ width,
1257
+ kind: section.kind,
1258
+ title: section.title,
1259
+ rightTitle: section.rightTitle,
1260
+ content: section.content,
1261
+ collapsed: section.collapsed === true,
1262
+ lines
1263
+ };
1264
+ return lines;
1265
+ }
1266
+ function sectionMatchesCache(section, cache, width = cache.width) {
1267
+ return cache.width === width && cache.kind === section.kind && cache.title === section.title && cache.rightTitle === section.rightTitle && cache.content === section.content && cache.collapsed === (section.collapsed === true);
1268
+ }
1269
+ function createSectionLines(section, width) {
1270
+ const style = sectionStyles[section.kind];
1271
+ const contentWidth = Math.max(1, width - 4);
1272
+ const title = ` ${section.title} `;
1273
+ const rightTitle = section.rightTitle ? ` ${section.rightTitle} ` : "";
1274
+ if (section.collapsed) {
1275
+ const borderWidth2 = Math.max(
1276
+ 0,
1277
+ width - 2 - title.length - rightTitle.length
1278
+ );
1279
+ const top2 = `${style.color}\u256D${title}${style.border.repeat(borderWidth2)}${rightTitle}\u256E${colors.reset}`;
1280
+ const bottom2 = `${style.color}\u2570${style.border.repeat(Math.max(0, width - 2))}\u256F${colors.reset}`;
1281
+ return [top2, bottom2];
1282
+ }
1283
+ const borderWidth = Math.max(0, width - 2 - title.length - rightTitle.length);
1284
+ const top = `${style.color}\u256D${title}${style.border.repeat(borderWidth)}${rightTitle}\u256E${colors.reset}`;
1285
+ const bottom = `${style.color}\u2570${style.border.repeat(Math.max(0, width - 2))}\u256F${colors.reset}`;
1286
+ const content = section.content.length > 0 ? renderMarkdown(section.content) : colors.dim + "(streaming...)" + colors.reset;
1287
+ const lines = content.split("\n").flatMap((line) => wrapVisibleLine(line, contentWidth));
1288
+ return [
1289
+ top,
1290
+ ...lines.map((line) => sectionLine(line, contentWidth, style.color)),
1291
+ bottom
1292
+ ];
1293
+ }
1294
+ function sectionLine(line, contentWidth, color) {
1295
+ const visible = sliceVisible(line, contentWidth);
1296
+ const padding = " ".repeat(
1297
+ Math.max(0, contentWidth - visibleLength(visible))
1298
+ );
1299
+ return `${color}\u2502${colors.reset} ${visible}${padding} ${color}\u2502${colors.reset}`;
1300
+ }
1301
+ function wrapVisibleLine(line, width) {
1302
+ if (line.length === 0) {
1303
+ return [""];
1304
+ }
1305
+ const lines = [];
1306
+ let remaining = line;
1307
+ while (visibleLength(remaining) > width) {
1308
+ const breakAt = findVisibleBreakPoint(remaining, width);
1309
+ lines.push(remaining.slice(0, breakAt).trimEnd());
1310
+ remaining = remaining.slice(breakAt).trimStart();
1311
+ }
1312
+ lines.push(remaining);
1313
+ return lines;
1314
+ }
1315
+ function findVisibleBreakPoint(input, width) {
1316
+ const slice = sliceVisible(input, width + 1);
1317
+ const lastSpace = slice.lastIndexOf(" ");
1318
+ if (lastSpace > 0) {
1319
+ return lastSpace;
1320
+ }
1321
+ return sliceVisible(input, width).length;
1322
+ }
1323
+ function extractResponseStatistics(chunk) {
1324
+ var _a, _b;
1325
+ const usage = "usage" in chunk ? chunk.usage : void 0;
1326
+ const metadataUsage = "messageMetadata" in chunk ? (_a = chunk.messageMetadata) == null ? void 0 : _a.usage : void 0;
1327
+ const metadataPerformance = "messageMetadata" in chunk ? (_b = chunk.messageMetadata) == null ? void 0 : _b.performance : void 0;
1328
+ return {
1329
+ totalTokens: extractTotalTokenCountFromUsage(usage != null ? usage : metadataUsage),
1330
+ outputTokens: extractOutputTokenCountFromUsage(usage != null ? usage : metadataUsage),
1331
+ outputTokensPerSecond: metadataPerformance == null ? void 0 : metadataPerformance.outputTokensPerSecond
1332
+ };
1333
+ }
1334
+ function extractResponseStatisticsFromMetadata(metadata) {
1335
+ var _a;
1336
+ const stats = metadata;
1337
+ return {
1338
+ totalTokens: extractTotalTokenCountFromUsage(stats == null ? void 0 : stats.usage),
1339
+ outputTokens: extractOutputTokenCountFromUsage(stats == null ? void 0 : stats.usage),
1340
+ outputTokensPerSecond: (_a = stats == null ? void 0 : stats.performance) == null ? void 0 : _a.outputTokensPerSecond
1341
+ };
1342
+ }
1343
+ function extractTotalTokenCountFromUsage(usage) {
1344
+ const totalTokens = usage == null ? void 0 : usage.totalTokens;
1345
+ if (typeof totalTokens === "number") {
1346
+ return totalTokens;
1347
+ }
1348
+ if (typeof (totalTokens == null ? void 0 : totalTokens.total) === "number") {
1349
+ return totalTokens.total;
1350
+ }
1351
+ const inputTokens = extractInputTokenCountFromUsage(usage);
1352
+ const outputTokens = extractOutputTokenCountFromUsage(usage);
1353
+ if (inputTokens != null && outputTokens != null) {
1354
+ return inputTokens + outputTokens;
1355
+ }
1356
+ return void 0;
1357
+ }
1358
+ function extractInputTokenCountFromUsage(usage) {
1359
+ const inputTokens = usage == null ? void 0 : usage.inputTokens;
1360
+ if (typeof inputTokens === "number") {
1361
+ return inputTokens;
1362
+ }
1363
+ if (typeof (inputTokens == null ? void 0 : inputTokens.total) === "number") {
1364
+ return inputTokens.total;
1365
+ }
1366
+ return usage == null ? void 0 : usage.promptTokens;
1367
+ }
1368
+ function extractOutputTokenCountFromUsage(usage) {
1369
+ const outputTokens = usage == null ? void 0 : usage.outputTokens;
1370
+ if (typeof outputTokens === "number") {
1371
+ return outputTokens;
1372
+ }
1373
+ if (typeof (outputTokens == null ? void 0 : outputTokens.total) === "number") {
1374
+ return outputTokens.total;
1375
+ }
1376
+ return usage == null ? void 0 : usage.completionTokens;
1377
+ }
1378
+ function formatTokenCount(tokens, contextSize) {
1379
+ if (tokens == null) {
1380
+ return void 0;
1381
+ }
1382
+ const tokenCount = `${tokens.toLocaleString()} ${tokens === 1 ? "token" : "tokens"}`;
1383
+ const contextPercentage = formatContextPercentage(tokens, contextSize);
1384
+ return contextPercentage == null ? tokenCount : `${tokenCount} ${contextPercentage}`;
1385
+ }
1386
+ function formatContextPercentage(tokens, contextSize) {
1387
+ if (contextSize == null || contextSize <= 0 || !Number.isFinite(contextSize)) {
1388
+ return void 0;
1389
+ }
1390
+ return `${Math.round(tokens / contextSize * 100).toLocaleString()}%`;
1391
+ }
1392
+ function formatResponseStatistics(stats, mode) {
1393
+ if (mode === "outputTokensPerSecond") {
1394
+ return formatOutputTokensPerSecond(stats.outputTokensPerSecond);
1395
+ }
1396
+ return formatTokenCount(stats.outputTokens);
1397
+ }
1398
+ function formatOutputTokensPerSecond(outputTokensPerSecond) {
1399
+ if (outputTokensPerSecond == null) {
1400
+ return void 0;
1401
+ }
1402
+ return `${formatNumber(outputTokensPerSecond)} tok/s`;
1403
+ }
1404
+ function formatNumber(value) {
1405
+ return Number.isInteger(value) ? value.toLocaleString() : value.toLocaleString(void 0, { maximumFractionDigits: 1 });
1406
+ }
1407
+ function parseKey(chunk) {
1408
+ const value = chunk.toString("utf8");
1409
+ switch (value) {
1410
+ case "\f":
1411
+ return { type: "ctrl-l" };
1412
+ case "":
1413
+ return { type: "ctrl-c" };
1414
+ case "\x1B":
1415
+ return { type: "escape" };
1416
+ case "\r":
1417
+ case "\n":
1418
+ return { type: "enter" };
1419
+ case "\x7F":
1420
+ case "\b":
1421
+ return { type: "backspace" };
1422
+ case "\x1B[A":
1423
+ return { type: "up" };
1424
+ case "\x1B[B":
1425
+ return { type: "down" };
1426
+ case "\x1B[5~":
1427
+ return { type: "page-up" };
1428
+ case "\x1B[6~":
1429
+ return { type: "page-down" };
1430
+ default:
1431
+ if (value >= " " && value !== "\x7F") {
1432
+ return { type: "character", value };
1433
+ }
1434
+ return { type: "ignore" };
1435
+ }
1436
+ }
1437
+
1438
+ // src/agent-tui-runner.ts
1439
+ import {
1440
+ convertToModelMessages,
1441
+ getToolName as getToolName2,
1442
+ isToolUIPart as isToolUIPart2
1443
+ } from "ai";
1444
+ var defaultResponseStatistics2 = "outputTokensPerSecond";
1445
+ var AgentTUIRunner = class {
1446
+ constructor(options) {
1447
+ var _a, _b, _c, _d;
1448
+ this.agent = options.agent;
1449
+ this.renderer = (_a = createRenderer(options)) != null ? _a : createDefaultRenderer(options);
1450
+ this.title = options.title;
1451
+ this.tools = (_b = options.tools) != null ? _b : "auto-collapsed";
1452
+ this.reasoning = (_c = options.reasoning) != null ? _c : "auto-collapsed";
1453
+ this.responseStatistics = (_d = options.responseStatistics) != null ? _d : defaultResponseStatistics2;
1454
+ this.contextSize = options.contextSize;
1455
+ }
1456
+ async run() {
1457
+ const title = this.title;
1458
+ const messages = [];
1459
+ let nextMessageIndex = 0;
1460
+ const generateMessageId = () => `message-${++nextMessageIndex}`;
1461
+ let prompt;
1462
+ let hasRunTurn = false;
1463
+ let streamWithoutPrompt = false;
1464
+ while (true) {
1465
+ if (!streamWithoutPrompt) {
1466
+ if (prompt == null) {
1467
+ if (!this.renderer.readPrompt) {
1468
+ if (hasRunTurn) {
1469
+ return;
1470
+ }
1471
+ throw new Error(
1472
+ "No prompt was provided and the renderer does not support prompt input."
1473
+ );
1474
+ }
1475
+ try {
1476
+ prompt = await this.renderer.readPrompt({ title });
1477
+ } catch (error) {
1478
+ if (isInterruptedError(error)) {
1479
+ return;
1480
+ }
1481
+ throw error;
1482
+ }
1483
+ if (prompt == null) {
1484
+ return;
1485
+ }
1486
+ }
1487
+ messages.push(createUserMessage(generateMessageId(), prompt));
1488
+ hasRunTurn = true;
1489
+ }
1490
+ const result = await this.streamMessages(
1491
+ [...messages],
1492
+ generateMessageId
1493
+ );
1494
+ try {
1495
+ const responseMessage = await this.renderer.renderStream(result, {
1496
+ title,
1497
+ submittedPrompt: prompt,
1498
+ continueSession: Boolean(this.renderer.readPrompt),
1499
+ tools: this.tools,
1500
+ reasoning: this.reasoning,
1501
+ responseStatistics: this.responseStatistics,
1502
+ contextSize: this.contextSize,
1503
+ waitForExit: false
1504
+ });
1505
+ if (responseMessage && responseMessage.parts.length > 0) {
1506
+ const approvalRequests = findPendingToolApprovalRequests(responseMessage);
1507
+ if (approvalRequests.length > 0) {
1508
+ if (!this.renderer.readToolApproval) {
1509
+ throw new Error(
1510
+ "Tool approval was requested, but the renderer does not support tool approval input."
1511
+ );
1512
+ }
1513
+ for (const request of approvalRequests) {
1514
+ const response = await this.renderer.readToolApproval(request, {
1515
+ title
1516
+ });
1517
+ applyToolApprovalResponse(responseMessage, request, response);
1518
+ }
1519
+ upsertResponseMessage(
1520
+ messages,
1521
+ responseMessage,
1522
+ streamWithoutPrompt
1523
+ );
1524
+ streamWithoutPrompt = true;
1525
+ prompt = void 0;
1526
+ continue;
1527
+ }
1528
+ upsertResponseMessage(messages, responseMessage, streamWithoutPrompt);
1529
+ }
1530
+ } catch (error) {
1531
+ if (isInterruptedError(error)) {
1532
+ return;
1533
+ }
1534
+ throw error;
1535
+ }
1536
+ streamWithoutPrompt = false;
1537
+ prompt = void 0;
1538
+ }
1539
+ }
1540
+ async streamMessages(messages, generateMessageId) {
1541
+ const abortController = new AbortController();
1542
+ const result = await this.agent.stream({
1543
+ prompt: await convertToModelMessages(messages, {
1544
+ tools: this.agent.tools
1545
+ }),
1546
+ abortSignal: abortController.signal,
1547
+ options: void 0
1548
+ });
1549
+ return {
1550
+ uiMessageStream: textStreamToUIMessageStream(
1551
+ result.fullStream,
1552
+ generateMessageId,
1553
+ messages
1554
+ ),
1555
+ message: lastAssistantMessage(messages),
1556
+ abort: () => abortController.abort()
1557
+ };
1558
+ }
1559
+ };
1560
+ function createDefaultRenderer(options) {
1561
+ return options.tools === void 0 && options.reasoning === void 0 && options.responseStatistics === void 0 && options.contextSize === void 0 ? new TerminalRenderer() : new TerminalRenderer({
1562
+ tools: options.tools,
1563
+ reasoning: options.reasoning,
1564
+ responseStatistics: options.responseStatistics,
1565
+ contextSize: options.contextSize
1566
+ });
1567
+ }
1568
+ function createRenderer(options) {
1569
+ if (options.renderer) {
1570
+ return options.renderer;
1571
+ }
1572
+ if (!options.screen && !options.userInput) {
1573
+ return void 0;
1574
+ }
1575
+ return new TerminalRenderer({
1576
+ tools: options.tools,
1577
+ reasoning: options.reasoning,
1578
+ responseStatistics: options.responseStatistics,
1579
+ contextSize: options.contextSize,
1580
+ input: options.userInput,
1581
+ output: options.screen
1582
+ });
1583
+ }
1584
+ async function* textStreamToUIMessageStream(stream, generateMessageId, originalMessages = []) {
1585
+ var _a, _b;
1586
+ const openTextParts = /* @__PURE__ */ new Set();
1587
+ const openReasoningParts = /* @__PURE__ */ new Set();
1588
+ const openToolCalls = /* @__PURE__ */ new Set();
1589
+ let latestStepUsage;
1590
+ let latestPerformance;
1591
+ let sentFinish = false;
1592
+ yield {
1593
+ type: "start",
1594
+ messageId: (_b = (_a = lastAssistantMessage(originalMessages)) == null ? void 0 : _a.id) != null ? _b : generateMessageId()
1595
+ };
1596
+ for await (const part of stream) {
1597
+ switch (part.type) {
1598
+ case "text-start":
1599
+ openTextParts.add(part.id);
1600
+ yield {
1601
+ type: "text-start",
1602
+ id: part.id,
1603
+ providerMetadata: part.providerMetadata
1604
+ };
1605
+ break;
1606
+ case "text-delta":
1607
+ if (!openTextParts.has(part.id)) {
1608
+ openTextParts.add(part.id);
1609
+ yield {
1610
+ type: "text-start",
1611
+ id: part.id,
1612
+ providerMetadata: part.providerMetadata
1613
+ };
1614
+ }
1615
+ yield {
1616
+ type: "text-delta",
1617
+ id: part.id,
1618
+ delta: part.text,
1619
+ providerMetadata: part.providerMetadata
1620
+ };
1621
+ break;
1622
+ case "text-end":
1623
+ openTextParts.delete(part.id);
1624
+ yield {
1625
+ type: "text-end",
1626
+ id: part.id,
1627
+ providerMetadata: part.providerMetadata
1628
+ };
1629
+ break;
1630
+ case "reasoning-start":
1631
+ openReasoningParts.add(part.id);
1632
+ yield {
1633
+ type: "reasoning-start",
1634
+ id: part.id,
1635
+ providerMetadata: part.providerMetadata
1636
+ };
1637
+ break;
1638
+ case "reasoning-delta":
1639
+ if (!openReasoningParts.has(part.id)) {
1640
+ openReasoningParts.add(part.id);
1641
+ yield {
1642
+ type: "reasoning-start",
1643
+ id: part.id,
1644
+ providerMetadata: part.providerMetadata
1645
+ };
1646
+ }
1647
+ yield {
1648
+ type: "reasoning-delta",
1649
+ id: part.id,
1650
+ delta: part.text,
1651
+ providerMetadata: part.providerMetadata
1652
+ };
1653
+ break;
1654
+ case "reasoning-end":
1655
+ openReasoningParts.delete(part.id);
1656
+ yield {
1657
+ type: "reasoning-end",
1658
+ id: part.id,
1659
+ providerMetadata: part.providerMetadata
1660
+ };
1661
+ break;
1662
+ case "tool-input-start":
1663
+ yield {
1664
+ type: "tool-input-start",
1665
+ toolCallId: part.id,
1666
+ toolName: part.toolName,
1667
+ providerExecuted: part.providerExecuted,
1668
+ providerMetadata: part.providerMetadata,
1669
+ toolMetadata: part.toolMetadata,
1670
+ dynamic: part.dynamic,
1671
+ title: part.title
1672
+ };
1673
+ break;
1674
+ case "tool-input-delta":
1675
+ yield {
1676
+ type: "tool-input-delta",
1677
+ toolCallId: part.id,
1678
+ inputTextDelta: part.delta
1679
+ };
1680
+ break;
1681
+ case "tool-call":
1682
+ openToolCalls.add(part.toolCallId);
1683
+ yield {
1684
+ type: "tool-input-available",
1685
+ toolCallId: part.toolCallId,
1686
+ toolName: part.toolName,
1687
+ input: part.input,
1688
+ providerExecuted: part.providerExecuted,
1689
+ providerMetadata: part.providerMetadata,
1690
+ toolMetadata: part.toolMetadata,
1691
+ dynamic: part.dynamic,
1692
+ title: part.title
1693
+ };
1694
+ break;
1695
+ case "tool-approval-request":
1696
+ if (!openToolCalls.has(part.toolCall.toolCallId)) {
1697
+ openToolCalls.add(part.toolCall.toolCallId);
1698
+ yield {
1699
+ type: "tool-input-available",
1700
+ toolCallId: part.toolCall.toolCallId,
1701
+ toolName: part.toolCall.toolName,
1702
+ input: part.toolCall.input,
1703
+ providerExecuted: part.toolCall.providerExecuted,
1704
+ providerMetadata: part.toolCall.providerMetadata,
1705
+ toolMetadata: part.toolCall.toolMetadata,
1706
+ dynamic: part.toolCall.dynamic,
1707
+ title: part.toolCall.title
1708
+ };
1709
+ }
1710
+ yield {
1711
+ type: "tool-approval-request",
1712
+ approvalId: part.approvalId,
1713
+ toolCallId: part.toolCall.toolCallId,
1714
+ isAutomatic: part.isAutomatic
1715
+ };
1716
+ break;
1717
+ case "tool-approval-response":
1718
+ yield {
1719
+ type: "tool-approval-response",
1720
+ approvalId: part.approvalId,
1721
+ approved: part.approved,
1722
+ reason: part.reason,
1723
+ providerExecuted: part.providerExecuted
1724
+ };
1725
+ break;
1726
+ case "tool-result":
1727
+ yield {
1728
+ type: "tool-output-available",
1729
+ toolCallId: part.toolCallId,
1730
+ output: part.output,
1731
+ providerExecuted: part.providerExecuted,
1732
+ providerMetadata: part.providerMetadata,
1733
+ toolMetadata: part.toolMetadata,
1734
+ dynamic: part.dynamic,
1735
+ preliminary: part.preliminary
1736
+ };
1737
+ break;
1738
+ case "tool-error":
1739
+ yield {
1740
+ type: "tool-output-error",
1741
+ toolCallId: part.toolCallId,
1742
+ errorText: formatStreamError2(part.error),
1743
+ providerExecuted: part.providerExecuted,
1744
+ providerMetadata: part.providerMetadata,
1745
+ toolMetadata: part.toolMetadata,
1746
+ dynamic: part.dynamic
1747
+ };
1748
+ break;
1749
+ case "tool-output-denied":
1750
+ yield { type: "tool-output-denied", toolCallId: part.toolCallId };
1751
+ break;
1752
+ case "source":
1753
+ if (part.sourceType === "url") {
1754
+ yield {
1755
+ type: "source-url",
1756
+ sourceId: part.id,
1757
+ url: part.url,
1758
+ title: part.title,
1759
+ providerMetadata: part.providerMetadata
1760
+ };
1761
+ } else {
1762
+ yield {
1763
+ type: "source-document",
1764
+ sourceId: part.id,
1765
+ mediaType: part.mediaType,
1766
+ title: part.title,
1767
+ filename: part.filename,
1768
+ providerMetadata: part.providerMetadata
1769
+ };
1770
+ }
1771
+ break;
1772
+ case "file":
1773
+ yield {
1774
+ type: "file",
1775
+ url: fileToDataUrl(part.file.mediaType, part.file.base64),
1776
+ mediaType: part.file.mediaType,
1777
+ providerMetadata: part.providerMetadata
1778
+ };
1779
+ break;
1780
+ case "reasoning-file":
1781
+ yield {
1782
+ type: "reasoning-file",
1783
+ url: fileToDataUrl(part.file.mediaType, part.file.base64),
1784
+ mediaType: part.file.mediaType,
1785
+ providerMetadata: part.providerMetadata
1786
+ };
1787
+ break;
1788
+ case "start-step":
1789
+ yield { type: "start-step" };
1790
+ break;
1791
+ case "finish-step":
1792
+ latestStepUsage = part.usage;
1793
+ latestPerformance = part.performance;
1794
+ yield { type: "finish-step" };
1795
+ break;
1796
+ case "finish":
1797
+ yield* closeOpenParts(openTextParts, openReasoningParts);
1798
+ sentFinish = true;
1799
+ yield {
1800
+ type: "finish",
1801
+ finishReason: part.finishReason,
1802
+ messageMetadata: createResponseMetadata(
1803
+ latestStepUsage != null ? latestStepUsage : part.totalUsage,
1804
+ latestPerformance
1805
+ )
1806
+ };
1807
+ break;
1808
+ case "abort":
1809
+ yield { type: "abort", reason: part.reason };
1810
+ break;
1811
+ case "error":
1812
+ yield { type: "error", errorText: formatStreamError2(part.error) };
1813
+ break;
1814
+ }
1815
+ }
1816
+ if (!sentFinish) {
1817
+ yield* closeOpenParts(openTextParts, openReasoningParts);
1818
+ yield { type: "finish" };
1819
+ }
1820
+ }
1821
+ function createResponseMetadata(usage, performance) {
1822
+ if ((usage == null ? void 0 : usage.totalTokens) == null && (usage == null ? void 0 : usage.outputTokens) == null && (performance == null ? void 0 : performance.outputTokensPerSecond) == null) {
1823
+ return void 0;
1824
+ }
1825
+ return {
1826
+ ...(usage == null ? void 0 : usage.totalTokens) == null && (usage == null ? void 0 : usage.outputTokens) == null ? {} : {
1827
+ usage: {
1828
+ ...usage.totalTokens == null ? {} : { totalTokens: usage.totalTokens },
1829
+ ...usage.outputTokens == null ? {} : { outputTokens: usage.outputTokens }
1830
+ }
1831
+ },
1832
+ ...(performance == null ? void 0 : performance.outputTokensPerSecond) == null ? {} : {
1833
+ performance: {
1834
+ outputTokensPerSecond: performance.outputTokensPerSecond
1835
+ }
1836
+ }
1837
+ };
1838
+ }
1839
+ function* closeOpenParts(textPartIds, reasoningPartIds) {
1840
+ for (const id of textPartIds) {
1841
+ yield { type: "text-end", id };
1842
+ }
1843
+ textPartIds.clear();
1844
+ for (const id of reasoningPartIds) {
1845
+ yield { type: "reasoning-end", id };
1846
+ }
1847
+ reasoningPartIds.clear();
1848
+ }
1849
+ function createUserMessage(id, text) {
1850
+ return {
1851
+ id,
1852
+ role: "user",
1853
+ parts: [{ type: "text", text }]
1854
+ };
1855
+ }
1856
+ function upsertResponseMessage(messages, responseMessage, replaceLast) {
1857
+ var _a;
1858
+ if (replaceLast && ((_a = messages.at(-1)) == null ? void 0 : _a.role) === "assistant") {
1859
+ messages[messages.length - 1] = responseMessage;
1860
+ return;
1861
+ }
1862
+ messages.push(responseMessage);
1863
+ }
1864
+ function lastAssistantMessage(messages) {
1865
+ const message = messages.at(-1);
1866
+ return (message == null ? void 0 : message.role) === "assistant" ? message : void 0;
1867
+ }
1868
+ function findPendingToolApprovalRequests(message) {
1869
+ const requests = [];
1870
+ for (const [index, part] of message.parts.entries()) {
1871
+ if (!isToolUIPart2(part) || part.state !== "approval-requested" || part.approval.isAutomatic === true) {
1872
+ continue;
1873
+ }
1874
+ requests.push({
1875
+ approvalId: part.approval.id,
1876
+ toolCallId: part.toolCallId,
1877
+ toolName: getToolName2(part),
1878
+ title: part.title,
1879
+ input: part.input,
1880
+ providerExecuted: part.providerExecuted,
1881
+ messageId: message.id,
1882
+ partIndex: index
1883
+ });
1884
+ }
1885
+ return requests;
1886
+ }
1887
+ function applyToolApprovalResponse(message, request, response) {
1888
+ const part = message.parts[request.partIndex];
1889
+ if (!part || !isToolUIPart2(part) || part.toolCallId !== request.toolCallId) {
1890
+ throw new Error(
1891
+ `Could not find tool approval request ${request.approvalId}.`
1892
+ );
1893
+ }
1894
+ part.state = "approval-responded";
1895
+ part.approval = {
1896
+ id: request.approvalId,
1897
+ approved: response.approved,
1898
+ ...response.reason ? { reason: response.reason } : {}
1899
+ };
1900
+ }
1901
+ function formatStreamError2(error) {
1902
+ if (error instanceof Error) {
1903
+ return error.message;
1904
+ }
1905
+ if (typeof error === "string") {
1906
+ return error;
1907
+ }
1908
+ return JSON.stringify(error);
1909
+ }
1910
+ function fileToDataUrl(mediaType, base64) {
1911
+ return `data:${mediaType};base64,${base64}`;
1912
+ }
1913
+ function isInterruptedError(error) {
1914
+ return error instanceof Error && error.message === "Interrupted";
1915
+ }
1916
+
1917
+ // src/run-agent-tui.ts
1918
+ async function runAgentTUI(options) {
1919
+ await new AgentTUIRunner(options).run();
1920
+ }
1921
+ export {
1922
+ runAgentTUI
1923
+ };
1924
+ //# sourceMappingURL=index.js.map