@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
@@ -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,
@@ -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
  }