@causyne/agent 1.20.111 → 1.20.116

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 (151) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +72 -37
  4. package/src/agentLoop.ts +70 -38
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +7 -2
  8. package/src/browser/causyneBrowser.ts +8 -2
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/computerUse/visionGrounding.js +31 -27
  18. package/src/computerUse/visionGrounding.ts +27 -27
  19. package/src/continuum/ui/continuumPicker.js +14 -6
  20. package/src/continuum/ui/continuumPicker.ts +13 -6
  21. package/src/continuum/ui/continuumPickerView.js +24 -15
  22. package/src/continuum/ui/continuumPickerView.ts +24 -16
  23. package/src/observer/advisory.js +32 -22
  24. package/src/observer/advisory.ts +30 -18
  25. package/src/observer/coldObserver.js +21 -33
  26. package/src/observer/coldObserver.ts +20 -33
  27. package/src/observer/evidence.js +20 -13
  28. package/src/observer/evidence.ts +21 -13
  29. package/src/observer.js +47 -12
  30. package/src/observer.ts +50 -18
  31. package/src/pluginsFactory/discovery.js +28 -16
  32. package/src/pluginsFactory/discovery.ts +29 -16
  33. package/src/pluginsFactory/pluginsFactory.js +213 -38
  34. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  35. package/src/pluginsFactory/strategy.js +26 -16
  36. package/src/pluginsFactory/strategy.ts +34 -19
  37. package/src/pluginsFactory/templates.js +183 -62
  38. package/src/pluginsFactory/templates.ts +174 -54
  39. package/src/timeMachine.js +43 -22
  40. package/src/timeMachine.ts +44 -22
  41. package/src/tool-scripts/desktop_act.applescript +1 -0
  42. package/src/tools/computerUse.js +23 -10
  43. package/src/tools/computerUse.ts +19 -8
  44. package/src/tools/desktopAct.js +12 -1
  45. package/src/tools/pluginsFactory.js +108 -5
  46. package/src/tools/pluginsFactory.ts +115 -5
  47. package/src/tui/CausyneRotor.js +24 -10
  48. package/src/tui/CausyneRotor.ts +25 -10
  49. package/src/tui/activityLayout.js +9 -5
  50. package/src/tui/activityLayout.ts +9 -5
  51. package/src/tui/ask.js +34 -14
  52. package/src/tui/banner.js +55 -18
  53. package/src/tui/banner.ts +52 -17
  54. package/src/tui/block.js +47 -20
  55. package/src/tui/block.ts +54 -27
  56. package/src/tui/chatRenderer.js +135 -83
  57. package/src/tui/chatboxClipboard.js +12 -5
  58. package/src/tui/chatboxClipboard.ts +10 -4
  59. package/src/tui/clipboardImage.js +52 -42
  60. package/src/tui/clipboardImage.ts +50 -39
  61. package/src/tui/clipboardSync.js +12 -1
  62. package/src/tui/clipboardSync.ts +9 -1
  63. package/src/tui/codeProgress.js +57 -26
  64. package/src/tui/codeProgress.ts +57 -25
  65. package/src/tui/codeStreamRenderer.js +59 -14
  66. package/src/tui/codeStreamRenderer.ts +58 -14
  67. package/src/tui/commandPresentation.js +9 -2
  68. package/src/tui/commandPresentation.ts +9 -2
  69. package/src/tui/completion.js +45 -23
  70. package/src/tui/composerControls.js +21 -10
  71. package/src/tui/composerControls.ts +18 -10
  72. package/src/tui/composerGeometry.js +6 -4
  73. package/src/tui/composerGeometry.ts +6 -4
  74. package/src/tui/consoleGuard.js +29 -7
  75. package/src/tui/consoleGuard.ts +28 -7
  76. package/src/tui/dialogs.js +134 -71
  77. package/src/tui/diff.js +8 -4
  78. package/src/tui/history.js +6 -5
  79. package/src/tui/home.js +25 -13
  80. package/src/tui/homeView.js +37 -18
  81. package/src/tui/homeView.ts +38 -18
  82. package/src/tui/inlineSlash.js +6 -5
  83. package/src/tui/inlineSlash.ts +6 -5
  84. package/src/tui/keys.js +33 -17
  85. package/src/tui/layout.js +27 -9
  86. package/src/tui/layout.ts +26 -9
  87. package/src/tui/lineEditor.js +49 -23
  88. package/src/tui/markdownMath.js +64 -14
  89. package/src/tui/markdownMath.ts +69 -13
  90. package/src/tui/messageActionPlacement.js +28 -13
  91. package/src/tui/messageActionPlacement.ts +28 -13
  92. package/src/tui/messageInteraction.js +111 -46
  93. package/src/tui/messageInteraction.ts +115 -47
  94. package/src/tui/modelPicker.js +44 -15
  95. package/src/tui/modelPicker.ts +48 -15
  96. package/src/tui/observerPicker.js +56 -13
  97. package/src/tui/observerPicker.ts +73 -30
  98. package/src/tui/overlay.js +79 -35
  99. package/src/tui/overlay.ts +81 -34
  100. package/src/tui/prompt.js +162 -94
  101. package/src/tui/runningLight.js +1 -1
  102. package/src/tui/runningLight.ts +1 -1
  103. package/src/tui/scrollInteraction.js +64 -36
  104. package/src/tui/scrollInteraction.ts +70 -37
  105. package/src/tui/selectList.js +60 -32
  106. package/src/tui/sessionLayout.js +11 -3
  107. package/src/tui/sessionLayout.ts +10 -3
  108. package/src/tui/sessionPicker.js +74 -46
  109. package/src/tui/sessionPicker.ts +73 -48
  110. package/src/tui/sessionPickerView.js +32 -19
  111. package/src/tui/sessionPickerView.ts +31 -18
  112. package/src/tui/sessionSidebar.js +87 -57
  113. package/src/tui/sessionSidebar.ts +90 -54
  114. package/src/tui/setup.js +28 -3
  115. package/src/tui/setup.ts +27 -3
  116. package/src/tui/skillAuthoring.js +11 -5
  117. package/src/tui/skillAuthoring.ts +11 -5
  118. package/src/tui/smartLinkClick.js +75 -23
  119. package/src/tui/smartLinkClick.ts +86 -26
  120. package/src/tui/stage.js +47 -16
  121. package/src/tui/stage.ts +53 -18
  122. package/src/tui/stageSurface.js +120 -49
  123. package/src/tui/statusLine.js +85 -53
  124. package/src/tui/statusLine.ts +82 -46
  125. package/src/tui/terminalInputFramer.js +5 -2
  126. package/src/tui/text.js +117 -46
  127. package/src/tui/text.ts +113 -43
  128. package/src/tui/textLayout.js +6 -4
  129. package/src/tui/textLayout.ts +11 -5
  130. package/src/tui/theme.js +17 -8
  131. package/src/tui/thinkingBox.js +95 -95
  132. package/src/tui/thinkingBox.ts +105 -80
  133. package/src/tui/toolActivityPolicy.js +8 -1
  134. package/src/tui/toolActivityPolicy.ts +7 -1
  135. package/src/tui/toolDisplay.js +15 -6
  136. package/src/tui/toolDisplay.ts +16 -6
  137. package/src/tui/toolOutputNormalizer.js +16 -3
  138. package/src/tui/toolOutputNormalizer.ts +13 -3
  139. package/src/tui/transcript.js +15 -9
  140. package/src/tui/turnRail.js +156 -67
  141. package/src/tui/turnRail.ts +155 -58
  142. package/src/tui/usageCard.js +80 -45
  143. package/src/tui/usageCard.ts +81 -46
  144. package/src/tui/viewport.js +48 -23
  145. package/src/tui/viewport.ts +48 -27
  146. package/src/tui/viewportAnchor.js +2 -2
  147. package/src/tui/viewportAnchor.ts +2 -2
  148. package/src/tui/workspaceFileIndex.js +8 -6
  149. package/src/tui/workspaceFileIndex.ts +8 -6
  150. package/src/tui/workspaceSwitch.js +13 -10
  151. package/src/tui/workspaceSwitch.ts +11 -7
