@causyne/agent 1.20.55 → 1.20.62

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 (56) hide show
  1. package/package.json +1 -1
  2. package/src/acp/agentCatalog.js +1 -1
  3. package/src/acp/agentCatalog.ts +1 -1
  4. package/src/acp/peerProfiles.js +3 -3
  5. package/src/acp/peerProfiles.ts +3 -3
  6. package/src/agentLoop.js +91 -19
  7. package/src/agentLoop.ts +102 -22
  8. package/src/checkpoints.js +23 -5
  9. package/src/cliMode.js +4 -2
  10. package/src/commands.js +503 -78
  11. package/src/contextManager.d.ts +3 -0
  12. package/src/contextManager.js +78 -5
  13. package/src/cortex/autoCondenser.js +105 -145
  14. package/src/cortex/autoCondenser.ts +185 -0
  15. package/src/cortex/cortexEngine.js +179 -0
  16. package/src/cortex/cortexEngine.ts +209 -0
  17. package/src/cortex/provisioner.js +12 -14
  18. package/src/cortex/provisioner.ts +29 -0
  19. package/src/cortex/vectorDb.js +307 -386
  20. package/src/cortex/vectorDb.ts +473 -0
  21. package/src/decisionPolicy.js +3 -3
  22. package/src/decisionPolicy.ts +3 -3
  23. package/src/observer/coldObserver.js +10 -4
  24. package/src/observer/coldObserver.ts +10 -4
  25. package/src/observer/evidence.js +8 -3
  26. package/src/observer/evidence.ts +8 -3
  27. package/src/reporting.js +30 -7
  28. package/src/sessionJournal.js +13 -0
  29. package/src/sessionJournal.ts +13 -0
  30. package/src/tokenTracker.js +22 -0
  31. package/src/tokenTracker.ts +28 -0
  32. package/src/tools/memoryWrite.js +11 -3
  33. package/src/tools/memoryWrite.ts +12 -3
  34. package/src/tools/toolSelfRepair.js +11 -0
  35. package/src/tools/toolSelfRepair.ts +10 -0
  36. package/src/tui/chatRenderer.js +8 -4
  37. package/src/tui/completion.js +34 -15
  38. package/src/tui/composerControls.js +5 -0
  39. package/src/tui/composerControls.ts +5 -0
  40. package/src/tui/layout.js +1 -1
  41. package/src/tui/layout.ts +1 -1
  42. package/src/tui/messageInteraction.js +1 -1
  43. package/src/tui/messageInteraction.ts +1 -1
  44. package/src/tui/observerPicker.js +323 -0
  45. package/src/tui/observerPicker.ts +386 -0
  46. package/src/tui/prompt.js +185 -23
  47. package/src/tui/stage.js +2 -2
  48. package/src/tui/stageSurface.js +22 -27
  49. package/src/tui/thinkingBox.js +2 -2
  50. package/src/tui/thinkingBox.ts +2 -2
  51. package/src/tui/usageCard.js +178 -0
  52. package/src/tui/usageCard.ts +240 -0
  53. package/src/utils/paths.js +30 -1
  54. package/src/utils/paths.ts +32 -1
  55. package/src/cortex/autoCondenser.d.ts +0 -2
  56. package/src/cortex/vectorDb.d.ts +0 -1
package/src/tui/prompt.js CHANGED
@@ -23,9 +23,10 @@ import { PromptHistory } from './history.js';
23
23
  import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
24
24
  import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
25
25
  import { barBlock, GUTTER } from './block.js';
26
- import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay } from './text.js';
26
+ import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay, stripAnsi } from './text.js';
27
27
  import { pickExample, fitHints } from './banner.js';
28
28
  import { panelRows } from './overlay.js';
29
+ import { renderUsageCardRows, collectUsageCardData } from './usageCard.js';
29
30
  import { commandPalette, skillPicker, ApprovalLayer, DecisionLayer, ConfirmLayer, HomeLayer, TextLayer } from './dialogs.js';
30
31
  import { describeTool } from './toolDisplay.js';
31
32
  import { readClipboardSync, writeClipboardSync } from './clipboardSync.js';
