@causyne/agent 1.20.111 → 1.20.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +72 -37
  4. package/src/agentLoop.ts +70 -38
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +7 -2
  8. package/src/browser/causyneBrowser.ts +8 -2
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/computerUse/visionGrounding.js +31 -27
  18. package/src/computerUse/visionGrounding.ts +27 -27
  19. package/src/continuum/ui/continuumPicker.js +14 -6
  20. package/src/continuum/ui/continuumPicker.ts +13 -6
  21. package/src/continuum/ui/continuumPickerView.js +24 -15
  22. package/src/continuum/ui/continuumPickerView.ts +24 -16
  23. package/src/observer/advisory.js +32 -22
  24. package/src/observer/advisory.ts +30 -18
  25. package/src/observer/coldObserver.js +21 -33
  26. package/src/observer/coldObserver.ts +20 -33
  27. package/src/observer/evidence.js +20 -13
  28. package/src/observer/evidence.ts +21 -13
  29. package/src/observer.js +47 -12
  30. package/src/observer.ts +50 -18
  31. package/src/pluginsFactory/discovery.js +28 -16
  32. package/src/pluginsFactory/discovery.ts +29 -16
  33. package/src/pluginsFactory/pluginsFactory.js +213 -38
  34. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  35. package/src/pluginsFactory/strategy.js +26 -16
  36. package/src/pluginsFactory/strategy.ts +34 -19
  37. package/src/pluginsFactory/templates.js +183 -62
  38. package/src/pluginsFactory/templates.ts +174 -54
  39. package/src/timeMachine.js +43 -22
  40. package/src/timeMachine.ts +44 -22
  41. package/src/tool-scripts/desktop_act.applescript +1 -0
  42. package/src/tools/computerUse.js +23 -10
  43. package/src/tools/computerUse.ts +19 -8
  44. package/src/tools/desktopAct.js +12 -1
  45. package/src/tools/pluginsFactory.js +108 -5
  46. package/src/tools/pluginsFactory.ts +115 -5
  47. package/src/tui/CausyneRotor.js +24 -10
  48. package/src/tui/CausyneRotor.ts +25 -10
  49. package/src/tui/activityLayout.js +9 -5
  50. package/src/tui/activityLayout.ts +9 -5
  51. package/src/tui/ask.js +34 -14
  52. package/src/tui/banner.js +55 -18
  53. package/src/tui/banner.ts +52 -17
  54. package/src/tui/block.js +47 -20
  55. package/src/tui/block.ts +54 -27
  56. package/src/tui/chatRenderer.js +135 -83
  57. package/src/tui/chatboxClipboard.js +12 -5
  58. package/src/tui/chatboxClipboard.ts +10 -4
  59. package/src/tui/clipboardImage.js +52 -42
  60. package/src/tui/clipboardImage.ts +50 -39
  61. package/src/tui/clipboardSync.js +12 -1
  62. package/src/tui/clipboardSync.ts +9 -1
  63. package/src/tui/codeProgress.js +57 -26
  64. package/src/tui/codeProgress.ts +57 -25
  65. package/src/tui/codeStreamRenderer.js +59 -14
  66. package/src/tui/codeStreamRenderer.ts +58 -14
  67. package/src/tui/commandPresentation.js +9 -2
  68. package/src/tui/commandPresentation.ts +9 -2
  69. package/src/tui/completion.js +45 -23
  70. package/src/tui/composerControls.js +21 -10
  71. package/src/tui/composerControls.ts +18 -10
  72. package/src/tui/composerGeometry.js +6 -4
  73. package/src/tui/composerGeometry.ts +6 -4
  74. package/src/tui/consoleGuard.js +29 -7
  75. package/src/tui/consoleGuard.ts +28 -7
  76. package/src/tui/dialogs.js +134 -71
  77. package/src/tui/diff.js +8 -4
  78. package/src/tui/history.js +6 -5
  79. package/src/tui/home.js +25 -13
  80. package/src/tui/homeView.js +37 -18
  81. package/src/tui/homeView.ts +38 -18
  82. package/src/tui/inlineSlash.js +6 -5
  83. package/src/tui/inlineSlash.ts +6 -5
  84. package/src/tui/keys.js +33 -17
  85. package/src/tui/layout.js +27 -9
  86. package/src/tui/layout.ts +26 -9
  87. package/src/tui/lineEditor.js +49 -23
  88. package/src/tui/markdownMath.js +64 -14
  89. package/src/tui/markdownMath.ts +69 -13
  90. package/src/tui/messageActionPlacement.js +28 -13
  91. package/src/tui/messageActionPlacement.ts +28 -13
  92. package/src/tui/messageInteraction.js +111 -46
  93. package/src/tui/messageInteraction.ts +115 -47
  94. package/src/tui/modelPicker.js +44 -15
  95. package/src/tui/modelPicker.ts +48 -15
  96. package/src/tui/observerPicker.js +56 -13
  97. package/src/tui/observerPicker.ts +73 -30
  98. package/src/tui/overlay.js +79 -35
  99. package/src/tui/overlay.ts +81 -34
  100. package/src/tui/prompt.js +162 -94
  101. package/src/tui/runningLight.js +1 -1
  102. package/src/tui/runningLight.ts +1 -1
  103. package/src/tui/scrollInteraction.js +64 -36
  104. package/src/tui/scrollInteraction.ts +70 -37
  105. package/src/tui/selectList.js +60 -32
  106. package/src/tui/sessionLayout.js +11 -3
  107. package/src/tui/sessionLayout.ts +10 -3
  108. package/src/tui/sessionPicker.js +74 -46
  109. package/src/tui/sessionPicker.ts +73 -48
  110. package/src/tui/sessionPickerView.js +32 -19
  111. package/src/tui/sessionPickerView.ts +31 -18
  112. package/src/tui/sessionSidebar.js +87 -57
  113. package/src/tui/sessionSidebar.ts +90 -54
  114. package/src/tui/setup.js +28 -3
  115. package/src/tui/setup.ts +27 -3
  116. package/src/tui/skillAuthoring.js +11 -5
  117. package/src/tui/skillAuthoring.ts +11 -5
  118. package/src/tui/smartLinkClick.js +75 -23
  119. package/src/tui/smartLinkClick.ts +86 -26
  120. package/src/tui/stage.js +47 -16
  121. package/src/tui/stage.ts +53 -18
  122. package/src/tui/stageSurface.js +120 -49
  123. package/src/tui/statusLine.js +85 -53
  124. package/src/tui/statusLine.ts +82 -46
  125. package/src/tui/terminalInputFramer.js +5 -2
  126. package/src/tui/text.js +117 -46
  127. package/src/tui/text.ts +113 -43
  128. package/src/tui/textLayout.js +6 -4
  129. package/src/tui/textLayout.ts +11 -5
  130. package/src/tui/theme.js +17 -8
  131. package/src/tui/thinkingBox.js +95 -95
  132. package/src/tui/thinkingBox.ts +105 -80
  133. package/src/tui/toolActivityPolicy.js +8 -1
  134. package/src/tui/toolActivityPolicy.ts +7 -1
  135. package/src/tui/toolDisplay.js +15 -6
  136. package/src/tui/toolDisplay.ts +16 -6
  137. package/src/tui/toolOutputNormalizer.js +16 -3
  138. package/src/tui/toolOutputNormalizer.ts +13 -3
  139. package/src/tui/transcript.js +15 -9
  140. package/src/tui/turnRail.js +156 -67
  141. package/src/tui/turnRail.ts +155 -58
  142. package/src/tui/usageCard.js +80 -45
  143. package/src/tui/usageCard.ts +81 -46
  144. package/src/tui/viewport.js +48 -23
  145. package/src/tui/viewport.ts +48 -27
  146. package/src/tui/viewportAnchor.js +2 -2
  147. package/src/tui/viewportAnchor.ts +2 -2
  148. package/src/tui/workspaceFileIndex.js +8 -6
  149. package/src/tui/workspaceFileIndex.ts +8 -6
  150. package/src/tui/workspaceSwitch.js +13 -10
  151. package/src/tui/workspaceSwitch.ts +11 -7
