@causyne/agent 1.20.0 → 1.20.7

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 (130) hide show
  1. package/README.md +13 -9
  2. package/SECURITY.md +1 -4
  3. package/package.json +1 -1
  4. package/src/acp/client.js +176 -26
  5. package/src/acp/client.ts +167 -25
  6. package/src/acp/protocol.js +116 -0
  7. package/src/acp/protocol.ts +163 -0
  8. package/src/acp/server.js +5 -6
  9. package/src/acp/server.ts +4 -6
  10. package/src/agentLoop.d.ts +1 -0
  11. package/src/agentLoop.js +681 -245
  12. package/src/agentLoop.ts +708 -262
  13. package/src/agentPolicy.js +9 -0
  14. package/src/agentPolicy.ts +9 -0
  15. package/src/approvalPolicy.js +55 -0
  16. package/src/approvalPolicy.ts +66 -0
  17. package/src/browser/browserRuntime.js +217 -14
  18. package/src/browser/browserRuntime.ts +255 -14
  19. package/src/browser/causyneBrowser.js +1215 -68
  20. package/src/browser/causyneBrowser.ts +1340 -72
  21. package/src/cliMode.js +52 -29
  22. package/src/commands.js +141 -17
  23. package/src/config.js +22 -12
  24. package/src/continuum/ui/continuumPicker.js +18 -1
  25. package/src/continuum/ui/continuumPicker.ts +19 -1
  26. package/src/dynamicCatalogue.js +87 -20
  27. package/src/dynamicCatalogue.ts +85 -15
  28. package/src/launchIntent.js +40 -0
  29. package/src/launchIntent.ts +49 -0
  30. package/src/memoryManager.js +26 -2
  31. package/src/modelCatalogue.js +2 -0
  32. package/src/planCache.js +320 -11
  33. package/src/planCache.ts +402 -13
  34. package/src/providers/acp.js +173 -18
  35. package/src/providers/acp.ts +169 -19
  36. package/src/providers/antigravity.d.ts +5 -1
  37. package/src/providers/antigravity.js +674 -34
  38. package/src/providers/antigravity.ts +707 -35
  39. package/src/providers/base.d.ts +10 -0
  40. package/src/providers/factory.js +2 -0
  41. package/src/providers/pi.js +161 -0
  42. package/src/providers/pi.ts +148 -0
  43. package/src/provisioning/capabilityProvisioner.js +17 -0
  44. package/src/provisioning/capabilityTools.js +1 -1
  45. package/src/sandbox.js +30 -39
  46. package/src/sessionJournal.js +53 -10
  47. package/src/sessionJournal.ts +64 -10
  48. package/src/taskShape.js +9 -9
  49. package/src/taskShape.ts +9 -9
  50. package/src/timeMachine.js +124 -0
  51. package/src/timeMachine.ts +141 -0
  52. package/src/toolPacks.js +4 -10
  53. package/src/tools/archive.js +196 -59
  54. package/src/tools/archive.ts +220 -0
  55. package/src/tools/browserAutomator.js +78 -9
  56. package/src/tools/browserAutomator.ts +90 -9
  57. package/src/tools/desktopOpen.js +114 -31
  58. package/src/tools/desktopOpen.ts +144 -0
  59. package/src/tools/gitExec.js +5 -3
  60. package/src/tools/nativeEngine.js +4 -3
  61. package/src/tools/nativeEngine.ts +5 -3
  62. package/src/tools/openSourceToolProvisioner.js +5 -4
  63. package/src/tools/openSourceToolProvisioner.ts +5 -4
  64. package/src/tools/registry.js +3 -0
  65. package/src/tools/screenshot.js +55 -71
  66. package/src/tools/screenshot.ts +70 -0
  67. package/src/tools/sysRun.js +284 -117
  68. package/src/tools/sysRun.ts +347 -0
  69. package/src/tools/toolSelfRepair.js +109 -2
  70. package/src/tools/toolSelfRepair.ts +100 -2
  71. package/src/tools/updatePlan.js +49 -1
  72. package/src/tools/updatePlan.ts +43 -1
  73. package/src/tools/viewImage.js +93 -78
  74. package/src/tools/viewImage.ts +116 -0
  75. package/src/tools/webFetch.js +20 -6
  76. package/src/tools/webFetch.ts +26 -6
  77. package/src/tui/activityLayout.js +9 -0
  78. package/src/tui/activityLayout.ts +10 -0
  79. package/src/tui/block.d.ts +1 -0
  80. package/src/tui/chatRenderer.d.ts +23 -0
  81. package/src/tui/chatRenderer.js +49 -49
  82. package/src/tui/clipboardSync.js +28 -1
  83. package/src/tui/clipboardSync.ts +26 -1
  84. package/src/tui/codeProgress.js +299 -0
  85. package/src/tui/codeProgress.ts +304 -0
  86. package/src/tui/codeStreamRenderer.js +132 -0
  87. package/src/tui/codeStreamRenderer.ts +141 -0
  88. package/src/tui/commandPresentation.js +11 -0
  89. package/src/tui/commandPresentation.ts +18 -0
  90. package/src/tui/completion.js +45 -13
  91. package/src/tui/composerControls.js +131 -0
  92. package/src/tui/composerControls.ts +184 -0
  93. package/src/tui/diff.d.ts +2 -0
  94. package/src/tui/home.js +4 -2
  95. package/src/tui/homeTransition.js +21 -0
  96. package/src/tui/homeTransition.ts +27 -0
  97. package/src/tui/homeView.js +62 -0
  98. package/src/tui/homeView.ts +91 -0
  99. package/src/tui/layout.js +46 -0
  100. package/src/tui/layout.ts +52 -0
  101. package/src/tui/messageActionPlacement.js +16 -0
  102. package/src/tui/messageActionPlacement.ts +25 -0
  103. package/src/tui/messageInteraction.js +221 -0
  104. package/src/tui/messageInteraction.ts +275 -0
  105. package/src/tui/modelPicker.js +4 -24
  106. package/src/tui/modelPicker.ts +4 -20
  107. package/src/tui/mouseHover.js +6 -0
  108. package/src/tui/mouseHover.ts +5 -0
  109. package/src/tui/prompt.js +175 -101
  110. package/src/tui/resizeRecovery.js +15 -0
  111. package/src/tui/resizeRecovery.ts +27 -0
  112. package/src/tui/scrollInteraction.js +97 -0
  113. package/src/tui/scrollInteraction.ts +189 -0
  114. package/src/tui/sessionLayout.js +12 -0
  115. package/src/tui/sessionLayout.ts +12 -0
  116. package/src/tui/sessionPicker.js +111 -16
  117. package/src/tui/sessionPicker.ts +121 -16
  118. package/src/tui/sessionSidebar.js +78 -0
  119. package/src/tui/sessionSidebar.ts +95 -0
  120. package/src/tui/setup.js +1 -1
  121. package/src/tui/setup.ts +1 -1
  122. package/src/tui/stageSurface.js +120 -58
  123. package/src/tui/text.d.ts +6 -0
  124. package/src/tui/textLayout.js +23 -0
  125. package/src/tui/textLayout.ts +28 -0
  126. package/src/tui/viewport.js +204 -279
  127. package/src/tui/viewport.ts +326 -0
  128. package/src/types/contracts.ts +54 -0
  129. package/src/utils/paths.js +5 -4
  130. package/src/utils/paths.ts +5 -5
