@ai-sdk/tui 1.0.115 → 1.0.118

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 CHANGED
@@ -1,12 +1,3 @@
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
1
  // src/tui/terminal-text.ts
11
2
  var ansiEscape = String.fromCharCode(27);
12
3
  var ansiPattern = new RegExp(`${ansiEscape}\\[[0-?]*[ -/]*[@-~]`, "g");
@@ -97,7 +88,6 @@ var ansi = {
97
88
  };
98
89
  var tableSeparator = "\u2500";
99
90
  function renderMarkdown(input) {
100
- var _a;
101
91
  const lines = input.split("\n");
102
92
  const output = [];
103
93
  for (let index = 0; index < lines.length; index += 1) {
@@ -107,7 +97,7 @@ function renderMarkdown(input) {
107
97
  index = table.endIndex - 1;
108
98
  continue;
109
99
  }
110
- output.push(renderMarkdownLine((_a = lines[index]) != null ? _a : ""));
100
+ output.push(renderMarkdownLine(lines[index] ?? ""));
111
101
  }
112
102
  return output.join("\n");
113
103
  }
@@ -140,12 +130,11 @@ function renderInlineMarkdown(input) {
140
130
  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
131
  }
142
132
  function parseTable(lines, startIndex) {
143
- var _a, _b, _c;
144
- const header = parseTableCells((_a = lines[startIndex]) != null ? _a : "");
133
+ const header = parseTableCells(lines[startIndex] ?? "");
145
134
  if (header == null || header.length < 2) {
146
135
  return void 0;
147
136
  }
148
- const separatorCells = parseTableCells((_b = lines[startIndex + 1]) != null ? _b : "");
137
+ const separatorCells = parseTableCells(lines[startIndex + 1] ?? "");
149
138
  if (separatorCells == null || separatorCells.length !== header.length) {
150
139
  return void 0;
151
140
  }
@@ -156,7 +145,7 @@ function parseTable(lines, startIndex) {
156
145
  const rows = [];
157
146
  let endIndex = startIndex + 2;
158
147
  while (endIndex < lines.length) {
159
- const row = parseTableCells((_c = lines[endIndex]) != null ? _c : "");
148
+ const row = parseTableCells(lines[endIndex] ?? "");
160
149
  if (row == null) {
161
150
  break;
162
151
  }
@@ -216,10 +205,7 @@ function parseTableAlignments(cells) {
216
205
  return alignments;
217
206
  }
218
207
  function normalizeTableRow(row, length) {
219
- return Array.from({ length }, (_, index) => {
220
- var _a;
221
- return (_a = row[index]) != null ? _a : "";
222
- });
208
+ return Array.from({ length }, (_, index) => row[index] ?? "");
223
209
  }
224
210
  function renderTable(table) {
225
211
  const header = table.header.map(
@@ -228,10 +214,7 @@ function renderTable(table) {
228
214
  const rows = table.rows.map((row) => row.map(renderInlineMarkdown));
229
215
  const tableRows = [header, ...rows];
230
216
  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
- }))
217
+ (_, columnIndex) => Math.max(3, ...tableRows.map((row) => visibleLength(row[columnIndex] ?? "")))
235
218
  );
236
219
  return [
237
220
  formatTableRow(header, widths, table.alignments),
@@ -241,10 +224,7 @@ function renderTable(table) {
241
224
  }
242
225
  function formatTableRow(row, widths, alignments) {
243
226
  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
- }
227
+ (cell, index) => alignTableCell(cell, widths[index] ?? 0, alignments[index] ?? "left")
248
228
  ).join(" ");
249
229
  }
250
230
  function alignTableCell(cell, width, alignment) {
@@ -263,7 +243,6 @@ function alignTableCell(cell, width, alignment) {
263
243
  // src/tui/layout.ts
264
244
  var horizontal = "\u2500";
265
245
  function renderScreenViewport(state) {
266
- var _a;
267
246
  const width = Math.max(20, state.width);
268
247
  const height = Math.max(8, state.height);
269
248
  const inputHeight = 3;
@@ -279,7 +258,7 @@ function renderScreenViewport(state) {
279
258
  bottomBorder(width),
280
259
  topBorder(width, state.inputActive ? "Input" : "Status"),
281
260
  boxLine(
282
- state.inputActive ? `> ${state.input}${state.inputCursorVisible === false ? " " : "\u2588"}` : (_a = state.status) != null ? _a : "Streaming... \u2191/\u2193 scroll \xB7 Ctrl+C quit",
261
+ state.inputActive ? `> ${state.input}${state.inputCursorVisible === false ? " " : "\u2588"}` : state.status ?? "Streaming... \u2191/\u2193 scroll \xB7 Ctrl+C quit",
283
262
  width
284
263
  ),
285
264
  bottomBorder(width)
@@ -318,55 +297,46 @@ var clearScreen = `${escape}[2J`;
318
297
  var clearLine = `${escape}[2K`;
319
298
  var synchronizeStart = `${escape}[?2026h`;
320
299
  var synchronizeEnd = `${escape}[?2026l`;
321
- var _useSynchronizedUpdates, _originalWrite, _previousFrame, _isWritingFrame, _externalWriteSinceLastFrame, _TerminalFrameBuffer_instances, writeUpdate_fn;
322
300
  var TerminalFrameBuffer = class {
301
+ #useSynchronizedUpdates;
302
+ #originalWrite;
303
+ #previousFrame;
304
+ #isWritingFrame = false;
305
+ #externalWriteSinceLastFrame = false;
323
306
  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);
307
+ this.#originalWrite = output.write.bind(output);
308
+ this.#useSynchronizedUpdates = options?.useSynchronizedUpdates ?? true;
333
309
  output.write = ((chunk, encodingOrCallback, callback) => {
334
- if (!__privateGet(this, _isWritingFrame)) {
335
- __privateSet(this, _externalWriteSinceLastFrame, true);
310
+ if (!this.#isWritingFrame) {
311
+ this.#externalWriteSinceLastFrame = true;
336
312
  }
337
- return __privateGet(this, _originalWrite).call(this, chunk, encodingOrCallback, callback);
313
+ return this.#originalWrite(chunk, encodingOrCallback, callback);
338
314
  });
339
315
  }
340
316
  present(frame) {
341
317
  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);
318
+ const update = this.#previousFrame && !this.#externalWriteSinceLastFrame ? diffFrame(this.#previousFrame, nextFrame) : `${cursorHome}${clearScreen}${frame}`;
319
+ this.#previousFrame = nextFrame;
320
+ this.#externalWriteSinceLastFrame = false;
345
321
  if (update.length === 0) {
346
322
  return;
347
323
  }
348
- __privateMethod(this, _TerminalFrameBuffer_instances, writeUpdate_fn).call(this, update);
324
+ this.#writeUpdate(update);
349
325
  }
350
326
  reset() {
351
- __privateSet(this, _previousFrame, void 0);
327
+ this.#previousFrame = void 0;
352
328
  }
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;
329
+ #writeUpdate(update) {
330
+ this.#isWritingFrame = true;
331
+ try {
332
+ if (!this.#useSynchronizedUpdates) {
333
+ this.#originalWrite(update);
334
+ return;
335
+ }
336
+ this.#originalWrite(`${synchronizeStart}${update}${synchronizeEnd}`);
337
+ } finally {
338
+ this.#isWritingFrame = false;
366
339
  }
367
- __privateGet(this, _originalWrite).call(this, `${synchronizeStart}${update}${synchronizeEnd}`);
368
- } finally {
369
- __privateSet(this, _isWritingFrame, false);
370
340
  }
371
341
  };
372
342
  function snapshotFrame(frame) {
@@ -383,7 +353,7 @@ function diffFrame(previousFrame, nextFrame) {
383
353
  if (previousFrame.lines[index] === line) {
384
354
  continue;
385
355
  }
386
- output += `${escape}[${index + 1};1H${clearLine}${line != null ? line : ""}`;
356
+ output += `${escape}[${index + 1};1H${clearLine}${line ?? ""}`;
387
357
  }
388
358
  return output;
389
359
  }
@@ -421,607 +391,575 @@ var processingStatus = `Processing input... ${activeControls}`;
421
391
  var processingToolResultsStatus = `Processing tool results... ${activeControls}`;
422
392
  var streamingStatus = `Streaming... ${activeControls}`;
423
393
  var executingToolsStatus = `Executing tools... ${activeControls}`;
424
- 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;
425
394
  var TerminalRenderer = class {
395
+ #input;
396
+ #output;
397
+ #frameBuffer;
398
+ #tools;
399
+ #reasoning;
400
+ #responseStatistics;
401
+ #defaultContextSize;
402
+ #sections = [];
403
+ #inputText = "";
404
+ #inputActive = false;
405
+ #scrollOffset = 0;
406
+ #title = "";
407
+ #status = streamingStatus;
408
+ #isInteractive = false;
409
+ #interrupted = false;
410
+ #totalTokens;
411
+ #contextSize;
412
+ #assistantOutputTokens;
413
+ #assistantOutputTokensPerSecond;
414
+ #inputCursorVisible = true;
415
+ #inputCursorTimer;
416
+ #onData;
417
+ #onResize;
418
+ #resolveStreamInterrupt;
426
419
  constructor(options) {
427
- __privateAdd(this, _TerminalRenderer_instances);
428
- __privateAdd(this, _input);
429
- __privateAdd(this, _output);
430
- __privateAdd(this, _frameBuffer);
431
- __privateAdd(this, _tools);
432
- __privateAdd(this, _reasoning);
433
- __privateAdd(this, _responseStatistics);
434
- __privateAdd(this, _defaultContextSize);
435
- __privateAdd(this, _sections, []);
436
- __privateAdd(this, _inputText, "");
437
- __privateAdd(this, _inputActive, false);
438
- __privateAdd(this, _scrollOffset, 0);
439
- __privateAdd(this, _title, "");
440
- __privateAdd(this, _status, streamingStatus);
441
- __privateAdd(this, _isInteractive, false);
442
- __privateAdd(this, _interrupted, false);
443
- __privateAdd(this, _totalTokens);
444
- __privateAdd(this, _contextSize);
445
- __privateAdd(this, _assistantOutputTokens);
446
- __privateAdd(this, _assistantOutputTokensPerSecond);
447
- __privateAdd(this, _inputCursorVisible, true);
448
- __privateAdd(this, _inputCursorTimer);
449
- __privateAdd(this, _onData);
450
- __privateAdd(this, _onResize);
451
- __privateAdd(this, _resolveStreamInterrupt);
452
- var _a, _b, _c, _d, _e, _f;
453
- __privateSet(this, _input, (_a = options == null ? void 0 : options.input) != null ? _a : process.stdin);
454
- __privateSet(this, _output, (_b = options == null ? void 0 : options.output) != null ? _b : process.stdout);
455
- __privateSet(this, _frameBuffer, (_c = options == null ? void 0 : options.frameBuffer) != null ? _c : new TerminalFrameBuffer(__privateGet(this, _output)));
456
- __privateSet(this, _tools, (_d = options == null ? void 0 : options.tools) != null ? _d : "auto-collapsed");
457
- __privateSet(this, _reasoning, (_e = options == null ? void 0 : options.reasoning) != null ? _e : "auto-collapsed");
458
- __privateSet(this, _responseStatistics, (_f = options == null ? void 0 : options.responseStatistics) != null ? _f : defaultResponseStatistics);
459
- __privateSet(this, _defaultContextSize, options == null ? void 0 : options.contextSize);
460
- __privateSet(this, _contextSize, options == null ? void 0 : options.contextSize);
420
+ this.#input = options?.input ?? process.stdin;
421
+ this.#output = options?.output ?? process.stdout;
422
+ this.#frameBuffer = options?.frameBuffer ?? new TerminalFrameBuffer(this.#output);
423
+ this.#tools = options?.tools ?? "auto-collapsed";
424
+ this.#reasoning = options?.reasoning ?? "auto-collapsed";
425
+ this.#responseStatistics = options?.responseStatistics ?? defaultResponseStatistics;
426
+ this.#defaultContextSize = options?.contextSize;
427
+ this.#contextSize = options?.contextSize;
461
428
  }
462
429
  async readPrompt(options) {
463
- var _a;
464
- __privateMethod(this, _TerminalRenderer_instances, start_fn).call(this, options);
465
- __privateSet(this, _inputActive, true);
466
- __privateSet(this, _inputText, (_a = options == null ? void 0 : options.initialPrompt) != null ? _a : "");
467
- __privateSet(this, _status, `Type a prompt and press Enter \xB7 ${activeControls}`);
468
- __privateMethod(this, _TerminalRenderer_instances, startInputCursorBlink_fn).call(this);
469
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
430
+ this.#start(options);
431
+ this.#inputActive = true;
432
+ this.#inputText = options?.initialPrompt ?? "";
433
+ this.#status = `Type a prompt and press Enter \xB7 ${activeControls}`;
434
+ this.#startInputCursorBlink();
435
+ this.#paint();
470
436
  return await new Promise((resolve, reject) => {
471
- __privateSet(this, _onData, (chunk) => {
437
+ this.#onData = (chunk) => {
472
438
  const key = parseKey(chunk);
473
439
  switch (key.type) {
474
440
  case "character":
475
- __privateSet(this, _inputText, __privateGet(this, _inputText) + key.value);
476
- __privateMethod(this, _TerminalRenderer_instances, showInputCursor_fn).call(this);
477
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
441
+ this.#inputText += key.value;
442
+ this.#showInputCursor();
443
+ this.#paint();
478
444
  break;
479
445
  case "backspace":
480
- __privateSet(this, _inputText, removeLastGrapheme(__privateGet(this, _inputText)));
481
- __privateMethod(this, _TerminalRenderer_instances, showInputCursor_fn).call(this);
482
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
446
+ this.#inputText = removeLastGrapheme(this.#inputText);
447
+ this.#showInputCursor();
448
+ this.#paint();
483
449
  break;
484
450
  case "enter": {
485
- const prompt = __privateGet(this, _inputText);
486
- __privateSet(this, _inputActive, false);
487
- __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
488
- __privateSet(this, _status, processingStatus);
489
- __privateMethod(this, _TerminalRenderer_instances, addUserSection_fn).call(this, prompt);
490
- __privateSet(this, _inputText, "");
491
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
492
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
451
+ const prompt = this.#inputText;
452
+ this.#inputActive = false;
453
+ this.#stopInputCursorBlink();
454
+ this.#status = processingStatus;
455
+ this.#addUserSection(prompt);
456
+ this.#inputText = "";
457
+ this.#paint();
458
+ this.#detachInput();
493
459
  resolve(prompt);
494
460
  break;
495
461
  }
496
462
  case "up":
497
463
  case "down":
498
- __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
464
+ this.#handleScroll(key.type);
499
465
  break;
500
466
  case "page-up":
501
467
  case "page-down":
502
- __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
468
+ this.#handlePageScroll(key.type);
503
469
  break;
504
470
  case "ctrl-l":
505
- __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
471
+ this.#repaint();
506
472
  break;
507
473
  case "escape":
508
474
  case "ctrl-c":
509
- __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
510
- __privateMethod(this, _TerminalRenderer_instances, stop_fn).call(this);
475
+ this.#stopInputCursorBlink();
476
+ this.#stop();
511
477
  reject(interruptedError());
512
478
  break;
513
479
  case "ignore":
514
480
  break;
515
481
  }
516
- });
517
- __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
482
+ };
483
+ this.#attachInput();
518
484
  });
519
485
  }
520
486
  async renderStream(result, options) {
521
- var _a, _b, _c, _d;
522
- __privateMethod(this, _TerminalRenderer_instances, start_fn).call(this, options);
523
- __privateSet(this, _inputActive, false);
524
- __privateSet(this, _status, processingStatus);
525
- __privateMethod(this, _TerminalRenderer_instances, addSubmittedPrompt_fn).call(this, options == null ? void 0 : options.submittedPrompt);
526
- __privateSet(this, _interrupted, false);
527
- __privateSet(this, _totalTokens, void 0);
528
- __privateSet(this, _assistantOutputTokens, void 0);
529
- __privateSet(this, _assistantOutputTokensPerSecond, void 0);
487
+ this.#start(options);
488
+ this.#inputActive = false;
489
+ this.#status = processingStatus;
490
+ this.#addSubmittedPrompt(options?.submittedPrompt);
491
+ this.#interrupted = false;
492
+ this.#totalTokens = void 0;
493
+ this.#assistantOutputTokens = void 0;
494
+ this.#assistantOutputTokensPerSecond = void 0;
530
495
  const displayModes = {
531
- tools: (_a = options == null ? void 0 : options.tools) != null ? _a : __privateGet(this, _tools),
532
- reasoning: (_b = options == null ? void 0 : options.reasoning) != null ? _b : __privateGet(this, _reasoning),
533
- responseStatistics: (_c = options == null ? void 0 : options.responseStatistics) != null ? _c : __privateGet(this, _responseStatistics)
496
+ tools: options?.tools ?? this.#tools,
497
+ reasoning: options?.reasoning ?? this.#reasoning,
498
+ responseStatistics: options?.responseStatistics ?? this.#responseStatistics
534
499
  };
535
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
500
+ this.#paint();
536
501
  const streamInterrupted = new Promise((resolve) => {
537
- __privateSet(this, _resolveStreamInterrupt, resolve);
502
+ this.#resolveStreamInterrupt = resolve;
538
503
  });
539
- __privateSet(this, _onData, (chunk) => __privateMethod(this, _TerminalRenderer_instances, handleStreamingKey_fn).call(this, chunk));
540
- __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
504
+ this.#onData = (chunk) => this.#handleStreamingKey(chunk);
505
+ this.#attachInput();
541
506
  let responseMessage;
542
507
  const stream = toReadableStream(
543
- __privateMethod(this, _TerminalRenderer_instances, observeUIMessageStream_fn).call(this, result.uiMessageStream)
508
+ this.#observeUIMessageStream(result.uiMessageStream)
544
509
  );
545
510
  try {
546
511
  const messages = readUIMessageStream({
547
512
  message: result.message,
548
513
  stream,
549
- onError: (error) => __privateMethod(this, _TerminalRenderer_instances, addErrorSection_fn).call(this, "Error", formatStreamError(error))
514
+ onError: (error) => this.#addErrorSection("Error", formatStreamError(error))
550
515
  });
551
516
  for await (const message of takeUntil(messages, streamInterrupted)) {
552
- if (__privateGet(this, _interrupted)) {
517
+ if (this.#interrupted) {
553
518
  break;
554
519
  }
555
520
  responseMessage = message;
556
- __privateMethod(this, _TerminalRenderer_instances, renderAssistantMessage_fn).call(this, message, displayModes);
521
+ this.#renderAssistantMessage(message, displayModes);
557
522
  }
558
- if (!__privateGet(this, _interrupted) && responseMessage && __privateGet(this, _assistantOutputTokens) != null) {
559
- __privateMethod(this, _TerminalRenderer_instances, renderAssistantMessage_fn).call(this, responseMessage, displayModes);
523
+ if (!this.#interrupted && responseMessage && this.#assistantOutputTokens != null) {
524
+ this.#renderAssistantMessage(responseMessage, displayModes);
560
525
  }
561
526
  } finally {
562
- __privateSet(this, _resolveStreamInterrupt, void 0);
563
- if (__privateGet(this, _interrupted)) {
564
- (_d = result.abort) == null ? void 0 : _d.call(result);
527
+ this.#resolveStreamInterrupt = void 0;
528
+ if (this.#interrupted) {
529
+ result.abort?.();
565
530
  }
566
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
567
- __privateSet(this, _status, __privateGet(this, _interrupted) ? "Interrupted" : (options == null ? void 0 : options.continueSession) ? `Done \xB7 Enter another prompt \xB7 ${activeControls}` : `Done \xB7 ${doneControls}`);
568
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
569
- await __privateMethod(this, _TerminalRenderer_instances, waitForExit_fn).call(this, options);
570
- if (__privateGet(this, _interrupted) || !(options == null ? void 0 : options.continueSession)) {
571
- __privateMethod(this, _TerminalRenderer_instances, stop_fn).call(this);
531
+ this.#detachInput();
532
+ this.#status = this.#interrupted ? "Interrupted" : options?.continueSession ? `Done \xB7 Enter another prompt \xB7 ${activeControls}` : `Done \xB7 ${doneControls}`;
533
+ this.#paint();
534
+ await this.#waitForExit(options);
535
+ if (this.#interrupted || !options?.continueSession) {
536
+ this.#stop();
572
537
  }
573
538
  }
574
- if (__privateGet(this, _interrupted)) {
539
+ if (this.#interrupted) {
575
540
  throw interruptedError();
576
541
  }
577
542
  return responseMessage;
578
543
  }
579
544
  async readToolApproval(request, options) {
580
- __privateMethod(this, _TerminalRenderer_instances, start_fn).call(this, options);
581
- __privateSet(this, _inputActive, false);
582
- __privateSet(this, _status, `Approve ${formatToolApprovalTitle(request)}? y/n \xB7 ${activeControls}`);
583
- __privateSet(this, _interrupted, false);
584
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
545
+ this.#start(options);
546
+ this.#inputActive = false;
547
+ this.#status = `Approve ${formatToolApprovalTitle(request)}? y/n \xB7 ${activeControls}`;
548
+ this.#interrupted = false;
549
+ this.#paint();
585
550
  return await new Promise((resolve, reject) => {
586
- __privateSet(this, _onData, (chunk) => {
551
+ this.#onData = (chunk) => {
587
552
  const key = parseKey(chunk);
588
553
  switch (key.type) {
589
554
  case "character": {
590
555
  const value = key.value.toLowerCase();
591
556
  if (value === "y") {
592
- __privateSet(this, _status, `Approved \xB7 ${processingStatus}`);
593
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
594
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
557
+ this.#status = `Approved \xB7 ${processingStatus}`;
558
+ this.#detachInput();
559
+ this.#paint();
595
560
  resolve({ approved: true });
596
561
  } else if (value === "n") {
597
- __privateSet(this, _status, `Denied \xB7 ${processingStatus}`);
598
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
599
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
562
+ this.#status = `Denied \xB7 ${processingStatus}`;
563
+ this.#detachInput();
564
+ this.#paint();
600
565
  resolve({ approved: false, reason: "Denied by user." });
601
566
  }
602
567
  break;
603
568
  }
604
569
  case "up":
605
570
  case "down":
606
- __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
571
+ this.#handleScroll(key.type);
607
572
  break;
608
573
  case "page-up":
609
574
  case "page-down":
610
- __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
575
+ this.#handlePageScroll(key.type);
611
576
  break;
612
577
  case "ctrl-l":
613
- __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
578
+ this.#repaint();
614
579
  break;
615
580
  case "escape":
616
581
  case "ctrl-c":
617
- __privateSet(this, _interrupted, true);
618
- __privateMethod(this, _TerminalRenderer_instances, stop_fn).call(this);
582
+ this.#interrupted = true;
583
+ this.#stop();
619
584
  reject(interruptedError());
620
585
  break;
621
586
  default:
622
587
  break;
623
588
  }
624
- });
625
- __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
589
+ };
590
+ this.#attachInput();
626
591
  });
627
592
  }
628
- };
629
- _input = new WeakMap();
630
- _output = new WeakMap();
631
- _frameBuffer = new WeakMap();
632
- _tools = new WeakMap();
633
- _reasoning = new WeakMap();
634
- _responseStatistics = new WeakMap();
635
- _defaultContextSize = new WeakMap();
636
- _sections = new WeakMap();
637
- _inputText = new WeakMap();
638
- _inputActive = new WeakMap();
639
- _scrollOffset = new WeakMap();
640
- _title = new WeakMap();
641
- _status = new WeakMap();
642
- _isInteractive = new WeakMap();
643
- _interrupted = new WeakMap();
644
- _totalTokens = new WeakMap();
645
- _contextSize = new WeakMap();
646
- _assistantOutputTokens = new WeakMap();
647
- _assistantOutputTokensPerSecond = new WeakMap();
648
- _inputCursorVisible = new WeakMap();
649
- _inputCursorTimer = new WeakMap();
650
- _onData = new WeakMap();
651
- _onResize = new WeakMap();
652
- _resolveStreamInterrupt = new WeakMap();
653
- _TerminalRenderer_instances = new WeakSet();
654
- start_fn = function(options) {
655
- var _a, _b, _c, _d;
656
- __privateSet(this, _title, (_a = options == null ? void 0 : options.title) != null ? _a : __privateGet(this, _title));
657
- __privateSet(this, _contextSize, (_b = options == null ? void 0 : options.contextSize) != null ? _b : __privateGet(this, _defaultContextSize));
658
- if (__privateGet(this, _isInteractive)) {
659
- return;
660
- }
661
- __privateSet(this, _isInteractive, true);
662
- __privateGet(this, _frameBuffer).reset();
663
- __privateGet(this, _output).write("\x1B[?1049h\x1B[?25l");
664
- if (__privateGet(this, _input).isTTY) {
665
- (_d = (_c = __privateGet(this, _input)).setRawMode) == null ? void 0 : _d.call(_c, true);
666
- __privateGet(this, _input).resume();
667
- }
668
- __privateSet(this, _onResize, () => __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this));
669
- __privateGet(this, _output).on("resize", __privateGet(this, _onResize));
670
- };
671
- stop_fn = function() {
672
- var _a, _b;
673
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
674
- __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
675
- if (!__privateGet(this, _isInteractive)) {
676
- return;
593
+ #start(options) {
594
+ this.#title = options?.title ?? this.#title;
595
+ this.#contextSize = options?.contextSize ?? this.#defaultContextSize;
596
+ if (this.#isInteractive) {
597
+ return;
598
+ }
599
+ this.#isInteractive = true;
600
+ this.#frameBuffer.reset();
601
+ this.#output.write("\x1B[?1049h\x1B[?25l");
602
+ if (this.#input.isTTY) {
603
+ this.#input.setRawMode?.(true);
604
+ this.#input.resume();
605
+ }
606
+ this.#onResize = () => this.#repaint();
607
+ this.#output.on("resize", this.#onResize);
677
608
  }
678
- if (__privateGet(this, _input).isTTY) {
679
- (_b = (_a = __privateGet(this, _input)).setRawMode) == null ? void 0 : _b.call(_a, false);
680
- __privateGet(this, _input).pause();
609
+ #stop() {
610
+ this.#detachInput();
611
+ this.#stopInputCursorBlink();
612
+ if (!this.#isInteractive) {
613
+ return;
614
+ }
615
+ if (this.#input.isTTY) {
616
+ this.#input.setRawMode?.(false);
617
+ this.#input.pause();
618
+ }
619
+ if (this.#onResize) {
620
+ this.#output.off("resize", this.#onResize);
621
+ this.#onResize = void 0;
622
+ }
623
+ this.#output.write("\x1B[?25h\x1B[?1049l");
624
+ this.#frameBuffer.reset();
625
+ this.#isInteractive = false;
681
626
  }
682
- if (__privateGet(this, _onResize)) {
683
- __privateGet(this, _output).off("resize", __privateGet(this, _onResize));
684
- __privateSet(this, _onResize, void 0);
627
+ #attachInput() {
628
+ if (this.#onData) {
629
+ this.#input.on("data", this.#onData);
630
+ }
685
631
  }
686
- __privateGet(this, _output).write("\x1B[?25h\x1B[?1049l");
687
- __privateGet(this, _frameBuffer).reset();
688
- __privateSet(this, _isInteractive, false);
689
- };
690
- attachInput_fn = function() {
691
- if (__privateGet(this, _onData)) {
692
- __privateGet(this, _input).on("data", __privateGet(this, _onData));
632
+ #detachInput() {
633
+ if (this.#onData) {
634
+ this.#input.off("data", this.#onData);
635
+ this.#onData = void 0;
636
+ }
693
637
  }
694
- };
695
- detachInput_fn = function() {
696
- if (__privateGet(this, _onData)) {
697
- __privateGet(this, _input).off("data", __privateGet(this, _onData));
698
- __privateSet(this, _onData, void 0);
638
+ #handleStreamingKey(chunk) {
639
+ const key = parseKey(chunk);
640
+ switch (key.type) {
641
+ case "up":
642
+ case "down":
643
+ this.#handleScroll(key.type);
644
+ break;
645
+ case "page-up":
646
+ case "page-down":
647
+ this.#handlePageScroll(key.type);
648
+ break;
649
+ case "ctrl-l":
650
+ this.#repaint();
651
+ break;
652
+ case "escape":
653
+ case "ctrl-c":
654
+ this.#interrupted = true;
655
+ this.#resolveStreamInterrupt?.();
656
+ break;
657
+ default:
658
+ break;
659
+ }
699
660
  }
700
- };
701
- handleStreamingKey_fn = function(chunk) {
702
- var _a;
703
- const key = parseKey(chunk);
704
- switch (key.type) {
705
- case "up":
706
- case "down":
707
- __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
708
- break;
709
- case "page-up":
710
- case "page-down":
711
- __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
712
- break;
713
- case "ctrl-l":
714
- __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
715
- break;
716
- case "escape":
717
- case "ctrl-c":
718
- __privateSet(this, _interrupted, true);
719
- (_a = __privateGet(this, _resolveStreamInterrupt)) == null ? void 0 : _a.call(this);
720
- break;
721
- default:
722
- break;
661
+ #handleScroll(direction, lines = 1) {
662
+ const delta = direction === "up" ? lines : -lines;
663
+ this.#scrollOffset = this.#clampScrollOffset(this.#scrollOffset + delta);
664
+ this.#paint();
723
665
  }
724
- };
725
- handleScroll_fn = function(direction, lines = 1) {
726
- const delta = direction === "up" ? lines : -lines;
727
- __privateSet(this, _scrollOffset, __privateMethod(this, _TerminalRenderer_instances, clampScrollOffset_fn).call(this, __privateGet(this, _scrollOffset) + delta));
728
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
729
- };
730
- handlePageScroll_fn = function(direction) {
731
- __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, direction === "page-up" ? "up" : "down", __privateMethod(this, _TerminalRenderer_instances, bodyContentHeight_fn).call(this));
732
- };
733
- startInputCursorBlink_fn = function() {
734
- var _a, _b;
735
- __privateMethod(this, _TerminalRenderer_instances, stopInputCursorBlink_fn).call(this);
736
- __privateMethod(this, _TerminalRenderer_instances, showInputCursor_fn).call(this);
737
- __privateSet(this, _inputCursorTimer, setInterval(() => {
738
- __privateSet(this, _inputCursorVisible, !__privateGet(this, _inputCursorVisible));
739
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
740
- }, inputCursorBlinkMs));
741
- (_b = (_a = __privateGet(this, _inputCursorTimer)).unref) == null ? void 0 : _b.call(_a);
742
- };
743
- stopInputCursorBlink_fn = function() {
744
- if (__privateGet(this, _inputCursorTimer)) {
745
- clearInterval(__privateGet(this, _inputCursorTimer));
746
- __privateSet(this, _inputCursorTimer, void 0);
666
+ #handlePageScroll(direction) {
667
+ this.#handleScroll(
668
+ direction === "page-up" ? "up" : "down",
669
+ this.#bodyContentHeight()
670
+ );
747
671
  }
748
- __privateSet(this, _inputCursorVisible, true);
749
- };
750
- showInputCursor_fn = function() {
751
- __privateSet(this, _inputCursorVisible, true);
752
- };
753
- addSubmittedPrompt_fn = function(prompt) {
754
- if (prompt == null) {
755
- return;
672
+ #startInputCursorBlink() {
673
+ this.#stopInputCursorBlink();
674
+ this.#showInputCursor();
675
+ this.#inputCursorTimer = setInterval(() => {
676
+ this.#inputCursorVisible = !this.#inputCursorVisible;
677
+ this.#paint();
678
+ }, inputCursorBlinkMs);
679
+ this.#inputCursorTimer.unref?.();
680
+ }
681
+ #stopInputCursorBlink() {
682
+ if (this.#inputCursorTimer) {
683
+ clearInterval(this.#inputCursorTimer);
684
+ this.#inputCursorTimer = void 0;
685
+ }
686
+ this.#inputCursorVisible = true;
756
687
  }
757
- const section = __privateGet(this, _sections).at(-1);
758
- if ((section == null ? void 0 : section.kind) === "user" && section.content === prompt) {
759
- return;
688
+ #showInputCursor() {
689
+ this.#inputCursorVisible = true;
760
690
  }
761
- __privateMethod(this, _TerminalRenderer_instances, addUserSection_fn).call(this, prompt);
762
- };
763
- addUserSection_fn = function(prompt) {
764
- const previousBodyLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
765
- __privateGet(this, _sections).push({ kind: "user", title: "User", content: prompt });
766
- __privateMethod(this, _TerminalRenderer_instances, paintAfterBodyChange_fn).call(this, previousBodyLineCount);
767
- };
768
- renderAssistantMessage_fn = function(message, displayModes) {
769
- var _a, _b, _c;
770
- const previousBodyLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
771
- const activeSectionIds = /* @__PURE__ */ new Set();
772
- const metadataStats = extractResponseStatisticsFromMetadata(
773
- message.metadata
774
- );
775
- __privateSet(this, _totalTokens, (_a = metadataStats.totalTokens) != null ? _a : __privateGet(this, _totalTokens));
776
- __privateSet(this, _assistantOutputTokens, (_b = metadataStats.outputTokens) != null ? _b : __privateGet(this, _assistantOutputTokens));
777
- __privateSet(this, _assistantOutputTokensPerSecond, (_c = metadataStats.outputTokensPerSecond) != null ? _c : __privateGet(this, _assistantOutputTokensPerSecond));
778
- for (const [index, part] of message.parts.entries()) {
779
- const id = sectionId(message.id, index);
780
- switch (part.type) {
781
- case "text": {
782
- const content = part.text.trim();
783
- if (content.length === 0) {
784
- break;
785
- }
786
- activeSectionIds.add(id);
787
- __privateMethod(this, _TerminalRenderer_instances, upsertSection_fn).call(this, {
788
- id,
789
- kind: "assistant",
790
- title: "Assistant",
791
- rightTitle: formatResponseStatistics(
792
- {
793
- totalTokens: __privateGet(this, _totalTokens),
794
- outputTokens: __privateGet(this, _assistantOutputTokens),
795
- outputTokensPerSecond: __privateGet(this, _assistantOutputTokensPerSecond)
796
- },
797
- displayModes.responseStatistics
798
- ),
799
- content
800
- });
801
- break;
802
- }
803
- case "reasoning": {
804
- const content = part.text.trim();
805
- if (displayModes.reasoning === "hidden" || content.length === 0) {
691
+ #addSubmittedPrompt(prompt) {
692
+ if (prompt == null) {
693
+ return;
694
+ }
695
+ const section = this.#sections.at(-1);
696
+ if (section?.kind === "user" && section.content === prompt) {
697
+ return;
698
+ }
699
+ this.#addUserSection(prompt);
700
+ }
701
+ #addUserSection(prompt) {
702
+ const previousBodyLineCount = this.#bodyLineCount();
703
+ this.#sections.push({ kind: "user", title: "User", content: prompt });
704
+ this.#paintAfterBodyChange(previousBodyLineCount);
705
+ }
706
+ #renderAssistantMessage(message, displayModes) {
707
+ const previousBodyLineCount = this.#bodyLineCount();
708
+ const activeSectionIds = /* @__PURE__ */ new Set();
709
+ const metadataStats = extractResponseStatisticsFromMetadata(
710
+ message.metadata
711
+ );
712
+ this.#totalTokens = metadataStats.totalTokens ?? this.#totalTokens;
713
+ this.#assistantOutputTokens = metadataStats.outputTokens ?? this.#assistantOutputTokens;
714
+ this.#assistantOutputTokensPerSecond = metadataStats.outputTokensPerSecond ?? this.#assistantOutputTokensPerSecond;
715
+ for (const [index, part] of message.parts.entries()) {
716
+ const id = sectionId(message.id, index);
717
+ switch (part.type) {
718
+ case "text": {
719
+ const content = part.text.trim();
720
+ if (content.length === 0) {
721
+ break;
722
+ }
723
+ activeSectionIds.add(id);
724
+ this.#upsertSection({
725
+ id,
726
+ kind: "assistant",
727
+ title: "Assistant",
728
+ rightTitle: formatResponseStatistics(
729
+ {
730
+ totalTokens: this.#totalTokens,
731
+ outputTokens: this.#assistantOutputTokens,
732
+ outputTokensPerSecond: this.#assistantOutputTokensPerSecond
733
+ },
734
+ displayModes.responseStatistics
735
+ ),
736
+ content
737
+ });
806
738
  break;
807
739
  }
808
- activeSectionIds.add(id);
809
- __privateMethod(this, _TerminalRenderer_instances, upsertSection_fn).call(this, {
810
- id,
811
- kind: "reasoning",
812
- title: "Reasoning",
813
- content,
814
- collapsed: shouldCollapsePart(
815
- message,
816
- index,
817
- displayModes.reasoning,
818
- displayModes
819
- )
820
- });
821
- break;
822
- }
823
- default:
824
- if (isToolUIPart(part)) {
825
- if (displayModes.tools === "hidden") {
740
+ case "reasoning": {
741
+ const content = part.text.trim();
742
+ if (displayModes.reasoning === "hidden" || content.length === 0) {
826
743
  break;
827
744
  }
828
745
  activeSectionIds.add(id);
829
- __privateMethod(this, _TerminalRenderer_instances, upsertSection_fn).call(this, {
746
+ this.#upsertSection({
830
747
  id,
831
- ...renderToolInvocation(part, {
832
- mode: displayModes.tools,
833
- collapsed: shouldCollapsePart(
834
- message,
835
- index,
836
- displayModes.tools,
837
- displayModes
838
- )
839
- })
748
+ kind: "reasoning",
749
+ title: "Reasoning",
750
+ content,
751
+ collapsed: shouldCollapsePart(
752
+ message,
753
+ index,
754
+ displayModes.reasoning,
755
+ displayModes
756
+ )
840
757
  });
758
+ break;
841
759
  }
842
- break;
760
+ default:
761
+ if (isToolUIPart(part)) {
762
+ if (displayModes.tools === "hidden") {
763
+ break;
764
+ }
765
+ activeSectionIds.add(id);
766
+ this.#upsertSection({
767
+ id,
768
+ ...renderToolInvocation(part, {
769
+ mode: displayModes.tools,
770
+ collapsed: shouldCollapsePart(
771
+ message,
772
+ index,
773
+ displayModes.tools,
774
+ displayModes
775
+ )
776
+ })
777
+ });
778
+ }
779
+ break;
780
+ }
781
+ }
782
+ this.#removeStaleAssistantSections(message.id, activeSectionIds);
783
+ this.#paintAfterBodyChange(previousBodyLineCount);
784
+ }
785
+ #upsertSection(section) {
786
+ const existingSection = section.id ? this.#sections.find((candidate) => candidate.id === section.id) : void 0;
787
+ if (existingSection) {
788
+ const cache = existingSection.cache;
789
+ existingSection.kind = section.kind;
790
+ existingSection.title = section.title;
791
+ existingSection.rightTitle = section.rightTitle;
792
+ existingSection.content = section.content;
793
+ existingSection.collapsed = section.collapsed;
794
+ existingSection.cache = cache && sectionMatchesCache(section, cache) ? cache : void 0;
795
+ return;
843
796
  }
