@causyne/agent 1.20.0 → 1.20.5

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 (125) hide show
  1. package/README.md +0 -18
  2. package/package.json +1 -1
  3. package/src/acp/client.js +2 -1
  4. package/src/acp/client.ts +2 -1
  5. package/src/acp/server.js +5 -6
  6. package/src/acp/server.ts +4 -6
  7. package/src/agentLoop.d.ts +1 -0
  8. package/src/agentLoop.js +505 -241
  9. package/src/agentLoop.ts +527 -258
  10. package/src/agentPolicy.js +9 -0
  11. package/src/agentPolicy.ts +9 -0
  12. package/src/approvalPolicy.js +55 -0
  13. package/src/approvalPolicy.ts +66 -0
  14. package/src/browser/browserRuntime.js +217 -14
  15. package/src/browser/browserRuntime.ts +255 -14
  16. package/src/browser/causyneBrowser.js +1215 -68
  17. package/src/browser/causyneBrowser.ts +1340 -72
  18. package/src/cliMode.js +52 -29
  19. package/src/commands.js +141 -17
  20. package/src/config.js +22 -12
  21. package/src/continuum/ui/continuumPicker.js +18 -1
  22. package/src/continuum/ui/continuumPicker.ts +19 -1
  23. package/src/dynamicCatalogue.js +87 -20
  24. package/src/dynamicCatalogue.ts +85 -15
  25. package/src/launchIntent.js +40 -0
  26. package/src/launchIntent.ts +49 -0
  27. package/src/memoryManager.js +26 -2
  28. package/src/modelCatalogue.js +2 -0
  29. package/src/planCache.js +320 -11
  30. package/src/planCache.ts +402 -13
  31. package/src/providers/acp.js +67 -1
  32. package/src/providers/acp.ts +65 -2
  33. package/src/providers/antigravity.d.ts +5 -1
  34. package/src/providers/antigravity.js +643 -32
  35. package/src/providers/antigravity.ts +671 -33
  36. package/src/providers/base.d.ts +9 -0
  37. package/src/providers/factory.js +2 -0
  38. package/src/providers/pi.js +157 -0
  39. package/src/providers/pi.ts +144 -0
  40. package/src/provisioning/capabilityProvisioner.js +17 -0
  41. package/src/provisioning/capabilityTools.js +1 -1
  42. package/src/sandbox.js +30 -39
  43. package/src/sessionJournal.js +53 -10
  44. package/src/sessionJournal.ts +64 -10
  45. package/src/taskShape.js +9 -9
  46. package/src/taskShape.ts +9 -9
  47. package/src/timeMachine.js +124 -0
  48. package/src/timeMachine.ts +141 -0
  49. package/src/toolPacks.js +4 -10
  50. package/src/tools/archive.js +196 -59
  51. package/src/tools/archive.ts +220 -0
  52. package/src/tools/browserAutomator.js +78 -9
  53. package/src/tools/browserAutomator.ts +90 -9
  54. package/src/tools/desktopOpen.js +114 -31
  55. package/src/tools/desktopOpen.ts +144 -0
  56. package/src/tools/gitExec.js +5 -3
  57. package/src/tools/nativeEngine.js +4 -3
  58. package/src/tools/nativeEngine.ts +5 -3
  59. package/src/tools/openSourceToolProvisioner.js +5 -4
  60. package/src/tools/openSourceToolProvisioner.ts +5 -4
  61. package/src/tools/registry.js +3 -0
  62. package/src/tools/screenshot.js +55 -71
  63. package/src/tools/screenshot.ts +70 -0
  64. package/src/tools/sysRun.js +284 -117
  65. package/src/tools/sysRun.ts +347 -0
  66. package/src/tools/toolSelfRepair.js +109 -2
  67. package/src/tools/toolSelfRepair.ts +100 -2
  68. package/src/tools/updatePlan.js +49 -1
  69. package/src/tools/updatePlan.ts +43 -1
  70. package/src/tools/viewImage.js +93 -78
  71. package/src/tools/viewImage.ts +116 -0
  72. package/src/tools/webFetch.js +20 -6
  73. package/src/tools/webFetch.ts +26 -6
  74. package/src/tui/block.d.ts +1 -0
  75. package/src/tui/chatRenderer.d.ts +21 -0
  76. package/src/tui/chatRenderer.js +34 -47
  77. package/src/tui/clipboardSync.js +28 -1
  78. package/src/tui/clipboardSync.ts +26 -1
  79. package/src/tui/codeProgress.js +299 -0
  80. package/src/tui/codeProgress.ts +304 -0
  81. package/src/tui/codeStreamRenderer.js +116 -0
  82. package/src/tui/codeStreamRenderer.ts +124 -0
  83. package/src/tui/commandPresentation.js +11 -0
  84. package/src/tui/commandPresentation.ts +18 -0
  85. package/src/tui/completion.js +45 -13
  86. package/src/tui/composerControls.js +66 -0
  87. package/src/tui/composerControls.ts +78 -0
  88. package/src/tui/diff.d.ts +2 -0
  89. package/src/tui/home.js +4 -2
  90. package/src/tui/homeTransition.js +21 -0
  91. package/src/tui/homeTransition.ts +27 -0
  92. package/src/tui/homeView.js +62 -0
  93. package/src/tui/homeView.ts +91 -0
  94. package/src/tui/layout.js +46 -0
  95. package/src/tui/layout.ts +52 -0
  96. package/src/tui/messageActionPlacement.js +16 -0
  97. package/src/tui/messageActionPlacement.ts +25 -0
  98. package/src/tui/messageInteraction.js +221 -0
  99. package/src/tui/messageInteraction.ts +275 -0
  100. package/src/tui/modelPicker.js +4 -24
  101. package/src/tui/modelPicker.ts +4 -20
  102. package/src/tui/mouseHover.js +6 -0
  103. package/src/tui/mouseHover.ts +5 -0
  104. package/src/tui/prompt.js +152 -76
  105. package/src/tui/resizeRecovery.js +15 -0
  106. package/src/tui/resizeRecovery.ts +27 -0
  107. package/src/tui/scrollInteraction.js +97 -0
  108. package/src/tui/scrollInteraction.ts +189 -0
  109. package/src/tui/sessionLayout.js +12 -0
  110. package/src/tui/sessionLayout.ts +12 -0
  111. package/src/tui/sessionPicker.js +111 -16
  112. package/src/tui/sessionPicker.ts +121 -16
  113. package/src/tui/sessionSidebar.js +78 -0
  114. package/src/tui/sessionSidebar.ts +95 -0
  115. package/src/tui/setup.js +1 -1
  116. package/src/tui/setup.ts +1 -1
  117. package/src/tui/stageSurface.js +120 -58
  118. package/src/tui/text.d.ts +5 -0
  119. package/src/tui/textLayout.js +23 -0
  120. package/src/tui/textLayout.ts +28 -0
  121. package/src/tui/viewport.js +204 -279
  122. package/src/tui/viewport.ts +326 -0
  123. package/src/types/contracts.ts +54 -0
  124. package/src/utils/paths.js +5 -4
  125. package/src/utils/paths.ts +5 -5
