@orion-agents/orion-code 0.4.7 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/README.md +8 -9
  3. package/README.zh-CN.md +8 -8
  4. package/dist/acp/session-updates.js +1 -0
  5. package/dist/cli.js +42 -3
  6. package/dist/commands/session-command-handlers.js +8 -3
  7. package/dist/commands/system-commands.js +3 -3
  8. package/dist/commands/types.d.ts +3 -0
  9. package/dist/framework/loop-progress.js +3 -1
  10. package/dist/framework/query.d.ts +6 -8
  11. package/dist/framework/query.js +39 -76
  12. package/dist/framework/tool-serializer.d.ts +12 -0
  13. package/dist/framework/tool-serializer.js +35 -0
  14. package/dist/framework/tool.d.ts +2 -0
  15. package/dist/framework/verification-command.d.ts +21 -0
  16. package/dist/framework/verification-command.js +53 -4
  17. package/dist/harness/context-harness.d.ts +3 -9
  18. package/dist/harness/context-harness.js +43 -163
  19. package/dist/harness/ledger.js +2 -1
  20. package/dist/harness/state.d.ts +3 -0
  21. package/dist/harness/state.js +37 -4
  22. package/dist/harness/task-checklist.d.ts +1 -1
  23. package/dist/harness/task-checklist.js +1 -1
  24. package/dist/harness/types.d.ts +1 -0
  25. package/dist/harness/verification.js +5 -4
  26. package/dist/print-ui/delivery.d.ts +15 -0
  27. package/dist/print-ui/delivery.js +131 -0
  28. package/dist/print-ui/event-stream.d.ts +6 -1
  29. package/dist/print-ui/event-stream.js +56 -10
  30. package/dist/print-ui/launch.d.ts +5 -0
  31. package/dist/print-ui/launch.js +66 -9
  32. package/dist/runtime/agent-loop.d.ts +3 -1
  33. package/dist/runtime/agent-loop.js +26 -41
  34. package/dist/runtime/agent-runtime-controller.d.ts +4 -1
  35. package/dist/runtime/agent-runtime-controller.js +36 -22
  36. package/dist/runtime/agent-runtime-runner.d.ts +4 -0
  37. package/dist/runtime/agent-runtime-runner.js +9 -0
  38. package/dist/runtime/builtin-tool-provider.js +6 -5
  39. package/dist/runtime/composer/layout.d.ts +1 -1
  40. package/dist/runtime/composer/layout.js +5 -5
  41. package/dist/runtime/core-tools/descriptors.d.ts +1 -1
  42. package/dist/runtime/core-tools/descriptors.js +39 -1
  43. package/dist/runtime/first-party-core-provider.js +1 -0
  44. package/dist/runtime/first-party-tool-services.js +10 -0
  45. package/dist/runtime/goal-lifecycle-v2.js +5 -0
  46. package/dist/runtime/goal-runtime-coordinator.js +6 -2
  47. package/dist/runtime/goals/evidence.js +2 -0
  48. package/dist/runtime/legacy-thread-materializer.d.ts +7 -0
  49. package/dist/runtime/legacy-thread-materializer.js +32 -6
  50. package/dist/runtime/orion-runtime-v1.d.ts +2 -1
  51. package/dist/runtime/orion-runtime-v1.js +34 -6
  52. package/dist/runtime/product-bootstrap.d.ts +2 -0
  53. package/dist/runtime/product-bootstrap.js +1 -0
  54. package/dist/runtime/product-orion-runtime.d.ts +2 -1
  55. package/dist/runtime/product-orion-runtime.js +7 -2
  56. package/dist/runtime/rich-text/layout.d.ts +3 -1
  57. package/dist/runtime/rich-text/layout.js +37 -22
  58. package/dist/runtime/shell-process-sessions.d.ts +41 -0
  59. package/dist/runtime/shell-process-sessions.js +258 -0
  60. package/dist/runtime/step-snapshot.js +61 -11
  61. package/dist/runtime/subagents/presets.d.ts +1 -1
  62. package/dist/runtime/subagents/presets.js +1 -0
  63. package/dist/runtime/task-context-recovery.js +14 -3
  64. package/dist/runtime/task-context-service.d.ts +2 -6
  65. package/dist/runtime/task-context-service.js +3 -12
  66. package/dist/runtime/thread-event-store.d.ts +3 -0
  67. package/dist/runtime/thread-event-store.js +35 -22
  68. package/dist/runtime/thread-session-index.d.ts +15 -3
  69. package/dist/runtime/thread-session-index.js +152 -45
  70. package/dist/runtime/thread-session-view.js +1 -1
  71. package/dist/runtime/thread-ui-adapter.d.ts +1 -1
  72. package/dist/runtime/thread-ui-adapter.js +23 -5
  73. package/dist/runtime/tool-gateway.d.ts +1 -0
  74. package/dist/runtime/tool-gateway.js +1 -0
  75. package/dist/runtime/tool-transcript-entry.d.ts +8 -1
  76. package/dist/runtime/tool-transcript-entry.js +35 -7
  77. package/dist/runtime/ui-events.d.ts +10 -0
  78. package/dist/runtime/verification-feedback.d.ts +4 -0
  79. package/dist/runtime/verification-feedback.js +61 -0
  80. package/dist/services/global-config.d.ts +1 -1
  81. package/dist/services/global-config.js +2 -0
  82. package/dist/services/llm.d.ts +3 -0
  83. package/dist/services/llm.js +48 -4
  84. package/dist/terminal-ui/raw-editor.js +2 -1
  85. package/dist/tools/bash_security.d.ts +1 -24
  86. package/dist/tools/bash_security.js +7 -124
  87. package/dist/tools/core/exec-command.js +51 -42
  88. package/dist/tools/core/index.d.ts +2 -1
  89. package/dist/tools/core/index.js +4 -1
  90. package/dist/tools/core/process-session.d.ts +2 -0
  91. package/dist/tools/core/process-session.js +54 -0
  92. package/dist/tools/todo.js +9 -13
  93. package/dist/tui-core/frame.d.ts +2 -0
  94. package/dist/tui-core/frame.js +19 -0
  95. package/dist/tui-core/input-parser.d.ts +4 -1
  96. package/dist/tui-core/input-parser.js +22 -0
  97. package/dist/tui-ui/chrome-view-model.d.ts +0 -2
  98. package/dist/tui-ui/chrome-view-model.js +54 -56
  99. package/dist/tui-ui/launch.js +133 -202
  100. package/dist/tui-ui/layout.d.ts +16 -41
  101. package/dist/tui-ui/layout.js +408 -295
  102. package/dist/tui-ui/render-scheduler.d.ts +2 -5
  103. package/dist/tui-ui/render-scheduler.js +10 -10
  104. package/dist/tui-ui/response-clipboard.d.ts +17 -0
  105. package/dist/tui-ui/response-clipboard.js +201 -0
  106. package/dist/tui-ui/runner.d.ts +65 -80
  107. package/dist/tui-ui/runner.js +545 -738
  108. package/dist/tui-ui/session-picker-preview.d.ts +8 -0
  109. package/dist/tui-ui/session-picker-preview.js +119 -0
  110. package/dist/tui-ui/session-picker.d.ts +20 -0
  111. package/dist/tui-ui/session-picker.js +42 -0
  112. package/dist/tui-ui/state.d.ts +34 -81
  113. package/dist/tui-ui/state.js +155 -288
  114. package/dist/tui-ui/terminal-image.d.ts +3 -7
  115. package/dist/tui-ui/terminal-image.js +18 -47
  116. package/dist/tui-ui/terminal-viewport.d.ts +55 -0
  117. package/dist/tui-ui/terminal-viewport.js +221 -0
  118. package/dist/tui-ui/transcript-layout.d.ts +5 -0
  119. package/dist/tui-ui/transcript-layout.js +43 -28
  120. package/dist/tui-ui/transcript-pager.d.ts +39 -0
  121. package/dist/tui-ui/transcript-pager.js +278 -0
  122. package/dist/tui-ui/transcript-tool-output.d.ts +16 -0
  123. package/dist/tui-ui/transcript-tool-output.js +102 -0
  124. package/dist/utils/bounded-file.d.ts +4 -0
  125. package/dist/utils/bounded-file.js +30 -0
  126. package/dist/utils/command-process.d.ts +4 -0
  127. package/dist/utils/command-process.js +23 -0
  128. package/dist/utils/shell-command.d.ts +29 -0
  129. package/dist/utils/shell-command.js +185 -0
  130. package/docs/cli-guide.md +50 -6
  131. package/npm-shrinkwrap.json +115 -15
  132. package/package.json +4 -1
  133. package/dist/tui-ui/inline-surface.d.ts +0 -191
  134. package/dist/tui-ui/inline-surface.js +0 -644
  135. package/dist/tui-ui/input-ownership.d.ts +0 -46
  136. package/dist/tui-ui/input-ownership.js +0 -74
  137. package/dist/tui-ui/transcript-inspector-layout.d.ts +0 -9
  138. package/dist/tui-ui/transcript-inspector-layout.js +0 -107
  139. package/dist/tui-ui/transcript-inspector-surface.d.ts +0 -18
  140. package/dist/tui-ui/transcript-inspector-surface.js +0 -91
  141. package/dist/tui-ui/transcript-inspector.d.ts +0 -36
  142. package/dist/tui-ui/transcript-inspector.js +0 -129
@@ -5,13 +5,12 @@ const frame_1 = require("../tui-core/frame");
5
5
  const input_parser_1 = require("../tui-core/input-parser");
6
6
  const commands_1 = require("../commands");