@@ -4,8 +4,13 @@
4
4
  import { SessionPickerLayer } from './sessionPickerView.js';
5
5
  // @ts-expect-error untyped local TUI theme
6
6
  import { GLYPHS } from './theme.js';
7
+ import { safeDisplay } from './text.js';
8
+ import { measureMessages } from '../contextManager.js';
7
9
  import { listSessions, getActiveSessionId, switchSession, createSession, forkSession } from '../sessionJournal.js';
8
10
  import { revokeAllAlways } from '../approvalGrants.js';
11
+ function cleanTitle(value) {
12
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? '')).replace(/[\r\n]+/g, ' ').trim() || 'Untitled';
13
+ }
9
14
  /** The divider counts conversation messages that the history renderer displays. */
10
15
  function visibleHistoryCount(messages) {
11
16
  return messages.filter((message) => {
@@ -15,6 +20,8 @@ function visibleHistoryCount(messages) {
15
20
  }).length;
16
21
  }
17
22
  function formatTimeAgo(timestamp) {
23
+ if (!Number.isFinite(timestamp))
24
+ return 'unknown';
18
25
  const diffMs = Math.max(0, Date.now() - timestamp);
19
26
  const minutes = Math.floor(diffMs / (60 * 1000));
20
27
  if (minutes < 1)
@@ -67,44 +74,58 @@ export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
67
74
  if (activeId) {
68
75
  const active = sessions.find(s => s.id === activeId);
69
76
  if (active) {
77
+ const activeTitle = cleanTitle(active.title);
70
78
  items.push({
71
79
  id: '__FORK_SESSION__',
72
- label: `Branch / Fork Current Session ("${active.title}")`,
80
+ label: `Branch / Fork Current Session ("${activeTitle}")`,
73
81
  category: 'Actions',
74
82
  description: 'Copy conversation history into a new branch without copying permissions',
75
83
  searchText: 'fork branch clone copy session fresh permissions',
76
84
  value: {
77
85
  type: 'fork',
78
86
  id: activeId,
79
- title: active.title
87
+ title: activeTitle
80
88
  }
81
89
  });
82
90
  }
83
91
  }
84
- for (const s of [...sessions].sort((a, b) => b.updatedAt - a.updatedAt)) {
92
+ const sortedSessions = [...sessions].sort((a, b) => {
93
+ const aValid = Number.isFinite(a.updatedAt);
94
+ const bValid = Number.isFinite(b.updatedAt);
95
+ if (!aValid && !bValid)
96
+ return 0;
97
+ if (!aValid)
98
+ return 1;
99
+ if (!bValid)
100
+ return -1;
101
+ return b.updatedAt === a.updatedAt ? 0 : b.updatedAt > a.updatedAt ? 1 : -1;
102
+ });
103
+ for (const s of sortedSessions) {
85
104
  // A session without any turns has no conversation to resume. Keep the
86
105
  // active one available, but do not fill the picker with abandoned starts.
87
- if (s.messageCount === 0 && s.id !== activeId)
106
+ const safeMessageCount = Number.isFinite(s.messageCount) ? Math.max(0, Math.floor(s.messageCount)) : 0;
107
+ if (safeMessageCount === 0 && s.id !== activeId)
88
108
  continue;
89
109
  const isCurrent = s.id === activeId;
90
110
  const timeAgo = formatTimeAgo(s.updatedAt);
91
111
  const wsLabel = shortenPath(s.workspace);
92
- const msgCount = `${s.messageCount} msg${s.messageCount === 1 ? '' : 's'}`;
112
+ const msgCount = `${safeMessageCount} msg${safeMessageCount === 1 ? '' : 's'}`;
93
113
  const category = dateGroup(s.updatedAt);
94
114
  const mark = isCurrent ? `● ` : ` `;
95
115
  const tag = isCurrent ? ` [active]` : '';
116
+ const title = cleanTitle(s.title);
96
117
  items.push({
97
118
  id: s.id,
98
- label: `${mark}${s.title}${tag}`,
119
+ label: `${mark}${title}${tag}`,
99
120
  category,
100
121
  description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${s.workspace === currentWorkspace ? ' (current)' : ''}`,
101
- searchText: `${s.title} ${s.id} ${s.workspace || ''} ${category}`,
122
+ searchText: `${title} ${s.id} ${s.workspace || ''} ${category}`,
102
123
  value: {
103
124
  type: 'switch',
104
125
  id: s.id,
105
- title: s.title,
126
+ title,
106
127
  workspace: s.workspace,
107
- messageCount: s.messageCount,
128
+ messageCount: safeMessageCount,
108
129
  updatedAt: s.updatedAt,
109
130
  isCurrent
110
131
  }
@@ -148,6 +169,44 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
148
169
  if (!picked || !picked.value) {
149
170
  return 'Cancelled. Session was not changed.';
150
171
  }
172
+ const syncSessionSurface = (record, messages) => {
173
+ const renderer = prompt.renderer || options.loop?.connection?.renderer;
174
+ const surface = prompt.surface;
175
+ const contextChars = messages.length > 0 ? Math.max(0, measureMessages(messages)) : 0;
176
+ const sessionMeta = {
177
+ id: record.id,
178
+ title: cleanTitle(record.title),
179
+ messagesCount: visibleHistoryCount(messages),
180
+ contextChars,
181
+ plan: []
182
+ };
183
+ if (renderer?.status && typeof renderer.status === 'object') {
184
+ renderer.status.contextChars = contextChars;
185
+ }
186
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
187
+ renderer.renderSessionHistory(messages, sessionMeta);
188
+ }
189
+ if (renderer && typeof renderer.setSessionInfo === 'function') {
190
+ renderer.setSessionInfo(sessionMeta);
191
+ }
192
+ if (surface && typeof surface === 'object') {
193
+ if ('homeInfo' in surface && surface.homeInfo && typeof surface.leaveHome === 'function') {
194
+ surface.leaveHome(true);
195
+ }
196
+ if ('activeTurnIndex' in surface)
197
+ surface.activeTurnIndex = null;
198
+ if ('hoveredTurnIndex' in surface)
199
+ surface.hoveredTurnIndex = null;
200
+ if ('hoveredMessageFrameId' in surface)
201
+ surface.hoveredMessageFrameId = null;
202
+ if (typeof surface.setSessionInfo === 'function') {
203
+ surface.setSessionInfo(sessionMeta);
204
+ }
205
+ if (surface.viewport && typeof surface.viewport.toBottom === 'function') {
206
+ surface.viewport.toBottom();
207
+ }
208
+ }
209
+ };
151
210
  // Case 1: Start fresh new session
152
211
  if (picked.value.type === 'new') {
153
212
  let newSession;
@@ -164,19 +223,9 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
164
223
  options.loop.tokenTracker.reset();
165
224
  }
166
225
  }
167
- const renderer = prompt.renderer || options.loop?.connection?.renderer;
168
- if (renderer && typeof renderer.renderSessionHistory === 'function') {
169
- renderer.renderSessionHistory([], {
170
- id: newSession.id,
171
- title: newSession.title,
172
- messagesCount: 0
173
- });
174
- }
175
- if (prompt.surface?.viewport && typeof prompt.surface.viewport.toBottom === 'function') {
176
- prompt.surface.viewport.toBottom();
177
- }
226
+ syncSessionSurface(newSession, []);
178
227
  cleanPrompt();
179
- return `Started new session: "${newSession.title}" (${newSession.id}) in ${shortenPath(workspace)}.`;
228
+ return `Started new session: "${cleanTitle(newSession.title)}" (${newSession.id}) in ${shortenPath(workspace)}.`;
180
229
  }
181
230
  // Case 2: Fork session into a new branch without copying permissions
182
231
  if (picked.value.type === 'fork') {
@@ -211,19 +260,9 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
211
260
  options.loop.tokenTracker.reset();
212
261
  }
213
262
  }
214
- const renderer = prompt.renderer || options.loop?.connection?.renderer;
215
- if (renderer && typeof renderer.renderSessionHistory === 'function') {
216
- renderer.renderSessionHistory(historyMessages, {
217
- id: forked.id,
218
- title: forked.title,
219
- messagesCount: visibleHistoryCount(historyMessages)
220
- });
221
- }
222
- if (prompt.surface?.viewport && typeof prompt.surface.viewport.toBottom === 'function') {
223
- prompt.surface.viewport.toBottom();
224
- }
263
+ syncSessionSurface(forked, historyMessages);
225
264
  cleanPrompt();
226
- return `Forked into "${forked.title}" (${forked.messages.length} messages, ${forked.id}). Permissions and standing approvals were reset; any gated actions will request authorization anew.`;
265
+ return `Forked into "${cleanTitle(forked.title)}" (${forked.messages.length} messages, ${forked.id}). Permissions and standing approvals were reset; any gated actions will request authorization anew.`;
227
266
  }
228
267
  // Case 3: Switch to selected session
229
268
  const targetId = picked.value.id;
@@ -251,18 +290,7 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
251
290
  options.loop.tokenTracker.reset();
252
291
  }
253
292
  }
254
- // Render the conversation history to the transcript & viewport
255
- const renderer = prompt.renderer || options.loop?.connection?.renderer;
256
- if (renderer && typeof renderer.renderSessionHistory === 'function') {
257
- renderer.renderSessionHistory(historyMessages, {
258
- id: switched.id,
259
- title: switched.title,
260
- messagesCount: visibleHistoryCount(historyMessages)
261
- });
262
- }
263
- if (prompt.surface?.viewport && typeof prompt.surface.viewport.toBottom === 'function') {
264
- prompt.surface.viewport.toBottom();
265
- }
293
+ syncSessionSurface(switched, historyMessages);
266
294
  cleanPrompt();
267
- return `Switched to "${switched.title}" (${switched.messages.length} messages, ${switched.id}).`;
295
+ return `Switched to "${cleanTitle(switched.title)}" (${switched.messages.length} messages, ${switched.id}).`;
268
296
  }
@@ -5,6 +5,8 @@
5
5
  import { SessionPickerLayer } from './sessionPickerView.js';
6
6
  // @ts-expect-error untyped local TUI theme
7
7
  import { GLYPHS } from './theme.js';
8
+ import { safeDisplay } from './text.js';
9
+ import { measureMessages } from '../contextManager.js';
8
10
  import {
9
11
  listSessions,
10
12
  getActiveSessionId,
@@ -15,6 +17,10 @@ import {
15
17
  } from '../sessionJournal.js';
16
18
  import { revokeAllAlways } from '../approvalGrants.js';
17
19
 
20
+ function cleanTitle(value: unknown): string {
21
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? '')).replace(/[\r\n]+/g, ' ').trim() || 'Untitled';
22
+ }
23
+
18
24
  export interface SessionPickerItemValue {
19
25
  type: 'new' | 'switch' | 'fork';
20
26
  id?: string | undefined;
@@ -61,6 +67,7 @@ function visibleHistoryCount(messages: Array<{ role: string; content?: unknown }
61
67
  }
62
68
 
63
69
  function formatTimeAgo(timestamp: number): string {
70
+ if (!Number.isFinite(timestamp)) return 'unknown';
64
71
  const diffMs = Math.max(0, Date.now() - timestamp);
65
72
  const minutes = Math.floor(diffMs / (60 * 1000));
66
73
  if (minutes < 1) return 'just now';
@@ -116,47 +123,59 @@ export function buildSessionPickerItems(
116
123
  if (activeId) {
117
124
  const active = sessions.find(s => s.id === activeId);
118
125
  if (active) {
126
+ const activeTitle = cleanTitle(active.title);
119
127
  items.push({
120
128
  id: '__FORK_SESSION__',
121
- label: `Branch / Fork Current Session ("${active.title}")`,
129
+ label: `Branch / Fork Current Session ("${activeTitle}")`,
122
130
  category: 'Actions',
123
131
  description: 'Copy conversation history into a new branch without copying permissions',
124
132
  searchText: 'fork branch clone copy session fresh permissions',
125
133
  value: {
126
134
  type: 'fork',
127
135
  id: activeId,
128
- title: active.title
136
+ title: activeTitle
129
137
  }
130
138
  });
131
139
  }
132
140
  }
133
141
 
134
- for (const s of [...sessions].sort((a, b) => b.updatedAt - a.updatedAt)) {
142
+ const sortedSessions = [...sessions].sort((a, b) => {
143
+ const aValid = Number.isFinite(a.updatedAt);
144
+ const bValid = Number.isFinite(b.updatedAt);
145
+ if (!aValid && !bValid) return 0;
146
+ if (!aValid) return 1;
147
+ if (!bValid) return -1;
148
+ return b.updatedAt === a.updatedAt ? 0 : b.updatedAt > a.updatedAt ? 1 : -1;
149
+ });
150
+
151
+ for (const s of sortedSessions) {
135
152
  // A session without any turns has no conversation to resume. Keep the
136
153
  // active one available, but do not fill the picker with abandoned starts.
137
- if (s.messageCount === 0 && s.id !== activeId) continue;
154
+ const safeMessageCount = Number.isFinite(s.messageCount) ? Math.max(0, Math.floor(s.messageCount)) : 0;
155
+ if (safeMessageCount === 0 && s.id !== activeId) continue;
138
156
  const isCurrent = s.id === activeId;
139
157
  const timeAgo = formatTimeAgo(s.updatedAt);
140
158
  const wsLabel = shortenPath(s.workspace);
141
- const msgCount = `${s.messageCount} msg${s.messageCount === 1 ? '' : 's'}`;
159
+ const msgCount = `${safeMessageCount} msg${safeMessageCount === 1 ? '' : 's'}`;
142
160
 
143
161
  const category = dateGroup(s.updatedAt);
144
162
 
145
163
  const mark = isCurrent ? `● ` : ` `;
146
164
  const tag = isCurrent ? ` [active]` : '';
165
+ const title = cleanTitle(s.title);
147
166
 
148
167
  items.push({
149
168
  id: s.id,
150
- label: `${mark}${s.title}${tag}`,
169
+ label: `${mark}${title}${tag}`,
151
170
  category,
152
171
  description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${s.workspace === currentWorkspace ? ' (current)' : ''}`,
153
- searchText: `${s.title} ${s.id} ${s.workspace || ''} ${category}`,
172
+ searchText: `${title} ${s.id} ${s.workspace || ''} ${category}`,
154
173
  value: {
155
174
  type: 'switch',
156
175
  id: s.id,
157
- title: s.title,
176
+ title,
158
177
  workspace: s.workspace,
159
- messageCount: s.messageCount,
178
+ messageCount: safeMessageCount,
160
179
  updatedAt: s.updatedAt,
161
180
  isCurrent
162
181
  }
@@ -216,6 +235,45 @@ export async function runInteractiveSessionPicker(
216
235
  return 'Cancelled. Session was not changed.';
217
236
  }
218
237
 
238
+ const syncSessionSurface = (
239
+ record: { id: string; title: string },
240
+ messages: Array<{ role: string; content?: unknown }>
241
+ ): void => {
242
+ const renderer = (prompt as any).renderer || (options.loop as any)?.connection?.renderer;
243
+ const surface = (prompt as any).surface;
244
+ const contextChars = messages.length > 0 ? Math.max(0, measureMessages(messages as any)) : 0;
245
+ const sessionMeta = {
246
+ id: record.id,
247
+ title: cleanTitle(record.title),
248
+ messagesCount: visibleHistoryCount(messages),
249
+ contextChars,
250
+ plan: []
251
+ };
252
+ if (renderer?.status && typeof renderer.status === 'object') {
253
+ renderer.status.contextChars = contextChars;
254
+ }
255
+ if (renderer && typeof renderer.renderSessionHistory === 'function') {
256
+ renderer.renderSessionHistory(messages, sessionMeta);
257
+ }
258
+ if (renderer && typeof renderer.setSessionInfo === 'function') {
259
+ renderer.setSessionInfo(sessionMeta);
260
+ }
261
+ if (surface && typeof surface === 'object') {
262
+ if ('homeInfo' in surface && surface.homeInfo && typeof surface.leaveHome === 'function') {
263
+ surface.leaveHome(true);
264
+ }
265
+ if ('activeTurnIndex' in surface) surface.activeTurnIndex = null;
266
+ if ('hoveredTurnIndex' in surface) surface.hoveredTurnIndex = null;
267
+ if ('hoveredMessageFrameId' in surface) surface.hoveredMessageFrameId = null;
268
+ if (typeof surface.setSessionInfo === 'function') {
269
+ surface.setSessionInfo(sessionMeta);
270
+ }
271
+ if (surface.viewport && typeof surface.viewport.toBottom === 'function') {
272
+ surface.viewport.toBottom();
273
+ }
274
+ }
275
+ };
276
+
219
277
  // Case 1: Start fresh new session
220
278
  if (picked.value.type === 'new') {
221
279
  let newSession: SessionRecord;
@@ -233,20 +291,10 @@ export async function runInteractiveSessionPicker(
233
291
  }
234
292
  }
235
293
 
236
- const renderer = (prompt as any).renderer || (options.loop as any)?.connection?.renderer;
237
- if (renderer && typeof renderer.renderSessionHistory === 'function') {
238
- renderer.renderSessionHistory([], {
239
- id: newSession.id,
240
- title: newSession.title,
241
- messagesCount: 0
242
- });
243
- }
244
- if ((prompt as any).surface?.viewport && typeof (prompt as any).surface.viewport.toBottom === 'function') {
245
- (prompt as any).surface.viewport.toBottom();
246
- }
294
+ syncSessionSurface(newSession, []);
247
295
 
248
296
  cleanPrompt();
249
- return `Started new session: "${newSession.title}" (${newSession.id}) in ${shortenPath(workspace)}.`;
297
+ return `Started new session: "${cleanTitle(newSession.title)}" (${newSession.id}) in ${shortenPath(workspace)}.`;
250
298
  }
251
299
 
252
300
  // Case 2: Fork session into a new branch without copying permissions
@@ -287,21 +335,10 @@ export async function runInteractiveSessionPicker(
287
335
  }
288
336
  }
289
337
 
290
- const renderer = (prompt as any).renderer || (options.loop as any)?.connection?.renderer;
291
- if (renderer && typeof renderer.renderSessionHistory === 'function') {
292
- renderer.renderSessionHistory(historyMessages, {
293
- id: forked.id,
294
- title: forked.title,
295
- messagesCount: visibleHistoryCount(historyMessages)
296
- });
297
- }
298
-
299
- if ((prompt as any).surface?.viewport && typeof (prompt as any).surface.viewport.toBottom === 'function') {
300
- (prompt as any).surface.viewport.toBottom();
301
- }
338
+ syncSessionSurface(forked, historyMessages);
302
339
 
303
340
  cleanPrompt();
304
- return `Forked into "${forked.title}" (${forked.messages.length} messages, ${forked.id}). Permissions and standing approvals were reset; any gated actions will request authorization anew.`;
341
+ return `Forked into "${cleanTitle(forked.title)}" (${forked.messages.length} messages, ${forked.id}). Permissions and standing approvals were reset; any gated actions will request authorization anew.`;
305
342
  }
306
343
 
307
344
  // Case 3: Switch to selected session
@@ -334,20 +371,8 @@ export async function runInteractiveSessionPicker(
334
371
  }
335
372
  }
336
373
 
337
- // Render the conversation history to the transcript & viewport
338
- const renderer = (prompt as any).renderer || (options.loop as any)?.connection?.renderer;
339
- if (renderer && typeof renderer.renderSessionHistory === 'function') {
340
- renderer.renderSessionHistory(historyMessages, {
341
- id: switched.id,
342
- title: switched.title,
343
- messagesCount: visibleHistoryCount(historyMessages)
344
- });
345
- }
346
-
347
- if ((prompt as any).surface?.viewport && typeof (prompt as any).surface.viewport.toBottom === 'function') {
348
- (prompt as any).surface.viewport.toBottom();
349
- }
374
+ syncSessionSurface(switched, historyMessages);
350
375
 
351
376
  cleanPrompt();
352
- return `Switched to "${switched.title}" (${switched.messages.length} messages, ${switched.id}).`;
377
+ return `Switched to "${cleanTitle(switched.title)}" (${switched.messages.length} messages, ${switched.id}).`;
353
378
  }
@@ -12,7 +12,7 @@ const INNER_HEADER_ROWS = 3; // scope, search, divider
12
12
  const INNER_DETAIL_ROWS = 3; // divider, selected title, metadata
13
13
  const MAX_PANEL_HEIGHT = 28;
14
14
  function clean(value) {
15
- return safeDisplay(typeof value === 'string' ? value : String(value ?? ''));
15
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? '')).replace(/[\r\n]+/g, ' ');
16
16
  }