@@ -0,0 +1,189 @@
1
+ // Sovereign TUI Scroll & Mouse Isolation Controller
2
+ //
3
+ // Implements OpenCode-compliant viewport containment:
4
+ // 1. Mouse wheel events are strictly confined to the chat box viewport.
5
+ // 2. Overscrolling past the top (0) or bottom (maxScrollTop) saturates cleanly.
6
+ // 3. Mouse reporting is NEVER released to the terminal during an active session,
7
+ // preventing terminal scrollback desync and UI freezes.
8
+ // 4. Scrollbar (rail) mouse interactions clamp cleanly even if clicked above or
9
+ // below the chat box bounds.
10
+
11
+ export interface MouseCoordinate {
12
+ x: number;
13
+ y: number;
14
+ button?: number;
15
+ pressed?: boolean;
16
+ }
17
+
18
+ export interface WheelCoordinate {
19
+ direction: 'up' | 'down' | 'left' | 'right';
20
+ x?: number;
21
+ y?: number;
22
+ }
23
+
24
+ export interface KeyEvent {
25
+ name: string;
26
+ wheel?: WheelCoordinate;
27
+ mouse?: MouseCoordinate;
28
+ shift?: boolean;
29
+ alt?: boolean;
30
+ ctrl?: boolean;
31
+ text?: string;
32
+ sequence?: string;
33
+ }
34
+
35
+ export interface ViewportContract {
36
+ scrollTop: number;
37
+ maxScrollTop(): number;
38
+ wheel(direction: 'up' | 'down', notches?: number, now?: number): number;
39
+ scrollTo(position: number, options?: { snap?: boolean }): number;
40
+ toBottom(): number;
41
+ toTop(): number;
42
+ pageUp(): number;
43
+ pageDown(): number;
44
+ lineUp(n?: number): number;
45
+ lineDown(n?: number): number;
46
+ halfPageUp(): number;
47
+ halfPageDown(): number;
48
+ following: boolean;
49
+ height: number;
50
+ width: number;
51
+ lastWheelMoved?: boolean;
52
+ }
53
+
54
+ export interface SurfaceContract {
55
+ stage?: {
56
+ height: number;
57
+ width(): number;
58
+ reserved?: boolean;
59
+ };
60
+ viewport?: ViewportContract;
61
+ width?: number;
62
+ mouseCaptured?: boolean;
63
+ detached?: boolean;
64
+ releaseMouse?(): boolean;
65
+ captureMouse?(): boolean;
66
+ railEnabled?(width: number): boolean;
67
+ }
68
+
69
+ export interface PromptScrollHost {
70
+ surface: SurfaceContract | null;
71
+ out: { rows?: number; columns?: number; write?(text: string): boolean } | null;
72
+ notice: string;
73
+ draw(): void;
74
+ scheduleDraw?(): void;
75
+ pickerLayout?: {
76
+ pickerStart: number;
77
+ pickerCount: number;
78
+ totalPromptRows: number;
79
+ } | null;
80
+ }
81
+
82
+ /**
83
+ * Handle mouse wheel scrolling with full viewport containment.
84
+ * Replaces the buggy overscroll release with clean boundary saturation.
85
+ */
86
+ export function handleViewportWheel(
87
+ key: KeyEvent,
88
+ viewport: ViewportContract | null | undefined,
89
+ surface: SurfaceContract | null | undefined,
90
+ host: PromptScrollHost
91
+ ): boolean {
92
+ if (!viewport || !key.wheel) return true;
93
+
94
+ // Auto-heal: If the surface was ever detached, immediately re-capture mouse
95
+ // so the session stays responsive and never freezes.
96
+ if (surface && typeof surface.captureMouse === 'function' && surface.detached) {
97
+ surface.captureMouse();
98
+ if (host.notice.startsWith('top of this view')) {
99
+ host.notice = '';
100
+ }
101
+ }
102
+
103
+ // Pure isolated scrolling: clamp strictly inside [0, maxScrollTop]
104
+ viewport.wheel(key.wheel.direction === 'down' ? 'down' : 'up');
105
+
106
+ // Immediately draw updated viewport
107
+ host.draw();
108
+ return true;
109
+ }
110
+
111
+ /**
112
+ * Handle mouse clicks on the scrollbar rail.
113
+ * Safely clamps coordinates even when clicking above or below the chat box.
114
+ */
115
+ export function handleScrollbarMouse(
116
+ key: KeyEvent,
117
+ viewport: ViewportContract | null | undefined,
118
+ surface: SurfaceContract | null | undefined,
119
+ host: PromptScrollHost
120
+ ): boolean {
121
+ if (!viewport || !surface || !key.mouse || !key.mouse.pressed) return false;
122
+ if (key.mouse.button !== 0) return false; // Left click only
123
+
124
+ // If completion picker is active, check if click was on the picker
125
+ if (host.pickerLayout && Number.isFinite(key.mouse.y)) {
126
+ const termRows = host.out?.rows || 24;
127
+ const stageH = surface.stage?.height || termRows;
128
+ const promptTop = Math.max(1, stageH - host.pickerLayout.totalPromptRows + 1);
129
+ const pickerTop = promptTop + host.pickerLayout.pickerStart - 1;
130
+ const pickerBottom = pickerTop + host.pickerLayout.pickerCount;
131
+ if (key.mouse.y >= pickerTop && key.mouse.y <= pickerBottom) {
132
+ return false; // Leave to completion handler
133
+ }
134
+ }
135
+
136
+ const termRows = host.out?.rows || 24;
137
+ const stageH = surface.stage?.height || termRows;
138
+ const stageTop = Math.max(0, termRows - stageH);
139
+ const viewportH = viewport.height;
140
+ const stageW = typeof surface.stage?.width === 'function' ? surface.stage.width() : (surface.width || 80);
141
+ const hasRail = typeof surface.railEnabled === 'function' ? surface.railEnabled(stageW) : true;
142
+ const contentW = hasRail ? Math.max(20, stageW - 3) : stageW;
143
+
144
+ const mouseX = key.mouse.x;
145
+ const mouseY = key.mouse.y;
146
+
147
+ // Rail occupies column contentW - 1 through stageW
148
+ const isRailColumn = mouseX >= contentW - 1 && mouseX <= stageW;
149
+
150
+ if (isRailColumn) {
151
+ // Auto-heal if detached
152
+ if (typeof surface.captureMouse === 'function' && surface.detached) {
153
+ surface.captureMouse();
154
+ if (host.notice.startsWith('top of this view')) host.notice = '';
155
+ }
156
+
157
+ // Boundary clamping:
158
+ // Clicks preceding/above chat box clamp to top (0)
159
+ if (mouseY < stageTop) {
160
+ viewport.scrollTo(0);
161
+ host.draw();
162
+ return true;
163
+ }
164
+
165
+ // Clicks below viewport clamp to bottom (maxScrollTop) and resume following
166
+ if (mouseY >= stageTop + viewportH) {
167
+ viewport.toBottom();
168
+ host.draw();
169
+ return true;
170
+ }
171
+
172
+ // Clicks on rail inside viewport: compute proportional scroll
173
+ const relY = mouseY - stageTop;
174
+ const fraction = viewportH > 1 ? relY / (viewportH - 1) : 0;
175
+ const clampedFraction = Math.max(0, Math.min(1, fraction));
176
+ const target = Math.round(clampedFraction * viewport.maxScrollTop());
177
+
178
+ if (target >= viewport.maxScrollTop()) {
179
+ viewport.toBottom();
180
+ } else {
181
+ viewport.scrollTo(target);
182
+ }
183
+
184
+ host.draw();
185
+ return true;
186
+ }
187
+
188
+ return false;
189
+ }
@@ -0,0 +1,12 @@
1
+ /** Keep an opened conversation anchored to the terminal bottom at every width. */
2
+ export function sessionStageHeight(maxHeight, promptRows, contentRows, fullSession) {
3
+ const limit = Math.max(1, Math.floor(maxHeight));
4
+ return fullSession ? limit : Math.min(limit, Math.max(1, promptRows + contentRows));
5
+ }
6
+ /** Place a short transcript beside the input; spare space belongs above it. */
7
+ export function alignTranscriptRows(rows, contentRows) {
8
+ const visible = Math.max(0, Math.min(rows.length, Math.floor(contentRows)));
9
+ if (visible === rows.length)
10
+ return rows;
11
+ return Array(rows.length - visible).fill('').concat(rows.slice(0, visible));
12
+ }
@@ -0,0 +1,12 @@
1
+ /** Keep an opened conversation anchored to the terminal bottom at every width. */
2
+ export function sessionStageHeight(maxHeight: number, promptRows: number, contentRows: number, fullSession: boolean): number {
3
+ const limit = Math.max(1, Math.floor(maxHeight));
4
+ return fullSession ? limit : Math.min(limit, Math.max(1, promptRows + contentRows));
5
+ }
6
+
7
+ /** Place a short transcript beside the input; spare space belongs above it. */
8
+ export function alignTranscriptRows(rows: string[], contentRows: number): string[] {
9
+ const visible = Math.max(0, Math.min(rows.length, Math.floor(contentRows)));
10
+ if (visible === rows.length) return rows;
11
+ return Array<string>(rows.length - visible).fill('').concat(rows.slice(0, visible));
12
+ }
@@ -5,20 +5,46 @@
5
5
  import { SelectLayer } from './dialogs.js';
