@causyne/agent 1.20.31 → 1.20.32

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.
@@ -1,8 +1,18 @@
1
- import { getActiveSessionId, getSession, type SessionRecord } from '../sessionJournal.js';
1
+ import {
2
+ getActiveSessionId,
3
+ getSession,
4
+ listSessions,
5
+ saveSessionMessages,
6
+ type SessionRecord
7
+ } from '../sessionJournal.js';
2
8
  import { revokeAllAlways } from '../approvalGrants.js';
9
+ // @ts-expect-error Legacy checkpoints module has no TypeScript declarations yet.
10
+ import { undoLast } from '../checkpoints.js';
3
11
  import { writeClipboardSync } from './clipboardSync.js';
12
+ import { registerStageConsoleGuard, setTransientNotice } from './consoleGuard.js';
13
+ import { detectLinkAtPoint, openDetectedLink } from './smartLinkClick.js';
4
14
  import { sidebarVisible, sessionMainWidth } from './sessionSidebar.js';
5
- import { truncate, padEnd } from './text.js';
15
+ import { stripAnsi, truncate, padEnd } from './text.js';
6
16
  // @ts-expect-error Legacy overlay has no declaration yet.
7
17
  import { Layer } from './overlay.js';
8
18
  // @ts-expect-error Legacy theme has no declaration yet.
@@ -30,18 +40,23 @@ interface MessageHost {
30
40
  surface: MessageSurface | null;
31
41
  busy: boolean;
32
42
  notice: string;
33
- renderer?: { renderSessionHistory?: (messages: unknown[], info: object) => void };
43
+ renderer?: {
44
+ renderSessionHistory?: (messages: unknown[], info: object) => void;
45
+ setSessionInfo?: (info: object) => void;
46
+ };
47
+ interrupt?: () => void;
48
+ setText?: (value: string) => void;
34
49
  openLayer(layer: unknown): unknown;
35
50
  scheduleDraw(): void;
36
51
  }
37
52
 