17
17
  function sameWorkspace(first, second) {
18
18
  if (!first || !second)
@@ -22,7 +22,7 @@ function sameWorkspace(first, second) {
22
22
  return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
23
23
  }
24
24
  function rowPair(left, right, width) {
25
- const room = Math.max(0, Math.floor(width));
25
+ const room = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 60;
26
26
  const rightWidth = visibleWidth(right);
27
27
  if (rightWidth >= room - 5)
28
28
  return truncate(left, room, '…');
@@ -54,9 +54,13 @@ function actionOrSessionText(item, selected, width) {
54
54
  const marker = selected ? paint('accent', GLYPHS.arrow) : ' ';
55
55
  const leftPrefix = ` ${marker} `;
56
56
  const rawName = itemTitle(item);
57
+ const rawMsgs = Number(item.value.messageCount);
58
+ const safeMsgs = Number.isFinite(rawMsgs) ? Math.max(0, Math.floor(rawMsgs)) : 0;
59
+ const timeText = shortTime(item);
60
+ const metaCore = timeText ? `${safeMsgs} msgs ${GLYPHS.dot} ${timeText}` : `${safeMsgs} msgs`;
57
61
  const right = isAction
58
62
  ? dim(item.value.type === 'new' ? 'create' : 'branch')
59
- : dim(`${item.value.messageCount ?? 0} msgs ${GLYPHS.dot} ${shortTime(item)}${item.value.isCurrent ? ' ACTIVE' : ''}`);
63
+ : dim(`${metaCore}${item.value.isCurrent ? ' ACTIVE' : ''}`);
60
64
  const available = Math.max(1, width - visibleWidth(leftPrefix) - 1);
61
65
  // Keep titles legible on small terminals instead of allowing metadata to eat them.
62
66
  const showMeta = available >= 42;
@@ -72,22 +76,27 @@ function actionOrSessionText(item, selected, width) {
72
76
  */
73
77
  export function renderSessionRows(entries, start, selected, width, budget) {
74
78
  const rows = [];
75
- let lastIndex = start - 1;
79
+ const safeStart = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0;
80
+ const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 60;
81
+ const safeBudget = budget === Number.POSITIVE_INFINITY
82
+ ? entries.length
83
+ : (Number.isFinite(budget) ? Math.max(0, Math.floor(budget)) : 0);
84
+ let lastIndex = safeStart - 1;
76
85
  let previousCategory = null;
77
- for (let i = start; i < entries.length && rows.length < budget; i++) {
86
+ for (let i = safeStart; i < entries.length && rows.length < safeBudget; i++) {
78
87
  const item = entries[i].item;
79
88
  const category = clean(item.category || 'Sessions');
80
89
  const isNewGroup = category !== previousCategory;
81
90
  // Avoid leaving an orphaned header in the final available row.
82
- if (isNewGroup && budget - rows.length >= 2) {
83
- rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, width - 4), '…')}`));
91
+ if (isNewGroup && safeBudget - rows.length >= 2) {
92
+ rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, safeWidth - 4), '…')}`));
84
93
  }
85
94
  else if (isNewGroup && rows.length > 0) {
86
95
  break;
87
96
  }
88
- if (rows.length >= budget)
97
+ if (rows.length >= safeBudget)
89
98
  break;
90
- rows.push(actionOrSessionText(item, i === selected, width));
99
+ rows.push(actionOrSessionText(item, i === selected, safeWidth));
91
100
  lastIndex = i;
92
101
  previousCategory = category;
93
102
  }
@@ -149,21 +158,22 @@ export class SessionPickerLayer extends SelectLayer {
149
158
  return result;
150
159
  }
151
160
  body(width, height) {
152
- const w = Math.max(12, Math.floor(width));
153
- const h = Math.max(1, Math.floor(height));
161
+ const w = Math.max(12, Number.isFinite(width) ? Math.floor(width) : 60);
162
+ const h = Math.max(1, Number.isFinite(height) ? Math.floor(height) : 20);
154
163
  const rows = [];
155
164
  const scopeLabel = this.scope === 'all' ? 'ALL WORKSPACES' : 'THIS WORKSPACE';
156
165
  const total = this.allItems.filter(item => item.value.type === 'switch').length;
157
166
  const count = this.countSessions();
158
167
  rows.push(rowPair(` ${paint('accent', scopeLabel)}`, w >= 52 ? dim(`${count} / ${total} sessions`) : '', w));
159
- const query = String(this.list.query || '');
168
+ const query = clean(this.list.query || '');
160
169
  const lead = ` ${paint('accent', GLYPHS.arrow)} `;
161
170
  const maxInput = Math.max(1, w - visibleWidth(lead) - 1);
162
- let visibleQuery = query;
163
- // Show the tail of long queries so the edit caret stays near the typing point.
164
- while (visibleWidth(visibleQuery) > maxInput)
165
- visibleQuery = visibleQuery.slice(1);
166
- const shown = query ? clean(visibleQuery) : dim('Search by title, workspace or ID…');
171
+ // Show the tail of long queries without splitting UTF-16 surrogate pairs.
172
+ const runes = Array.from(query);
173
+ while (runes.length > 0 && visibleWidth(runes.join('')) > maxInput)
174
+ runes.shift();
175
+ const visibleQuery = runes.join('');
176
+ const shown = query ? visibleQuery : dim('Search by title, workspace or ID…');
167
177
  rows.push(lead + truncate(shown, maxInput, '…'));
168
178
  this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + (query ? visibleWidth(visibleQuery) : 0)), y: 1 };