@@ -0,0 +1,221 @@
1
+ import { getActiveSessionId, getSession } from '../sessionJournal.js';
2
+ import { revokeAllAlways } from '../approvalGrants.js';
3
+ import { writeClipboardSync } from './clipboardSync.js';
4
+ import { sidebarVisible, sessionMainWidth } from './sessionSidebar.js';
5
+ import { truncate, padEnd } from './text.js';
6
+ // @ts-expect-error Legacy overlay has no declaration yet.
7
+ import { Layer } from './overlay.js';
8
+ // @ts-expect-error Legacy theme has no declaration yet.
9
+ import { paint, bold, fill } from './theme.js';
10
+ /** Two actions need two rows; the generic searchable picker hides the second one. */
11
+ export class MessageActionsLayer extends Layer {
12
+ messageActions = true;
13
+ actionLayout = null;
14
+ anchorY;
15
+ items;
16
+ list;
17
+ onPick;
18
+ settled = false;
19
+ constructor(items, onPick, anchorY = null) {
20
+ super({ title: 'Message Actions', width: 68, height: items.length + 2, footer: '↑↓ move · enter select · esc close' });
21
+ this.items = items;
22
+ this.onPick = onPick;
23
+ this.anchorY = anchorY;
24
+ this.list = {
25
+ filtered: items,
26
+ selected: 0,
27
+ moveTo: (index) => { this.list.selected = Math.max(0, Math.min(items.length - 1, index)); }
28
+ };
29
+ }
30
+ preferredHeight() { return this.items.length + 2; }
31
+ body(width) {
32
+ return this.items.map((item, index) => {
33
+ const selected = index === this.list.selected;
34
+ const label = `${selected ? '▸' : ' '} ${item.label}`;
35
+ const description = ` ${item.description}`;
36
+ const room = Math.max(0, width - description.length);
37
+ const content = `${truncate(label, room, '…')}${description}`;
38
+ return selected ? paint('accent', bold(truncate(content, width, '…'))) : paint('ink', truncate(content, width, '…'));
39
+ });
40
+ }
41
+ key(event) {
42
+ if (event.name === 'escape')
43
+ return 'close';
44
+ if (event.name === 'up' || event.name === 'down') {
45
+ const delta = event.name === 'up' ? -1 : 1;
46
+ this.list.moveTo((this.list.selected + delta + this.items.length) % this.items.length);
47
+ return 'handled';
48
+ }
49
+ if (event.name === 'enter' || event.name === 'return') {
50
+ this.settled = true;
51
+ this.onPick(this.items[this.list.selected] ?? null);
52
+ return 'close';
53
+ }
54
+ return 'handled';
55
+ }
56
+ answer() {
57
+ if (!this.settled) {
58
+ this.settled = true;
59
+ this.onPick(null);
60
+ }
61
+ }
62
+ }
63
+ export function isMouseMotion(sequence) {
64
+ const code = Number(/^\x1b\[<(\d+);/.exec(sequence || '')?.[1]);
65
+ return Number.isFinite(code) && (code & 32) !== 0;
66
+ }
67
+ export function handleMessageMouse(host, loop, event) {
68
+ const mouse = event.mouse;
69
+ const surface = host.surface;
70
+ if (!mouse || !surface)
71
+ return false;
72
+ const marker = messageAt(surface, mouse);
73
+ if (surface.hoveredMessageFrameId !== (marker?.id ?? null)) {
74
+ surface.hoveredMessageFrameId = marker?.id ?? null;
75
+ host.scheduleDraw();
76
+ }
77
+ // SGR motion carries bit 32; it must update hover without opening the menu.
78
+ if (isMouseMotion(event.sequence))
79
+ return true;
80
+ if (mouse.button === 0 && mouse.pressed && marker)
81
+ openMessageActions(host, loop, marker, mouse.y);
82
+ return true;
83
+ }
84
+ const isMessage = (marker) => (marker.kind === 'user' || marker.kind === 'assistant')
85
+ && typeof marker.meta?.messageText === 'string';
86
+ /** Resolve screen coordinates against the painted viewport, including top padding. */
87
+ export function messageAt(surface, point) {
88
+ if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y))
89
+ return null;
90
+ const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
91
+ if (point.x < 0 || point.x >= Math.min(mainWidth, surface.viewport.width))
92
+ return null;
93
+ const top = Math.max(0, (surface.out.rows || surface.stage.height) - surface.stage.height);
94
+ const viewRow = point.y - top;
95
+ if (viewRow < 0 || viewRow >= surface.viewport.height)
96
+ return null;
97
+ const flat = surface.transcript.flatten(surface.viewport.width);
98
+ const visible = Math.max(0, Math.min(surface.viewport.height, flat.rows.length - surface.viewport.scrollTop));
99
+ const padding = surface.viewport.height - visible;
100
+ if (viewRow < padding)
101
+ return null;
102
+ const row = surface.viewport.scrollTop + viewRow - padding;
103
+ for (let i = flat.markers.length - 1; i >= 0; i--) {
104
+ const marker = flat.markers[i];
105
+ if (!marker || marker.row > row)
106
+ continue;
107
+ const next = flat.markers[i + 1];
108
+ if (isMessage(marker) && row < (next?.row ?? flat.rows.length))
109
+ return marker;
110
+ return null;
111
+ }
112
+ return null;
113
+ }
114
+ /** Highlight only the visible rows of the hovered message, without altering transcript data. */
115
+ export function markHoveredMessage(rows, surface, contentWidth) {
116
+ const id = surface.hoveredMessageFrameId;
117
+ if (!id)
118
+ return;
119
+ const flat = surface.transcript.flatten(contentWidth);
120
+ const marker = flat.markers.find(item => item.id === id);
121
+ if (!marker || !isMessage(marker))
122
+ return;
123
+ const visible = Math.max(0, Math.min(rows.length, flat.rows.length - surface.viewport.scrollTop));
124
+ const padding = rows.length - visible;
125
+ const next = flat.markers[flat.markers.indexOf(marker) + 1];
126
+ const first = Math.max(marker.row, surface.viewport.scrollTop);
127
+ const last = Math.min(next?.row ?? flat.rows.length, surface.viewport.scrollTop + visible);
128
+ for (let transcriptRow = first; transcriptRow < last; transcriptRow++) {
129
+ const row = transcriptRow - surface.viewport.scrollTop + padding;
130
+ if (row < padding || row >= rows.length)
131
+ continue;
132
+ const content = transcriptRow === marker.row
133
+ ? `${paint('accent', '▸')} ${truncate(rows[row] ?? '', Math.max(0, contentWidth - 2), '')}`
134
+ : rows[row] ?? '';
135
+ rows[row] = fill('surfaceHi', padEnd(content, contentWidth));
136
+ }
137
+ }
138
+ function messageText(content) {
139
+ if (typeof content === 'string')
140
+ return content;
141
+ if (Array.isArray(content))
142
+ return content.map(part => typeof part === 'string' ? part : part && typeof part === 'object' && 'text' in part
143
+ ? String(part.text) : '').filter(Boolean).join('\n');
144
+ return '';
145
+ }
146
+ /** Match in conversation order; never guess a fork point from visual row alone. */
147
+ export function persistedMessageIndex(marker, markers, messages) {
148
+ let matched = -1;
149
+ for (const shown of markers) {
150
+ if (!isMessage(shown))
151
+ continue;
152
+ let found = -1;
153
+ for (let i = matched + 1; i < messages.length; i++) {
154
+ const message = messages[i];
155
+ if (message?.role === shown.kind && messageText(message.content) === shown.meta?.messageText) {
156
+ found = i;
157
+ break;
158
+ }
159
+ }
160
+ if (found >= 0)
161
+ matched = found;
162
+ if (shown.id === marker.id)
163
+ return found >= 0 ? found : null;
164
+ }
165
+ return null;
166
+ }
167
+ export function openMessageActions(host, loop, marker, anchorY = null) {
168
+ const text = marker.meta?.messageText;
169
+ if (typeof text !== 'string')
170
+ return;
171
+ const sourceId = loop.memoryManager?.sessionId || getActiveSessionId();
172
+ const source = sourceId ? getSession(sourceId) : null;
173
+ const markers = host.surface?.transcript.flatten(host.surface.viewport.width).markers || [];
174
+ const index = source ? persistedMessageIndex(marker, markers, source.messages) : null;
175
+ const options = [
176
+ { label: 'Copy message', description: 'to clipboard', value: 'copy' },
177
+ ...(!host.busy && index !== null ? [{ label: 'Fork from here', description: 'fresh permissions', value: 'fork' }] : [])
178
+ ];
179
+ const layer = new MessageActionsLayer(options, (choice) => {
180
+ if (choice?.value === 'copy') {
181
+ host.notice = writeClipboardSync(text) ? 'Message copied to clipboard' : 'Clipboard unavailable on this terminal';
182
+ }
183
+ if (choice?.value === 'fork' && source && index !== null && !host.busy) {
184
+ const forked = loop.memoryManager?.sessionId === source.id && loop.memoryManager.forkSession
185
+ ? loop.memoryManager.forkSession(null, index)
186
+ : null;
187
+ if (!forked) {
188
+ host.notice = 'Could not fork this message; session was not changed';
189
+ }
190
+ else {
191
+ revokeAllAlways();
192
+ loop.resetApprovalScope?.();
193
+ const history = loop.memoryManager?.loadHistory?.() || forked.messages.filter(m => m.role !== 'system');
194
+ loop.messages = history;
195
+ loop.taskId = `cli_chat_${Date.now()}`;
196
+ loop.tokenTracker?.reset?.();
197
+ host.renderer?.renderSessionHistory?.(history, {
198
+ id: forked.id, title: forked.title, messagesCount: history.length
199
+ });
200
+ host.surface?.viewport?.toBottom?.();
201
+ host.notice = 'Forked from selected message. Permissions reset.';
202
+ }
203
+ }
204
+ host.scheduleDraw();
205
+ }, anchorY);
206
+ host.openLayer(layer);
207
+ }
208
+ /** Mouse selection for the small message menu; other dialogs retain their own input handling. */
209
+ export function handleMessageActionMenuMouse(layer, event) {
210
+ if (!layer.messageActions || !layer.actionLayout || !event.mouse)
211
+ return null;
212
+ const { x, y, width, count } = layer.actionLayout;
213
+ const { mouse } = event;
214
+ const index = mouse.y - (y + 1); // only the frame precedes the two action rows
215
+ if (mouse.x < x || mouse.x >= x + width || index < 0 || index >= count)
216
+ return 'handled';
217
+ layer.list?.moveTo(index);
218
+ if (isMouseMotion(event.sequence))
219
+ return 'handled';
220
+ return mouse.button === 0 && mouse.pressed ? layer.key({ name: 'enter' }) : 'handled';
221
+ }
@@ -0,0 +1,275 @@
1
+ import { getActiveSessionId, getSession, type SessionRecord } from '../sessionJournal.js';
2
+ import { revokeAllAlways } from '../approvalGrants.js';
3
+ import { writeClipboardSync } from './clipboardSync.js';
4
+ import { sidebarVisible, sessionMainWidth } from './sessionSidebar.js';
5
+ import { truncate, padEnd } from './text.js';
6
+ // @ts-expect-error Legacy overlay has no declaration yet.
7
+ import { Layer } from './overlay.js';
8
+ // @ts-expect-error Legacy theme has no declaration yet.
9
+ import { paint, bold, fill } from './theme.js';
10
+
11
+ export interface MessageMarker {
12
+ id: number;
13
+ kind: string;
14
+ row: number;
15
+ meta?: { messageText?: string } | null;
16
+ }
17
+
18
+ interface MousePoint { x: number; y: number }
19
+ interface MessageSurface {
20
+ width: number;
21
+ out: { rows?: number };
22
+ stage: { height: number; reserved: boolean };
23
+ viewport: { height: number; width: number; scrollTop: number; toBottom?: () => void };
24
+ transcript: { flatten(width: number): { rows: string[]; markers: MessageMarker[] } };
25
+ hoveredMessageFrameId?: number | null;
26
+ }
27
+
28
+ interface MessageHost {
29
+ surface: MessageSurface | null;
30
+ busy: boolean;
31
+ notice: string;
32
+ renderer?: { renderSessionHistory?: (messages: unknown[], info: object) => void };
33
+ openLayer(layer: unknown): unknown;
34
+ scheduleDraw(): void;
35
+ }
36
+
37
+ interface MessageAction {
38
+ label: string;
39
+ description: string;
40
+ value: 'copy' | 'fork';
41
+ }
42
+
43
+ /** Two actions need two rows; the generic searchable picker hides the second one. */
44
+ export class MessageActionsLayer extends Layer {
45
+ declare title: string;
46
+ declare footer: string;
47
+ declare width: number;
48
+ declare height: number;
49
+ declare cursor: null;
50
+ readonly messageActions = true;
51
+ actionLayout: { x: number; y: number; width: number; count: number } | null = null;
52
+ anchorY: number | null;
53
+ readonly items: MessageAction[];
54
+ readonly list: { filtered: MessageAction[]; selected: number; moveTo: (index: number) => void };
55
+ private readonly onPick: (choice: MessageAction | null) => void;
56
+ private settled = false;
57
+
58
+ constructor(items: MessageAction[], onPick: (choice: MessageAction | null) => void, anchorY: number | null = null) {
59
+ super({ title: 'Message Actions', width: 68, height: items.length + 2, footer: '↑↓ move · enter select · esc close' });
60
+ this.items = items;
61
+ this.onPick = onPick;
62
+ this.anchorY = anchorY;
63
+ this.list = {
64
+ filtered: items,
65
+ selected: 0,
66
+ moveTo: (index: number) => { this.list.selected = Math.max(0, Math.min(items.length - 1, index)); }
67
+ };
68
+ }
69
+
70
+ preferredHeight(): number { return this.items.length + 2; }
71
+
72
+ body(width: number): string[] {
73
+ return this.items.map((item, index) => {
74
+ const selected = index === this.list.selected;
75
+ const label = `${selected ? '▸' : ' '} ${item.label}`;
76
+ const description = ` ${item.description}`;
77
+ const room = Math.max(0, width - description.length);
78
+ const content = `${truncate(label, room, '…')}${description}`;
79
+ return selected ? paint('accent', bold(truncate(content, width, '…'))) : paint('ink', truncate(content, width, '…'));
80
+ });
81
+ }
82
+
83
+ key(event: { name: string }): string {
84
+ if (event.name === 'escape') return 'close';
85
+ if (event.name === 'up' || event.name === 'down') {
86
+ const delta = event.name === 'up' ? -1 : 1;
87
+ this.list.moveTo((this.list.selected + delta + this.items.length) % this.items.length);
88
+ return 'handled';
89
+ }
90
+ if (event.name === 'enter' || event.name === 'return') {
91
+ this.settled = true;
92
+ this.onPick(this.items[this.list.selected] ?? null);
93
+ return 'close';
94
+ }
95
+ return 'handled';
96
+ }
97
+
98
+ answer(): void {
99
+ if (!this.settled) { this.settled = true; this.onPick(null); }
100
+ }
101
+ }
102
+
103
+ interface MessageLoop {
104
+ memoryManager?: {
105
+ sessionId?: string | null;
106
+ session?: SessionRecord;
107
+ forkSession?: (title?: string | null, upToMessageIndex?: number | null) => SessionRecord | null;
108
+ loadHistory?: () => Array<{ role: string; content?: unknown }>;
109
+ };
110
+ messages?: Array<{ role: string; content?: unknown }>;
111
+ taskId?: string;
112
+ resetApprovalScope?: () => void;
113
+ tokenTracker?: { reset?: () => void };
114
+ }
115
+
116
+ export function isMouseMotion(sequence: string | undefined): boolean {
117
+ const code = Number(/^\x1b\[<(\d+);/.exec(sequence || '')?.[1]);
118
+ return Number.isFinite(code) && (code & 32) !== 0;
119
+ }
120
+
121
+ export function handleMessageMouse(
122
+ host: MessageHost, loop: MessageLoop, event: {
123
+ mouse?: MousePoint & { button?: number; pressed?: boolean };
124
+ sequence?: string;
125
+ }
126
+ ): boolean {
127
+ const mouse = event.mouse;
128
+ const surface = host.surface;
129
+ if (!mouse || !surface) return false;
130
+ const marker = messageAt(surface, mouse);
131
+ if (surface.hoveredMessageFrameId !== (marker?.id ?? null)) {
132
+ surface.hoveredMessageFrameId = marker?.id ?? null;
133
+ host.scheduleDraw();
134
+ }
135
+ // SGR motion carries bit 32; it must update hover without opening the menu.
136
+ if (isMouseMotion(event.sequence)) return true;
137
+ if (mouse.button === 0 && mouse.pressed && marker) openMessageActions(host, loop, marker, mouse.y);
138
+ return true;
139
+ }
140
+
141
+ const isMessage = (marker: MessageMarker): boolean =>
142
+ (marker.kind === 'user' || marker.kind === 'assistant')
143
+ && typeof marker.meta?.messageText === 'string';
144
+
145
+ /** Resolve screen coordinates against the painted viewport, including top padding. */
146
+ export function messageAt(surface: MessageSurface | null, point: MousePoint): MessageMarker | null {
147
+ if (!surface?.stage.reserved || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;
148
+ const mainWidth = sidebarVisible(surface.width) ? sessionMainWidth(surface.width) : surface.width;
149
+ if (point.x < 0 || point.x >= Math.min(mainWidth, surface.viewport.width)) return null;
150
+ const top = Math.max(0, (surface.out.rows || surface.stage.height) - surface.stage.height);
151
+ const viewRow = point.y - top;
152
+ if (viewRow < 0 || viewRow >= surface.viewport.height) return null;
153
+ const flat = surface.transcript.flatten(surface.viewport.width);
154
+ const visible = Math.max(0, Math.min(surface.viewport.height, flat.rows.length - surface.viewport.scrollTop));
155
+ const padding = surface.viewport.height - visible;
156
+ if (viewRow < padding) return null;
157
+ const row = surface.viewport.scrollTop + viewRow - padding;
158
+ for (let i = flat.markers.length - 1; i >= 0; i--) {
159
+ const marker = flat.markers[i];
160
+ if (!marker || marker.row > row) continue;
161
+ const next = flat.markers[i + 1];
162
+ if (isMessage(marker) && row < (next?.row ?? flat.rows.length)) return marker;
163
+ return null;
164
+ }
165
+ return null;
166
+ }
167
+
168
+ /** Highlight only the visible rows of the hovered message, without altering transcript data. */
169
+ export function markHoveredMessage(
170
+ rows: string[], surface: MessageSurface, contentWidth: number
171
+ ): void {
172
+ const id = surface.hoveredMessageFrameId;
173
+ if (!id) return;
174
+ const flat = surface.transcript.flatten(contentWidth);
175
+ const marker = flat.markers.find(item => item.id === id);
176
+ if (!marker || !isMessage(marker)) return;
177
+ const visible = Math.max(0, Math.min(rows.length, flat.rows.length - surface.viewport.scrollTop));
178
+ const padding = rows.length - visible;
179
+ const next = flat.markers[flat.markers.indexOf(marker) + 1];
180
+ const first = Math.max(marker.row, surface.viewport.scrollTop);
181
+ const last = Math.min(next?.row ?? flat.rows.length, surface.viewport.scrollTop + visible);
182
+ for (let transcriptRow = first; transcriptRow < last; transcriptRow++) {
183
+ const row = transcriptRow - surface.viewport.scrollTop + padding;
184
+ if (row < padding || row >= rows.length) continue;
185
+ const content = transcriptRow === marker.row
186
+ ? `${paint('accent', '▸')} ${truncate(rows[row] ?? '', Math.max(0, contentWidth - 2), '')}`
187
+ : rows[row] ?? '';
188
+ rows[row] = fill('surfaceHi', padEnd(content, contentWidth));
189
+ }
190
+ }
191
+
192
+ function messageText(content: unknown): string {
193
+ if (typeof content === 'string') return content;
194
+ if (Array.isArray(content)) return content.map(part =>
195
+ typeof part === 'string' ? part : part && typeof part === 'object' && 'text' in part
196
+ ? String(part.text) : '').filter(Boolean).join('\n');
197
+ return '';
198
+ }
199
+
200
+ /** Match in conversation order; never guess a fork point from visual row alone. */
201
+ export function persistedMessageIndex(
202
+ marker: MessageMarker, markers: MessageMarker[], messages: SessionRecord['messages']
203
+ ): number | null {
204
+ let matched = -1;
205
+ for (const shown of markers) {
206
+ if (!isMessage(shown)) continue;
207
+ let found = -1;
208
+ for (let i = matched + 1; i < messages.length; i++) {
209
+ const message = messages[i];
210
+ if (message?.role === shown.kind && messageText(message.content) === shown.meta?.messageText) {
211
+ found = i;
212
+ break;
213
+ }
214
+ }
215
+ if (found >= 0) matched = found;
216
+ if (shown.id === marker.id) return found >= 0 ? found : null;
217
+ }
218
+ return null;
219
+ }
220
+
221
+ export function openMessageActions(host: MessageHost, loop: MessageLoop, marker: MessageMarker, anchorY: number | null = null): void {
222
+ const text = marker.meta?.messageText;
223
+ if (typeof text !== 'string') return;
224
+ const sourceId = loop.memoryManager?.sessionId || getActiveSessionId();
225
+ const source = sourceId ? getSession(sourceId) : null;
226
+ const markers = host.surface?.transcript.flatten(host.surface.viewport.width).markers || [];
227
+ const index = source ? persistedMessageIndex(marker, markers, source.messages) : null;
228
+ const options: MessageAction[] = [
229
+ { label: 'Copy message', description: 'to clipboard', value: 'copy' },
230
+ ...(!host.busy && index !== null ? [{ label: 'Fork from here', description: 'fresh permissions', value: 'fork' } as const] : [])
231
+ ];
232
+ const layer = new MessageActionsLayer(options, (choice) => {
233
+ if (choice?.value === 'copy') {
234
+ host.notice = writeClipboardSync(text) ? 'Message copied to clipboard' : 'Clipboard unavailable on this terminal';
235
+ }
236
+ if (choice?.value === 'fork' && source && index !== null && !host.busy) {
237
+ const forked = loop.memoryManager?.sessionId === source.id && loop.memoryManager.forkSession
238
+ ? loop.memoryManager.forkSession(null, index)
239
+ : null;
240
+ if (!forked) {
241
+ host.notice = 'Could not fork this message; session was not changed';
242
+ } else {
243
+ revokeAllAlways();
244
+ loop.resetApprovalScope?.();
245
+ const history = loop.memoryManager?.loadHistory?.() || forked.messages.filter(m => m.role !== 'system');
246
+ loop.messages = history;
247
+ loop.taskId = `cli_chat_${Date.now()}`;
248
+ loop.tokenTracker?.reset?.();
249
+ host.renderer?.renderSessionHistory?.(history, {
250
+ id: forked.id, title: forked.title, messagesCount: history.length
251
+ });
252
+ host.surface?.viewport?.toBottom?.();
253
+ host.notice = 'Forked from selected message. Permissions reset.';
254
+ }
255
+ }
256
+ host.scheduleDraw();
257
+ }, anchorY);
258
+ host.openLayer(layer);
259
+ }
260
+
261
+ /** Mouse selection for the small message menu; other dialogs retain their own input handling. */
262
+ export function handleMessageActionMenuMouse(
263
+ layer: { messageActions?: boolean; actionLayout?: { x: number; y: number; width: number; count: number };
264
+ list?: { moveTo(index: number): unknown }; key(event: { name: string }): string | null },
265
+ event: { mouse?: MousePoint & { button?: number; pressed?: boolean }; sequence?: string }
266
+ ): string | null {
267
+ if (!layer.messageActions || !layer.actionLayout || !event.mouse) return null;
268
+ const { x, y, width, count } = layer.actionLayout;
269
+ const { mouse } = event;
270
+ const index = mouse.y - (y + 1); // only the frame precedes the two action rows
271
+ if (mouse.x < x || mouse.x >= x + width || index < 0 || index >= count) return 'handled';
272
+ layer.list?.moveTo(index);
273
+ if (isMouseMotion(event.sequence)) return 'handled';
274
+ return mouse.button === 0 && mouse.pressed ? layer.key({ name: 'enter' }) : 'handled';
275
+ }
@@ -131,7 +131,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
131
131
  });