6
6
  // @ts-expect-error untyped local TUI theme
7
7
  import { GLYPHS } from './theme.js';
8
- import { listSessions, getActiveSessionId, switchSession, createSession } from '../sessionJournal.js';
8
+ import { listSessions, getActiveSessionId, switchSession, createSession, forkSession } from '../sessionJournal.js';
9
+ import { revokeAllAlways } from '../approvalGrants.js';
10
+ /** The divider counts conversation turns that the history renderer can show. */
11
+ function visibleHistoryCount(messages) {
12
+ return messages.filter((message) => {
13
+ if (message.role !== 'user' && message.role !== 'assistant')
14
+ return false;
15
+ if (typeof message.content === 'string')
16
+ return message.content.trim().length > 0;
17
+ if (Array.isArray(message.content)) {
18
+ return message.content.some((part) => typeof part === 'string' && part.trim().length > 0
19
+ || !!part && typeof part === 'object' && 'text' in part
20
+ && typeof part.text === 'string' && part.text.trim().length > 0);
21
+ }
22
+ return false;
23
+ }).length;
24
+ }
9
25
  function formatTimeAgo(timestamp) {
10
- const diffMs = Date.now() - timestamp;
26
+ const diffMs = Math.max(0, Date.now() - timestamp);
11
27
  const minutes = Math.floor(diffMs / (60 * 1000));
12
28
  if (minutes < 1)
13
29
  return 'just now';
14
30
  if (minutes < 60)
15
31
  return `${minutes}m ago`;
16
- const hours = Math.floor(minutes / (60 * 60 * 1000));
32
+ const hours = Math.floor(minutes / 60);
17
33
  if (hours < 24)
18
34
  return `${hours}h ago`;
19
- const days = Math.floor(hours / (24 * 60 * 60 * 1000));
35
+ const days = Math.floor(hours / 24);
20
36
  return `${days}d ago`;
21
37
  }
