@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
@@ -57,9 +57,11 @@ const REASONING_LINES = 12;
57
57
  const STATUS_GUTTER = 10;
58
58
 
59
59
  function formatDuration(ms) {
60
- if (ms < 1000) return `${ms}ms`;
60
+ if (!Number.isFinite(ms) || ms <= 0) return '0ms';
61
+ if (ms < 1000) return `${Math.round(ms)}ms`;
61
62
  if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
62
- return `${Math.floor(ms / 60000)}m ${Math.round((ms % 60000) / 1000)}s`;
63
+ const totalSeconds = Math.round(ms / 1000);
64
+ return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
63
65
  }
64
66
 
65
67
  /**
@@ -70,7 +72,14 @@ function formatDuration(ms) {
70
72
  * inline code, fenced blocks and list bullets. Anything fancier belongs in a
71
73
  * pager, not a chat transcript.
72
74
  */
75
+ function clampMarkdownIndent(raw, markerCols, targetWidth) {
76
+ const maxLead = Math.max(0, Math.min(Math.floor(targetWidth / 3), targetWidth - markerCols - 8));
77
+ const rawCols = visibleWidth(String(raw || '').replace(/\t/g, ' '));
78
+ return ' '.repeat(Math.min(rawCols, maxLead));
79
+ }
80
+
73
81
  function renderMarkdown(text, width) {
82
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.max(12, Math.floor(width)) : 80;
74
83
  const lines = [];
75
84
  let inFence = false;
76
85
 
@@ -80,11 +89,14 @@ function renderMarkdown(text, width) {
80
89
  if (/^\s*```/.test(line)) {
81
90
  inFence = !inFence;
82
91
  const language = line.replace(/^\s*```/, '').trim();
83
- lines.push(dim(`${GLYPHS.hLine.repeat(3)}${language ? ' ' + language + ' ' : ' '}${GLYPHS.hLine.repeat(Math.max(0, width - 6 - language.length))}`));
92
+ const maxLabel = Math.max(0, safeWidth - 8);
93
+ const safeLang = language.length > maxLabel ? language.slice(0, maxLabel) : language;
94
+ const trail = Math.max(0, safeWidth - 3 - (safeLang ? safeLang.length + 2 : 1));
95
+ lines.push(dim(`${GLYPHS.hLine.repeat(3)}${safeLang ? ' ' + safeLang + ' ' : ' '}${GLYPHS.hLine.repeat(trail)}`));
84
96
  continue;
85
97
  }
86
98
  if (inFence) {
87
- for (const codeRow of wrapBlock(' ' + line, Math.max(8, width), { hang: 0 })) {
99
+ for (const codeRow of wrapBlock(' ' + line, Math.max(8, safeWidth), { hang: 0 })) {
88
100
  lines.push(paint('accent', codeRow));
89
101
  }
90
102
  continue;
@@ -93,21 +105,21 @@ function renderMarkdown(text, width) {
93
105
  const heading = line.match(/^(#{1,6})\s+(.*)$/);
94
106
  if (heading) {
95
107
  lines.push('');
96
- for (const headingRow of wrap(heading[2], Math.max(8, width))) {
108
+ for (const headingRow of wrap(heading[2], Math.max(8, safeWidth))) {
97
109
  lines.push(bold(paint('ink', headingRow)));
98
110
  }
99
111
  continue;
100
112
  }
101
113
 
102
114
  if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
103
- lines.push(dim(GLYPHS.hLine.repeat(Math.max(4, Math.min(width, 40)))));
115
+ lines.push(dim(GLYPHS.hLine.repeat(Math.max(4, Math.min(safeWidth, 40)))));
104
116
  continue;
105
117
  }
106
118
 
107
119
  const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
108
120
  if (bullet) {
109
- const indent = bullet[1] + ' ';
110
- const wrapped = wrap(inline(bullet[2]), width - indent.length - 2);
121
+ const indent = clampMarkdownIndent(bullet[1], 4, safeWidth) + ' ';
122
+ const wrapped = wrap(inline(bullet[2]), Math.max(8, safeWidth - indent.length - 2));
111
123
  wrapped.forEach((part, index) => {
112
124
  lines.push(index === 0 ? `${indent}${paint('muted', GLYPHS.bullet)} ${part}` : `${indent} ${part}`);
113
125
  });
@@ -116,9 +128,12 @@ function renderMarkdown(text, width) {
116
128
 
117
129
  const numbered = line.match(/^(\s*)(\d+\.)\s+(.*)$/);
118
130
  if (numbered) {
119
- const prefix = `${numbered[1]}${bold(numbered[2])} `;
120
- const indent = ' '.repeat(visibleWidth(`${numbered[1]}${numbered[2]} `));
121
- const wrapped = wrap(inline(numbered[3]), width - indent.length);
131
+ const markerCols = visibleWidth(numbered[2]) + 1;
132
+ const lead = clampMarkdownIndent(numbered[1], markerCols, safeWidth);
133
+ const prefix = `${lead}${bold(numbered[2])} `;
134
+ const indentCols = visibleWidth(lead) + markerCols;
135
+ const indent = ' '.repeat(indentCols);
136
+ const wrapped = wrap(inline(numbered[3]), Math.max(8, safeWidth - indentCols));
122
137
  wrapped.forEach((part, index) => {
123
138
  lines.push(index === 0 ? `${prefix}${part}` : `${indent}${part}`);
124
139
  });
@@ -127,8 +142,9 @@ function renderMarkdown(text, width) {
127
142
 
128
143
  const quote = line.match(/^(\s*)>\s?(.*)$/);
129
144
  if (quote) {
130
- const indent = quote[1] + paint('muted', '│ ');
131
- const wrapped = wrap(inline(quote[2]), width - visibleWidth(indent));
145
+ const lead = clampMarkdownIndent(quote[1], 2, safeWidth);
146
+ const indent = lead + paint('muted', '│ ');
147
+ const wrapped = wrap(inline(quote[2]), Math.max(8, safeWidth - visibleWidth(lead) - 2));
132
148
  wrapped.forEach((part) => {
133
149
  lines.push(`${indent}${part}`);
134
150
  });
@@ -136,14 +152,14 @@ function renderMarkdown(text, width) {
136
152
  }
137
153
 
138
154
  if (/^\s*\|?(\s*:?-+:?\s*\|)+\s*$/.test(line)) {
139
- lines.push(dim(' ' + GLYPHS.hLine.repeat(Math.max(4, Math.min(width - 4, 48)))));
155
+ lines.push(dim(' ' + GLYPHS.hLine.repeat(Math.max(4, Math.min(safeWidth - 4, 48)))));
140
156
  continue;
141
157
  }
142
158
 
143
159
  const tableRow = line.match(/^\s*\|(.+)\|\s*$/);
144
160
  if (tableRow) {
145
161
  const cells = tableRow[1].split('|').map(c => c.trim());
146
- for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, width), { hang: 0 })) {
162
+ for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, safeWidth), { hang: 0 })) {
147
163
  lines.push(inline(tableLine));
148
164
  }
149
165
  continue;
@@ -152,7 +168,7 @@ function renderMarkdown(text, width) {
152
168
  const trimmed = line.trim();
153
169
  if (trimmed === '') { lines.push(''); continue; }
154
170
  if (trimmed === '[' || trimmed === ']') continue;
155
- for (const part of wrap(inline(line), width)) lines.push(part);
171
+ for (const part of wrap(inline(line), safeWidth)) lines.push(part);
156
172
  }
157
173
 
158
174
  // A fence that never closed.
@@ -470,7 +486,7 @@ export class ChatRenderer {
470
486
 
471
487
  this.frame('turn', () => {
472
488
  const parts = [];
473
- if (model) parts.push(paint('ink', model));
489
+ if (model) parts.push(paint('ink', safeDisplay(model)));
474
490
  parts.push(`${steps} step${steps === 1 ? '' : 's'}`);
475
491
  if (durationMs > 0) parts.push(formatDuration(durationMs));
476
492
 
@@ -486,6 +502,7 @@ export class ChatRenderer {
486
502
  this.stepCount = 0;
487
503
  this.stepStartedAt = null;
488
504
  this.turnStartedAt = Date.now();
505
+ this._activeAssistant = false;
489
506
  this._activeReasoning = false;
490
507
  this.status.reset();
491
508
  }
@@ -563,10 +580,17 @@ export class ChatRenderer {
563
580
  if (!text.trim()) return;
564
581
 
565
582
  this.frame('user', () => {
566
- const width = this.transcript
567
- ? (this.transcript.surface?.composeWidth?.() ?? sessionComposerWidth(this.width()))
583
+ const measured = this.width();
584
+ const maxCaptureWidth = Math.max(8, Math.min(
585
+ measured,
586
+ this.transcript?.surface?.composeAvailableWidth?.() ?? measured
587
+ ) - 4);
588
+ const preferred = this.transcript
589
+ ? (this.transcript.surface?.composeWidth?.() ?? sessionComposerWidth(measured))
568
590
  : composerWidth(this.measure());
569
- const blockWidth = Math.max(8, width);
591
+ const blockWidth = this.transcript
592
+ ? Math.max(8, Math.min(preferred, maxCaptureWidth))
593
+ : Math.max(8, preferred);
570
594
  const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - 1);
571
595
  const rows = barBlock(
572
596
  wrapBlock(safeDisplay(text), innerWidth, { hang: 0 }),
@@ -594,19 +618,26 @@ export class ChatRenderer {
594
618
  renderSessionDivider(info = {}) {
595
619
  this.transcript?.surface?.setSessionInfo?.(info);
596
620
  this.frame('session', () => {
597
- const width = this.measure();
598
- const title = safeDisplay(info.title || 'Session');
599
- const count = info.messagesCount ?? 0;
600
- const countText = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
621
+ const width = Math.max(12, this.measure());
622
+ const rawTitle = safeDisplay((info && info.title) || 'Session');
623
+ const count = (info && info.messagesCount) ?? 0;
624
+ const rawCount = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
625
+ const countText = visibleWidth(rawCount) <= Math.max(0, width - 10) ? rawCount : '';
626
+ const title = truncate(rawTitle, Math.max(4, width - visibleWidth(countText) - 6), GLYPHS.ellipsis);
601
627
  const badgeText = `${title}${countText}`;
602
- const ruleWidth = Math.max(2, Math.floor((width - visibleWidth(badgeText) - 4) / 2));
628
+ const remaining = Math.max(2, width - visibleWidth(badgeText) - 2);
629
+ const leftRule = Math.max(1, Math.floor(remaining / 2));
630
+ const rightRule = Math.max(1, remaining - leftRule);
603
631
  this.write();
604
- this.write(`${paint('rule', GLYPHS.hLine.repeat(ruleWidth))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(ruleWidth))}`);
632
+ this.write(`${paint('rule', GLYPHS.hLine.repeat(leftRule))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(rightRule))}`);
605
633
  this.write();
606
634
  });
607
635
  }
608
636
 
609
637
  clearTranscript() {
638
+ this._activeAssistant = false;
639
+ this._activeReasoning = false;
640
+ this.lastOutput = null;
610
641
  if (this.transcript && typeof this.transcript.clear === 'function') {
611
642
  this.transcript.clear();
612
643
  }
@@ -617,6 +648,7 @@ export class ChatRenderer {
617
648
  * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
618
649
  */
619
650
  renderSessionHistory(messages = [], sessionInfo = null) {
651
+ const safeMessages = Array.isArray(messages) ? messages : [];
620
652
  const renderContent = () => {
621
653
  this.transcript?.surface?.leaveHome?.(true);
622
654
  this.clearTranscript();
@@ -625,32 +657,31 @@ export class ChatRenderer {
625
657
  this.resetTurn();
626
658
 
627
659
  const info = sessionInfo ? { ...sessionInfo } : {};
628
- if (info.messagesCount === undefined || info.messagesCount === null) {
629
- info.messagesCount = messages.filter(m => m && m.role !== 'system').length;
630
- }
631
- const measuredChars = measureMessages(messages);
632
- if (measuredChars > 0) {
660
+ if (info.messagesCount === undefined || info.messagesCount === null) {
661
+ info.messagesCount = safeMessages.filter(m => m && m.role !== 'system').length;
662
+ }
663
+ const measuredChars = measureMessages(safeMessages);
664
+ // Loading an empty session must clear usage from the previous chat.
633
665
  this.status.contextChars = measuredChars;
634
666
  info.contextChars = measuredChars;
635
- }
636
667
 
637
- if (info.title || info.id) {
638
- this.renderSessionDivider(info);
639
- }
668
+ if (info.title || info.id) {
669
+ this.renderSessionDivider(info);
670
+ }
640
671
 
641
- // Index tool results by tool_call_id to pair them with assistant tool_calls
642
- const toolResultsById = new Map();
643
- for (const m of messages) {
644
- if (m && m.role === 'tool' && m.tool_call_id) {
645
- toolResultsById.set(m.tool_call_id, m);
672
+ // Index tool results by tool_call_id to pair them with assistant tool_calls
673
+ const toolResultsById = new Map();
674
+ for (const m of safeMessages) {
675
+ if (m && m.role === 'tool' && m.tool_call_id) {
676
+ toolResultsById.set(m.tool_call_id, m);
677
+ }
646
678
  }
647
- }
648
679
 
649
- const renderedToolMessages = new Set();
680
+ const renderedToolMessages = new Set();
650
681
 
651
- for (let i = 0; i < messages.length; i++) {
652
- const msg = messages[i];
653
- if (!msg) continue;
682
+ for (let i = 0; i < safeMessages.length; i++) {
683
+ const msg = safeMessages[i];
684
+ if (!msg) continue;
654
685
  const role = String(msg.role || '').toLowerCase();
655
686
 
656
687
  if (role === 'user') {
@@ -693,6 +724,7 @@ export class ChatRenderer {
693
724
  // 3. If assistant invoked tool calls, render each tool step and pair with its result
694
725
  if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
695
726
  for (const call of msg.tool_calls) {
727
+ if (!call || typeof call !== 'object') continue;
696
728
  const toolName = call.function?.name || call.name || 'tool';
697
729
  let args = {};
698
730
  try {
@@ -706,7 +738,7 @@ export class ChatRenderer {
706
738
  // Restore active implementation plan if update_plan was called
707
739
  if (toolName === 'update_plan' && args && Array.isArray(args.plan)) {
708
740
  this.onAgentPlan({
709
- plan: args.plan.map(item => ({
741
+ plan: args.plan.filter(Boolean).map(item => ({
710
742
  ...item,
711
743
  text: item.text || item.step || item.content || ''
712
744
  }))
@@ -724,7 +756,7 @@ export class ChatRenderer {
724
756
  }
725
757
  if (toolName === 'update_plan' && Array.isArray(normalized.plan)) {
726
758
  this.onAgentPlan({
727
- plan: normalized.plan.map(item => ({
759
+ plan: normalized.plan.filter(Boolean).map(item => ({
728
760
  ...item,
729
761
  text: item.text || item.step || item.content || ''
730
762
  }))
@@ -743,7 +775,7 @@ export class ChatRenderer {
743
775
  ? msg.content
744
776
  : (Array.isArray(msg.content)
745
777
  ? msg.content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
746
- : String(msg.content || ''));
778
+ : (msg.content == null ? '' : String(msg.content)));
747
779
  // The agent loop stores a protocol placeholder when a peer emits no
748
780
  // final reply. Restoring it as a Causyne message falsely implies an
749
781
  // answer was given. Older histories have the literal but no marker.
@@ -751,7 +783,7 @@ export class ChatRenderer {
751
783
  || (text.trim() === 'No final response was provided.'
752
784
  && (!Array.isArray(msg.tool_calls) || msg.tool_calls.length === 0));
753
785
  if (syntheticNoFinal) {
754
- const isLatestTurn = !messages.slice(i + 1).some(next =>
786
+ const isLatestTurn = !safeMessages.slice(i + 1).some(next =>
755
787
  next && (next.role === 'assistant' || next.role === 'user'));
756
788
  if (isLatestTurn) {
757
789
  this.frame('notice', () => {
@@ -785,12 +817,15 @@ export class ChatRenderer {
785
817
  }
786
818
  }
787
819
 
788
- const finalMeasured = measureMessages(messages);
820
+ const finalMeasured = measureMessages(safeMessages);
789
821
  if (finalMeasured > 0) {
790
822
  this.status.contextChars = finalMeasured;
791
823
  }
792
824
  if (!this.status.contextLimit) {
793
- this.status.contextLimit = resolveCharPool(this.status.tier);
825
+ this.status.contextLimit = resolveCharPool(this.status.tier, undefined, {
826
+ provider: sessionInfo?.provider || this.status.provider,
827
+ model: sessionInfo?.model || this.status.model
828
+ });
794
829
  }
795
830
  if (sessionInfo) {
796
831
  this.status.setSession({
@@ -1005,20 +1040,24 @@ export class ChatRenderer {
1005
1040
  }
1006
1041
 
1007
1042
  onAgentActivity(msg) {
1043
+ if (!msg || typeof msg !== 'object') return;
1008
1044
  const text = String(msg.activity || msg.message || '').trim();
1009
1045
  if (!text) return;
1010
1046
  this.frame('notice', () => {
1011
1047
  const prefix = `${GLYPHS.arrow || '▸'} `;
1012
1048
  for (const [index, row] of activityRows(text, this.width(), prefix).entries()) {
1013
- this.write(index === 0
1014
- ? `${paint('accent', GLYPHS.arrow || '▸')} ${dim(row.slice(prefix.length))}`
1015
- : dim(row));
1049
+ if (index === 0) {
1050
+ const body = row.startsWith(prefix) ? row.slice(prefix.length) : row;
1051
+ this.write(`${paint('accent', GLYPHS.arrow || '▸')} ${dim(body)}`);
1052
+ } else {
1053
+ this.write(dim(row));
1054
+ }
1016
1055
  }
1017
1056
  }, { activity: true });
1018
1057
  }
1019
1058
 
1020
1059
  onAgentPlan(msg) {
1021
- if (!Array.isArray(msg.plan) || msg.plan.length === 0) return;
1060
+ if (!msg || !Array.isArray(msg.plan) || msg.plan.length === 0) return;
1022
1061
  const plan = msg.plan.slice();
1023
1062
  this.latestPlan = plan;
1024
1063
  const placement = this.onPlanChange?.(plan);
@@ -1028,7 +1067,7 @@ export class ChatRenderer {
1028
1067
 
1029
1068
  onDecisionRequest(msg) {
1030
1069
  if (this.dialogWillAsk) return;
1031
- const request = msg.request || {};
1070
+ const request = (msg && msg.request) || {};
1032
1071
  this.frame('approval', () => {
1033
1072
  this.write();
1034
1073
  this.write(`${paint('accent', GLYPHS.arrow)} ${bold(safeDisplay(request.header || 'decision required'))}`);
@@ -1038,8 +1077,8 @@ export class ChatRenderer {
1038
1077
  }
1039
1078
 
1040
1079
  onDecisionResult(msg) {
1041
- const request = msg.request || {};
1042
- const answer = msg.answer;
1080
+ const request = (msg && msg.request) || {};
1081
+ const answer = msg && msg.answer;
1043
1082
  this.frame('approval', () => {
1044
1083
  if (!answer) {
1045
1084
  this.write(` ${paint('muted', 'decision dismissed')} ${safeDisplay(request.header || '')}`);
@@ -1050,10 +1089,12 @@ export class ChatRenderer {
1050
1089
  }
1051
1090
 
1052
1091
  renderPlan(plan) {
1092
+ if (!Array.isArray(plan) || plan.length === 0) return;
1053
1093
  const width = this.width();
1054
1094
  this.write();
1055
1095
  this.write(paint('muted', 'plan'));
1056
1096
  for (const item of plan) {
1097
+ if (!item || typeof item !== 'object') continue;
1057
1098
  const done = item.status === 'completed';
1058
1099
  const active = item.status === 'in_progress';
1059
1100
  const mark = done ? paint('success', GLYPHS.check)
@@ -1061,35 +1102,39 @@ export class ChatRenderer {
1061
1102
  : paint('muted', GLYPHS.dot);
1062
1103
  const text = item.text || item.step || item.content || '';
1063
1104
  const label = done ? dim(safeDisplay(text)) : paint('ink', safeDisplay(text));
1064
- this.write(` ${mark} ${truncate(label, width - 5, GLYPHS.ellipsis)}`);
1105
+ this.write(` ${mark} ${truncate(label, Math.max(8, width - 5), GLYPHS.ellipsis)}`);
1065
1106
  }
1066
1107
  this.write();
1067
1108
  }
1068
1109
 
1069
1110
  onStepStart(msg) {
1111
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1070
1112
  this.stepStartedAt = Date.now();
1071
1113
  this.stepCount++;
1072
1114
 
1073
- const { verb, detail } = describeTool(msg.tool, msg.args);
1115
+ const toolLabel = safeDisplay(safeMsg.tool || 'tool') || 'tool';
1116
+ const { verb, detail } = describeTool(safeMsg.tool, safeMsg.args);
1074
1117
  const step = this.stepCount;
1075
1118
 
1076
1119
  this.frame('step', () => {
1077
1120
  const width = this.width();
1078
1121
  const index = paint('muted', String(step).padStart(2, '0'));
1079
- const name = paint('accent', padEnd(verb || msg.tool, STATUS_GUTTER));
1122
+ const displayVerb = verb || toolLabel;
1123
+ const name = paint('accent', padEnd(displayVerb, STATUS_GUTTER));
1080
1124
 
1081
- const used = 2 + 2 + 1 + Math.max(visibleWidth(verb || msg.tool), STATUS_GUTTER) + 1;
1125
+ const used = 2 + 2 + 1 + Math.max(visibleWidth(displayVerb), STATUS_GUTTER) + 1;
1082
1126
  const detailText = detail ? paint('ink', truncate(detail, Math.max(10, width - used - 12), GLYPHS.ellipsis)) : '';
1083
1127
 
1084
1128
  this.write(`${paint('muted', GLYPHS.arrow)} ${index} ${name} ${detailText}`);
1085
- }, { step, tool: msg.tool, verb: verb || msg.tool, detail });
1129
+ }, { step, tool: safeMsg.tool, verb: verb || toolLabel, detail });
1086
1130
  }
1087
1131
 
1088
1132
  onStepComplete(msg) {
1089
- const elapsed = typeof msg?.elapsed === 'string'
1090
- ? msg.elapsed
1133
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1134
+ const elapsed = typeof safeMsg.elapsed === 'string'
1135
+ ? safeMsg.elapsed
1091
1136
  : (this.stepStartedAt ? formatDuration(Date.now() - this.stepStartedAt) : '');
1092
- const result = msg.result || {};
1137
+ const result = safeMsg.result || {};
1093
1138
 
1094
1139
  // Kept so Ctrl+O can show the whole thing, and set here rather than inside
1095
1140
  // the closure — a reflow must not re-point "the last output" at a tool
@@ -1147,14 +1192,14 @@ export class ChatRenderer {
1147
1192
  // leave two frames showing two different outputs, not one shown twice.
1148
1193
  const output = this.lastOutput;
1149
1194
  this.frame('result', () => {
1150
- const width = this.width() - 7;
1195
+ const width = Math.max(8, this.width() - 7);
1151
1196
  this.write('');
1152
1197
  for (const line of String(output.text).split('\n')) {
1153
1198
  for (const part of wrap(safeDisplay(line), width)) {
1154
1199
  this.write(` ${paint('rule', GLYPHS.vLine)} ${dim(part)}`);
1155
1200
  }
1156
1201
  }
1157
- if (output.spillPath) {
1202
+ if (output.spillPath) {
1158
1203
  this.write(this.clipHint(output.spillPath));
1159
1204
  }
1160
1205
  this.write('');
@@ -1166,7 +1211,8 @@ export class ChatRenderer {
1166
1211
  * Remember the payload Ctrl+O expands. Separate from rendering it, because
1167
1212
  * rendering runs again on every reflow and this must not.
1168
1213
  */
1169
- captureLastOutput(result = {}) {
1214
+ captureLastOutput(result) {
1215
+ if (!result || typeof result !== 'object') return;
1170
1216
  const payload = typeof result.output === 'string' ? result.output
1171
1217
  : typeof result.log === 'string' ? result.log
1172
1218
  : '';
@@ -1175,6 +1221,7 @@ export class ChatRenderer {
1175
1221
  }
1176
1222
 
1177
1223
  renderOutputPreview(result, toolName = '') {
1224
+ if (!result || typeof result !== 'object') return;
1178
1225
  const rawPayload = typeof result.output === 'string' ? result.output
1179
1226
  : typeof result.log === 'string' ? result.log
1180
1227
  : '';
@@ -1186,7 +1233,7 @@ export class ChatRenderer {
1186
1233
  : payload;
1187
1234
  if (!source.trim()) return;
1188
1235
 
1189
- const width = this.width() - 7;
1236
+ const width = Math.max(8, this.width() - 7);
1190
1237
  const cleaned = safeDisplay(source).replace(/\n{3,}/g, '\n\n').trim();
1191
1238
 
1192
1239
  // Wrap first, THEN cut — bounding by source newlines lets a single long
@@ -1252,7 +1299,8 @@ export class ChatRenderer {
1252
1299
  * loudly as the work trains the user to read neither.
1253
1300
  */
1254
1301
  onCheckpoint(msg) {
1255
- const where = typeof msg.path === 'string' ? shortenHome(msg.path) : '';
1302
+ if (!msg || typeof msg !== 'object') return;
1303
+ const where = typeof msg.path === 'string' ? safeDisplay(shortenHome(msg.path)) : '';
1256
1304
  const count = Number(msg.count) || 1;
1257
1305
  this.frame('checkpoint', () => {
1258
1306
  const label = where
@@ -1263,14 +1311,15 @@ export class ChatRenderer {
1263
1311
  }
1264
1312
 
1265
1313
  onStepError(msg) {
1314
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1266
1315
  // Wrapped and hanging-indented, not written as one long string.
1267
1316
  //
1268
1317
  // Loop-level failures now carry a real explanation across several lines —
1269
1318
  // what could not be reached, why, and what to check. Emitting that as a
1270
1319
  // single write put the continuation lines at column 0, under a marker
1271
1320
  // indented five columns, so the whole block read as unrelated fragments.
1272
- const label = `${msg.tool || ''}`.trim();
1273
- const rawError = msg.error || (msg.result && (msg.result.error || msg.result.message)) || '';
1321
+ const label = safeDisplay(`${safeMsg.tool || ''}`.trim());
1322
+ const rawError = safeMsg.error || (safeMsg.result && (safeMsg.result.error || safeMsg.result.message)) || '';
1274
1323
  const detail = safeDisplay(`${rawError}`.trim());
1275
1324
  const head = label && detail ? `${label} ${detail}` : (detail || label || 'failed');
1276
1325
 
@@ -1278,7 +1327,7 @@ export class ChatRenderer {
1278
1327
  const rows = wrapBlock(head, Math.max(20, this.width() - 7), { hang: 0 });
1279
1328
  this.write(` ${paint('danger', GLYPHS.cross)} ${paint('danger', rows[0] || '')}`);
1280
1329
  for (const row of rows.slice(1)) this.write(` ${dim(row)}`);
1281
- }, { tool: msg.tool });
1330
+ }, { tool: safeMsg.tool });
1282
1331
  }
1283
1332
 
1284
1333
  /**
@@ -1286,7 +1335,8 @@ export class ChatRenderer {
1286
1335
  * L6 in the local-path audit: a bare "Proceed?" is not human-in-the-loop.
1287
1336
  */
1288
1337
  onApprovalRequest(msg) {
1289
- this.pendingApprovals.set(msg.toolCallId, msg);
1338
+ if (!msg || typeof msg !== 'object') return;
1339
+ if (msg.toolCallId) this.pendingApprovals.set(msg.toolCallId, msg);
1290
1340
 
1291
1341
  // When an interactive dialog will ask the question, DO NOT also print the
1292
1342
  // whole request into the transcript. It shipped doing both: the same risk
@@ -1315,6 +1365,7 @@ export class ChatRenderer {
1315
1365
  }
1316
1366
 
1317
1367
  renderApprovalRequest(msg, diff = undefined) {
1368
+ if (!msg || typeof msg !== 'object') return;
1318
1369
  // Colour carries the tier; the word never reaches the user. See the note
1319
1370
  // in dialogs.js ApprovalLayer — 'DANGEROUS' printed at somebody installing a
1320
1371
  // package teaches them to stop reading these.
@@ -1325,7 +1376,7 @@ export class ChatRenderer {
1325
1376
  this.write();
1326
1377
  this.write(`${paint(role, GLYPHS.warnMark)} ${paint('ink', 'permission required')} ${bold(safeDisplay(msg.tool || ''))}${verb ? dim(` ${verb}`) : ''}`);
1327
1378
  if (detail) {
1328
- this.write(` ${paint('ink', truncate(detail, this.width() - 4, GLYPHS.ellipsis))}`);
1379
+ this.write(` ${paint('ink', truncate(detail, Math.max(8, this.width() - 4), GLYPHS.ellipsis))}`);
1329
1380
  }
1330
1381
 
1331
1382
  // What the user is actually consenting to. Without this the approval gate
@@ -1379,7 +1430,8 @@ export class ChatRenderer {
1379
1430
  }
1380
1431
 
1381
1432
  onError(msg) {
1382
- const message = safeDisplay(msg.message || '');
1433
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1434
+ const message = safeDisplay(safeMsg.message || '');
1383
1435
  this.frame('error', () => {
1384
1436
  this.write();
1385
1437
  for (const row of wrappedChatRows(message, this.width(), `${badge('danger', 'ERROR')} `, 'danger')) this.write(row);
@@ -1388,14 +1440,16 @@ export class ChatRenderer {
1388
1440
  }
1389
1441
 
1390
1442
  onBudgetWarning(msg) {
1391
- const message = safeDisplay(msg.message || '');
1443
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1444
+ const message = safeDisplay(safeMsg.message || '');
1392
1445
  this.frame('notice', () => {
1393
1446
  for (const row of wrappedChatRows(message, this.width(), `${badge('warn', 'BUDGET')} `, 'warn')) this.write(row);
1394
1447
  }, { tone: 'warn' });
1395
1448
  }
1396
1449
 
1397
1450
  onStatus(msg) {
1398
- this.startSpinner(msg.message || '');
1451
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1452
+ this.startSpinner(safeMsg.message || '');
1399
1453
  }
1400
1454
 
1401
1455
  /**
@@ -1414,9 +1468,9 @@ export class ChatRenderer {
1414
1468
  const head = `${paint('accent', GLYPHS.step)} ${bold(paint('ink', 'skill'))}`
1415
1469
  + `${dim(` ${GLYPHS.dot} `)}${paint('agent', safeDisplay(id))}`;
1416
1470
  this.write();
1417
- this.write(truncate(head, width - 1, GLYPHS.ellipsis));
1471
+ this.write(truncate(head, Math.max(8, width - 1), GLYPHS.ellipsis));
1418
1472
  if (instruction) {
1419
- for (const line of wrapBlock(safeDisplay(instruction), width - 4, { hang: 0 })) {
1473
+ for (const line of wrapBlock(safeDisplay(instruction), Math.max(8, width - 4), { hang: 0 })) {
1420
1474
  this.write(dim(` ${line}`));
1421
1475
  }
1422
1476
  }
@@ -1436,12 +1490,13 @@ export class ChatRenderer {
1436
1490
  * as loudly as the agent's answer trains the user to stop reading both.
1437
1491
  */
1438
1492
  onNotice(msg) {
1439
- const tone = ['accent', 'success', 'warn', 'muted'].includes(msg.tone) ? msg.tone : 'muted';
1440
- const message = safeDisplay(msg.message || '');
1493
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1494
+ const tone = ['accent', 'success', 'warn', 'muted'].includes(safeMsg.tone) ? safeMsg.tone : 'muted';
1495
+ const message = safeDisplay(safeMsg.message || '');
1441
1496
  this.frame('notice', () => {
1442
1497
  const width = this.measure();
1443
1498
  const marker = paint(tone === 'muted' ? 'rule' : tone, GLYPHS.vLine);
1444
- for (const line of wrapBlock(message, width - 2, { hang: 0 })) {
1499
+ for (const line of wrapBlock(message, Math.max(8, width - 2), { hang: 0 })) {
1445
1500
  this.write(`${marker} ${dim(line)}`);
1446
1501
  }
1447
1502
  }, { tone });
@@ -24,7 +24,6 @@ export function normalizeClipboardText(raw) {
24
24
  export function copyToClipboard(text) {
25
25
  if (typeof text !== 'string' || text.length === 0)
26
26
  return false;
27
- emitOsc52Copy(text);
28
27
  return writeClipboardSync(text);
29
28
  }
30
29
  /**
@@ -167,10 +166,13 @@ export function extractLastAssistantTurn(loop) {
167
166
  for (let i = loop.messages.length - 1; i >= 0; i--) {
168
167
  const msg = loop.messages[i];
169
168
  if (msg && msg.role === 'assistant') {
170
- if (typeof msg.content === 'string')
171
- return msg.content;
169
+ if (typeof msg.content === 'string') {
170
+ if (msg.content.trim())
171
+ return msg.content;
172
+ continue;
173
+ }
172
174
  if (Array.isArray(msg.content)) {
173
- return msg.content
175
+ const joined = msg.content
174
176
  .map((part) => {
175
177
  if (typeof part === 'string')
176
178
  return part;
@@ -181,6 +183,8 @@ export function extractLastAssistantTurn(loop) {
181
183
  })
182
184
  .filter(Boolean)
183
185
  .join('\n');
186
+ if (joined.trim())
187
+ return joined;
184
188
  }
185
189
  }
186
190
  }
@@ -208,7 +212,10 @@ export function runCopyCommand(argv, ctx) {
208
212
  return { ok: false, output: 'Chatbox input is currently empty.' };
209
213
  }
210
214
  const res = copyChatboxInput(ctx.prompt);
211
- return { ok: res.success, output: 'Copied chatbox input to clipboard.' };
215
+ return {
216
+ ok: res.success,
217
+ output: res.success ? 'Copied chatbox input to clipboard.' : 'Chatbox input is currently empty.'
218
+ };
212
219
  }
213
220
  if (argv.length > 0) {
214
221
  const customText = argv.join(' ');