132
132
  prompt.openLayer(layer);
133
133
  });
134
- const notifyPromptAndClean = (providerId, modelId) => {
134
+ const notifyPrompt = (providerId, modelId) => {
135
135
  if (typeof prompt.updateModel === 'function') {
136
136
  prompt.updateModel(providerId, modelId);
137
137
  }
@@ -140,29 +140,14 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
140
140
  if (typeof prompt.scheduleDraw === 'function')
141
141
  prompt.scheduleDraw();
142
142
  }
143
- if (prompt.editor && typeof prompt.editor.clear === 'function') {
144
- prompt.editor.clear();
145
- if (typeof prompt.scheduleDraw === 'function')
146
- prompt.scheduleDraw();
147
- }
148
143
  };
149
144
  if (!picked || !picked.value) {
150
- if (prompt.editor && typeof prompt.editor.clear === 'function') {
151
- prompt.editor.clear();
152
- if (typeof prompt.scheduleDraw === 'function')
153
- prompt.scheduleDraw();
154
- }
155
145
  return 'Cancelled. Model was not changed.';
156
146
  }
157
147
  const target = picked.value;
158
148
  // Case 1: ACP Peer Agent or Antigravity
159
149
  if (target.type === 'acp') {
160
150
  if (!target.installed) {
161
- if (prompt.editor && typeof prompt.editor.clear === 'function') {
162
- prompt.editor.clear();
163
- if (typeof prompt.scheduleDraw === 'function')
164
- prompt.scheduleDraw();
165
- }
166
151
  return (`⚠️ Notice: "${target.providerLabel}" is not installed on this machine.\n` +
167
152
  `Setup: ${target.setupInstruction || 'Install the CLI binary.'}\n\n` +
168
153
  `Model was not changed.`);
@@ -178,7 +163,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
178
163
  options.loop.updateTierLimits();
179
164
  }
180
165
  }