38
+ function dateGroup(timestamp) {
39
+ const date = new Date(timestamp);
40
+ if (!Number.isFinite(date.getTime()))
41
+ return 'Unknown date';
42
+ const today = new Date();
43
+ if (date.toDateString() === today.toDateString())
44
+ return 'Today';
45
+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
46
+ return date.toDateString() === yesterday.toDateString() ? 'Yesterday' : date.toDateString();
47
+ }
22
48
  function shortenPath(p) {
23
49
  if (!p)
24
50
  return '(default)';
@@ -45,25 +71,41 @@ export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
45
71
  type: 'new'
46
72
  }
47
73
  });
48
- for (const s of sessions) {
74
+ // Pinned item 1: Fork active conversation if available
75
+ if (activeId) {
76
+ const active = sessions.find(s => s.id === activeId);
77
+ if (active) {
78
+ items.push({
79
+ id: '__FORK_SESSION__',
80
+ label: `Branch / Fork Current Session ("${active.title}")`,
81
+ category: 'Actions',
82
+ description: 'Copy conversation history into a new branch without copying permissions',
83
+ searchText: 'fork branch clone copy session fresh permissions',
84
+ value: {
85
+ type: 'fork',
86
+ id: activeId,
87
+ title: active.title
88
+ }
89
+ });
90
+ }
91
+ }
92
+ for (const s of [...sessions].sort((a, b) => b.updatedAt - a.updatedAt)) {
93
+ // A session without any turns has no conversation to resume. Keep the
94
+ // active one available, but do not fill the picker with abandoned starts.
95
+ if (s.messageCount === 0 && s.id !== activeId)
96
+ continue;
49
97
  const isCurrent = s.id === activeId;
50
98
  const timeAgo = formatTimeAgo(s.updatedAt);
51
99
  const wsLabel = shortenPath(s.workspace);
52
100
  const msgCount = `${s.messageCount} msg${s.messageCount === 1 ? '' : 's'}`;
53
- let category = 'Other Workspaces';
54
- if (s.workspace === currentWorkspace || !s.workspace) {
55
- category = 'Current Workspace';
56
- }
57
- if (s.title.startsWith('[Adopted]')) {
58
- category = 'Continuum (Peer Agent)';
59
- }
101
+ const category = dateGroup(s.updatedAt);
60
102
  const mark = isCurrent ? `● ` : ` `;
61
103
  const tag = isCurrent ? ` [active]` : '';
62
104
  items.push({
63
105
  id: s.id,
64
106
  label: `${mark}${s.title}${tag}`,
65
107
  category,
66
- description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel} ${GLYPHS.dot} ${s.id}`,
108
+ description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${s.workspace === currentWorkspace ? ' (current)' : ''}`,
67
109
  searchText: `${s.title} ${s.id} ${s.workspace || ''} ${category}`,
68
110
  value: {
69
111
  type: 'switch',
@@ -86,6 +128,7 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
86
128
  const sessions = listSessions();
87
129
  const activeId = getActiveSessionId();
88
130
  const items = buildSessionPickerItems(sessions, activeId, workspace);
131
+ const conversationCount = items.filter(item => item.value.type === 'switch').length;
89
132
  const cleanPrompt = () => {
90
133
  if (prompt.editor && typeof prompt.editor.clear === 'function') {
91
134
  prompt.editor.clear();
@@ -95,7 +138,7 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
95
138
  };
96
139
  const picked = await new Promise((resolve) => {
97
140
  const layer = new SelectLayer({
98
- title: `Sessions · Manage & Switch Conversations (${sessions.length})`,
141
+ title: `Sessions (${conversationCount})`,
99
142
  placeholder: 'search sessions by title, id, or workspace...',
100
143
  emptyText: 'no matching sessions found',
101
144
  width: 78,
@@ -106,6 +149,11 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
106
149
  resolve(item || null);
107
150
  }
108
151
  });
152
+ // Opening the picker should highlight a conversation, not an action that
153
+ // creates a new one. Actions remain available above the dated list.
154
+ const selected = items.findIndex(item => item.id === activeId);
155
+ const firstConversation = items.findIndex(item => item.value.type === 'switch');
156
+ layer.list.moveTo(selected >= 0 ? selected : Math.max(0, firstConversation), 15);
109
157
  prompt.openLayer(layer);
110
158
  });
111
159
  cleanPrompt();
@@ -142,7 +190,54 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
142
190
  cleanPrompt();
143
191
  return `Started new session: "${newSession.title}" (${newSession.id}) in ${shortenPath(workspace)}.`;
144
192
  }
145
- // Case 2: Switch to selected session
193
+ // Case 2: Fork session into a new branch without copying permissions
194
+ if (picked.value.type === 'fork') {
195
+ const sourceId = picked.value.id || activeId;
196
+ if (!sourceId) {
197
+ return 'Cancelled. No session to fork.';
198
+ }
199
+ let forked = null;
200
+ if (options.loop?.memoryManager && typeof options.loop.memoryManager.forkSession === 'function') {
201
+ forked = options.loop.memoryManager.forkSession();
202
+ }
203
+ else {
204
+ forked = forkSession(sourceId, { makeActive: true });
205
+ }
206
+ if (!forked) {
207
+ cleanPrompt();
208
+ return `Could not fork session "${sourceId}".`;
209
+ }
210
+ // CRITICAL SECURITY INVARIANT (Claude Code Architecture, p. 24):
211
+ // Permissions and allowlists MUST NOT be copied across the fork.
212
+ revokeAllAlways();
213
+ if (options.loop && typeof options.loop.resetApprovalScope === 'function') {
214
+ options.loop.resetApprovalScope();
215
+ }
216
+ const historyMessages = options.loop?.memoryManager && typeof options.loop.memoryManager.loadHistory === 'function'
217
+ ? options.loop.memoryManager.loadHistory()
218
+ : forked.messages.filter(m => m.role !== 'system');
219
+ if (options.loop) {
220
+ options.loop.messages = historyMessages;
221
+ options.loop.taskId = `cli_chat_${Date.now()}`;
222
+ if (options.loop.tokenTracker && typeof options.loop.tokenTracker.reset === 'function') {
223
+ options.loop.tokenTracker.reset();
224
+ }
225
+ }
226
+ const renderer = prompt.renderer || options.loop?.connection?.renderer;
227
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
228
+ renderer.renderSessionHistory(historyMessages, {
229
+ id: forked.id,
230
+ title: forked.title,
231
+ messagesCount: visibleHistoryCount(historyMessages)
232
+ });
233
+ }
234
+ if (prompt.surface?.viewport && typeof prompt.surface.viewport.toBottom === 'function') {
235
+ prompt.surface.viewport.toBottom();
236
+ }
237
+ cleanPrompt();
238
+ return `Forked into "${forked.title}" (${forked.messages.length} messages, ${forked.id}). Permissions and standing approvals were reset; any gated actions will request authorization anew.`;
239
+ }
240
+ // Case 3: Switch to selected session
146
241
  const targetId = picked.value.id;
147
242
  if (!targetId) {
148
243
  return 'Cancelled. No session selected.';
@@ -174,7 +269,7 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
174
269
  renderer.renderSessionHistory(historyMessages, {
175
270
  id: switched.id,
176
271
  title: switched.title,
177
- messagesCount: switched.messages.length
272
+ messagesCount: visibleHistoryCount(historyMessages)
178
273
  });
179
274
  }
180
275
  if (prompt.surface?.viewport && typeof prompt.surface.viewport.toBottom === 'function') {
@@ -11,11 +11,13 @@ import {
11
11
  getActiveSessionId,
12
12
  switchSession,
13
13
  createSession,
14
+ forkSession,
14
15
  type SessionRecord
15
16
  } from '../sessionJournal.js';
17
+ import { revokeAllAlways } from '../approvalGrants.js';
16
18
 
17
19
  export interface SessionPickerItemValue {
18
- type: 'new' | 'switch';
20
+ type: 'new' | 'switch' | 'fork';
19
21
  id?: string | undefined;
20
22
  title?: string | undefined;
21
23
  workspace?: string | undefined;
@@ -37,9 +39,11 @@ export interface InteractiveSessionPickerOptions {
37
39
  taskId?: string;
38
40
  messages?: Array<{ role: string; content?: unknown }>;
39
41
  tokenTracker?: { reset?: () => void; sessionTokens?: number };
42
+ resetApprovalScope?: () => void;
40
43
  memoryManager?: {
41
44
  startNewSession?: (title?: string) => any;
42
45
  useSession?: (id: string) => any;
46
+ forkSession?: (title?: string) => any;
43
47
  loadHistory?: () => Array<{ role: string; content?: unknown }>;
44
48
  sessionId?: string | null;
45
49
  session?: any;
@@ -48,17 +52,41 @@ export interface InteractiveSessionPickerOptions {
48
52
  workspace?: string | undefined;
49
53
  }
50
54
 
55
+ /** The divider counts conversation turns that the history renderer can show. */
56
+ function visibleHistoryCount(messages: Array<{ role: string; content?: unknown }>): number {
57
+ return messages.filter((message) => {
58
+ if (message.role !== 'user' && message.role !== 'assistant') return false;
59
+ if (typeof message.content === 'string') return message.content.trim().length > 0;
60
+ if (Array.isArray(message.content)) {
61
+ return message.content.some((part: unknown) =>
62
+ typeof part === 'string' && part.trim().length > 0
63
+ || !!part && typeof part === 'object' && 'text' in part
64
+ && typeof part.text === 'string' && part.text.trim().length > 0);
65
+ }
66
+ return false;
67
+ }).length;
68
+ }
69
+
51
70
  function formatTimeAgo(timestamp: number): string {
52
- const diffMs = Date.now() - timestamp;
71
+ const diffMs = Math.max(0, Date.now() - timestamp);
53
72
  const minutes = Math.floor(diffMs / (60 * 1000));
54
73
  if (minutes < 1) return 'just now';
55
74
  if (minutes < 60) return `${minutes}m ago`;
56
- const hours = Math.floor(minutes / (60 * 60 * 1000));
75
+ const hours = Math.floor(minutes / 60);
57
76
  if (hours < 24) return `${hours}h ago`;
58
- const days = Math.floor(hours / (24 * 60 * 60 * 1000));
77
+ const days = Math.floor(hours / 24);
59
78
  return `${days}d ago`;
60
79
  }
61
80
 
81
+ function dateGroup(timestamp: number): string {
82
+ const date = new Date(timestamp);
83
+ if (!Number.isFinite(date.getTime())) return 'Unknown date';
84
+ const today = new Date();
85
+ if (date.toDateString() === today.toDateString()) return 'Today';
86
+ const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
87
+ return date.toDateString() === yesterday.toDateString() ? 'Yesterday' : date.toDateString();
88
+ }
89
+
62
90
  function shortenPath(p: string | undefined): string {
63
91
  if (!p) return '(default)';
64
92
  const home = process.env.HOME || '';
@@ -91,19 +119,35 @@ export function buildSessionPickerItems(
91
119
  }
92
120
  });
93
121
 
94
- for (const s of sessions) {
122
+ // Pinned item 1: Fork active conversation if available
123
+ if (activeId) {
124
+ const active = sessions.find(s => s.id === activeId);
125
+ if (active) {
126
+ items.push({
127
+ id: '__FORK_SESSION__',
128
+ label: `Branch / Fork Current Session ("${active.title}")`,
129
+ category: 'Actions',
130
+ description: 'Copy conversation history into a new branch without copying permissions',
131
+ searchText: 'fork branch clone copy session fresh permissions',
132
+ value: {
133
+ type: 'fork',
134
+ id: activeId,
135
+ title: active.title
136
+ }
137
+ });
138
+ }
139
+ }
140
+
141
+ for (const s of [...sessions].sort((a, b) => b.updatedAt - a.updatedAt)) {
142
+ // A session without any turns has no conversation to resume. Keep the
143
+ // active one available, but do not fill the picker with abandoned starts.
144
+ if (s.messageCount === 0 && s.id !== activeId) continue;
95
145
  const isCurrent = s.id === activeId;
96
146
  const timeAgo = formatTimeAgo(s.updatedAt);
97
147
  const wsLabel = shortenPath(s.workspace);
98
148
  const msgCount = `${s.messageCount} msg${s.messageCount === 1 ? '' : 's'}`;
99
149
 
100
- let category = 'Other Workspaces';
101
- if (s.workspace === currentWorkspace || !s.workspace) {
102
- category = 'Current Workspace';
103
- }
104
- if (s.title.startsWith('[Adopted]')) {
105
- category = 'Continuum (Peer Agent)';
106
- }
150
+ const category = dateGroup(s.updatedAt);
107
151
 
108
152
  const mark = isCurrent ? `● ` : ` `;
109
153
  const tag = isCurrent ? ` [active]` : '';
@@ -112,7 +156,7 @@ export function buildSessionPickerItems(
112
156
  id: s.id,
113
157
  label: `${mark}${s.title}${tag}`,
114
158
  category,
115
- description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel} ${GLYPHS.dot} ${s.id}`,
159
+ description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${s.workspace === currentWorkspace ? ' (current)' : ''}`,
116
160
  searchText: `${s.title} ${s.id} ${s.workspace || ''} ${category}`,
117
161
  value: {
118
162
  type: 'switch',
@@ -147,6 +191,7 @@ export async function runInteractiveSessionPicker(
147
191
  const activeId = getActiveSessionId();
148
192
 
149
193
  const items = buildSessionPickerItems(sessions, activeId, workspace);
194
+ const conversationCount = items.filter(item => item.value.type === 'switch').length;
150
195
 
151
196
  const cleanPrompt = () => {
152
197
  if (prompt.editor && typeof prompt.editor.clear === 'function') {
@@ -157,7 +202,7 @@ export async function runInteractiveSessionPicker(
157
202
 
158
203
  const picked = await new Promise<SessionPickerItem | null>((resolve) => {
159
204
  const layer = new SelectLayer({
160
- title: `Sessions · Manage & Switch Conversations (${sessions.length})`,
205
+ title: `Sessions (${conversationCount})`,
161
206
  placeholder: 'search sessions by title, id, or workspace...',
162
207
  emptyText: 'no matching sessions found',
163
208
  width: 78,
@@ -168,6 +213,11 @@ export async function runInteractiveSessionPicker(
168
213
  resolve(item || null);
169
214
  }
170
215
  });
216
+ // Opening the picker should highlight a conversation, not an action that
217
+ // creates a new one. Actions remain available above the dated list.
218
+ const selected = items.findIndex(item => item.id === activeId);
219
+ const firstConversation = items.findIndex(item => item.value.type === 'switch');
220
+ layer.list.moveTo(selected >= 0 ? selected : Math.max(0, firstConversation), 15);
171
221
  prompt.openLayer(layer);
172
222
  });
173
223
 
@@ -210,7 +260,62 @@ export async function runInteractiveSessionPicker(
210
260
  return `Started new session: "${newSession.title}" (${newSession.id}) in ${shortenPath(workspace)}.`;
211
261
  }
212
262
 
213
- // Case 2: Switch to selected session
263
+ // Case 2: Fork session into a new branch without copying permissions
264
+ if (picked.value.type === 'fork') {
265
+ const sourceId = picked.value.id || activeId;
266
+ if (!sourceId) {
267
+ return 'Cancelled. No session to fork.';
268
+ }
269
+
270
+ let forked: SessionRecord | null = null;
271
+ if (options.loop?.memoryManager && typeof options.loop.memoryManager.forkSession === 'function') {
272
+ forked = options.loop.memoryManager.forkSession();
273
+ } else {
274
+ forked = forkSession(sourceId, { makeActive: true });
275
+ }
276
+
277
+ if (!forked) {
278
+ cleanPrompt();
279
+ return `Could not fork session "${sourceId}".`;
280
+ }
281
+
282
+ // CRITICAL SECURITY INVARIANT (Claude Code Architecture, p. 24):
283
+ // Permissions and allowlists MUST NOT be copied across the fork.
284
+ revokeAllAlways();
285
+ if (options.loop && typeof options.loop.resetApprovalScope === 'function') {
286
+ options.loop.resetApprovalScope();
287
+ }
288
+
289
+ const historyMessages = options.loop?.memoryManager && typeof options.loop.memoryManager.loadHistory === 'function'
290
+ ? options.loop.memoryManager.loadHistory()
291
+ : forked.messages.filter(m => m.role !== 'system');
292
+
293
+ if (options.loop) {
294
+ options.loop.messages = historyMessages;
295
+ options.loop.taskId = `cli_chat_${Date.now()}`;
296
+ if (options.loop.tokenTracker && typeof options.loop.tokenTracker.reset === 'function') {
297
+ options.loop.tokenTracker.reset();
298
+ }
299
+ }
300
+
301
+ const renderer = (prompt as any).renderer || (options.loop as any)?.connection?.renderer;
302
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
303
+ renderer.renderSessionHistory(historyMessages, {
304
+ id: forked.id,
305
+ title: forked.title,
306
+ messagesCount: visibleHistoryCount(historyMessages)
307
+ });
308
+ }
309
+
310
+ if ((prompt as any).surface?.viewport && typeof (prompt as any).surface.viewport.toBottom === 'function') {
311
+ (prompt as any).surface.viewport.toBottom();
312
+ }
313
+
314
+ cleanPrompt();
315
+ return `Forked into "${forked.title}" (${forked.messages.length} messages, ${forked.id}). Permissions and standing approvals were reset; any gated actions will request authorization anew.`;
316
+ }
317
+
318
+ // Case 3: Switch to selected session
214
319
  const targetId = picked.value.id;
215
320
  if (!targetId) {
216
321
  return 'Cancelled. No session selected.';
@@ -246,7 +351,7 @@ export async function runInteractiveSessionPicker(
246
351
  renderer.renderSessionHistory(historyMessages, {
247
352
  id: switched.id,
248
353
  title: switched.title,
249
- messagesCount: switched.messages.length
354
+ messagesCount: visibleHistoryCount(historyMessages)
250
355
  });
251
356
  }
252
357