@causyne/agent 1.20.112 → 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,6 +4,14 @@ import { calculateThinkingLineCount, DEFAULT_MAX_EXPANDED_LINES, renderThinkingF
4
4
  import { formatElapsed } from './statusLine.js';
5
5
  import { markerAt } from './messageInteraction.js';
6
6
  import { AdaptiveWheelDampener } from './scrollInteraction.js';
7
+ import { safeDisplay } from './text.js';
8
+ function stripTrailingEllipsisText(value) {
9
+ let text = value.trim();
10
+ while (text.endsWith('…') || text.endsWith('...')) {
11
+ text = (text.endsWith('...') ? text.slice(0, -3) : text.slice(0, -1)).trimEnd();
12
+ }
13
+ return text;
14
+ }
7
15
  function lastStart(event) {
8
16
  return Math.max(0, codePreviewLineCount(event) - CODE_PANEL_LINES);
9
17
  }
@@ -30,15 +38,19 @@ export class CodeStreamRenderer extends ChatRenderer {
30
38
  * so the running-light shimmer advances smoothly across both surfaces.
31
39
  */
32
40
  onStatusTick(nowMs, tick) {
33
- this.streamingNowMs = nowMs;
34
- this.streamingTick = tick;
41
+ if (!Number.isFinite(nowMs))
42
+ return;
43
+ this.streamingNowMs = Math.max(0, nowMs);
44
+ if (tick === undefined || Number.isFinite(tick)) {
45
+ this.streamingTick = tick === undefined ? undefined : Math.max(0, Math.floor(tick));
46
+ }
35
47
  const transcript = this.transcript;
36
48
  if (!transcript || !Array.isArray(transcript.frames))
37
49
  return;
38
50
  const activeFrame = transcript.frames.findLast((f) => f?.meta?.reasoning === true && f.meta?.streaming === true);
39
51
  if (activeFrame && activeFrame.meta) {
40
- if (nowMs > 0) {
41
- activeFrame.meta.durationText = formatElapsed(nowMs);
52
+ if (this.streamingNowMs > 0) {
53
+ activeFrame.meta.durationText = formatElapsed(this.streamingNowMs);
42
54
  }
43
55
  activeFrame.rows = null;
44
56
  activeFrame.renderedWidth = -1;
@@ -103,6 +115,7 @@ export class CodeStreamRenderer extends ChatRenderer {
103
115
  if (next === state.start)
104
116
  return true;
105
117
  state.start = next;
118
+ state.userScrolled = true;
106
119
  state.followTail = next === limit;
107
120
  frame.rows = null;
108
121
  frame.renderedWidth = -1;
@@ -128,8 +141,28 @@ export class CodeStreamRenderer extends ChatRenderer {
128
141
  if (!frame || frame.meta?.reasoning !== true || frame.meta?.collapsed)
129
142
  return false;
130
143
  const content = typeof frame.meta.content === 'string' ? frame.meta.content : '';
131
- const totalLines = calculateThinkingLineCount(content, this.measure());
132
- const limit = Math.max(0, totalLines - DEFAULT_MAX_EXPANDED_LINES);
144
+ const renderedMainWidth = (typeof frame.renderedWidth === 'number' && Number.isFinite(frame.renderedWidth) && frame.renderedWidth > 0)
145
+ ? frame.renderedWidth
146
+ : (typeof surface?.viewport?.viewWidth === 'number' && Number.isFinite(surface.viewport.viewWidth) && surface.viewport.viewWidth > 0)
147
+ ? surface.viewport.viewWidth
148
+ : 0;
149
+ const prevForcedWidth = this.forcedWidth;
150
+ if (renderedMainWidth > 0 && !prevForcedWidth) {
151
+ this.forcedWidth = renderedMainWidth;
152
+ }
153
+ let measureWidth;
154
+ try {
155
+ measureWidth = this.measure();
156
+ }
157
+ finally {
158
+ this.forcedWidth = prevForcedWidth;
159
+ }
160
+ const totalLines = calculateThinkingLineCount(content, measureWidth);
161
+ const rawMaxVisible = Number(frame.meta.maxVisibleLines);
162
+ const maxVisibleLines = Number.isFinite(rawMaxVisible) && rawMaxVisible >= 1
163
+ ? Math.floor(rawMaxVisible)
164
+ : DEFAULT_MAX_EXPANDED_LINES;
165
+ const limit = Math.max(0, totalLines - maxVisibleLines);
133
166
  if (limit === 0)
134
167
  return false;
135
168
  if (!frame.meta._dampener) {
@@ -190,9 +223,9 @@ export class CodeStreamRenderer extends ChatRenderer {
190
223
  handle(message) {
191
224
  const selfStatus = this;
192
225
  if (message?.type === 'agent_activity') {
193
- const rawActivity = String(message.activity || message.message || '').trim();
226
+ const rawActivity = safeDisplay(String(message.activity || message.message || '')).replace(/\s+/g, ' ').trim();
194
227
  if (rawActivity) {
195
- this.currentActivity = rawActivity.replace(/…|\.\.\.$/, '').trim();
228
+ this.currentActivity = stripTrailingEllipsisText(rawActivity);
196
229
  if (this._activeReasoning && this.lastReasoning) {
197
230
  super.onAgentReasoning({
198
231
  content: this.lastReasoning,
@@ -206,7 +239,11 @@ export class CodeStreamRenderer extends ChatRenderer {
206
239
  }
207
240
  return true;
208
241
  }
209
- const handled = super.handle(message);
242
+ const handled = super.handle({
243
+ ...message,
244
+ activity: rawActivity,
245
+ message: rawActivity
246
+ });
210
247
  if (selfStatus.quietStatus) {
211
248
  selfStatus.currentStatus = rawActivity;
212
249
  selfStatus.onStatusChange?.(rawActivity);
@@ -216,7 +253,7 @@ export class CodeStreamRenderer extends ChatRenderer {
216
253
  }
217
254
  if (message?.type === 'notice' && message.nativeStep === true) {
218
255
  this.stepCount = (this.stepCount || 0) + 1;
219
- const stepLine = String(message.message || '').trim();
256
+ const stepLine = safeDisplay(String(message.message || '')).replace(/\s+/g, ' ').trim();
220
257
  if (stepLine) {
221
258
  const actionName = String(message.actionName || stepLine).toLowerCase();
222
259
  let activity = this.currentActivity || 'processing';
@@ -266,8 +303,8 @@ export class CodeStreamRenderer extends ChatRenderer {
266
303
  this._activeReasoning = false;
267
304
  }
268
305
  if (this.activeCode && this.transcript) {
269
- const note = content.trim().split('\n').at(-1) || '';
270
- this.modelNote = note.slice(-140);
306
+ const note = safeDisplay(content).trim().split('\n').at(-1) || '';
307
+ this.modelNote = Array.from(note).slice(-140).join('');
271
308
  this.paintCodePanel(this.activeCode);
272
309
  if (message.streaming === false) {
273
310
  this.lastReasoning = '';
@@ -327,7 +364,8 @@ export class CodeStreamRenderer extends ChatRenderer {
327
364
  if (!this.transcript && event.phase === 'draft')
328
365
  return;
329
366
  if (this.lastReasoning && !this.modelNote) {
330
- this.modelNote = (this.lastReasoning.trim().split('\n').at(-1) || '').slice(-140);
367
+ const lastLine = safeDisplay(this.lastReasoning).trim().split('\n').at(-1) || '';
368
+ this.modelNote = Array.from(lastLine).slice(-140).join('');
331
369
  }
332
370
  if (this._activeReasoning) {
333
371
  super.onAgentReasoning({ content: this.lastReasoning, streaming: false });
@@ -360,6 +398,7 @@ export class CodeStreamRenderer extends ChatRenderer {
360
398
  }
361
399
  }
362
400
  const state = targetFrame ? this.codePanels.get(targetFrame) : undefined;
401
+ const transitionedToEdit = Boolean(state && event.operation === 'Editing' && state.event.operation !== 'Editing');
363
402
  const panelState = state || {
364
403
  event,
365
404
  modelNote: this.modelNote,
@@ -368,7 +407,13 @@ export class CodeStreamRenderer extends ChatRenderer {
368
407
  };
369
408
  panelState.event = event;
370
409
  panelState.modelNote = this.modelNote;
371
- panelState.start = panelState.followTail ? lastStart(event) : Math.min(panelState.start, lastStart(event));
410
+ if (transitionedToEdit && !panelState.userScrolled) {
411
+ panelState.followTail = false;
412
+ panelState.start = defaultPreviewStart(event);
413
+ }
414
+ else {
415
+ panelState.start = panelState.followTail ? lastStart(event) : Math.min(panelState.start, lastStart(event));
416
+ }
372
417
  const produce = () => {
373
418
  for (const row of renderCodeProgress(panelState.event, this.measure(), panelState.modelNote, panelState.start))
374
419
  this.write(row);
@@ -4,6 +4,15 @@ import { calculateThinkingLineCount, DEFAULT_MAX_EXPANDED_LINES, renderThinkingF
4
4
  import { formatElapsed, type StatusLine } from './statusLine.js';
5
5
  import { markerAt } from './messageInteraction.js';
6
6
  import { AdaptiveWheelDampener } from './scrollInteraction.js';
7
+ import { safeDisplay } from './text.js';
8
+
9
+ function stripTrailingEllipsisText(value: string): string {
10
+ let text = value.trim();
11
+ while (text.endsWith('…') || text.endsWith('...')) {
12
+ text = (text.endsWith('...') ? text.slice(0, -3) : text.slice(0, -1)).trimEnd();
13
+ }
14
+ return text;
15
+ }
7
16
 
8
17
  type RendererEvent = { type: string; [key: string]: unknown };
9
18
  type CodePanelState = {
@@ -11,6 +20,7 @@ type CodePanelState = {
11
20
  modelNote: string;
12
21
  start: number;
13
22
  followTail: boolean;
23
+ userScrolled?: boolean;
14
24
  dampener?: AdaptiveWheelDampener;
15
25
  };
16
26
  type CodeFrame = { id: number; meta?: Record<string, unknown> | null; rows?: string[] | null; renderedWidth?: number; produce?: (width: number) => string[] };
@@ -57,16 +67,19 @@ export class CodeStreamRenderer extends ChatRenderer {
57
67
  * so the running-light shimmer advances smoothly across both surfaces.
58
68
  */
59
69
  onStatusTick(nowMs: number, tick?: number): void {
60
- this.streamingNowMs = nowMs;
61
- this.streamingTick = tick;
70
+ if (!Number.isFinite(nowMs)) return;
71
+ this.streamingNowMs = Math.max(0, nowMs);
72
+ if (tick === undefined || Number.isFinite(tick)) {
73
+ this.streamingTick = tick === undefined ? undefined : Math.max(0, Math.floor(tick));
74
+ }
62
75
  const transcript = this.transcript as unknown as CodeTranscript | null;
63
76
  if (!transcript || !Array.isArray(transcript.frames)) return;
64
77
  const activeFrame = transcript.frames.findLast(
65
78
  (f: CodeFrame) => f?.meta?.reasoning === true && f.meta?.streaming === true
66
79
  );
67
80
  if (activeFrame && activeFrame.meta) {
68
- if (nowMs > 0) {
69
- activeFrame.meta.durationText = formatElapsed(nowMs);
81
+ if (this.streamingNowMs > 0) {
82
+ activeFrame.meta.durationText = formatElapsed(this.streamingNowMs);
70
83
  }
71
84
  activeFrame.rows = null;
72
85
  activeFrame.renderedWidth = -1;
@@ -145,6 +158,7 @@ export class CodeStreamRenderer extends ChatRenderer {
145
158
  if (next === state.start) return true;
146
159
 
147
160
  state.start = next;
161
+ state.userScrolled = true;
148
162
  state.followTail = next === limit;
149
163
  frame.rows = null;
150
164
  frame.renderedWidth = -1;
@@ -169,8 +183,27 @@ export class CodeStreamRenderer extends ChatRenderer {
169
183
  if (!frame || frame.meta?.reasoning !== true || frame.meta?.collapsed) return false;
170
184
 
171
185
  const content = typeof frame.meta.content === 'string' ? frame.meta.content : '';
172
- const totalLines = calculateThinkingLineCount(content, this.measure());
173
- const limit = Math.max(0, totalLines - DEFAULT_MAX_EXPANDED_LINES);
186
+ const renderedMainWidth = (typeof frame.renderedWidth === 'number' && Number.isFinite(frame.renderedWidth) && frame.renderedWidth > 0)
187
+ ? frame.renderedWidth
188
+ : (typeof surface?.viewport?.viewWidth === 'number' && Number.isFinite(surface.viewport.viewWidth) && surface.viewport.viewWidth > 0)
189
+ ? surface.viewport.viewWidth
190
+ : 0;
191
+ const prevForcedWidth = (this as any).forcedWidth;
192
+ if (renderedMainWidth > 0 && !prevForcedWidth) {
193
+ (this as any).forcedWidth = renderedMainWidth;
194
+ }
195
+ let measureWidth: number;
196
+ try {
197
+ measureWidth = this.measure();
198
+ } finally {
199
+ (this as any).forcedWidth = prevForcedWidth;
200
+ }
201
+ const totalLines = calculateThinkingLineCount(content, measureWidth);
202
+ const rawMaxVisible = Number(frame.meta.maxVisibleLines);
203
+ const maxVisibleLines = Number.isFinite(rawMaxVisible) && rawMaxVisible >= 1
204
+ ? Math.floor(rawMaxVisible)
205
+ : DEFAULT_MAX_EXPANDED_LINES;
206
+ const limit = Math.max(0, totalLines - maxVisibleLines);
174
207
  if (limit === 0) return false;
175
208
 
176
209
  if (!frame.meta._dampener) {
@@ -239,9 +272,9 @@ export class CodeStreamRenderer extends ChatRenderer {
239
272
  };
240
273
 
241
274
  if (message?.type === 'agent_activity') {
242
- const rawActivity = String((message as any).activity || (message as any).message || '').trim();
275
+ const rawActivity = safeDisplay(String((message as any).activity || (message as any).message || '')).replace(/\s+/g, ' ').trim();
243
276
  if (rawActivity) {
244
- this.currentActivity = rawActivity.replace(/…|\.\.\.$/, '').trim();
277
+ this.currentActivity = stripTrailingEllipsisText(rawActivity);
245
278
  if (this._activeReasoning && this.lastReasoning) {
246
279
  super.onAgentReasoning({
247
280
  content: this.lastReasoning,
@@ -255,7 +288,11 @@ export class CodeStreamRenderer extends ChatRenderer {
255
288
  }
256
289
  return true;
257
290
  }
258
- const handled = super.handle(message);
291
+ const handled = super.handle({
292
+ ...message,
293
+ activity: rawActivity,
294
+ message: rawActivity
295
+ });
259
296
  if (selfStatus.quietStatus) {
260
297
  selfStatus.currentStatus = rawActivity;
261
298
  selfStatus.onStatusChange?.(rawActivity);
@@ -266,7 +303,7 @@ export class CodeStreamRenderer extends ChatRenderer {
266
303
 
267
304
  if (message?.type === 'notice' && message.nativeStep === true) {
268
305
  this.stepCount = (this.stepCount || 0) + 1;
269
- const stepLine = String(message.message || '').trim();
306
+ const stepLine = safeDisplay(String(message.message || '')).replace(/\s+/g, ' ').trim();
270
307
  if (stepLine) {
271
308
  const actionName = String((message as any).actionName || stepLine).toLowerCase();
272
309
  let activity = this.currentActivity || 'processing';
@@ -314,8 +351,8 @@ export class CodeStreamRenderer extends ChatRenderer {
314
351
  this._activeReasoning = false;
315
352
  }
316
353
  if (this.activeCode && this.transcript) {
317
- const note = content.trim().split('\n').at(-1) || '';
318
- this.modelNote = note.slice(-140);
354
+ const note = safeDisplay(content).trim().split('\n').at(-1) || '';
355
+ this.modelNote = Array.from(note).slice(-140).join('');
319
356
  this.paintCodePanel(this.activeCode);
320
357
  if (message.streaming === false) {
321
358
  this.lastReasoning = '';
@@ -373,7 +410,8 @@ export class CodeStreamRenderer extends ChatRenderer {
373
410
  || typeof event.description !== 'string' || !['draft', 'working', 'done', 'failed'].includes(event.phase)) return;
374
411
  if (!this.transcript && event.phase === 'draft') return;
375
412
  if (this.lastReasoning && !this.modelNote) {
376
- this.modelNote = (this.lastReasoning.trim().split('\n').at(-1) || '').slice(-140);
413
+ const lastLine = safeDisplay(this.lastReasoning).trim().split('\n').at(-1) || '';
414
+ this.modelNote = Array.from(lastLine).slice(-140).join('');
377
415
  }
378
416
  if (this._activeReasoning) {
379
417
  super.onAgentReasoning({ content: this.lastReasoning, streaming: false });
@@ -408,6 +446,7 @@ export class CodeStreamRenderer extends ChatRenderer {
408
446
  }
409
447
 
410
448
  const state = targetFrame ? this.codePanels.get(targetFrame) : undefined;
449
+ const transitionedToEdit = Boolean(state && event.operation === 'Editing' && state.event.operation !== 'Editing');
411
450
  const panelState: CodePanelState = state || {
412
451
  event,
413
452
  modelNote: this.modelNote,
@@ -416,7 +455,12 @@ export class CodeStreamRenderer extends ChatRenderer {
416
455
  };
417
456
  panelState.event = event;
418
457
  panelState.modelNote = this.modelNote;
419
- panelState.start = panelState.followTail ? lastStart(event) : Math.min(panelState.start, lastStart(event));
458
+ if (transitionedToEdit && !panelState.userScrolled) {
459
+ panelState.followTail = false;
460
+ panelState.start = defaultPreviewStart(event);
461
+ } else {
462
+ panelState.start = panelState.followTail ? lastStart(event) : Math.min(panelState.start, lastStart(event));
463
+ }
420
464
  const produce = (): void => {
421
465
  for (const row of renderCodeProgress(panelState.event, this.measure(), panelState.modelNote, panelState.start)) this.write(row);
422
466
  };
@@ -1,11 +1,18 @@
1
+ import { safeDisplay } from './text.js';
1
2
  /** Local session and MCP feedback belongs in a dialog, never a chat turn. */
2
3
  export function commandDialog(input, result) {
4
+ if (typeof input !== 'string' || !result || typeof result !== 'object')
5
+ return null;
3
6
  const command = /^\/(sessions?|mcp)(?:\s|$)/iu.exec(input.trim())?.[1]?.toLowerCase();
4
7
  if (!command || ['silent', 'pick-session', 'pick-mcp', 'invoke-skill', 'exit'].includes(result.effect || ''))
5
8
  return null;
9
+ const defaultTitle = command === 'mcp' ? 'MCP servers' : 'Sessions';
10
+ const cleanTitle = typeof result.title === 'string'
11
+ ? safeDisplay(result.title).replace(/\s+/g, ' ').trim()
12
+ : '';
6
13
  return {
7
- title: result.title || (command === 'mcp' ? 'MCP servers' : 'Sessions'),
8
- text: result.output || '',
14
+ title: cleanTitle || defaultTitle,
15
+ text: typeof result.output === 'string' ? safeDisplay(result.output) : '',
9
16
  danger: result.ok === false
10
17
  };
11
18
  }
@@ -1,3 +1,5 @@
1
+ import { safeDisplay } from './text.js';
2
+
1
3
  export interface CommandPresentationResult {
2
4
  ok?: boolean;
3
5
  effect?: string;
@@ -8,11 +10,16 @@ export interface CommandPresentationResult {
8
10
  /** Local session and MCP feedback belongs in a dialog, never a chat turn. */
9
11
  export function commandDialog(input: string, result: CommandPresentationResult):
10
12
  { title: string; text: string; danger: boolean } | null {
13
+ if (typeof input !== 'string' || !result || typeof result !== 'object') return null;
11
14
  const command = /^\/(sessions?|mcp)(?:\s|$)/iu.exec(input.trim())?.[1]?.toLowerCase();
12
15
  if (!command || ['silent', 'pick-session', 'pick-mcp', 'invoke-skill', 'exit'].includes(result.effect || '')) return null;
16
+ const defaultTitle = command === 'mcp' ? 'MCP servers' : 'Sessions';
17
+ const cleanTitle = typeof result.title === 'string'
18
+ ? safeDisplay(result.title).replace(/\s+/g, ' ').trim()
19
+ : '';
13
20
  return {
14
- title: result.title || (command === 'mcp' ? 'MCP servers' : 'Sessions'),
15
- text: result.output || '',
21
+ title: cleanTitle || defaultTitle,
22
+ text: typeof result.output === 'string' ? safeDisplay(result.output) : '',
16
23
  danger: result.ok === false
17
24
  };
18
25
  }
@@ -184,7 +184,11 @@ function commandItems(query = '') {
184
184
  const needle = query.toLowerCase();
185
185
  if (needle.length < SKILL_QUERY_MIN) return commands;
186
186
  const skills = listSkillsForCompletion()
187
- .filter((skill) => String(skill.id || '').toLowerCase().includes(needle))
187
+ .filter((skill) =>
188
+ isTerminalSafe(skill.id) &&
189
+ isTerminalSafe(skill.domain) &&
190
+ String(skill.id || '').toLowerCase().includes(needle)
191
+ )
188
192
  .map((skill) => ({
189
193
  value: `/skills ${skill.domain}/${skill.id}`,
190
194
  match: skill.id,
@@ -312,14 +316,21 @@ function directoryItems(root, partial) {
312
316
  // Trigger detection
313
317
  // ---------------------------------------------------------------------------
314
318
 
319
+ function clampCursor(text, cursor) {
320
+ if (!Number.isFinite(cursor)) return text.length;
321
+ return Math.max(0, Math.min(text.length, Math.floor(cursor)));
322
+ }
323
+
315
324
  /**
316
325
  * Find a slash command or @ reference at the current caret position.
317
326
  * Slash detection works at any whitespace-delimited token boundary. Execution
318
327
  * remains exclusive to explicit selection; normal prompt dispatch is unchanged.
319
328
  */
320
329
  export function detectTrigger(text, cursor) {
321
- const before = text.slice(0, cursor);
322
- const slash = detectInlineSlashTrigger(text, cursor);
330
+ const input = String(text == null ? '' : text);
331
+ const pos = clampCursor(input, cursor);
332
+ const before = input.slice(0, pos);
333
+ const slash = detectInlineSlashTrigger(input, pos);
323
334
  if (slash) return slash;
324
335
 
325
336
  // 1. Quoted @ file mention: @"pixel2d games/ or @'pixel2d games/
@@ -331,7 +342,7 @@ export function detectTrigger(text, cursor) {
331
342
  return {
332
343
  kind: 'file',
333
344
  quote,
334
- start: cursor - query.length - 2, // accounts for @ and quote char
345
+ start: pos - query.length - 2, // accounts for @ and quote char
335
346
  query
336
347
  };
337
348
  }
@@ -342,7 +353,7 @@ export function detectTrigger(text, cursor) {
342
353
  return {
343
354
  kind: 'file',
344
355
  quote: null,
345
- start: cursor - mention[1].length - 1,
356
+ start: pos - mention[1].length - 1,
346
357
  query: mention[1]
347
358
  };
348
359
  }
@@ -373,17 +384,20 @@ export function suggest(text, cursor, options = {}) {
373
384
 
374
385
  const root = options.root || process.cwd();
375
386
  const index = options.index;
376
- const focusDir = options.focusDir || null;
387
+ const rawFocusDir = options.focusDir ? String(options.focusDir).replace(/\/+$/, '') : null;
388
+ const focusDir = rawFocusDir && isTerminalSafe(rawFocusDir) ? rawFocusDir : null;
377
389
  if (index) void index.ensure();
378
390
 
379
391
  let pool;
380
392
  if (index && index.isReady && trigger.query) {
381
- pool = index.candidates(trigger.query).map((relative) => ({
382
- value: relative,
383
- match: relative,
384
- label: relative,
385
- description: relative.endsWith('/') ? 'directory' : ''
386
- }));
393
+ pool = index.candidates(trigger.query)
394
+ .filter((relative) => isTerminalSafe(relative))
395
+ .map((relative) => ({
396
+ value: relative,
397
+ match: relative,
398
+ label: relative,
399
+ description: relative.endsWith('/') ? 'directory' : ''
400
+ }));
387
401
  } else {
388
402
  pool = directoryItems(root, trigger.query);
389
403
  if (focusDir) {
@@ -414,24 +428,27 @@ export function suggest(text, cursor, options = {}) {
414
428
 
415
429
  /** Replace the trigger span with the chosen value. */
416
430
  export function applyCompletion(text, cursor, trigger, item) {
431
+ const input = String(text == null ? '' : text);
432
+ const pos = clampCursor(input, cursor);
433
+ const start = Math.max(0, Math.min(pos, Number.isFinite(trigger?.start) ? Math.floor(trigger.start) : 0));
417
434
  if (trigger.kind === 'command-argument') {
418
- const head = text.slice(0, trigger.start);
419
- const tail = text.slice(cursor);
435
+ const head = input.slice(0, start);
436
+ const tail = input.slice(pos);
420
437
  const complete = item.value.includes('/');
421
438
  const replaced = head + item.value + (complete ? ' ' : '');
422
439
  return { text: replaced + tail, cursor: replaced.length };
423
440
  }
424
441
 
425
442
  if (trigger.kind === 'command') {
426
- const head = text.slice(0, trigger.start);
427
- const tail = text.slice(cursor);
443
+ const head = input.slice(0, start);
444
+ const tail = input.slice(pos);
428
445
  const replaced = head + item.value + ' ';
429
446
  return { text: replaced + tail, cursor: replaced.length };
430
447
  }
431
448
 
432
449
  // trigger.kind === 'file'
433
- const head = text.slice(0, trigger.start);
434
- const tail = text.slice(cursor);
450
+ const head = input.slice(0, start);
451
+ const tail = input.slice(pos);
435
452
  const isDir = item.value.endsWith('/');
436
453
  const hasSpace = item.value.includes(' ');
437
454
  const quote = trigger.quote || (hasSpace ? '"' : '');
@@ -459,12 +476,17 @@ export function applyCompletion(text, cursor, trigger, item) {
459
476
 
460
477
  /** Rows for the picker, already bounded and safe to print. */
461
478
  export function renderPicker(items, selected, width) {
462
- const start = Math.max(0, Math.min(selected - MAX_VISIBLE + 1, items.length - MAX_VISIBLE));
463
- const window = items.slice(Math.max(0, start), Math.max(0, start) + MAX_VISIBLE);
479
+ if (!Array.isArray(items) || items.length === 0) return [];
480
+ const safeSelected = Number.isFinite(selected)
481
+ ? Math.max(0, Math.min(items.length - 1, Math.floor(selected)))
482
+ : 0;
483
+ const start = Math.max(0, Math.min(safeSelected - MAX_VISIBLE + 1, items.length - MAX_VISIBLE));
484
+ const window = items.slice(start, start + MAX_VISIBLE);
485
+ const cleanSingleLine = (text) => sanitize(String(text == null ? '' : text)).replace(/[\r\n]+/g, ' ');
464
486
  return window.map((item, offset) => ({
465
487
  item,
466
- selected: Math.max(0, start) + offset === selected,
467
- label: shortenHome(item.label),
468
- description: item.description || ''
488
+ selected: start + offset === safeSelected,
489
+ label: cleanSingleLine(shortenHome(String(item?.label ?? item?.value ?? ''))),
490
+ description: cleanSingleLine(item?.description ?? '')
469
491
  }));
470
492
  }
@@ -26,21 +26,31 @@ export function openModeControl(prompt, loop) {
26
26
  }
27
27
  }));
28
28
  }
29
+ function splitModelVariant(model) {
30
+ if (!model.endsWith(')'))
31
+ return null;
32
+ const openIndex = model.lastIndexOf(' (');
33
+ if (openIndex < 0)
34
+ return null;
35
+ const variant = model.slice(openIndex + 2, -1);
36
+ if (!variant || variant.includes('(') || variant.includes(')'))
37
+ return null;
38
+ return { base: model.slice(0, openIndex), variant };
39
+ }
29
40
  /** Only offer sibling variants the selected provider actually advertises. */
30
41
  export function availableModelVariants(config) {
31
- const current = String(config.model || '');
32
- const match = current.match(/^(.*)\s\(([^()]+)\)$/);
33
- if (!match)
42
+ if (!config || typeof config !== 'object')
43
+ return [];
44
+ const current = typeof config.model === 'string' ? config.model : String(config.model ?? '');
45
+ const parsed = splitModelVariant(current);
46
+ if (!parsed)
34
47
  return [];
35
48
  const overview = getAvailableProvidersOverview(config);
36
- const provider = String(config.provider || '');
49
+ const provider = typeof config.provider === 'string' ? config.provider : String(config.provider ?? '');
37
50
  const advertised = overview.acp.find(peer => peer.providerKey === provider)?.models
38
51
  ?? overview.byok.find(item => item.id === provider)?.models
39
52
  ?? [];
40
- return advertised.filter(model => {
41
- const sibling = model.match(/^(.*)\s\(([^()]+)\)$/);
42
- return sibling?.[1] === match[1];
43
- });
53
+ return advertised.filter(model => splitModelVariant(model)?.base === parsed.base);
44
54
  }
45
55
  export function openVariantControl(prompt) {
46
56
  const config = loadConfig();
@@ -50,18 +60,19 @@ export function openVariantControl(prompt) {
50
60
  prompt.scheduleDraw();
51
61
  return;
52
62
  }
63
+ const provider = typeof config.provider === 'string' ? config.provider.trim() : '';
53
64
  prompt.openLayer(new SelectLayer({
54
65
  title: 'Model variant',
55
66
  items: variants.map(model => ({
56
67
  id: model,
57
68
  label: `${model}${model === config.model ? ' (active)' : ''}`,
58
- description: String(config.provider || ''),
69
+ description: provider,
59
70
  value: model
60
71
  })),
61
72
  onPick: (item) => {
62
73
  if (!item?.value || item.value === config.model)
63
74
  return;
64
- prompt.deliver(`/model ${String(config.provider)}/${item.value}`);
75
+ prompt.deliver(provider ? `/model ${provider}/${item.value}` : `/model ${item.value}`);
65
76
  prompt.notice = 'Model variant change queued';
66
77
  prompt.scheduleDraw();
67
78
  }
@@ -39,20 +39,27 @@ export function openModeControl(prompt: ControlPrompt, loop: ControlLoop): void
39
39
  }));
40
40
  }
41
41
 
42
+ function splitModelVariant(model: string): { base: string; variant: string } | null {
43
+ if (!model.endsWith(')')) return null;
44
+ const openIndex = model.lastIndexOf(' (');
45
+ if (openIndex < 0) return null;
46
+ const variant = model.slice(openIndex + 2, -1);
47
+ if (!variant || variant.includes('(') || variant.includes(')')) return null;
48
+ return { base: model.slice(0, openIndex), variant };
49
+ }
50
+
42
51
  /** Only offer sibling variants the selected provider actually advertises. */
43
52
  export function availableModelVariants(config: Record<string, unknown>): string[] {
44
- const current = String(config.model || '');
45
- const match = current.match(/^(.*)\s\(([^()]+)\)$/);
46
- if (!match) return [];
53
+ if (!config || typeof config !== 'object') return [];
54
+ const current = typeof config.model === 'string' ? config.model : String(config.model ?? '');
55
+ const parsed = splitModelVariant(current);
56
+ if (!parsed) return [];
47
57
  const overview = getAvailableProvidersOverview(config);
48
- const provider = String(config.provider || '');
58
+ const provider = typeof config.provider === 'string' ? config.provider : String(config.provider ?? '');
49
59
  const advertised = overview.acp.find(peer => peer.providerKey === provider)?.models
50
60
  ?? overview.byok.find(item => item.id === provider)?.models
51
61
  ?? [];
52
- return advertised.filter(model => {
53
- const sibling = model.match(/^(.*)\s\(([^()]+)\)$/);
54
- return sibling?.[1] === match[1];
55
- });
62
+ return advertised.filter(model => splitModelVariant(model)?.base === parsed.base);
56
63
  }
57
64
 
58
65
  export function openVariantControl(prompt: ControlPrompt): void {
@@ -63,17 +70,18 @@ export function openVariantControl(prompt: ControlPrompt): void {
63
70
  prompt.scheduleDraw();
64
71
  return;
65
72
  }
73
+ const provider = typeof config.provider === 'string' ? config.provider.trim() : '';
66
74
  prompt.openLayer(new SelectLayer({
67
75
  title: 'Model variant',
68
76
  items: variants.map(model => ({
69
77
  id: model,
70
78
  label: `${model}${model === config.model ? ' (active)' : ''}`,
71
- description: String(config.provider || ''),
79
+ description: provider,
72
80
  value: model
73
81
  })),
74
82
  onPick: (item: { value?: string } | null) => {
75
83
  if (!item?.value || item.value === config.model) return;
76
- prompt.deliver(`/model ${String(config.provider)}/${item.value}`);
84
+ prompt.deliver(provider ? `/model ${provider}/${item.value}` : `/model ${item.value}`);
77
85
  prompt.notice = 'Model variant change queued';
78
86
  prompt.scheduleDraw();
79
87
  }
@@ -16,10 +16,12 @@ export function composerGeometry(requestedWidth, barColumns, gutterColumns) {
16
16
  * The ordinary roomy Home composition is unchanged.
17
17
  */
18
18
  export function fitHomeContent(logoRows, promptRows, stageHeight, caretRow, requestedSpacer) {
19
+ const safeLogoRows = Array.isArray(logoRows) ? logoRows : [];
20
+ const safePromptRows = Array.isArray(promptRows) ? promptRows : [];
19
21
  const available = Number.isFinite(stageHeight)
20
22
  ? Math.max(1, Math.trunc(stageHeight))
21
23
  : 24;
22
- const prompt = promptRows.length ? [...promptRows] : [''];
24
+ const prompt = safePromptRows.length ? [...safePromptRows] : [''];
23
25
  const caret = Number.isFinite(caretRow)
24
26
  ? Math.max(0, Math.min(prompt.length - 1, Math.trunc(caretRow)))
25
27
  : 0;
@@ -31,10 +33,10 @@ export function fitHomeContent(logoRows, promptRows, stageHeight, caretRow, requ
31
33
  const remaining = available - visiblePrompt.length;
32
34
  // A cropped rotor/wordmark looks broken. On cramped terminals, hide the
33
35
  // banner as a whole rather than displaying an arbitrary bottom fragment.
34
- const showLogo = logoRows.length > 0 && remaining >= logoRows.length;
35
- const visibleLogo = showLogo ? [...logoRows] : [];
36
+ const showLogo = safeLogoRows.length > 0 && remaining >= safeLogoRows.length;
37
+ const visibleLogo = showLogo ? [...safeLogoRows] : [];
36
38
  const spacer = showLogo
37
- ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - logoRows.length)
39
+ ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - safeLogoRows.length)
38
40
  : 0;
39
41
  return {
40
42
  logoRows: visibleLogo,