181
- notifyPromptAndClean(target.providerId, target.modelId);
166
+ notifyPrompt(target.providerId, target.modelId);
182
167
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
183
168
  }
184
169
  // Case 2: BYOK Provider (Cloud or Local API)
@@ -209,7 +194,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
209
194
  options.loop.updateTierLimits();
210
195
  }
211
196
  }
212
- notifyPromptAndClean(target.providerId, target.modelId);
197
+ notifyPrompt(target.providerId, target.modelId);
213
198
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
214
199
  }
215
200
  // Key is required: open modal input dialog (InputLayer)
@@ -228,11 +213,6 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
228
213
  prompt.openLayer(layer);
229
214
  });
230
215
  if (!enteredKey || !enteredKey.trim()) {
231
- if (prompt.editor && typeof prompt.editor.clear === 'function') {
232
- prompt.editor.clear();
233
- if (typeof prompt.scheduleDraw === 'function')
234
- prompt.scheduleDraw();
235
- }
236
216
  return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
237
217
  }
238
218
  const cleanKey = enteredKey.trim();
@@ -249,6 +229,6 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
249
229
  options.loop.updateTierLimits();
250
230
  }
251
231
  }
252
- notifyPromptAndClean(target.providerId, target.modelId);
232
+ notifyPrompt(target.providerId, target.modelId);
253
233
  return `Saved API key. Now using ${target.providerLabel} / ${target.modelId}.`;
