@causyne/agent 1.20.62 → 1.20.65

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 (65) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/acp/client.js +48 -0
  4. package/src/acp/client.ts +44 -0
  5. package/src/agentLoop.js +181 -11
  6. package/src/agentLoop.ts +184 -11
  7. package/src/approvalPolicy.js +19 -0
  8. package/src/approvalPolicy.ts +18 -0
  9. package/src/browser/causyneBrowser.js +34 -4
  10. package/src/browser/causyneBrowser.ts +32 -4
  11. package/src/cliMode.js +12 -28
  12. package/src/commands.js +33 -0
  13. package/src/decisionPolicy.js +18 -1
  14. package/src/decisionPolicy.ts +18 -1
  15. package/src/implementationPlan.js +26 -0
  16. package/src/implementationPlan.ts +25 -0
  17. package/src/observer/coldObserver.js +6 -1
  18. package/src/observer/coldObserver.ts +6 -1
  19. package/src/observer.js +24 -2
  20. package/src/observer.ts +24 -2
  21. package/src/providers/acp.js +2 -8
  22. package/src/providers/acp.ts +2 -8
  23. package/src/providers/antigravity.js +7 -10
  24. package/src/providers/antigravity.ts +7 -10
  25. package/src/smartToolsUse.js +1 -1
  26. package/src/smartToolsUse.ts +1 -1
  27. package/src/toolPacks.js +1 -1
  28. package/src/toolPacks.ts +1 -1
  29. package/src/tools/toolSelfRepair.js +51 -8
  30. package/src/tools/toolSelfRepair.ts +42 -9
  31. package/src/tui/CausyneRotor.js +234 -0
  32. package/src/tui/CausyneRotor.ts +280 -0
  33. package/src/tui/activityLayout.js +1 -1
  34. package/src/tui/activityLayout.ts +1 -1
  35. package/src/tui/chatRenderer.js +56 -7
  36. package/src/tui/chatboxClipboard.js +96 -10
  37. package/src/tui/chatboxClipboard.ts +121 -11
  38. package/src/tui/clipboardImage.js +308 -0
  39. package/src/tui/clipboardImage.ts +320 -0
  40. package/src/tui/codeStreamRenderer.js +89 -1
  41. package/src/tui/codeStreamRenderer.ts +109 -1
  42. package/src/tui/composerControls.js +2 -0
  43. package/src/tui/composerControls.ts +2 -0
  44. package/src/tui/dialogs.js +41 -6
  45. package/src/tui/engineSpinner.js +20 -0
  46. package/src/tui/engineSpinner.ts +46 -0
  47. package/src/tui/lineEditor.js +44 -12
  48. package/src/tui/messageInteraction.js +16 -5
  49. package/src/tui/messageInteraction.ts +14 -5
  50. package/src/tui/observerPicker.js +4 -8
  51. package/src/tui/observerPicker.ts +4 -8
  52. package/src/tui/prompt.js +80 -43
  53. package/src/tui/runningLight.js +213 -0
  54. package/src/tui/runningLight.ts +271 -0
  55. package/src/tui/sessionSidebar.js +7 -1
  56. package/src/tui/sessionSidebar.ts +7 -1
  57. package/src/tui/stage.js +4 -4
  58. package/src/tui/stageSurface.js +21 -14
  59. package/src/tui/statusLine.js +27 -4
  60. package/src/tui/statusLine.ts +27 -4
  61. package/src/tui/theme.js +5 -2
  62. package/src/tui/thinkingBox.js +41 -10
  63. package/src/tui/thinkingBox.ts +43 -10
  64. package/src/tui/turnRail.js +155 -24
  65. package/src/tui/turnRail.ts +170 -22
@@ -1,6 +1,8 @@
1
1
  // Chatbox Clipboard Manager: surgical operations for copy, paste, and CRLF normalization.
2
2
  // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
3
  import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