@@ -121,6 +122,7 @@ export class ChatPrompt {
121
122
  this.busy = false;
122
123
  this.active = false;
123
124
  this.drawnRows = 0;
125
+ this.usageCard = null;
124
126
 
125
127
  // Which row of the drawn block the caret is parked on.
126
128
  //
@@ -250,7 +252,47 @@ export class ChatPrompt {
250
252
 
251
253
  handleData = (chunk) => {
252
254
  let motionOnly = true;
253
- for (const key of this.decoder.decode(chunk)) {
255
+ const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
256
+ // Unbracketed multi-line or bulk paste safeguard: when a multi-line or bulk block arrives
257
+ // without bracketed paste (e.g. VS Code terminal, native clipboard paste, terminal ANSI logs,
258
+ // or piped stream), handle it atomically as a paste event rather than executing multiple
259
+ // spurious Enter submissions or freezing in per-character completion loops.
260
+ const isBracketedPasteStart = str.startsWith('\x1b[200~');
261
+ const isMouse = str.startsWith('\x1b[<') || str.startsWith('\x1b[M');
262
+ const hasNewlines = str.includes('\n') || str.includes('\r');
263
+ if (!this.layer && !this.decoder.inPaste && !isBracketedPasteStart && !isMouse && (
264
+ (str.length > 2 && hasNewlines) ||
265
+ (str.length >= 64 && !str.startsWith('\x1b'))
266
+ )) {
267
+ const clean = stripAnsi(str).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
268
+ try {
269
+ this.handleKey({ name: 'paste', text: clean, sequence: clean });
270
+ } catch (e) {
271
+ process.stderr.write(`\n[tui] paste failed: ${e.message}\n`);
272
+ }
273
+ this.draw();
274
+ return;
275
+ }
276
+
277
+ const keys = this.decoder.decode(chunk);
278
+ let charBatch = '';
279
+
280
+ for (let i = 0; i < keys.length; i++) {
281
+ const key = keys[i];
282
+ if (!this.layer && key.name === 'char' && typeof key.text === 'string' && !key.alt && !key.ctrl) {
283
+ charBatch += key.text;
284
+ motionOnly = false;
285
+ continue;
286
+ }
287
+ if (charBatch.length > 0) {
288
+ this.editor.insert(charBatch);
289
+ if (charBatch.length < 60 && !charBatch.includes('\n')) {
290
+ this.refreshCompletion();
291
+ } else {
292
+ this.completion = null;
293
+ }
294
+ charBatch = '';
295
+ }
254
296
  if (key.name !== 'mouse' || !isMouseMotion(key.sequence)) motionOnly = false;
255
297
  try {
256
298
  this.handleKey(key);
@@ -260,6 +302,17 @@ export class ChatPrompt {
260
302
  process.stderr.write(`\n[tui] key "${key.name}" failed: ${e.message}\n`);
261
303
  }
262
304
  }
305
+
306
+ if (charBatch.length > 0) {
307
+ this.editor.insert(charBatch);
308
+ if (charBatch.length < 60 && !charBatch.includes('\n')) {
309
+ this.refreshCompletion();
310
+ } else {
311
+ this.completion = null;
312
+ }
313
+ charBatch = '';
314
+ }
315
+
263
316
  // All-motion chunks repaint only when the hovered message actually changes.
264
317
  if (!motionOnly) this.draw();
265
318
  };
@@ -492,7 +545,13 @@ export class ChatPrompt {
492
545
  showText(title, text, options = {}) {
493
546
  const panelWidth = dialogWidth(this.width(), options.width || 76);
494
547
  const contentWidth = Math.max(12, panelWidth - 4);
495
- const lines = wrapBlock(safeDisplay(String(text == null ? '' : text)), contentWidth);
548
+ let lines = wrapBlock(safeDisplay(String(text == null ? '' : text)), contentWidth);
549
+ if (lines.length > 0 && lines[0].trim().toLowerCase() === String(title || '').trim().toLowerCase()) {
550
+ lines = lines.slice(1);
551
+ if (lines.length > 0 && /^[-─═_]+$/.test(lines[0].trim())) {
552
+ lines = lines.slice(1);
553
+ }
554
+ }
496
555
  return this.openLayer(new TextLayer({
497
556
  title: String(title || 'Details'),
498
557
  lines: options.danger ? lines.map((line) => paint('danger', line)) : lines,
@@ -501,6 +560,31 @@ export class ChatPrompt {
501
560
  }));
502
561
  }
503
562
 
563
+ /** Toggle the docked usage card directly above the chatbox. */
564
+ async toggleUsageCard(loop = null) {
565
+ if (this.usageCard) {
566
+ this.usageCard = null;
567
+ this.scheduleDraw();
568
+ return false;
569
+ }
570
+ this.usageCard = await collectUsageCardData(loop || this.messageActionLoop);
571
+ this.scheduleDraw();
572
+ return true;
573
+ }
574
+
575
+ showUsageCard(loop = null) {
576
+ return this.toggleUsageCard(loop);
577
+ }
578
+
579
+ closeUsageCard() {
580
+ if (this.usageCard) {
581
+ this.usageCard = null;
582
+ this.scheduleDraw();
583
+ return true;
584
+ }
585
+ return false;
586
+ }
587
+
504
588
  /**
505
589
  * Ask for approval of a tool call: risk, arguments and a scrollable diff.
506
590
  *
@@ -627,6 +711,9 @@ export class ChatPrompt {
627
711
  this.history.add(text);
628
712
  this.editor.clear();
629
713
  this.completion = null;
714
+ if (this.usageCard && !this.isCommand(text)) {
715
+ this.usageCard = null;
716
+ }
630
717
 
631
718
  // Control commands take priority over busy turns so the user is never locked out.
632
719
  // Commands like /stop, /new, /model, /session, /sessions, /continuum, /clear can interrupt
@@ -641,6 +728,14 @@ export class ChatPrompt {
641
728
  text === '/clear'
642
729
  );
643
730
 
731
+ // Immediate abort signals interrupt the running turn directly without queuing as a future task.
732
+ if ((text === '/stop' || text === '/interrupt') && this.busy) {
733
+ this.interrupt();
734
+ this.notice = 'Interrupted';
735
+ this.scheduleDraw();
736
+ return;
737
+ }
738
+
644
739
  if (isControlCommand && this.busy) {
645
740
  this.interrupt();
646
741
  }
@@ -660,6 +755,10 @@ export class ChatPrompt {
660
755
  const settle = this.waiter;
661
756
  this.waiter = null;
662
757
  if (settle) settle(text);
758
+ else {
759
+ if (!Array.isArray(this.queue)) this.queue = [];
760
+ this.queue.push(text); // nobody is reading yet: hold it, never drop it
761
+ }
663
762
  return;
664
763
  }
665
764
 
@@ -669,7 +768,7 @@ export class ChatPrompt {
669
768
  else this.commit('user', (width) => {
670
769
  const blockWidth = Math.max(8, width);
671
770
  return barBlock(
672
- wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER)),
771
+ wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER), { hang: 0 }),
673
772
  { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
674
773
  );
675
774
  });
@@ -683,6 +782,14 @@ export class ChatPrompt {
683
782
  // -------------------------------------------------------------------------
684
783
 
685
784
  handleKey(key) {
785
+ // A notice reports the result of the last action. Once the user edits the
786
+ // line again it is stale, and leaving it up made "copied ..." follow every
787
+ // later keystroke for the rest of the session.
788
+ if (this.notice && !this.layer
789
+ && (key.name === 'char' || key.name === 'paste' || key.name === 'backspace' || key.name === 'delete')) {
790
+ this.notice = '';
791
+ }
792
+
686
793
  // The wheel was handed to the terminal at the top of the band; the moment
687
794
  // the user types again they are driving this prompt, so take it back.
688
795
  if (key.name !== 'wheel' && key.name !== 'mouse') {
@@ -737,8 +844,16 @@ export class ChatPrompt {
737
844
  }
738
845
 
739
846
  if (key.name === 'paste') {
847
+ if (this.surface && typeof this.surface.captureMouse === 'function') {
848
+ this.surface.captureMouse();
849
+ }
740
850
  this.editor.insert(key.text);
741
- this.refreshCompletion();
851
+ if (typeof key.text === 'string' && !key.text.includes('\n') && key.text.length < 60) {
852
+ this.refreshCompletion();
853
+ } else {
854
+ this.completion = null;
855
+ }
856
+ this.scheduleDraw();
742
857
  return;
743
858
  }
744
859
 
@@ -983,8 +1098,8 @@ export class ChatPrompt {
983
1098
  // sit at almost the same seam — a footer is immediately followed by the next
984
1099
  // question — so accepting either made the jump land twice two rows apart
985
1100
  // instead of once per exchange.
986
- if (key.name === '[' || (key.alt && key.name === '<')) { viewport.jump(-1, ['user']); return true; }
987
- if (key.name === ']' || (key.alt && key.name === '>')) { viewport.jump(1, ['user']); return true; }
1101
+ if ((key.alt && key.name === '[') || (key.alt && key.name === '<')) { viewport.jump(-1, ['user']); return true; }
1102
+ if ((key.alt && key.name === ']') || (key.alt && key.name === '>')) { viewport.jump(1, ['user']); return true; }
988
1103
 
989
1104
  if (key.alt && key.name === 'u') { this.offerUndo(); return true; }
990
1105
 
@@ -1173,6 +1288,25 @@ export class ChatPrompt {
1173
1288
  handleCompletionKey(key) {
1174
1289
  if (key.name === 'up') { this.moveSelection(-1); return true; }
1175
1290
  if (key.name === 'down') { this.moveSelection(1); return true; }
1291
+ // The wheel, PgUp and PgDn belong to the open picker. Letting them fall
1292
+ // through scrolled the transcript behind a frozen menu.
1293
+ if (key.name === 'wheel') {
1294
+ const direction = key.wheel && key.wheel.direction;
1295
+ if (direction === 'up') this.moveSelectionClamped(-1);
1296
+ else if (direction === 'down') this.moveSelectionClamped(1);
1297
+ this.scheduleDraw();
1298
+ return true;
1299
+ }
1300
+ if (key.name === 'pageup' && !key.shift) {
1301
+ this.moveSelectionClamped(-MAX_VISIBLE);
1302
+ this.scheduleDraw();
1303
+ return true;
1304
+ }
1305
+ if (key.name === 'pagedown' && !key.shift) {
1306
+ this.moveSelectionClamped(MAX_VISIBLE);
1307
+ this.scheduleDraw();
1308
+ return true;
1309
+ }
1176
1310
  if (key.name === 'mouse') {
1177
1311
  if (key.mouse && key.mouse.pressed && key.mouse.button === 0) {
1178
1312
  let item = null;
@@ -1183,7 +1317,11 @@ export class ChatPrompt {
1183
1317
  const pickerBottom = pickerTop + this.pickerLayout.pickerCount - 1;
1184
1318
 
1185
1319
  if (key.mouse.row >= pickerTop && key.mouse.row <= pickerBottom) {
1186
- const index = key.mouse.row - pickerTop;
1320
+ // The picker renders a scrolled window (renderPicker); a click maps
1321
+ // to the item under the cursor, not to the first page of items.
1322
+ const total = this.completion.items ? this.completion.items.length : 0;
1323
+ const windowStart = Math.max(0, Math.min(this.selected - MAX_VISIBLE + 1, total - MAX_VISIBLE));
1324
+ const index = windowStart + (key.mouse.row - pickerTop);
1187
1325
  item = this.completion.items && this.completion.items[index];
1188
1326
  } else {
1189
1327
  // Click outside picker closes it
@@ -1197,16 +1335,17 @@ export class ChatPrompt {
1197
1335
 
1198
1336
  if (item) {
1199
1337
  if (this.completion.kind === 'command') {
1200
- this.editor.clear();
1201
- this.completion = null;
1202
- this.deliver(item.value);
1338
+ // A skill entry goes onto the line so the user can say what to do
1339
+ // with it; clicking it used to invoke it immediately with no task.
1340
+ if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1341
+ this.acceptCompletion();
1342
+ return true;
1343
+ }
1344
+ this.submitPickedCommand(item.value);
1203
1345
  return true;
1204
1346
  }
1205
1347
  if (this.completion.kind === 'command-argument') {
1206
- const cmd = this.completion.command;
1207
- this.editor.clear();
1208
- this.completion = null;
1209
- this.deliver(`/${cmd} ${item.value}`);
1348
+ this.submitPickedCommand(`/${this.completion.command} ${item.value}`);
1210
1349
  return true;
1211
1350
  }
1212
1351
  this.acceptCompletion();
@@ -1218,10 +1357,12 @@ export class ChatPrompt {
1218
1357
  if (key.name === 'enter' && !key.alt) {
1219
1358
  const item = this.completion.items && this.completion.items[this.selected];
1220
1359
  if (this.completion.kind === 'command' && item) {
1221
- // Instant execution on single Enter for any slash command
1222
- this.editor.clear();
1223
- this.completion = null;
1224
- this.deliver(item.value);
1360
+ if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1361
+ this.acceptCompletion();
1362
+ return true;
1363
+ }
1364
+ // Instant execution on single Enter for any pure slash command
1365
+ this.submitPickedCommand(item.value);
1225
1366
  return true;
1226
1367
  }
1227
1368
  if (this.completionIsExact()) {
@@ -1250,6 +1391,26 @@ export class ChatPrompt {
1250
1391
  this.selected = (this.selected + direction + count) % count;
1251
1392
  }
1252
1393
 
1394
+ /** Move without wrapping: a wheel or page key stops at either end. */
1395
+ moveSelectionClamped(delta) {
1396
+ const count = this.completion.items.length;
1397
+ if (count === 0) return;
1398
+ this.selected = Math.max(0, Math.min(count - 1, this.selected + delta));
1399
+ }
1400
+
1401
+ /**
1402
+ * Run a command chosen in the picker through the same path as typing it.
1403
+ *
1404
+ * deliver() bypassed submit(): during a running turn a picked `/stop` was
1405
+ * queued behind the very turn it was meant to stop, and the command never
1406
+ * reached input history.
1407
+ */
1408
+ submitPickedCommand(value) {
1409
+ this.completion = null;
1410
+ this.editor.setText(value);
1411
+ this.submit();
1412
+ }
1413
+
1253
1414
  acceptCompletion() {
1254
1415
  const item = this.completion.items[this.selected];
1255
1416
  if (!item) { this.completion = null; return; }
@@ -1358,7 +1519,7 @@ export class ChatPrompt {
1358
1519
  let body = window.slice();
1359
1520
 
1360
1521
  if (this.editor.isEmpty && !this.completion) {
1361
- const idle = fitHints([`try "${this.example}"`, '/ commands', '@ files'], inner, 'ask anything');
1522
+ const idle = fitHints([`try "${this.example}"`, '/ commands', '@ files'], Math.max(8, inner), 'ask anything');
1362
1523
  body = [dim(this.busy ? 'type to queue a message…' : idle)];
1363
1524
  }
1364
1525
 
@@ -1392,10 +1553,11 @@ export class ChatPrompt {
1392
1553
  punctuate: false
1393
1554
  });
1394
1555
 
1556
+ const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, width) : [];
1395
1557
  const planRows = this.planRows(width);
1396
1558
  const pickerRows = this.completion ? this.pickerRows(width) : [];
1397
1559
  this.pickerLayout = this.completion ? {
1398
- pickerStart: planRows.length + boxRows.length,
1560
+ pickerStart: usageCardRows.length + planRows.length + boxRows.length,
1399
1561
  pickerCount: pickerRows.length,
1400
1562
  totalPromptRows: 0
1401
1563
  } : null;
@@ -1409,7 +1571,7 @@ export class ChatPrompt {
1409
1571
  const gap = status.length > 0 ? new Array(FOOTER_GAP).fill('') : [];
1410
1572
 
1411
1573
  const all = this.clampRows(
1412
- planRows.concat(boxRows, pickerRows, noticeRows, gap, status), width
1574
+ usageCardRows.concat(planRows, boxRows, pickerRows, noticeRows, gap, status), width
1413
1575
  );
1414
1576
  if (this.pickerLayout) this.pickerLayout.totalPromptRows = all.length;
1415
1577
 
@@ -1420,7 +1582,7 @@ export class ChatPrompt {
1420
1582
  const positioned = this.surface
1421
1583
  ? (this.surface.homeInfo ? centerRows(all, this.surface.width) : sessionRows(all, availableWidth))
1422
1584
  : { rows: all, inset: 0 };
1423
- this.present(positioned.rows, planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
1585
+ this.present(positioned.rows, usageCardRows.length + planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
1424
1586
  }
1425
1587
 
1426
1588
  /**
package/src/tui/stage.js CHANGED
@@ -246,7 +246,7 @@ export class Stage {
246
246
  this.moveTo(target.row);
247
247
  this.write('\r');
248
248
  if (target.col > 0) this.write(`\x1b[${target.col}C`);
249
- this.write(SHOW_CURSOR + SYNC_OFF);
249
+ this.write(SHOW_CURSOR + '\x1b[6 q' + SYNC_OFF);
250
250
 
251
251
  this.prev = next;
252
252
  this.caret = target;
@@ -267,7 +267,7 @@ export class Stage {
267
267
  if (!this.reserved) return;
268
268
  this.write(SYNC_ON);
269
269
  this.moveTo(0);
270
- this.write('\r' + ERASE_BELOW + SHOW_CURSOR + SYNC_OFF);
270
+ this.write('\r' + ERASE_BELOW + SHOW_CURSOR + '\x1b[0 q' + SYNC_OFF);
271
271
  this.reserved = false;
272
272
  this.cursor = 0;
273
273
  this.prev = [];
@@ -201,23 +201,14 @@ export class StageSurface {
201
201
 
202
202
  composeAvailableWidth() {
203
203
  if (this.homeInfo) return this.width;
204
- const mainWidth = sessionMainWidth(this.width);
205
- const rail = this.railEnabled(mainWidth);
206
- const hasTurns = hasSessionTurns(this.transcript);
207
- const turnRailBudget = (rail && hasTurns) ? 3 : 0;
208
- return rail ? Math.max(20, mainWidth - RAIL_BUDGET - turnRailBudget) : mainWidth;
204
+ return sessionMainWidth(this.width);
209
205
  }
210
206
 
211
207
  /** Home is compact; a session uses its full conversation column. */
212
208
  composeWidth() {
213
209
  if (this.homeInfo) return composerWidth(this.width);
214
210
  const mainWidth = sessionMainWidth(this.width);
215
- const rail = this.railEnabled(mainWidth);
216
- const hasTurns = hasSessionTurns(this.transcript);
217
- if (!hasTurns) return sessionComposerWidth(mainWidth);
218
- const turnRailBudget = rail ? 3 : 0;
219
- const contentWidth = rail ? Math.max(20, mainWidth - RAIL_BUDGET - turnRailBudget) : mainWidth;
220
- return sessionComposerWidth(contentWidth);
211
+ return sessionComposerWidth(mainWidth);
221
212
  }
222
213
 
223
214
  /** Keep Home distinct from a selected or newly started conversation. */
@@ -409,20 +400,12 @@ export class StageSurface {
409
400
  const sidebar = sidebarVisible(width);
410
401
  const mainWidth = sessionMainWidth(width);
411
402
  const rail = this.railEnabled(mainWidth);
412
- const hasTurns = hasSessionTurns(this.transcript);
413
- const turnRailBudget = (rail && hasTurns) ? 3 : 0;
414
- const contentWidth = rail ? Math.max(20, mainWidth - RAIL_BUDGET - turnRailBudget) : mainWidth;
403
+ const contentWidth = rail ? Math.max(20, mainWidth - RAIL_BUDGET) : mainWidth;
415
404
 
416
405
  let block = promptRows;
417
406
  let caretRow = caret && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
418
407
  let caretCol = caret ? caret.col : 0;
419
408
 
420
- if (turnRailBudget > 0) {
421
- const railGutter = ' '.repeat(turnRailBudget);
422
- block = block.map(row => (row ? railGutter + row : row));
423
- caretCol += turnRailBudget;
424
- }
425
-
426
409
  // Grow the band to what there is to show, before deciding anything else.
427
410
  //
428
411
  // Direct chat keeps its printed header and grows with content. A session
@@ -661,13 +644,13 @@ export class StageSurface {
661
644
  */
662
645
  attachRail(rows, contentWidth) {
663
646
  const turns = collectSessionTurns(this.transcript, contentWidth);
647
+ const hasTurns = turns.length > 0;
664
648
  const isAtBottom = typeof this.viewport?.atBottom === 'function' ? this.viewport.atBottom() : false;
665
649
  const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, this.viewport.state().scrollTop, rows.length, isAtBottom);
666
- const railResult = turns.length > 0
650
+ const railResult = hasTurns
667
651
  ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex)
668
652
  : null;
669
653
 
670
- const hasTurns = turns.length > 0;
671
654
  this.turnRailLayout = {
672
655
  railX: hasTurns ? 1 : contentWidth + 1,
673
656
  stageTop: (this.out.rows || this.stage.height) - this.stage.height,
@@ -680,12 +663,24 @@ export class StageSurface {
680
663
  const rail = this.buildRail(rows.length, contentWidth);
681
664
  for (let i = 0; i < rows.length; i++) {
682
665
  const rightCell = rail[i] || ' ';
683
- if (hasTurns) {
684
- const leftCell = railResult?.cells[i] || ' ';
685
- rows[i] = ` ${leftCell} ${padEnd(rows[i], contentWidth)} ${rightCell}`;
686
- } else {
687
- rows[i] = `${padEnd(rows[i], contentWidth)} ${rightCell}`;
666
+ let row = rows[i] || '';
667
+ if (hasTurns && railResult) {
668
+ const leftCell = railResult.cells[i] || ' ';
669
+ if (leftCell !== ' ') {
670
+ if (row.startsWith(' ')) {
671
+ row = ` ${leftCell} ${row.slice(3)}`;
672
+ } else if (row.startsWith(' ')) {
673
+ row = ` ${leftCell}${row.slice(2)}`;
674
+ } else if (row.startsWith(' ')) {
675
+ row = ` ${leftCell}${row.slice(1)}`;
676
+ } else if (row.length > 0) {
677
+ row = ` ${leftCell} ${row}`;
678
+ } else {
679
+ row = ` ${leftCell} `;
680
+ }
681
+ }
688
682
  }
683
+ rows[i] = `${padEnd(row, contentWidth)} ${rightCell}`;
689
684
  }
690
685
  return rows;
691
686
  }
@@ -83,11 +83,11 @@ export function renderCollapsedThinkingBadge(options, totalLines) {
83
83
  const { activeLabel, completedLabel } = resolveActivityLabels(options);
84
84
  if (isStreaming) {
85
85
  const timePart = durationText ? ` · ${durationText}` : '';
86
- return ` ${paint('warn', arrow)} ${bold(paint('warn', activeLabel))}${dim(timePart)} ${dim('· click to expand')}`;
86
+ return `${paint('warn', arrow)} ${bold(paint('warn', activeLabel))}${dim(timePart)} ${dim('· click to expand')}`;
87
87
  }
88
88
  const timePart = durationText ? ` for ${durationText}` : '';
89
89
  const lineWord = totalLines === 1 ? 'line' : 'lines';
90
- return ` ${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
90
+ return `${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
91
91
  }
92
92
  /**
93
93
  * Builds the top, bottom, and side frame borders for the thinking box.
@@ -92,12 +92,12 @@ export function renderCollapsedThinkingBadge(
92
92
 
93
93
  if (isStreaming) {
94
94
  const timePart = durationText ? ` · ${durationText}` : '';
95
- return ` ${paint('warn', arrow)} ${bold(paint('warn', activeLabel))}${dim(timePart)} ${dim('· click to expand')}`;
95
+ return `${paint('warn', arrow)} ${bold(paint('warn', activeLabel))}${dim(timePart)} ${dim('· click to expand')}`;
96
96
  }
97
97
 
98
98
  const timePart = durationText ? ` for ${durationText}` : '';
99
99
  const lineWord = totalLines === 1 ? 'line' : 'lines';
100
- return ` ${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
100
+ return `${paint('muted', arrow)} ${dim(`${completedLabel}${timePart}`)} ${dim(`(${totalLines} ${lineWord})`)} ${dim('· click to expand')}`;
101
101
  }
102
102
 
103
103
  /**