@causyne/agent 1.20.112 → 1.20.117

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 (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
package/src/tui/stage.ts CHANGED
@@ -71,12 +71,17 @@ const ERASE_BELOW = '\x1b[J';
71
71
  *
72
72
  * CAUSYNE_STAGE: off | auto | <rows> | <pct>%
73
73
  */
74
- export function stageHeight(out: StageOutput = process.stdout, env: StageEnvironment = process.env): number {
75
- const setting = String(env.CAUSYNE_STAGE ?? 'auto').trim().toLowerCase();
74
+ export function stageHeight(
75
+ out: StageOutput = process.stdout,
76
+ env: StageEnvironment | null | undefined = process.env
77
+ ): number {
78
+ const safeEnv: StageEnvironment = env && typeof env === 'object' ? env : {};
79
+ const setting = String(safeEnv.CAUSYNE_STAGE ?? 'auto').trim().toLowerCase();
76
80
  if (setting === 'off' || setting === '0' || setting === 'false') return 0;
77
81
 
78
- const rows = Number(out && out.rows);
79
- if (!Number.isFinite(rows) || rows <= 0) return 0;
82
+ const rawRows = Number(out && out.rows);
83
+ if (!Number.isFinite(rawRows) || rawRows <= 0) return 0;
84
+ const rows = Math.floor(rawRows);
80
85
 
81
86
  // The seam: never take the last row of the user's screen. It costs one row
82
87
  // and it is the difference between "a region" and "the screen".
@@ -98,11 +103,15 @@ export function stageHeight(out: StageOutput = process.stdout, env: StageEnviron
98
103
  * Everything here is a reason the region could not be repainted safely, so the
99
104
  * answer is the scrollback renderer rather than a stage that misbehaves.
100
105
  */
101
- export function stageEnabled(out: StageOutput = process.stdout, env: StageEnvironment = process.env): boolean {
106
+ export function stageEnabled(
107
+ out: StageOutput = process.stdout,
108
+ env: StageEnvironment | null | undefined = process.env
109
+ ): boolean {
110
+ const safeEnv: StageEnvironment = env && typeof env === 'object' ? env : {};
102
111
  if (!out || !out.isTTY) return false;
103
- if (String(env.TERM || '') === 'dumb') return false;
104
- if (env.CAUSYNE_SIMPLE_INPUT === '1') return false;
105
- return stageHeight(out, env) > 0;
112
+ if (String(safeEnv.TERM || '') === 'dumb') return false;
113
+ if (safeEnv.CAUSYNE_SIMPLE_INPUT === '1') return false;
114
+ return stageHeight(out, safeEnv) > 0;
106
115
  }
107
116
 
108
117
  export class Stage {
@@ -115,7 +124,11 @@ export class Stage {
115
124
  prev: Array<string | null>;
116
125
  caret: StageCaret;
117
126
  stats: { paints: number; rowsWritten: number; bytes: number; claimed: number };
118
- constructor({ out = process.stdout, env = process.env, height = 0 }: StageOptions = {}) {
127
+ constructor(options: StageOptions | null = {}) {
128
+ const opts: StageOptions = options && typeof options === 'object' ? options : {};
129
+ const out = opts.out ?? process.stdout;
130
+ const env = opts.env && typeof opts.env === 'object' ? opts.env : process.env;
131
+ const height = opts.height ?? 0;
119
132
  this.out = out;
120
133
  this.env = env;
121
134
 
@@ -124,7 +137,7 @@ export class Stage {
124
137
  // it has something to put in and grows from there. Sizing it to the screen
125
138
  // is free on an alternate screen — which is what opencode is — and on a
126
139
  // reserved band it is 73 rows of void and a banner scrolled out of sight.
127
- this.maxHeight = height > 0 ? Math.floor(height) : stageHeight(out, env);
140
+ this.maxHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : stageHeight(out, env);
128
141
  // Rows actually claimed. Zero until reserve().
129
142
  this.height = 0;
130
143
 
@@ -175,7 +188,8 @@ export class Stage {
175
188
  */
176
189
  reserve(rows: number = this.maxHeight): boolean {
177
190
  if (this.reserved || this.maxHeight < 1) return false;
178
- const claim = Math.max(1, Math.min(Math.floor(rows), this.maxHeight));
191
+ const requested = Number.isFinite(rows) ? Math.floor(rows) : this.maxHeight;
192
+ const claim = Math.max(1, Math.min(requested, this.maxHeight));
179
193
  this.write('\n'.repeat(claim));
180
194
  this.stats.claimed += claim;
181
195
  this.reserved = true;
@@ -200,7 +214,7 @@ export class Stage {
200
214
  * (b) permits to move it.
201
215
  */
202
216
  grow(delta: number): number {
203
- if (!this.reserved || delta <= 0) return 0;
217
+ if (!this.reserved || !Number.isFinite(delta) || delta <= 0) return 0;
204
218
  const room = this.maxHeight - this.height;
205
219
  const claim = Math.min(Math.floor(delta), room);
206
220
  if (claim <= 0) return 0;
@@ -228,6 +242,7 @@ export class Stage {
228
242
  const out = new Array(this.height);
229
243
  for (let i = 0; i < this.height; i++) {
230
244
  let row = rows && rows[i] != null ? String(rows[i]) : '';
245
+ if (row.includes('\r')) row = row.replace(/\r/g, '');
231
246
  if (row.includes('\n')) row = row.split('\n')[0] ?? '';
232
247
  out[i] = visibleWidth(row) <= limit ? row : truncate(row, limit, '');
233
248
  }
@@ -235,7 +250,8 @@ export class Stage {
235
250
  }
236
251
 
237
252
  moveTo(row: number): void {
238
- const target = Math.max(0, Math.min(row, this.height - 1));
253
+ if (!Number.isFinite(row) || this.height <= 0) return;
254
+ const target = Math.max(0, Math.min(Math.floor(row), this.height - 1));
239
255
  const delta = target - this.cursor;
240
256
  // CUU/CUD only. Never a newline: on the band's last row a newline scrolls
241
257
  // the terminal, which would move the whole block out from under the diff.
@@ -259,6 +275,17 @@ export class Stage {
259
275
  return true;
260
276
  }
261
277
 
278
+ private unclosedOsc8Term(row: string): string {
279
+ if (!row.includes('\x1b]8;')) return '';
280
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
281
+ let active = '';
282
+ let match: RegExpExecArray | null;
283
+ while ((match = osc8Re.exec(row)) !== null) {
284
+ active = (match[1] ?? '').length > 0 ? (match[2] ?? '\x1b\\') : '';
285
+ }
286
+ return active;
287
+ }
288
+
262
289
  /**
263
290
  * Repaint the band. Rows that did not change cost nothing.
264
291
  *
@@ -266,11 +293,12 @@ export class Stage {
266
293
  * idle frame is free.
267
294
  */
268
295
  paint(rows: readonly unknown[], caret: StageCaret | null = null): number {
269
- if (!this.reserved) return 0;
296
+ if (!this.reserved || this.height <= 0) return 0;
270
297
 
271
298
  const next = this.normalize(rows);
299
+ const rawCol = caret && Number.isFinite(caret.col) ? Math.floor(caret.col) : 0;
272
300
  const target = caret && Number.isFinite(caret.row)
273
- ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(Math.max(0, this.width() - 2), Math.floor(caret.col) || 0)), hideCursor: Boolean(caret.hideCursor) }
301
+ ? { row: Math.max(0, Math.min(Math.floor(caret.row), this.height - 1)), col: Math.max(0, Math.min(Math.max(0, this.width() - 2), rawCol)), hideCursor: Boolean(caret.hideCursor) }
274
302
  : { row: this.height - 1, col: 0, hideCursor: Boolean(caret?.hideCursor) };
275
303
 
276
304
  const changed = [];
@@ -286,7 +314,11 @@ export class Stage {
286
314
  this.write(SYNC_ON + HIDE_CURSOR + NOWRAP_ON);
287
315
  for (const i of changed) {
288
316
  this.moveTo(i);
289
- this.write('\r' + (next[i] ?? '') + ERASE_LINE);
317
+ const content = next[i] ?? '';
318
+ const osc8Term = this.unclosedOsc8Term(content);
319
+ const osc8Reset = osc8Term ? `\x1b]8;;${osc8Term}` : '';
320
+ const reset = content.includes('\x1b') && !content.endsWith('\x1b[0m') ? '\x1b[0m' : '';
321
+ this.write('\r' + content + osc8Reset + reset + ERASE_LINE);
290
322
  }
291
323
  this.moveTo(target.row);
292
324
  this.write('\r');
@@ -314,7 +346,9 @@ export class Stage {
314
346
  this.moveTo(0);
315
347
  this.write('\r' + ERASE_BELOW + SHOW_CURSOR + '\x1b[0 q' + SYNC_OFF);
316
348
  this.reserved = false;
349
+ this.height = 0;
317
350
  this.cursor = 0;
351
+ this.caret = { row: 0, col: 0 };
318
352
  this.prev = [];
319
353
  }
320
354
 
@@ -348,13 +382,14 @@ export class Stage {
348
382
  * (ChatPrompt already settles resize at 60ms).
349
383
  */
350
384
  resize(height = 0, claim = 0) {
351
- const next = height > 0 ? Math.floor(height) : stageHeight(this.out, this.env);
385
+ const next = Number.isFinite(height) && height > 0 ? Math.floor(height) : stageHeight(this.out, this.env);
352
386
  const wasReserved = this.reserved;
353
387
  if (wasReserved) this.collapse();
354
388
  this.maxHeight = next;
355
389
  this.height = 0;
356
390
  if (next < 1) return false;
357
- if (wasReserved) return this.reserve(claim > 0 ? claim : next);
391
+ const nextClaim = Number.isFinite(claim) && claim > 0 ? Math.floor(claim) : next;
392
+ if (wasReserved) return this.reserve(nextClaim);
358
393
  return false;
359
394
  }
360
395
 
@@ -32,10 +32,10 @@ import { mouseHoverTracking } from './mouseHover.js';
32
32
  import { truncate, padEnd, visibleWidth, stripAnsi } from './text.js';
33
33
  import { composerWidth } from './layout.js';
34
34
  import { placeHome, placeDialog } from './homeView.js';
35
- import { sidebarVisible, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
35
+ import { sidebarVisible, sessionSidebarWidth, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
36
36
  import { sessionStageHeight, alignTranscriptRows } from './sessionLayout.js';
37
- import { hasSessionTurns, collectSessionTurns, buildTurnRailCells, renderTurnPreviewCard, overlayTurnPreviewCard, resolveActiveTurnIndex } from './turnRail.js';
38
- import { registerStageConsoleGuard, setStageConsoleGuardActive } from './consoleGuard.js';
37
+ import { hasSessionTurns, collectSessionTurns, buildTurnRailCells, renderTurnPreviewCard, overlayTurnPreviewCard, resolveActiveTurnIndex, formatPreviewCardMarkdown } from './turnRail.js';
38
+ import { registerStageConsoleGuard, setStageConsoleGuardActive, runWithStageWrite } from './consoleGuard.js';
39
39
 
40
40
  // Rows of evicted transcript held for the exit log. Eviction only happens after
41
41
  // MAX_FRAMES, so this is a bound on a pathological session, not a working limit.
@@ -163,16 +163,17 @@ function railGlyph(kind) {
163
163
  * settled.
164
164
  */
165
165
  export function scrollSettings(env = process.env, config = null) {
166
+ const safeEnv = env && typeof env === 'object' ? env : {};
166
167
  const tui = (config && typeof config === 'object' && config.tui) || {};
167
168
 
168
- let speed = Number(env.CAUSYNE_SCROLL_SPEED);
169
+ let speed = Number(safeEnv.CAUSYNE_SCROLL_SPEED);
169
170
  if (!Number.isFinite(speed) || speed <= 0) speed = Number(tui.scrollSpeed);
170
171
  if (!Number.isFinite(speed) || speed <= 0) speed = DEFAULT_SCROLL_SPEED;
171
172
  // A wheel that moves half the screen per notch is not a preference, it is a
172
173
  // misconfiguration; clamp rather than obey it.
173
174
  speed = Math.min(speed, 20);
174
175
 
175
- const raw = env.CAUSYNE_SCROLL_ACCEL;
176
+ const raw = safeEnv.CAUSYNE_SCROLL_ACCEL;
176
177
  const accelerate = raw !== undefined && raw !== ''
177
178
  ? raw === '1' || raw === 'true'
178
179
  : Boolean(tui.scrollAcceleration);
@@ -180,6 +181,60 @@ export function scrollSettings(env = process.env, config = null) {
180
181
  return { speed, accelerate };
181
182
  }
182
183
 
184
+
185
+ /**
186
+ * A rail dot represents a *time-ordered group* when a long conversation is
187
+ * compressed into fewer terminal rows. The video reference shows a titled
188
+ * history list with timestamps, not a single-turn assistant-summary card.
189
+ * This function never changes transcript geometry or user content.
190
+ */
191
+ export function renderTurnTimelineCard(turns, maxCardWidth = 52, maxHeight = 16, offset = 0) {
192
+ if (!Array.isArray(turns) || turns.length === 0) {
193
+ return { rows: [], entries: [], entryStart: 4, maxOffset: 0 };
194
+ }
195
+ const width = Number.isFinite(maxCardWidth) ? Math.max(24, Math.min(52, Math.floor(maxCardWidth))) : 52;
196
+ const inner = width - 4;
197
+ const viewHeight = Number.isFinite(maxHeight) ? Math.max(6, Math.floor(maxHeight)) : 16;
198
+ const count = Math.max(1, Math.min(10, turns.length, viewHeight - 5));
199
+ const maxOffset = Math.max(0, turns.length - count);
200
+ const start = Number.isFinite(offset) ? Math.max(0, Math.min(maxOffset, Math.floor(offset))) : 0;
201
+ const entries = turns.slice(start, start + count);
202
+ const bg = '\x1b[48;2;28;28;32m';
203
+ const border = bg + '\x1b[38;2;75;75;82m';
204
+ const reset = '\x1b[0m';
205
+ const top = border + '╭' + '─'.repeat(width - 2) + '╮' + reset;
206
+ const bottom = border + '╰' + '─'.repeat(width - 2) + '╯' + reset;
207
+ const blank = border + '│' + bg + ' '.repeat(inner + 2) + border + '│' + reset;
208
+ const line = (value, style = '') => {
209
+ const text = truncate(formatPreviewCardMarkdown(String(value || '')), inner, '…');
210
+ return border + '│' + bg + ' ' + style + padEnd(text, inner) + border + ' │' + reset;
211
+ };
212
+ const shortTime = turn => {
213
+ const ts = Number(turn?.timestamp);
214
+ return Number.isFinite(ts) && ts > 0
215
+ ? new Date(ts).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })
216
+ : '';
217
+ };
218
+ const first = turns[0];
219
+ const last = turns[turns.length - 1];
220
+ const title = first?.userPrompt || 'Conversation history';
221
+ const range = shortTime(first) + (turns.length > 1 ? ' – ' + shortTime(last) : '');
222
+ const header = range.trim() + ' · ' + turns.length + (turns.length === 1 ? ' turn' : ' turns');
223
+ const rows = [
224
+ top,
225
+ line(title, '\x1b[1m\x1b[38;2;235;235;242m'),
226
+ line(header, '\x1b[38;2;145;145;155m'),
227
+ blank
228
+ ];
229
+ for (const turn of entries) {
230
+ const when = shortTime(turn);
231
+ const prompt = turn?.userPrompt || 'Turn ' + String(turn?.turnIndex ?? '');
232
+ rows.push(line((when ? when + ' ' : '') + prompt, '\x1b[38;2;185;185;193m'));
233
+ }
234
+ rows.push(bottom);
235
+ return { rows, entries, entryStart: 4, maxOffset };
236
+ }
237
+
183
238
  export class StageSurface {
184
239
  constructor({ out = process.stdout, env = process.env, config = null, speed, accelerate, openingWidth = 0 } = {}) {
185
240
  this.out = out;
@@ -216,6 +271,7 @@ export class StageSurface {
216
271
  this.mouseWanted = String(env.CAUSYNE_MOUSE ?? '1') !== '0';
217
272
  this.mouseOn = false;
218
273
  this.mouseCaptured = false;
274
+ this.mouseMotionOn = false;
219
275
  this.detached = false;
220
276
 
221
277
  // Retained for callers that pass a measured header width. The composer now
@@ -238,6 +294,7 @@ export class StageSurface {
238
294
  this.unregisterConsoleGuard = null;
239
295
  this.wasModal = false;
240
296
  this.lastBlockLength = 0;
297
+ this.lastUserTurnCount = 0;
241
298
  }
242
299
 
243
300
  get width() {
@@ -274,7 +331,19 @@ export class StageSurface {
274
331
  }
275
332
 
276
333
  setSessionInfo(info) {
277
- this.sessionInfo = { ...this.sessionInfo, ...info };
334
+ const changedSession = info?.id && this.sessionInfo?.id && info.id !== this.sessionInfo.id;
335
+ if (changedSession) {
336
+ // Sidebar plans and turn hover coordinates belong to the previous chat.
337
+ this.sidebarPlan = [];
338
+ this.hoveredTurnIndex = null;
339
+ this.hoveredTurnAnchorY = null;
340
+ this.activeTurnIndex = null;
341
+ this.hoveredMessageFrameId = null;
342
+ this.turnRailLayout = null;
343
+ }
344
+ this.sessionInfo = changedSession
345
+ ? { ...this.sessionInfo, activeSkill: null, contextChars: 0, ...info }
346
+ : { ...this.sessionInfo, ...info };
278
347
  this.stage.invalidate();
279
348
  }
280
349
 
@@ -303,22 +372,47 @@ export class StageSurface {
303
372
  return true;
304
373
  }
305
374
 
375
+ writeModeControl(sequence) {
376
+ if (!sequence) return;
377
+ runWithStageWrite(() => {
378
+ this.out.write(sequence);
379
+ });
380
+ }
381
+
382
+ syncTurnRailMotion(railHasTurns) {
383
+ if (!this.mouseOn || !this.mouseCaptured || !this.stage.reserved) return;
384
+ const preference = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '').trim();
385
+ // Hover needs 1003, not just 1000. Limit default motion tracking to
386
+ // visible turn rails; preserve explicit opt-in and opt-out preferences.
387
+ const wantMotion = preference === '1' || (preference !== '0' && railHasTurns);
388
+ if (this.mouseMotionOn === wantMotion) return;
389
+ this.writeModeControl(mouseHoverTracking(wantMotion, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
390
+ this.mouseMotionOn = wantMotion;
391
+ if (!wantMotion) {
392
+ // 1003 can replace 1000 in terminal tracking-mode state. When it is
393
+ // removed, explicitly restore 1000 or the wheel scrolls the shell.
394
+ this.writeModeControl(mouseTracking(true));
395
+ }
396
+ }
397
+
306
398
  enableMouse() {
307
- if (!this.mouseWanted || this.mouseOn || !this.stage.reserved) return false;
308
- this.out.write(mouseTracking(true));
309
- this.out.write(mouseHoverTracking(true, this.env));
399
+ if (this.homeInfo || !this.mouseWanted || this.mouseOn || !this.stage.reserved) return false;
400
+ this.writeModeControl(mouseTracking(true));
401
+ this.writeModeControl(mouseHoverTracking(true, this.env));
310
402
  this.mouseCaptured = true;
311
403
  this.mouseOn = true;
404
+ this.mouseMotionOn = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '') === '1';
312
405
  return true;
313
406
  }
314
407
 
315
408
  disableMouse(force = false) {
316
409
  if (!force && !this.mouseOn && !this.mouseCaptured) return false;
317
410
  // Restore terminal motion modes, including stale tracking from an interrupted turn.
318
- this.out.write(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
319
- this.out.write(mouseTracking(false));
411
+ this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
412
+ this.writeModeControl(mouseTracking(false));
320
413
  this.mouseCaptured = false;
321
414
  this.mouseOn = false;
415
+ this.mouseMotionOn = false;
322
416
  this.detached = false;
323
417
  return true;
324
418
  }
@@ -413,6 +507,16 @@ export class StageSurface {
413
507
 
414
508
  handleChange() {
415
509
  if (!this.transcript.isEmpty()) this.opened = true;
510
+ let userTurns = 0;
511
+ for (const frame of this.transcript.frames) {
512
+ if (frame && frame.kind === 'user') userTurns++;
513
+ }
514
+ if (userTurns > this.lastUserTurnCount) {
515
+ this.activeTurnIndex = null;
516
+ this.hoveredTurnIndex = null;
517
+ this.hoveredTurnAnchorY = null;
518
+ }
519
+ this.lastUserTurnCount = userTurns;
416
520
  const before = this.lastHeight;
417
521
  const mainWidth = sessionMainWidth(this.width, false, this.env);
418
522
  const contentWidth = this.railEnabled(mainWidth)
@@ -450,6 +554,11 @@ export class StageSurface {
450
554
  this.lastPromptCaret = caret;
451
555
  }
452
556
 
557
+ // Do not grow, resize, or invalidate the band while the terminal owns
558
+ // scrollback; otherwise stage.grow emits newlines that shift the user's
559
+ // scroll position before the detached repaint guard below.
560
+ if (this.detached) return false;
561
+
453
562
  const isModal = Boolean(caret?.modal);
454
563
  if (isModal !== this.wasModal) {
455
564
  this.wasModal = isModal;
@@ -457,6 +566,10 @@ export class StageSurface {
457
566
  }
458
567
 
459
568
  if (this.homeInfo || (caret?.modal && !caret?.inline)) {
569
+ this.syncTurnRailMotion(false);
570
+ this.turnRailLayout = null;
571
+ this.hoveredTurnIndex = null;
572
+ this.hoveredTurnAnchorY = null;
460
573
  if (this.stage.height < this.stage.maxHeight) {
461
574
  this.stage.grow(this.stage.maxHeight - this.stage.height);
462
575
  }
@@ -474,7 +587,7 @@ export class StageSurface {
474
587
  ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
475
588
  : mainWidth;
476
589
 
477
- let block = promptRows;
590
+ let block = Array.isArray(promptRows) && promptRows.length > 0 ? promptRows : [''];
478
591
  let caretRow = caret && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
479
592
  let caretCol = caret ? caret.col : 0;
480
593
 
@@ -506,6 +619,7 @@ export class StageSurface {
506
619
  block = block.slice(cut);
507
620
  caretRow = Math.max(0, caretRow - cut);
508
621
  }
622
+ caretRow = Math.max(0, Math.min(block.length - 1, Math.floor(caretRow)));
509
623
 
510
624
  if (this.lastBlockLength > 0 && this.lastBlockLength !== block.length) {
511
625
  this.stage.invalidate();
@@ -513,6 +627,7 @@ export class StageSurface {
513
627
  this.lastBlockLength = block.length;
514
628
 
515
629
  const budget = Math.max(0, height - block.length);
630
+ this.syncTurnRailMotion(rail && budget > 0 && hasSessionTurns(this.transcript));
516
631
  let rows = [];
517
632
  if (budget > 0) {
518
633
  this.viewport.resize({ height: budget, width: contentWidth });
@@ -529,22 +644,45 @@ export class StageSurface {
529
644
  }
530
645
  this.decorate(rows, contentWidth);
531
646
  markHoveredMessage(rows, this, contentWidth);
532
- if (rail) this.attachRail(rows, contentWidth);
647
+ if (rail) {
648
+ this.attachRail(rows, contentWidth);
649
+ } else {
650
+ this.turnRailLayout = null;
651
+ this.hoveredTurnIndex = null;
652
+ this.hoveredTurnAnchorY = null;
653
+ }
533
654
  if (this.hoveredTurnIndex && this.turnRailLayout?.turns?.length) {
534
655
  const hoveredTurn = this.turnRailLayout.turns.find(t => t.turnIndex === this.hoveredTurnIndex);
535
656
  if (hoveredTurn) {
536
- const card = renderTurnPreviewCard(hoveredTurn, 52);
657
+ const groupRow = this.turnRailLayout?.dotRows?.get(hoveredTurn.turnIndex);
658
+ const group = this.turnRailLayout?.rowToTurns?.get(groupRow) || [hoveredTurn];
659
+ const timeline = group.length > 1
660
+ ? renderTurnTimelineCard(group, Math.min(52, mainWidth - 5), rows.length, this.turnRailCardOffset || 0)
661
+ : null;
662
+ const card = timeline?.rows || renderTurnPreviewCard(hoveredTurn, 52);
537
663
  const anchorY = this.hoveredTurnAnchorY ?? Math.floor(rows.length / 2);
538
664
  rows = overlayTurnPreviewCard(rows, card, anchorY, this.turnRailLayout?.railX ?? 1, mainWidth);
539
665
  if (this.turnRailLayout) {
540
- const cardWidth = 52;
666
+ const cardWidth = visibleWidth(card[0] || '') || 52;
541
667
  const railX = this.turnRailLayout.railX ?? 1;
668
+ const safeAnchorY = Number.isFinite(anchorY) ? Math.floor(anchorY) : Math.floor(rows.length / 2);
542
669
  let cardX = railX - cardWidth - 1;
543
- if (cardX < 0 || (railX <= 4 && railX + 2 + cardWidth <= mainWidth)) {
670
+ if (railX <= 4 && railX + 2 < mainWidth) {
671
+ cardX = railX + 2;
672
+ } else if (cardX < 0) {
544
673
  cardX = Math.max(0, Math.min(mainWidth - cardWidth - 1, railX + 2));
545
674
  }
546
- const startY = Math.max(0, Math.min(rows.length - card.length, anchorY - Math.floor(card.length / 2)));
547
- this.turnRailLayout.cardRect = { x: cardX, y: startY, width: cardWidth, height: card.length, turnIndex: hoveredTurn.turnIndex };
675
+ const effectiveCardWidth = Math.max(1, Math.min(cardWidth, Math.max(1, mainWidth - cardX)));
676
+ const startY = Math.max(0, Math.min(rows.length - card.length, safeAnchorY - Math.floor(card.length / 2)));
677
+ const visibleCardHeight = Math.min(card.length, Math.max(0, rows.length - startY));
678
+ this.turnRailLayout.cardRect = {
679
+ x: cardX, y: startY, width: effectiveCardWidth, height: visibleCardHeight,
680
+ turnIndex: hoveredTurn.turnIndex,
681
+ entries: timeline?.entries || null,
682
+ entryStart: timeline?.entryStart ?? null,
683
+ groupTurns: group.length > 1 ? group : null,
684
+ maxOffset: timeline?.maxOffset || 0
685
+ };
548
686
  }
549
687
  }
550
688
  } else if (this.turnRailLayout) {
@@ -552,8 +690,9 @@ export class StageSurface {
552
690
  }
553
691
  if (this.messageActionOverlay) {
554
692
  const overlay = this.messageActionOverlay;
555
- const placed = placeMessageActionPanel(rows, overlay.panel, contentWidth,
556
- (this.out.rows || height) - height, overlay.layer.anchorY,
693
+ const overlayWidth = rail ? Math.max(contentWidth, mainWidth - RAIL_BUDGET) : contentWidth;
694
+ const placed = placeMessageActionPanel(rows, overlay.panel, overlayWidth,
695
+ Math.max(0, (this.out.rows || height) - height), overlay.layer.anchorY,
557
696
  overlay.layer.items.length, {
558
697
  messageBounds: overlay.layer.messageBounds,
559
698
  dimBackdrop: true
@@ -561,35 +700,25 @@ export class StageSurface {
561
700
  rows = placed.rows;
562
701
  overlay.layer.actionLayout = placed.layout;
563
702
  }
703
+ } else {
704
+ this.turnRailLayout = null;
705
+ this.hoveredTurnIndex = null;
706
+ this.hoveredTurnAnchorY = null;
564
707
  }
565
708
 
566
- // DO NOT PAINT WHILE THE TERMINAL OWNS THE SCROLL.
567
- //
568
- // The Stage repaints by DIFF against the rows it believes are on screen. It
569
- // has no way to know the user scrolled the terminal's own scrollback, and
570
- // when they do, the band's absolute rows move while the diff keeps writing
571
- // to the old coordinates — which is how a session ends up with a stray rail
572
- // column down the middle and fragments of old frames at the edges.
573
- //
574
- // We cannot detect a terminal scroll directly. What we CAN detect is the
575
- // moment we handed the wheel over (viewport at its top, mouse reporting
576
- // released), and from then until the user types again the terminal is the
577
- // thing scrolling. Painting nothing is correct: the band is not where we
578
- // left it, so every write would land somewhere wrong.
579
- if (this.detached) return false;
580
-
581
709
  const mainRows = rows.concat(block);
710
+ const panelWidth = sidebar ? sessionSidebarWidth(width, false, this.env) : 0;
582
711
  const panelRows = sidebar ? sessionSidebarRows({
583
712
  ...this.sessionInfo,
584
713
  cwd: this.sidebarStatus?.cwd || this.sessionInfo?.cwd,
585
714
  provider: this.sidebarStatus?.provider || this.sessionInfo?.provider,
586
715
  model: this.sidebarStatus?.model || this.sessionInfo?.model,
587
- contextChars: this.sidebarStatus?.contextChars,
588
- contextLimit: this.sidebarStatus?.contextLimit,
716
+ contextChars: this.sidebarStatus?.contextChars ?? this.sessionInfo?.contextChars,
717
+ contextLimit: this.sidebarStatus?.contextLimit ?? this.sessionInfo?.contextLimit,
589
718
  plan: this.sidebarPlan,
590
719
  activeSkill: this.sessionInfo?.activeSkill
591
- }, mainRows.length) : [];
592
- const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth) : mainRows;
720
+ }, mainRows.length, panelWidth) : [];
721
+ const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth, panelWidth) : mainRows;
593
722
  return this.stage.paint(painted, {
594
723
  row: rows.length + caretRow,
595
724
  // The composer may never put its caret into the sidebar or the reserved
@@ -655,6 +784,11 @@ export class StageSurface {
655
784
  this.evicted = [];
656
785
  this.transcript.clear();
657
786
  this.lastHeight = 0;
787
+ this.lastUserTurnCount = 0;
788
+ this.activeTurnIndex = null;
789
+ this.hoveredTurnIndex = null;
790
+ this.hoveredTurnAnchorY = null;
791
+ this.turnRailLayout = null;
658
792
  this.stage.invalidate();
659
793
  if (this.viewport) {
660
794
  this.viewport.manual = false;
@@ -682,6 +816,10 @@ export class StageSurface {
682
816
  // The existing rows are already reserved: repaint them in place with
683
817
  // their new width, clearing trailing cells through Stage.paint().
684
818
  const columns = this.stage.width();
819
+ if (columns !== this.lastColumns || next !== this.stage.maxHeight) {
820
+ this.hoveredTurnIndex = null;
821
+ this.hoveredTurnAnchorY = null;
822
+ }
685
823
  if (!this.stage.reserved || next !== this.stage.maxHeight) {
686
824
  this.stage.resize(next, 1);
687
825
  } else if (columns !== this.lastColumns && !this.detached) {
@@ -723,15 +861,32 @@ export class StageSurface {
723
861
  * Returns `height` single-column strings.
724
862
  */
725
863
  buildRail(height, contentWidth) {
726
- const total = Math.max(1, this.transcript.height(contentWidth));
727
- const slotOf = (row) => Math.max(0, Math.min(height - 1, Math.floor((row / total) * height)));
864
+ const flat = typeof this.transcript.flatten === 'function' ? this.transcript.flatten(contentWidth) : null;
865
+ const flatRows = Array.isArray(flat?.rows) ? flat.rows : [];
866
+ const markers = Array.isArray(flat?.markers) ? flat.markers : this.transcript.markers(contentWidth);
867
+ const rawTotal = Math.max(0, flat ? flatRows.length : this.transcript.height(contentWidth));
868
+ const total = Math.max(1, rawTotal);
869
+ const padding = rawTotal <= height ? Math.max(0, height - rawTotal) : 0;
870
+ const slotOf = (row) => (rawTotal <= height
871
+ ? Math.max(0, Math.min(height - 1, padding + row))
872
+ : Math.max(0, Math.min(height - 1, Math.floor((row / total) * height))));
728
873
 
729
874
  const kinds = new Array(height).fill(null);
730
- for (const marker of this.transcript.markers(contentWidth)) {
875
+ for (let mIdx = 0; mIdx < markers.length; mIdx++) {
876
+ const marker = markers[mIdx];
731
877
  // Suppress repetitive step/result/reasoning noise on the overview rail.
732
878
  // Checkpoints, user turns, approvals, and errors remain discoverable.
733
879
  if ((RAIL_PRIORITY[marker.kind] || 0) < 50) continue;
734
- const slot = slotOf(marker.row);
880
+ let markerRow = marker.row;
881
+ if (marker.kind === 'user' && flatRows.length > 0) {
882
+ const nextRow = mIdx + 1 < markers.length ? markers[mIdx + 1].row : flatRows.length;
883
+ if (markerRow + 1 < nextRow && markerRow + 1 < flatRows.length) {
884
+ const firstLine = stripAnsi(String(flatRows[markerRow] ?? '')).trim();
885
+ const secondLine = stripAnsi(String(flatRows[markerRow + 1] ?? '')).trim();
886
+ if (firstLine === '' && secondLine !== '') markerRow += 1;
887
+ }
888
+ }
889
+ const slot = slotOf(markerRow);
735
890
  const held = kinds[slot];
736
891
  if (!held || (RAIL_PRIORITY[marker.kind] || 0) > (RAIL_PRIORITY[held] || 0)) {
737
892
  kinds[slot] = marker.kind;
@@ -769,14 +924,35 @@ export class StageSurface {
769
924
  const turns = collectSessionTurns(this.transcript, contentWidth);
770
925
  const hasTurns = turns.length > 0;
771
926
  const isAtBottom = typeof this.viewport?.atBottom === 'function' ? this.viewport.atBottom() : false;
772
- const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, this.viewport.state().scrollTop, rows.length, isAtBottom);
927
+ const scrollTop = this.viewport.state().scrollTop;
928
+ const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, scrollTop, rows.length, isAtBottom);
773
929
  const railResult = hasTurns
774
- ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex)
930
+ ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex, scrollTop)
775
931
  : null;
776
932
 
933
+ // Keep the original sparse rail. Cluster every turn behind the nearest
934
+ // *visible* dot so no unseen history becomes impossible to reach.
935
+ const rowToTurns = new Map();
936
+ const dotRows = [...(railResult?.layout?.rowToTurn?.keys() || [])].sort((a, b) => a - b);
937
+ for (const turn of turns) {
938
+ const rawRow = railResult?.layout?.dotRows?.get(turn.turnIndex);
939
+ if (!Number.isFinite(rawRow) || dotRows.length === 0) continue;
940
+ let nearest = dotRows[0];
941
+ let distance = Math.abs(rawRow - nearest);
942
+ for (const dotRow of dotRows) {
943
+ const delta = Math.abs(rawRow - dotRow);
944
+ if (delta < distance) {
945
+ nearest = dotRow;
946
+ distance = delta;
947
+ }
948
+ }
949
+ if (!rowToTurns.has(nearest)) rowToTurns.set(nearest, []);
950
+ rowToTurns.get(nearest).push(turn);
951
+ }
777
952
  this.turnRailLayout = {
778
953
  railX: hasTurns ? 1 : contentWidth + 1,
779
- stageTop: (this.out.rows || this.stage.height) - this.stage.height,
954
+ rowToTurns,
955
+ stageTop: Math.max(0, (this.out.rows || this.stage.height) - this.stage.height),
780
956
  viewportHeight: rows.length,
781
957
  dotRows: railResult?.layout?.dotRows || new Map(),
782
958
  rowToTurn: railResult?.layout?.rowToTurn || new Map(),
@@ -802,7 +978,9 @@ export class StageSurface {
802
978
  // Turn markers consume their own three-column lane. Preserve ALL
803
979
  // previously rendered command text instead of clipping its last cells.
804
980
  const rowWidth = contentWidth + (hasTurns ? TURN_RAIL_BUDGET : 0);
805
- rows[i] = `${padEnd(truncate(row, rowWidth, ''), rowWidth)} ${rightCell}`;
981
+ const paddedRow = padEnd(truncate(row, rowWidth, ''), rowWidth);
982
+ const railReset = paddedRow.includes('\x1b[') ? '\x1b[0m' : '';
983
+ rows[i] = `${paddedRow}${railReset} ${rightCell}`;
806
984
  }
807
985
  return rows;
808
986
  }
@@ -819,9 +997,11 @@ export class StageSurface {
819
997
  */
820
998
  releaseMouse() {
821
999
  if (!this.mouseCaptured) return false;
822
- this.out.write(mouseHoverTracking(false, this.env));
823
- this.out.write(mouseTracking(false));
1000
+ // Auto-enabled rail hover must be disarmed even without env opt-in.
1001
+ this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
1002
+ this.writeModeControl(mouseTracking(false));
824
1003
  this.mouseCaptured = false;
1004
+ this.mouseMotionOn = false;
825
1005
  this.detached = true;
826
1006
  return true;
827
1007
  }
@@ -830,9 +1010,10 @@ export class StageSurface {
830
1010
  captureMouse() {
831
1011
  // Home and suspended stages must not arm modes their teardown cannot observe.
832
1012
  if (!this.mouseWanted || !this.mouseOn || !this.stage.reserved || this.mouseCaptured) return false;
833
- this.out.write(mouseTracking(true));
834
- this.out.write(mouseHoverTracking(true, this.env));
1013
+ this.writeModeControl(mouseTracking(true));
1014
+ this.writeModeControl(mouseHoverTracking(true, this.env));
835
1015
  this.mouseCaptured = true;
1016
+ this.mouseMotionOn = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '') === '1';
836
1017
  this.detached = false;
837
1018
  // After native scrollback, the former physical cursor location is unknown.
838
1019
  // Return to the screen bottom before repainting any transcript rows.