@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
@@ -73,7 +73,6 @@ export function normalizeClipboardText(raw: unknown): string {
73
73
  */
74
74
  export function copyToClipboard(text: string): boolean {
75
75
  if (typeof text !== 'string' || text.length === 0) return false;
76
- emitOsc52Copy(text);
77
76
  return writeClipboardSync(text);
78
77
  }
79
78
 
@@ -225,9 +224,12 @@ export function extractLastAssistantTurn(loop?: ChatboxLoop): string {
225
224
  for (let i = loop.messages.length - 1; i >= 0; i--) {
226
225
  const msg = loop.messages[i];
227
226
  if (msg && msg.role === 'assistant') {
228
- if (typeof msg.content === 'string') return msg.content;
227
+ if (typeof msg.content === 'string') {
228
+ if (msg.content.trim()) return msg.content;
229
+ continue;
230
+ }
229
231
  if (Array.isArray(msg.content)) {
230
- return msg.content
232
+ const joined = msg.content
231
233
  .map((part: unknown) => {
232
234
  if (typeof part === 'string') return part;
233
235
  if (part && typeof part === 'object' && 'text' in part && typeof (part as { text: unknown }).text === 'string') {
@@ -237,6 +239,7 @@ export function extractLastAssistantTurn(loop?: ChatboxLoop): string {
237
239
  })
238
240
  .filter(Boolean)
239
241
  .join('\n');
242
+ if (joined.trim()) return joined;
240
243
  }
241
244
  }
242
245
  }
@@ -270,7 +273,10 @@ export function runCopyCommand(
270
273
  return { ok: false, output: 'Chatbox input is currently empty.' };
271
274
  }
272
275
  const res = copyChatboxInput(ctx.prompt);
273
- return { ok: res.success, output: 'Copied chatbox input to clipboard.' };
276
+ return {
277
+ ok: res.success,
278
+ output: res.success ? 'Copied chatbox input to clipboard.' : 'Chatbox input is currently empty.'
279
+ };
274
280
  }
275
281
 
276
282
  if (argv.length > 0) {
@@ -8,15 +8,17 @@ import path from 'node:path';
8
8
  import os from 'node:os';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { causyneHome, resolveUserPath } from '../utils/paths.js';
11
+ import { stripAnsi } from './text.js';
11
12
  /**
12
13
  * Format bytes into readable string: '128 KB', '1.5 MB'.
13
14
  */
14
15
  export function formatByteSize(bytes) {
15
- if (bytes < 1024)
16
- return `${bytes} B`;
17
- if (bytes < 1024 * 1024)
18
- return `${Math.round(bytes / 1024)} KB`;
19
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
16
+ const safe = Number.isFinite(bytes) ? Math.max(0, Math.floor(bytes)) : 0;
17
+ if (safe < 1024)
18
+ return `${safe} B`;
19
+ if (safe < 1024 * 1024)
20
+ return `${Math.round(safe / 1024)} KB`;
21
+ return `${(safe / (1024 * 1024)).toFixed(1)} MB`;
20
22
  }
21
23
  /**
22
24
  * Detect image mime type from binary magic bytes.
@@ -66,8 +68,12 @@ export function persistImageBuffer(buffer, preferredName) {
66
68
  : mimeType === 'image/gif' ? 'gif'
67
69
  : 'png';
68
70
  const timestamp = Date.now();
69
- const filename = preferredName
70
- ? path.basename(preferredName)
71
+ const cleanedPreferred = preferredName
72
+ ? stripAnsi(preferredName).replace(/[\x00-\x1f\x7f-\x9f]/g, '').trim()
73
+ : '';
74
+ const basePreferred = cleanedPreferred ? path.basename(cleanedPreferred) : '';
75
+ const filename = basePreferred && basePreferred !== '.' && basePreferred !== '..'
76
+ ? basePreferred
71
77
  : `screenshot_${timestamp}.${ext}`;
72
78
  const attachmentsDir = getAttachmentsDirectory();
73
79
  const filePath = path.join(attachmentsDir, filename);
@@ -86,36 +92,39 @@ export function persistImageBuffer(buffer, preferredName) {
86
92
  * Supports both PNG and JPEG image data placed on clipboard by macOS, browsers, and terminals.
87
93
  */
88
94
  function readDarwinClipboardImageSync() {
89
- const tempFile = path.join('/tmp', `causyne_clip_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.png`);
90
- // Script uses standard AppleScript POSIX file API with safe error handling and file descriptor close guard
91
- const script = [
92
- 'try',
93
- ' set imageData to (the clipboard as "PNGf")',
94
- ` set fileRef to open for access POSIX file "${tempFile}" with write permission`,
95
- ' set eof fileRef to 0',
96
- ' write imageData to fileRef',
97
- ' close access fileRef',
98
- ' return "ok"',
99
- 'on error',
100
- ' try',
101
- ` close access (POSIX file "${tempFile}")`,
102
- ' end try',
103
- ' try',
104
- ' set imageData to (the clipboard as JPEG picture)',
105
- ` set fileRef to open for access POSIX file "${tempFile}" with write permission`,
106
- ' set eof fileRef to 0',
107
- ' write imageData to fileRef',
108
- ' close access fileRef',
109
- ' return "ok"',
110
- ' on error',
111
- ' try',
112
- ` close access (POSIX file "${tempFile}")`,
113
- ' end try',
114
- ' return ""',
115
- ' end try',
116
- 'end try'
117
- ].join('\n');
95
+ let tempDir = '';
118
96
  try {
97
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-clip-'));
98
+ const tempFile = path.join(tempDir, 'clip.png');
99
+ const quotedFile = JSON.stringify(tempFile);
100
+ // Script uses standard AppleScript POSIX file API with safe error handling and file descriptor close guard
101
+ const script = [
102
+ 'try',
103
+ ' set imageData to (the clipboard as "PNGf")',
104
+ ` set fileRef to open for access POSIX file ${quotedFile} with write permission`,
105
+ ' set eof fileRef to 0',
106
+ ' write imageData to fileRef',
107
+ ' close access fileRef',
108
+ ' return "ok"',
109
+ 'on error',
110
+ ' try',
111
+ ` close access (POSIX file ${quotedFile})`,
112
+ ' end try',
113
+ ' try',
114
+ ' set imageData to (the clipboard as JPEG picture)',
115
+ ` set fileRef to open for access POSIX file ${quotedFile} with write permission`,
116
+ ' set eof fileRef to 0',
117
+ ' write imageData to fileRef',
118
+ ' close access fileRef',
119
+ ' return "ok"',
120
+ ' on error',
121
+ ' try',
122
+ ` close access (POSIX file ${quotedFile})`,
123
+ ' end try',
124
+ ' return ""',
125
+ ' end try',
126
+ 'end try'
127
+ ].join('\n');
119
128
  const res = spawnSync('osascript', ['-e', script], {
120
129
  encoding: 'utf8',
121
130
  timeout: 3000,
@@ -130,12 +139,13 @@ function readDarwinClipboardImageSync() {
130
139
  // osascript clipboard read is best-effort
131
140
  }
132
141
  finally {
133
- try {
134
- if (fs.existsSync(tempFile))
135
- fs.unlinkSync(tempFile);
136
- }
137
- catch {
138
- // Ignore cleanup error
142
+ if (tempDir) {
143
+ try {
144
+ fs.rmSync(tempDir, { recursive: true, force: true });
145
+ }
146
+ catch {
147
+ // Ignore cleanup error
148
+ }
139
149
  }
140
150
  }
141
151
  return null;
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import os from 'node:os';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { causyneHome, resolveUserPath } from '../utils/paths.js';
12
+ import { stripAnsi } from './text.js';
12
13
 
13
14
  export interface ClipboardImageAttachment {
14
15
  type: 'image';
@@ -23,9 +24,10 @@ export interface ClipboardImageAttachment {
23
24
  * Format bytes into readable string: '128 KB', '1.5 MB'.
24
25
  */
25
26
  export function formatByteSize(bytes: number): string {
26
- if (bytes < 1024) return `${bytes} B`;
27
- if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
28
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
27
+ const safe = Number.isFinite(bytes) ? Math.max(0, Math.floor(bytes)) : 0;
28
+ if (safe < 1024) return `${safe} B`;
29
+ if (safe < 1024 * 1024) return `${Math.round(safe / 1024)} KB`;
30
+ return `${(safe / (1024 * 1024)).toFixed(1)} MB`;
29
31
  }
30
32
 
31
33
  /**
@@ -81,8 +83,12 @@ export function persistImageBuffer(
81
83
  : 'png';
82
84
 
83
85
  const timestamp = Date.now();
84
- const filename = preferredName
85
- ? path.basename(preferredName)
86
+ const cleanedPreferred = preferredName
87
+ ? stripAnsi(preferredName).replace(/[\x00-\x1f\x7f-\x9f]/g, '').trim()
88
+ : '';
89
+ const basePreferred = cleanedPreferred ? path.basename(cleanedPreferred) : '';
90
+ const filename = basePreferred && basePreferred !== '.' && basePreferred !== '..'
91
+ ? basePreferred
86
92
  : `screenshot_${timestamp}.${ext}`;
87
93
 
88
94
  const attachmentsDir = getAttachmentsDirectory();
@@ -105,37 +111,40 @@ export function persistImageBuffer(
105
111
  * Supports both PNG and JPEG image data placed on clipboard by macOS, browsers, and terminals.
106
112
  */
107
113
  function readDarwinClipboardImageSync(): Buffer | null {
108
- const tempFile = path.join('/tmp', `causyne_clip_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.png`);
109
- // Script uses standard AppleScript POSIX file API with safe error handling and file descriptor close guard
110
- const script = [
111
- 'try',
112
- ' set imageData to (the clipboard as "PNGf")',
113
- ` set fileRef to open for access POSIX file "${tempFile}" with write permission`,
114
- ' set eof fileRef to 0',
115
- ' write imageData to fileRef',
116
- ' close access fileRef',
117
- ' return "ok"',
118
- 'on error',
119
- ' try',
120
- ` close access (POSIX file "${tempFile}")`,
121
- ' end try',
122
- ' try',
123
- ' set imageData to (the clipboard as JPEG picture)',
124
- ` set fileRef to open for access POSIX file "${tempFile}" with write permission`,
125
- ' set eof fileRef to 0',
126
- ' write imageData to fileRef',
127
- ' close access fileRef',
128
- ' return "ok"',
129
- ' on error',
130
- ' try',
131
- ` close access (POSIX file "${tempFile}")`,
132
- ' end try',
133
- ' return ""',
134
- ' end try',
135
- 'end try'
136
- ].join('\n');
137
-
114
+ let tempDir = '';
138
115
  try {
116
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-clip-'));
117
+ const tempFile = path.join(tempDir, 'clip.png');
118
+ const quotedFile = JSON.stringify(tempFile);
119
+ // Script uses standard AppleScript POSIX file API with safe error handling and file descriptor close guard
120
+ const script = [
121
+ 'try',
122
+ ' set imageData to (the clipboard as "PNGf")',
123
+ ` set fileRef to open for access POSIX file ${quotedFile} with write permission`,
124
+ ' set eof fileRef to 0',
125
+ ' write imageData to fileRef',
126
+ ' close access fileRef',
127
+ ' return "ok"',
128
+ 'on error',
129
+ ' try',
130
+ ` close access (POSIX file ${quotedFile})`,
131
+ ' end try',
132
+ ' try',
133
+ ' set imageData to (the clipboard as JPEG picture)',
134
+ ` set fileRef to open for access POSIX file ${quotedFile} with write permission`,
135
+ ' set eof fileRef to 0',
136
+ ' write imageData to fileRef',
137
+ ' close access fileRef',
138
+ ' return "ok"',
139
+ ' on error',
140
+ ' try',
141
+ ` close access (POSIX file ${quotedFile})`,
142
+ ' end try',
143
+ ' return ""',
144
+ ' end try',
145
+ 'end try'
146
+ ].join('\n');
147
+
139
148
  const res = spawnSync('osascript', ['-e', script], {
140
149
  encoding: 'utf8',
141
150
  timeout: 3000,
@@ -148,10 +157,12 @@ function readDarwinClipboardImageSync(): Buffer | null {
148
157
  } catch {
149
158
  // osascript clipboard read is best-effort
150
159
  } finally {
151
- try {
152
- if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile);
153
- } catch {
154
- // Ignore cleanup error
160
+ if (tempDir) {
161
+ try {
162
+ fs.rmSync(tempDir, { recursive: true, force: true });
163
+ } catch {
164
+ // Ignore cleanup error
165
+ }
155
166
  }
156
167
  }
157
168
  return null;
@@ -2,6 +2,7 @@
2
2
  // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), Linux (wl-paste, xclip, xsel),
3
3
  // and terminal emulator OSC 52 escape sequences across SSH and local sessions.
4
4
  import { execFileSync, spawnSync } from 'node:child_process';
5
+ import { runWithStageWrite } from './consoleGuard.js';
5
6
  /**
6
7
  * Emit OSC 52 escape sequence to synchronize terminal emulator clipboard.
7
8
  * Allows copy/paste even across SSH sessions, tmux, and container boundaries.
@@ -9,9 +10,19 @@ import { execFileSync, spawnSync } from 'node:child_process';
9
10
  export function emitOsc52Copy(text, stream = process.stdout) {
10
11
  if (typeof text !== 'string' || text.length === 0 || Buffer.byteLength(text) > 100_000)
11
12
  return false;
13
+ if (!stream || typeof stream.write !== 'function')
14
+ return false;
15
+ if (stream === process.stdout && !process.stdout?.isTTY)
16
+ return false;
12
17
  try {
13
18
  const base64 = Buffer.from(text, 'utf8').toString('base64');
14
- stream.write(`\x1b]52;c;${base64}\x07`);
19
+ const payload = `\x1b]52;c;${base64}\x07`;
20
+ if (stream === process.stdout) {
21
+ runWithStageWrite(() => stream.write(payload));
22
+ }
23
+ else {
24
+ stream.write(payload);
25
+ }
15
26
  return true;
16
27
  }
17
28
  catch {
@@ -3,6 +3,7 @@
3
3
  // and terminal emulator OSC 52 escape sequences across SSH and local sessions.
4
4
 
5
5
  import { execFileSync, spawnSync } from 'node:child_process';
6
+ import { runWithStageWrite } from './consoleGuard.js';
6
7
 
7
8
  /**
8
9
  * Emit OSC 52 escape sequence to synchronize terminal emulator clipboard.
@@ -10,9 +11,16 @@ import { execFileSync, spawnSync } from 'node:child_process';
10
11
  */
11
12
  export function emitOsc52Copy(text: string, stream: NodeJS.WritableStream = process.stdout): boolean {
12
13
  if (typeof text !== 'string' || text.length === 0 || Buffer.byteLength(text) > 100_000) return false;
14
+ if (!stream || typeof stream.write !== 'function') return false;
15
+ if (stream === process.stdout && !process.stdout?.isTTY) return false;
13
16
  try {
14
17
  const base64 = Buffer.from(text, 'utf8').toString('base64');
15
- stream.write(`\x1b]52;c;${base64}\x07`);
18
+ const payload = `\x1b]52;c;${base64}\x07`;
19
+ if (stream === process.stdout) {
20
+ runWithStageWrite(() => stream.write(payload));
21
+ } else {
22
+ stream.write(payload);
23
+ }
16
24
  return true;
17
25
  } catch {
18
26
  return false;
@@ -10,14 +10,15 @@ export const CODE_PANEL_LINES = 10;
10
10
  const MAX_STREAM_PREVIEW_CHARS = 256_000;
11
11
  const FILE_TOOLS = {
12
12
  fs_write: 'Creating', fs_edit: 'Editing', MultiEdit: 'Editing',
13
+ write: 'Creating', edit: 'Editing', multiedit: 'Editing', multi_edit: 'Editing',
13
14
  'fs.write': 'Creating', 'fs.edit': 'Editing',
14
15
  fs_delete: 'Removing', fs_move: 'Moving',
15
- write_file: 'Creating', edit_file: 'Editing', delete_file: 'Removing',
16
+ write_file: 'Creating', write_to_file: 'Creating', edit_file: 'Editing', delete_file: 'Removing',
16
17
  create_file: 'Creating', new_file: 'Creating',
17
18
  remove_file: 'Removing', unlink: 'Removing', move_file: 'Moving',
18
19
  replace_file_content: 'Editing', multi_replace_file_content: 'Editing',
19
20
  apply_patch: 'Editing', patch: 'Editing', str_replace_editor: 'Editing',
20
- WriteFile: 'Creating', EditFile: 'Editing', DeleteFile: 'Removing',
21
+ WriteFile: 'Creating', WriteToFile: 'Creating', EditFile: 'Editing', DeleteFile: 'Removing',
21
22
  CreateFile: 'Creating', RemoveFile: 'Removing', MoveFile: 'Moving',
22
23
  ReplaceFileContent: 'Editing', MultiReplaceFileContent: 'Editing'
23
24
  };
@@ -68,17 +69,18 @@ function previousCodeFromArgs(args) {
68
69
  return previous.length && previous.every(value => value !== undefined) ? previous.join('\n') : undefined;
69
70
  }
70
71
  export function codeProgressFromAction(tool, args, id, phase = 'working', source = 'tool') {
71
- const operation = FILE_TOOLS[tool];
72
- if (!operation)
72
+ if (typeof tool !== 'string' || !Object.hasOwn(FILE_TOOLS, tool))
73
73
  return null;
74
- const path = stringField(args.path ?? args.Path ?? args.file_path ?? args.FilePath ?? args.AbsolutePath ?? args.TargetFile ?? args.source);
75
- const destination = stringField(args.destination);
74
+ const operation = FILE_TOOLS[tool];
75
+ const safeArgs = args && typeof args === 'object' ? args : {};
76
+ const path = stringField(safeArgs.path ?? safeArgs.Path ?? safeArgs.file_path ?? safeArgs.FilePath ?? safeArgs.AbsolutePath ?? safeArgs.TargetFile ?? safeArgs.source);
77
+ const destination = stringField(safeArgs.destination);
76
78
  const label = path ? path.split(/[/\\]/).pop() || path : 'file';
77
79
  const description = operation === 'Moving' && destination
78
80
  ? `Moving ${label} to ${destination}`
79
81
  : `${operation} ${label}`;
80
- const before = previousCodeFromArgs(args);
81
- const code = codeFromArgs(args);
82
+ const before = previousCodeFromArgs(safeArgs);
83
+ const code = codeFromArgs(safeArgs);
82
84
  return {
83
85
  type: 'code_progress', id, phase, operation,
84
86
  ...(path ? { path } : {}), description,
@@ -88,23 +90,25 @@ export function codeProgressFromAction(tool, args, id, phase = 'working', source
88
90
  export class StreamingCodePreview {
89
91
  buffer = '';
90
92
  lastCode = '';
91
- lastSentAt = 0;
93
+ lastSentAt = null;
92
94
  truncated = false;
93
95
  accept(chunk, now = Date.now()) {
94
- if (!chunk)
96
+ if (!chunk || typeof chunk !== 'string')
95
97
  return null;
96
98
  this.buffer += chunk;
97
99
  if (this.buffer.length > MAX_STREAM_PREVIEW_CHARS) {
98
100
  this.buffer = this.buffer.slice(-MAX_STREAM_PREVIEW_CHARS);
99
101
  this.truncated = true;
100
102
  }
101
- if (now - this.lastSentAt < 100 && !chunk.includes('\n'))
103
+ const safeNow = Number.isFinite(now) ? now : Date.now();
104
+ if (this.lastSentAt !== null && safeNow >= this.lastSentAt && safeNow - this.lastSentAt < 100 && !chunk.includes('\n')) {
102
105
  return null;
106
+ }
103
107
  const code = this.draftCode();
104
108
  if (!code.trim() || code === this.lastCode)
105
109
  return null;
106
110
  this.lastCode = code;
107
- this.lastSentAt = now;
111
+ this.lastSentAt = safeNow;
108
112
  return { type: 'code_progress', id: 'model-draft', phase: 'draft',
109
113
  operation: 'Drafting', description: 'Writing code from the model stream', code,
110
114
  ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
@@ -168,13 +172,17 @@ export class NativeCodeObserver {
168
172
  this.emit = emit;
169
173
  }
170
174
  handle(event) {
171
- if (!event.path || !['Creating', 'Editing'].includes(event.operation))
175
+ if (!event || typeof event !== 'object' || !event.path || !['Creating', 'Editing'].includes(event.operation))
172
176
  return;
173
177
  if (event.code !== undefined || event.phase === 'failed') {
174
178
  this.stop(event.id);
175
179
  return;
176
180
  }
177
- const target = path.resolve(this.workspaceRoot, event.path);
181
+ const target = this.resolveTarget(event.path);
182
+ if (!target) {
183
+ this.stop(event.id);
184
+ return;
185
+ }
178
186
  if (event.phase === 'working') {
179
187
  this.stop(event.id);
180
188
  const previous = this.read(target);
@@ -214,7 +222,7 @@ export class NativeCodeObserver {
214
222
  });
215
223
  }
216
224
  dispose() {
217
- for (const id of this.active.keys())
225
+ for (const id of [...this.active.keys()])
218
226
  this.stop(id);
219
227
  }
220
228
  stop(id) {
@@ -223,15 +231,28 @@ export class NativeCodeObserver {
223
231
  clearInterval(entry.timer);
224
232
  this.active.delete(id);
225
233
  }
234
+ resolveTarget(rawPath) {
235
+ const root = path.resolve(this.workspaceRoot);
236
+ const target = path.resolve(root, rawPath);
237
+ const rel = path.relative(root, target);
238
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
239
+ return null;
240
+ return target;
241
+ }
226
242
  read(file) {
227
243
  try {
228
244
  const name = path.basename(file).toLowerCase();
229
245
  if (/^(\.env(?:\.|$)|.*\.(?:pem|key|p12|pfx)$)/u.test(name))
230
246
  return null;
231
- const stat = fs.lstatSync(file);
247
+ const realRoot = fs.realpathSync(this.workspaceRoot);
248
+ const realFile = fs.realpathSync(file);
249
+ const rel = path.relative(realRoot, realFile);
250
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
251
+ return null;
252
+ const stat = fs.lstatSync(realFile);
232
253
  if (!stat.isFile() || stat.size > 256_000)
233
254
  return null;
234
- const bytes = fs.readFileSync(file);
255
+ const bytes = fs.readFileSync(realFile);
235
256
  if (bytes.includes(0))
236
257
  return null;
237
258
  return bytes.toString('utf8');
@@ -250,7 +271,7 @@ function splitCodeLines(code) {
250
271
  return lines;
251
272
  }
252
273
  function previewLines(event) {
253
- if (event.code === undefined)
274
+ if (!event || typeof event !== 'object' || event.code === undefined)
254
275
  return [];
255
276
  // When creating or drafting code, every line is new code (addition).
256
277
  // Even if a previous file existed on disk, the action is Creating/Drafting.
@@ -317,6 +338,8 @@ export function codePreviewLineCount(event) {
317
338
  return previewLines(event).length;
318
339
  }
319
340
  export function defaultPreviewStart(event) {
341
+ if (!event || typeof event !== 'object')
342
+ return 0;
320
343
  const codeLines = previewLines(event);
321
344
  const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
322
345
  if (event.operation === 'Editing') {
@@ -342,19 +365,28 @@ function highlightCode(kind, text, width) {
342
365
  : (IS_LIGHT ? '48;5;224' : '48;5;52');
343
366
  return paint(role, marker) + `\x1b[${background}m ${body}\x1b[49m`;
344
367
  }
368
+ function oneLineCodeText(value) {
369
+ return safeDisplay(value).replace(/\s+/g, ' ').trim();
370
+ }
345
371
  /** Render a bounded, resize-safe panel. The terminal theme supplies rounded corners. */
346
372
  export function renderCodeProgress(event, width, modelNote = '', startLine) {
347
- const safeWidth = Math.max(12, Math.floor(width) || 80);
373
+ const safeEvent = event && typeof event === 'object'
374
+ ? event
375
+ : { type: 'code_progress', id: 'unknown', phase: 'working', operation: 'code', description: '', source: 'tool' };
376
+ const safeWidth = Number.isFinite(width) ? Math.max(12, Math.floor(width)) : 80;
348
377
  const inner = safeWidth - 4;
349
- const title = `${event.phase === 'done' ? '✓ ' : event.phase === 'failed' ? '× ' : ''}code · ${event.operation.toLowerCase()}`;
350
- const rows = [truncate(safeDisplay(event.description), inner)];
351
- if (event.path)
352
- rows.push(truncate(safeDisplay(event.path), inner));
378
+ const operation = oneLineCodeText(safeEvent.operation).toLowerCase() || 'code';
379
+ const title = `${safeEvent.phase === 'done' ? '✓ ' : safeEvent.phase === 'failed' ? '× ' : ''}code · ${operation}`;
380
+ const rows = [truncate(oneLineCodeText(safeEvent.description), inner)];
381
+ if (safeEvent.path)
382
+ rows.push(truncate(oneLineCodeText(safeEvent.path), inner));
353
383
  if (modelNote)
354
- rows.push(truncate(`model note: ${safeDisplay(modelNote)}`, inner));
355
- const codeLines = previewLines(event);
384
+ rows.push(truncate(`model note: ${oneLineCodeText(modelNote)}`, inner));
385
+ const codeLines = previewLines(safeEvent);
356
386
  const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
357
- const start = startLine === undefined ? defaultPreviewStart(event) : Math.max(0, Math.min(Math.floor(startLine), maxStart));
387
+ const start = startLine === undefined || !Number.isFinite(startLine)
388
+ ? defaultPreviewStart(safeEvent)
389
+ : Math.max(0, Math.min(Math.floor(startLine), maxStart));
358
390
  const visible = codeLines.slice(start, start + CODE_PANEL_LINES);
359
391
  if (visible.length) {
360
392
  rows.push('');
@@ -363,8 +395,8 @@ export function renderCodeProgress(event, width, modelNote = '', startLine) {
363
395
  if (codeLines.length > CODE_PANEL_LINES) {
364
396
  rows.push(truncate(`lines ${start + 1}-${start + visible.length} of ${codeLines.length} · scroll over code`, inner));
365
397
  }
366
- if (event.codeTruncated)
398
+ if (safeEvent.codeTruncated)
367
399
  rows.push(truncate('Earlier draft content exceeded the preview limit', inner));
368
400
  }
369
- return panel(rows, { width: safeWidth, title, role: event.phase === 'failed' ? 'danger' : 'rule' });
401
+ return panel(rows, { width: safeWidth, title, role: safeEvent.phase === 'failed' ? 'danger' : 'rule' });
370
402
  }