4
+ import { readClipboardImageSync, formatByteSize, loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile } from './clipboardImage.js';
5
+ export { loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile };
4
6
  /**
5
7
  * Clean up text copied or pasted: normalize Windows CRLF and classic Mac CR to LF,
6
8
  * remove null bytes and non-printable control characters while preserving valid newlines and tabs.
@@ -42,22 +44,103 @@ export function copyChatboxInput(prompt) {
42
44
  }
43
45
  /**
44
46
  * Paste clipboard content into the chatbox prompt editor.
47
+ * Seamlessly supports both text and screenshot images from system clipboard,
48
+ * as well as drag-and-dropped local image file paths and empty bracketed pastes.
45
49
  */
46
50
  export function pasteIntoChatbox(prompt, fallbackText) {
47
- const raw = fallbackText ?? readClipboardSync();
48
- const text = normalizeClipboardText(raw);
49
- if (!text) {
50
- prompt.notice = 'clipboard is empty';
51
+ const clean = normalizeClipboardText(fallbackText);
52
+ // 1. If fallbackText was provided (e.g. drag & drop or file paste), check if it's a local image file
53
+ if (clean) {
54
+ const filePath = extractPastedFilePath(clean);
55
+ const localImg = loadLocalImageAttachment(filePath);
56
+ if (localImg) {
57
+ if (!Array.isArray(prompt.pendingAttachments)) {
58
+ prompt.pendingAttachments = [];
59
+ }
60
+ prompt.pendingAttachments.push(localImg);
61
+ const index = prompt.pendingAttachments.length;
62
+ const tag = `[Image ${index}] `;
63
+ prompt.editor.insert(tag);
64
+ if (typeof prompt.refreshCompletion === 'function') {
65
+ prompt.refreshCompletion();
66
+ }
67
+ prompt.notice = `attached image ${index} (${formatByteSize(localImg.size)})`;
68
+ prompt.scheduleDraw();
69
+ return { success: true, notice: prompt.notice, text: tag, isImage: true };
70
+ }
71
+ }
72
+ // 2. If fallbackText was empty (empty bracketed paste from Cmd+V in terminal when an image is copied)
73
+ // OR no fallbackText was passed (user pressed Ctrl+V, Alt+V, or typed /paste):
74
+ // Probe system clipboard for screenshot / image FIRST!
75
+ if (!clean) {
76
+ const img = readClipboardImageSync();
77
+ if (img) {
78
+ if (!Array.isArray(prompt.pendingAttachments)) {
79
+ prompt.pendingAttachments = [];
80
+ }
81
+ prompt.pendingAttachments.push(img);
82
+ const index = prompt.pendingAttachments.length;
83
+ const tag = `[Image ${index}] `;
84
+ prompt.editor.insert(tag);
85
+ if (typeof prompt.refreshCompletion === 'function') {
86
+ prompt.refreshCompletion();
87
+ }
88
+ prompt.notice = `attached clipboard image ${index} (${formatByteSize(img.size)})`;
89
+ prompt.scheduleDraw();
90
+ return { success: true, notice: prompt.notice, text: tag, isImage: true };
91
+ }
92
+ }
93
+ // 3. If fallbackText had non-image text: insert it into the editor
94
+ if (clean) {
95
+ prompt.editor.insert(clean);
96
+ if (typeof prompt.refreshCompletion === 'function') {
97
+ prompt.refreshCompletion();
98
+ }
99
+ prompt.notice = 'pasted from clipboard';
51
100
  prompt.scheduleDraw();
52
- return { success: false, notice: prompt.notice, text: '' };
101
+ return { success: true, notice: prompt.notice, text: clean, isImage: false };
53
102
  }
54
- prompt.editor.insert(text);
55
- if (typeof prompt.refreshCompletion === 'function') {
56
- prompt.refreshCompletion();
103
+ // 4. No fallbackText provided and no clipboard image: read text from clipboard
104
+ const clipText = normalizeClipboardText(readClipboardSync());
105
+ if (clipText) {
106
+ const filePath = extractPastedFilePath(clipText);
107
+ const localImg = loadLocalImageAttachment(filePath);
108
+ if (localImg) {
109
+ if (!Array.isArray(prompt.pendingAttachments)) {
110
+ prompt.pendingAttachments = [];
111
+ }
112
+ prompt.pendingAttachments.push(localImg);
113
+ const index = prompt.pendingAttachments.length;
114
+ const tag = `[Image ${index}] `;
115
+ prompt.editor.insert(tag);
116
+ if (typeof prompt.refreshCompletion === 'function') {
117
+ prompt.refreshCompletion();
118
+ }
119
+ prompt.notice = `attached image ${index} (${formatByteSize(localImg.size)})`;
120
+ prompt.scheduleDraw();
121
+ return { success: true, notice: prompt.notice, text: tag, isImage: true };
122
+ }
123
+ prompt.editor.insert(clipText);
124
+ if (typeof prompt.refreshCompletion === 'function') {
125
+ prompt.refreshCompletion();
126
+ }
127
+ prompt.notice = 'pasted from clipboard';
128
+ prompt.scheduleDraw();
129
+ return { success: true, notice: prompt.notice, text: clipText, isImage: false };
57
130
  }
58
- prompt.notice = 'pasted from clipboard';
131
+ // 5. Fallback to editor killRing
132
+ if (prompt.editor.killRing) {
133
+ prompt.editor.insert(prompt.editor.killRing);
134
+ if (typeof prompt.refreshCompletion === 'function') {
135
+ prompt.refreshCompletion();
136
+ }
137
+ prompt.notice = 'yanked from kill ring';
138
+ prompt.scheduleDraw();
139
+ return { success: true, notice: prompt.notice, text: prompt.editor.killRing, isImage: false };
140
+ }
141
+ prompt.notice = 'clipboard is empty';
59
142
  prompt.scheduleDraw();
60
- return { success: true, notice: prompt.notice, text };
143
+ return { success: false, notice: prompt.notice, text: '' };
61
144
  }
62
145
  /**
63
146
  * Extract the content of the last assistant turn from the conversation.
@@ -148,5 +231,8 @@ export function runPasteCommand(argv, ctx) {
148
231
  if (!result.success) {
149
232
  return { ok: false, output: 'Clipboard is empty or unavailable.' };
150
233
  }
234
+ if (result.isImage) {
235
+ return { ok: true, output: `Attached screenshot from clipboard (${result.text.trim()}).` };
236
+ }
151
237
  return { ok: true, output: `Pasted ${result.text.length} characters into chatbox input.` };
152
238
  }
@@ -2,6 +2,21 @@
2
2
  // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
3
 
4
4
  import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
5
+ import {
6
+ readClipboardImageSync,
7
+ formatByteSize,
8
+ loadLocalImageAttachment,
9
+ extractPastedFilePath,
10
+ isLocalImageFile,
11
+ type ClipboardImageAttachment
12
+ } from './clipboardImage.js';
13
+
14
+ export {
15
+ loadLocalImageAttachment,
16
+ extractPastedFilePath,
17
+ isLocalImageFile,
18
+ type ClipboardImageAttachment
19
+ };
5
20
 
6
21
  export interface ChatboxEditor {
7
22
  lines: string[][];
@@ -20,6 +35,7 @@ export interface ChatboxPrompt {
20
35
  notice: string;
21
36
  scheduleDraw(): void;
22
37
  refreshCompletion?: (() => void) | undefined;
38
+ pendingAttachments?: ClipboardImageAttachment[] | undefined;
23
39
  }
24
40
 
25
41
  export interface ConversationMessage {
@@ -79,22 +95,113 @@ export function copyChatboxInput(prompt: ChatboxPrompt): { success: boolean; not
79
95
 
80
96
  /**
81
97
  * Paste clipboard content into the chatbox prompt editor.
98
+ * Seamlessly supports both text and screenshot images from system clipboard,
99
+ * as well as drag-and-dropped local image file paths and empty bracketed pastes.
82
100
  */
83
- export function pasteIntoChatbox(prompt: ChatboxPrompt, fallbackText?: string): { success: boolean; notice: string; text: string } {
84
- const raw = fallbackText ?? readClipboardSync();
85
- const text = normalizeClipboardText(raw);
86
- if (!text) {
87
- prompt.notice = 'clipboard is empty';
101
+ export function pasteIntoChatbox(
102
+ prompt: ChatboxPrompt,
103
+ fallbackText?: string
104
+ ): { success: boolean; notice: string; text: string; isImage?: boolean } {
105
+ const clean = normalizeClipboardText(fallbackText);
106
+
107
+ // 1. If fallbackText was provided (e.g. drag & drop or file paste), check if it's a local image file
108
+ if (clean) {
109
+ const filePath = extractPastedFilePath(clean);
110
+ const localImg = loadLocalImageAttachment(filePath);
111
+ if (localImg) {
112
+ if (!Array.isArray(prompt.pendingAttachments)) {
113
+ prompt.pendingAttachments = [];
114
+ }
115
+ prompt.pendingAttachments.push(localImg);
116
+ const index = prompt.pendingAttachments.length;
117
+ const tag = `[Image ${index}] `;
118
+ prompt.editor.insert(tag);
119
+ if (typeof prompt.refreshCompletion === 'function') {
120
+ prompt.refreshCompletion();
121
+ }
122
+ prompt.notice = `attached image ${index} (${formatByteSize(localImg.size)})`;
123
+ prompt.scheduleDraw();
124
+ return { success: true, notice: prompt.notice, text: tag, isImage: true };
125
+ }
126
+ }
127
+
128
+ // 2. If fallbackText was empty (empty bracketed paste from Cmd+V in terminal when an image is copied)
129
+ // OR no fallbackText was passed (user pressed Ctrl+V, Alt+V, or typed /paste):
130
+ // Probe system clipboard for screenshot / image FIRST!
131
+ if (!clean) {
132
+ const img = readClipboardImageSync();
133
+ if (img) {
134
+ if (!Array.isArray(prompt.pendingAttachments)) {
135
+ prompt.pendingAttachments = [];
136
+ }
137
+ prompt.pendingAttachments.push(img);
138
+ const index = prompt.pendingAttachments.length;
139
+ const tag = `[Image ${index}] `;
140
+ prompt.editor.insert(tag);
141
+ if (typeof prompt.refreshCompletion === 'function') {
142
+ prompt.refreshCompletion();
143
+ }
144
+ prompt.notice = `attached clipboard image ${index} (${formatByteSize(img.size)})`;
145
+ prompt.scheduleDraw();
146
+ return { success: true, notice: prompt.notice, text: tag, isImage: true };
147
+ }
148
+ }
149
+
150
+ // 3. If fallbackText had non-image text: insert it into the editor
151
+ if (clean) {
152
+ prompt.editor.insert(clean);
153
+ if (typeof prompt.refreshCompletion === 'function') {
154
+ prompt.refreshCompletion();
155
+ }
156
+ prompt.notice = 'pasted from clipboard';
88
157
  prompt.scheduleDraw();
89
- return { success: false, notice: prompt.notice, text: '' };
158
+ return { success: true, notice: prompt.notice, text: clean, isImage: false };
90
159
  }
91
- prompt.editor.insert(text);
92
- if (typeof prompt.refreshCompletion === 'function') {
93
- prompt.refreshCompletion();
160
+
161
+ // 4. No fallbackText provided and no clipboard image: read text from clipboard
162
+ const clipText = normalizeClipboardText(readClipboardSync());
163
+ if (clipText) {
164
+ const filePath = extractPastedFilePath(clipText);
165
+ const localImg = loadLocalImageAttachment(filePath);
166
+ if (localImg) {
167
+ if (!Array.isArray(prompt.pendingAttachments)) {
168
+ prompt.pendingAttachments = [];
169
+ }
170
+ prompt.pendingAttachments.push(localImg);
171
+ const index = prompt.pendingAttachments.length;
172
+ const tag = `[Image ${index}] `;
173
+ prompt.editor.insert(tag);
174
+ if (typeof prompt.refreshCompletion === 'function') {
175
+ prompt.refreshCompletion();
176
+ }
177
+ prompt.notice = `attached image ${index} (${formatByteSize(localImg.size)})`;
178
+ prompt.scheduleDraw();
179
+ return { success: true, notice: prompt.notice, text: tag, isImage: true };
180
+ }
181
+
182
+ prompt.editor.insert(clipText);
183
+ if (typeof prompt.refreshCompletion === 'function') {
184
+ prompt.refreshCompletion();
185
+ }
186
+ prompt.notice = 'pasted from clipboard';
187
+ prompt.scheduleDraw();
188
+ return { success: true, notice: prompt.notice, text: clipText, isImage: false };
94
189
  }
95
- prompt.notice = 'pasted from clipboard';
190
+
191
+ // 5. Fallback to editor killRing
192
+ if (prompt.editor.killRing) {
193
+ prompt.editor.insert(prompt.editor.killRing);
194
+ if (typeof prompt.refreshCompletion === 'function') {
195
+ prompt.refreshCompletion();
196
+ }
197
+ prompt.notice = 'yanked from kill ring';
198
+ prompt.scheduleDraw();
199
+ return { success: true, notice: prompt.notice, text: prompt.editor.killRing, isImage: false };
200
+ }
201
+
202
+ prompt.notice = 'clipboard is empty';
96
203
  prompt.scheduleDraw();
97
- return { success: true, notice: prompt.notice, text };
204
+ return { success: false, notice: prompt.notice, text: '' };
98
205
  }
99
206
 
100
207
  /**
@@ -197,5 +304,8 @@ export function runPasteCommand(
197
304
  if (!result.success) {
198
305
  return { ok: false, output: 'Clipboard is empty or unavailable.' };
199
306
  }
307
+ if (result.isImage) {
308
+ return { ok: true, output: `Attached screenshot from clipboard (${result.text.trim()}).` };
309
+ }
200
310
  return { ok: true, output: `Pasted ${result.text.length} characters into chatbox input.` };
201
311
  }
@@ -0,0 +1,308 @@
1
+ // Sovereign Cross-Platform Clipboard Image Reader & Attachment Manager.
2
+ // Captures screenshots and images pasted from system clipboard across macOS (osascript),
3
+ // Windows/WSL (PowerShell System.Windows.Forms), and Linux (wl-paste, xclip).
4
+ // Provides seamless multimodal image attachment for TUI prompt editors and slash commands.
5
+ import { spawnSync } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { causyneHome, resolveUserPath } from '../utils/paths.js';
11
+ /**
12
+ * Format bytes into readable string: '128 KB', '1.5 MB'.
13
+ */
14
+ 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`;
20
+ }
21
+ /**
22
+ * Detect image mime type from binary magic bytes.
23
+ */
24
+ export function detectImageMimeType(buffer) {
25
+ if (!buffer || buffer.length < 8)
26
+ return null;
27
+ // PNG: 89 50 4E 47 0D 0A 1A 0A
28
+ if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {
29
+ return 'image/png';
30
+ }
31
+ // JPEG: FF D8 FF
32
+ if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
33
+ return 'image/jpeg';
34
+ }
35
+ // GIF: 47 49 46 38
36
+ if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38) {
37
+ return 'image/gif';
38
+ }
39
+ // WebP: 52 49 46 46 ... 57 45 42 50
40
+ if (buffer.length >= 12 &&
41
+ buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 &&
42
+ buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {
43
+ return 'image/webp';
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * Ensure the causyne attachments directory exists and return its path.
49
+ */
50
+ export function getAttachmentsDirectory() {
51
+ const dir = path.join(causyneHome(), 'attachments');
52
+ if (!fs.existsSync(dir)) {
53
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ }
55
+ return dir;
56
+ }
57
+ /**
58
+ * Save raw image buffer to persistent attachments directory and return attachment object.
59
+ */
60
+ export function persistImageBuffer(buffer, preferredName) {
61
+ const mimeType = detectImageMimeType(buffer);
62
+ if (!mimeType)
63
+ return null;
64
+ const ext = mimeType === 'image/jpeg' ? 'jpg'
65
+ : mimeType === 'image/webp' ? 'webp'
66
+ : mimeType === 'image/gif' ? 'gif'
67
+ : 'png';
68
+ const timestamp = Date.now();
69
+ const filename = preferredName
70
+ ? path.basename(preferredName)
71
+ : `screenshot_${timestamp}.${ext}`;
72
+ const attachmentsDir = getAttachmentsDirectory();
73
+ const filePath = path.join(attachmentsDir, filename);
74
+ fs.writeFileSync(filePath, buffer, { mode: 0o600 });
75
+ return {
76
+ type: 'image',
77
+ mimeType,
78
+ base64: buffer.toString('base64'),
79
+ name: filename,
80
+ path: filePath,
81
+ size: buffer.length
82
+ };
83
+ }
84
+ /**
85
+ * Read screenshot or image from macOS clipboard using built-in osascript.
86
+ * Supports both PNG and JPEG image data placed on clipboard by macOS, browsers, and terminals.
87
+ */
88
+ 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');
118
+ try {
119
+ const res = spawnSync('osascript', ['-e', script], {
120
+ encoding: 'utf8',
121
+ timeout: 3000,
122
+ windowsHide: true
123
+ });
124
+ if (res.status === 0 && res.stdout.trim() === 'ok' && fs.existsSync(tempFile)) {
125
+ const buf = fs.readFileSync(tempFile);
126
+ return buf.length > 0 ? buf : null;
127
+ }
128
+ }
129
+ catch {
130
+ // osascript clipboard read is best-effort
131
+ }
132
+ finally {
133
+ try {
134
+ if (fs.existsSync(tempFile))
135
+ fs.unlinkSync(tempFile);
136
+ }
137
+ catch {
138
+ // Ignore cleanup error
139
+ }
140
+ }
141
+ return null;
142
+ }
143
+ /**
144
+ * Read screenshot or image from Windows or WSL clipboard via PowerShell.
145
+ */
146
+ function readWindowsClipboardImageSync() {
147
+ const command = process.platform === 'win32' ? 'powershell.exe' : 'powershell.exe';
148
+ const psScript = 'Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }';
149
+ try {
150
+ const res = spawnSync(command, ['-NonInteractive', '-NoProfile', '-Command', psScript], {
151
+ encoding: 'utf8',
152
+ timeout: 4000,
153
+ maxBuffer: 32 * 1024 * 1024,
154
+ windowsHide: true
155
+ });
156
+ if (res.status === 0 && res.stdout) {
157
+ const b64 = res.stdout.trim();
158
+ if (b64.length > 0) {
159
+ const buf = Buffer.from(b64, 'base64');
160
+ return buf.length > 0 ? buf : null;
161
+ }
162
+ }
163
+ }
164
+ catch {
165
+ // PowerShell clipboard image is best-effort
166
+ }
167
+ return null;
168
+ }
169
+ /**
170
+ * Read screenshot or image from Linux clipboard via Wayland (wl-paste) or X11 (xclip).
171
+ */
172
+ function readLinuxClipboardImageSync() {
173
+ // Try Wayland first
174
+ try {
175
+ const wl = spawnSync('wl-paste', ['-t', 'image/png'], {
176
+ timeout: 2500,
177
+ maxBuffer: 32 * 1024 * 1024
178
+ });
179
+ if (wl.status === 0 && Buffer.isBuffer(wl.stdout) && wl.stdout.length > 0) {
180
+ return wl.stdout;
181
+ }
182
+ }
183
+ catch {
184
+ // Fall through to X11
185
+ }
186
+ // Try X11 xclip
187
+ try {
188
+ const xc = spawnSync('xclip', ['-selection', 'clipboard', '-t', 'image/png', '-o'], {
189
+ timeout: 2500,
190
+ maxBuffer: 32 * 1024 * 1024
191
+ });
192
+ if (xc.status === 0 && Buffer.isBuffer(xc.stdout) && xc.stdout.length > 0) {
193
+ return xc.stdout;
194
+ }
195
+ }
196
+ catch {
197
+ // Fall through
198
+ }
199
+ return null;
200
+ }
201
+ /**
202
+ * Synchronously read screenshot or image from the system clipboard.
203
+ * Returns ClipboardImageAttachment if an image is present, or null if none.
204
+ */
205
+ export function readClipboardImageSync() {
206
+ try {
207
+ let buf = null;
208
+ if (process.platform === 'darwin') {
209
+ buf = readDarwinClipboardImageSync();
210
+ }
211
+ else if (process.platform === 'win32' || (os.release().toLowerCase().includes('wsl'))) {
212
+ buf = readWindowsClipboardImageSync();
213
+ }
214
+ else if (process.platform === 'linux') {
215
+ buf = readLinuxClipboardImageSync();
216
+ }
217
+ if (buf && buf.length > 0) {
218
+ return persistImageBuffer(buf);
219
+ }
220
+ }
221
+ catch {
222
+ // Non-throwing guard
223
+ }
224
+ return null;
225
+ }
226
+ /**
227
+ * Clean up and extract a valid local file path from pasted text or drag-and-drop strings.
228
+ * Strips quotes, file:// URIs, and backslash escape sequences.
229
+ */
230
+ export function extractPastedFilePath(input) {
231
+ let raw = String(input ?? '').trim();
232
+ // Strip surrounding quotes
233
+ while (raw.length >= 2 && ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'")))) {
234
+ raw = raw.slice(1, -1).trim();
235
+ }
236
+ // Handle file:// URI
237
+ if (raw.startsWith('file://')) {
238
+ try {
239
+ raw = fileURLToPath(raw);
240
+ }
241
+ catch {
242
+ // ignore
243
+ }
244
+ }
245
+ // Unescape backslash-escaped spaces/characters on Unix, and backslash-escaped spaces on Windows
246
+ if (process.platform !== 'win32') {
247
+ raw = raw.replace(/\\(.)/g, '$1');
248
+ }
249
+ else {
250
+ raw = raw.replace(/\\ /g, ' ');
251
+ }
252
+ return raw;
253
+ }
254
+ const KNOWN_IMAGE_EXTENSIONS = new Set([
255
+ '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff', '.tif'
256
+ ]);
257
+ /**
258
+ * Check if a file path corresponds to an existing local image file.
259
+ */
260
+ export function isLocalImageFile(rawPath) {
261
+ try {
262
+ const cleaned = extractPastedFilePath(rawPath);
263
+ if (!cleaned)
264
+ return false;
265
+ const resolved = resolveUserPath(cleaned);
266
+ const ext = path.extname(resolved).toLowerCase();
267
+ if (!KNOWN_IMAGE_EXTENSIONS.has(ext))
268
+ return false;
269
+ if (!fs.existsSync(resolved))
270
+ return false;
271
+ const stat = fs.statSync(resolved);
272
+ return stat.isFile() && stat.size > 0 && stat.size <= 25 * 1024 * 1024;
273
+ }
274
+ catch {
275
+ return false;
276
+ }
277
+ }
278
+ /**
279
+ * Load a local image file as an attachment (e.g. from /image or /attach command).
280
+ */
281
+ export function loadLocalImageAttachment(rawPath) {
282
+ try {
283
+ const cleaned = extractPastedFilePath(rawPath);
284
+ if (!cleaned)
285
+ return null;
286
+ const resolved = resolveUserPath(cleaned);
287
+ if (!fs.existsSync(resolved))
288
+ return null;
289
+ const stat = fs.statSync(resolved);
290
+ if (!stat.isFile() || stat.size > 25 * 1024 * 1024)
291
+ return null; // 25 MB ceiling
292
+ const buffer = fs.readFileSync(resolved);
293
+ const mimeType = detectImageMimeType(buffer);
294
+ if (!mimeType)
295
+ return null;
296
+ return {
297
+ type: 'image',
298
+ mimeType,
299
+ base64: buffer.toString('base64'),
300
+ name: path.basename(resolved),
301
+ path: resolved,
302
+ size: buffer.length
303
+ };
304
+ }
305
+ catch {
306
+ return null;
307
+ }
308
+ }