169
179
  rows.push(paint('rule', '─'.repeat(w)));
@@ -178,8 +188,11 @@ export class SessionPickerLayer extends SelectLayer {
178
188
  rows.push(dim(' Try another title, ID, or workspace.'));
179
189
  }
180
190
  else {
181
- const selected = Math.max(0, Math.min(this.list.selected, entries.length - 1));
182
- let start = Math.max(0, Math.min(this.list.offset, selected));
191
+ const rawSel = Number.isFinite(this.list.selected) ? Math.floor(this.list.selected) : 0;
192
+ const rawOff = Number.isFinite(this.list.offset) ? Math.floor(this.list.offset) : 0;
193
+ const selected = Math.max(0, Math.min(rawSel, entries.length - 1));
194
+ this.list.selected = selected;
195
+ let start = Math.max(0, Math.min(rawOff, selected));
183
196
  let output = renderSessionRows(entries, start, selected, w, available);
184
197
  while (output.lastIndex < selected && start < selected) {
185
198
  start++;
@@ -25,7 +25,7 @@ const INNER_DETAIL_ROWS = 3; // divider, selected title, metadata
25
25
  const MAX_PANEL_HEIGHT = 28;
26
26
 
27
27
  function clean(value: unknown): string {
28
- return safeDisplay(typeof value === 'string' ? value : String(value ?? ''));
28
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? '')).replace(/[\r\n]+/g, ' ');
29
29
  }
