@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
@@ -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;
@@ -68,17 +68,18 @@ function previousCodeFromArgs(args) {
68
68
  return previous.length && previous.every(value => value !== undefined) ? previous.join('\n') : undefined;
69
69
  }
70
70
  export function codeProgressFromAction(tool, args, id, phase = 'working', source = 'tool') {
71
- const operation = FILE_TOOLS[tool];
72
- if (!operation)
71
+ if (typeof tool !== 'string' || !Object.hasOwn(FILE_TOOLS, tool))
73
72
  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);
73
+ const operation = FILE_TOOLS[tool];
74
+ const safeArgs = args && typeof args === 'object' ? args : {};
75
+ const path = stringField(safeArgs.path ?? safeArgs.Path ?? safeArgs.file_path ?? safeArgs.FilePath ?? safeArgs.AbsolutePath ?? safeArgs.TargetFile ?? safeArgs.source);
76
+ const destination = stringField(safeArgs.destination);
76
77
  const label = path ? path.split(/[/\\]/).pop() || path : 'file';
77
78
  const description = operation === 'Moving' && destination
78
79
  ? `Moving ${label} to ${destination}`
79
80
  : `${operation} ${label}`;
80
- const before = previousCodeFromArgs(args);
81
- const code = codeFromArgs(args);
81
+ const before = previousCodeFromArgs(safeArgs);
82
+ const code = codeFromArgs(safeArgs);
82
83
  return {
83
84
  type: 'code_progress', id, phase, operation,
84
85
  ...(path ? { path } : {}), description,
@@ -88,23 +89,25 @@ export function codeProgressFromAction(tool, args, id, phase = 'working', source
88
89
  export class StreamingCodePreview {
89
90
  buffer = '';
90
91
  lastCode = '';
91
- lastSentAt = 0;
92
+ lastSentAt = null;
92
93
  truncated = false;
93
94
  accept(chunk, now = Date.now()) {
94
- if (!chunk)
95
+ if (!chunk || typeof chunk !== 'string')
95
96
  return null;
96
97
  this.buffer += chunk;
97
98
  if (this.buffer.length > MAX_STREAM_PREVIEW_CHARS) {
98
99
  this.buffer = this.buffer.slice(-MAX_STREAM_PREVIEW_CHARS);
99
100
  this.truncated = true;
100
101
  }
101
- if (now - this.lastSentAt < 100 && !chunk.includes('\n'))
102
+ const safeNow = Number.isFinite(now) ? now : Date.now();
103
+ if (this.lastSentAt !== null && safeNow >= this.lastSentAt && safeNow - this.lastSentAt < 100 && !chunk.includes('\n')) {
102
104
  return null;
105
+ }
103
106
  const code = this.draftCode();
104
107
  if (!code.trim() || code === this.lastCode)
105
108
  return null;
106
109
  this.lastCode = code;
107
- this.lastSentAt = now;
110
+ this.lastSentAt = safeNow;
108
111
  return { type: 'code_progress', id: 'model-draft', phase: 'draft',
109
112
  operation: 'Drafting', description: 'Writing code from the model stream', code,
110
113
  ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
@@ -168,13 +171,17 @@ export class NativeCodeObserver {
168
171
  this.emit = emit;
169
172
  }
170
173
  handle(event) {
171
- if (!event.path || !['Creating', 'Editing'].includes(event.operation))
174
+ if (!event || typeof event !== 'object' || !event.path || !['Creating', 'Editing'].includes(event.operation))
172
175
  return;
173
176
  if (event.code !== undefined || event.phase === 'failed') {
174
177
  this.stop(event.id);
175
178
  return;
176
179
  }
177
- const target = path.resolve(this.workspaceRoot, event.path);
180
+ const target = this.resolveTarget(event.path);
181
+ if (!target) {
182
+ this.stop(event.id);
183
+ return;
184
+ }
178
185
  if (event.phase === 'working') {
179
186
  this.stop(event.id);
180
187
  const previous = this.read(target);
@@ -214,7 +221,7 @@ export class NativeCodeObserver {
214
221
  });
215
222
  }
216
223
  dispose() {
217
- for (const id of this.active.keys())
224
+ for (const id of [...this.active.keys()])
218
225
  this.stop(id);
219
226
  }
220
227
  stop(id) {
@@ -223,15 +230,28 @@ export class NativeCodeObserver {
223
230
  clearInterval(entry.timer);
224
231
  this.active.delete(id);
225
232
  }
233
+ resolveTarget(rawPath) {
234
+ const root = path.resolve(this.workspaceRoot);
235
+ const target = path.resolve(root, rawPath);
236
+ const rel = path.relative(root, target);
237
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
238
+ return null;
239
+ return target;
240
+ }
226
241
  read(file) {
227
242
  try {
228
243
  const name = path.basename(file).toLowerCase();
229
244
  if (/^(\.env(?:\.|$)|.*\.(?:pem|key|p12|pfx)$)/u.test(name))
230
245
  return null;
231
- const stat = fs.lstatSync(file);
246
+ const realRoot = fs.realpathSync(this.workspaceRoot);
247
+ const realFile = fs.realpathSync(file);
248
+ const rel = path.relative(realRoot, realFile);
249
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
250
+ return null;
251
+ const stat = fs.lstatSync(realFile);
232
252
  if (!stat.isFile() || stat.size > 256_000)
233
253
  return null;
234
- const bytes = fs.readFileSync(file);
254
+ const bytes = fs.readFileSync(realFile);
235
255
  if (bytes.includes(0))
236
256
  return null;
237
257
  return bytes.toString('utf8');
@@ -250,7 +270,7 @@ function splitCodeLines(code) {
250
270
  return lines;
251
271
  }
252
272
  function previewLines(event) {
253
- if (event.code === undefined)
273
+ if (!event || typeof event !== 'object' || event.code === undefined)
254
274
  return [];
255
275
  // When creating or drafting code, every line is new code (addition).
256
276
  // Even if a previous file existed on disk, the action is Creating/Drafting.
@@ -317,6 +337,8 @@ export function codePreviewLineCount(event) {
317
337
  return previewLines(event).length;
318
338
  }
319
339
  export function defaultPreviewStart(event) {
340
+ if (!event || typeof event !== 'object')
341
+ return 0;
320
342
  const codeLines = previewLines(event);
321
343
  const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
322
344
  if (event.operation === 'Editing') {
@@ -342,19 +364,28 @@ function highlightCode(kind, text, width) {
342
364
  : (IS_LIGHT ? '48;5;224' : '48;5;52');
343
365
  return paint(role, marker) + `\x1b[${background}m ${body}\x1b[49m`;
344
366
  }
367
+ function oneLineCodeText(value) {
368
+ return safeDisplay(value).replace(/\s+/g, ' ').trim();
369
+ }
345
370
  /** Render a bounded, resize-safe panel. The terminal theme supplies rounded corners. */
346
371
  export function renderCodeProgress(event, width, modelNote = '', startLine) {
347
- const safeWidth = Math.max(12, Math.floor(width) || 80);
372
+ const safeEvent = event && typeof event === 'object'
373
+ ? event
374
+ : { type: 'code_progress', id: 'unknown', phase: 'working', operation: 'code', description: '', source: 'tool' };
375
+ const safeWidth = Number.isFinite(width) ? Math.max(12, Math.floor(width)) : 80;
348
376
  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));
377
+ const operation = oneLineCodeText(safeEvent.operation).toLowerCase() || 'code';
378
+ const title = `${safeEvent.phase === 'done' ? '✓ ' : safeEvent.phase === 'failed' ? '× ' : ''}code · ${operation}`;
379
+ const rows = [truncate(oneLineCodeText(safeEvent.description), inner)];
380
+ if (safeEvent.path)
381
+ rows.push(truncate(oneLineCodeText(safeEvent.path), inner));
353
382
  if (modelNote)
354
- rows.push(truncate(`model note: ${safeDisplay(modelNote)}`, inner));
355
- const codeLines = previewLines(event);
383
+ rows.push(truncate(`model note: ${oneLineCodeText(modelNote)}`, inner));
384
+ const codeLines = previewLines(safeEvent);
356
385
  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));
386
+ const start = startLine === undefined || !Number.isFinite(startLine)
387
+ ? defaultPreviewStart(safeEvent)
388
+ : Math.max(0, Math.min(Math.floor(startLine), maxStart));
358
389
  const visible = codeLines.slice(start, start + CODE_PANEL_LINES);
359
390
  if (visible.length) {
360
391
  rows.push('');
@@ -363,8 +394,8 @@ export function renderCodeProgress(event, width, modelNote = '', startLine) {
363
394
  if (codeLines.length > CODE_PANEL_LINES) {
364
395
  rows.push(truncate(`lines ${start + 1}-${start + visible.length} of ${codeLines.length} · scroll over code`, inner));
365
396
  }
366
- if (event.codeTruncated)
397
+ if (safeEvent.codeTruncated)
367
398
  rows.push(truncate('Earlier draft content exceeded the preview limit', inner));
368
399
  }
369
- return panel(rows, { width: safeWidth, title, role: event.phase === 'failed' ? 'danger' : 'rule' });
400
+ return panel(rows, { width: safeWidth, title, role: safeEvent.phase === 'failed' ? 'danger' : 'rule' });
370
401
  }
@@ -93,16 +93,17 @@ export function codeProgressFromAction(
93
93
  phase: CodePhase = 'working',
94
94
  source: CodeProgressEvent['source'] = 'tool'
95
95
  ): CodeProgressEvent | null {
96
- const operation = FILE_TOOLS[tool];
97
- if (!operation) return null;
98
- const path = stringField(args.path ?? args.Path ?? args.file_path ?? args.FilePath ?? args.AbsolutePath ?? args.TargetFile ?? args.source);
99
- const destination = stringField(args.destination);
96
+ if (typeof tool !== 'string' || !Object.hasOwn(FILE_TOOLS, tool)) return null;
97
+ const operation = FILE_TOOLS[tool]!;
98
+ const safeArgs: Record<string, unknown> = args && typeof args === 'object' ? args : {};
99
+ const path = stringField(safeArgs.path ?? safeArgs.Path ?? safeArgs.file_path ?? safeArgs.FilePath ?? safeArgs.AbsolutePath ?? safeArgs.TargetFile ?? safeArgs.source);
100
+ const destination = stringField(safeArgs.destination);
100
101
  const label = path ? path.split(/[/\\]/).pop() || path : 'file';
101
102
  const description = operation === 'Moving' && destination
102
103
  ? `Moving ${label} to ${destination}`
103
104
  : `${operation} ${label}`;
104
- const before = previousCodeFromArgs(args);
105
- const code = codeFromArgs(args);
105
+ const before = previousCodeFromArgs(safeArgs);
106
+ const code = codeFromArgs(safeArgs);
106
107
  return {
107
108
  type: 'code_progress', id, phase, operation,
108
109
  ...(path ? { path } : {}), description,
@@ -113,21 +114,24 @@ export function codeProgressFromAction(
113
114
  export class StreamingCodePreview {
114
115
  private buffer = '';
115
116
  private lastCode = '';
116
- private lastSentAt = 0;
117
+ private lastSentAt: number | null = null;
117
118
  private truncated = false;
118
119
 
119
120
  accept(chunk: string, now = Date.now()): CodeProgressEvent | null {
120
- if (!chunk) return null;
121
+ if (!chunk || typeof chunk !== 'string') return null;
121
122
  this.buffer += chunk;
122
123
  if (this.buffer.length > MAX_STREAM_PREVIEW_CHARS) {
123
124
  this.buffer = this.buffer.slice(-MAX_STREAM_PREVIEW_CHARS);
124
125
  this.truncated = true;
125
126
  }
126
- if (now - this.lastSentAt < 100 && !chunk.includes('\n')) return null;
127
+ const safeNow = Number.isFinite(now) ? now : Date.now();
128
+ if (this.lastSentAt !== null && safeNow >= this.lastSentAt && safeNow - this.lastSentAt < 100 && !chunk.includes('\n')) {
129
+ return null;
130
+ }
127
131
  const code = this.draftCode();
128
132
  if (!code.trim() || code === this.lastCode) return null;
129
133
  this.lastCode = code;
130
- this.lastSentAt = now;
134
+ this.lastSentAt = safeNow;
131
135
  return { type: 'code_progress', id: 'model-draft', phase: 'draft',
132
136
  operation: 'Drafting', description: 'Writing code from the model stream', code,
133
137
  ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
@@ -184,12 +188,16 @@ export class NativeCodeObserver {
184
188
  }
185
189
 
186
190
  handle(event: CodeProgressEvent): void {
187
- if (!event.path || !['Creating', 'Editing'].includes(event.operation)) return;
191
+ if (!event || typeof event !== 'object' || !event.path || !['Creating', 'Editing'].includes(event.operation)) return;
188
192
  if (event.code !== undefined || event.phase === 'failed') {
189
193
  this.stop(event.id);
190
194
  return;
191
195
  }
192
- const target = path.resolve(this.workspaceRoot, event.path);
196
+ const target = this.resolveTarget(event.path);
197
+ if (!target) {
198
+ this.stop(event.id);
199
+ return;
200
+ }
193
201
  if (event.phase === 'working') {
194
202
  this.stop(event.id);
195
203
  const previous = this.read(target);
@@ -229,7 +237,7 @@ export class NativeCodeObserver {
229
237
  }
230
238
 
231
239
  dispose(): void {
232
- for (const id of this.active.keys()) this.stop(id);
240
+ for (const id of [...this.active.keys()]) this.stop(id);
233
241
  }
234
242
 
235
243
  private stop(id: string): void {
@@ -238,13 +246,25 @@ export class NativeCodeObserver {
238
246
  this.active.delete(id);
239
247
  }
240
248
 
249
+ private resolveTarget(rawPath: string): string | null {
250
+ const root = path.resolve(this.workspaceRoot);
251
+ const target = path.resolve(root, rawPath);
252
+ const rel = path.relative(root, target);
253
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
254
+ return target;
255
+ }
256
+
241
257
  private read(file: string): string | null {
242
258
  try {
243
259
  const name = path.basename(file).toLowerCase();
244
260
  if (/^(\.env(?:\.|$)|.*\.(?:pem|key|p12|pfx)$)/u.test(name)) return null;
245
- const stat = fs.lstatSync(file);
261
+ const realRoot = fs.realpathSync(this.workspaceRoot);
262
+ const realFile = fs.realpathSync(file);
263
+ const rel = path.relative(realRoot, realFile);
264
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
265
+ const stat = fs.lstatSync(realFile);
246
266
  if (!stat.isFile() || stat.size > 256_000) return null;
247
- const bytes = fs.readFileSync(file);
267
+ const bytes = fs.readFileSync(realFile);
248
268
  if (bytes.includes(0)) return null;
249
269
  return bytes.toString('utf8');
250
270
  } catch {
@@ -263,7 +283,7 @@ function splitCodeLines(code: string): string[] {
263
283
  }
264
284
 
265
285
  function previewLines(event: CodeProgressEvent): PreviewLine[] {
266
- if (event.code === undefined) return [];
286
+ if (!event || typeof event !== 'object' || event.code === undefined) return [];
267
287
 
268
288
  // When creating or drafting code, every line is new code (addition).
269
289
  // Even if a previous file existed on disk, the action is Creating/Drafting.
@@ -339,6 +359,7 @@ export function codePreviewLineCount(event: CodeProgressEvent): number {
339
359
  }
340
360
 
341
361
  export function defaultPreviewStart(event: CodeProgressEvent): number {
362
+ if (!event || typeof event !== 'object') return 0;
342
363
  const codeLines = previewLines(event);
343
364
  const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
344
365
  if (event.operation === 'Editing') {
@@ -365,17 +386,28 @@ function highlightCode(kind: PreviewLine['kind'], text: string, width: number):
365
386
  return paint(role, marker) + `\x1b[${background}m ${body}\x1b[49m`;
366
387
  }
367
388
 
389
+ function oneLineCodeText(value: unknown): string {
390
+ return safeDisplay(value).replace(/\s+/g, ' ').trim();
391
+ }
392
+
368
393
  /** Render a bounded, resize-safe panel. The terminal theme supplies rounded corners. */
369
394
  export function renderCodeProgress(event: CodeProgressEvent, width: number, modelNote = '', startLine?: number): string[] {
370
- const safeWidth = Math.max(12, Math.floor(width) || 80);
395
+ const safeEvent: CodeProgressEvent =
396
+ event && typeof event === 'object'
397
+ ? event
398
+ : { type: 'code_progress', id: 'unknown', phase: 'working', operation: 'code', description: '', source: 'tool' };
399
+ const safeWidth = Number.isFinite(width) ? Math.max(12, Math.floor(width)) : 80;
371
400
  const inner = safeWidth - 4;
372
- const title = `${event.phase === 'done' ? '✓ ' : event.phase === 'failed' ? '× ' : ''}code · ${event.operation.toLowerCase()}`;
373
- const rows = [truncate(safeDisplay(event.description), inner)];
374
- if (event.path) rows.push(truncate(safeDisplay(event.path), inner));
375
- if (modelNote) rows.push(truncate(`model note: ${safeDisplay(modelNote)}`, inner));
376
- const codeLines = previewLines(event);
401
+ const operation = oneLineCodeText(safeEvent.operation).toLowerCase() || 'code';
402
+ const title = `${safeEvent.phase === 'done' ? '✓ ' : safeEvent.phase === 'failed' ? '× ' : ''}code · ${operation}`;
403
+ const rows = [truncate(oneLineCodeText(safeEvent.description), inner)];
404
+ if (safeEvent.path) rows.push(truncate(oneLineCodeText(safeEvent.path), inner));
405
+ if (modelNote) rows.push(truncate(`model note: ${oneLineCodeText(modelNote)}`, inner));
406
+ const codeLines = previewLines(safeEvent);
377
407
  const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
378
- const start = startLine === undefined ? defaultPreviewStart(event) : Math.max(0, Math.min(Math.floor(startLine), maxStart));
408
+ const start = startLine === undefined || !Number.isFinite(startLine)
409
+ ? defaultPreviewStart(safeEvent)
410
+ : Math.max(0, Math.min(Math.floor(startLine), maxStart));
379
411
  const visible = codeLines.slice(start, start + CODE_PANEL_LINES);
380
412
  if (visible.length) {
381
413
  rows.push('');
@@ -383,7 +415,7 @@ export function renderCodeProgress(event: CodeProgressEvent, width: number, mode
383
415
  if (codeLines.length > CODE_PANEL_LINES) {
384
416
  rows.push(truncate(`lines ${start + 1}-${start + visible.length} of ${codeLines.length} · scroll over code`, inner));
385
417
  }
386
- if (event.codeTruncated) rows.push(truncate('Earlier draft content exceeded the preview limit', inner));
418
+ if (safeEvent.codeTruncated) rows.push(truncate('Earlier draft content exceeded the preview limit', inner));
387
419
  }
388
- return panel(rows, { width: safeWidth, title, role: event.phase === 'failed' ? 'danger' : 'rule' });
420
+ return panel(rows, { width: safeWidth, title, role: safeEvent.phase === 'failed' ? 'danger' : 'rule' });
389
421
  }