254
234
  }
@@ -187,24 +187,16 @@ export async function runInteractiveModelPicker(
187
187
  prompt.openLayer(layer);
188
188
  });
189
189
 
190
- const notifyPromptAndClean = (providerId: string, modelId: string) => {
190
+ const notifyPrompt = (providerId: string, modelId: string) => {
191
191
  if (typeof (prompt as any).updateModel === 'function') {
192
192
  (prompt as any).updateModel(providerId, modelId);
193
193
  } else if ((prompt as any).renderer?.status) {
194
194
  (prompt as any).renderer.status.setSession({ provider: providerId, model: modelId });
195
195
  if (typeof (prompt as any).scheduleDraw === 'function') (prompt as any).scheduleDraw();
196
196
  }
197
- if ((prompt as any).editor && typeof (prompt as any).editor.clear === 'function') {
198
- (prompt as any).editor.clear();
199
- if (typeof (prompt as any).scheduleDraw === 'function') (prompt as any).scheduleDraw();
200
- }
201
197
  };
202
198
 
203
199
  if (!picked || !picked.value) {
204
- if ((prompt as any).editor && typeof (prompt as any).editor.clear === 'function') {
205
- (prompt as any).editor.clear();
206
- if (typeof (prompt as any).scheduleDraw === 'function') (prompt as any).scheduleDraw();
207
- }
208
200
  return 'Cancelled. Model was not changed.';
209
201
  }
210
202
 
@@ -213,10 +205,6 @@ export async function runInteractiveModelPicker(
213
205
  // Case 1: ACP Peer Agent or Antigravity
214
206
  if (target.type === 'acp') {
215
207
  if (!target.installed) {
216
- if ((prompt as any).editor && typeof (prompt as any).editor.clear === 'function') {
217
- (prompt as any).editor.clear();
218
- if (typeof (prompt as any).scheduleDraw === 'function') (prompt as any).scheduleDraw();
219
- }
220
208
  return (
221
209
  `⚠️ Notice: "${target.providerLabel}" is not installed on this machine.\n` +
222
210
  `Setup: ${target.setupInstruction || 'Install the CLI binary.'}\n\n` +
@@ -236,7 +224,7 @@ export async function runInteractiveModelPicker(
236
224
  options.loop.updateTierLimits();
237
225
  }
238
226
  }
239
- notifyPromptAndClean(target.providerId, target.modelId);
227
+ notifyPrompt(target.providerId, target.modelId);
240
228
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
241
229
  }
242
230
 
@@ -268,7 +256,7 @@ export async function runInteractiveModelPicker(
268
256
  options.loop.updateTierLimits();
269
257
  }
270
258
  }
271
- notifyPromptAndClean(target.providerId, target.modelId);
259
+ notifyPrompt(target.providerId, target.modelId);
272
260
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
273
261
  }
274
262
 
@@ -289,10 +277,6 @@ export async function runInteractiveModelPicker(
289
277
  });
