@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
@@ -51,10 +51,12 @@ export function fitHomeContent(
51
51
  caretRow: number,
52
52
  requestedSpacer: number
53
53
  ): FittedHomeContent {
54
+ const safeLogoRows = Array.isArray(logoRows) ? logoRows : [];
55
+ const safePromptRows = Array.isArray(promptRows) ? promptRows : [];
54
56
  const available = Number.isFinite(stageHeight)
55
57
  ? Math.max(1, Math.trunc(stageHeight))
56
58
  : 24;
57
- const prompt = promptRows.length ? [...promptRows] : [''];
59
+ const prompt = safePromptRows.length ? [...safePromptRows] : [''];
58
60
  const caret = Number.isFinite(caretRow)
59
61
  ? Math.max(0, Math.min(prompt.length - 1, Math.trunc(caretRow)))
60
62
  : 0;
@@ -66,10 +68,10 @@ export function fitHomeContent(
66
68
  const remaining = available - visiblePrompt.length;
67
69
  // A cropped rotor/wordmark looks broken. On cramped terminals, hide the
68
70
  // banner as a whole rather than displaying an arbitrary bottom fragment.
69
- const showLogo = logoRows.length > 0 && remaining >= logoRows.length;
70
- const visibleLogo = showLogo ? [...logoRows] : [];
71
+ const showLogo = safeLogoRows.length > 0 && remaining >= safeLogoRows.length;
72
+ const visibleLogo = showLogo ? [...safeLogoRows] : [];
71
73
  const spacer = showLogo
72
- ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - logoRows.length)
74
+ ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - safeLogoRows.length)
73
75
  : 0;
