@causyne/agent 1.20.85 → 1.20.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.85",
3
+ "version": "1.20.87",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -7,6 +7,7 @@
7
7
  // preventing terminal scrollback desync and UI freezes.
8
8
  // 4. Scrollbar (rail) mouse interactions clamp cleanly even if clicked above or
9
9
  // below the chat box bounds.
10
+ import { sessionMainWidth } from './sessionSidebar.js';
10
11
  /**
11
12
  * Adaptive Wheel Dampener & Momentum Controller.
12
13
  *
@@ -148,12 +149,13 @@ export function handleScrollbarMouse(key, viewport, surface, host) {
148
149
  const stageTop = Math.max(0, termRows - stageH);
149
150
  const viewportH = viewport.height;
150
151
  const stageW = typeof surface.stage?.width === 'function' ? surface.stage.width() : (surface.width || 80);
151
- const hasRail = typeof surface.railEnabled === 'function' ? surface.railEnabled(stageW) : true;
152
- const contentW = hasRail ? Math.max(20, stageW - 3) : stageW;
152
+ const mainW = sessionMainWidth(stageW);
153
+ const hasRail = typeof surface.railEnabled === 'function' ? surface.railEnabled(mainW) : true;
154
+ const contentW = hasRail ? Math.max(20, mainW - 3) : mainW;
153
155
  const mouseX = key.mouse.x;
154
156
  const mouseY = key.mouse.y;
155
- // Rail occupies column contentW - 1 through stageW
156
- const isRailColumn = mouseX >= contentW - 1 && mouseX <= stageW;
157
+ // Rail occupies column contentW - 1 through mainW
158
+ const isRailColumn = mouseX >= contentW - 1 && mouseX <= mainW;
157
159
  if (isRailColumn) {
158
160
  // Auto-heal if detached
159
161
  if (typeof surface.captureMouse === 'function' && surface.detached) {
@@ -8,6 +8,8 @@
8
8
  // 4. Scrollbar (rail) mouse interactions clamp cleanly even if clicked above or
9
9
  // below the chat box bounds.
10
10
 
11
+ import { sessionMainWidth } from './sessionSidebar.js';
12
+
11
13
  export interface MouseCoordinate {
12
14
  x: number;
13
15
  y: number;
@@ -255,14 +257,15 @@ export function handleScrollbarMouse(
255
257
  const stageTop = Math.max(0, termRows - stageH);
256
258
  const viewportH = viewport.height;
257
259
  const stageW = typeof surface.stage?.width === 'function' ? surface.stage.width() : (surface.width || 80);
258
- const hasRail = typeof surface.railEnabled === 'function' ? surface.railEnabled(stageW) : true;
259
- const contentW = hasRail ? Math.max(20, stageW - 3) : stageW;
260
+ const mainW = sessionMainWidth(stageW);
261
+ const hasRail = typeof surface.railEnabled === 'function' ? surface.railEnabled(mainW) : true;
262
+ const contentW = hasRail ? Math.max(20, mainW - 3) : mainW;
260
263
 
261
264
  const mouseX = key.mouse.x;
262
265
  const mouseY = key.mouse.y;
263
266
 
264
- // Rail occupies column contentW - 1 through stageW
265
- const isRailColumn = mouseX >= contentW - 1 && mouseX <= stageW;
267
+ // Rail occupies column contentW - 1 through mainW
268
+ const isRailColumn = mouseX >= contentW - 1 && mouseX <= mainW;
266
269
 
267
270
  if (isRailColumn) {
268
271
  // Auto-heal if detached
@@ -29,7 +29,7 @@ import { markHoveredMessage } from './messageInteraction.js';
29
29
  import { placeMessageActionPanel } from './messageActionPlacement.js';
30
30
  import { mouseTracking } from './keys.js';
31
31
  import { mouseHoverTracking } from './mouseHover.js';
32
- import { truncate, padEnd, visibleWidth } from './text.js';
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
35
  import { sidebarVisible, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
@@ -727,9 +727,11 @@ export class StageSurface {
727
727
  let row = rows[i] || '';
728
728
  if (hasTurns && railResult) {
729
729
  const leftCell = railResult.cells[i] || ' ';
730
- if (row.startsWith(' ')) {
731
- row = ` ${leftCell} ${row.slice(3)}`;
732
- } else if (row.length === 0) {
730
+ const leadMatch = row.match(/^((?:\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_])*)[ ]{3}/);
731
+ if (leadMatch) {
732
+ const leadEscapes = leadMatch[1] || '';
733
+ row = `${leadEscapes} ${leftCell} ${row.slice(leadMatch[0].length)}`;
734
+ } else if (stripAnsi(row).length === 0) {
733
735
  row = leftCell !== ' ' ? ` ${leftCell} ` : '';
734
736
  } else {
735
737
  row = ` ${leftCell} ${row}`;
@@ -1,29 +1,35 @@
1
1
  /**
2
- * Keep the full execution trail, but collapse the second, visually redundant
3
- * success row once a long tool-heavy run is underway. A failure, a non-empty
4
- * output, a diagnostic, or any missing result stays expanded.
2
+ * Presentation-only compaction of completed, silent tool steps.
5
3
  *
6
- * Only the presentation changes. Original tool results still pass through
7
- * captureLastOutput() and the AgentLoop is not affected.
4
+ * Never drop errors, unknown diagnostics, structured results, or output. The
5
+ * AgentLoop's execution contract and underlying result object are unchanged.
6
+ * This TypeScript file is the single source of truth; `toolActivityPolicy.js`
7
+ * is the existing runtime compiler's emitted output.
8
8
  */
