@causyne/agent 1.20.9 → 1.20.11

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 (47) hide show
  1. package/package.json +2 -1
  2. package/src/agentLoop.js +127 -72
  3. package/src/agentLoop.ts +137 -75
  4. package/src/browser/causyneBrowser.js +36 -0
  5. package/src/browser/causyneBrowser.ts +36 -1
  6. package/src/commands.js +25 -0
  7. package/src/contextManager.js +16 -0
  8. package/src/providers/antigravity.js +63 -11
  9. package/src/providers/antigravity.ts +62 -12
  10. package/src/provisioning/capabilityProvisioner.js +2 -7
  11. package/src/provisioning/npmInstall.js +19 -0
  12. package/src/provisioning/npmInstall.ts +19 -0
  13. package/src/smartToolsUse.js +20 -0
  14. package/src/smartToolsUse.ts +21 -0
  15. package/src/stallGuard.js +347 -0
  16. package/src/stallGuard.ts +423 -0
  17. package/src/tools/browserAutomator.js +3 -3
  18. package/src/tools/browserAutomator.ts +3 -3
  19. package/src/tools/fsRead.js +91 -80
  20. package/src/tools/fsRead.ts +125 -0
  21. package/src/tools/peerAgent.js +1 -1
  22. package/src/tools/peerAgent.ts +1 -1
  23. package/src/tools/screenshot.js +5 -1
  24. package/src/tools/screenshot.ts +5 -1
  25. package/src/tools/toolScanner.js +19 -0
  26. package/src/tools/toolScanner.ts +17 -0
  27. package/src/tools/toolSelfRepair.js +63 -1
  28. package/src/tools/toolSelfRepair.ts +61 -1
  29. package/src/tools/visionInspector.js +80 -142
  30. package/src/tools/visionInspector.ts +110 -0
  31. package/src/tui/chatboxClipboard.js +152 -0
  32. package/src/tui/chatboxClipboard.ts +201 -0
  33. package/src/tui/clipboardSync.js +38 -7
  34. package/src/tui/clipboardSync.ts +39 -7
  35. package/src/tui/codeProgress.js +89 -18
  36. package/src/tui/codeProgress.ts +102 -17
  37. package/src/tui/codeStreamRenderer.js +7 -2
  38. package/src/tui/codeStreamRenderer.ts +7 -2
  39. package/src/tui/composerControls.js +9 -0
  40. package/src/tui/composerControls.ts +9 -0
  41. package/src/tui/dialogs.js +8 -3
  42. package/src/tui/diff.d.ts +1 -0
  43. package/src/tui/lineEditor.js +166 -14
  44. package/src/tui/mouseHover.js +6 -2
  45. package/src/tui/mouseHover.ts +7 -2
  46. package/src/tui/prompt.js +96 -19
  47. package/src/tui/stageSurface.js +3 -1
