@causyne/agent 1.20.112 → 1.20.117

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 (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  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/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { stdout } from 'node:process';
13
+ import { safeDisplay } from './text.js';
13
14
 
14
15
  export type RotorMotion = 'heavy' | 'smooth' | 'pulse';
15
16
 
@@ -83,8 +84,13 @@ function smoothstep(t: number): number {
83
84
  return x * x * (3 - 2 * x);
84
85
  }
85
86
 
87
+ function clampRotorRange(value: number | undefined, min: number, max: number, fallback: number): number {
88
+ const numeric = Number(value ?? fallback);
89
+ return Number.isFinite(numeric) ? Math.max(min, Math.min(max, Math.floor(numeric))) : fallback;
90
+ }
91
+
86
92
  export function getAngle(elapsedMs: number, motion: RotorMotion = 'heavy'): number {
87
- const t = Math.max(0, elapsedMs);
93
+ const t = Number.isFinite(elapsedMs) ? Math.max(0, elapsedMs) : 0;
88
94
  if (motion === 'smooth') return (t / 4200) * TAU;
89
95
  if (motion === 'pulse') {
90
96
  const cycle = t / 1000;
@@ -129,8 +135,8 @@ export function renderCausyneRotor(
129
135
  elapsedMs: number,
130
136
  options: RotorOptions = {},
131
137
  ): string {
132
- const columns = Math.max(12, Math.min(56, Math.floor(options.columns ?? 24)));
133
- const rows = Math.max(6, Math.min(28, Math.floor(options.rows ?? 12)));
138
+ const columns = clampRotorRange(options.columns, 12, 56, 24);
139
+ const rows = clampRotorRange(options.rows, 6, 28, 12);
134
140
  const color = options.color ?? true;
135
141
  const angle = getAngle(elapsedMs, options.motion ?? 'heavy');
136
142
  const blades = Array.from({ length: 6 }, (_, i) => {
@@ -177,7 +183,10 @@ export function renderCausyneRotor(
177
183
  }
178
184
 
179
185
  if (options.label !== '') {
180
- const label = options.label ?? 'working';
186
+ const cleanLabel = options.label === undefined
187
+ ? 'working'
188
+ : safeDisplay(options.label).replace(/\s+/g, ' ').trim();
189
+ const label = cleanLabel || 'working';
181
190
  const status = color
182
191
  ? `${COLORS.lime}●${COLORS.reset} ${COLORS.text}${label}${COLORS.reset}`
183
192
  : `● ${label}`;
@@ -196,11 +205,14 @@ export function startCausyneRotor(options: RotorOptions & { fps?: number | undef
196
205
  } {
197
206
  const color = options.color ?? (Boolean(stdout.isTTY) && !process.env.NO_COLOR && !process.env.CAUSYNE_NO_COLOR);
198
207
  if (!stdout.isTTY) {
199
- stdout.write((options.label ?? 'working') + '\n');
208
+ const label = options.label === undefined
209
+ ? 'working'
210
+ : safeDisplay(options.label).replace(/\s+/g, ' ').trim();
211
+ stdout.write(label + '\n');
200
212
  return { stop() {} };
201
213
  }
202
214
 
203
- const fps = Math.max(4, Math.min(30, options.fps ?? 16));
215
+ const fps = clampRotorRange(options.fps, 4, 30, 16);
204
216
  const started = Date.now();
205
217
  let stopped = false;
206
218
  let lastLines = 0;
@@ -260,21 +272,24 @@ export function getRotorSpinnerFrames(color = true, unicode = true): readonly st
260
272
 
261
273
  export function getRotorSpinnerFrame(tick: number, color = true, unicode = true): string {
262
274
  const frames = getRotorSpinnerFrames(color, unicode);
263
- const index = Math.abs(Math.floor(tick)) % frames.length;
275
+ const safeTick = Number.isFinite(tick) ? Math.abs(Math.floor(tick)) : 0;
276
+ const index = safeTick % frames.length;
264
277
  return frames[index] ?? frames[0] ?? '⠇⠙';
265
278
  }
266
279
 
267
280
  const DOT_FRAMES = [' ', '. ', '.. ', '...'] as const;
268
281
 
269
282
  export function getAnimatedDots(tick: number): string {
270
- const stage = Math.floor(Math.abs(Math.floor(tick)) / 2) % DOT_FRAMES.length;
283
+ const safeTick = Number.isFinite(tick) ? Math.abs(Math.floor(tick)) : 0;
284
+ const stage = Math.floor(safeTick / 2) % DOT_FRAMES.length;
271
285
  return DOT_FRAMES[stage] ?? ' ';
272
286
  }
273
287
 
274
288
  export function formatAnimatedStatus(message: string, tick: number): string {
275
- let base = (message || 'working').trimEnd();
289
+ let base = safeDisplay(message ?? '').replace(/\s+/g, ' ').trimEnd();
276
290
  while (base.endsWith('.') || base.endsWith('…')) {
277
291
  base = base.slice(0, -1).trimEnd();
278
292
  }
279
- return `${base}${getAnimatedDots(tick)}`;
293
+ const label = base.trim().length > 0 ? base : 'working';
294
+ return `${label}${getAnimatedDots(tick)}`;
280
295
  }
@@ -1,9 +1,13 @@
1
- import { safeDisplay, visibleWidth, wrapBlock } from './text.js';
1
+ import { safeDisplay, truncate, visibleWidth, wrap, wrapBlock } from './text.js';
2
2
  /** Render provider activity inside the conversation column, including multiline commands. */
3
3
  export function activityRows(message, columns, prefix = '▸ ') {
4
- const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
5
- const inset = visibleWidth(prefix);
4
+ const width = Number.isFinite(columns) ? Math.max(4, Math.floor(columns)) : 80;
5
+ const safePrefix = truncate(safeDisplay(String(prefix ?? '')).replace(/\r?\n/g, ' '), Math.max(1, width - 2), '');
6
+ const inset = visibleWidth(safePrefix);
6
7
  const bodyWidth = Math.max(1, width - inset - 1);
7
- const lines = wrapBlock(safeDisplay(message).trim(), bodyWidth, { hang: 0 });
8
- return lines.map((line, index) => `${index === 0 ? prefix : ' '.repeat(inset)}${line}`);
8
+ // wrapBlock keeps indentation but assumes at least eight columns.
9
+ // Hard-wrap its output when the actual conversation width is narrower.
10
+ const lines = wrapBlock(safeDisplay(String(message ?? '')).trim(), bodyWidth, { hang: 0 })
11
+ .flatMap(line => wrap(line, bodyWidth));
12
+ return lines.map((line, index) => `${index === 0 ? safePrefix : ' '.repeat(inset)}${line}`);
9
13
  }
@@ -1,10 +1,14 @@
1
- import { safeDisplay, visibleWidth, wrapBlock } from './text.js';
1
+ import { safeDisplay, truncate, visibleWidth, wrap, wrapBlock } from './text.js';
2
2
 
3
3
  /** Render provider activity inside the conversation column, including multiline commands. */
4
4
  export function activityRows(message: string, columns: number, prefix = '▸ '): string[] {
5
- const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
6
- const inset = visibleWidth(prefix);
5
+ const width = Number.isFinite(columns) ? Math.max(4, Math.floor(columns)) : 80;
6
+ const safePrefix = truncate(safeDisplay(String(prefix ?? '')).replace(/\r?\n/g, ' '), Math.max(1, width - 2), '');
7
+ const inset = visibleWidth(safePrefix);
7
8
  const bodyWidth = Math.max(1, width - inset - 1);
8
- const lines = wrapBlock(safeDisplay(message).trim(), bodyWidth, { hang: 0 });
9
- return lines.map((line, index) => `${index === 0 ? prefix : ' '.repeat(inset)}${line}`);
9
+ // wrapBlock keeps indentation but assumes at least eight columns.
10
+ // Hard-wrap its output when the actual conversation width is narrower.
11
+ const lines = wrapBlock(safeDisplay(String(message ?? '')).trim(), bodyWidth, { hang: 0 })
12
+ .flatMap(line => wrap(line, bodyWidth));
13
+ return lines.map((line, index) => `${index === 0 ? safePrefix : ' '.repeat(inset)}${line}`);
10
14
  }
package/src/tui/ask.js CHANGED
@@ -72,10 +72,20 @@ export function canAskInPanel() {
72
72
  }
73
73
 
74
74
  /** Plain readline, for pipes, CI and any terminal that refuses raw mode. */
75
- function fallbackQuestion(question, { mask = false } = {}) {
75
+ export function fallbackQuestion(question, { mask = false, input = process.stdin, output = process.stdout } = {}) {
76
76
  return new Promise((resolve) => {
77
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
78
- rl.question(`${question} `, (answer) => { rl.close(); resolve(answer); });
77
+ let settled = false;
78
+ const rl = readline.createInterface({ input, output });
79
+ const done = (value) => {
80
+ if (settled) return;
81
+ settled = true;
82
+ resolve(value);
83
+ };
84
+ rl.once('close', () => done(null));
85
+ rl.question(`${question} `, (answer) => {
86
+ rl.close();
87
+ done(answer);
88
+ });
79
89
  if (mask) {
80
90
  // Suppress the echo of what is typed. `_writeToOutput` is readline's own
81
91
  // hook for exactly this; the prompt itself still has to be drawn or the
@@ -95,8 +105,9 @@ function fallbackQuestion(question, { mask = false } = {}) {
95
105
  * @param {Array} options.items `{ id, label, description }`
96
106
  * @returns {Promise<object|null>} the chosen item, or null if dismissed
97
107
  */
98
- export async function askSelect({ title = '', items = [] } = {}) {
99
- if (items.length === 0) return null;
108
+ export async function askSelect(options = {}) {
109
+ const { title = '', items = [] } = options && typeof options === 'object' ? options : {};
110
+ if (!Array.isArray(items) || items.length === 0) return null;
100
111
 
101
112
  if (canAskInPanel()) {
102
113
  const answer = await hostOneLayer((resolve) => new SelectLayer({
@@ -113,6 +124,7 @@ export async function askSelect({ title = '', items = [] } = {}) {
113
124
  console.log(` ${String(index + 1).padStart(2)}. ${item.label}${item.description ? ` — ${item.description}` : ''}`);
114
125
  });
115
126
  const raw = await fallbackQuestion(`Choose 1-${items.length}:`);
127
+ if (raw === null) return null;
116
128
  const choice = Number(String(raw).trim());
117
129
  return Number.isInteger(choice) && choice >= 1 && choice <= items.length ? items[choice - 1] : null;
118
130
  }
@@ -122,7 +134,10 @@ export async function askSelect({ title = '', items = [] } = {}) {
122
134
  *
123
135
  * @returns {Promise<string|null>} the answer, or null if dismissed
124
136
  */
125
- export async function askText({ title = '', lines = [], value = '', placeholder = '', mask = false, validate = null } = {}) {
137
+ export async function askText(options = {}) {
138
+ let { title = '', lines = [], value = '', placeholder = '', mask = false, validate = null } =
139
+ options && typeof options === 'object' ? options : {};
140
+ lines = Array.isArray(lines) ? lines : [];
126
141
  while (true) {
127
142
  let answer;
128
143
 
@@ -160,6 +175,7 @@ export async function askConfirm(message) {
160
175
  if (answer !== undefined) return Boolean(answer);
161
176
  }
162
177
  const raw = await fallbackQuestion(`${message} [y/N]`);
178
+ if (raw === null) return false;
163
179
  return /^y(es)?$/i.test(String(raw).trim());
164
180
  }
165
181
 
@@ -170,33 +186,37 @@ export async function askConfirm(message) {
170
186
  * never grants a tool the right to mutate files or execute a command.
171
187
  */
172
188
  export async function askDecision(request = {}) {
173
- const options = Array.isArray(request.options) ? request.options : [];
189
+ const safeRequest = request && typeof request === 'object' ? request : {};
190
+ const options = Array.isArray(safeRequest.options) ? safeRequest.options : [];
191
+ if (options.length === 0 && safeRequest.allowCustom === false) return null;
174
192
 
175
193
  if (canAskInPanel()) {
176
194
  const answer = await hostOneLayer((resolve) => new DecisionLayer({
177
- request,
195
+ request: safeRequest,
178
196
  onAnswer: resolve
179
197
  }));
180
198
  if (answer !== undefined) return answer;
181
199
  }
182
200
 
183
201
  const custom = { id: '__custom__', label: 'Type your own answer', description: '' };
202
+ const items = safeRequest.allowCustom === false ? options : [...options, custom];
203
+ if (items.length === 0 || (options.length === 0 && !safeRequest.id && !safeRequest.question)) return null;
184
204
  const selected = await askSelect({
185
- title: request.header || 'Decision required',
186
- items: [...options, custom]
205
+ title: safeRequest.header || 'Decision required',
206
+ items
187
207
  });
188
208
  if (!selected) return null;
189
209
  if (selected.id === custom.id) {
190
210
  const label = await askText({
191
- title: request.question || 'Describe the direction you want',
192
- lines: request.reason ? [request.reason] : [],
211
+ title: safeRequest.question || 'Describe the direction you want',
212
+ lines: safeRequest.reason ? [safeRequest.reason] : [],
193
213
  validate: (value) => String(value).trim() ? null : 'An answer is required.'
194
214
  });
195
215
  if (!label) return null;
196
- return { requestId: request.id, optionId: null, label: String(label).trim(), custom: true };
216
+ return { requestId: safeRequest.id, optionId: null, label: String(label).trim(), custom: true };
197
217
  }
198
218
  return {
199
- requestId: request.id,
219
+ requestId: safeRequest.id,
200
220
  optionId: selected.id,
201
221
  label: selected.label,
202
222
  custom: false
package/src/tui/banner.js CHANGED
@@ -7,6 +7,12 @@
7
7
  * CAUSYNE_ASCII=1 (7-bit only), and CAUSYNE_NO_ANIM=1.
8
8
  */
9
9
  import { homedir } from 'node:os';
10
+ import { safeDisplay } from './text.js';
11
+ function cleanMeta(value) {
12
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? ''))
13
+ .replace(/[\r\n]+/g, ' ')
14
+ .trim();
15
+ }
10
16
  export const TAGLINE = 'From intention to meaningful progress.';
11
17
  // ---- Logo -----------------------------------------------------------------------------------------------
12
18
  // One character = one "pixel". A terminal cell holds two stacked pixels (drawn with the half blocks ▀ ▄ █).
@@ -109,16 +115,25 @@ function pickVariant(c) {
109
115
  return 'compact';
110
116
  return 'full';
111
117
  }
118
+ const VALID_COLORS = new Set(['truecolor', '256', '16', 'none']);
119
+ const VALID_VARIANTS = new Set(['full', 'compact', 'mini']);
112
120
  export function detect(o = {}, stream = process.stdout) {
113
- const env = process.env, tty = Boolean(stream.isTTY);
114
- const width = o.width || stream.columns || 80, height = o.height || stream.rows || 24;
115
- const want = o.color;
121
+ const opts = o && typeof o === 'object' ? o : {};
122
+ const safeStream = stream && typeof stream === 'object' ? stream : {};
123
+ const env = process.env, tty = Boolean(safeStream.isTTY);
124
+ const positiveDim = (v, fallback) => {
125
+ const n = Number(v);
126
+ return Number.isFinite(n) && n >= 1 ? Math.floor(n) : fallback;
127
+ };
128
+ const width = positiveDim(opts.width, positiveDim(safeStream.columns, 80));
129
+ const height = positiveDim(opts.height, positiveDim(safeStream.rows, 24));
130
+ const want = opts.color;
116
131
  let color;
117
132
  if (want === true)
118
133
  color = 'truecolor';
119
134
  else if (want === false)
120
135
  color = 'none';
121
- else if (want !== undefined && want !== 'auto')
136
+ else if (typeof want === 'string' && VALID_COLORS.has(want))
122
137
  color = want;
123
138
  else {
124
139
  const f = env['FORCE_COLOR'];
@@ -129,17 +144,19 @@ export function detect(o = {}, stream = process.stdout) {
129
144
  else if (!tty || env['TERM'] === 'dumb')
130
145
  color = 'none';
131
146
  else {
132
- const d = stream.getColorDepth?.() ?? 4;
147
+ const d = safeStream.getColorDepth?.() ?? 4;
133
148
  color = /truecolor|24bit/i.test(env['COLORTERM'] ?? '') || d >= 24 ? 'truecolor' : d >= 8 ? '256' : d >= 4 ? '16' : 'none';
134
149
  }
135
150
  }
136
- let unicode = o.unicode;
151
+ let unicode = opts.unicode;
137
152
  if (unicode === undefined) {
138
153
  const loc = env['LC_ALL'] || env['LC_CTYPE'] || env['LANG'] || '', ascii = env['CAUSYNE_ASCII'];
139
154
  unicode = !(ascii && ascii !== '0') && !(process.platform !== 'win32' && loc !== '' && !/utf-?8/i.test(loc));
140
155
  }
141
- const caps = { tty, width, height, color, unicode, variant: 'full' };
142
- caps.variant = o.variant && o.variant !== 'auto' ? o.variant : pickVariant(caps);
156
+ const caps = { tty, width, height, color, unicode: Boolean(unicode), variant: 'full' };
157
+ caps.variant = typeof opts.variant === 'string' && VALID_VARIANTS.has(opts.variant)
158
+ ? opts.variant
159
+ : pickVariant(caps);
143
160
  return caps;
144
161
  }
145
162
  // ---- Pixel canvas -> terminal cells ---------------------------------------------------------------------
@@ -220,8 +237,13 @@ function cells(px, caps) {
220
237
  return lines;
221
238
  }
222
239
  function txt(str, key, caps, maxw, bold) {
223
- if (maxw !== undefined && str.length > maxw)
224
- str = str.slice(0, Math.max(0, maxw - 1)) + (caps.unicode ? '…' : '~');
240
+ if (maxw !== undefined) {
241
+ const limit = Number.isFinite(maxw) ? Math.floor(maxw) : maxw === Number.POSITIVE_INFINITY ? str.length : 0;
242
+ if (limit <= 0)
243
+ return '';
244
+ if (str.length > limit)
245
+ str = str.slice(0, Math.max(0, limit - 1)) + (caps.unicode ? '…' : '~');
246
+ }
225
247
  if (caps.color === 'none')
226
248
  return str;
227
249
  return ESC + (bold ? '1;' : '') + fgCode(key, caps.color) + 'm' + str + RESET;
@@ -237,13 +259,18 @@ function shortPath(p, maxw) {
237
259
  }
238
260
  function statusLine(info, maxw, unicode) {
239
261
  const sep = unicode ? ' · ' : ' | ';
240
- const providerModel = [info.provider, info.model].filter(Boolean).join('/');
262
+ const safeProvider = cleanMeta(info.provider);
263
+ const safeModel = cleanMeta(info.model);
264
+ const safeVersion = cleanMeta(info.version).replace(/^v/, '');
265
+ const safeMode = cleanMeta(info.mode);
266
+ const safeCwd = cleanMeta(info.cwd);
267
+ const providerModel = [safeProvider, safeModel].filter(Boolean).join('/');
241
268
  const providerPart = providerModel || 'select provider';
242
- const parts = [info.version ? 'v' + String(info.version).replace(/^v/, '') : '', providerPart, info.mode ?? '', info.cwd ?? ''].filter(Boolean);
269
+ const parts = [safeVersion ? 'v' + safeVersion : '', providerPart, safeMode, safeCwd].filter(Boolean);
243
270
  const fits = () => parts.join(sep).length <= maxw;
244
- if (!fits() && info.cwd) {
271
+ if (!fits() && safeCwd) {
245
272
  const others = parts.slice(0, -1).join(sep).length + (parts.length > 1 ? sep.length : 0);
246
- parts[parts.length - 1] = shortPath(info.cwd, Math.max(8, maxw - others));
273
+ parts[parts.length - 1] = shortPath(safeCwd, Math.max(8, maxw - others));
247
274
  }
248
275
  while (!fits() && parts.length > 1)
249
276
  parts.pop();
@@ -283,7 +310,8 @@ function layoutCompact(caps, info, active) {
283
310
  });
284
311
  }
285
312
  function layoutMini(caps, info) {
286
- const ver = info.version ? ' v' + String(info.version).replace(/^v/, '') : '';
313
+ const safeVer = cleanMeta(info.version).replace(/^v/, '');
314
+ const ver = safeVer ? ' v' + safeVer : '';
287
315
  let line = txt(caps.unicode ? '■' : '#', 'lime', caps) + ' ' + txt('CAUSYNE', 'white', caps, undefined, true) + txt(' AGENT', 'lime', caps, undefined, true);
288
316
  if (ver && 'x CAUSYNE AGENT'.length + ver.length <= caps.width - 2)
289
317
  line += txt(ver, 'dim', caps);
@@ -402,9 +430,18 @@ export function pickExample() {
402
430
  /** Drop complete hint fragments until the remaining line fits. */
403
431
  export function fitHints(parts, width, fallback) {
404
432
  const separator = ' · ';
405
- const kept = parts.slice();
406
- while (kept.length > 1 && kept.join(separator).length > width)
433
+ const safeParts = Array.isArray(parts) ? parts : [];
434
+ if (!Number.isFinite(width))
435
+ return width === Number.POSITIVE_INFINITY ? safeParts.join(separator) : '';
436
+ const limit = Math.floor(width);
437
+ if (limit <= 0)
438
+ return '';
439
+ const kept = safeParts.slice();
440
+ while (kept.length > 1 && kept.join(separator).length > limit)
407
441
  kept.pop();
408
442
  const line = kept.join(separator);
409
- return line.length <= width ? line : fallback;
443
+ if (line.length <= limit)
444
+ return line;
445
+ const safeFallback = typeof fallback === 'string' ? fallback : '';
446
+ return safeFallback.length <= limit ? safeFallback : safeFallback.slice(0, limit);
410
447
  }
package/src/tui/banner.ts CHANGED
@@ -7,6 +7,13 @@
7
7
  * CAUSYNE_ASCII=1 (7-bit only), and CAUSYNE_NO_ANIM=1.
8
8
  */
9
9
  import { homedir } from 'node:os';
10
+ import { safeDisplay } from './text.js';
11
+
12
+ function cleanMeta(value: unknown): string {
13
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? ''))
14
+ .replace(/[\r\n]+/g, ' ')
15
+ .trim();
16
+ }
10
17
 
11
18
  export type ColorMode = 'truecolor' | '256' | '16' | 'none';
12
19
  export type Variant = 'full' | 'compact' | 'mini';
@@ -147,31 +154,43 @@ function pickVariant(c: Pick<Caps, 'width' | 'height' | 'unicode'>): Variant {
147
154
  if (c.width < 80 || c.height < 24 || !c.unicode) return 'compact';
148
155
  return 'full';
149
156
  }
157
+ const VALID_COLORS = new Set<ColorMode>(['truecolor', '256', '16', 'none']);
158
+ const VALID_VARIANTS = new Set<Variant>(['full', 'compact', 'mini']);
159
+
150
160
  export function detect(o: BannerOptions = {}, stream: TermStream = process.stdout): Caps {
151
- const env = process.env, tty = Boolean(stream.isTTY);
152
- const width = o.width || stream.columns || 80, height = o.height || stream.rows || 24;
153
- const want = o.color;
161
+ const opts: BannerOptions = o && typeof o === 'object' ? o : {};
162
+ const safeStream: Partial<TermStream> = stream && typeof stream === 'object' ? stream : {};
163
+ const env = process.env, tty = Boolean(safeStream.isTTY);
164
+ const positiveDim = (v: unknown, fallback: number): number => {
165
+ const n = Number(v);
166
+ return Number.isFinite(n) && n >= 1 ? Math.floor(n) : fallback;
167
+ };
168
+ const width = positiveDim(opts.width, positiveDim(safeStream.columns, 80));
169
+ const height = positiveDim(opts.height, positiveDim(safeStream.rows, 24));
170
+ const want = opts.color;
154
171
  let color: ColorMode;
155
172
  if (want === true) color = 'truecolor';
156
173
  else if (want === false) color = 'none';
157
- else if (want !== undefined && want !== 'auto') color = want;
174
+ else if (typeof want === 'string' && VALID_COLORS.has(want as ColorMode)) color = want as ColorMode;
158
175
  else {
159
176
  const f = env['FORCE_COLOR'];
160
177
  if (f !== undefined && f !== '') color = FORCE[f] ?? '16';
161
178
  else if (env['NO_COLOR'] || env['CAUSYNE_NO_COLOR'] === '1') color = 'none';
162
179
  else if (!tty || env['TERM'] === 'dumb') color = 'none';
163
180
  else {
164
- const d = stream.getColorDepth?.() ?? 4;
181
+ const d = safeStream.getColorDepth?.() ?? 4;
165
182
  color = /truecolor|24bit/i.test(env['COLORTERM'] ?? '') || d >= 24 ? 'truecolor' : d >= 8 ? '256' : d >= 4 ? '16' : 'none';
166
183
  }
167
184
  }
168
- let unicode = o.unicode;
185
+ let unicode = opts.unicode;
169
186
  if (unicode === undefined) {
170
187
  const loc = env['LC_ALL'] || env['LC_CTYPE'] || env['LANG'] || '', ascii = env['CAUSYNE_ASCII'];
171
188
  unicode = !(ascii && ascii !== '0') && !(process.platform !== 'win32' && loc !== '' && !/utf-?8/i.test(loc));
172
189
  }
173
- const caps: Caps = { tty, width, height, color, unicode, variant: 'full' };
174
- caps.variant = o.variant && o.variant !== 'auto' ? o.variant : pickVariant(caps);
190
+ const caps: Caps = { tty, width, height, color, unicode: Boolean(unicode), variant: 'full' };
191
+ caps.variant = typeof opts.variant === 'string' && VALID_VARIANTS.has(opts.variant as Variant)
192
+ ? (opts.variant as Variant)
193
+ : pickVariant(caps);
175
194
  return caps;
176
195
  }
177
196
 
@@ -226,7 +245,11 @@ function cells(px: Canvas, caps: Caps): string[] {
226
245
  return lines;
227
246
  }
228
247
  function txt(str: string, key: Key, caps: Caps, maxw?: number, bold?: boolean): string {
229
- if (maxw !== undefined && str.length > maxw) str = str.slice(0, Math.max(0, maxw - 1)) + (caps.unicode ? '…' : '~');
248
+ if (maxw !== undefined) {
249
+ const limit = Number.isFinite(maxw) ? Math.floor(maxw) : maxw === Number.POSITIVE_INFINITY ? str.length : 0;
250
+ if (limit <= 0) return '';
251
+ if (str.length > limit) str = str.slice(0, Math.max(0, limit - 1)) + (caps.unicode ? '…' : '~');
252
+ }
230
253
  if (caps.color === 'none') return str;
231
254
  return ESC + (bold ? '1;' : '') + fgCode(key, caps.color) + 'm' + str + RESET;
232
255
  }
@@ -240,13 +263,18 @@ function shortPath(p: string, maxw: number): string {
240
263
  }
241
264
  function statusLine(info: BannerInfo, maxw: number, unicode: boolean): string {
242
265
  const sep = unicode ? ' · ' : ' | ';
243
- const providerModel = [info.provider, info.model].filter(Boolean).join('/');
266
+ const safeProvider = cleanMeta(info.provider);
267
+ const safeModel = cleanMeta(info.model);
268
+ const safeVersion = cleanMeta(info.version).replace(/^v/, '');
269
+ const safeMode = cleanMeta(info.mode);
270
+ const safeCwd = cleanMeta(info.cwd);
271
+ const providerModel = [safeProvider, safeModel].filter(Boolean).join('/');
244
272
  const providerPart = providerModel || 'select provider';
245
- const parts = [info.version ? 'v' + String(info.version).replace(/^v/, '') : '', providerPart, info.mode ?? '', info.cwd ?? ''].filter(Boolean);
273
+ const parts = [safeVersion ? 'v' + safeVersion : '', providerPart, safeMode, safeCwd].filter(Boolean);
246
274
  const fits = (): boolean => parts.join(sep).length <= maxw;
247
- if (!fits() && info.cwd) {
275
+ if (!fits() && safeCwd) {
248
276
  const others = parts.slice(0, -1).join(sep).length + (parts.length > 1 ? sep.length : 0);
249
- parts[parts.length - 1] = shortPath(info.cwd, Math.max(8, maxw - others));
277
+ parts[parts.length - 1] = shortPath(safeCwd, Math.max(8, maxw - others));
250
278
  }
251
279
  while (!fits() && parts.length > 1) parts.pop();
252
280
  return parts.join(sep);
@@ -281,7 +309,8 @@ function layoutCompact(caps: Caps, info: BannerInfo, active: number): string[] {
281
309
  });
282
310
  }
283
311
  function layoutMini(caps: Caps, info: BannerInfo): string[] {
284
- const ver = info.version ? ' v' + String(info.version).replace(/^v/, '') : '';
312
+ const safeVer = cleanMeta(info.version).replace(/^v/, '');
313
+ const ver = safeVer ? ' v' + safeVer : '';
285
314
  let line = txt(caps.unicode ? '■' : '#', 'lime', caps) + ' ' + txt('CAUSYNE', 'white', caps, undefined, true) + txt(' AGENT', 'lime', caps, undefined, true);
286
315
  if (ver && 'x CAUSYNE AGENT'.length + ver.length <= caps.width - 2) line += txt(ver, 'dim', caps);
287
316
  return [' ' + line];
@@ -408,8 +437,14 @@ export function pickExample(): string {
408
437
  /** Drop complete hint fragments until the remaining line fits. */
409
438
  export function fitHints(parts: string[], width: number, fallback: string): string {
410
439
  const separator = ' · ';
411
- const kept = parts.slice();
412
- while (kept.length > 1 && kept.join(separator).length > width) kept.pop();
440
+ const safeParts = Array.isArray(parts) ? parts : [];
441
+ if (!Number.isFinite(width)) return width === Number.POSITIVE_INFINITY ? safeParts.join(separator) : '';
442
+ const limit = Math.floor(width);
443
+ if (limit <= 0) return '';
444
+ const kept = safeParts.slice();
445
+ while (kept.length > 1 && kept.join(separator).length > limit) kept.pop();
413
446
  const line = kept.join(separator);
414
- return line.length <= width ? line : fallback;
447
+ if (line.length <= limit) return line;
448
+ const safeFallback = typeof fallback === 'string' ? fallback : '';
449
+ return safeFallback.length <= limit ? safeFallback : safeFallback.slice(0, limit);
415
450
  }
package/src/tui/block.js CHANGED
@@ -27,6 +27,12 @@ import { visibleWidth, padEnd, truncate, wrap } from './text.js';
27
27
  // Columns between the bar and the text. opencode uses paddingLeft={2} inside its
28
28
  // bordered box; one column belongs to the bar, so the gutter is one more.
29
29
  const GUTTER = 1;
30
+ function finiteWidth(width, fallback = 80) {
31
+ return typeof width === 'number' && Number.isFinite(width) ? Math.floor(width) : fallback;
32
+ }
33
+ function collapseLine(value) {
34
+ return String(value == null ? '' : value).replace(/[\r\n]+/g, ' ');
35
+ }
30
36
  /**
31
37
  * Render `lines` as one block with a left accent bar.
32
38
  * Uses a continuous unbroken box-drawing heavy rule (barHeavy '┃')
@@ -36,21 +42,25 @@ const GUTTER = 1;
36
42
  * @param options configuration options
37
43
  * @returns rows, each exactly `width` columns wide
38
44
  */
39
- export function barBlock(lines, { width = 80, role = 'accent', filled = true, surface = 'surface', punctuate = false } = {}) {
45
+ export function barBlock(lines, options = {}) {
46
+ const { width = 80, role = 'accent', filled = true, surface = 'surface', punctuate = false } = options || {};
47
+ void punctuate;
40
48
  // Use continuous heavy vertical line ('┃') for clean, solid, unbroken alignment.
41
49
  // Box-drawing characters connect seamlessly across lines in all terminal fonts without line-height leading gaps.
42
50
  const glyph = GLYPHS.barHeavy || GLYPHS.bar || '┃';
43
51
  const barWidth = visibleWidth(glyph);
44
- const body = Math.max(1, width - barWidth - GUTTER);
52
+ const body = Math.max(1, finiteWidth(width) - barWidth - GUTTER);
45
53
  const bar = paint(role, glyph);
46
54
  const gutter = ' '.repeat(GUTTER);
47
- return lines.map((line) => {
55
+ return (Array.isArray(lines) ? lines : []).map((rawLine) => {
48
56
  // Clip first, then pad: a line longer than the block would otherwise push
49
57
  // the fill past the right edge and wrap, which is the failure ChatPrompt
50
58
  // clampRows() exists to prevent one layer up.
59
+ const line = collapseLine(rawLine);
51
60
  const clipped = visibleWidth(line) > body ? truncate(line, body, GLYPHS.ellipsis) : line;
52
61
  const padded = padEnd(clipped, body);
53
- const inner = filled ? fill(surface, gutter + padded) : gutter + padded;
62
+ const tailReset = !filled && clipped.includes('\x1b[') ? '\x1b[0m' : '';
63
+ const inner = filled ? fill(surface, gutter + padded) : gutter + padded + tailReset;
54
64
  return bar + inner;
55
65
  });
56
66
  }
@@ -61,20 +71,26 @@ export function barBlock(lines, { width = 80, role = 'accent', filled = true, su
61
71
  * rows individually (the prompt editor, a status row) use barBlock directly.
62
72
  */
63
73
  export function blockOf(text, options = {}) {
64
- const width = options.width || 80;
74
+ const safeOptions = options || {};
75
+ const safeWidth = Math.max(4, finiteWidth(safeOptions.width));
65
76
  const glyph = GLYPHS.barHeavy || GLYPHS.bar || '┃';
66
- const inner = Math.max(1, width - visibleWidth(glyph) - GUTTER);
77
+ const inner = Math.max(1, safeWidth - visibleWidth(glyph) - GUTTER);
67
78
  const lines = wrap(String(text == null ? '' : text), inner);
68
- return barBlock(lines.length ? lines : [''], options);
79
+ return barBlock(lines.length ? lines : [''], { ...safeOptions, width: safeWidth });
69
80
  }
70
81
  /**
71
82
  * A bordered panel with its title inset into the top border.
72
83
  */
73
- export function panel(rows, { width = 80, title = '', role = 'rule' } = {}) {
74
- const inner = Math.max(4, width - 2);
84
+ export function panel(rows, options = {}) {
85
+ const { width = 80, title = '', role = 'rule' } = options || {};
86
+ const inner = Math.max(4, finiteWidth(width) - 2);
75
87
  const h = GLYPHS.hLine;
76
- const label = title ? ` ${title} ` : '';
77
- const clippedLabel = visibleWidth(label) > inner - 2 ? '' : label;
88
+ const cleanTitle = collapseLine(title).trim();
89
+ const maxTitleChars = inner - 3;
90
+ const boundedTitle = cleanTitle && maxTitleChars >= 3
91
+ ? truncate(cleanTitle, maxTitleChars, GLYPHS.ellipsis)
92
+ : '';
93
+ const clippedLabel = boundedTitle ? ` ${boundedTitle} ` : '';
78
94
  const lead = clippedLabel ? h : '';
79
95
  const trail = h.repeat(Math.max(0, inner - visibleWidth(clippedLabel) - visibleWidth(lead)));
80
96
  const top = paint(role, GLYPHS.topLeft + lead)
@@ -82,9 +98,11 @@ export function panel(rows, { width = 80, title = '', role = 'rule' } = {}) {
82
98
  + paint(role, trail + GLYPHS.topRight);
83
99
  const bottom = paint(role, GLYPHS.bottomLeft + h.repeat(inner) + GLYPHS.bottomRight);
84
100
  const side = paint(role, GLYPHS.vLine);
85
- const middle = rows.map((row) => {
101
+ const middle = (Array.isArray(rows) ? rows : []).map((rawRow) => {
102
+ const row = collapseLine(rawRow);
86
103
  const clipped = visibleWidth(row) > inner ? truncate(row, inner, GLYPHS.ellipsis) : row;
87
- return side + padEnd(clipped, inner) + side;
104
+ const borderReset = clipped.includes('\x1b[') ? '\x1b[0m' : '';
105
+ return side + padEnd(clipped, inner) + borderReset + side;
88
106
  });
89
107
  return [top, ...middle, bottom];
90
108
  }
@@ -92,15 +110,24 @@ export function panel(rows, { width = 80, title = '', role = 'rule' } = {}) {
92
110
  * `9.2K (5%)` — what the context window has left, at a glance.
93
111
  */
94
112
  export function contextMeter(usedTokens, limitTokens) {
95
- const used = Number(usedTokens) || 0;
96
- const limit = Number(limitTokens) || 0;
113
+ const rawUsed = Number(usedTokens);
114
+ const rawLimit = Number(limitTokens);
115
+ const used = Number.isFinite(rawUsed) ? rawUsed : 0;
116
+ const limit = Number.isFinite(rawLimit) ? rawLimit : 0;
97
117
  if (used <= 0)
98
118
  return '';
99
- const compact = used < 1000
100
- ? String(Math.round(used))
101
- : used < 1000000
102
- ? `${(used / 1000).toFixed(used < 10000 ? 1 : 0)}K`
103
- : `${(used / 1000000).toFixed(1)}M`;
119
+ const rounded = Math.round(used);
120
+ let compact;
121
+ if (rounded < 1000) {
122
+ compact = String(rounded);
123
+ }
124
+ else if (used < 9950) {
125
+ compact = `${(used / 1000).toFixed(1)}K`;
126
+ }
127
+ else {
128
+ const thousands = Math.round(used / 1000);
129
+ compact = thousands < 1000 ? `${thousands}K` : `${(used / 1000000).toFixed(1)}M`;
130
+ }
104
131
  if (limit <= 0)
105
132
  return compact;
106
133
  return `${compact} (${Math.round((used / limit) * 100)}%)`;