30
30
 
31
31
  function sameWorkspace(first: string | undefined, second: string): boolean {
@@ -36,7 +36,7 @@ function sameWorkspace(first: string | undefined, second: string): boolean {
36
36
  }
37
37
 
38
38
  function rowPair(left: string, right: string, width: number): string {
39
- const room = Math.max(0, Math.floor(width));
39
+ const room = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 60;
40
40
  const rightWidth = visibleWidth(right);
41
41
  if (rightWidth >= room - 5) return truncate(left, room, '…');
42
42
  const safeLeft = truncate(left, Math.max(0, room - rightWidth - 2), '…');
@@ -64,9 +64,13 @@ function actionOrSessionText(item: SessionPickerItem, selected: boolean, width:
64
64
  const marker = selected ? paint('accent', GLYPHS.arrow) : ' ';
65
65
  const leftPrefix = ` ${marker} `;
66
66
  const rawName = itemTitle(item);
67
+ const rawMsgs = Number(item.value.messageCount);
68
+ const safeMsgs = Number.isFinite(rawMsgs) ? Math.max(0, Math.floor(rawMsgs)) : 0;
69
+ const timeText = shortTime(item);
70
+ const metaCore = timeText ? `${safeMsgs} msgs ${GLYPHS.dot} ${timeText}` : `${safeMsgs} msgs`;
67
71
  const right = isAction
68
72
  ? dim(item.value.type === 'new' ? 'create' : 'branch')
69
- : dim(`${item.value.messageCount ?? 0} msgs ${GLYPHS.dot} ${shortTime(item)}${item.value.isCurrent ? ' ACTIVE' : ''}`);
73
+ : dim(`${metaCore}${item.value.isCurrent ? ' ACTIVE' : ''}`);
70
74
  const available = Math.max(1, width - visibleWidth(leftPrefix) - 1);
71
75
  // Keep titles legible on small terminals instead of allowing metadata to eat them.
72
76
  const showMeta = available >= 42;
@@ -91,20 +95,25 @@ export function renderSessionRows(
91
95
  budget: number
92
96
  ): ListWindow {
93
97
  const rows: string[] = [];
94
- let lastIndex = start - 1;
98
+ const safeStart = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0;
99
+ const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 60;
100
+ const safeBudget = budget === Number.POSITIVE_INFINITY
101
+ ? entries.length
102
+ : (Number.isFinite(budget) ? Math.max(0, Math.floor(budget)) : 0);
103
+ let lastIndex = safeStart - 1;
95
104
  let previousCategory: string | null = null;
96
- for (let i = start; i < entries.length && rows.length < budget; i++) {
105
+ for (let i = safeStart; i < entries.length && rows.length < safeBudget; i++) {
97
106
  const item = entries[i]!.item;
98
107
  const category = clean(item.category || 'Sessions');
99
108
  const isNewGroup = category !== previousCategory;
100
109
  // Avoid leaving an orphaned header in the final available row.
101
- if (isNewGroup && budget - rows.length >= 2) {
102
- rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, width - 4), '…')}`));
110
+ if (isNewGroup && safeBudget - rows.length >= 2) {
111
+ rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, safeWidth - 4), '…')}`));
103
112
  } else if (isNewGroup && rows.length > 0) {
104
113
  break;
105
114
  }
106
- if (rows.length >= budget) break;
107
- rows.push(actionOrSessionText(item, i === selected, width));
115
+ if (rows.length >= safeBudget) break;
116
+ rows.push(actionOrSessionText(item, i === selected, safeWidth));
108
117
  lastIndex = i;
109
118
  previousCategory = category;
110
119
  }