@@ -0,0 +1,110 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+
7
+ import { ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
8
+
9
+ const execFileAsync = promisify(execFile);
10
+
11
+ interface VisionArgs {
12
+ target: 'desktop' | 'android_adb';
13
+ prompt: string;
14
+ deviceSerial?: string;
15
+ }
16
+
17
+ interface OcrWord {
18
+ text: string;
19
+ confidence: number;
20
+ bbox: { x0: number; x1: number; y0: number; y1: number };
21
+ }
22
+
23
+ export const visionInspector = {
24
+ schema: {
25
+ name: 'vision.inspect_ui',
26
+ description: 'Capture a live desktop or Android screen and pass its pixels to a vision-capable model. OCR coordinates are included when the OCR capability is available. A capture failure is not visual verification.',
27
+ parameters: {
28
+ type: 'object',
29
+ properties: {
30
+ target: { type: 'string', enum: ['desktop', 'android_adb'] },
31
+ prompt: { type: 'string', description: 'What to inspect in the captured UI.' },
32
+ deviceSerial: { type: 'string', description: 'Optional Android ADB device serial.' }
33
+ },
34
+ required: ['target', 'prompt']
35
+ }
36
+ },
37
+
38
+ async execute(args: VisionArgs) {
39
+ const target = args.target;
40
+ if (target !== 'desktop' && target !== 'android_adb') {
41
+ return { success: false, error: 'target must be desktop or android_adb' };
42
+ }
43
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'causyne-vision-inspect-'));
44
+ const imagePath = path.join(tempDir, 'screen.png');
45
+ try {
46
+ if (target === 'android_adb') {
47
+ const adbArgs = args.deviceSerial ? ['-s', args.deviceSerial] : [];
48
+ const { stdout } = await execFileAsync('adb', [...adbArgs, 'shell', 'screencap', '-p'], {
49
+ encoding: 'buffer', maxBuffer: 20 * 1024 * 1024
50
+ });
51
+ const bytes = process.platform === 'win32'
52
+ ? Buffer.from(stdout.toString('binary').replace(/\r\n/g, '\n'), 'binary')
53
+ : stdout;
54
+ await fs.writeFile(imagePath, bytes);
55
+ } else {
56
+ const vision = await ensureCapability('vision');
57
+ if (!vision.ok) return { success: false, error: vision.reason, requiresConsent: vision.requiresConsent };
58
+ const capture = await loadCapabilityPackage('screenshot-desktop') as (options: { filename: string }) => Promise<void>;
59
+ await capture({ filename: imagePath });
60
+ }
61
+
62
+ const bytes = await fs.readFile(imagePath);
63
+ if (bytes.length === 0 || bytes.length > 20 * 1024 * 1024) {
64
+ return { success: false, error: 'Captured image is empty or exceeds 20 MB' };
65
+ }
66
+
67
+ let ocrOutput = 'OCR was not available for this capture.';
68
+ try {
69
+ const ocr = await ensureCapability('ocr');
70
+ if (ocr.ok) {
71
+ const tesseract = await loadCapabilityPackage('tesseract.js') as {
72
+ createWorker(language: string): Promise<{
73
+ recognize(file: string): Promise<{ data?: { words?: OcrWord[] } }>;
74
+ terminate(): Promise<void>;
75
+ }>;
76
+ };
77
+ const worker = await tesseract.createWorker('eng');
78
+ try {
79
+ const recognized = await worker.recognize(imagePath);
80
+ const words = (recognized.data?.words ?? []).filter(word => word.confidence > 75).slice(0, 30);
81
+ ocrOutput = words.length > 0
82
+ ? words.map(word => `- [${word.text}] X:${Math.floor((word.bbox.x0 + word.bbox.x1) / 2)}, Y:${Math.floor((word.bbox.y0 + word.bbox.y1) / 2)}`).join('\n')
83
+ : 'No confident OCR text tokens detected.';
84
+ } finally {
85
+ await worker.terminate();
86
+ }
87
+ }
88
+ } catch (error: unknown) {
89
+ ocrOutput = `OCR unavailable: ${error instanceof Error ? error.message : String(error)}`;
90
+ }
91
+
92
+ return {
93
+ success: true,
94
+ _is_image_marker: true,
95
+ mimeType: 'image/png',
96
+ base64: bytes.toString('base64'),
97
+ filename: `${target} screenshot`,
98
+ output: `Capture prompt: ${args.prompt}\n${ocrOutput}`
99
+ };
100
+ } catch (error: unknown) {
101
+ const reason = error instanceof Error ? error.message : String(error);
102
+ const guidance = process.platform === 'darwin' && /could not create image from display/i.test(reason)
103
+ ? ' macOS could not capture the display. Check Screen Recording access for the terminal app and that a display session is available; then restart the terminal.'
104
+ : '';
105
+ return { success: false, error: `Live screen capture failed: ${reason}.${guidance}` };
106
+ } finally {
107
+ await fs.rm(tempDir, { recursive: true, force: true });
108
+ }
109
+ }
110
+ };
@@ -0,0 +1,152 @@
1
+ // Chatbox Clipboard Manager: surgical operations for copy, paste, and CRLF normalization.
2
+ // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
+ import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
4
+ /**
5
+ * Clean up text copied or pasted: normalize Windows CRLF and classic Mac CR to LF,
6
+ * remove null bytes and non-printable control characters while preserving valid newlines and tabs.
7
+ */
8
+ export function normalizeClipboardText(raw) {
9
+ if (typeof raw !== 'string')
10
+ return '';
11
+ return raw
12
+ .replace(/\r\n/g, '\n')
13
+ .replace(/\r/g, '\n')
14
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
15
+ }
16
+ /**
17
+ * Copy text to system clipboard and terminal emulator (via OSC 52).
18
+ */
19
+ export function copyToClipboard(text) {
20
+ if (typeof text !== 'string' || text.length === 0)
21
+ return false;
22
+ emitOsc52Copy(text);
23
+ return writeClipboardSync(text);
24
+ }
25
+ /**
26
+ * Copy the current text in the chatbox prompt editor to system clipboard.
27
+ */
28
+ export function copyChatboxInput(prompt) {
29
+ const text = prompt.editor.getText();
30
+ if (!text || !text.trim()) {
31
+ prompt.notice = 'input is empty (nothing to copy)';
32
+ prompt.scheduleDraw();
33
+ return { success: false, notice: prompt.notice, text: '' };
34
+ }
35
+ const copied = copyToClipboard(text);
36
+ if ('killRing' in prompt.editor) {
37
+ prompt.editor.killRing = text;
38
+ }
39
+ prompt.notice = copied ? 'copied input to clipboard' : 'copied input to kill-ring';
40
+ prompt.scheduleDraw();
41
+ return { success: true, notice: prompt.notice, text };
42
+ }
43
+ /**
44
+ * Paste clipboard content into the chatbox prompt editor.
45
+ */
46
+ 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
+ prompt.scheduleDraw();
52
+ return { success: false, notice: prompt.notice, text: '' };
53
+ }
54
+ prompt.editor.insert(text);
55
+ if (typeof prompt.refreshCompletion === 'function') {
56
+ prompt.refreshCompletion();
57
+ }
58
+ prompt.notice = 'pasted from clipboard';
59
+ prompt.scheduleDraw();
60
+ return { success: true, notice: prompt.notice, text };
61
+ }
62
+ /**
63
+ * Extract the content of the last assistant turn from the conversation.
64
+ */
65
+ export function extractLastAssistantTurn(loop) {
66
+ if (!loop || !Array.isArray(loop.messages) || loop.messages.length === 0)
67
+ return '';
68
+ for (let i = loop.messages.length - 1; i >= 0; i--) {
69
+ const msg = loop.messages[i];
70
+ if (msg && msg.role === 'assistant') {
71
+ if (typeof msg.content === 'string')
72
+ return msg.content;
73
+ if (Array.isArray(msg.content)) {
74
+ return msg.content
75
+ .map((part) => {
76
+ if (typeof part === 'string')
77
+ return part;
78
+ if (part && typeof part === 'object' && 'text' in part && typeof part.text === 'string') {
79
+ return part.text;
80
+ }
81
+ return '';
82
+ })
83
+ .filter(Boolean)
84
+ .join('\n');
85
+ }
86
+ }
87
+ }
88
+ return '';
89
+ }
90
+ /**
91
+ * Command implementation for /copy.
92
+ */
93
+ export function runCopyCommand(argv, ctx) {
94
+ const target = argv[0]?.toLowerCase();
95
+ if (target === 'last' || target === 'response' || target === 'assistant') {
96
+ const lastTurn = extractLastAssistantTurn(ctx.loop);
97
+ if (!lastTurn) {
98
+ return { ok: false, output: 'No assistant response found in this session to copy.' };
99
+ }
100
+ copyToClipboard(lastTurn);
101
+ if (ctx.prompt) {
102
+ ctx.prompt.notice = 'copied last assistant response to clipboard';
103
+ ctx.prompt.scheduleDraw();
104
+ }
105
+ return { ok: true, output: `Copied last assistant response (${lastTurn.length} characters) to clipboard.` };
106
+ }
107
+ if (target === 'input') {
108
+ if (!ctx.prompt || ctx.prompt.editor.isEmpty) {
109
+ return { ok: false, output: 'Chatbox input is currently empty.' };
110
+ }
111
+ const res = copyChatboxInput(ctx.prompt);
112
+ return { ok: res.success, output: 'Copied chatbox input to clipboard.' };
113
+ }
114
+ if (argv.length > 0) {
115
+ const customText = argv.join(' ');
116
+ copyToClipboard(customText);
117
+ if (ctx.prompt) {
118
+ ctx.prompt.notice = 'copied text to clipboard';
119
+ ctx.prompt.scheduleDraw();
120
+ }
121
+ return { ok: true, output: `Copied ${customText.length} characters to clipboard.` };
122
+ }
123
+ // Default: copy input if not empty, otherwise copy last assistant turn
124
+ if (ctx.prompt && !ctx.prompt.editor.isEmpty) {
125
+ const res = copyChatboxInput(ctx.prompt);
126
+ return { ok: res.success, output: res.success ? 'Copied chatbox input to clipboard.' : 'Failed to write to system clipboard.' };
127
+ }
128
+ const lastTurn = extractLastAssistantTurn(ctx.loop);
129
+ if (lastTurn) {
130
+ copyToClipboard(lastTurn);
131
+ if (ctx.prompt) {
132
+ ctx.prompt.notice = 'copied last assistant response to clipboard';
133
+ ctx.prompt.scheduleDraw();
134
+ }
135
+ return { ok: true, output: `Copied last assistant response (${lastTurn.length} characters) to clipboard.` };
136
+ }
137
+ return { ok: false, output: 'Nothing to copy. Chatbox input is empty and no previous responses exist.' };
138
+ }
139
+ /**
140
+ * Command implementation for /paste.
141
+ */
142
+ export function runPasteCommand(argv, ctx) {
143
+ if (!ctx.prompt) {
144
+ return { ok: false, output: 'The /paste command is only available in interactive chat mode.' };
145
+ }
146
+ const explicitText = argv.length > 0 ? argv.join(' ') : undefined;
147
+ const result = pasteIntoChatbox(ctx.prompt, explicitText);
148
+ if (!result.success) {
149
+ return { ok: false, output: 'Clipboard is empty or unavailable.' };
150
+ }
151
+ return { ok: true, output: `Pasted ${result.text.length} characters into chatbox input.` };
152
+ }
@@ -0,0 +1,201 @@
1
+ // Chatbox Clipboard Manager: surgical operations for copy, paste, and CRLF normalization.
2
+ // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
+
4
+ import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
5
+
6
+ export interface ChatboxEditor {
7
+ lines: string[][];
8
+ line: number;
9
+ col: number;
10
+ killRing?: string | undefined;
11
+ isEmpty: boolean;
12
+ getText(): string;
13
+ setText(text: string): void;
14
+ insert(text: string): void;
15
+ clear(): void;
16
+ }
17
+
18
+ export interface ChatboxPrompt {
19
+ editor: ChatboxEditor;
20
+ notice: string;
21
+ scheduleDraw(): void;
22
+ refreshCompletion?: (() => void) | undefined;
23
+ }
24
+
25
+ export interface ConversationMessage {
26
+ role: string;
27
+ content: unknown;
28
+ }
29
+
30
+ export interface ChatboxLoop {
31
+ messages?: ConversationMessage[] | undefined;
32
+ }
33
+
34
+ export interface ChatboxCommandContext {
35
+ prompt?: ChatboxPrompt | undefined;
36
+ loop?: ChatboxLoop | undefined;
37
+ surface?: string | undefined;
38
+ }
39
+
40
+ /**
41
+ * Clean up text copied or pasted: normalize Windows CRLF and classic Mac CR to LF,
42
+ * remove null bytes and non-printable control characters while preserving valid newlines and tabs.
43
+ */
44
+ export function normalizeClipboardText(raw: unknown): string {
45
+ if (typeof raw !== 'string') return '';
46
+ return raw
47
+ .replace(/\r\n/g, '\n')
48
+ .replace(/\r/g, '\n')
49
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
50
+ }
51
+
52
+ /**
53
+ * Copy text to system clipboard and terminal emulator (via OSC 52).
54
+ */
55
+ export function copyToClipboard(text: string): boolean {
56
+ if (typeof text !== 'string' || text.length === 0) return false;
57
+ emitOsc52Copy(text);
58
+ return writeClipboardSync(text);
59
+ }
60
+
61
+ /**
62
+ * Copy the current text in the chatbox prompt editor to system clipboard.
63
+ */
64
+ export function copyChatboxInput(prompt: ChatboxPrompt): { success: boolean; notice: string; text: string } {
65
+ const text = prompt.editor.getText();
66
+ if (!text || !text.trim()) {
67
+ prompt.notice = 'input is empty (nothing to copy)';
68
+ prompt.scheduleDraw();
69
+ return { success: false, notice: prompt.notice, text: '' };
70
+ }
71
+ const copied = copyToClipboard(text);
72
+ if ('killRing' in prompt.editor) {
73
+ prompt.editor.killRing = text;
74
+ }
75
+ prompt.notice = copied ? 'copied input to clipboard' : 'copied input to kill-ring';
76
+ prompt.scheduleDraw();
77
+ return { success: true, notice: prompt.notice, text };
78
+ }
79
+
80
+ /**
81
+ * Paste clipboard content into the chatbox prompt editor.
82
+ */
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';
88
+ prompt.scheduleDraw();
89
+ return { success: false, notice: prompt.notice, text: '' };
90
+ }
91
+ prompt.editor.insert(text);
92
+ if (typeof prompt.refreshCompletion === 'function') {
93
+ prompt.refreshCompletion();
94
+ }
95
+ prompt.notice = 'pasted from clipboard';
96
+ prompt.scheduleDraw();
97
+ return { success: true, notice: prompt.notice, text };
98
+ }
99
+
100
+ /**
101
+ * Extract the content of the last assistant turn from the conversation.
102
+ */
103
+ export function extractLastAssistantTurn(loop?: ChatboxLoop): string {
104
+ if (!loop || !Array.isArray(loop.messages) || loop.messages.length === 0) return '';
105
+ for (let i = loop.messages.length - 1; i >= 0; i--) {
106
+ const msg = loop.messages[i];
107
+ if (msg && msg.role === 'assistant') {
108
+ if (typeof msg.content === 'string') return msg.content;
109
+ if (Array.isArray(msg.content)) {
110
+ return msg.content
111
+ .map((part: unknown) => {
112
+ if (typeof part === 'string') return part;
113
+ if (part && typeof part === 'object' && 'text' in part && typeof (part as { text: unknown }).text === 'string') {
114
+ return (part as { text: string }).text;
115
+ }
116
+ return '';
117
+ })
118
+ .filter(Boolean)
119
+ .join('\n');
120
+ }
121
+ }
122
+ }
123
+ return '';
124
+ }
125
+
126
+ /**
127
+ * Command implementation for /copy.
128
+ */
129
+ export function runCopyCommand(
130
+ argv: string[],
131
+ ctx: ChatboxCommandContext
132
+ ): { ok: boolean; output: string } {
133
+ const target = argv[0]?.toLowerCase();
134
+
135
+ if (target === 'last' || target === 'response' || target === 'assistant') {
136
+ const lastTurn = extractLastAssistantTurn(ctx.loop);
137
+ if (!lastTurn) {
138
+ return { ok: false, output: 'No assistant response found in this session to copy.' };
139
+ }
140
+ copyToClipboard(lastTurn);
141
+ if (ctx.prompt) {
142
+ ctx.prompt.notice = 'copied last assistant response to clipboard';
143
+ ctx.prompt.scheduleDraw();
144
+ }
145
+ return { ok: true, output: `Copied last assistant response (${lastTurn.length} characters) to clipboard.` };
146
+ }
147
+
148
+ if (target === 'input') {
149
+ if (!ctx.prompt || ctx.prompt.editor.isEmpty) {
150
+ return { ok: false, output: 'Chatbox input is currently empty.' };
151
+ }
152
+ const res = copyChatboxInput(ctx.prompt);
153
+ return { ok: res.success, output: 'Copied chatbox input to clipboard.' };
154
+ }
155
+
156
+ if (argv.length > 0) {
157
+ const customText = argv.join(' ');
158
+ copyToClipboard(customText);
159
+ if (ctx.prompt) {
160
+ ctx.prompt.notice = 'copied text to clipboard';
161
+ ctx.prompt.scheduleDraw();
162
+ }
163
+ return { ok: true, output: `Copied ${customText.length} characters to clipboard.` };
164
+ }
165
+
166
+ // Default: copy input if not empty, otherwise copy last assistant turn
167
+ if (ctx.prompt && !ctx.prompt.editor.isEmpty) {
168
+ const res = copyChatboxInput(ctx.prompt);
169
+ return { ok: res.success, output: res.success ? 'Copied chatbox input to clipboard.' : 'Failed to write to system clipboard.' };
170
+ }
171
+
172
+ const lastTurn = extractLastAssistantTurn(ctx.loop);
173
+ if (lastTurn) {
174
+ copyToClipboard(lastTurn);
175
+ if (ctx.prompt) {
176
+ ctx.prompt.notice = 'copied last assistant response to clipboard';
177
+ ctx.prompt.scheduleDraw();
178
+ }
179
+ return { ok: true, output: `Copied last assistant response (${lastTurn.length} characters) to clipboard.` };
180
+ }
181
+
182
+ return { ok: false, output: 'Nothing to copy. Chatbox input is empty and no previous responses exist.' };
183
+ }
184
+
185
+ /**
186
+ * Command implementation for /paste.
187
+ */
188
+ export function runPasteCommand(
189
+ argv: string[],
190
+ ctx: ChatboxCommandContext
191
+ ): { ok: boolean; output: string } {
192
+ if (!ctx.prompt) {
193
+ return { ok: false, output: 'The /paste command is only available in interactive chat mode.' };
194
+ }
195
+ const explicitText = argv.length > 0 ? argv.join(' ') : undefined;
196
+ const result = pasteIntoChatbox(ctx.prompt, explicitText);
197
+ if (!result.success) {
198
+ return { ok: false, output: 'Clipboard is empty or unavailable.' };
199
+ }
200
+ return { ok: true, output: `Pasted ${result.text.length} characters into chatbox input.` };
201
+ }
@@ -1,6 +1,23 @@
1
1
  // Sovereign Synchronous Clipboard Reader for TUI prompts & modal dialogs.