7
7
  const layout_1 = require("./layout");
8
+ const transcript_pager_1 = require("./transcript-pager");
8
9
  const pickers_1 = require("./pickers");
9
10
  const ui_view_model_1 = require("../runtime/ui-view-model");
10
11
  const render_scheduler_1 = require("./render-scheduler");
11
12
  const state_1 = require("./state");
12
- const input_ownership_1 = require("./input-ownership");
13
- const transcript_inspector_1 = require("./transcript-inspector");
14
- const transcript_inspector_layout_1 = require("./transcript-inspector-layout");
13
+ const transcript_tool_output_1 = require("./transcript-tool-output");
15
14
  const transcript_cache_1 = require("./transcript-cache");
16
15
  const transcript_layout_1 = require("./transcript-layout");
17
16
  const theme_1 = require("./theme");
@@ -19,6 +18,9 @@ const history_1 = require("../runtime/composer/history");
19
18
  const promises_1 = require("fs/promises");
20
19
  const os_1 = require("os");
21
20
  const path_1 = require("path");
21
+ const EXIT_HISTORY_ROWS = 2000;
22
+ const PREVIEW_DEBOUNCE_MS = 75;
23
+ const MAX_SESSION_QUERY_LENGTH = 512;
22
24
  /** Actions that should use 'stream' priority (FPS-capped). */