38
- interface MessageAction {
53
+ export interface MessageAction {
39
54
  label: string;
40
55
  description: string;
41
- value: 'copy' | 'fork';
56
+ value: 'copy' | 'fork' | 'revert' | string;
42
57
  }
43
58
 
44
- /** Two actions need two rows; the generic searchable picker hides the second one. */
59
+ /** Multi-action message menu overlay supporting Copy, Fork, and Revert. */
45
60
  export class MessageActionsLayer extends Layer {
46
61
  declare title: string;
47
62
  declare footer: string;
@@ -52,7 +67,7 @@ export class MessageActionsLayer extends Layer {
52
67
  actionLayout: { x: number; y: number; width: number; count: number } | null = null;
53
68
  anchorY: number | null;
54
69
  readonly items: MessageAction[];
55
- readonly list: { filtered: MessageAction[]; selected: number; moveTo: (index: number) => void };
70
+ readonly list: { filtered: MessageAction[]; selected: number; moveTo: (index: number, rows?: number) => void };
56
71
  private readonly onPick: (choice: MessageAction | null) => void;
57
72
  private settled = false;
58
73
 
@@ -81,8 +96,12 @@ export class MessageActionsLayer extends Layer {
81
96
  });
82
97
  }
83
98
 
84
- key(event: { name: string }): string {
85
- if (event.name === 'escape') return 'close';
99
+ key(event: { name: string; ctrl?: boolean; alt?: boolean }): string {
100
+ if (event.name === 'escape') {
101
+ this.settled = true;
102
+ this.onPick(null);
103
+ return 'close';
104
+ }
86
105
  if (event.name === 'up' || event.name === 'down') {
87
106
  const delta = event.name === 'up' ? -1 : 1;
88
107
  this.list.moveTo((this.list.selected + delta + this.items.length) % this.items.length);
@@ -93,8 +112,7 @@ export class MessageActionsLayer extends Layer {
93
112
  this.onPick(this.items[this.list.selected] ?? null);
94
113
  return 'close';
95
114
  }
96
- const e = event as { name: string; ctrl?: boolean; alt?: boolean };
97
- if (!e.ctrl && !e.alt && (e.name.length === 1 || e.name === 'space' || e.name === 'backspace')) {
115
+ if (!event.ctrl && !event.alt && (event.name.length === 1 || event.name === 'space' || event.name === 'backspace')) {
98
116
  this.settled = true;
99
117
  this.onPick(null);
100
118
  return 'dismiss';
@@ -113,9 +131,11 @@ interface MessageLoop {
113
131
  session?: SessionRecord;
114
132
  forkSession?: (title?: string | null, upToMessageIndex?: number | null) => SessionRecord | null;
115
133
  loadHistory?: () => Array<{ role: string; content?: unknown }>;
134
+ saveHistory?: (messages: Array<{ role: string; content?: unknown }>) => void;
116
135
  };
117
136
  messages?: Array<{ role: string; content?: unknown }>;
118
137
  taskId?: string;
138
+ abort?: () => void;
119
139
  resetApprovalScope?: () => void;
120
140
  tokenTracker?: { reset?: () => void };
121
141
  }
@@ -129,6 +149,9 @@ export function handleMessageMouse(
129
149
  host: MessageHost, loop: MessageLoop, event: {
130
150
  mouse?: MousePoint & { button?: number; pressed?: boolean };
131
151
  sequence?: string;
152
+ ctrl?: boolean;
153
+ alt?: boolean;
154
+ shift?: boolean;
132
155
  }
133
156
  ): boolean {
134
157
  const mouse = event.mouse;
@@ -141,7 +164,26 @@ export function handleMessageMouse(
141
164
  }
142
165
  // SGR motion carries bit 32; it must update hover without opening the menu.
143
166
  if (isMouseMotion(event.sequence)) return true;
144
- if (mouse.button === 0 && mouse.pressed && marker) openMessageActions(host, loop, marker, mouse.y);
167
+
168
+ if (mouse.button === 0 && mouse.pressed) {
169
+ // Smart link detection: if the user clicked (or Cmd/Ctrl+Clicked) on a URL or OSC 8 hyperlink,
170
+ // open the link directly in the system browser instead of popping up the Message Actions modal.
171
+ const hitLink = detectLinkAtPoint(surface, mouse, marker);
172
+ if (hitLink) {
173
+ openDetectedLink(hitLink.url);
174
+ writeClipboardSync(hitLink.url);
175
+ surface.hoveredMessageFrameId = null;
176
+ setTransientNotice(host, `Opened ${hitLink.url}`);
177
+ return true;
178
+ }
179
+ // Never open Message Actions on a modifier click (Ctrl/Alt/Shift+Click) that missed a link by 1 cell.
180
+ if (event.ctrl || event.alt || event.shift) {
181
+ return true;
182
+ }
183
+ if (marker) {
184
+ openMessageActions(host, loop, marker, mouse.y);
185
+ }
186
+ }
145
187
  return true;
146
188
  }
147
189
 
@@ -173,10 +215,11 @@ export function messageAt(surface: MessageSurface | null, point: MousePoint): Me
173
215
  return null;
174
216
  }
175
217
 
176
- /** Highlight only the visible rows of the hovered message, without altering transcript data. */
218
+ /** Highlight only the visible non-empty rows of the hovered message, without altering transcript data. */
177
219
  export function markHoveredMessage(
178
220
  rows: string[], surface: MessageSurface, contentWidth: number
179
221
  ): void {
222
+ registerStageConsoleGuard(surface);
180
223
  const id = surface.hoveredMessageFrameId;
181
224
  if (!id) return;
182
225
  const flat = surface.transcript.flatten(contentWidth);
@@ -185,14 +228,32 @@ export function markHoveredMessage(
185
228
  const visible = Math.max(0, Math.min(rows.length, flat.rows.length - surface.viewport.scrollTop));
186
229
  const padding = rows.length - visible;
187
230
  const next = flat.markers[flat.markers.indexOf(marker) + 1];
188
- const first = Math.max(marker.row, surface.viewport.scrollTop);
189
- const last = Math.min(next?.row ?? flat.rows.length, surface.viewport.scrollTop + visible);
231
+ const rawStart = marker.row;
232
+ const rawEnd = next?.row ?? flat.rows.length;
233
+
234
+ // Skip leading and trailing blank separator lines inside the message frame
235
+ // so we never paint a stray '▸' on an empty spacing row above '▸ Causyne'.
236
+ let firstContentRow = rawStart;
237
+ while (firstContentRow < rawEnd && stripAnsi(flat.rows[firstContentRow] ?? '').trim() === '') {
238
+ firstContentRow++;
239
+ }
240
+ let lastContentRow = rawEnd - 1;
241
+ while (lastContentRow > firstContentRow && stripAnsi(flat.rows[lastContentRow] ?? '').trim() === '') {
242
+ lastContentRow--;
243
+ }
244
+ if (firstContentRow >= rawEnd) return;
245
+
246
+ const first = Math.max(firstContentRow, surface.viewport.scrollTop);
247
+ const last = Math.min(lastContentRow + 1, surface.viewport.scrollTop + visible);
190
248
  for (let transcriptRow = first; transcriptRow < last; transcriptRow++) {
191
249
  const row = transcriptRow - surface.viewport.scrollTop + padding;
192
250
  if (row < padding || row >= rows.length) continue;
193
- const content = transcriptRow === marker.row
194
- ? `${paint('accent', '▸')} ${truncate(rows[row] ?? '', Math.max(0, contentWidth - 2), '')}`
195
- : rows[row] ?? '';
251
+ const existingRow = rows[row] ?? '';
252
+ const plainTrimmed = stripAnsi(existingRow).trimStart();
253
+ const alreadyHasMarker = plainTrimmed.startsWith('▸') || plainTrimmed.startsWith('│');
254
+ const content = transcriptRow === firstContentRow && !alreadyHasMarker
255
+ ? `${paint('accent', '▸')} ${truncate(existingRow, Math.max(0, contentWidth - 2), '')}`
256
+ : existingRow;
196
257
  rows[row] = fill('surfaceHi', padEnd(content, contentWidth));
197
258
  }
198
259
  }
@@ -205,6 +266,19 @@ function messageText(content: unknown): string {
205
266
  return '';
206
267
  }
207
268
 
269
+ function messagesMatch(persistedContent: unknown, shownText: string | undefined): boolean {
270
+ if (typeof shownText !== 'string') return false;
271
+ const persisted = messageText(persistedContent);
272
+ if (persisted === shownText) return true;
273
+ const cleanPersisted = persisted.trim();
274
+ const cleanShown = shownText.trim();
275
+ if (!cleanShown) return false;
276
+ if (cleanPersisted === cleanShown) return true;
277
+ // Handle messages where an attachment system notification was appended on save
278
+ if (cleanPersisted.startsWith(cleanShown)) return true;
279
+ return false;
280
+ }
281
+
208
282
  /** Match in conversation order; never guess a fork point from visual row alone. */
209
283
  export function persistedMessageIndex(
210
284
  marker: MessageMarker, markers: MessageMarker[], messages: SessionRecord['messages']
@@ -215,7 +289,7 @@ export function persistedMessageIndex(
215
289
  let found = -1;
216
290
  for (let i = matched + 1; i < messages.length; i++) {
217
291
  const message = messages[i];
218
- if (message?.role === shown.kind && messageText(message.content) === shown.meta?.messageText) {
292
+ if (message?.role === shown.kind && messagesMatch(message.content, shown.meta?.messageText)) {
219
293
  found = i;
220
294
  break;
221
295
  }
@@ -226,43 +300,145 @@ export function persistedMessageIndex(
226
300
  return null;
227
301
  }
228
302
 
303
+ function computeNextForkTitle(sourceTitle: string | undefined): string {
304
+ const cleanBase = (sourceTitle && sourceTitle !== 'Untitled' ? sourceTitle : 'Conversation')
305
+ .replace(/\s*\(fork #\d+\)$/i, '')
306
+ .trim();
307
+ let maxForkNum = 0;
308
+ try {
309
+ const existing = listSessions();
310
+ const escaped = cleanBase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
311
+ const forkRe = new RegExp(`^${escaped}\\s*\\(fork #(\\d+)\\)$`, 'i');
312
+ for (const s of existing) {
313
+ const m = forkRe.exec((s.title || '').trim());
314
+ if (m?.[1]) {
315
+ const n = Number(m[1]);
316
+ if (Number.isFinite(n) && n > maxForkNum) maxForkNum = n;
317
+ }
318
+ }
319
+ } catch {
320
+ // Ignore session listing failures
321
+ }
322
+ return `${cleanBase} (fork #${maxForkNum + 1})`;
323
+ }
324
+
325
+ function syncInFlightMessagesToSession(loop: MessageLoop, sourceId: string | null): SessionRecord | null {
326
+ if (!sourceId) return null;
327
+ let source = getSession(sourceId);
328
+ const inMemory = Array.isArray(loop.messages)
329
+ ? loop.messages.filter(m => m && m.role !== 'system')
330
+ : [];
331
+ const onDiskCount = source?.messages?.length ?? 0;
332
+
333
+ if (inMemory.length > onDiskCount) {
334
+ try {
335
+ if (typeof loop.memoryManager?.saveHistory === 'function') {
336
+ loop.memoryManager.saveHistory(loop.messages!);
337
+ } else {
338
+ saveSessionMessages(sourceId, inMemory as SessionRecord['messages']);
339
+ }
340
+ source = getSession(sourceId);
341
+ } catch {
342
+ // Keep existing source record if disk sync fails
343
+ }
344
+ }
345
+ return source;
346
+ }
347
+
229
348
  export function openMessageActions(host: MessageHost, loop: MessageLoop, marker: MessageMarker, anchorY: number | null = null): void {
230
349
  const text = marker.meta?.messageText;
231
350
  if (typeof text !== 'string') return;
232
351
  const sourceId = loop.memoryManager?.sessionId || getActiveSessionId();
233
- const source = sourceId ? getSession(sourceId) : null;
352
+ const source = syncInFlightMessagesToSession(loop, sourceId);
234
353
  const markers = host.surface?.transcript.flatten(host.surface.viewport.width).markers || [];
235
354
  const index = source ? persistedMessageIndex(marker, markers, source.messages) : null;
355
+
356
+ const canModifySession = Boolean(source && index !== null);
236
357
  const options: MessageAction[] = [
237
358
  { label: 'Copy message', description: 'to clipboard', value: 'copy' },
238
- ...(!host.busy && index !== null ? [{ label: 'Fork from here', description: 'fresh permissions', value: 'fork' } as const] : [])
359
+ ...(canModifySession
360
+ ? [
361
+ { label: 'Fork from here', description: 'create a new session · fresh permissions', value: 'fork' } as const,
362
+ { label: 'Revert to here', description: 'undo messages and file changes', value: 'revert' } as const
363
+ ]
364
+ : [])
239
365
  ];
366
+
240
367
  const layer = new MessageActionsLayer(options, (choice) => {
241
- if (choice?.value === 'copy') {
242
- host.notice = writeClipboardSync(text) ? 'Message copied to clipboard' : 'Clipboard unavailable on this terminal';
368
+ if (host.surface) {
369
+ host.surface.hoveredMessageFrameId = null;
370
+ }
371
+ if (!choice) {
372
+ host.scheduleDraw();
373
+ return;
374
+ }
375
+
376
+ if (choice.value === 'copy') {
377
+ const ok = writeClipboardSync(text);
378
+ setTransientNotice(host, ok ? 'Message copied to clipboard' : 'Clipboard unavailable on this terminal');
379
+ return;
380
+ }
381
+
382
+ if (choice.value === 'fork' && source && index !== null) {
383
+ if (host.busy) {
384
+ host.interrupt?.();
385
+ loop.abort?.();
386
+ syncInFlightMessagesToSession(loop, source.id);
243
387
  }
244
- if (choice?.value === 'fork' && source && index !== null && !host.busy) {
245
- const forked = loop.memoryManager?.sessionId === source.id && loop.memoryManager.forkSession
246
- ? loop.memoryManager.forkSession(null, index)
247
- : null;
248
- if (!forked) {
249
- host.notice = 'Could not fork this message; session was not changed';
250
- } else {
251
- revokeAllAlways();
252
- loop.resetApprovalScope?.();
253
- const history = loop.memoryManager?.loadHistory?.() || forked.messages.filter(m => m.role !== 'system');
254
- loop.messages = history;
255
- loop.taskId = `cli_chat_${Date.now()}`;
256
- loop.tokenTracker?.reset?.();
257
- host.renderer?.renderSessionHistory?.(history, {
258
- id: forked.id, title: forked.title, messagesCount: history.length
259
- });
260
- host.surface?.viewport?.toBottom?.();
261
- host.notice = 'Forked from selected message. Permissions reset.';
262
- }
388
+ const forkTitle = computeNextForkTitle(source.title);
389
+ const forked = loop.memoryManager?.sessionId === source.id && loop.memoryManager.forkSession
390
+ ? loop.memoryManager.forkSession(forkTitle, index)
391
+ : null;
392
+ if (!forked) {
393
+ setTransientNotice(host, 'Could not fork this message; session was not changed');
394
+ } else {
395
+ revokeAllAlways();
396
+ loop.resetApprovalScope?.();
397
+ const history = loop.memoryManager?.loadHistory?.() || forked.messages.filter(m => m.role !== 'system');
398
+ loop.messages = history;
399
+ loop.taskId = `cli_chat_${Date.now()}`;
400
+ loop.tokenTracker?.reset?.();
401
+ const info = { id: forked.id, title: forked.title, messagesCount: history.length };
402
+ host.renderer?.setSessionInfo?.(info);
403
+ host.renderer?.renderSessionHistory?.(history, info);
404
+ host.surface?.viewport?.toBottom?.();
405
+ setTransientNotice(host, `Forked into "${forked.title}". Permissions reset.`);
263
406
  }
264
- host.scheduleDraw();
265
- }, anchorY);
407
+ return;
408
+ }
409
+
410
+ if (choice.value === 'revert' && source && index !== null) {
411
+ if (host.busy) {
412
+ host.interrupt?.();
413
+ loop.abort?.();
414
+ }
415
+ try {
416
+ undoLast({ dryRun: false, scope: 'code' });
417
+ } catch {
418
+ // Checkpoints are optional if no files were modified in the reverted turn.
419
+ }
420
+ const latestSource = getSession(source.id) || source;
421
+ const keptMessages = latestSource.messages.slice(0, index);
422
+ saveSessionMessages(source.id, keptMessages);
423
+ if (loop.memoryManager?.session && loop.memoryManager.session.id === source.id) {
424
+ loop.memoryManager.session.messages = keptMessages;
425
+ }
426
+ const history = keptMessages.filter(m => m.role !== 'system');
427
+ loop.messages = history;
428
+ loop.taskId = `cli_chat_${Date.now()}`;
429
+ const info = { id: latestSource.id, title: latestSource.title, messagesCount: history.length };
430
+ host.renderer?.setSessionInfo?.(info);
431
+ host.renderer?.renderSessionHistory?.(history, info);
432
+ host.surface?.viewport?.toBottom?.();
433
+ if (marker.kind === 'user' && text) {
434
+ host.setText?.(text);
435
+ }
436
+ setTransientNotice(host, 'Reverted messages and file changes to selected point.');
437
+ return;
438
+ }
439
+
440
+ host.scheduleDraw();
441
+ }, anchorY);
266
442
  host.openLayer(layer);
267
443
  }
268
444
 
@@ -275,7 +451,7 @@ export function handleMessageActionMenuMouse(
275
451
  if (!layer.messageActions || !layer.actionLayout || !event.mouse) return null;
276
452
  const { x, y, width, count } = layer.actionLayout;
277
453
  const { mouse } = event;
278
- const index = mouse.y - (y + 1); // only the frame precedes the two action rows
454
+ const index = mouse.y - (y + 1); // only the frame precedes the action rows
279
455
  if (mouse.x < x || mouse.x >= x + width || index < 0 || index >= count) {
280
456
  return mouse.button === 0 && mouse.pressed ? 'close' : 'handled';
281
457
  }
@@ -1,9 +1,13 @@
1
+ import { setStageConsoleGuardActive } from './consoleGuard.js';
1
2
  /**
2
3
  * Terminal-wide motion reports (?1003h) allow hover feedback, but hijack native mouse selection.
3
4
  * Disabled by default so users can freely select, drag, and copy text in the terminal.
4
5
  * Opt-in via CAUSYNE_MOUSE_HOVER=1.
5
6
  */
6
7
  export function mouseHoverTracking(enabled, env = process.env) {
8
+ if (env === process.env) {
9
+ setStageConsoleGuardActive(enabled);
10
+ }
7
11
  if (String(env.CAUSYNE_MOUSE_HOVER ?? '0') !== '1')
8
12
  return '';
9
13
  return enabled ? '\x1b[?1003h' : '\x1b[?1003l';
@@ -1,9 +1,14 @@
1
+ import { setStageConsoleGuardActive } from './consoleGuard.js';
2
+
1
3
  /**
2
4
  * Terminal-wide motion reports (?1003h) allow hover feedback, but hijack native mouse selection.
3
5
  * Disabled by default so users can freely select, drag, and copy text in the terminal.
4
6
  * Opt-in via CAUSYNE_MOUSE_HOVER=1.
5
7
  */
6
8
  export function mouseHoverTracking(enabled: boolean, env: NodeJS.ProcessEnv = process.env): string {
9
+ if (env === process.env) {
10
+ setStageConsoleGuardActive(enabled);
11
+ }
7
12
  if (String(env.CAUSYNE_MOUSE_HOVER ?? '0') !== '1') return '';
8
13
  return enabled ? '\x1b[?1003h' : '\x1b[?1003l';
9
14
  }