9
9
  export const TOOL_ACTIVITY_COMPACT_AFTER = 8;
10
-
10
+ const METADATA_ONLY = new Set([
11
+ 'success', 'exitCode', 'exit_code', 'durationMs', 'elapsedMs',
12
+ 'duration', 'statusCode', 'status_code'
13
+ ]);
14
+ /** Returns true only for a known silent success that can share its step row. */
11
15
  export function compactSuccessfulToolResult(stepCount, result, tail, toolName) {
12
- if (!Number.isFinite(stepCount) || stepCount < TOOL_ACTIVITY_COMPACT_AFTER) return false;
13
- if (!result || result.success !== true) return false;
14
- if (!tail || tail.kind !== 'step' || !tail.meta) return false;
15
- if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? '')) return false;
16
- // Only truly silent successes qualify. Unknown provider-specific result
17
- // fields must remain visible, rather than being hidden by an allowlist of
18
- // familiar output property names.
19
- const metadataOnly = new Set([
20
- 'success', 'exitCode', 'exit_code', 'durationMs', 'elapsedMs', 'duration',
21
- 'statusCode', 'status_code'
22
- ]);
23
- for (const [key, value] of Object.entries(result)) {
24
- if (metadataOnly.has(key)) continue;
25
- if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) continue;
26
- return false;
27
- }
28
- return true;
16
+ if (!Number.isFinite(stepCount) || stepCount < TOOL_ACTIVITY_COMPACT_AFTER)
17
+ return false;
18
+ if (result === null || typeof result !== 'object' || Array.isArray(result))
19
+ return false;
20
+ const record = result;
21
+ if (record.success !== true)
22
+ return false;
23
+ if (!tail || tail.kind !== 'step' || !tail.meta)
24
+ return false;
25
+ if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? ''))
26
+ return false;
27
+ for (const [key, value] of Object.entries(record)) {
28
+ if (METADATA_ONLY.has(key))
29
+ continue;
30
+ if (value == null || value === '' || (Array.isArray(value) && value.length === 0))
31
+ continue;
32
+ return false;
33
+ }
34
+ return true;
29
35
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Presentation-only compaction of completed, silent tool steps.
3
+ *
4
+ * Never drop errors, unknown diagnostics, structured results, or output. The
5
+ * AgentLoop's execution contract and underlying result object are unchanged.
6
+ * This TypeScript file is the single source of truth; `toolActivityPolicy.js`
7
+ * is the existing runtime compiler's emitted output.
8
+ */
9
+
10
+ export const TOOL_ACTIVITY_COMPACT_AFTER = 8;
11
+
12
+ export interface ToolActivityFrame {
13
+ readonly kind?: string;
14
+ readonly meta?: Readonly<Record<string, unknown>> | null;
15
+ }
16
+
17
+ const METADATA_ONLY = new Set([
18
+ 'success', 'exitCode', 'exit_code', 'durationMs', 'elapsedMs',
19
+ 'duration', 'statusCode', 'status_code'
20
+ ]);
21
+
22
+ /** Returns true only for a known silent success that can share its step row. */
23
+ export function compactSuccessfulToolResult(
24
+ stepCount: number,
25
+ result: unknown,
26
+ tail: ToolActivityFrame | null | undefined,
27
+ toolName: unknown
28
+ ): boolean {
29
+ if (!Number.isFinite(stepCount) || stepCount < TOOL_ACTIVITY_COMPACT_AFTER) return false;
30
+ if (result === null || typeof result !== 'object' || Array.isArray(result)) return false;
31
+ const record = result as Readonly<Record<string, unknown>>;
32
+ if (record.success !== true) return false;
33
+ if (!tail || tail.kind !== 'step' || !tail.meta) return false;
34
+ if (tail.meta.step !== stepCount || String(tail.meta.tool ?? '') !== String(toolName ?? '')) return false;
35
+
36
+ for (const [key, value] of Object.entries(record)) {
37
+ if (METADATA_ONLY.has(key)) continue;
38
+ if (value == null || value === '' || (Array.isArray(value) && value.length === 0)) continue;
39
+ return false;
40
+ }
41
+ return true;
42
+ }
@@ -347,11 +347,20 @@ export function overlayTurnPreviewCard(viewportRows, cardRows, anchorY, railX, s
347
347
  if (x <= 6 && railX <= 4) {
348
348
  const plainBase = stripAnsi(baseRow);
349
349
  const dotChar = plainBase[railX] || ' ';
350
- const isDot = dotChar === '●' || dotChar === '•' || dotChar === '·' || dotChar === '[' || dotChar === ']';
350
+ const isDot = dotChar === '●' || dotChar === '•' || dotChar === '·';
351
351
  let dotCell = ' ';
352
352
  if (isDot) {
353
- const sliceDot = sliceFromColumn(baseRow, railX);
354
- dotCell = sliceDot ? truncate(sliceDot, 1, '') : dotChar;
353
+ if (dotChar === '●') {
354
+ dotCell = baseRow.includes('230;235;245m')
355
+ ? '\x1b[1m\x1b[38;2;230;235;245m●\x1b[0m'
356
+ : '\x1b[1m\x1b[38;2;250;250;250m●\x1b[0m';
357
+ }
358
+ else if (dotChar === '•') {
359
+ dotCell = '\x1b[38;2;115;115;120m•\x1b[0m';
360
+ }
361
+ else {
362
+ dotCell = dotChar;
363
+ }
355
364
  }
356
365
  const leadingSpace = ' '.repeat(Math.max(0, railX));
357
366
  const trailingSpace = ' '.repeat(Math.max(0, x - railX - 1));
@@ -362,11 +371,12 @@ export function overlayTurnPreviewCard(viewportRows, cardRows, anchorY, railX, s
362
371
  }
363
372
  let restOfRow = '';
364
373
  if (x <= 6) {
365
- // For left-placed turn cards, do not leave severed text tails sticking out
366
- const totalRowWidth = Math.max(screenWidth, visibleWidth(baseRow));
367
- const rightCell = sliceFromColumn(baseRow, totalRowWidth - 1);
374
+ // For left-placed turn cards, preserve the right overview rail without severed text leaks
375
+ const rowLen = visibleWidth(baseRow);
376
+ const rightCell = rowLen > 0 ? sliceFromColumn(baseRow, rowLen - 1) : ' ';
368
377
  const rightCellWidth = visibleWidth(rightCell);
369
- const gap = Math.max(0, totalRowWidth - x - cardWidth - rightCellWidth);
378
+ const targetWidth = Math.max(screenWidth, rowLen);
379
+ const gap = Math.max(0, targetWidth - x - cardWidth - rightCellWidth);
370
380
  restOfRow = `${' '.repeat(gap)}${rightCell}`;
371
381
  }
372
382
  else {
@@ -391,10 +401,10 @@ export function handleTurnRailMouse(event, surface, host) {
391
401
  const mouseY = event.mouse.y;
392
402
  const stageTop = layout.stageTop ?? 0;
393
403
  const relY = mouseY - stageTop;
394
- // Rail hit box: if railX <= 2, check columns 0..3 (left margin); otherwise check [railX - 1, railX + 2]
395
- const isRail = layout.railX <= 2
396
- ? (mouseX >= 0 && mouseX <= Math.max(3, layout.railX + 2))
397
- : (mouseX >= layout.railX - 1 && mouseX <= layout.railX + 2);
404
+ // Rail hit box: if railX <= 4, check columns 0..5 (left margin); otherwise check [railX - 2, railX + 3]
405
+ const isRail = layout.railX <= 4
406
+ ? (mouseX >= 0 && mouseX <= Math.max(5, layout.railX + 3))
407
+ : (mouseX >= layout.railX - 2 && mouseX <= layout.railX + 3);
398
408
  // Check if currently showing a card and mouse is hovering over the card or bridge tunnel
399
409
  const hasActiveCard = surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined;
400
410
  let isCard = false;
@@ -432,11 +432,18 @@ export function overlayTurnPreviewCard(
432
432
  if (x <= 6 && railX <= 4) {
433
433
  const plainBase = stripAnsi(baseRow);
434
434
  const dotChar = plainBase[railX] || ' ';
435
- const isDot = dotChar === '●' || dotChar === '•' || dotChar === '·' || dotChar === '[' || dotChar === ']';
435
+ const isDot = dotChar === '●' || dotChar === '•' || dotChar === '·';
436
436
  let dotCell = ' ';
437
437
  if (isDot) {
438
- const sliceDot = sliceFromColumn(baseRow, railX);
439
- dotCell = sliceDot ? truncate(sliceDot, 1, '') : dotChar;
438
+ if (dotChar === '●') {
439
+ dotCell = baseRow.includes('230;235;245m')
440
+ ? '\x1b[1m\x1b[38;2;230;235;245m●\x1b[0m'
441
+ : '\x1b[1m\x1b[38;2;250;250;250m●\x1b[0m';
442
+ } else if (dotChar === '•') {
443
+ dotCell = '\x1b[38;2;115;115;120m•\x1b[0m';
444
+ } else {
445
+ dotCell = dotChar;
446
+ }
440
447
  }
441
448
  const leadingSpace = ' '.repeat(Math.max(0, railX));
442
449
  const trailingSpace = ' '.repeat(Math.max(0, x - railX - 1));
@@ -447,11 +454,12 @@ export function overlayTurnPreviewCard(
447
454
 
448
455
  let restOfRow = '';
449
456
  if (x <= 6) {
450
- // For left-placed turn cards, do not leave severed text tails sticking out
451
- const totalRowWidth = Math.max(screenWidth, visibleWidth(baseRow));
452
- const rightCell = sliceFromColumn(baseRow, totalRowWidth - 1);
457
+ // For left-placed turn cards, preserve the right overview rail without severed text leaks
458
+ const rowLen = visibleWidth(baseRow);
459
+ const rightCell = rowLen > 0 ? sliceFromColumn(baseRow, rowLen - 1) : ' ';
453
460
  const rightCellWidth = visibleWidth(rightCell);
454
- const gap = Math.max(0, totalRowWidth - x - cardWidth - rightCellWidth);
461
+ const targetWidth = Math.max(screenWidth, rowLen);
462
+ const gap = Math.max(0, targetWidth - x - cardWidth - rightCellWidth);
455
463
  restOfRow = `${' '.repeat(gap)}${rightCell}`;
456
464
  } else {
457
465
  restOfRow = sliceFromColumn(baseRow, x + cardWidth);
@@ -482,10 +490,10 @@ export function handleTurnRailMouse(
482
490
  const stageTop = layout.stageTop ?? 0;
483
491
  const relY = mouseY - stageTop;
484
492
 
485
- // Rail hit box: if railX <= 2, check columns 0..3 (left margin); otherwise check [railX - 1, railX + 2]
486
- const isRail = layout.railX <= 2
487
- ? (mouseX >= 0 && mouseX <= Math.max(3, layout.railX + 2))
488
- : (mouseX >= layout.railX - 1 && mouseX <= layout.railX + 2);
493
+ // Rail hit box: if railX <= 4, check columns 0..5 (left margin); otherwise check [railX - 2, railX + 3]
494
+ const isRail = layout.railX <= 4
495
+ ? (mouseX >= 0 && mouseX <= Math.max(5, layout.railX + 3))
496
+ : (mouseX >= layout.railX - 2 && mouseX <= layout.railX + 3);
489
497
 
490
498
  // Check if currently showing a card and mouse is hovering over the card or bridge tunnel
491
499
  const hasActiveCard = surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined;
@@ -1,77 +1,80 @@
1
1
  /**
2
- * Preserve the reader's location while terminal geometry changes.
2
+ * Frame-anchored viewport reflow for Causyne's Stage/Transcript architecture.
3
3
  *
4
- * Row indices are screen-layout positions, not document positions. Re-wrapping a
5
- * transcript changes frame heights, so keeping the same numeric scrollTop can
6
- * jump to unrelated content. Frame identity + relative offset is stable across
7
- * width changes, without storing or duplicating any message content.
4
+ * Numeric scroll rows are layout coordinates. They change when a terminal is
5
+ * resized, whereas a transcript frame's ID remains stable. Preserve the frame
6
+ * identity and the approximate relative reading position within that frame.
8
7
  *
9
- * This module is deliberately independent of Stage, Transcript, and Node I/O.
8
+ * TypeScript is the authoritative source. Runtime JS is produced by the
9
+ * repository's existing `tsc -p tsconfig.runtime.json` build.
10
10
  */
11
-
12
11
  function finiteRow(value) {
13
- return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
12
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
14
13
  }
15
-
16
14
  function safeMarkers(markers) {
17
- if (!Array.isArray(markers)) return [];
18
- return markers
19
- .filter(marker => marker && Number.isFinite(marker.row) && marker.row >= 0)
20
- .map((marker, index) => ({
21
- id: marker.id,
22
- row: finiteRow(marker.row),
23
- originalIndex: index
24
- }));
15
+ if (!Array.isArray(markers))
16
+ return [];
17
+ return markers.flatMap((marker, originalIndex) => {
18
+ if (!marker || !Number.isFinite(marker.row) || marker.row < 0)
19
+ return [];
20
+ return [{ id: marker.id, row: finiteRow(marker.row), originalIndex }];
21
+ });
25
22
  }
26
-
27
- /** Capture an anchor at the first visible row, measured within its frame. */
23
+ /** Capture the first currently visible frame and relative position within it. */
28
24
  export function captureReadingAnchor(markers, top, totalHeight) {
29
- const entries = safeMarkers(markers);
30
- if (!entries.length) return null;
31
- const row = finiteRow(top);
32
- let selected = 0;
33
- for (let i = 0; i < entries.length; i++) {
34
- if (entries[i].row > row) break;
35
- selected = i;
36
- }
37
- const start = entries[selected].row;
38
- const next = entries[selected + 1]?.row ?? finiteRow(totalHeight);
39
- const frameLength = Math.max(1, next - start);
40
- return Object.freeze({
41
- id: entries[selected].id ?? null,
42
- index: entries[selected].originalIndex,
43
- offset: Math.max(0, row - start),
44
- fraction: Math.max(0, Math.min(1, (row - start) / frameLength)),
45
- originalTop: row
46
- });
25
+ const entries = safeMarkers(markers);
26
+ if (entries.length === 0)
27
+ return null;
28
+ const row = finiteRow(top);
29
+ let selected = 0;
30
+ for (let i = 0; i < entries.length; i++) {
31
+ if ((entries[i]?.row ?? Number.POSITIVE_INFINITY) > row)
32
+ break;
33
+ selected = i;
34
+ }
35
+ const entry = entries[selected];
36
+ if (!entry)
37
+ return null;
38
+ const start = entry.row;
39
+ const next = entries[selected + 1]?.row ?? finiteRow(totalHeight);
40
+ const frameLength = Math.max(1, next - start);
41
+ return Object.freeze({
42
+ id: entry.id ?? null,
43
+ index: entry.originalIndex,
44
+ offset: Math.max(0, row - start),
45
+ fraction: Math.max(0, Math.min(1, (row - start) / frameLength)),
46
+ originalTop: row
47
+ });
47
48
  }
48
-
49
- /** Restore to the corresponding frame and approximately the same content line. */
49
+ /** Restore the matching frame and a proportional content offset after reflow. */
50
50
  export function restoreReadingAnchor(anchor, markers, totalHeight, viewportHeight) {
51
- const total = finiteRow(totalHeight);
52
- const visible = Math.max(1, finiteRow(viewportHeight));
53
- const max = Math.max(0, total - visible);
54
- if (!anchor || !max) return 0;
55
- const entries = safeMarkers(markers);
56
- if (!entries.length) return Math.min(max, finiteRow(anchor.originalTop));
57
-
58
- let selected = anchor.id == null
59
- ? -1
60
- : entries.findIndex(marker => marker.id === anchor.id);
61
- if (selected < 0 && anchor.id == null && entries[anchor.index]?.originalIndex === anchor.index) {
62
- selected = anchor.index;
63
- }
64
- if (selected < 0) {
65
- // Frames may have been evicted while the user was reading. Use the first
66
- // surviving frame rather than silently jumping to an unrelated old row.
67
- selected = 0;
68
- }
69
- const start = entries[selected].row;
70
- const end = entries[selected + 1]?.row ?? total;
71
- const length = Math.max(1, end - start);
72
- const fraction = Number.isFinite(anchor.fraction) ? Math.max(0, Math.min(1, anchor.fraction)) : 0;
73
- // Relative position is more useful than raw offset after a long paragraph
74
- // wraps from 15 lines to 30, while staying inside the same frame.
75
- const offset = Math.min(length - 1, Math.round(fraction * length));
76
- return Math.max(0, Math.min(max, start + offset));
51
+ const total = finiteRow(totalHeight);
52
+ const visible = Math.max(1, finiteRow(viewportHeight));
53
+ const max = Math.max(0, total - visible);
54
+ if (!anchor || max === 0)
55
+ return 0;
56
+ const entries = safeMarkers(markers);
57
+ if (entries.length === 0)
58
+ return Math.min(max, finiteRow(anchor.originalTop));
59
+ let selected = anchor.id == null
60
+ ? -1
61
+ : entries.findIndex(marker => marker.id === anchor.id);
62
+ if (selected < 0 && anchor.id == null && entries[anchor.index]?.originalIndex === anchor.index) {
63
+ selected = anchor.index;
64
+ }
65
+ if (selected < 0) {
66
+ // When the anchored frame was evicted, recover in the surviving transcript.
67
+ selected = 0;
68
+ }
69
+ const entry = entries[selected];
70
+ if (!entry)
71
+ return Math.min(max, finiteRow(anchor.originalTop));
72
+ const start = entry.row;
73
+ const end = entries[selected + 1]?.row ?? total;
74
+ const length = Math.max(1, end - start);
75
+ const fraction = Number.isFinite(anchor.fraction)
76
+ ? Math.max(0, Math.min(1, anchor.fraction))
77
+ : 0;
78
+ const offset = Math.min(length - 1, Math.round(fraction * length));
79
+ return Math.max(0, Math.min(max, start + offset));
77
80
  }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Frame-anchored viewport reflow for Causyne's Stage/Transcript architecture.
3
+ *
4
+ * Numeric scroll rows are layout coordinates. They change when a terminal is
5
+ * resized, whereas a transcript frame's ID remains stable. Preserve the frame
6
+ * identity and the approximate relative reading position within that frame.
7
+ *
8
+ * TypeScript is the authoritative source. Runtime JS is produced by the
9
+ * repository's existing `tsc -p tsconfig.runtime.json` build.
10
+ */
11
+
12
+ export interface ReadingMarker {
13
+ readonly id?: number;
14
+ readonly row: number;
15
+ readonly kind?: string;
16
+ }
17
+
18
+ export interface ReadingAnchor {
19
+ readonly id: number | null;
20
+ readonly index: number;
21
+ readonly offset: number;
22
+ readonly fraction: number;
23
+ readonly originalTop: number;
24
+ }
25
+
26
+ interface SafeMarker {
27
+ readonly id: number | undefined;
28
+ readonly row: number;
29
+ readonly originalIndex: number;
30
+ }
31
+
32
+ function finiteRow(value: number): number {
33
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
34
+ }
35
+
36
+ function safeMarkers(markers: readonly ReadingMarker[] | null | undefined): SafeMarker[] {
37
+ if (!Array.isArray(markers)) return [];
38
+ return markers.flatMap((marker, originalIndex): SafeMarker[] => {
39
+ if (!marker || !Number.isFinite(marker.row) || marker.row < 0) return [];
40
+ return [{ id: marker.id, row: finiteRow(marker.row), originalIndex }];
41
+ });
42
+ }
43
+
44
+ /** Capture the first currently visible frame and relative position within it. */
45
+ export function captureReadingAnchor(
46
+ markers: readonly ReadingMarker[] | null | undefined,
47
+ top: number,
48
+ totalHeight: number
49
+ ): ReadingAnchor | null {
50
+ const entries = safeMarkers(markers);
51
+ if (entries.length === 0) return null;
52
+ const row = finiteRow(top);
53
+ let selected = 0;
54
+ for (let i = 0; i < entries.length; i++) {
55
+ if ((entries[i]?.row ?? Number.POSITIVE_INFINITY) > row) break;
56
+ selected = i;
57
+ }
58
+ const entry = entries[selected];
59
+ if (!entry) return null;
60
+ const start = entry.row;
61
+ const next = entries[selected + 1]?.row ?? finiteRow(totalHeight);
62
+ const frameLength = Math.max(1, next - start);
63
+ return Object.freeze({
64
+ id: entry.id ?? null,
65
+ index: entry.originalIndex,
66
+ offset: Math.max(0, row - start),
67
+ fraction: Math.max(0, Math.min(1, (row - start) / frameLength)),
68
+ originalTop: row
69
+ });
70
+ }
71
+
72
+ /** Restore the matching frame and a proportional content offset after reflow. */
73
+ export function restoreReadingAnchor(
74
+ anchor: ReadingAnchor | null,
75
+ markers: readonly ReadingMarker[] | null | undefined,
76
+ totalHeight: number,
77
+ viewportHeight: number
78
+ ): number {
79
+ const total = finiteRow(totalHeight);
80
+ const visible = Math.max(1, finiteRow(viewportHeight));
81
+ const max = Math.max(0, total - visible);
82
+ if (!anchor || max === 0) return 0;
83
+ const entries = safeMarkers(markers);
84
+ if (entries.length === 0) return Math.min(max, finiteRow(anchor.originalTop));
85
+
86
+ let selected = anchor.id == null
87
+ ? -1
88
+ : entries.findIndex(marker => marker.id === anchor.id);
89
+ if (selected < 0 && anchor.id == null && entries[anchor.index]?.originalIndex === anchor.index) {
90
+ selected = anchor.index;
91
+ }
92
+ if (selected < 0) {
93
+ // When the anchored frame was evicted, recover in the surviving transcript.
94
+ selected = 0;
95
+ }
96
+ const entry = entries[selected];
97
+ if (!entry) return Math.min(max, finiteRow(anchor.originalTop));
98
+ const start = entry.row;
99
+ const end = entries[selected + 1]?.row ?? total;
100
+ const length = Math.max(1, end - start);
101
+ const fraction = Number.isFinite(anchor.fraction)
102
+ ? Math.max(0, Math.min(1, anchor.fraction))
103
+ : 0;
104
+ const offset = Math.min(length - 1, Math.round(fraction * length));
105
+ return Math.max(0, Math.min(max, start + offset));
106
+ }
@@ -1,19 +0,0 @@
1
- export interface ReadingMarker { id?: number; row: number; kind?: string }
2
- export interface ReadingAnchor {
3
- readonly id: number | null;
4
- readonly index: number;
5
- readonly offset: number;
6
- readonly fraction: number;
7
- readonly originalTop: number;
8
- }
9
- export declare function captureReadingAnchor(
10
- markers: ReadingMarker[] | null | undefined,
11
- top: number,
12
- totalHeight: number
13
- ): ReadingAnchor | null;
14
- export declare function restoreReadingAnchor(
15
- anchor: ReadingAnchor | null,
16
- markers: ReadingMarker[] | null | undefined,
17
- totalHeight: number,
18
- viewportHeight: number
19
- ): number;