797
+ this.#sections.push(section);
844
798
  }
845
- __privateMethod(this, _TerminalRenderer_instances, removeStaleAssistantSections_fn).call(this, message.id, activeSectionIds);
846
- __privateMethod(this, _TerminalRenderer_instances, paintAfterBodyChange_fn).call(this, previousBodyLineCount);
847
- };
848
- upsertSection_fn = function(section) {
849
- const existingSection = section.id ? __privateGet(this, _sections).find((candidate) => candidate.id === section.id) : void 0;
850
- if (existingSection) {
851
- const cache = existingSection.cache;
852
- existingSection.kind = section.kind;
853
- existingSection.title = section.title;
854
- existingSection.rightTitle = section.rightTitle;
855
- existingSection.content = section.content;
856
- existingSection.collapsed = section.collapsed;
857
- existingSection.cache = cache && sectionMatchesCache(section, cache) ? cache : void 0;
858
- return;
799
+ #removeStaleAssistantSections(messageId, activeSectionIds) {
800
+ const prefix = `${messageId}:`;
801
+ this.#sections = this.#sections.filter(
802
+ (section) => section.id == null || !section.id.startsWith(prefix) || activeSectionIds.has(section.id)
803
+ );
859
804
  }
860
- __privateGet(this, _sections).push(section);
861
- };
862
- removeStaleAssistantSections_fn = function(messageId, activeSectionIds) {
863
- const prefix = `${messageId}:`;
864
- __privateSet(this, _sections, __privateGet(this, _sections).filter(
865
- (section) => section.id == null || !section.id.startsWith(prefix) || activeSectionIds.has(section.id)
866
- ));
867
- };
868
- observeUIMessageStream_fn = async function* (stream) {
869
- let hasPendingToolResults = false;
870
- for await (const chunk of iterateUIMessageStream(stream)) {
871
- const nextStatus = statusForStreamChunk(chunk, { hasPendingToolResults });
872
- if (chunk.type === "start-step") {
873
- hasPendingToolResults = false;
874
- } else if (finishesToolExecution(chunk)) {
875
- hasPendingToolResults = true;
805
+ async *#observeUIMessageStream(stream) {
806
+ let hasPendingToolResults = false;
807
+ for await (const chunk of iterateUIMessageStream(stream)) {
808
+ const nextStatus = statusForStreamChunk(chunk, { hasPendingToolResults });
809
+ if (chunk.type === "start-step") {
810
+ hasPendingToolResults = false;
811
+ } else if (finishesToolExecution(chunk)) {
812
+ hasPendingToolResults = true;
813
+ }
814
+ if (nextStatus && this.#status !== nextStatus) {
815
+ this.#status = nextStatus;
816
+ this.#paint();
817
+ } else if (startsVisibleAssistantStream(chunk) && this.#status !== streamingStatus) {
818
+ this.#status = streamingStatus;
819
+ this.#paint();
820
+ }
821
+ if (chunk.type === "error") {
822
+ this.#addErrorSection("Error", chunk.errorText);
823
+ }
824
+ if (chunk.type === "finish") {
825
+ const stats = extractResponseStatistics(chunk);
826
+ this.#totalTokens = stats.totalTokens;
827
+ this.#assistantOutputTokens = stats.outputTokens;
828
+ this.#assistantOutputTokensPerSecond = stats.outputTokensPerSecond;
829
+ }
830
+ yield chunk;
876
831
  }
877
- if (nextStatus && __privateGet(this, _status) !== nextStatus) {
878
- __privateSet(this, _status, nextStatus);
879
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
880
- } else if (startsVisibleAssistantStream(chunk) && __privateGet(this, _status) !== streamingStatus) {
881
- __privateSet(this, _status, streamingStatus);
882
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
832
+ }
833
+ #addErrorSection(title, content) {
834
+ const previousBodyLineCount = this.#bodyLineCount();
835
+ this.#sections.push({ kind: "error", title, content });
836
+ this.#paintAfterBodyChange(previousBodyLineCount);
837
+ }
838
+ #paintAfterBodyChange(previousBodyLineCount) {
839
+ if (this.#scrollOffset !== 0) {
840
+ const bodyLineDelta = this.#bodyLineCount() - previousBodyLineCount;
841
+ this.#scrollOffset = this.#clampScrollOffset(
842
+ this.#scrollOffset + bodyLineDelta
843
+ );
883
844
  }
884
- if (chunk.type === "error") {
885
- __privateMethod(this, _TerminalRenderer_instances, addErrorSection_fn).call(this, "Error", chunk.errorText);
845
+ this.#paint();
846
+ }
847
+ #paint() {
848
+ const frame = renderScreenViewport({
849
+ width: this.#width(),
850
+ height: this.#height(),
851
+ title: this.#title,
852
+ rightTitle: formatTokenCount(this.#totalTokens, this.#contextSize),
853
+ visibleBodyLines: this.#visibleBodyLines(),
854
+ input: this.#inputText,
855
+ inputActive: this.#inputActive,
856
+ inputCursorVisible: this.#inputCursorVisible,
857
+ status: this.#status
858
+ });
859
+ this.#frameBuffer.present(frame);
860
+ }
861
+ #repaint() {
862
+ this.#frameBuffer.reset();
863
+ this.#paint();
864
+ }
865
+ #visibleBodyLines() {
866
+ if (this.#sections.length === 0) {
867
+ return ["Waiting for input..."];
886
868
  }