2
- // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), and Linux (wl-paste, xclip).
2
+ // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), Linux (wl-paste, xclip, xsel),
3
+ // and terminal emulator OSC 52 escape sequences across SSH and local sessions.
3
4
  import { execFileSync, spawnSync } from 'node:child_process';
5
+ /**
6
+ * Emit OSC 52 escape sequence to synchronize terminal emulator clipboard.
7
+ * Allows copy/paste even across SSH sessions, tmux, and container boundaries.
8
+ */
9
+ export function emitOsc52Copy(text, stream = process.stdout) {
10
+ if (typeof text !== 'string' || text.length === 0 || Buffer.byteLength(text) > 100_000)
11
+ return false;
12
+ try {
13
+ const base64 = Buffer.from(text, 'utf8').toString('base64');
14
+ stream.write(`\x1b]52;c;${base64}\x07`);
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ }
4
21
  /**
5
22
  * Read system clipboard text synchronously without hanging or throwing.
6
23
  * Returns empty string if clipboard is empty, unavailable, or unsupported.
@@ -19,13 +36,21 @@ export function readClipboardSync() {
19
36
  }
20
37
  if (process.platform === 'linux') {
21
38
  try {
22
- return execFileSync('wl-paste', { encoding: 'utf8', timeout: 500 });
39
+ return execFileSync('wl-paste', ['--no-newline'], { encoding: 'utf8', timeout: 500 });
23
40
  }
24
41
  catch {
25
- return execFileSync('xclip', ['-selection', 'clipboard', '-o'], {
26
- encoding: 'utf8',
27
- timeout: 500
28
- });
42
+ try {
43
+ return execFileSync('xclip', ['-selection', 'clipboard', '-o'], {
44
+ encoding: 'utf8',
45
+ timeout: 500
46
+ });
47
+ }
48
+ catch {
49
+ return execFileSync('xsel', ['--clipboard', '--output'], {
50
+ encoding: 'utf8',
51
+ timeout: 500
52
+ });
53
+ }
29
54
  }
30
55
  }
31
56
  }
@@ -38,12 +63,18 @@ export function readClipboardSync() {
38
63
  export function writeClipboardSync(value) {
39
64
  if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value) > 4_000_000)
40
65
  return false;
66
+ // Emit OSC 52 to synchronize host terminal clipboard (local & SSH)
67
+ emitOsc52Copy(value);
41
68
  const candidates = process.platform === 'darwin'
42
69
  ? [['pbcopy', []]]
43
70
  : process.platform === 'win32'
44
71
  ? [['powershell.exe', ['-NoProfile', '-Command', 'Set-Clipboard -Value ([Console]::In.ReadToEnd())']]]
45
72
  : process.platform === 'linux'
46
- ? [['wl-copy', []], ['xclip', ['-selection', 'clipboard', '-i']]]
73
+ ? [
74
+ ['wl-copy', []],
75
+ ['xclip', ['-selection', 'clipboard', '-i']],
76
+ ['xsel', ['--clipboard', '--input']]
77
+ ]
47
78
  : [];
48
79
  for (const [command, args] of candidates) {
49
80
  try {
@@ -1,8 +1,24 @@
1
1
  // Sovereign Synchronous Clipboard Reader for TUI prompts & modal dialogs.
2
- // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), and Linux (wl-paste, xclip).
2
+ // Supports macOS (pbpaste), Windows (powershell Get-Clipboard), Linux (wl-paste, xclip, xsel),
3
+ // and terminal emulator OSC 52 escape sequences across SSH and local sessions.
3
4
 
4
5
  import { execFileSync, spawnSync } from 'node:child_process';
5
6
 
7
+ /**
8
+ * Emit OSC 52 escape sequence to synchronize terminal emulator clipboard.
9
+ * Allows copy/paste even across SSH sessions, tmux, and container boundaries.
10
+ */
11
+ export function emitOsc52Copy(text: string, stream: NodeJS.WritableStream = process.stdout): boolean {
12
+ if (typeof text !== 'string' || text.length === 0 || Buffer.byteLength(text) > 100_000) return false;
13
+ try {
14
+ const base64 = Buffer.from(text, 'utf8').toString('base64');
15
+ stream.write(`\x1b]52;c;${base64}\x07`);
16
+ return true;
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+
6
22
  /**
7
23
  * Read system clipboard text synchronously without hanging or throwing.
8
24
  * Returns empty string if clipboard is empty, unavailable, or unsupported.
@@ -21,12 +37,19 @@ export function readClipboardSync(): string {
21
37
  }
22
38
  if (process.platform === 'linux') {
23
39
  try {
24
- return execFileSync('wl-paste', { encoding: 'utf8', timeout: 500 });
40
+ return execFileSync('wl-paste', ['--no-newline'], { encoding: 'utf8', timeout: 500 });
25
41
  } catch {
26
- return execFileSync('xclip', ['-selection', 'clipboard', '-o'], {
27
- encoding: 'utf8',
28
- timeout: 500
29
- });
42
+ try {
43
+ return execFileSync('xclip', ['-selection', 'clipboard', '-o'], {
44
+ encoding: 'utf8',
45
+ timeout: 500
46
+ });
47
+ } catch {
48
+ return execFileSync('xsel', ['--clipboard', '--output'], {
49
+ encoding: 'utf8',
50
+ timeout: 500
51
+ });
52
+ }
30
53
  }
31
54
  }
32
55
  } catch {
@@ -38,12 +61,20 @@ export function readClipboardSync(): string {
38
61
  /** Write text through stdin, never through a shell or a command argument. */
39
62
  export function writeClipboardSync(value: string): boolean {
40
63
  if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value) > 4_000_000) return false;
64
+
65
+ // Emit OSC 52 to synchronize host terminal clipboard (local & SSH)
66
+ emitOsc52Copy(value);
67
+
41
68
  const candidates: Array<[string, string[]]> = process.platform === 'darwin'
42
69
  ? [['pbcopy', []]]
43
70
  : process.platform === 'win32'
44
71
  ? [['powershell.exe', ['-NoProfile', '-Command', 'Set-Clipboard -Value ([Console]::In.ReadToEnd())']]]
45
72
  : process.platform === 'linux'
46
- ? [['wl-copy', []], ['xclip', ['-selection', 'clipboard', '-i']]]
73
+ ? [
74
+ ['wl-copy', []],
75
+ ['xclip', ['-selection', 'clipboard', '-i']],
76
+ ['xsel', ['--clipboard', '--input']]
77
+ ]
47
78
  : [];
48
79
  for (const [command, args] of candidates) {
49
80
  try {
@@ -59,3 +90,4 @@ export function writeClipboardSync(value: string): boolean {
59
90
  }
60
91
  return false;
61
92
  }
93
+