@@ -187,21 +196,22 @@ export class SessionPickerLayer extends SelectLayer {
187
196
  }
188
197
 
189
198
  body(width: number, height: number): string[] {
190
- const w = Math.max(12, Math.floor(width));
191
- const h = Math.max(1, Math.floor(height));
199
+ const w = Math.max(12, Number.isFinite(width) ? Math.floor(width) : 60);
200
+ const h = Math.max(1, Number.isFinite(height) ? Math.floor(height) : 20);
192
201
  const rows: string[] = [];
193
202
  const scopeLabel = this.scope === 'all' ? 'ALL WORKSPACES' : 'THIS WORKSPACE';
194
203
  const total = this.allItems.filter(item => item.value.type === 'switch').length;
195
204
  const count = this.countSessions();
196
205
 
197
206
  rows.push(rowPair(` ${paint('accent', scopeLabel)}`, w >= 52 ? dim(`${count} / ${total} sessions`) : '', w));
198
- const query = String(this.list.query || '');
207
+ const query = clean(this.list.query || '');
199
208
  const lead = ` ${paint('accent', GLYPHS.arrow)} `;
200
209
  const maxInput = Math.max(1, w - visibleWidth(lead) - 1);
201
- let visibleQuery = query;
202
- // Show the tail of long queries so the edit caret stays near the typing point.
203
- while (visibleWidth(visibleQuery) > maxInput) visibleQuery = visibleQuery.slice(1);
204
- const shown = query ? clean(visibleQuery) : dim('Search by title, workspace or ID…');
210
+ // Show the tail of long queries without splitting UTF-16 surrogate pairs.
211
+ const runes = Array.from(query);
212
+ while (runes.length > 0 && visibleWidth(runes.join('')) > maxInput) runes.shift();
213
+ const visibleQuery = runes.join('');
214
+ const shown = query ? visibleQuery : dim('Search by title, workspace or ID…');
205
215
  rows.push(lead + truncate(shown, maxInput, '…'));
206
216
  this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + (query ? visibleWidth(visibleQuery) : 0)), y: 1 };
207
217
  rows.push(paint('rule', '─'.repeat(w)));
@@ -214,8 +224,11 @@ export class SessionPickerLayer extends SelectLayer {
214
224
  if (rows.length < h - INNER_DETAIL_ROWS) rows.push(dim(' No sessions match this search.'));
215
225
  if (rows.length < h - INNER_DETAIL_ROWS) rows.push(dim(' Try another title, ID, or workspace.'));
216
226
  } else {
217
- const selected = Math.max(0, Math.min(this.list.selected, entries.length - 1));
218
- let start = Math.max(0, Math.min(this.list.offset, selected));
227
+ const rawSel = Number.isFinite(this.list.selected) ? Math.floor(this.list.selected) : 0;
228
+ const rawOff = Number.isFinite(this.list.offset) ? Math.floor(this.list.offset) : 0;
229
+ const selected = Math.max(0, Math.min(rawSel, entries.length - 1));
230
+ this.list.selected = selected;
231
+ let start = Math.max(0, Math.min(rawOff, selected));
219
232
  let output = renderSessionRows(entries, start, selected, w, available);
220
233
  while (output.lastIndex < selected && start < selected) {
221
234
  start++;