74
76
  return {
75
77
  logoRows: visibleLogo,
@@ -1,3 +1,4 @@
1
+ import { safeDisplay } from './text.js';
1
2
  const activeStageHosts = new Set();
2
3
  let stageMouseSessionDepth = 0;
3
4
  let guardInstalled = false;
@@ -16,6 +17,11 @@ const originalStdoutWrite = process.stdout?.write
16
17
  let stageInternalWriting = false;
17
18
  /**
18
19
  * Run a write operation with permission to write to stdout during Stage sessions.
20
+ *
21
+ * Every TUI-owned terminal control write (Stage band diffs, OSC 52 clipboard sync,
22
+ * StageSurface mouse mode toggles ?1000/?1006/?1003, and ChatPrompt bracketed
23
+ * paste ?2004 / Ctrl+L clear) MUST execute inside runWithStageWrite(); otherwise
24
+ * the process.stdout guard drops escape sequences while a Stage is reserved.
19
25
  */
20
26
  export function runWithStageWrite(fn) {
21
27
  const prev = stageInternalWriting;
@@ -27,6 +33,16 @@ export function runWithStageWrite(fn) {
27
33
  stageInternalWriting = prev;
28
34
  }
29
35
  }
36
+ function chunkToText(chunk, encodingOrCb) {
37
+ if (typeof chunk === 'string')
38
+ return chunk;
39
+ const encoding = typeof encodingOrCb === 'string' ? encodingOrCb : 'utf8';
40
+ if (Buffer.isBuffer(chunk))
41
+ return chunk.toString(encoding);
42
+ if (chunk instanceof Uint8Array)
43
+ return Buffer.from(chunk).toString(encoding);
44
+ return String(chunk ?? '');
45
+ }
30
46
  export function isAnyStageReservedOnStdout() {
31
47
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
32
48
  return true;
@@ -70,9 +86,9 @@ function ensureConsoleGuardInstalled() {
70
86
  if (originalStdoutWrite && process.stdout) {
71
87
  process.stdout.write = ((chunk, encodingOrCb, cb) => {
72
88
  if (isAnyStageReservedOnStdout() && !stageInternalWriting) {
73
- // Prevent rogue unmanaged writes from emitting bare newlines that scroll the stage
74
- const text = String(chunk ?? '');
75
- if (text.includes('\n')) {
89
+ // Prevent rogue unmanaged writes from emitting newlines, CRs, or escape codes that corrupt the stage
90
+ const text = chunkToText(chunk, encodingOrCb);
91
+ if (text.includes('\n') || text.includes('\r') || text.includes('\x1b')) {
76
92
  if (typeof encodingOrCb === 'function')
77
93
  encodingOrCb();
78
94
  else if (typeof cb === 'function')
@@ -117,17 +133,23 @@ export function setTransientNotice(host, message, ttlMs = 4000) {
117
133
  clearTimeout(existing);
118
134
  noticeTimers.delete(host);
119
135
  }
120
- host.notice = message;
136
+ const cleanMessage = typeof message === 'string' && message.length > 0
137
+ ? safeDisplay(message).replace(/\s+/g, ' ').trim()
138
+ : '';
139
+ host.notice = cleanMessage;
121
140
  host.scheduleDraw();
122
- if (!message || ttlMs <= 0)
141
+ const safeTtlMs = !Number.isFinite(ttlMs)
142
+ ? (Number.isNaN(ttlMs) ? 4000 : 0)
143
+ : Math.min(Math.floor(ttlMs), 2_147_483_647);
144
+ if (!cleanMessage || safeTtlMs <= 0)
123
145
  return;
124
146
  const timer = setTimeout(() => {
125
147
  noticeTimers.delete(host);
126
- if (host.notice === message) {
148
+ if (host.notice === cleanMessage) {
127
149
  host.notice = '';
128
150
  host.scheduleDraw();
129
151
  }
130
- }, ttlMs);
152
+ }, safeTtlMs);
131
153
  timer.unref?.();
132
154
  noticeTimers.set(host, timer);
133
155
  }
@@ -1,3 +1,5 @@
1
+ import { safeDisplay } from './text.js';
2
+
1
3
  export interface ConsoleGuardStageHost {
2
4
  out?: NodeJS.WriteStream | { rows?: number; columns?: number };
3
5
  stage?: { reserved?: boolean; invalidate?: () => void };
@@ -31,6 +33,11 @@ let stageInternalWriting = false;
31
33
 
32
34
  /**
33
35
  * Run a write operation with permission to write to stdout during Stage sessions.
36
+ *
37
+ * Every TUI-owned terminal control write (Stage band diffs, OSC 52 clipboard sync,
38
+ * StageSurface mouse mode toggles ?1000/?1006/?1003, and ChatPrompt bracketed
39
+ * paste ?2004 / Ctrl+L clear) MUST execute inside runWithStageWrite(); otherwise
40
+ * the process.stdout guard drops escape sequences while a Stage is reserved.
34
41
  */
35
42
  export function runWithStageWrite<T>(fn: () => T): T {
36
43
  const prev = stageInternalWriting;
@@ -42,6 +49,14 @@ export function runWithStageWrite<T>(fn: () => T): T {
42
49
  }
43
50
  }
44
51
 
52
+ function chunkToText(chunk: unknown, encodingOrCb?: unknown): string {
53
+ if (typeof chunk === 'string') return chunk;
54
+ const encoding = typeof encodingOrCb === 'string' ? encodingOrCb as BufferEncoding : 'utf8';
55
+ if (Buffer.isBuffer(chunk)) return chunk.toString(encoding);
56
+ if (chunk instanceof Uint8Array) return Buffer.from(chunk).toString(encoding);
57
+ return String(chunk ?? '');
58
+ }
59
+
45
60
  export function isAnyStageReservedOnStdout(): boolean {
46
61
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
47
62
  return true;
@@ -87,9 +102,9 @@ function ensureConsoleGuardInstalled(): void {
87
102
  if (originalStdoutWrite && process.stdout) {
88
103
  process.stdout.write = ((chunk: unknown, encodingOrCb?: unknown, cb?: unknown): boolean => {
89
104
  if (isAnyStageReservedOnStdout() && !stageInternalWriting) {
90
- // Prevent rogue unmanaged writes from emitting bare newlines that scroll the stage
91
- const text = String(chunk ?? '');
92
- if (text.includes('\n')) {
105
+ // Prevent rogue unmanaged writes from emitting newlines, CRs, or escape codes that corrupt the stage
106
+ const text = chunkToText(chunk, encodingOrCb);
107
+ if (text.includes('\n') || text.includes('\r') || text.includes('\x1b')) {
93
108
  if (typeof encodingOrCb === 'function') (encodingOrCb as () => void)();
94
109
  else if (typeof cb === 'function') (cb as () => void)();
95
110
  return true;
@@ -135,17 +150,23 @@ export function setTransientNotice(host: TransientNoticeHost, message: string, t
135
150
  clearTimeout(existing);
136
151
  noticeTimers.delete(host);
137
152
  }
138
- host.notice = message;
153
+ const cleanMessage = typeof message === 'string' && message.length > 0
154
+ ? safeDisplay(message).replace(/\s+/g, ' ').trim()
155
+ : '';
156
+ host.notice = cleanMessage;
139
157
  host.scheduleDraw();
140
- if (!message || ttlMs <= 0) return;
158
+ const safeTtlMs = !Number.isFinite(ttlMs)
159
+ ? (Number.isNaN(ttlMs) ? 4000 : 0)
160
+ : Math.min(Math.floor(ttlMs), 2_147_483_647);
161
+ if (!cleanMessage || safeTtlMs <= 0) return;
141
162
 
142
163
  const timer = setTimeout(() => {
143
164
  noticeTimers.delete(host);
144
- if (host.notice === message) {
165
+ if (host.notice === cleanMessage) {
145
166
  host.notice = '';
146
167
  host.scheduleDraw();
147
168
  }
148
- }, ttlMs);
169
+ }, safeTtlMs);
149
170
  timer.unref?.();
150
171
  noticeTimers.set(host, timer);
151
172
  }
@@ -22,9 +22,13 @@ import { LineEditor } from './lineEditor.js';
22
22
  import { paint, bold, dim, badge, GLYPHS } from './theme.js';
23
23
  import { truncate, wrap, visibleWidth, safeDisplay, shortenHome } from './text.js';
24
24
  import { approvalDiff } from './diff.js';
25
- import { isChar } from './keys.js';
25
+ import { isChar, isMouseMotion } from './keys.js';
26
26
  import { readClipboardSync } from './clipboardSync.js';
27
27
 
28
+ const cleanDialogText = (value) => (
29
+ value == null ? '' : safeDisplay(String(value)).replace(/\s+/g, ' ').trim()
30
+ );
31
+
28
32
  /**
29
33
  * A picker. `items` are SelectList items; `onPick(item)` fires on enter.
30
34
  *
@@ -33,14 +37,16 @@ import { readClipboardSync } from './clipboardSync.js';
33
37
  */
34
38
  export class SelectLayer extends Layer {
35
39
  constructor(options = {}) {
36
- super({ width: options.width || 68, height: options.height || 18, ...options });
37
- this.list = new SelectList(options.items || [], {
38
- placeholder: options.placeholder,
39
- emptyText: options.emptyText
40
+ const opts = options && typeof options === 'object' ? options : {};
41
+ super({ width: opts.width || 68, height: opts.height || 18, ...opts });
42
+ this.list = new SelectList(opts.items || [], {
43
+ placeholder: opts.placeholder,
44
+ emptyText: opts.emptyText,
45
+ showFilter: opts.showFilter
40
46
  });
41
- this.onPick = options.onPick || null;
47
+ this.onPick = opts.onPick || null;
42
48
  this.settled = false;
43
- this.footer = options.footer || dialogHint();
49
+ this.footer = opts.footer || dialogHint();
44
50
  }
45
51
 
46
52
  /** Dismissal must resolve pending picker flows, just like text inputs. */
@@ -91,14 +97,15 @@ export class SelectLayer extends Layer {
91
97
 
92
98
  export class InputLayer extends Layer {
93
99
  constructor(options = {}) {
94
- super({ width: options.width || 68, height: options.height || 10, ...options });
95
- this.editor = new LineEditor(String(options.value == null ? '' : options.value));
96
- this.lines = Array.isArray(options.lines) ? options.lines : [];
97
- this.mask = options.mask === true;
98
- this.placeholder = options.placeholder || '';
99
- this.onSubmit = options.onSubmit || null;
100
- this.onCancel = options.onCancel || null;
101
- this.footer = options.footer || `enter accept ${GLYPHS.dot} esc cancel`;
100
+ const opts = options && typeof options === 'object' ? options : {};
101
+ super({ width: opts.width || 68, height: opts.height || 10, ...opts });
102
+ this.editor = new LineEditor(String(opts.value == null ? '' : opts.value));
103
+ this.lines = Array.isArray(opts.lines) ? opts.lines : [];
104
+ this.mask = opts.mask === true;
105
+ this.placeholder = opts.placeholder || '';
106
+ this.onSubmit = opts.onSubmit || null;
107
+ this.onCancel = opts.onCancel || null;
108
+ this.footer = opts.footer || `enter accept ${GLYPHS.dot} esc cancel`;
102
109
  this.settled = false;
103
110
  }
104
111
 
@@ -113,19 +120,26 @@ export class InputLayer extends Layer {
113
120
  }
114
121
 
115
122
  body(width) {
116
- const rows = this.lines.map((line) => truncate(line, width, GLYPHS.ellipsis));
123
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.floor(width) : 8;
124
+ const rows = this.lines.map((line) => truncate(cleanDialogText(line), safeWidth, GLYPHS.ellipsis));
117
125
  if (rows.length) rows.push('');
118
126
 
119
127
  const raw = this.editor.getText();
120
- const shown = this.mask ? GLYPHS.bullet.repeat(raw.length) : raw;
121
- const text = shown.length === 0 && this.placeholder ? dim(this.placeholder) : shown;
128
+ const shown = this.mask ? GLYPHS.bullet.repeat(Array.from(raw).length) : cleanDialogText(raw);
129
+ const cleanPlaceholder = cleanDialogText(this.placeholder);
130
+ const text = shown.length === 0 && cleanPlaceholder ? dim(cleanPlaceholder) : shown;
122
131
 
123
132
  const prefix = paint('accent', `${GLYPHS.arrow} `);
124
- rows.push(truncate(prefix + text, width, GLYPHS.ellipsis));
133
+ rows.push(truncate(prefix + text, safeWidth, GLYPHS.ellipsis));
125
134
 
126
135
  // Park the caret after what is displayed — which for a masked field is the
127
- // dot count, not the character count, or the caret drifts off the value.
128
- this.cursor = { x: 2 + (this.mask ? this.editor.col : visibleWidth(raw.slice(0, this.editor.col))), y: rows.length - 1 };
136
+ // dot count, not the character count, or the caret drifts off the value —
137
+ // and never past the rightmost body column.
138
+ const before = this.mask
139
+ ? Array.from(raw.slice(0, this.editor.col)).length
140
+ : visibleWidth(cleanDialogText(raw.slice(0, this.editor.col)));
141
+ const maxCol = Math.max(0, safeWidth - 1);
142
+ this.cursor = { x: Math.min(maxCol, 2 + before), y: rows.length - 1 };
129
143
  return rows;
130
144
  }
131
145
 
@@ -227,8 +241,12 @@ export class HomeLayer extends Layer {
227
241
  // The hint column is right-padded from the widest label so the two columns
228
242
  // line up, but it is computed from the ACTUAL labels rather than a constant:
229
243
  // a hardcoded inset is what makes a menu look off by one at some widths.
230
- const labelWidth = this.items.reduce((max, item) => Math.max(max, visibleWidth(item.label)), 0);
231
- return this.items.map((item, i) => {
244
+ const cleanItems = this.items.map((item) => ({
245
+ label: cleanDialogText(item?.label || ''),
246
+ hint: cleanDialogText(item?.hint || '')
247
+ }));
248
+ const labelWidth = cleanItems.reduce((max, item) => Math.max(max, visibleWidth(item.label)), 0);
249
+ return cleanItems.map((item, i) => {
232
250
  const selected = i === this.index;
233
251
  const marker = selected ? paint('accent', GLYPHS.arrow) : ' ';
234
252
  const label = selected ? bold(paint('accent', item.label)) : item.label;
@@ -244,8 +262,14 @@ export class HomeLayer extends Layer {
244
262
  if (!event) return null;
245
263
 
246
264
  switch (event.name) {
247
- case 'up': this.index = (this.index - 1 + this.items.length) % this.items.length; return 'handled';
248
- case 'down': this.index = (this.index + 1) % this.items.length; return 'handled';
265
+ case 'up':
266
+ if (this.items.length === 0) return 'handled';
267
+ this.index = (this.index - 1 + this.items.length) % this.items.length;
268
+ return 'handled';
269
+ case 'down':
270
+ if (this.items.length === 0) return 'handled';
271
+ this.index = (this.index + 1) % this.items.length;
272
+ return 'handled';
249
273
  case 'enter':
250
274
  case 'return': {
251
275
  const item = this.current;
@@ -284,17 +308,19 @@ export class TextLayer extends Layer {
284
308
  preferredHeight() { return this.lines.length + 2; }
285
309
 
286
310
  body(width, height) {
287
- this.viewHeight = height;
288
- const maximum = Math.max(0, this.lines.length - height);
311
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.floor(width) : 8;
312
+ const safeHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : 1;
313
+ this.viewHeight = safeHeight;
314
+ const maximum = Math.max(0, this.lines.length - safeHeight);
289
315
  this.scroll = Math.max(0, Math.min(this.scroll, maximum));
290
316
 
291
- const window = this.lines.slice(this.scroll, this.scroll + height)
292
- .map((line) => truncate(line, width, GLYPHS.ellipsis));
317
+ const window = this.lines.slice(this.scroll, this.scroll + safeHeight)
318
+ .map((line) => truncate(line == null ? '' : safeDisplay(String(line)), safeWidth, GLYPHS.ellipsis));
293
319
 
294
- if (this.lines.length > height) {
295
- const position = `${this.scroll + 1}-${Math.min(this.lines.length, this.scroll + height)}/${this.lines.length}`;
296
- while (window.length < height) window.push('');
297
- window[height - 1] = dim(position.padStart(width));
320
+ if (this.lines.length > safeHeight) {
321
+ const position = `${this.scroll + 1}-${Math.min(this.lines.length, this.scroll + safeHeight)}/${this.lines.length}`;
322
+ while (window.length < safeHeight) window.push('');
323
+ window[safeHeight - 1] = dim(position.padStart(safeWidth));
298
324
  }
299
325
  this.cursor = null;
300
326
  return window;
@@ -306,12 +332,17 @@ export class TextLayer extends Layer {
306
332
  switch (event.name) {
307
333
  case 'escape':
308
334
  case 'q': return 'close';
309
- case 'up': this.scroll--; return 'handled';
335
+ case 'wheel':
336
+ if (event.wheel?.direction === 'up') this.scroll = Math.max(0, this.scroll - 1);
337
+ else if (event.wheel?.direction === 'down') this.scroll++;
338
+ return 'handled';
339
+ case 'up': this.scroll = Math.max(0, this.scroll - 1); return 'handled';
310
340
  case 'down': this.scroll++; return 'handled';
311
- case 'pageup': this.scroll -= page; return 'handled';
341
+ case 'pageup': this.scroll = Math.max(0, this.scroll - page); return 'handled';
312
342
  case 'pagedown': this.scroll += page; return 'handled';
313
343
  case 'home': this.scroll = 0; return 'handled';
314
344
  case 'end': this.scroll = this.lines.length; return 'handled';
345
+ case 'enter':
315
346
  case 'return': return 'close';
316
347
  default: return 'handled';
317
348
  }
@@ -414,10 +445,11 @@ export class ApprovalLayer extends Layer {
414
445
  // chips, so the diff never grows into the controls and push them off-panel.
415
446
  const height = Math.max(1, fullHeight - 2);
416
447
  const rows = [];
417
- rows.push(`${paint(this.role, GLYPHS.warnMark)} ${bold(safeDisplay(this.request.tool || ''))}${this.verb ? dim(` ${this.verb}`) : ''}`);
448
+ const cleanVerb = this.verb ? cleanDialogText(this.verb) : '';
449
+ rows.push(`${paint(this.role, GLYPHS.warnMark)} ${bold(safeDisplay(this.request.tool || ''))}${cleanVerb ? dim(` ${cleanVerb}`) : ''}`);
418
450
 
419
451
  if (this.detail) {
420
- for (const line of wrap(paint('ink', this.detail), width).slice(0, 2)) rows.push(line);
452
+ for (const line of wrap(paint('ink', cleanDialogText(this.detail)), width).slice(0, 2)) rows.push(line);
421
453
  }
422
454
 
423
455
  if (this.diff) {
@@ -425,10 +457,10 @@ export class ApprovalLayer extends Layer {
425
457
  this.diff.added ? paint('success', `+${this.diff.added}`) : '',
426
458
  this.diff.removed ? paint('danger', `-${this.diff.removed}`) : ''
427
459
  ].filter(Boolean).join(' ');
428
- const note = this.diff.note ? dim(` ${GLYPHS.dot} ${this.diff.note}`) : '';
460
+ const note = this.diff.note ? dim(` ${GLYPHS.dot} ${cleanDialogText(this.diff.note)}`) : '';
429
461
  // The detail row above already names the file; printing the path again
430
462
  // here just spends a row saying the same thing twice.
431
- const where = this.detail ? '' : `${dim(this.diff.path)} `;
463
+ const where = this.detail ? '' : `${dim(cleanDialogText(this.diff.path))} `;
432
464
  rows.push('');
433
465
  rows.push(`${where}${stat}${note}`);
434
466
  rows.push(paint('rule', GLYPHS.hLine.repeat(width)));
@@ -501,16 +533,27 @@ export class ApprovalLayer extends Layer {
501
533
  return 'close';
502
534
  }
503
535
 
504
- if (event.name === 'mouse' && event.mouse && event.mouse.pressed && event.mouse.button === 0) {
536
+ if (event.name === 'mouse' && event.mouse && event.mouse.pressed && event.mouse.button === 0 && !isMouseMotion(event.sequence)) {
505
537
  if (!Array.isArray(this.optionBounds) || this.optionBounds.length === 0) {
506
538
  this.optionRow();
507
539
  }
508
540
  const geom = this.panelGeometry;
509
- if (geom && Number.isFinite(event.mouse.row) && Number.isFinite(geom.optionScreenRow)) {
510
- if (Math.abs(event.mouse.row - geom.optionScreenRow) > 1) return 'handled';
541
+ const hasZeroRow = Number.isFinite(event.mouse.y);
542
+ const rawRow = hasZeroRow
543
+ ? Math.floor(event.mouse.y)
544
+ : (Number.isFinite(event.mouse.row) ? Math.floor(event.mouse.row) : NaN);
545
+ if (geom && Number.isFinite(rawRow) && Number.isFinite(geom.optionScreenRow)) {
546
+ // drawLayer() computes 0-based screen rows; legacy synthetic callers send 1-based row.
547
+ const zeroBasedRow = hasZeroRow ? rawRow : rawRow - 1;
548
+ if (Math.abs(zeroBasedRow - geom.optionScreenRow) > 1) return 'handled';
511
549
  }
512
- const rawCol = Number.isFinite(event.mouse.col) ? event.mouse.col : -1;
513
- const bodyCol = geom ? rawCol - 1 - (geom.inset || 0) - 2 : rawCol;
550
+ const hasZeroCol = Number.isFinite(event.mouse.x);
551
+ const rawCol = hasZeroCol
552
+ ? Math.floor(event.mouse.x)
553
+ : (Number.isFinite(event.mouse.col) ? Math.floor(event.mouse.col) : -1);
554
+ const bodyCol = geom
555
+ ? rawCol - (hasZeroCol ? 0 : 1) - (geom.inset || 0) - 2
556
+ : rawCol;
514
557
  const hit = (this.optionBounds || []).find(b => bodyCol >= b.startCol && bodyCol <= b.endCol);
515
558
  if (hit) {
516
559
  this.selected = hit.index;
@@ -521,15 +564,15 @@ export class ApprovalLayer extends Layer {
521
564
  }
522
565
 
523
566
  if (event.name === 'wheel') {
524
- if (event.wheel?.direction === 'up') this.scroll--;
567
+ if (event.wheel?.direction === 'up') this.scroll = Math.max(0, this.scroll - 1);
525
568
  else if (event.wheel?.direction === 'down') this.scroll++;
526
569
  return 'handled';
527
570
  }
528
571
 
529
572
  switch (event.name) {
530
- case 'up': this.scroll--; return 'handled';
573
+ case 'up': this.scroll = Math.max(0, this.scroll - 1); return 'handled';
531
574
  case 'down': this.scroll++; return 'handled';
532
- case 'pageup': this.scroll -= page; return 'handled';
575
+ case 'pageup': this.scroll = Math.max(0, this.scroll - page); return 'handled';
533
576
  case 'pagedown': this.scroll += page; return 'handled';
534
577
  case 'home': this.scroll = 0; return 'handled';
535
578
  case 'end': this.scroll = this.diff ? this.diff.rows.length : 0; return 'handled';
@@ -587,18 +630,27 @@ export class DecisionLayer extends Layer {
587
630
  if (option.description) rows.push(` ${dim(truncate(safeDisplay(option.description), Math.max(1, width - 2), GLYPHS.ellipsis))}`);
588
631
  }
589
632
 
633
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.floor(width) : 8;
634
+ const safeHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : rows.length + 2;
590
635
  const customSelected = this.selected === this.customIndex;
591
636
  rows.push(`${customSelected ? paint('accent', GLYPHS.arrow) : paint('muted', GLYPHS.dot)} ${customSelected ? bold('Type your own answer') : 'Type your own answer'}`);
592
637
  if (this.customMode) {
593
- const value = this.editor.getText();
594
- rows.push(`${paint('accent', `${GLYPHS.arrow} `)}${value || dim('Describe the direction you want')}`);
595
- this.cursor = { x: 2 + visibleWidth(value.slice(0, this.editor.col)), y: rows.length - 1 };
638
+ const raw = this.editor.getText();
639
+ const value = cleanDialogText(raw);
640
+ rows.push(truncate(`${paint('accent', `${GLYPHS.arrow} `)}${value || dim('Describe the direction you want')}`, safeWidth, GLYPHS.ellipsis));
641
+ const rendered = rows.length > safeHeight ? rows.slice(rows.length - safeHeight) : rows;
642
+ const before = visibleWidth(cleanDialogText(raw.slice(0, this.editor.col)));
643
+ this.cursor = {
644
+ x: Math.min(Math.max(0, safeWidth - 1), 2 + before),
645
+ y: Math.max(0, rendered.length - 1)
646
+ };
596
647
  this.footer = `enter submit ${GLYPHS.dot} esc choices`;
648
+ return rendered;
597
649
  } else {
598
650
  this.cursor = null;
599
651
  this.footer = `↑↓ choose ${GLYPHS.dot} enter select ${GLYPHS.dot} esc cancel`;
600
652
  }
601
- return rows.slice(0, height);
653
+ return rows.slice(0, safeHeight);
602
654
  }
603
655
 
604
656
  key(event) {
@@ -695,18 +747,19 @@ export class ConfirmLayer extends Layer {
695
747
 
696
748
  /** The command palette — every command in the app, fuzzy-searchable. */
697
749
  export function commandPalette(commands, onRun) {
750
+ const safeCommands = Array.isArray(commands) ? commands.filter(Boolean) : [];
698
751
  return new SelectLayer({
699
752
  title: 'commands',
700
753
  placeholder: 'search commands',
701
754
  emptyText: 'no command matches',
702
755
  width: 72,
703
756
  height: 20,
704
- items: commands.map((command) => ({
705
- label: command.name,
706
- description: command.description || '',
707
- category: command.category || '',
708
- hint: command.hint || '',
709
- searchText: command.description || '',
757
+ items: safeCommands.map((command) => ({
758
+ label: cleanDialogText(command.name || ''),
759
+ description: cleanDialogText(command.description || ''),
760
+ category: cleanDialogText(command.category || ''),
761
+ hint: cleanDialogText(command.hint || ''),
762
+ searchText: cleanDialogText(command.description || ''),
710
763
  value: command
711
764
  })),
712
765
  onPick: (item) => { if (item && onRun) onRun(item.value); }
@@ -724,17 +777,18 @@ export function commandPalette(commands, onRun) {
724
777
  * the pane rather than to the terminal, so overflow is structurally impossible.
725
778
  */
726
779
  export function skillPicker(skills, onOpen) {
780
+ const safeSkills = Array.isArray(skills) ? skills.filter(Boolean) : [];
727
781
  return new SelectLayer({
728
- title: `skills (${skills.length})`,
782
+ title: `skills (${safeSkills.length})`,
729
783
  placeholder: 'search skills',
730
784
  emptyText: 'no skill matches',
731
785
  width: 76,
732
786
  height: 22,
733
- items: skills.map((skill) => ({
734
- label: `${skill.domain}/${skill.id}`,
735
- description: skill.description || '',
736
- category: skill.domain,
737
- searchText: `${skill.name} ${skill.description || ''}`,
787
+ items: safeSkills.map((skill) => ({
788
+ label: `${cleanDialogText(skill.domain || '')}/${cleanDialogText(skill.id || '')}`,
789
+ description: cleanDialogText(skill.description || ''),
790
+ category: cleanDialogText(skill.domain || ''),
791
+ searchText: cleanDialogText(`${skill.name || ''} ${skill.description || ''}`),
738
792
  value: skill
739
793
  })),
740
794
  onPick: (item) => { if (item && onOpen) onOpen(item.value); }
@@ -743,10 +797,15 @@ export function skillPicker(skills, onOpen) {
743
797
 
744
798
  /** Help: the keys, grouped, in a scrolling pane. */
745
799
  export function helpLayer(sections) {
800
+ const safeSections = Array.isArray(sections) ? sections.filter(Boolean) : [];
746
801
  const lines = [];
747
- for (const section of sections) {
748
- lines.push(bold(paint('ink', section.title)));
749
- for (const [keys, what] of section.rows) {
802
+ for (const section of safeSections) {
803
+ lines.push(bold(paint('ink', cleanDialogText(section.title || ''))));
804
+ const rows = Array.isArray(section.rows) ? section.rows : [];
805
+ for (const pair of rows) {
806
+ if (!Array.isArray(pair)) continue;
807
+ const keys = cleanDialogText(pair[0] || '');
808
+ const what = cleanDialogText(pair[1] || '');
750
809
  lines.push(` ${paint('accent', keys.padEnd(18))}${dim(what)}`);
751
810
  }
752
811
  lines.push('');
@@ -756,12 +815,16 @@ export function helpLayer(sections) {
756
815
 
757
816
  /** A status pane: session facts that would otherwise need a scrollback hunt. */
758
817
  export function statusLayer(rows) {
759
- const width = rows.reduce((max, row) => Math.max(max, row[0].length), 0);
760
- const lines = rows.map(([label, value]) => (
761
- label === ''
818
+ const safeRows = (Array.isArray(rows) ? rows : []).filter(row => Array.isArray(row));
819
+ const labels = safeRows.map(row => cleanDialogText(row[0] == null ? '' : String(row[0])));
820
+ const width = labels.reduce((max, label) => Math.max(max, label.length), 0);
821
+ const lines = safeRows.map((row, index) => {
822
+ const label = labels[index];
823
+ const value = cleanDialogText(row[1] == null ? '' : String(row[1]));
824
+ return label === ''
762
825
  ? ''
763
- : `${paint('muted', String(label).padEnd(width + 2))}${paint('ink', safeDisplay(String(value)))}`
764
- ));
826
+ : `${paint('muted', label.padEnd(width + 2))}${paint('ink', value)}`;
827
+ });
765
828
  return new TextLayer({ title: 'session', lines, width: 74, height: Math.min(24, lines.length + 3) });
766
829
  }
767
830
 
package/src/tui/diff.js CHANGED
@@ -156,8 +156,12 @@ function collapse(ops) {
156
156
  * meaning on their own, which is what makes the no-colour output still readable.
157
157
  */
158
158
  export function renderDiffOps(ops, options = {}) {
159
- const width = Math.max(20, (options.width || 80) - 8);
160
- const maxLines = options.maxLines || MAX_RENDER_LINES;
159
+ if (!Array.isArray(ops)) return { rows: [], clipped: false };
160
+ const safeWidth = Number.isFinite(options?.width) && options.width > 0 ? Math.floor(options.width) : 80;
161
+ const width = Math.max(20, safeWidth - 8);
162
+ const maxLines = Number.isFinite(options?.maxLines) && options.maxLines > 0
163
+ ? Math.floor(options.maxLines)
164
+ : MAX_RENDER_LINES;
161
165
  const collapsed = collapse(ops);
162
166
  const rendered = [];
163
167
 
@@ -281,8 +285,8 @@ export function approvalDiff(toolName, args, options = {}) {
281
285
  if (rows.length === 0) return null;
282
286
 
283
287
  return {
284
- path: plan.path ? shortenHome(plan.path) : '',
285
- note: plan.note,
288
+ path: plan.path ? safeDisplay(shortenHome(plan.path)).replace(/[\r\n]+/g, ' ') : '',
289
+ note: plan.note ? safeDisplay(plan.note).replace(/[\r\n]+/g, ' ') : '',
286
290
  rows,
287
291
  added: stat.added,
288
292
  removed: stat.removed,
@@ -51,7 +51,7 @@ export class PromptHistory {
51
51
  return null;
52
52
  }
53
53
  })
54
- .filter((entry) => typeof entry === 'string' && entry.length > 0);
54
+ .filter((entry) => typeof entry === 'string' && entry.length > 0 && !looksSensitive(entry));
55
55
  } catch (e) {
56
56
  this.entries = []; // no history yet is the normal first run
57
57
  }
@@ -90,7 +90,7 @@ export class PromptHistory {
90
90
  fs.mkdirSync(path.dirname(this.file), { recursive: true });
91
91
  const body = this.entries.map((entry) => JSON.stringify(entry)).join('\n') + '\n';
92
92
  // Write then rename: a crash mid-write must not truncate the history.
93
- const temporary = this.file + '.tmp';
93
+ const temporary = `${this.file}.${process.pid}.tmp`;
94
94
  fs.writeFileSync(temporary, body, { mode: 0o600 });
95
95
  fs.renameSync(temporary, this.file);
96
96
  } catch (e) {
@@ -104,13 +104,14 @@ export class PromptHistory {
104
104
  * Typing `npm ` then pressing Up should walk npm prompts, not everything.
105
105
  */
106
106
  matching(prefix) {
107
- if (!prefix) return this.entries.slice().reverse();
108
- return this.entries.filter((entry) => entry.startsWith(prefix)).reverse();
107
+ const query = String(prefix == null ? '' : prefix);
108
+ if (!query) return this.entries.slice().reverse();
109
+ return this.entries.filter((entry) => entry.startsWith(query)).reverse();
109
110
  }
110
111
 
111
112
  /** Older entry, or null at the end. `draft` is the line being edited. */
112
113
  previous(draft) {
113
- if (this.cursor === -1) this.draft = draft;
114
+ if (this.cursor === -1) this.draft = String(draft == null ? '' : draft);
114
115
  const pool = this.matching(this.draft);
115
116
  if (pool.length === 0) return null;
116
117
  const next = Math.min(this.cursor + 1, pool.length - 1);