887
- if (chunk.type === "finish") {
888
- const stats = extractResponseStatistics(chunk);
889
- __privateSet(this, _totalTokens, stats.totalTokens);
890
- __privateSet(this, _assistantOutputTokens, stats.outputTokens);
891
- __privateSet(this, _assistantOutputTokensPerSecond, stats.outputTokensPerSecond);
869
+ const bodyContentHeight = this.#bodyContentHeight();
870
+ const totalLineCount = this.#bodyLineCount();
871
+ const start = Math.max(
872
+ 0,
873
+ totalLineCount - bodyContentHeight - this.#scrollOffset
874
+ );
875
+ const end = start + bodyContentHeight;
876
+ const visibleLines = [];
877
+ let sectionStart = 0;
878
+ for (const section of this.#sections) {
879
+ const sectionLines = renderSectionLines(section, this.#width() - 4);
880
+ const sectionEnd = sectionStart + sectionLines.length;
881
+ if (sectionEnd > start && sectionStart < end) {
882
+ visibleLines.push(
883
+ ...sectionLines.slice(
884
+ Math.max(0, start - sectionStart),
885
+ end - sectionStart
886
+ )
887
+ );
888
+ }
889
+ if (visibleLines.length >= bodyContentHeight) {
890
+ break;
891
+ }
892
+ sectionStart = sectionEnd;
892
893
  }
893
- yield chunk;
894
+ return visibleLines;
894
895
  }
895
- };
896
- addErrorSection_fn = function(title, content) {
897
- const previousBodyLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
898
- __privateGet(this, _sections).push({ kind: "error", title, content });
899
- __privateMethod(this, _TerminalRenderer_instances, paintAfterBodyChange_fn).call(this, previousBodyLineCount);
900
- };
901
- paintAfterBodyChange_fn = function(previousBodyLineCount) {
902
- if (__privateGet(this, _scrollOffset) !== 0) {
903
- const bodyLineDelta = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this) - previousBodyLineCount;
904
- __privateSet(this, _scrollOffset, __privateMethod(this, _TerminalRenderer_instances, clampScrollOffset_fn).call(this, __privateGet(this, _scrollOffset) + bodyLineDelta));
905
- }
906
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
907
- };
908
- paint_fn = function() {
909
- const frame = renderScreenViewport({
910
- width: __privateMethod(this, _TerminalRenderer_instances, width_fn).call(this),
911
- height: __privateMethod(this, _TerminalRenderer_instances, height_fn).call(this),
912
- title: __privateGet(this, _title),
913
- rightTitle: formatTokenCount(__privateGet(this, _totalTokens), __privateGet(this, _contextSize)),
914
- visibleBodyLines: __privateMethod(this, _TerminalRenderer_instances, visibleBodyLines_fn).call(this),
915
- input: __privateGet(this, _inputText),
916
- inputActive: __privateGet(this, _inputActive),
917
- inputCursorVisible: __privateGet(this, _inputCursorVisible),
918
- status: __privateGet(this, _status)
919
- });
920
- __privateGet(this, _frameBuffer).present(frame);
921
- };
922
- repaint_fn = function() {
923
- __privateGet(this, _frameBuffer).reset();
924
- __privateMethod(this, _TerminalRenderer_instances, paint_fn).call(this);
925
- };
926
- visibleBodyLines_fn = function() {
927
- if (__privateGet(this, _sections).length === 0) {
928
- return ["Waiting for input..."];
896
+ #clampScrollOffset(scrollOffset) {
897
+ const maxScrollOffset = Math.max(
898
+ 0,
899
+ this.#bodyLineCount() - this.#bodyContentHeight()
900
+ );
901
+ return Math.min(Math.max(0, scrollOffset), maxScrollOffset);
929
902
  }
930
- const bodyContentHeight = __privateMethod(this, _TerminalRenderer_instances, bodyContentHeight_fn).call(this);
931
- const totalLineCount = __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this);
932
- const start = Math.max(
933
- 0,
934
- totalLineCount - bodyContentHeight - __privateGet(this, _scrollOffset)
935
- );
936
- const end = start + bodyContentHeight;
937
- const visibleLines = [];
938
- let sectionStart = 0;
939
- for (const section of __privateGet(this, _sections)) {
940
- const sectionLines = renderSectionLines(section, __privateMethod(this, _TerminalRenderer_instances, width_fn).call(this) - 4);
941
- const sectionEnd = sectionStart + sectionLines.length;
942
- if (sectionEnd > start && sectionStart < end) {
943
- visibleLines.push(
944
- ...sectionLines.slice(
945
- Math.max(0, start - sectionStart),
946
- end - sectionStart
947
- )
948
- );
903
+ #bodyLineCount() {
904
+ if (this.#sections.length === 0) {
905
+ return 1;
949
906
  }
950
- if (visibleLines.length >= bodyContentHeight) {
951
- break;
907
+ let count = 0;
908
+ for (const section of this.#sections) {
909
+ count += renderSectionLines(section, this.#width() - 4).length;
952
910
  }
953
- sectionStart = sectionEnd;
911
+ return count;
954
912
  }
955
- return visibleLines;
956
- };
957
- clampScrollOffset_fn = function(scrollOffset) {
958
- const maxScrollOffset = Math.max(
959
- 0,
960
- __privateMethod(this, _TerminalRenderer_instances, bodyLineCount_fn).call(this) - __privateMethod(this, _TerminalRenderer_instances, bodyContentHeight_fn).call(this)
961
- );
962
- return Math.min(Math.max(0, scrollOffset), maxScrollOffset);
963
- };
964
- bodyLineCount_fn = function() {
965
- if (__privateGet(this, _sections).length === 0) {
966
- return 1;
913
+ #bodyContentHeight() {
914
+ return Math.max(1, this.#height() - 5);
967
915
  }
968
- let count = 0;
969
- for (const section of __privateGet(this, _sections)) {
970
- count += renderSectionLines(section, __privateMethod(this, _TerminalRenderer_instances, width_fn).call(this) - 4).length;
916
+ #width() {
917
+ return Math.max(20, this.#output.columns ?? 80);
971
918
  }
972
- return count;
973
- };
974
- bodyContentHeight_fn = function() {
975
- return Math.max(1, __privateMethod(this, _TerminalRenderer_instances, height_fn).call(this) - 5);
976
- };
977
- width_fn = function() {
978
- var _a;
979
- return Math.max(20, (_a = __privateGet(this, _output).columns) != null ? _a : 80);
980
- };
981
- height_fn = function() {
982
- var _a;
983
- return Math.max(8, (_a = __privateGet(this, _output).rows) != null ? _a : 24);
984
- };
985
- waitForExit_fn = async function(options) {
986
- if ((options == null ? void 0 : options.waitForExit) === false || !__privateGet(this, _input).isTTY || __privateGet(this, _interrupted)) {
987
- return;
919
+ #height() {
920
+ return Math.max(8, this.#output.rows ?? 24);
988
921
  }
989
- await new Promise((resolve) => {
990
- __privateSet(this, _onData, (chunk) => {
991
- const key = parseKey(chunk);
992
- switch (key.type) {
993
- case "up":
994
- case "down":
995
- __privateMethod(this, _TerminalRenderer_instances, handleScroll_fn).call(this, key.type);
996
- break;
997
- case "page-up":
998
- case "page-down":
999
- __privateMethod(this, _TerminalRenderer_instances, handlePageScroll_fn).call(this, key.type);
1000
- break;
1001
- case "ctrl-l":
1002
- __privateMethod(this, _TerminalRenderer_instances, repaint_fn).call(this);
1003
- break;
1004
- case "escape":
1005
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
1006
- resolve();
1007
- break;
1008
- case "character":
1009
- if (key.value === "q") {
1010
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
922
+ async #waitForExit(options) {
923
+ if (options?.waitForExit === false || !this.#input.isTTY || this.#interrupted) {
924
+ return;
925
+ }
926
+ await new Promise((resolve) => {
927
+ this.#onData = (chunk) => {
928
+ const key = parseKey(chunk);
929
+ switch (key.type) {
930
+ case "up":
931
+ case "down":
932
+ this.#handleScroll(key.type);
933
+ break;
934
+ case "page-up":
935
+ case "page-down":
936
+ this.#handlePageScroll(key.type);
937
+ break;
938
+ case "ctrl-l":
939
+ this.#repaint();
940
+ break;
941
+ case "escape":
942
+ this.#detachInput();
1011
943
  resolve();
1012
- }
1013
- break;
1014
- case "ctrl-c":
1015
- __privateMethod(this, _TerminalRenderer_instances, detachInput_fn).call(this);
1016
- process.exitCode = 130;
1017
- resolve();
1018
- break;
1019
- default:
1020
- break;
1021
- }
944
+ break;
945
+ case "character":
946
+ if (key.value === "q") {
947
+ this.#detachInput();
948
+ resolve();
949
+ }
950
+ break;
951
+ case "ctrl-c":
952
+ this.#detachInput();
953
+ process.exitCode = 130;
954
+ resolve();
955
+ break;
956
+ default:
957
+ break;
958
+ }
959
+ };
960
+ this.#attachInput();
1022
961
  });
1023
- __privateMethod(this, _TerminalRenderer_instances, attachInput_fn).call(this);
1024
- });
962
+ }
1025
963
  };
1026
964
  function interruptedError() {
1027
965
  return new Error("Interrupted");
@@ -1049,9 +987,8 @@ function formatStreamError(error) {
1049
987
  return JSON.stringify(error);
1050
988
  }
1051
989
  function renderToolInvocation(part, options) {
1052
- var _a, _b, _c, _d;
1053
990
  const toolName = getToolName(part);
1054
- const title = `Tool \xB7 ${(_a = part.title) != null ? _a : toolName}`;
991
+ const title = `Tool \xB7 ${part.title ?? toolName}`;
1055
992
  const input = "input" in part ? part.input : void 0;
1056
993
  const inputText = input === void 0 ? "Input: (streaming...)" : `Input:
1057
994
  ${formatValue(input)}`;
@@ -1107,7 +1044,7 @@ ${formatValue(part.output)}`
1107
1044
  case "output-error":
1108
1045
  return {
1109
1046
  kind: "error",
1110
- title: `Tool Error \xB7 ${(_b = part.title) != null ? _b : toolName}`,
1047
+ title: `Tool Error \xB7 ${part.title ?? toolName}`,
1111
1048
  rightTitle: status,
1112
1049
  content: `${inputText}
1113
1050
 
@@ -1117,11 +1054,11 @@ ${part.errorText}`
1117
1054
  case "output-denied":
1118
1055
  return {
1119
1056
  kind: "error",
1120
- title: `Tool Denied \xB7 ${(_c = part.title) != null ? _c : toolName}`,
1057
+ title: `Tool Denied \xB7 ${part.title ?? toolName}`,
1121
1058
  rightTitle: status,
1122
1059
  content: `${inputText}
1123
1060
 
1124
- Reason: ${(_d = part.approval.reason) != null ? _d : "denied"}`
1061
+ Reason: ${part.approval.reason ?? "denied"}`
1125
1062
  };
1126
1063
  }
1127
1064
  }
@@ -1209,8 +1146,7 @@ function formatValue(value) {
1209
1146
  return JSON.stringify(value, null, 2);
1210
1147
  }
1211
1148
  function formatToolApprovalTitle(request) {
1212
- var _a;
1213
- return `tool ${(_a = request.title) != null ? _a : request.toolName}`;
1149
+ return `tool ${request.title ?? request.toolName}`;
1214
1150
  }
1215
1151
  function sectionId(messageId, partIndex) {
1216
1152
  return `${messageId}:${partIndex}`;
@@ -1324,31 +1260,29 @@ function findVisibleBreakPoint(input, width) {
1324
1260
  return sliceVisible(input, width).length;
1325
1261
  }
1326
1262
  function extractResponseStatistics(chunk) {
1327
- var _a, _b;
1328
1263
  const usage = "usage" in chunk ? chunk.usage : void 0;
1329
- const metadataUsage = "messageMetadata" in chunk ? (_a = chunk.messageMetadata) == null ? void 0 : _a.usage : void 0;
1330
- const metadataPerformance = "messageMetadata" in chunk ? (_b = chunk.messageMetadata) == null ? void 0 : _b.performance : void 0;
1264
+ const metadataUsage = "messageMetadata" in chunk ? chunk.messageMetadata?.usage : void 0;
1265
+ const metadataPerformance = "messageMetadata" in chunk ? chunk.messageMetadata?.performance : void 0;
1331
1266
  return {
1332
- totalTokens: extractTotalTokenCountFromUsage(usage != null ? usage : metadataUsage),
1333
- outputTokens: extractOutputTokenCountFromUsage(usage != null ? usage : metadataUsage),
1334
- outputTokensPerSecond: metadataPerformance == null ? void 0 : metadataPerformance.outputTokensPerSecond
1267
+ totalTokens: extractTotalTokenCountFromUsage(usage ?? metadataUsage),
1268
+ outputTokens: extractOutputTokenCountFromUsage(usage ?? metadataUsage),
1269
+ outputTokensPerSecond: metadataPerformance?.outputTokensPerSecond
1335
1270
  };
1336
1271
  }
1337
1272
  function extractResponseStatisticsFromMetadata(metadata) {
1338
- var _a;
1339
1273
  const stats = metadata;
1340
1274
  return {
1341
- totalTokens: extractTotalTokenCountFromUsage(stats == null ? void 0 : stats.usage),
1342
- outputTokens: extractOutputTokenCountFromUsage(stats == null ? void 0 : stats.usage),
1343
- outputTokensPerSecond: (_a = stats == null ? void 0 : stats.performance) == null ? void 0 : _a.outputTokensPerSecond
1275
+ totalTokens: extractTotalTokenCountFromUsage(stats?.usage),
1276
+ outputTokens: extractOutputTokenCountFromUsage(stats?.usage),
1277
+ outputTokensPerSecond: stats?.performance?.outputTokensPerSecond
1344
1278
  };
1345
1279
  }
1346
1280
  function extractTotalTokenCountFromUsage(usage) {
1347
- const totalTokens = usage == null ? void 0 : usage.totalTokens;
1281
+ const totalTokens = usage?.totalTokens;
1348
1282
  if (typeof totalTokens === "number") {
1349
1283
  return totalTokens;
1350
1284
  }
1351
- if (typeof (totalTokens == null ? void 0 : totalTokens.total) === "number") {
1285
+ if (typeof totalTokens?.total === "number") {
1352
1286
  return totalTokens.total;
1353
1287
  }
1354
1288
  const inputTokens = extractInputTokenCountFromUsage(usage);
@@ -1358,24 +1292,24 @@ function extractTotalTokenCountFromUsage(usage) {
1358
1292
  }
1359
1293
  }
1360
1294
  function extractInputTokenCountFromUsage(usage) {
1361
- const inputTokens = usage == null ? void 0 : usage.inputTokens;
1295
+ const inputTokens = usage?.inputTokens;
1362
1296
  if (typeof inputTokens === "number") {
1363
1297
  return inputTokens;
1364
1298
  }
1365
- if (typeof (inputTokens == null ? void 0 : inputTokens.total) === "number") {
1299
+ if (typeof inputTokens?.total === "number") {
1366
1300
  return inputTokens.total;
1367
1301
  }
1368
- return usage == null ? void 0 : usage.promptTokens;
1302
+ return usage?.promptTokens;
1369
1303
  }
1370
1304
  function extractOutputTokenCountFromUsage(usage) {
1371
- const outputTokens = usage == null ? void 0 : usage.outputTokens;
1305
+ const outputTokens = usage?.outputTokens;
1372
1306
  if (typeof outputTokens === "number") {
1373
1307
  return outputTokens;
1374
1308
  }
1375
- if (typeof (outputTokens == null ? void 0 : outputTokens.total) === "number") {
1309
+ if (typeof outputTokens?.total === "number") {
1376
1310
  return outputTokens.total;
1377
1311
  }
1378
- return usage == null ? void 0 : usage.completionTokens;
1312
+ return usage?.completionTokens;
1379
1313
  }
1380
1314
  function formatTokenCount(tokens, contextSize) {
1381
1315
  if (tokens == null) {
@@ -1455,14 +1389,13 @@ var defaultResponseStatistics2 = "outputTokensPerSecond";
1455
1389
  var AgentTUIRunner = class {
1456
1390
  constructor(options) {
1457
1391
  this.chatId = generateId();
1458
- var _a, _b, _c, _d;
1459
1392
  this.agent = options.agent;
1460
1393
  this.transport = options.transport;
1461
- this.renderer = (_a = createRenderer(options)) != null ? _a : createDefaultRenderer(options);
1394
+ this.renderer = createRenderer(options) ?? createDefaultRenderer(options);
1462
1395
  this.title = options.title;
1463
- this.tools = (_b = options.tools) != null ? _b : "auto-collapsed";
1464
- this.reasoning = (_c = options.reasoning) != null ? _c : "auto-collapsed";
1465
- this.responseStatistics = (_d = options.responseStatistics) != null ? _d : defaultResponseStatistics2;
1396
+ this.tools = options.tools ?? "auto-collapsed";
1397
+ this.reasoning = options.reasoning ?? "auto-collapsed";
1398
+ this.responseStatistics = options.responseStatistics ?? defaultResponseStatistics2;
1466
1399
  this.contextSize = options.contextSize;
1467
1400
  this.sandbox = options.sandbox;
1468
1401
  }
@@ -1611,7 +1544,6 @@ function createRenderer(options) {
1611
1544
  });
1612
1545
  }
1613
1546
  async function* textStreamToUIMessageStream(stream, generateMessageId, originalMessages = []) {
1614
- var _a, _b;
1615
1547
  const openTextParts = /* @__PURE__ */ new Set();
1616
1548
  const openReasoningParts = /* @__PURE__ */ new Set();
1617
1549
  const openToolCalls = /* @__PURE__ */ new Set();
@@ -1620,7 +1552,7 @@ async function* textStreamToUIMessageStream(stream, generateMessageId, originalM
1620
1552
  let sentFinish = false;
1621
1553
  yield {
1622
1554
  type: "start",
1623
- messageId: (_b = (_a = lastAssistantMessage(originalMessages)) == null ? void 0 : _a.id) != null ? _b : generateMessageId()
1555
+ messageId: lastAssistantMessage(originalMessages)?.id ?? generateMessageId()
1624
1556
  };
1625
1557
  for await (const part of stream) {
1626
1558
  switch (part.type) {
@@ -1829,7 +1761,7 @@ async function* textStreamToUIMessageStream(stream, generateMessageId, originalM
1829
1761
  type: "finish",
1830
1762
  finishReason: part.finishReason,
1831
1763
  messageMetadata: createResponseMetadata(
1832
- latestStepUsage != null ? latestStepUsage : part.totalUsage,
1764
+ latestStepUsage ?? part.totalUsage,
1833
1765
  latestPerformance
1834
1766
  )
1835
1767
  };
@@ -1848,17 +1780,17 @@ async function* textStreamToUIMessageStream(stream, generateMessageId, originalM
1848
1780
  }
1849
1781
  }
1850
1782
  function createResponseMetadata(usage, performance) {
1851
- if ((usage == null ? void 0 : usage.totalTokens) == null && (usage == null ? void 0 : usage.outputTokens) == null && (performance == null ? void 0 : performance.outputTokensPerSecond) == null) {
1783
+ if (usage?.totalTokens == null && usage?.outputTokens == null && performance?.outputTokensPerSecond == null) {
1852
1784
  return void 0;
1853
1785
  }
1854
1786
  return {
1855
- ...(usage == null ? void 0 : usage.totalTokens) == null && (usage == null ? void 0 : usage.outputTokens) == null ? {} : {
1787
+ ...usage?.totalTokens == null && usage?.outputTokens == null ? {} : {
1856
1788
  usage: {
1857
1789
  ...usage.totalTokens == null ? {} : { totalTokens: usage.totalTokens },
1858
1790
  ...usage.outputTokens == null ? {} : { outputTokens: usage.outputTokens }
1859
1791
  }
1860
1792
  },
1861
- ...(performance == null ? void 0 : performance.outputTokensPerSecond) == null ? {} : {
1793
+ ...performance?.outputTokensPerSecond == null ? {} : {
1862
1794
  performance: {
1863
1795
  outputTokensPerSecond: performance.outputTokensPerSecond
1864
1796
  }
@@ -1883,8 +1815,7 @@ function createUserMessage(id, text) {
1883
1815
  };
1884
1816
  }
1885
1817
  function upsertResponseMessage(messages, responseMessage, replaceLast) {
1886
- var _a;
1887
- if (replaceLast && ((_a = messages.at(-1)) == null ? void 0 : _a.role) === "assistant") {
1818
+ if (replaceLast && messages.at(-1)?.role === "assistant") {
1888
1819
  messages[messages.length - 1] = responseMessage;
1889
1820
  return;
1890
1821
  }
@@ -1892,7 +1823,7 @@ function upsertResponseMessage(messages, responseMessage, replaceLast) {
1892
1823
  }
1893
1824
  function lastAssistantMessage(messages) {
1894
1825
  const message = messages.at(-1);
1895
- return (message == null ? void 0 : message.role) === "assistant" ? message : void 0;
1826
+ return message?.role === "assistant" ? message : void 0;
1896
1827
  }
1897
1828
  function findPendingToolApprovalRequests(message) {
1898
1829
  const requests = [];