290
278
 
291
279
  if (!enteredKey || !enteredKey.trim()) {
292
- if ((prompt as any).editor && typeof (prompt as any).editor.clear === 'function') {
293
- (prompt as any).editor.clear();
294
- if (typeof (prompt as any).scheduleDraw === 'function') (prompt as any).scheduleDraw();
295
- }
296
280
  return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
297
281
  }
298
282
 
@@ -313,6 +297,6 @@ export async function runInteractiveModelPicker(
313
297
  }
314
298
  }
315
299
 
316
- notifyPromptAndClean(target.providerId, target.modelId);
300
+ notifyPrompt(target.providerId, target.modelId);
317
301
  return `Saved API key. Now using ${target.providerLabel} / ${target.modelId}.`;
318
302
  }
@@ -0,0 +1,6 @@
1
+ /** Terminal-wide motion reports allow hover feedback; opt out for native text selection. */
2
+ export function mouseHoverTracking(enabled, env = process.env) {
3
+ if (String(env.CAUSYNE_MOUSE_HOVER ?? '1') === '0')
4
+ return '';
5
+ return enabled ? '\x1b[?1003h' : '\x1b[?1003l';
6
+ }
@@ -0,0 +1,5 @@
1
+ /** Terminal-wide motion reports allow hover feedback; opt out for native text selection. */
2
+ export function mouseHoverTracking(enabled: boolean, env: NodeJS.ProcessEnv = process.env): string {
3
+ if (String(env.CAUSYNE_MOUSE_HOVER ?? '1') === '0') return '';
4
+ return enabled ? '\x1b[?1003h' : '\x1b[?1003l';
5
+ }