@@ -3,9 +3,11 @@ import { padEnd, safeDisplay, stripAnsi, truncate } from './text.js';
3
3
  // @ts-expect-error theme.js has no TypeScript declaration yet.
4
4
  import { bold, dim, fill, paint } from './theme.js';
5
5
  export const SIDEBAR_WIDTH = 42;
6
- // A 42-column sidebar is only useful if the conversation retains a readable width.
7
- // Narrow IDE terminals should prioritize the user's complete message over metadata.
8
- export const SIDEBAR_THRESHOLD = 160;
6
+ export const COMPACT_SIDEBAR_WIDTH = 28;
7
+ // Show a compact responsive sidebar once past 100 columns so ordinary terminals
8
+ // and cmd windows do not have to be dragged excessively wide, while keeping <=100
9
+ // column IDE splits full-width for conversation readability.
10
+ export const SIDEBAR_THRESHOLD = 100;
9
11
  /** A side panel is useful only when a readable conversation column remains. */
10
12
  export function sidebarVisible(columns, home = false, env = typeof process !== 'undefined' ? process.env : {}) {
11
13
  if (env) {
@@ -15,41 +17,51 @@ export function sidebarVisible(columns, home = false, env = typeof process !== '
15
17
  }
16
18
  return !home && Number.isFinite(columns) && columns > SIDEBAR_THRESHOLD;
17
19
  }
20
+ /** Select a compact sidebar width on medium terminals and full width on wide screens. */
21
+ export function sessionSidebarWidth(columns, home = false, env = typeof process !== 'undefined' ? process.env : {}) {
22
+ if (!sidebarVisible(columns, home, env))
23
+ return 0;
24
+ const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
25
+ if (width < 120)
26
+ return COMPACT_SIDEBAR_WIDTH;
27
+ if (width < 150)
28
+ return 30;
29
+ if (width < 180)
30
+ return 34;
31
+ return SIDEBAR_WIDTH;
32
+ }
18
33
  /** Reserve the last terminal column so a wide row cannot wrap the stage. */
19
34
  export function sessionMainWidth(columns, home = false, env = typeof process !== 'undefined' ? process.env : {}) {
20
35
  const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
21
- return sidebarVisible(width, home, env) ? width - SIDEBAR_WIDTH - 1 : width;
36
+ const panelWidth = sessionSidebarWidth(width, home, env);
37
+ return panelWidth > 0 ? width - panelWidth - 1 : width;
22
38
  }
23
39
  /** The session input uses the available conversation column, with a small inset. */
24
40
  export function sessionComposerWidth(columns) {
25
41
  const available = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
26
- if (available <= 112) {
27
- return Math.max(20, available - 4);
28
- }
29
- // Dynamic readable measure scaling on wide terminals:
30
- const readableMeasure = Math.round(109 + 20 * Math.log2(available / 112));
31
- return Math.min(available - 4, Math.max(20, readableMeasure));
42
+ return Math.max(20, available - 4);
32
43
  }
33
44
  /** Render only facts the runtime can actually report. */
34
- export function sessionSidebarRows(facts, height) {
45
+ export function sessionSidebarRows(facts, height, width = SIDEBAR_WIDTH) {
46
+ const safeFacts = facts && typeof facts === 'object' ? facts : {};
35
47
  const count = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;
36
- const inner = SIDEBAR_WIDTH - 4;
48
+ const panelWidth = Number.isFinite(width) ? Math.max(20, Math.floor(width)) : SIDEBAR_WIDTH;
49
+ const inner = panelWidth - 4;
37
50
  const rows = [];
38
- const line = (value = '') => {
39
- const text = truncate(safeDisplay(value), inner, '…');
40
- rows.push(fill('surface', `${paint('rule', '│')} ${padEnd(text, inner)} `));
41
- };
42
- const styled = (value) => {
43
- rows.push(fill('surface', `${paint('rule', '│')} ${padEnd(truncate(value, inner, '…'), inner)} `));
51
+ const oneLine = (value) => safeDisplay(value).replace(/[\r\n]+/g, ' ');
52
+ const pushCell = (clean) => {
53
+ rows.push(fill('surface', `${paint('rule', '│')} ${padEnd(truncate(clean, inner, '…'), inner)} `));
44
54
  };
55
+ const line = (value = '') => pushCell(oneLine(value));
56
+ const styled = (value) => pushCell(String(value == null ? '' : value).replace(/[\r\n]+/g, ' '));
45
57
  line();
46
- styled(bold(safeDisplay(facts.title?.trim() || 'Untitled')));
47
- if (facts.id)
48
- line(facts.id);
58
+ styled(bold(oneLine(safeFacts.title).trim() || 'Untitled'));
59
+ if (safeFacts.id)
60
+ line(safeFacts.id);
49
61
  line();
50
62
  styled(bold('Context'));
51
- const limit = Number.isFinite(facts.contextLimit) ? Number(facts.contextLimit) : 0;
52
- const used = Number.isFinite(facts.contextChars) ? Number(facts.contextChars) : 0;
63
+ const limit = Number.isFinite(safeFacts.contextLimit) ? Number(safeFacts.contextLimit) : 0;
64
+ const used = Number.isFinite(safeFacts.contextChars) ? Number(safeFacts.contextChars) : 0;
53
65
  if (limit > 0 && used > 0) {
54
66
  const rawPercent = (used / limit) * 100;
55
67
  const percent = Math.max(1, Math.min(100, Math.round(rawPercent)));
@@ -60,74 +72,92 @@ export function sessionSidebarRows(facts, height) {
60
72
  }
61
73
  line();
62
74
  styled(bold('Model'));
63
- if (height >= 24 && facts.provider && facts.model) {
64
- line(facts.provider);
65
- line(facts.model);
75
+ if (count >= 24 && safeFacts.provider && safeFacts.model) {
76
+ line(safeFacts.provider);
77
+ line(safeFacts.model);
66
78
  }
67
79
  else {
68
- line([facts.provider, facts.model].filter(Boolean).join(' / ') || 'Not configured');
80
+ line([safeFacts.provider, safeFacts.model].filter(Boolean).join(' / ') || 'Not configured');
69
81
  }
70
82
  line();
71
83
  styled(bold('Workspace'));
72
- line(facts.cwd || 'Unknown');
73
- if (facts.activeSkill) {
74
- const raw = facts.activeSkill;
84
+ line(safeFacts.cwd || 'Unknown');
85
+ if (safeFacts.activeSkill) {
86
+ const raw = safeFacts.activeSkill;
75
87
  const skillId = typeof raw === 'string' ? raw : (raw.id || raw.name || '');
76
88
  const skillDesc = typeof raw === 'object' && raw ? raw.description || '' : '';
77
89
  if (skillId) {
78
90
  line();
79
91
  styled(bold('Active Skill'));
80
- styled(paint('accent', `✦ ${truncate(safeDisplay(skillId), inner - 4, '…')}`));
92
+ styled(paint('accent', `✦ ${truncate(oneLine(skillId), inner - 4, '…')}`));
81
93
  if (skillDesc) {
82
- line(truncate(skillDesc, inner, '…'));
94
+ line(skillDesc);
83
95
  }
84
96
  }
85
97
  }
86
- if (facts.plan?.length) {
87
- const completed = facts.plan.filter(item => item.status === 'completed').length;
98
+ const validPlan = Array.isArray(safeFacts.plan)
99
+ ? safeFacts.plan.filter((item) => Boolean(item && typeof item === 'object'))
100
+ : [];
101
+ const footerReserved = count >= 8 ? 1 : 0;
102
+ const bodyLimit = count - footerReserved;
103
+ if (validPlan.length) {
104
+ const completed = validPlan.filter(item => item.status === 'completed').length;
88
105
  // Budget from the actual metadata, including optional skill/model rows.
89
106
  // Preserve space for the focused step and overflow summaries on short panes.
90
- const planBudget = Math.min(6, Math.max(0, count - 3));
91
- while (rows.length > count - planBudget) {
107
+ const planBudget = Math.min(6, Math.max(0, bodyLimit - 3));
108
+ while (rows.length > bodyLimit - planBudget) {
92
109
  const blank = rows.findIndex(row => stripAnsi(row).replace('│', '').trim() === '');
93
110
  if (blank < 0)
94
111
  break;
95
112
  rows.splice(blank, 1);
96
113
  }
97
- if (rows.length > count - planBudget)
98
- rows.length = Math.max(0, count - planBudget);
99
- styled(bold(`Plan ${completed}/${facts.plan.length}`));
114
+ if (rows.length > bodyLimit - planBudget)
115
+ rows.length = Math.max(0, bodyLimit - planBudget);
116
+ styled(bold(`Plan ${completed}/${validPlan.length}`));
100
117
  // Keep plan steps in execution order and keep the active step in view.
101
- const maxSteps = Math.max(1, Math.min(10, count - rows.length - 3));
102
- const activeIndex = facts.plan.findIndex(item => item.status === 'in_progress');
103
- const pendingIndex = facts.plan.findIndex(item => item.status !== 'completed');
104
- const focus = activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : facts.plan.length - 1;
105
- const start = Math.max(0, Math.min(focus - Math.min(2, maxSteps - 1), facts.plan.length - maxSteps));
106
- const planItems = facts.plan.slice(start, start + maxSteps);
107
- if (start > 0)
118
+ const maxSteps = Math.max(1, Math.min(10, bodyLimit - rows.length - 2));
119
+ const activeIndex = validPlan.findIndex(item => item.status === 'in_progress');
120
+ const pendingIndex = validPlan.findIndex(item => item.status !== 'completed');
121
+ const focus = activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : validPlan.length - 1;
122
+ const start = Math.max(0, Math.min(focus - Math.min(2, maxSteps - 1), validPlan.length - maxSteps));
123
+ const planItems = validPlan.slice(start, start + maxSteps);
124
+ if (start > 0 && bodyLimit - rows.length > planItems.length)
108
125
  line(`${start} earlier plan steps`);
109
126
  for (const item of planItems) {
110
127
  const mark = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▸' : '·';
111
128
  line(`${mark} ${item.text || item.step || item.content || ''}`);
112
129
  }
113
- const remaining = facts.plan.length - start - planItems.length;
114
- if (remaining > 0)
130
+ const remaining = validPlan.length - start - planItems.length;
131
+ if (remaining > 0 && rows.length < bodyLimit)
115
132
  line(`${remaining} later plan steps`);
116
133
  }
117
- const visible = rows.slice(0, count);
134
+ const visible = rows.slice(0, bodyLimit);
118
135
  while (visible.length < count - 1)
119
- lineFor(visible);
120
- if (visible.length < count)
121
- visible.push(fill('surface', `${paint('rule', '│')} ${padEnd(dim('Causyne Agent'), inner)} `));
136
+ lineFor(visible, panelWidth);
137
+ if (visible.length < count) {
138
+ visible.push(fill('surface', `${paint('rule', '│')} ${padEnd(dim(truncate('Causyne Agent', inner, '…')), inner)} `));
139
+ }
122
140
  return visible;
123
141
  }
124
- function lineFor(rows) {
125
- rows.push(fill('surface', `${paint('rule', '│')}${' '.repeat(SIDEBAR_WIDTH - 1)}`));
142
+ function lineFor(rows, panelWidth = SIDEBAR_WIDTH) {
143
+ rows.push(fill('surface', `${paint('rule', '│')}${' '.repeat(Math.max(0, panelWidth - 1))}`));
126
144
  }
127
145
  /** Compose the panel beside the viewport and input without exceeding terminal width. */
128
- export function joinSessionSidebar(mainRows, sideRows, mainWidth) {
146
+ export function joinSessionSidebar(mainRows, sideRows, mainWidth, sideWidth = SIDEBAR_WIDTH) {
147
+ if (!Array.isArray(mainRows))
148
+ return [];
149
+ const safeSide = Array.isArray(sideRows) ? sideRows : [];
150
+ const safeWidth = Number.isFinite(mainWidth) ? Math.max(1, Math.floor(mainWidth)) : 80;
151
+ const targetSide = Number.isFinite(sideWidth) ? Math.max(1, Math.floor(sideWidth)) : SIDEBAR_WIDTH;
129
152
  return mainRows.map((row, index) => {
130
- const main = padEnd(truncate(row, Math.max(1, mainWidth), ''), mainWidth);
131
- return main + (sideRows[index] || ' '.repeat(SIDEBAR_WIDTH));
153
+ const cleanMain = String(row == null ? '' : row).replace(/[\r\n]+/g, ' ');
154
+ const main = padEnd(truncate(cleanMain, safeWidth, ''), safeWidth);
155
+ const rawSide = safeSide[index]
156
+ ? String(safeSide[index]).replace(/[\r\n]+/g, ' ')
157
+ : ' '.repeat(targetSide);
158
+ const side = padEnd(truncate(rawSide, targetSide, ''), targetSide);
159
+ // Reset any open SGR sequence from chat prose before entering the sidebar pane.
160
+ const boundaryReset = main.includes('\x1b[') ? '\x1b[0m' : '';
161
+ return main + boundaryReset + side;
132
162
  });
133
163
  }
@@ -4,9 +4,11 @@ import { padEnd, safeDisplay, stripAnsi, truncate } from './text.js';
4
4
  import { bold, dim, fill, paint } from './theme.js';
5
5
 
6
6
  export const SIDEBAR_WIDTH = 42;
7
- // A 42-column sidebar is only useful if the conversation retains a readable width.
8
- // Narrow IDE terminals should prioritize the user's complete message over metadata.
9
- export const SIDEBAR_THRESHOLD = 160;
7
+ export const COMPACT_SIDEBAR_WIDTH = 28;
8
+ // Show a compact responsive sidebar once past 100 columns so ordinary terminals
9
+ // and cmd windows do not have to be dragged excessively wide, while keeping <=100
10
+ // column IDE splits full-width for conversation readability.
11
+ export const SIDEBAR_THRESHOLD = 100;
10
12
 
11
13
  export interface SidebarFacts {
12
14
  title?: string;
@@ -29,43 +31,54 @@ export function sidebarVisible(columns: number, home = false, env: { CAUSYNE_SID
29
31
  return !home && Number.isFinite(columns) && columns > SIDEBAR_THRESHOLD;
30
32
  }
31
33
 
34
+ /** Select a compact sidebar width on medium terminals and full width on wide screens. */
35
+ export function sessionSidebarWidth(
36
+ columns: number,
37
+ home = false,
38
+ env: { CAUSYNE_SIDEBAR?: string } = typeof process !== 'undefined' ? process.env : {}
39
+ ): number {
40
+ if (!sidebarVisible(columns, home, env)) return 0;
41
+ const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
42
+ if (width < 120) return COMPACT_SIDEBAR_WIDTH;
43
+ if (width < 150) return 30;
44
+ if (width < 180) return 34;
45
+ return SIDEBAR_WIDTH;
46
+ }
47
+
32
48
  /** Reserve the last terminal column so a wide row cannot wrap the stage. */
33
49
  export function sessionMainWidth(columns: number, home = false, env: { CAUSYNE_SIDEBAR?: string } = typeof process !== 'undefined' ? process.env : {}): number {
34
50
  const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
35
- return sidebarVisible(width, home, env) ? width - SIDEBAR_WIDTH - 1 : width;
51
+ const panelWidth = sessionSidebarWidth(width, home, env);
52
+ return panelWidth > 0 ? width - panelWidth - 1 : width;
36
53
  }
37
54
 
38
55
  /** The session input uses the available conversation column, with a small inset. */
39
56
  export function sessionComposerWidth(columns: number): number {
40
57
  const available = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
41
- if (available <= 112) {
42
- return Math.max(20, available - 4);
43
- }
44
- // Dynamic readable measure scaling on wide terminals:
45
- const readableMeasure = Math.round(109 + 20 * Math.log2(available / 112));
46
- return Math.min(available - 4, Math.max(20, readableMeasure));
58
+ return Math.max(20, available - 4);
47
59
  }
48
60
 
49
61
  /** Render only facts the runtime can actually report. */
50
- export function sessionSidebarRows(facts: SidebarFacts, height: number): string[] {
62
+ export function sessionSidebarRows(facts: SidebarFacts, height: number, width: number = SIDEBAR_WIDTH): string[] {
63
+ const safeFacts: SidebarFacts = facts && typeof facts === 'object' ? facts : {};
51
64
  const count = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;
52
- const inner = SIDEBAR_WIDTH - 4;
65
+ const panelWidth = Number.isFinite(width) ? Math.max(20, Math.floor(width)) : SIDEBAR_WIDTH;
66
+ const inner = panelWidth - 4;
53
67
  const rows: string[] = [];
54
- const line = (value = ''): void => {
55
- const text = truncate(safeDisplay(value), inner, '…');
56
- rows.push(fill('surface', `${paint('rule', '│')} ${padEnd(text, inner)} `));
57
- };
58
- const styled = (value: string): void => {
59
- rows.push(fill('surface', `${paint('rule', '│')} ${padEnd(truncate(value, inner, '…'), inner)} `));
68
+ const oneLine = (value: unknown): string => safeDisplay(value).replace(/[\r\n]+/g, ' ');
69
+ const pushCell = (clean: string): void => {
70
+ rows.push(fill('surface', `${paint('rule', '│')} ${padEnd(truncate(clean, inner, '…'), inner)} `));
60
71
  };
72
+ const line = (value = ''): void => pushCell(oneLine(value));
73
+ const styled = (value: string): void => pushCell(String(value == null ? '' : value).replace(/[\r\n]+/g, ' '));
61
74
 
62
75
  line();
63
- styled(bold(safeDisplay(facts.title?.trim() || 'Untitled')));
64
- if (facts.id) line(facts.id);
76
+ styled(bold(oneLine(safeFacts.title).trim() || 'Untitled'));
77
+ if (safeFacts.id) line(safeFacts.id);
65
78
  line();
66
79
  styled(bold('Context'));
67
- const limit = Number.isFinite(facts.contextLimit) ? Number(facts.contextLimit) : 0;
68
- const used = Number.isFinite(facts.contextChars) ? Number(facts.contextChars) : 0;
80
+ const limit = Number.isFinite(safeFacts.contextLimit) ? Number(safeFacts.contextLimit) : 0;
81
+ const used = Number.isFinite(safeFacts.contextChars) ? Number(safeFacts.contextChars) : 0;
69
82
  if (limit > 0 && used > 0) {
70
83
  const rawPercent = (used / limit) * 100;
71
84
  const percent = Math.max(1, Math.min(100, Math.round(rawPercent)));
@@ -75,72 +88,95 @@ export function sessionSidebarRows(facts: SidebarFacts, height: number): string[
75
88
  }
76
89
  line();
77
90
  styled(bold('Model'));
78
- if (height >= 24 && facts.provider && facts.model) {
79
- line(facts.provider);
80
- line(facts.model);
91
+ if (count >= 24 && safeFacts.provider && safeFacts.model) {
92
+ line(safeFacts.provider);
93
+ line(safeFacts.model);
81
94
  } else {
82
- line([facts.provider, facts.model].filter(Boolean).join(' / ') || 'Not configured');
95
+ line([safeFacts.provider, safeFacts.model].filter(Boolean).join(' / ') || 'Not configured');
83
96
  }
84
97
  line();
85
98
  styled(bold('Workspace'));
86
- line(facts.cwd || 'Unknown');
99
+ line(safeFacts.cwd || 'Unknown');
87
100
 
88
- if (facts.activeSkill) {
89
- const raw = facts.activeSkill;
101
+ if (safeFacts.activeSkill) {
102
+ const raw = safeFacts.activeSkill;
90
103
  const skillId = typeof raw === 'string' ? raw : (raw.id || raw.name || '');
91
104
  const skillDesc = typeof raw === 'object' && raw ? raw.description || '' : '';
92
105
  if (skillId) {
93
106
  line();
94
107
  styled(bold('Active Skill'));
95
- styled(paint('accent', `✦ ${truncate(safeDisplay(skillId), inner - 4, '…')}`));
108
+ styled(paint('accent', `✦ ${truncate(oneLine(skillId), inner - 4, '…')}`));
96
109
  if (skillDesc) {
97
- line(truncate(skillDesc, inner, '…'));
110
+ line(skillDesc);
98
111
  }
99
112
  }
100
113
  }
101
114
 
102
- if (facts.plan?.length) {
103
- const completed = facts.plan.filter(item => item.status === 'completed').length;
115
+ const validPlan = Array.isArray(safeFacts.plan)
116
+ ? safeFacts.plan.filter((item): item is NonNullable<SidebarFacts['plan']>[number] => Boolean(item && typeof item === 'object'))
117
+ : [];
118
+ const footerReserved = count >= 8 ? 1 : 0;
119
+ const bodyLimit = count - footerReserved;
120
+ if (validPlan.length) {
121
+ const completed = validPlan.filter(item => item.status === 'completed').length;
104
122
  // Budget from the actual metadata, including optional skill/model rows.
105
123
  // Preserve space for the focused step and overflow summaries on short panes.
106
- const planBudget = Math.min(6, Math.max(0, count - 3));
107
- while (rows.length > count - planBudget) {
124
+ const planBudget = Math.min(6, Math.max(0, bodyLimit - 3));
125
+ while (rows.length > bodyLimit - planBudget) {
108
126
  const blank = rows.findIndex(row => stripAnsi(row).replace('│', '').trim() === '');
109
127
  if (blank < 0) break;
110
128
  rows.splice(blank, 1);
111
129
  }
112
- if (rows.length > count - planBudget) rows.length = Math.max(0, count - planBudget);
113
- styled(bold(`Plan ${completed}/${facts.plan.length}`));
130
+ if (rows.length > bodyLimit - planBudget) rows.length = Math.max(0, bodyLimit - planBudget);
131
+ styled(bold(`Plan ${completed}/${validPlan.length}`));
114
132
  // Keep plan steps in execution order and keep the active step in view.
115
- const maxSteps = Math.max(1, Math.min(10, count - rows.length - 3));
116
- const activeIndex = facts.plan.findIndex(item => item.status === 'in_progress');
117
- const pendingIndex = facts.plan.findIndex(item => item.status !== 'completed');
118
- const focus = activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : facts.plan.length - 1;
119
- const start = Math.max(0, Math.min(focus - Math.min(2, maxSteps - 1), facts.plan.length - maxSteps));
120
- const planItems = facts.plan.slice(start, start + maxSteps);
121
- if (start > 0) line(`${start} earlier plan steps`);
133
+ const maxSteps = Math.max(1, Math.min(10, bodyLimit - rows.length - 2));
134
+ const activeIndex = validPlan.findIndex(item => item.status === 'in_progress');
135
+ const pendingIndex = validPlan.findIndex(item => item.status !== 'completed');
136
+ const focus = activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : validPlan.length - 1;
137
+ const start = Math.max(0, Math.min(focus - Math.min(2, maxSteps - 1), validPlan.length - maxSteps));
138
+ const planItems = validPlan.slice(start, start + maxSteps);
139
+ if (start > 0 && bodyLimit - rows.length > planItems.length) line(`${start} earlier plan steps`);
122
140
  for (const item of planItems) {
123
141
  const mark = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▸' : '·';
124
142
  line(`${mark} ${item.text || item.step || item.content || ''}`);
125
143
  }
126
- const remaining = facts.plan.length - start - planItems.length;
127
- if (remaining > 0) line(`${remaining} later plan steps`);
144
+ const remaining = validPlan.length - start - planItems.length;
145
+ if (remaining > 0 && rows.length < bodyLimit) line(`${remaining} later plan steps`);
128
146
  }
129
147
 
130
- const visible = rows.slice(0, count);
131
- while (visible.length < count - 1) lineFor(visible);
132
- if (visible.length < count) visible.push(fill('surface', `${paint('rule', '│')} ${padEnd(dim('Causyne Agent'), inner)} `));
148
+ const visible = rows.slice(0, bodyLimit);
149
+ while (visible.length < count - 1) lineFor(visible, panelWidth);
150
+ if (visible.length < count) {
151
+ visible.push(fill('surface', `${paint('rule', '│')} ${padEnd(dim(truncate('Causyne Agent', inner, '…')), inner)} `));
152
+ }
133
153
  return visible;
134
154
  }
135
155
 
136
- function lineFor(rows: string[]): void {
137
- rows.push(fill('surface', `${paint('rule', '│')}${' '.repeat(SIDEBAR_WIDTH - 1)}`));
156
+ function lineFor(rows: string[], panelWidth: number = SIDEBAR_WIDTH): void {
157
+ rows.push(fill('surface', `${paint('rule', '│')}${' '.repeat(Math.max(0, panelWidth - 1))}`));
138
158
  }
139
159
 
140
160
  /** Compose the panel beside the viewport and input without exceeding terminal width. */
141
- export function joinSessionSidebar(mainRows: string[], sideRows: string[], mainWidth: number): string[] {
161
+ export function joinSessionSidebar(
162
+ mainRows: string[],
163
+ sideRows: string[],
164
+ mainWidth: number,
165
+ sideWidth: number = SIDEBAR_WIDTH
166
+ ): string[] {
167
+ if (!Array.isArray(mainRows)) return [];
168
+ const safeSide = Array.isArray(sideRows) ? sideRows : [];
169
+ const safeWidth = Number.isFinite(mainWidth) ? Math.max(1, Math.floor(mainWidth)) : 80;
170
+ const targetSide = Number.isFinite(sideWidth) ? Math.max(1, Math.floor(sideWidth)) : SIDEBAR_WIDTH;
142
171
  return mainRows.map((row, index) => {
143
- const main = padEnd(truncate(row, Math.max(1, mainWidth), ''), mainWidth);
144
- return main + (sideRows[index] || ' '.repeat(SIDEBAR_WIDTH));
172
+ const cleanMain = String(row == null ? '' : row).replace(/[\r\n]+/g, ' ');
173
+ const main = padEnd(truncate(cleanMain, safeWidth, ''), safeWidth);
174
+ const rawSide = safeSide[index]
175
+ ? String(safeSide[index]).replace(/[\r\n]+/g, ' ')
176
+ : ' '.repeat(targetSide);
177
+ const side = padEnd(truncate(rawSide, targetSide, ''), targetSide);
178
+ // Reset any open SGR sequence from chat prose before entering the sidebar pane.
179
+ const boundaryReset = main.includes('\x1b[') ? '\x1b[0m' : '';
180
+ return main + boundaryReset + side;
145
181
  });
146
182
  }
package/src/tui/setup.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /** Shared setup transaction for the home panel and standalone CLI. */
2
2
  import { resolveAvailableModels } from '../dynamicCatalogue.js';
3
+ import { safeDisplay } from './text.js';
3
4
  const string = (value) => typeof value === 'string' ? value : '';
4
5
  const customProviders = new Set(['openai-compatible', 'dashscope-byok', 'ollama']);
5
6
  /** Peers and Antigravity authenticate through their own CLI, not a stored key. */
@@ -12,6 +13,9 @@ const defaults = {
12
13
  'dashscope-byok': 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions'
13
14
  };
14
15
  export function validateEndpoint(value) {
16
+ if (typeof value !== 'string' || !value || /[\x00-\x1f\x7f-\x9f\s]/.test(value)) {
17
+ return 'Use a single-line endpoint URL without whitespace or control characters.';
18
+ }
15
19
  try {
16
20
  const url = new URL(value);
17
21
  if (url.username || url.password || url.search || url.hash)
@@ -65,7 +69,13 @@ export async function runSetup(ui, providers, store, workspace = process.cwd())
65
69
  // The peer already knows which models its account can reach. Listing them
66
70
  // is the whole point of treating it as a provider; a blank text box would
67
71
  // make the user guess ids the CLI could have told us for free.
68
- const known = (await resolveAvailableModels(provider.id, {}, false)).models;
72
+ let known = [];
73
+ try {
74
+ known = (await resolveAvailableModels(provider.id, {}, false)).models;
75
+ }
76
+ catch {
77
+ known = [];
78
+ }
69
79
  if (known.length === 0) {
70
80
  model = await text('Setup 3/5 · model', ['Enter a model ID published by the installed CLI.',
71
81
  'Leave the default to let the peer choose its own model.'], suggestedModel, false, value => value ? null : 'A model ID is required.');
@@ -112,10 +122,13 @@ export async function runSetup(ui, providers, store, workspace = process.cwd())
112
122
  draft.baseUrl = baseUrl;
113
123
  else
114
124
  delete draft.baseUrl;
125
+ const cleanWorkspace = safeDisplay(workspace).replace(/\s+/g, ' ').trim();
126
+ const cleanLabel = safeDisplay(provider.label).replace(/\s+/g, ' ').trim();
127
+ const cleanModel = safeDisplay(model).replace(/\s+/g, ' ').trim();
115
128
  const review = await ui.select({ title: 'Setup 5/5 · review', items: [
116
- { id: 'save', label: 'Save configuration', description: `${provider.label} · ${model} · Mode ${mode.id}` },
129
+ { id: 'save', label: 'Save configuration', description: `${cleanLabel} · ${cleanModel} · Mode ${mode.id}` },
117
130
  { id: 'edit', label: 'Edit choices', description: baseUrl || 'Provider default endpoint' },
118
- { id: 'cancel', label: 'Cancel without saving', description: `Workspace: ${workspace}` }
131
+ { id: 'cancel', label: 'Cancel without saving', description: `Workspace: ${cleanWorkspace}` }
119
132
  ] });
120
133
  if (!review || review.id === 'cancel')
121
134
  return null;
@@ -130,6 +143,18 @@ export async function runSetup(ui, providers, store, workspace = process.cwd())
130
143
  saved.baseUrl = baseUrl;
131
144
  else
132
145
  delete saved.baseUrl;
146
+ if (provider.id !== 'ollama' && !isLocalAgent(provider.id)) {
147
+ const existingProviderKeys = saved.providerKeys && typeof saved.providerKeys === 'object' && !Array.isArray(saved.providerKeys)
148
+ ? { ...saved.providerKeys }
149
+ : null;
150
+ if (apiKey) {
151
+ saved.providerKeys = { ...(existingProviderKeys || {}), [provider.id]: apiKey };
152
+ }
153
+ else if (existingProviderKeys && provider.id in existingProviderKeys) {
154
+ delete existingProviderKeys[provider.id];
155
+ saved.providerKeys = existingProviderKeys;
156
+ }
157
+ }
133
158
  store.saveConfig(saved);
134
159
  if (apiKey || provider.id === 'ollama' || isLocalAgent(provider.id)) {
135
160
  void resolveAvailableModels(provider.id, saved, true).catch(() => { });
package/src/tui/setup.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /** Shared setup transaction for the home panel and standalone CLI. */
2
2
  import { resolveAvailableModels } from '../dynamicCatalogue.js';
3
+ import { safeDisplay } from './text.js';
3
4
 
4
5
  export interface SetupChoice { id: string; label: string; description?: string }
5
6
  export interface SetupProvider { id: string; label: string; hint: string; model: string }
@@ -22,6 +23,9 @@ const defaults: Record<string, string> = {
22
23
  };
23
24
 
24
25
  export function validateEndpoint(value: string): string | null {
26
+ if (typeof value !== 'string' || !value || /[\x00-\x1f\x7f-\x9f\s]/.test(value)) {
27
+ return 'Use a single-line endpoint URL without whitespace or control characters.';
28
+ }
25
29
  try {
26
30
  const url = new URL(value);
27
31
  if (url.username || url.password || url.search || url.hash) return 'Use an endpoint without credentials, query parameters, or a fragment.';
@@ -70,7 +74,12 @@ export async function runSetup(ui: SetupUI, providers: SetupProvider[], store: {
70
74
  // The peer already knows which models its account can reach. Listing them
71
75
  // is the whole point of treating it as a provider; a blank text box would
72
76
  // make the user guess ids the CLI could have told us for free.
73
- const known = (await resolveAvailableModels(provider.id, {}, false)).models;
77
+ let known: string[] = [];
78
+ try {
79
+ known = (await resolveAvailableModels(provider.id, {}, false)).models;
80
+ } catch {
81
+ known = [];
82
+ }
74
83
  if (known.length === 0) {
75
84
  model = await text('Setup 3/5 · model',
76
85
  ['Enter a model ID published by the installed CLI.',
@@ -113,10 +122,13 @@ export async function runSetup(ui: SetupUI, providers: SetupProvider[], store: {
113
122
  if (!mode || !['A', 'B', 'C'].includes(mode.id)) return null;
114
123
  draft = { ...draft, provider: provider.id, model, apiKey, autonomyMode: mode.id };
115
124
  if (baseUrl) draft.baseUrl = baseUrl; else delete draft.baseUrl;
125
+ const cleanWorkspace = safeDisplay(workspace).replace(/\s+/g, ' ').trim();
126
+ const cleanLabel = safeDisplay(provider.label).replace(/\s+/g, ' ').trim();
127
+ const cleanModel = safeDisplay(model).replace(/\s+/g, ' ').trim();
116
128
  const review = await ui.select({ title: 'Setup 5/5 · review', items: [
117
- { id: 'save', label: 'Save configuration', description: `${provider.label} · ${model} · Mode ${mode.id}` },
129
+ { id: 'save', label: 'Save configuration', description: `${cleanLabel} · ${cleanModel} · Mode ${mode.id}` },
118
130
  { id: 'edit', label: 'Edit choices', description: baseUrl || 'Provider default endpoint' },
119
- { id: 'cancel', label: 'Cancel without saving', description: `Workspace: ${workspace}` }
131
+ { id: 'cancel', label: 'Cancel without saving', description: `Workspace: ${cleanWorkspace}` }
120
132
  ] });
121
133
  if (!review || review.id === 'cancel') return null;
122
134
  if (review.id === 'edit') continue;
@@ -125,6 +137,18 @@ export async function runSetup(ui: SetupUI, providers: SetupProvider[], store: {
125
137
  const next = { ...store.loadConfig(), provider: draft.provider, model, apiKey, autonomyMode: mode.id };
126
138
  const saved: Config = next;
127
139
  if (baseUrl) saved.baseUrl = baseUrl; else delete saved.baseUrl;
140
+ if (provider.id !== 'ollama' && !isLocalAgent(provider.id)) {
141
+ const existingProviderKeys =
142
+ saved.providerKeys && typeof saved.providerKeys === 'object' && !Array.isArray(saved.providerKeys)
143
+ ? { ...(saved.providerKeys as Record<string, string>) }
144
+ : null;
145
+ if (apiKey) {
146
+ saved.providerKeys = { ...(existingProviderKeys || {}), [provider.id]: apiKey };
147
+ } else if (existingProviderKeys && provider.id in existingProviderKeys) {
148
+ delete existingProviderKeys[provider.id];
149
+ saved.providerKeys = existingProviderKeys;
150
+ }
151
+ }
128
152
  store.saveConfig(saved);
129
153
  if (apiKey || provider.id === 'ollama' || isLocalAgent(provider.id)) {
130
154
  void resolveAvailableModels(provider.id, saved, true).catch(() => {});
@@ -1,7 +1,8 @@
1
1
  import { writeUserSkill, validateSegment, skillTemplate } from '../userSkills.js';
2
2
  import { invalidateUserSkills } from '../skillsManager.js';
3
+ import { safeDisplay } from './text.js';
3
4
  // @ts-expect-error theme.js has no TypeScript declaration yet.
4
- import { paint, bold, dim } from './theme.js';
5
+ import { paint } from './theme.js';
5
6
  // @ts-expect-error dialogs.js is awaiting TypeScript migration.
6
7
  import { InputLayer, SelectLayer } from './dialogs.js';
7
8
  const COMMON_DOMAINS = [
@@ -14,10 +15,15 @@ const COMMON_DOMAINS = [
14
15
  { value: 'mobile', label: 'mobile', description: 'Android, iOS, Flutter, React Native' },
15
16
  { value: '__other__', label: '+ Enter custom category...', description: 'Specify any category name' }
16
17
  ];
18
+ function trimInput(val) {
19
+ return typeof val === 'string' ? val.trim() : '';
20
+ }
17
21
  /**
18
22
  * Interactive wizard hosted on ChatPrompt to scaffold and create a new skill.
19
23
  */
20
24
  export async function runInteractiveSkillWizard(prompt) {
25
+ if (!prompt || typeof prompt.openLayer !== 'function')
26
+ return null;
21
27
  // Step 1: Select or enter domain/category
22
28
  const chosenDomain = await new Promise((resolve) => {
23
29
  let resolved = false;
@@ -55,7 +61,7 @@ export async function runInteractiveSkillWizard(prompt) {
55
61
  title: 'create skill · category name',
56
62
  lines: ['Category / domain name (e.g. data, analytics, cloud, tools):'],
57
63
  placeholder: 'category-name',
58
- onSubmit: (val) => finish(val.trim().toLowerCase()),
64
+ onSubmit: (val) => finish(trimInput(val).toLowerCase()),
59
65
  onCancel: () => finish(null)
60
66
  });
61
67
  prompt.openLayer(layer);
@@ -87,7 +93,7 @@ export async function runInteractiveSkillWizard(prompt) {
87
93
  'Skill name (lowercase letters, numbers, hyphens — e.g. play-store-release, pr-review):'
88
94
  ],
89
95
  placeholder: 'my-new-skill',
90
- onSubmit: (val) => finish(val.trim().toLowerCase()),
96
+ onSubmit: (val) => finish(trimInput(val).toLowerCase()),
91
97
  onCancel: () => finish(null)
92
98
  });
93
99
  prompt.openLayer(layer);
@@ -117,7 +123,7 @@ export async function runInteractiveSkillWizard(prompt) {
117
123
  'Short description: what this skill does and when the agent should use it:'
118
124
  ],
119
125
  placeholder: 'e.g. Prepares and validates Android app bundles for Google Play Store release.',
120
- onSubmit: (val) => finish(val.trim()),
126
+ onSubmit: (val) => finish(trimInput(val)),
121
127
  onCancel: () => finish(null)
122
128
  });
123
129
  prompt.openLayer(layer);
@@ -129,7 +135,7 @@ export async function runInteractiveSkillWizard(prompt) {
129
135
  const written = writeUserSkill({ domain, name: skillName, content, overwrite: false });
130
136
  if (!written.ok) {
131
137
  if (typeof prompt.showText === 'function') {
132
- prompt.showText('Skill Creation Failed', written.error || 'Failed to write skill file', { danger: true });
138
+ prompt.showText('Skill Creation Failed', safeDisplay(written.error || 'Failed to write skill file'), { danger: true });
133
139
  }
134
140
  return null;
135
141
  }