23
25
  const STREAM_ACTIONS = new Set([
24
26
  'updateTranscript',
@@ -30,38 +32,33 @@ const STREAM_ACTIONS = new Set([
30
32
  'researchEvent',
31
33
  'agentModeChanged',
32
34
  ]);
33
- const MAX_REFLOW_RECORDS = 128;
34
- const REFLOW_RESERVED_ROWS = 5; // Three composer rows, status, and activity.
35
35
  class TuiRunner {
36
36
  constructor(options) {
37
37
  this.options = options;
38
38
  this.parser = new input_parser_1.TuiInputParser();
39
- this.inputOwnership = new input_ownership_1.TuiInputOwnershipController();
39
+ this.previewGeneration = 0;
40
40
  this.transcriptCache = new transcript_cache_1.TranscriptLayoutCache();
41
+ this.historyLayoutCache = new transcript_cache_1.TranscriptLayoutCache();
42
+ this.chatPager = new transcript_pager_1.TranscriptPager();
43
+ this.transcriptPager = new transcript_pager_1.TranscriptPager();
44
+ this.earlierCursor = 0;
45
+ this.restoredCompletionOrder = 0;
46
+ this.earlierRecords = [];
41
47
  this.history = history_1.initialHistoryState;
42
48
  this.historySearchQuery = '';
43
49
  this.historySearchIndex = 0;
44
50
  this.historySearchMatch = '';
45
51
  this.animationFrame = 0;
46
- this.animationTimer = null;
52
+ this.activityTimer = null;
47
53
  this.surfaceFailed = false;
48
- this.inspectorReady = false;
49
- this.inspectorSearchActive = false;
54
+ this.stopped = false;
55
+ this.showingTranscript = false;
56
+ this.clipboardQueue = Promise.resolve();
50
57
  this.modalTransition = Promise.resolve();
51
- this.commitSequence = 0;
52
- this.commitInFlight = false;
53
- this.flushAllTranscript = false;
54
- this.commitMismatchRetries = 0;
55
58
  this.lastFrame = null;
56
- this.surfaceResizePending = false;
57
- this.transcriptChangedDuringResize = false;
58
- this.resizeEpoch = 0;
59
- this.surfaceResizeGeneration = 0;
60
59
  this.counters = {
61
60
  layoutCount: 0,
62
61
  paintCount: 0,
63
- changedRows: 0,
64
- commitCount: 0,
65
62
  };
66
63
  this.state = {
67
64
  ...state_1.initialTuiUiState,
@@ -72,14 +69,13 @@ class TuiRunner {
72
69
  this.surface = options.surface ?? null;
73
70
  this.theme = (0, theme_1.resolveTuiTheme)(options.theme);
74
71
  this.themeId = options.themeId ?? theme_1.DEFAULT_TUI_THEME_ID;
75
- this.inspectorSurface = options.inspectorSurface ?? null;
76
- this.inspectorController = options.detailRepository
77
- ? new transcript_inspector_1.TranscriptInspectorController(options.detailRepository, options.cwd ?? process.cwd())
72
+ this.now = options.schedulerDeps?.now ?? (() => performance.now());
73
+ this.toolOutput = options.detailRepository
74
+ ? new transcript_tool_output_1.TranscriptToolOutput(options.detailRepository, options.cwd ?? process.cwd())
78
75
  : null;
79
- this.scheduler = (0, render_scheduler_1.createTuiRenderScheduler)(() => this.renderLive(), options.schedulerDeps);
76
+ this.scheduler = (0, render_scheduler_1.createTuiRenderScheduler)(() => this.paint(), options.schedulerDeps);
80
77
  this.events = (0, state_1.createTuiUiEventSink)(action => this.dispatch(action));
81
- // Initial render: paint the live region immediately.
82
- this.renderLive();
78
+ this.paint();
83
79
  }
84
80
  getState() {
85
81
  return this.state;
@@ -95,82 +91,79 @@ class TuiRunner {
95
91
  return this.scheduler;
96
92
  }
97
93
  stop() {
94
+ this.stopped = true;
95
+ this.closeTranscriptPager();
96
+ this.toolOutput?.reset();
98
97
  clearTimeout(this.escapeTimer);
99
- this.stopAnimation();
98
+ clearTimeout(this.previewTimer);
99
+ this.stopActivity();
100
100
  this.scheduler.stop();
101
101
  }
102
- /** Stop stale-width paints as soon as the terminal reports SIGWINCH. */
103
- beginResize(width = this.width) {
104
- if (this.state.inspector)
105
- return;
106
- if (!this.surface || this.surfaceFailed)
107
- return;
108
- this.surfaceResizePending = true;
109
- this.resizeEpoch += 1;
110
- this.surfaceResizeGeneration = this.surface.beginResize(width);
111
- }
112
102
  resize(width, height) {
113
- if (this.state.inspector) {
114
- this.width = width;
115
- this.height = height;
116
- this.paintInspector();
117
- return;
118
- }
119
- this.beginResize(width);
120
- const resizeEpoch = this.resizeEpoch;
121
- const surfaceResizeGeneration = this.surfaceResizeGeneration;
122
103
  this.width = width;
123
104
  this.height = height;
124
- // Invalidate transcript cache on resize so committed entries are re-laid-out
125
- // at the new width.
126
- this.transcriptCache.invalidate(this.state.transcriptGeneration, this.transcriptWidth, this.themeId);
127
- if (this.surface && !this.surfaceFailed) {
128
- // Surface resize is async (serialized FIFO); fire-and-forget is safe
129
- // because subsequent renders go through the surface queue too.
130
- void this.surface
131
- .resize(width, height, () => {
132
- const frame = this.buildLiveFrame(width);
133
- this.lastFrame = frame;
134
- this.counters.layoutCount += 1;
135
- this.counters.paintCount += 1;
136
- return frame;
137
- }, surfaceResizeGeneration)
138
- .then(() => {
139
- if (resizeEpoch !== this.resizeEpoch)
140
- return;
141
- this.surfaceResizePending = false;
142
- if (this.transcriptChangedDuringResize) {
143
- this.transcriptChangedDuringResize = false;
144
- this.tryCommit(this.state, true);
145
- }
146
- this.scheduler.request('immediate');
147
- this.scheduler.flush();
148
- })
149
- .catch(error => this.handleSurfaceError(error));
150
- return;
151
- }
152
- this.scheduler.request('immediate');
153
- this.scheduler.flush();
105
+ this.surface?.invalidate();
106
+ this.scheduler.request('stream');
154
107
  }
155
108
  dispatch(action) {
156
- const prevState = this.state;
157
- this.state = (0, state_1.tuiUiReducer)(this.state, action);
158
- if (action.type === 'replaceTranscript')
159
- this.inspectorController?.reset();
160
- if (action.type === 'setProcessing') {
109
+ if (this.stopped)
110
+ return;
111
+ const previous = this.state;
112
+ this.state = (0, state_1.tuiUiReducer)(previous, action);
113
+ if (previous.overlay !== this.state.overlay)
114
+ this.updateSessionPreview(previous.overlay);
115
+ if (this.state.overlay)
116
+ this.closeTranscriptPager();
117
+ if (this.state.transcriptGeneration !== previous.transcriptGeneration) {
118
+ this.toolOutput?.reset();
119
+ this.setTranscriptHistorySource(undefined);
120
+ this.closeTranscriptPager();
121
+ this.chatPager.reset();
122
+ this.transcriptPager.reset();
123
+ }
124
+ if (action.type === 'setProcessing' && action.processing !== previous.processing) {
161
125
  if (action.processing)
162
- this.startAnimation();
126
+ this.startActivity();
163
127
  else
164
- this.stopAnimation();
128
+ this.stopActivity();
165
129
  }
166
- if (action.type === 'setToolOutputViewMode' && action.mode !== prevState.toolOutputViewMode) {
130
+ if (action.type === 'setToolOutputViewMode' && action.mode !== previous.toolOutputViewMode) {
167
131
  this.transcriptCache.clear();
168
132
  }
169
- // Check if any transcript entries became committable (finalized).
170
- this.tryCommit(prevState);
171
133
  const priority = STREAM_ACTIONS.has(action.type) ? 'stream' : 'immediate';
172
134
  this.scheduler.request(priority);
173
135
  }
136
+ updateSessionPreview(previous) {
137
+ const overlay = this.state.overlay;
138
+ const session = overlay?.type === 'sessions' ? overlay.matches[overlay.selectedIndex] : undefined;
139
+ const prior = previous?.type === 'sessions' ? previous.matches[previous.selectedIndex] : undefined;
140
+ if ((overlay?.type !== 'sessions' && previous?.type !== 'sessions') ||
141
+ (overlay?.type === 'sessions' &&
142
+ previous?.type === 'sessions' &&
143
+ overlay.request === previous.request &&
144
+ session === prior))
145
+ return;
146
+ clearTimeout(this.previewTimer);
147
+ const generation = ++this.previewGeneration;
148
+ const load = this.options.loadSessionPreview;
149
+ if (!session || !load)
150
+ return;
151
+ this.previewTimer = setTimeout(() => {
152
+ void (async () => {
153
+ let messages = [];
154
+ try {
155
+ messages = await load(session);
156
+ }
157
+ catch {
158
+ // An unreadable preview must not prevent an explicit resume.
159
+ }
160
+ if (!this.stopped && generation === this.previewGeneration) {
161
+ this.dispatch({ type: 'setSessionPreview', sessionId: session.id, messages });
162
+ }
163
+ })();
164
+ }, PREVIEW_DEBOUNCE_MS);
165
+ this.previewTimer.unref?.();
166
+ }
174
167
  feedInput(chunk) {
175
168
  clearTimeout(this.escapeTimer);
176
169
  const events = this.parser.feed(chunk, { detectUnbracketedMultilinePaste: true });
@@ -187,234 +180,122 @@ class TuiRunner {
187
180
  }
188
181
  return events;
189
182
  }
190
- /**
191
- * Render the full frame (legacy path for tests without surface).
192
- * Uses renderTuiUiFrame which includes both static and live transcript.
193
- */
183
+ setTranscriptHistorySource(source) {
184
+ this.historyLayoutCache.clear();
185
+ this.historySource = source;
186
+ this.earlierRecords = [];
187
+ this.earlierCursor = source?.before ?? 0;
188
+ this.restoredCompletionOrder = source ? this.state.latestCompletionOrder : 0;
189
+ }
194
190
  renderFullFrame() {
195
191
  this.counters.layoutCount += 1;
196
- const frame = (0, layout_1.renderTuiUiFrame)(this.state, {
192
+ const layoutOptions = {
197
193
  width: this.width,
198
194
  height: this.height,
199
195
  ...this.transcriptLayoutOptions(),
200
- });
196
+ };
197
+ const visibleRecords = new Set();
198
+ const frame = this.showingTranscript
199
+ ? (0, layout_1.renderTranscriptPagerFrame)(this.state, {
200
+ ...layoutOptions,
201
+ transcriptPager: this.transcriptPager,
202
+ olderRecords: this.earlierRecords,
203
+ hasEarlierRecords: this.earlierCursor > 0,
204
+ loadingEarlierRecords: this.pendingHistoryPage !== undefined,
205
+ layoutTranscriptRecord: (entry, width) => this.layoutTranscriptRecord(entry, width, true),
206
+ onVisibleRecord: entry => visibleRecords.add(entry),
207
+ })
208
+ : (0, layout_1.renderTuiUiFrame)(this.state, { ...layoutOptions, transcriptPager: this.chatPager });
209
+ if (this.showingTranscript) {
210
+ this.toolOutput?.observe(visibleRecords, () => {
211
+ this.historyLayoutCache.clear();
212
+ if (this.showingTranscript && !this.stopped)
213
+ this.scheduler.request('stream');
214
+ });
215
+ }
201
216
  this.lastFrame = frame;
202
217
  this.counters.paintCount += 1;
203
218
  return frame;
204
219
  }
205
- /**
206
- * Render the live region via InlineTerminalSurface.
207
- * In inline mode, recent transcript entries stay in the live region so
208
- * their source can be laid out again after a resize.
209
- * When no surface (test mode), renders the full frame including committed
210
- * transcript so tests can inspect complete content via getLastFrame().
211
- */
212
- renderLive() {
213
- if (this.state.inspector) {
214
- this.paintInspector();
220
+ paint() {
221
+ if (this.stopped || this.surfaceFailed)
215
222
  return;
223
+ try {
224
+ const frame = this.renderFullFrame();
225
+ void this.surface?.render(frame).catch(error => this.handleSurfaceError(error));
216
226
  }
217
- if (this.surface && !this.surfaceFailed) {
218
- if (this.surfaceResizePending)
219
- return;
220
- this.counters.layoutCount += 1;
221
- // Production path: render only the live region for inline surface.
222
- const frame = this.buildLiveFrame(this.width);
223
- this.lastFrame = frame;
224
- this.counters.paintCount += 1;
225
- // Surface renderLive is async (serialized FIFO), but for production use
226
- // we fire-and-forget because the next render will also go through the queue.
227
- void this.surface.renderLive(frame).catch(error => this.handleSurfaceError(error));
228
- }
229
- else {
230
- this.counters.layoutCount += 1;
231
- // Test path (no surface): render the full frame so getLastFrame() /
232
- // getVisibleRows() return complete content including committed transcript.
233
- const frame = (0, layout_1.renderTuiUiFrame)(this.state, {
234
- width: this.width,
235
- height: this.height,
236
- ...this.transcriptLayoutOptions(),
237
- });
238
- this.lastFrame = frame;
239
- this.counters.paintCount += 1;
227
+ catch (error) {
228
+ this.handleSurfaceError(error);
240
229
  }
241
230
  }
242
- /** Build a compact live-region frame that grows only for active content. */
243
- buildLiveFrame(terminalWidth) {
244
- const width = this.surface
245
- ? Math.max(1, Math.floor(terminalWidth) - 1)
246
- : Math.max(1, Math.floor(terminalWidth));
247
- const height = this.surface
248
- ? (0, layout_1.measureTuiLiveFrameHeight)(this.state, width, this.surface.getLiveBandRows(), this.transcriptLayoutOptions())
249
- : this.height - 1;
250
- return (0, layout_1.renderTuiLiveFrame)(this.state, {
251
- width,
252
- height,
253
- ...this.transcriptLayoutOptions(),
254
- });
255
- }
256
- /**
257
- * Try to commit any newly-finalized transcript entries to scrollback.
258
- * Called after each dispatch. Only commits entries that are committable
259
- * but not yet queued.
260
- */
261
- tryCommit(prevState, force = false) {
262
- if (!this.surface || this.surfaceFailed)
263
- return;
264
- const prevCommittable = prevState.committableTranscriptCount;
265
- const currCommittable = this.state.committableTranscriptCount;
266
- const generationChanged = this.state.transcriptGeneration !== prevState.transcriptGeneration;
267
- if (!force && !generationChanged && currCommittable <= prevCommittable)
268
- return;
269
- if (this.surfaceResizePending) {
270
- this.transcriptChangedDuringResize = true;
271
- return;
231
+ /** Project only completed records onto the shell once when the UI releases the terminal. */
232
+ completedHistoryRows(width = this.width) {
233
+ const blocks = [];
234
+ let remaining = EXIT_HISTORY_ROWS;
235
+ for (let index = this.state.transcript.length - 1; index >= 0 && remaining > 0; index -= 1) {
236
+ const entry = this.state.transcript[index];
237
+ if (!entry.finalized)
238
+ continue;
239
+ const layout = this.layoutTranscriptRecord(entry, width);
240
+ const rows = layout.slice(-remaining);
241
+ remaining -= rows.length;
242
+ blocks.push(rows);
272
243
  }
273
- if (this.state.inspector || this.commitInFlight)
274
- return;
275
- if (currCommittable <= this.state.queuedTranscriptCount)
276
- return;
277
- // Keep a viewport-sized suffix as source records. Terminal scrollback
278
- // owns older rows, which cannot be rewritten safely by the application.
279
- const pending = (0, state_1.pendingCommitRecords)(this.state);
280
- const entriesToCommit = this.flushAllTranscript
281
- ? pending
282
- : pending.slice(0, this.historyOverflowStart(pending));
283
- if (entriesToCommit.length === 0)
284
- return;
285
- // Advance the queued boundary so we don't double-commit.
286
- this.state = (0, state_1.markTranscriptQueued)(this.state, entriesToCommit.length);
287
- // Build the commit batch.
288
- const committedEntries = entriesToCommit.map(entry => ({
289
- displayKey: entry.id,
290
- rows: this.layoutTranscriptRecord(entry, this.transcriptWidth),
291
- }));
292
- const batch = {
293
- batchId: `tui-commit-${++this.commitSequence}`,
294
- generation: this.state.transcriptGeneration,
295
- reason: 'finalize',
296
- entries: committedEntries,
297
- };
298
- // The LiveFrameProvider ensures the live frame is rebuilt after commit
299
- // with the latest state (where committed entries are no longer in the
300
- // live region).
301
- const generation = batch.generation;
302
- const getLatestLiveFrame = () => this.buildLiveFrame(this.width);
303
- this.commitInFlight = true;
304
- let continueCommit = true;
305
- // Surface commit is async (serialized FIFO). Fire-and-forget: the
306
- // commit's internal getLatestLiveFrame already rebuilds the live region,
307
- // so no additional scheduler paint is needed here.
308
- void this.surface
309
- .commit(batch, getLatestLiveFrame)
310
- .then(result => {
311
- if (result.batchId !== batch.batchId ||
312
- result.generation !== generation ||
313
- result.committedEntries !== entriesToCommit.length) {
314
- if (this.state.transcriptGeneration === generation) {
315
- this.state = {
316
- ...this.state,
317
- queuedTranscriptCount: Math.max(0, this.state.queuedTranscriptCount - entriesToCommit.length),
318
- };
319
- this.commitMismatchRetries += 1;
320
- if (this.commitMismatchRetries > 1) {
321
- continueCommit = false;
322
- this.state = (0, state_1.tuiUiReducer)(this.state, {
323
- type: 'setStatus',
324
- message: 'TUI transcript acknowledgement mismatch; retained content for retry.',
325
- });
326
- }
327
- }
328
- void this.surface?.forceRedraw(this.buildLiveFrame(this.width));
329
- return;
330
- }
331
- const acknowledgement = (0, state_1.acknowledgeTranscriptCommit)(this.state, {
332
- generation,
333
- recordIds: result.displayKeys ?? [],
334
- });
335
- if (!acknowledgement.accepted) {
336
- if (this.state.transcriptGeneration === generation) {
337
- this.state = {
338
- ...this.state,
339
- queuedTranscriptCount: Math.max(0, this.state.queuedTranscriptCount - entriesToCommit.length),
340
- };
341
- this.commitMismatchRetries += 1;
342
- if (this.commitMismatchRetries > 1) {
343
- continueCommit = false;
344
- this.state = (0, state_1.tuiUiReducer)(this.state, {
345
- type: 'setStatus',
346
- message: 'TUI transcript acknowledgement mismatch; retained content for retry.',
347
- });
348
- }
349
- }
350
- void this.surface?.forceRedraw(this.buildLiveFrame(this.width));
351
- return;
352
- }
353
- this.state = acknowledgement.state;
354
- this.commitMismatchRetries = 0;
355
- this.counters.commitCount += 1;
356
- })
357
- .catch(error => this.handleSurfaceError(error))
358
- .finally(() => {
359
- this.commitInFlight = false;
360
- if (!this.surfaceFailed && continueCommit)
361
- this.tryCommit(this.state, true);
362
- });
363
- }
364
- historyOverflowStart(pending) {
365
- let remaining = Math.max(1, (this.surface?.getLiveBandRows() ?? this.height) - REFLOW_RESERVED_ROWS);
366
- const firstAllowed = Math.max(0, pending.length - MAX_REFLOW_RECORDS);
367
- let index = pending.length;
368
- for (; index > firstAllowed; index -= 1) {
369
- remaining -= this.layoutTranscriptRecord(pending[index - 1], this.transcriptWidth).length;
370
- if (remaining < 0)
371
- break;
372
- }
373
- return index;
244
+ return blocks.reverse().flat();
374
245
  }
375
246
  /** Layout a transcript record once per revision/width/theme combination. */
376
- layoutTranscriptRecord(entry, width) {
377
- const cached = this.transcriptCache.get(entry.id, entry.revision, this.state.transcriptGeneration, width, this.themeId);
247
+ layoutTranscriptRecord(entry, width, history = false) {
248
+ const cache = history ? this.historyLayoutCache : this.transcriptCache;
249
+ const cached = cache.get(entry.id, entry.revision, this.state.transcriptGeneration, width, this.themeId);
378
250
  if (cached)
379
251
  return cached;
380
- const rows = (0, transcript_layout_1.layoutTranscriptEntry)(entry, {
252
+ // The chat stays byte-bounded on resume. The pager can render the retained entry on demand.
253
+ const durableContent = history && entry.revision === 1
254
+ ? this.historySource?.recentEntries.find(recent => recent.id === entry.id)?.content
255
+ : undefined;
256
+ const displayEntry = durableContent === undefined ? entry : { ...entry, content: durableContent };
257
+ const rows = (0, transcript_layout_1.layoutTranscriptEntry)(displayEntry, {
381
258
  width,
382
259
  theme: this.theme,
383
260
  toolOutputMode: this.state.toolOutputViewMode,
261
+ history,
262
+ artifactOutput: history ? this.toolOutput?.get(entry) : undefined,
384
263
  });
385
- this.transcriptCache.set(entry.id, entry.revision, rows, this.state.transcriptGeneration, width, this.themeId);
264
+ cache.set(entry.id, entry.revision, rows, this.state.transcriptGeneration, width, this.themeId);
386
265
  return rows;
387
266
  }
388
- get transcriptWidth() {
389
- return this.surface ? Math.max(1, this.width - 1) : Math.max(1, this.width);
390
- }
391
267
  transcriptLayoutOptions() {
392
268
  return {
393
- transcriptWidth: this.transcriptWidth,
269
+ transcriptWidth: this.width,
394
270
  theme: this.theme,
395
271
  toolOutputMode: this.state.toolOutputViewMode,
396
272
  statusLine: this.options.statusLine,
397
- mascot: this.options.mascot,
273
+ startupRows: this.state.transcript.length === 0 ? this.options.startupRows?.(this.width) : undefined,
398
274
  animationFrame: this.animationFrame,
275
+ activityElapsedSeconds: this.activityStartedAt === undefined
276
+ ? undefined
277
+ : Math.max(0, Math.floor((this.now() - this.activityStartedAt) / 1000)),
399
278
  layoutTranscriptRecord: (entry, width) => this.layoutTranscriptRecord(entry, width),
400
279
  };
401
280
  }
402
- startAnimation() {
403
- if (this.animationTimer || this.options.motion === 'off') {
404
- return;
405
- }
406
- this.animationTimer = setInterval(() => {
407
- if (this.state.overlay?.type === 'permission' || this.state.inspector)
281
+ startActivity() {
282
+ this.activityStartedAt = this.now();
283
+ const animated = this.options.motion !== 'off';
284
+ const interval = animated ? (this.options.motion === 'reduced' ? 500 : 250) : 1000;
285
+ this.activityTimer = setInterval(() => {
286
+ if (this.state.overlay?.type === 'permission' || this.showingTranscript)
408
287
  return;
409
- this.animationFrame = (this.animationFrame + 1) % 8;
288
+ if (animated)
289
+ this.animationFrame += 1;
410
290
  this.scheduler.request('stream');
411
- }, this.options.motion === 'reduced' ? 500 : 250);
412
- this.animationTimer.unref?.();
291
+ }, interval);
292
+ this.activityTimer.unref?.();
413
293
  }
414
- stopAnimation() {
415
- if (this.animationTimer)
416
- clearInterval(this.animationTimer);
417
- this.animationTimer = null;
294
+ stopActivity() {
295
+ if (this.activityTimer)
296
+ clearInterval(this.activityTimer);
297
+ this.activityTimer = null;
298
+ this.activityStartedAt = undefined;
418
299
  this.animationFrame = 0;
419
300
  }
420
301
  handleSurfaceError(error) {
@@ -429,8 +310,15 @@ class TuiRunner {
429
310
  this.options.onSurfaceError?.(error);
430
311
  }
431
312
  applyInputEvent(event) {
432
- if (this.state.inspector) {
433
- this.applyInspectorInput(event);
313
+ if (this.stopped)
314
+ return;
315
+ if (this.showingTranscript) {
316
+ this.applyTranscriptInput(event);
317
+ return;
318
+ }
319
+ const overlay = this.state.overlay;
320
+ if (overlay?.type === 'sessions' || overlay?.type === 'queue') {
321
+ this.applyWorkbenchModalInput(event, overlay);
434
322
  return;
435
323
  }
436
324
  if (this.state.overlay?.type === 'permission') {
@@ -459,11 +347,145 @@ class TuiRunner {
459
347
  }
460
348
  this.updatePrompt(insertAtCursor(this.state.prompt.value, this.state.prompt.cursor, event.value));
461
349
  return;
350
+ case 'wheel':
351
+ if (!this.state.overlay) {
352
+ this.chatPager.scroll(3 * event.direction);
353
+ this.scheduler.request('immediate');
354
+ }
355
+ return;
462
356
  case 'key':
463
357
  this.applyKey(event.key);
464
358
  return;
465
359
  }
466
360
  }
361
+ applyWorkbenchModalInput(event, overlay) {
362
+ if (event.type === 'key' && event.key === 'ctrl+c') {
363
+ this.options.onCtrlC?.();
364
+ return;
365
+ }
366
+ if (event.type === 'key' && event.key === 'ctrl+l') {
367
+ this.redraw();
368
+ return;
369
+ }
370
+ if (overlay.type === 'sessions') {
371
+ this.applySessionPickerInput(event, overlay);
372
+ return;
373
+ }
374
+ this.applyFollowupQueueInput(event, overlay);
375
+ }
376
+ applySessionPickerInput(event, overlay) {
377
+ const { query } = overlay;
378
+ if (event.type === 'text' || event.type === 'paste') {
379
+ const text = event.value
380
+ .replace(/\s/gu, ' ')
381
+ .slice(0, MAX_SESSION_QUERY_LENGTH - query.value.length);
382
+ if (text)
383
+ this.dispatch({
384
+ type: 'setModalPrompt',
385
+ prompt: insertAtCursor(query.value, query.cursor, text),
386
+ });
387
+ return;
388
+ }
389
+ const pageSize = overlay.request.maxVisibleItems ?? 10;
390
+ const delta = pickerMovement(event, pageSize);
391
+ if (delta) {
392
+ this.dispatch({ type: 'moveOverlaySelection', delta });
393
+ return;
394
+ }
395
+ if (event.type !== 'key')
396
+ return;
397
+ if (event.key === 'escape') {
398
+ this.dispatch({ type: 'closeOverlay' });
399
+ return;
400
+ }
401
+ if (event.key === 'enter') {
402
+ const selected = overlay.matches[overlay.selectedIndex];
403
+ if (selected &&
404
+ this.options.onSelectSession?.(selected.id, Boolean(overlay.request.allProjects))) {
405
+ this.dispatch({ type: 'closeOverlay' });
406
+ }
407
+ return;
408
+ }
409
+ if (event.key === 'newline')
410
+ return;
411
+ const next = editPromptText(query, event.key);
412
+ if (next)
413
+ this.dispatch({ type: 'setModalPrompt', prompt: next });
414
+ }
415
+ applyFollowupQueueInput(event, overlay) {
416
+ const { editor } = overlay;
417
+ if (event.type === 'key' && event.key === 'escape') {
418
+ this.dispatch({ type: editor ? 'endFollowupEdit' : 'closeOverlay' });
419
+ return;
420
+ }
421
+ if (editor) {
422
+ const { value, cursor } = editor.draft;
423
+ if (event.type === 'text' || event.type === 'paste') {
424
+ this.dispatch({
425
+ type: 'setModalPrompt',
426
+ prompt: insertAtCursor(value, cursor, event.value),
427
+ });
428
+ }
429
+ else if (event.type === 'key' && event.key === 'enter') {
430
+ if (this.mutateFollowupQueue({
431
+ type: 'edit',
432
+ itemId: editor.itemId,
433
+ revision: editor.revision,
434
+ text: value,
435
+ })) {
436
+ this.dispatch({ type: 'endFollowupEdit' });
437
+ }
438
+ }
439
+ else if (event.type === 'key') {
440
+ const key = event.key;
441
+ const moved = key === 'up' || key === 'down'
442
+ ? (0, layout_1.moveTuiPromptVisualCursor)(value, cursor, this.width, key === 'up' ? -1 : 1)
443
+ : undefined;
444
+ const next = moved === undefined ? editPromptText(editor.draft, key) : { value, cursor: moved };
445
+ if (next)
446
+ this.dispatch({ type: 'setModalPrompt', prompt: next });
447
+ }
448
+ return;
449
+ }
450
+ const delta = pickerMovement(event, 8);
451
+ if (delta) {
452
+ this.dispatch({ type: 'moveOverlaySelection', delta });
453
+ return;
454
+ }
455
+ const items = this.state.followupQueue.items;
456
+ const selected = items[overlay.selectedIndex];
457
+ if (!selected)
458
+ return;
459
+ const target = { itemId: selected.id, revision: selected.revision };
460
+ if (event.type === 'key' && event.key === 'enter') {
461
+ this.dispatch({ type: 'beginFollowupEdit' });
462
+ }
463
+ else if (event.type === 'key' && event.key === 'delete') {
464
+ this.mutateFollowupQueue({ type: 'remove', ...target });
465
+ }
466
+ else if (event.type === 'text' && (event.value === '[' || event.value === ']')) {
467
+ const index = overlay.selectedIndex + (event.value === '[' ? -1 : 1);
468
+ if (index >= 0 && index < items.length)
469
+ this.mutateFollowupQueue({ type: 'move', ...target, index });
470
+ }
471
+ }
472
+ mutateFollowupQueue(mutation) {
473
+ let notice;
474
+ try {
475
+ notice = this.options.onQueueMutation
476
+ ? this.options.onQueueMutation(mutation)
477
+ : 'Queue editing is unavailable.';
478
+ }
479
+ catch {
480
+ notice = 'Could not update the queue. Try again.';
481
+ }
482
+ if (notice) {
483
+ this.dispatch({ type: 'setFollowupNotice', message: notice });
484
+ return false;
485
+ }
486
+ this.dispatch({ type: 'setFollowupNotice', message: '' });
487
+ return true;
488
+ }
467
489
  applyKey(key) {
468
490
  const { value, cursor } = this.state.prompt;
469
491
  const overlay = this.state.overlay;
@@ -474,32 +496,6 @@ class TuiRunner {
474
496
  void this.options.onCycleAgentMode?.();
475
497
  return;
476
498
  }
477
- if (overlay?.type === 'sessions') {
478
- switch (key) {
479
- case 'up':
480
- this.dispatch({ type: 'moveOverlaySelection', delta: -1 });
481
- return;
482
- case 'down':
483
- case 'tab':
484
- this.dispatch({ type: 'moveOverlaySelection', delta: 1 });
485
- return;
486
- case 'pageup':
487
- this.dispatch({
488
- type: 'moveOverlaySelection',
489
- delta: -Math.max(1, overlay.request.maxVisibleItems ?? 10),
490
- });
491
- return;
492
- case 'pagedown':
493
- this.dispatch({
494
- type: 'moveOverlaySelection',
495
- delta: Math.max(1, overlay.request.maxVisibleItems ?? 10),
496
- });
497
- return;
498
- case 'enter':
499
- this.submitPrompt({ allowEmpty: true });
500
- return;
501
- }
502
- }
503
499
  if (overlay?.type === 'model') {
504
500
  switch (key) {
505
501
  case 'up':
@@ -635,6 +631,8 @@ class TuiRunner {
635
631
  return;
636
632
  }
637
633
  const configuredAction = this.configuredActionForKey(key);
634
+ if (overlay && (configuredAction === 'transcript' || configuredAction === 'copy'))
635
+ return;
638
636
  if (configuredAction) {
639
637
  switch (configuredAction) {
640
638
  case 'submit':
@@ -656,10 +654,13 @@ class TuiRunner {
656
654
  this.openComposerInExternalEditor();
657
655
  return;
658
656
  case 'transcript':
659
- this.openToolInspector();
657
+ this.openTranscriptPager();
658
+ return;
659
+ case 'copy':
660
+ this.copyLastResponse();
660
661
  return;
661
662
  case 'redraw':
662
- this.forceOwnedRedraw();
663
+ this.redraw();
663
664
  return;
664
665
  case 'exit':
665
666
  if (!value)
@@ -668,11 +669,13 @@ class TuiRunner {
668
669
  }
669
670
  }
670
671
  switch (key) {
671
- case 'ctrl+o':
672
- this.openToolInspector();
672
+ case 'pageup':
673
+ case 'pagedown':
674
+ this.chatPager.page(key === 'pageup' ? -1 : 1);
675
+ this.scheduler.request('immediate');
673
676
  return;
674
677
  case 'ctrl+l':
675
- this.forceOwnedRedraw();
678
+ this.redraw();
676
679
  return;
677
680
  case 'ctrl+r':
678
681
  this.reverseHistorySearch();
@@ -687,34 +690,31 @@ class TuiRunner {
687
690
  case 'enter':
688
691
  this.submitPrompt();
689
692
  return;
690
- case 'newline':
691
- this.updatePrompt(insertAtCursor(value, cursor, '\n'));
693
+ case 'alt+up':
694
+ if (!overlay && this.state.followupQueue.items.length > 0) {
695
+ this.dispatch({
696
+ type: 'showFollowupQueue',
697
+ selectedIndex: this.state.followupQueue.items.length - 1,
698
+ });
699
+ this.dispatch({ type: 'beginFollowupEdit' });
700
+ }
692
701
  return;
702
+ case 'newline':
693
703
  case 'backspace':
694
- this.updatePrompt(deleteBeforeCursor(value, cursor));
695
- return;
696
704
  case 'delete':
697
- this.updatePrompt(deleteAfterCursor(value, cursor));
698
- return;
699
705
  case 'left':
700
- this.updatePrompt({ value, cursor: previousBoundary(value, cursor) });
701
- return;
702
706
  case 'right':
703
- this.updatePrompt({ value, cursor: nextBoundary(value, cursor) });
704
- return;
705
707
  case 'home':
706
- this.moveCursorLineHome();
707
- return;
708
708
  case 'end':
709
- this.moveCursorLineEnd();
710
- return;
711
709
  case 'ctrl+u':
712
- this.updatePrompt({ value: '', cursor: 0 });
713
- this.dispatch({ type: 'closeOverlay' });
714
- return;
715
- case 'ctrl+w':
716
- this.updatePrompt(deleteWordBeforeCursor(value, cursor));
710
+ case 'ctrl+w': {
711
+ const next = editPromptText({ value, cursor }, key);
712
+ if (next)
713
+ this.updatePrompt(next);
714
+ if (key === 'ctrl+u')
715
+ this.dispatch({ type: 'closeOverlay' });
717
716
  return;
717
+ }
718
718
  case 'ctrl+c':
719
719
  this.options.onCtrlC?.();
720
720
  return;
@@ -735,16 +735,23 @@ class TuiRunner {
735
735
  this.syncPromptOverlay(value, cursor);
736
736
  return;
737
737
  case 'up':
738
- this.moveCursorUpOrHistory();
738
+ this.moveCursorVertically(-1);
739
739
  return;
740
740
  case 'down':
741
- this.moveCursorDownOrHistory();
741
+ this.moveCursorVertically(1);
742
742
  return;
743
743
  }
744
744
  }
745
745
  configuredActionForKey(key) {
746
- const matches = Object.entries(this.options.keymap ?? {}).filter(([, bindings]) => bindings?.includes(key));
747
- return matches[0]?.[0] ?? null;
746
+ const keymap = this.options.keymap;
747
+ const matches = Object.entries(keymap ?? {}).find(([, bindings]) => bindings?.includes(key));
748
+ if (matches)
749
+ return matches[0];
750
+ if (key === 'ctrl+t' && !keymap?.transcript)
751
+ return 'transcript';
752
+ if (key === 'ctrl+o' && !keymap?.copy)
753
+ return 'copy';
754
+ return null;
748
755
  }
749
756
  queuePrompt() {
750
757
  const input = this.state.prompt.value.trim();
@@ -802,6 +809,8 @@ class TuiRunner {
802
809
  const filePath = (0, path_1.join)(directory, 'prompt.md');
803
810
  try {
804
811
  await (0, promises_1.writeFile)(filePath, original, { encoding: 'utf8', mode: 0o600 });
812
+ if (this.stopped)
813
+ return;
805
814
  await this.options.onOpenExternalEditor(filePath);
806
815
  const next = await (0, promises_1.readFile)(filePath, 'utf8');
807
816
  this.updatePrompt({ value: next, cursor: next.length });
@@ -837,55 +846,17 @@ class TuiRunner {
837
846
  const displayValue = (0, history_1.historyCurrentValue)(next, value);
838
847
  this.dispatch({ type: 'setPrompt', value: displayValue, cursor: displayValue.length });
839
848
  }
840
- /**
841
- * Up in a multi-line prompt moves the cursor to the previous visual line;
842
- * only at the first line does it fall back to command history (matching
843
- * shell/editor behaviour). Single-line prompts behave exactly as before.
844
- */
845
- moveCursorUpOrHistory() {
849
+ moveCursorVertically(direction) {
846
850
  if (this.state.overlay)
847
851
  return;
848
852
  const { value, cursor } = this.state.prompt;
849
- const { line, col } = lineColOfCursor(value, cursor);
850
- if (line > 0) {
851
- this.updatePrompt({ value, cursor: cursorOfLineCol(value, line - 1, col) });
852
- }
853
- else {
853
+ const next = (0, layout_1.moveTuiPromptVisualCursor)(value, cursor, this.width, direction);
854
+ if (next !== undefined)
855
+ this.updatePrompt({ value, cursor: next });
856
+ else if (direction < 0)
854
857
  this.historyBack();
855
- }
856
- }
857
- /**
858
- * Down in a multi-line prompt moves the cursor to the next visual line;
859
- * only at the last line does it fall back to command history.
860
- */
861
- moveCursorDownOrHistory() {
862
- if (this.state.overlay)
863
- return;
864
- const { value, cursor } = this.state.prompt;
865
- const lines = value.split('\n');
866
- const { line, col } = lineColOfCursor(value, cursor);
867
- if (line < lines.length - 1) {
868
- this.updatePrompt({ value, cursor: cursorOfLineCol(value, line + 1, col) });
869
- }
870
- else {
858
+ else
871
859
  this.historyForward();
872
- }
873
- }
874
- /** Home: move to the start of the current visual line (not whole buffer). */
875
- moveCursorLineHome() {
876
- const { value, cursor } = this.state.prompt;
877
- const { line } = lineColOfCursor(value, cursor);
878
- this.updatePrompt({ value, cursor: cursorOfLineCol(value, line, 0) });
879
- }
880
- /** End: move to the end of the current visual line (not whole buffer). */
881
- moveCursorLineEnd() {
882
- const { value, cursor } = this.state.prompt;
883
- const { line } = lineColOfCursor(value, cursor);
884
- const lines = value.split('\n');
885
- this.updatePrompt({
886
- value,
887
- cursor: cursorOfLineCol(value, line, lines[line].length),
888
- });
889
860
  }
890
861
  submitPrompt(options = {}) {
891
862
  const { value: input, cursor } = this.state.prompt;
@@ -918,15 +889,7 @@ class TuiRunner {
918
889
  handleLocalCommand(input) {
919
890
  const command = input.trim();
920
891
  if (command === '/queue') {
921
- const items = this.state.followupQueue.items;
922
- this.dispatch({
923
- type: 'setStatus',
924
- message: items.length
925
- ? `Queue ${items.length}/${this.state.followupQueue.limit}: ${items
926
- .map((item, index) => `${index + 1}. ${item.text.replace(/\s+/gu, ' ').slice(0, 28)}`)
927
- .join(' · ')}`
928
- : 'Follow-up queue is empty.',
929
- });
892
+ this.dispatch({ type: 'showFollowupQueue' });
930
893
  return true;
931
894
  }
932
895
  if (command === '/queue resume') {
@@ -957,14 +920,8 @@ class TuiRunner {
957
920
  }
958
921
  return false;
959
922
  }
960
- forceOwnedRedraw() {
961
- if (this.surface && !this.surfaceFailed) {
962
- void this.surface
963
- .forceRedraw(this.buildLiveFrame(this.width))
964
- .catch(error => this.handleSurfaceError(error));
965
- return;
966
- }
967
- this.lastFrame = null;
923
+ redraw() {
924
+ this.surface?.invalidate();
968
925
  this.scheduler.request('immediate');
969
926
  }
970
927
  updatePrompt(next) {
@@ -1041,375 +998,184 @@ class TuiRunner {
1041
998
  this.dispatch({ type: 'closeOverlay' });
1042
999
  void this.options.onPermissionDecision?.(overlay.request.id, approved, 'once');
1043
1000
  }
1044
- /** Restore any temporary Inspector terminal ownership before shutdown. */
1045
- async closeModalSurface() {
1046
- if (this.state.inspector || this.inspectorSurface?.isMounted) {
1047
- this.closeToolInspector();
1048
- }
1049
- await this.modalTransition;
1050
- }
1051
- /** Wait until the current Inspector ownership transition is complete. */
1001
+ /** Wait for an editor or clipboard action and the resulting paint. */
1052
1002
  async waitForModalSurface() {
1053
- await this.modalTransition;
1003
+ await Promise.all([this.modalTransition, this.clipboardQueue]);
1004
+ this.scheduler.flush();
1005
+ await this.surface?.whenIdle();
1054
1006
  }
1055
- /** Flush every finalized transcript batch, including batches queued by acknowledgements. */
1056
- async flushTranscriptCommits() {
1057
- if (!this.surface || this.surfaceFailed)
1058
- return;
1059
- this.flushAllTranscript = true;
1060
- try {
1061
- for (let attempt = 0; attempt < 1024; attempt += 1) {
1062
- await this.surface.whenIdle();
1063
- await Promise.resolve();
1064
- if (!this.commitInFlight && (0, state_1.pendingCommitRecords)(this.state).length === 0)
1065
- return;
1066
- if (!this.commitInFlight)
1067
- this.tryCommit(this.state, true);
1068
- }
1069
- throw new Error('TUI transcript commits did not settle');
1070
- }
1071
- finally {
1072
- this.flushAllTranscript = false;
1073
- }
1007
+ openTranscriptPager() {
1008
+ this.transcriptPager.reset();
1009
+ this.showingTranscript = true;
1010
+ this.scheduler.request('immediate');
1074
1011
  }
1075
- openToolInspector() {
1076
- if (this.state.inspector || !this.inspectorController || !this.inspectorSurface)
1012
+ closeTranscriptPager() {
1013
+ this.showingTranscript = false;
1014
+ clearImmediate(this.pendingHistoryPage);
1015
+ this.pendingHistoryPage = undefined;
1016
+ }
1017
+ loadEarlierTranscript() {
1018
+ if (this.pendingHistoryPage || !this.transcriptPager.nearStart)
1077
1019
  return;
1078
- this.inputOwnership.capture('inspector', {
1079
- value: this.state.prompt.value,
1080
- cursor: this.state.prompt.cursor,
1081
- parserState: this.parser.getState(),
1082
- });
1083
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'openToolInspector' });
1084
- this.inspectorReady = false;
1085
- this.inspectorSearchActive = false;
1086
- this.modalTransition = this.modalTransition
1087
- .then(async () => {
1088
- await this.surface?.suspend();
1089
- this.inspectorReady = true;
1090
- await this.inspectorSurface.mount(this.buildInspectorFrame());
1091
- })
1092
- .catch(error => this.handleSurfaceError(error));
1020
+ const page = this.readEarlierPage(this.earlierCursor);
1021
+ if (!page)
1022
+ return;
1023
+ this.transcriptPager.keepEarlierAnchor();
1024
+ this.earlierRecords = [...page.records, ...this.earlierRecords];
1025
+ this.earlierCursor = page.before;
1093
1026
  }
1094
- closeToolInspector() {
1095
- if (!this.state.inspector && !this.inspectorSurface?.isMounted)
1027
+ readEarlierPage(cursor) {
1028
+ if (!this.historySource || cursor <= 0)
1096
1029
  return;
1097
- this.inspectorController?.cancel();
1098
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'closeToolInspector' });
1099
- const snapshot = this.inputOwnership.restore();
1100
- if (snapshot) {
1101
- this.parser.setState(snapshot.parserState);
1102
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1103
- type: 'setPrompt',
1104
- value: snapshot.value,
1105
- cursor: snapshot.cursor,
1106
- });
1107
- }
1108
- this.inspectorReady = false;
1109
- this.inspectorSearchActive = false;
1110
- this.modalTransition = this.modalTransition
1111
- .then(async () => {
1112
- await this.inspectorSurface?.unmount();
1113
- if (this.surface) {
1114
- await this.surface.restore(() => this.buildLiveFrame(this.width), this.width, this.height);
1115
- }
1116
- this.tryCommit(this.state, true);
1117
- this.scheduler.request('immediate');
1118
- })
1119
- .catch(error => this.handleSurfaceError(error));
1030
+ const page = this.historySource.readBefore(cursor);
1031
+ if (page.before >= cursor)
1032
+ return;
1033
+ const records = page.entries.map(entry => ({ ...entry, finalized: true, revision: 1 }));
1034
+ return { records, before: page.before };
1120
1035
  }
1121
- applyInspectorInput(event) {
1122
- if (event.type === 'paste')
1036
+ loadTranscriptBeginning() {
1037
+ this.transcriptPager.first();
1038
+ if (!this.earlierCursor || this.pendingHistoryPage)
1123
1039
  return;
1124
- if (event.type === 'text') {
1125
- if (!this.inspectorSearchActive) {
1126
- if (event.value === 'j') {
1127
- this.moveInspectorSelection(1);
1128
- return;
1129
- }
1130
- if (event.value === 'k') {
1131
- this.moveInspectorSelection(-1);
1132
- return;
1133
- }
1134
- if (event.value === ' ') {
1135
- void this.loadSelectedInspectorDetail(false);
1136
- return;
1137
- }
1138
- if (event.value === 'g') {
1139
- this.moveInspectorSelectionTo('first');
1140
- return;
1141
- }
1142
- if (event.value === 'G') {
1143
- this.moveInspectorSelectionTo('last');
1144
- return;
1145
- }
1146
- if (event.value === 'n' && this.state.inspector?.searchQuery) {
1147
- this.moveInspectorSelection(1, true);
1148
- return;
1149
- }
1150
- if (event.value === 'N' && this.state.inspector?.searchQuery) {
1151
- this.moveInspectorSelection(-1, true);
1152
- return;
1153
- }
1154
- if (event.value === 'v') {
1155
- this.openSelectedInspectorDetailInEditor();
1040
+ let before = this.earlierCursor;
1041
+ const pages = [];
1042
+ const advance = () => {
1043
+ this.pendingHistoryPage = undefined;
1044
+ const page = this.readEarlierPage(before);
1045
+ if (page) {
1046
+ pages.push(page.records);
1047
+ before = page.before;
1048
+ if (before > 0) {
1049
+ // Let input, resize and rendering run between history batches.
1050
+ this.pendingHistoryPage = setImmediate(advance);
1156
1051
  return;
1157
1052
  }
1158
1053
  }
1159
- if (!this.inspectorSearchActive && (event.value === 'q' || event.value === 'Q')) {
1160
- this.closeToolInspector();
1161
- return;
1162
- }
1163
- if (!this.inspectorSearchActive && event.value === '/') {
1164
- this.inspectorSearchActive = true;
1165
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'setToolInspectorSearch', query: '' });
1166
- this.paintInspector();
1167
- return;
1168
- }
1169
- if (!this.inspectorSearchActive && event.value === '[') {
1170
- this.exportInspectorResults();
1171
- return;
1172
- }
1173
- if (this.inspectorSearchActive) {
1174
- const query = `${this.state.inspector?.searchQuery ?? ''}${event.value}`;
1175
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'setToolInspectorSearch', query });
1176
- this.paintInspector();
1177
- }
1178
- return;
1054
+ this.earlierRecords = pages.reverse().flat().concat(this.earlierRecords);
1055
+ this.earlierCursor = before;
1056
+ this.transcriptPager.first();
1057
+ this.scheduler.request('immediate');
1058
+ };
1059
+ this.pendingHistoryPage = setImmediate(advance);
1060
+ }
1061
+ applyTranscriptInput(event) {
1062
+ if (event.type === 'wheel') {
1063
+ if (event.direction === -1)
1064
+ this.loadEarlierTranscript();
1065
+ this.transcriptPager.scroll(3 * event.direction);
1179
1066
  }
1180
- switch (event.key) {
1181
- case 'ctrl+o':
1182
- case 'escape':
1183
- this.closeToolInspector();
1184
- return;
1185
- case 'ctrl+c':
1186
- this.closeToolInspector();
1187
- return;
1188
- case 'up':
1189
- this.moveInspectorSelection(-1);
1190
- return;
1191
- case 'down':
1192
- this.moveInspectorSelection(1);
1193
- return;
1194
- case 'pageup':
1195
- case 'ctrl+u':
1196
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'scrollToolInspector', delta: -10 });
1197
- this.paintInspector();
1198
- return;
1199
- case 'pagedown':
1200
- case 'ctrl+d':
1201
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'scrollToolInspector', delta: 10 });
1202
- void this.loadSelectedInspectorDetail(true);
1203
- return;
1204
- case 'home':
1205
- this.moveInspectorSelectionTo('first');
1206
- return;
1207
- case 'end':
1208
- this.moveInspectorSelectionTo('last');
1209
- return;
1210
- case 'backspace': {
1211
- if (!this.inspectorSearchActive)
1067
+ else if (event.type === 'text') {
1068
+ switch (event.value) {
1069
+ case 'q':
1070
+ this.closeTranscriptPager();
1071
+ break;
1072
+ case 'j':
1073
+ case 'k':
1074
+ if (event.value === 'k')
1075
+ this.loadEarlierTranscript();
1076
+ this.transcriptPager.scroll(event.value === 'j' ? 1 : -1);
1077
+ break;
1078
+ case ' ':
1079
+ this.transcriptPager.page(1, 0);
1080
+ break;
1081
+ default:
1212
1082
  return;
1213
- const query = this.state.inspector?.searchQuery ?? '';
1214
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1215
- type: 'setToolInspectorSearch',
1216
- query: query.slice(0, -1),
1217
- });
1218
- this.paintInspector();
1219
- return;
1220
1083
  }
1221
- case 'enter':
1222
- if (this.inspectorSearchActive) {
1223
- this.inspectorSearchActive = false;
1224
- this.paintInspector();
1225
- return;
1226
- }
1227
- void this.loadSelectedInspectorDetail(false);
1228
- return;
1229
- case 'ctrl+e':
1230
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'toggleAllToolInspectorEntries' });
1231
- this.paintInspector();
1232
- return;
1233
- case 'ctrl+l':
1234
- this.paintInspector();
1235
- return;
1236
- }
1237
- }
1238
- async loadSelectedInspectorDetail(append) {
1239
- const inspector = this.state.inspector;
1240
- if (!inspector || !this.inspectorController)
1241
- return;
1242
- const view = this.inspectorController.view(this.state.recentToolDetails, inspector);
1243
- const selected = view.selected;
1244
- if (!selected)
1245
- return;
1246
- const expanded = inspector.expandedCallIds.includes(selected.callId);
1247
- if (!append && expanded) {
1248
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1249
- type: 'toggleToolInspectorEntry',
1250
- callId: selected.callId,
1251
- });
1252
- this.paintInspector();
1253
- return;
1254
- }
1255
- if (!expanded) {
1256
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1257
- type: 'toggleToolInspectorEntry',
1258
- callId: selected.callId,
1259
- });
1260
1084
  }
1261
- this.paintInspector();
1262
- await this.inspectorController.load(selected, append && view.detail?.nextOffsetBytes !== undefined);
1263
- if (this.state.inspector)
1264
- this.paintInspector();
1265
- }
1266
- moveInspectorSelection(delta, wrap = false) {
1267
- const inspector = this.state.inspector;
1268
- if (!inspector || !this.inspectorController)
1269
- return;
1270
- const view = this.inspectorController.view(this.state.recentToolDetails, inspector);
1271
- if (view.entries.length === 0)
1272
- return;
1273
- const target = wrap
1274
- ? (view.selectedIndex + delta + view.entries.length) % view.entries.length
1275
- : Math.max(0, Math.min(view.entries.length - 1, view.selectedIndex + delta));
1276
- this.inspectorController.cancel();
1277
- this.state = (0, state_1.tuiUiReducer)(this.state, { type: 'setToolInspectorSelection', index: target });
1278
- this.paintInspector();
1279
- }
1280
- moveInspectorSelectionTo(edge) {
1281
- const inspector = this.state.inspector;
1282
- if (!inspector || !this.inspectorController)
1283
- return;
1284
- const view = this.inspectorController.view(this.state.recentToolDetails, inspector);
1285
- if (view.entries.length === 0)
1286
- return;
1287
- this.inspectorController.cancel();
1288
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1289
- type: 'setToolInspectorSelection',
1290
- index: edge === 'first' ? 0 : view.entries.length - 1,
1291
- });
1292
- this.paintInspector();
1293
- }
1294
- exportInspectorResults() {
1295
- const inspector = this.state.inspector;
1296
- if (!inspector || !this.inspectorController)
1297
- return;
1298
- const entries = this.inspectorController.view(this.state.recentToolDetails, inspector).entries;
1299
- this.closeToolInspector();
1300
- this.modalTransition = this.modalTransition
1301
- .then(async () => {
1302
- if (!this.surface) {
1303
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1304
- type: 'setStatus',
1305
- message: 'Inspector export requires an inline terminal surface.',
1306
- });
1307
- return;
1085
+ else if (event.type === 'key') {
1086
+ if (this.configuredActionForKey(event.key) === 'transcript') {
1087
+ this.closeTranscriptPager();
1308
1088
  }
1309
- for (const entry of entries) {
1310
- let pageIndex = 0;
1311
- for await (const page of this.inspectorController.readPages(entry)) {
1312
- const heading = pageIndex === 0 ? `#${entry.sequence} ${entry.toolName}\n` : '';
1313
- const rows = (0, transcript_layout_1.layoutTranscriptEntry)({
1314
- role: 'tool',
1315
- content: `${heading}${page.content}`,
1316
- }, {
1317
- width: this.transcriptWidth,
1318
- theme: this.theme,
1319
- toolOutputMode: 'full',
1320
- });
1321
- await this.surface.commit({
1322
- batchId: `tui-inspector-export-${++this.commitSequence}`,
1323
- generation: this.state.transcriptGeneration,
1324
- reason: 'append',
1325
- entries: [
1326
- {
1327
- displayKey: `inspector-export-${entry.callId}-${pageIndex}`,
1328
- rows,
1329
- },
1330
- ],
1331
- }, () => this.buildLiveFrame(this.width));
1332
- pageIndex += 1;
1089
+ else {
1090
+ switch (event.key) {
1091
+ case 'ctrl+c':
1092
+ this.closeTranscriptPager();
1093
+ break;
1094
+ case 'home':
1095
+ this.loadTranscriptBeginning();
1096
+ break;
1097
+ case 'end':
1098
+ this.transcriptPager.last();
1099
+ break;
1100
+ case 'pageup':
1101
+ case 'pagedown':
1102
+ case 'ctrl+b':
1103
+ case 'ctrl+f':
1104
+ if (event.key === 'pageup' || event.key === 'ctrl+b')
1105
+ this.loadEarlierTranscript();
1106
+ this.transcriptPager.page(event.key === 'pageup' || event.key === 'ctrl+b' ? -1 : 1, 0);
1107
+ break;
1108
+ case 'ctrl+u':
1109
+ case 'ctrl+d':
1110
+ if (event.key === 'ctrl+u')
1111
+ this.loadEarlierTranscript();
1112
+ this.transcriptPager.halfPage(event.key === 'ctrl+u' ? -1 : 1);
1113
+ break;
1114
+ case 'up':
1115
+ case 'down':
1116
+ if (event.key === 'up')
1117
+ this.loadEarlierTranscript();
1118
+ this.transcriptPager.scroll(event.key === 'up' ? -1 : 1);
1119
+ break;
1120
+ default:
1121
+ return;
1333
1122
  }
1334
1123
  }
1335
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1336
- type: 'setStatus',
1337
- message: `Exported ${entries.length} tool result${entries.length === 1 ? '' : 's'} to scrollback.`,
1338
- });
1339
- this.scheduler.request('immediate');
1340
- })
1341
- .catch(error => this.handleSurfaceError(error));
1342
- }
1343
- openSelectedInspectorDetailInEditor() {
1344
- const inspector = this.state.inspector;
1345
- if (!inspector || !this.inspectorController)
1346
- return;
1347
- const selected = this.inspectorController.view(this.state.recentToolDetails, inspector).selected;
1348
- if (!selected)
1124
+ }
1125
+ else {
1349
1126
  return;
1350
- if (!this.options.onOpenExternalEditor) {
1351
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1352
- type: 'setStatus',
1353
- message: 'External editor is unavailable in this TUI environment.',
1354
- });
1355
- this.paintInspector();
1127
+ }
1128
+ this.scheduler.request('immediate');
1129
+ }
1130
+ copyLastResponse() {
1131
+ const markdown = latestCompletedReply(this.state.transcript, this.restoredCompletionOrder) ??
1132
+ this.historySource?.latestCompletedReply;
1133
+ if (markdown === undefined) {
1134
+ this.events.append({ role: 'error', content: 'No agent response to copy' });
1356
1135
  return;
1357
1136
  }
1358
- this.closeToolInspector();
1359
- this.modalTransition = this.modalTransition
1360
- .then(async () => {
1361
- const directory = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'orion-code-tool-'));
1362
- const filePath = (0, path_1.join)(directory, `${selected.sequence}-${safeFileName(selected.toolName)}.txt`);
1137
+ const generation = this.state.transcriptGeneration;
1138
+ this.clipboardQueue = this.clipboardQueue.then(async () => {
1139
+ if (this.stopped || generation !== this.state.transcriptGeneration)
1140
+ return;
1141
+ let failure;
1363
1142
  try {
1364
- await this.inspectorController.writeDetailToFile(selected, filePath);
1365
- await this.options.onOpenExternalEditor(filePath);
1366
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1367
- type: 'setStatus',
1368
- message: `Viewed #${selected.sequence} ${selected.toolName} in external editor.`,
1369
- });
1143
+ if (!this.options.copyToClipboard)
1144
+ throw new Error('clipboard is unavailable');
1145
+ await this.options.copyToClipboard(markdown);
1370
1146
  }
1371
- finally {
1372
- await (0, promises_1.rm)(directory, { recursive: true, force: true });
1147
+ catch (error) {
1148
+ failure = error instanceof Error ? error.message : String(error);
1373
1149
  }
1374
- this.forceOwnedRedraw();
1375
- })
1376
- .catch(error => {
1377
- this.state = (0, state_1.tuiUiReducer)(this.state, {
1378
- type: 'setStatus',
1379
- message: `External editor failed: ${error instanceof Error ? error.message : String(error)}`,
1380
- });
1381
- this.forceOwnedRedraw();
1382
- });
1383
- }
1384
- paintInspector() {
1385
- if (!this.state.inspector ||
1386
- !this.inspectorController ||
1387
- !this.inspectorSurface ||
1388
- !this.inspectorReady)
1389
- return;
1390
- const frame = this.buildInspectorFrame();
1391
- this.lastFrame = frame;
1392
- void this.inspectorSurface.paint(frame).catch(error => this.handleSurfaceError(error));
1393
- }
1394
- buildInspectorFrame() {
1395
- const inspector = this.state.inspector;
1396
- const view = inspector && this.inspectorController
1397
- ? this.inspectorController.view(this.state.recentToolDetails, inspector)
1398
- : {
1399
- entries: [],
1400
- selectedIndex: 0,
1401
- expandedCallIds: [],
1402
- searchQuery: '',
1403
- detailOffset: 0,
1404
- };
1405
- return (0, transcript_inspector_layout_1.renderTranscriptInspectorFrame)(view, {
1406
- width: this.width,
1407
- height: this.height,
1408
- theme: this.theme,
1150
+ if (this.stopped || generation !== this.state.transcriptGeneration)
1151
+ return;
1152
+ this.events.append(failure === undefined
1153
+ ? { role: 'status', content: 'Copied last message to clipboard' }
1154
+ : { role: 'error', content: `Copy failed: ${failure}` });
1409
1155
  });
1410
1156
  }
1411
1157
  }
1412
1158
  exports.TuiRunner = TuiRunner;
1159
+ function latestCompletedReply(records, afterOrder) {
1160
+ let latest;
1161
+ for (let index = records.length - 1; index >= 0; index -= 1) {
1162
+ const record = records[index];
1163
+ if (!record.finalized ||
1164
+ (record.completedOrder ?? 0) <= afterOrder ||
1165
+ record.role !== 'assistant' ||
1166
+ record.title === 'reasoning' ||
1167
+ record.title?.toLowerCase() === 'tool' ||
1168
+ record.errorLayer ||
1169
+ record.budgetStop ||
1170
+ record.toolActivity ||
1171
+ record.command ||
1172
+ (latest && (record.completedOrder ?? 0) <= (latest.completedOrder ?? 0)) ||
1173
+ !record.content.trim())
1174
+ continue;
1175
+ latest = record;
1176
+ }
1177
+ return latest?.content;
1178
+ }
1413
1179
  function insertAtCursor(value, cursor, text) {
1414
1180
  const safeCursor = clampCursor(value, cursor);
1415
1181
  return {
@@ -1417,9 +1183,6 @@ function insertAtCursor(value, cursor, text) {
1417
1183
  cursor: safeCursor + text.length,
1418
1184
  };
1419
1185
  }
1420
- function safeFileName(value) {
1421
- return value.replace(/[^a-zA-Z0-9._-]+/gu, '-').replace(/^-+|-+$/gu, '') || 'tool';
1422
- }
1423
1186
  function deleteBeforeCursor(value, cursor) {
1424
1187
  const safeCursor = clampCursor(value, cursor);
1425
1188
  if (safeCursor === 0)
@@ -1448,6 +1211,50 @@ function deleteWordBeforeCursor(value, cursor) {
1448
1211
  cursor: before.length,
1449
1212
  };
1450
1213
  }
1214
+ function editPromptText(prompt, key) {
1215
+ const { value, cursor } = prompt;
1216
+ switch (key) {
1217
+ case 'newline':
1218
+ return insertAtCursor(value, cursor, '\n');
1219
+ case 'backspace':
1220
+ return deleteBeforeCursor(value, cursor);
1221
+ case 'delete':
1222
+ return deleteAfterCursor(value, cursor);
1223
+ case 'left':
1224
+ return { value, cursor: previousBoundary(value, cursor) };
1225
+ case 'right':
1226
+ return { value, cursor: nextBoundary(value, cursor) };
1227
+ case 'ctrl+u':
1228
+ return { value: '', cursor: 0 };
1229
+ case 'ctrl+w':
1230
+ return deleteWordBeforeCursor(value, cursor);
1231
+ case 'home':
1232
+ case 'end': {
1233
+ const { line } = lineColOfCursor(value, cursor);
1234
+ const column = key === 'home' ? 0 : value.split('\n')[line].length;
1235
+ return { value, cursor: cursorOfLineCol(value, line, column) };
1236
+ }
1237
+ }
1238
+ }
1239
+ function pickerMovement(event, pageSize) {
1240
+ if (event.type === 'wheel')
1241
+ return event.direction * 3;
1242
+ if (event.type !== 'key')
1243
+ return 0;
1244
+ switch (event.key) {
1245
+ case 'up':
1246
+ return -1;
1247
+ case 'down':
1248
+ case 'tab':
1249
+ return 1;
1250
+ case 'pageup':
1251
+ return -pageSize;
1252
+ case 'pagedown':
1253
+ return pageSize;
1254
+ default:
1255
+ return 0;
1256
+ }
1257
+ }
1451
1258
  function previousBoundary(value, cursor) {
1452
1259
  const safeCursor = clampCursor(value, cursor);
1453
1260
  let previous = 0;