@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -0,0 +1,567 @@
1
+ import { stat as fsStat } from 'node:fs/promises';
2
+
3
+ import { debug } from '$shared/utils/logger';
4
+
5
+ /**
6
+ * OS clipboard bridge for file copy/cut (Windows, macOS, Linux).
7
+ *
8
+ * Clopen is a web app (Bun backend + Svelte frontend in the browser), so the
9
+ * frontend's internal clipboard can never surface as real files in the native
10
+ * file manager — browsers have no access to CF_HDROP, NSPasteboard, or the
11
+ * X11/Wayland file-drop targets. But the Bun backend runs on the same machine
12
+ * in local usage, so it can place real file/folder paths onto the OS
13
+ * clipboard. After that the user opens the native file manager and pastes —
14
+ * the file manager performs the copy itself, so names, contents, extensions
15
+ * and folder structure arrive intact and the sources in Clopen are never
16
+ * modified by Clopen.
17
+ *
18
+ * The reverse direction (file manager → Clopen) works through
19
+ * `readOsClipboardFilePaths()` below: the backend reads the native file-drop
20
+ * list and the frontend duplicates those entries into the chosen destination
21
+ * with COPY semantics, so the file-manager sources are never moved or
22
+ * deleted. Browsers cannot read a native file-drop list on a context-menu
23
+ * click (no DataTransfer), which is why this backend round-trip exists —
24
+ * Ctrl+V/⌘V keeps using the `paste` event fast path in the frontend.
25
+ *
26
+ * Both directions are HOST-MACHINE operations: they read and write the
27
+ * clipboard of the machine the server runs on, not the viewer's. The WS
28
+ * routes therefore restrict them to admins (see `backend/ws/files/clipboard.ts`).
29
+ */
30
+
31
+ export const OS_CLIPBOARD_ENV_VAR = 'CLOPEN_OS_CLIP_PATHS_B64';
32
+
33
+ /**
34
+ * OLE drop effects (OLEIDL.H): COPY = 1, MOVE = 2.
35
+ * NOTE: these were once swapped here (COPY published as 2), which made
36
+ * Windows File Explorer MOVE the files on paste and delete the Clopen
37
+ * sources — even though the user did a COPY. COPY must always be 1 so the
38
+ * sources survive the paste; only CUT publishes 2.
39
+ */
40
+ const DROP_EFFECT_COPY = 1;
41
+ const DROP_EFFECT_MOVE = 2;
42
+
43
+ export type OsClipboardEffect = 'copy' | 'move';
44
+
45
+ /** Command timeout for every clipboard helper process. */
46
+ const CLIPBOARD_COMMAND_TIMEOUT_MS = 15_000;
47
+
48
+ /**
49
+ * Whether this platform can publish file references to the native clipboard.
50
+ * The frontend uses the thrown "not supported" error to fall back to the
51
+ * in-app clipboard silently, so keep this in sync with the branches in
52
+ * {@link copyPathsToOsClipboard}.
53
+ */
54
+ export function osClipboardWriteSupported(): boolean {
55
+ return process.platform === 'win32' || process.platform === 'darwin' || process.platform === 'linux';
56
+ }
57
+
58
+ /**
59
+ * Build the PowerShell script that reads the path list from
60
+ * `CLOPEN_OS_CLIP_PATHS_B64` and publishes it as a FileDropList with an
61
+ * explicit drop effect (COPY by default). The payload travels via an
62
+ * environment variable (base64 JSON) rather than command-line interpolation,
63
+ * so paths with spaces, quotes or `&` cannot break out of the PowerShell
64
+ * command. Exported (pure, no side effects) for unit tests.
65
+ */
66
+ export function buildOsClipboardPsScript(effect: OsClipboardEffect = 'copy'): string {
67
+ const dropEffect = effect === 'move' ? DROP_EFFECT_MOVE : DROP_EFFECT_COPY;
68
+ return [
69
+ '$ErrorActionPreference = \'Stop\'',
70
+ 'Add-Type -AssemblyName System.Windows.Forms',
71
+ `$json = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($env:${OS_CLIPBOARD_ENV_VAR}))`,
72
+ '$paths = $json | ConvertFrom-Json',
73
+ '$coll = New-Object Collections.Specialized.StringCollection',
74
+ 'foreach ($p in $paths) { [void]$coll.Add([string]$p) }',
75
+ '$data = New-Object Windows.Forms.DataObject',
76
+ '$data.SetFileDropList($coll)',
77
+ '$ms = New-Object IO.MemoryStream(4)',
78
+ `$ms.Write([BitConverter]::GetBytes(${dropEffect}), 0, 4)`,
79
+ // Rewind: the shell reads the stream from its current position, so a
80
+ // stream left at the end would arrive as an empty/unknown effect and
81
+ // Explorer could fall back to MOVE semantics.
82
+ '[void]$ms.Seek(0, \'Begin\')',
83
+ '$data.SetData(\'Preferred DropEffect\', $ms)',
84
+ '[Windows.Forms.Clipboard]::SetDataObject($data, $true)'
85
+ ].join('\r\n');
86
+ }
87
+
88
+ /** Classic multi-file pasteboard type; still what Finder itself publishes. */
89
+ const MAC_FILENAMES_PBOARD_TYPE = 'NSFilenamesPboardType';
90
+
91
+ /**
92
+ * Build the AppleScript (ASObjC) program that publishes file paths onto the
93
+ * macOS general pasteboard. Paths arrive as `argv`, and Bun spawns osascript
94
+ * without a shell, so no quoting or escaping applies to them.
95
+ *
96
+ * macOS has no clipboard equivalent of DROPEFFECT_MOVE: Finder decides
97
+ * copy-vs-move at paste time (⌘V copies, ⌘⌥V moves). A CUT therefore
98
+ * publishes the same entries as a COPY and the caller reports the actual
99
+ * published effect — see {@link copyPathsToOsClipboard}.
100
+ *
101
+ * Two details here are load-bearing for MULTI-FILE copies, and getting either
102
+ * wrong drops entries silently rather than failing:
103
+ *
104
+ * 1. `setPropertyList:forType:` writes the whole list as concrete data.
105
+ * `writeObjects:` instead hands the pasteboard server one lazily-provided
106
+ * item per URL; osascript exits before those are all pulled, so the number
107
+ * of entries that actually land is a race — the same four paths arrived as
108
+ * 1, 3 or 4 items across identical runs. `NSFilenamesPboardType` still
109
+ * yields `public.file-url` and the rest of the modern type set, so readers
110
+ * that only understand file URLs are unaffected.
111
+ * 2. The script reads the list back before exiting. Even an eager write is
112
+ * not guaranteed to be visible to other processes the instant the writer
113
+ * dies, and confirming it is what makes the result deterministic.
114
+ *
115
+ * Exported (pure, no side effects) for unit tests.
116
+ */
117
+ export function buildMacClipboardWriteScriptLines(): string[] {
118
+ return [
119
+ 'use framework "AppKit"',
120
+ 'use scripting additions',
121
+ 'on run argv',
122
+ 'set paths to {}',
123
+ 'repeat with p in argv',
124
+ 'set end of paths to (p as text)',
125
+ 'end repeat',
126
+ "set pb to current application's NSPasteboard's generalPasteboard()",
127
+ "pb's clearContents()",
128
+ `pb's declareTypes:{"${MAC_FILENAMES_PBOARD_TYPE}"} owner:(missing value)`,
129
+ `pb's setPropertyList:paths forType:"${MAC_FILENAMES_PBOARD_TYPE}"`,
130
+ 'repeat 50 times',
131
+ `set written to (pb's propertyListForType:"${MAC_FILENAMES_PBOARD_TYPE}")`,
132
+ 'if written is not missing value then',
133
+ "if ((written's |count|()) as integer) is (count of paths) then exit repeat",
134
+ 'end if',
135
+ 'delay 0.02',
136
+ 'end repeat',
137
+ 'end run'
138
+ ];
139
+ }
140
+
141
+ /**
142
+ * Encode a local path as a `file://` URI for the X11/Wayland clipboard
143
+ * targets. Each segment is percent-encoded separately so separators survive.
144
+ * Exported for unit tests.
145
+ */
146
+ export function pathToFileUri(path: string): string {
147
+ return `file://${path.split('/').map(encodeURIComponent).join('/')}`;
148
+ }
149
+
150
+ /**
151
+ * Build the `x-special/gnome-copied-files` payload understood by Nautilus,
152
+ * Nemo, Caja and (recent) Dolphin: an action line followed by one `file://`
153
+ * URI per line. This target is the only widely-supported way to express
154
+ * copy-vs-cut on Linux — plain `text/uri-list` always pastes as a copy.
155
+ * Exported (pure) for unit tests.
156
+ */
157
+ export function buildGnomeCopiedFilesPayload(paths: string[], effect: OsClipboardEffect = 'copy'): string {
158
+ const action = effect === 'move' ? 'cut' : 'copy';
159
+ return [action, ...paths.map(pathToFileUri)].join('\n');
160
+ }
161
+
162
+ const GNOME_COPIED_FILES_TARGET = 'x-special/gnome-copied-files';
163
+
164
+ /**
165
+ * Encode absolute paths for transport via `CLOPEN_OS_CLIP_PATHS_B64`.
166
+ * UTF-16LE matches the PowerShell `[Unicode]::GetString` decoding above.
167
+ * Exported for unit tests.
168
+ */
169
+ export function encodeOsClipboardPayload(paths: string[]): string {
170
+ return Buffer.from(JSON.stringify(paths), 'utf16le').toString('base64');
171
+ }
172
+
173
+ /** Decode helper used by tests to round-trip the payload encoding. */
174
+ export function decodeOsClipboardPayload(payload: string): string[] {
175
+ return JSON.parse(Buffer.from(payload, 'base64').toString('utf16le')) as string[];
176
+ }
177
+
178
+ interface CommandResult {
179
+ stdout: string;
180
+ stderr: string;
181
+ exitCode: number;
182
+ }
183
+
184
+ interface CommandOptions {
185
+ timeoutMs?: number;
186
+ env?: Record<string, string>;
187
+ }
188
+
189
+ /**
190
+ * Run a short-lived helper and collect its output. Only safe for processes
191
+ * that exit on their own — see {@link runClipboardOwner} for the forking
192
+ * selection-owner case.
193
+ */
194
+ async function runCommand(cmd: string, args: string[], options: CommandOptions = {}): Promise<CommandResult> {
195
+ const proc = Bun.spawn([cmd, ...args], {
196
+ stdout: 'pipe',
197
+ stderr: 'pipe',
198
+ stdin: 'ignore',
199
+ env: options.env ? { ...process.env, ...options.env } : undefined
200
+ });
201
+ const timer = setTimeout(() => {
202
+ try {
203
+ proc.kill();
204
+ } catch {
205
+ // Already exited.
206
+ }
207
+ }, options.timeoutMs ?? CLIPBOARD_COMMAND_TIMEOUT_MS);
208
+ try {
209
+ const [stdout, stderr, exitCode] = await Promise.all([
210
+ new Response(proc.stdout).text(),
211
+ new Response(proc.stderr).text(),
212
+ proc.exited
213
+ ]);
214
+ return { stdout, stderr, exitCode };
215
+ } finally {
216
+ clearTimeout(timer);
217
+ }
218
+ }
219
+
220
+ /** Wayland sessions expose `wl-copy`/`wl-paste`; X11 sessions use `xclip`. */
221
+ function preferWayland(): boolean {
222
+ return !!process.env.WAYLAND_DISPLAY;
223
+ }
224
+
225
+ /**
226
+ * Run a clipboard-owning helper (`xclip` / `wl-copy`) and wait for it to hand
227
+ * the selection off.
228
+ *
229
+ * These tools fork a background process that keeps serving the selection
230
+ * until another app claims it; the process we spawn exits immediately after.
231
+ * Their stdio must therefore be IGNORED rather than piped: the forked child
232
+ * inherits the pipes and never closes them, so draining stdout/stderr would
233
+ * block until the timeout even though the copy itself already succeeded.
234
+ * That costs us the helper's error text, which is why failures fall back to a
235
+ * generic message.
236
+ */
237
+ async function runClipboardOwner(cmd: string, args: string[], payload: string): Promise<number> {
238
+ const proc = Bun.spawn([cmd, ...args], {
239
+ stdin: new TextEncoder().encode(payload),
240
+ stdout: 'ignore',
241
+ stderr: 'ignore'
242
+ });
243
+ const timer = setTimeout(() => {
244
+ try {
245
+ proc.kill();
246
+ } catch {
247
+ // Already exited.
248
+ }
249
+ }, CLIPBOARD_COMMAND_TIMEOUT_MS);
250
+ try {
251
+ return await proc.exited;
252
+ } finally {
253
+ clearTimeout(timer);
254
+ }
255
+ }
256
+
257
+ async function writeLinuxClipboard(paths: string[], effect: OsClipboardEffect): Promise<void> {
258
+ const payload = buildGnomeCopiedFilesPayload(paths, effect);
259
+ const wlCopy = preferWayland() ? Bun.which('wl-copy') : null;
260
+ if (wlCopy) {
261
+ const exitCode = await runClipboardOwner(wlCopy, ['--type', GNOME_COPIED_FILES_TARGET], payload);
262
+ if (exitCode !== 0) {
263
+ throw new Error(`wl-copy exited with code ${exitCode}`);
264
+ }
265
+ return;
266
+ }
267
+ const xclip = Bun.which('xclip');
268
+ if (!xclip) {
269
+ throw new Error('Copying to the system clipboard needs xclip (X11) or wl-clipboard (Wayland)');
270
+ }
271
+ const exitCode = await runClipboardOwner(
272
+ xclip,
273
+ ['-selection', 'clipboard', '-t', GNOME_COPIED_FILES_TARGET, '-i'],
274
+ payload
275
+ );
276
+ if (exitCode !== 0) {
277
+ throw new Error(`xclip exited with code ${exitCode}`);
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Place existing files/folders onto the native clipboard as a file-drop list.
283
+ * `copy` (default) pastes duplicates and keeps the sources; `move` lets the
284
+ * file manager relocate them (used for CUT). Clopen itself never deletes the
285
+ * sources — the file manager performs the move.
286
+ *
287
+ * Returns the effect that was ACTUALLY published, which can differ from the
288
+ * requested one: macOS cannot express "move" on the pasteboard (Finder picks
289
+ * copy-vs-move at paste time), so a CUT publishes as `copy` there and the
290
+ * caller words its confirmation accordingly.
291
+ *
292
+ * Throws on unsupported effects, unsupported platforms, missing paths, or a
293
+ * failing helper process.
294
+ */
295
+ export async function copyPathsToOsClipboard(
296
+ paths: string[],
297
+ effect: OsClipboardEffect = 'copy'
298
+ ): Promise<{ count: number; effect: OsClipboardEffect }> {
299
+ if (effect !== 'copy' && effect !== 'move') {
300
+ throw new Error(`Unknown clipboard effect: ${String(effect)}`);
301
+ }
302
+ if (!osClipboardWriteSupported()) {
303
+ throw new Error('Copy to the system clipboard is not supported on this platform');
304
+ }
305
+ if (paths.length === 0) {
306
+ throw new Error('At least one path is required');
307
+ }
308
+ for (const p of paths) {
309
+ try {
310
+ await fsStat(p);
311
+ } catch {
312
+ throw new Error(`Path does not exist: ${p}`);
313
+ }
314
+ }
315
+
316
+ debug.log('file', 'Copy to OS clipboard:', { count: paths.length, effect, platform: process.platform });
317
+
318
+ if (process.platform === 'win32') {
319
+ const psPath = Bun.which('powershell.exe') ?? 'powershell.exe';
320
+ const { stdout, stderr, exitCode } = await runCommand(
321
+ psPath,
322
+ ['-NoProfile', '-NonInteractive', '-STA', '-Command', buildOsClipboardPsScript(effect)],
323
+ { env: { [OS_CLIPBOARD_ENV_VAR]: encodeOsClipboardPayload(paths) } }
324
+ );
325
+ if (exitCode !== 0) {
326
+ debug.error('file', 'Copy to OS clipboard failed:', { exitCode, stderr: stderr.trim(), stdout: stdout.trim() });
327
+ throw new Error(stderr.trim() || 'Failed to copy to the Windows clipboard');
328
+ }
329
+ return { count: paths.length, effect };
330
+ }
331
+
332
+ if (process.platform === 'darwin') {
333
+ const osaPath = Bun.which('osascript') ?? 'osascript';
334
+ const args: string[] = [];
335
+ for (const line of buildMacClipboardWriteScriptLines()) {
336
+ args.push('-e', line);
337
+ }
338
+ // Paths are argv, never interpolated into the script source.
339
+ const { stdout, stderr, exitCode } = await runCommand(osaPath, [...args, ...paths]);
340
+ if (exitCode !== 0) {
341
+ debug.error('file', 'Copy to Finder clipboard failed:', { exitCode, stderr: stderr.trim(), stdout: stdout.trim() });
342
+ throw new Error(stderr.trim() || 'Failed to copy to the Finder clipboard');
343
+ }
344
+ // Finder decides copy-vs-move at paste time, so a CUT lands as a copy.
345
+ return { count: paths.length, effect: 'copy' };
346
+ }
347
+
348
+ await writeLinuxClipboard(paths, effect);
349
+ return { count: paths.length, effect };
350
+ }
351
+
352
+ export interface OsClipboardItem {
353
+ path: string;
354
+ isDirectory: boolean;
355
+ }
356
+
357
+ /** Maximum entries read from the OS clipboard in one call (abuse guard). */
358
+ const OS_CLIPBOARD_READ_LIMIT = 200;
359
+
360
+ /**
361
+ * Split raw line-based command output into non-empty trimmed paths.
362
+ * Pure (no side effects) for unit tests.
363
+ */
364
+ export function parseFileDropLines(output: string): string[] {
365
+ return output
366
+ .split(/\r?\n/)
367
+ .map((line) => line.trim())
368
+ .filter((line) => line.length > 0);
369
+ }
370
+
371
+ /**
372
+ * Parse an X11/Wayland `text/uri-list` payload (`file://` URIs, `#` comments,
373
+ * percent-encoding) into local paths. Pure for unit tests.
374
+ */
375
+ export function parseTextUriList(output: string): string[] {
376
+ const out: string[] = [];
377
+ for (const raw of output.split(/\r?\n/)) {
378
+ const line = raw.trim();
379
+ if (!line || line.startsWith('#')) continue;
380
+ let rest = line;
381
+ if (rest.startsWith('file://')) {
382
+ rest = rest.slice('file://'.length);
383
+ // Strip a `host` segment (`file://host/path`); keep unix sockets
384
+ // style `file:///path` (empty host) intact.
385
+ if (!rest.startsWith('/') && rest.includes('/')) {
386
+ rest = rest.slice(rest.indexOf('/'));
387
+ }
388
+ }
389
+ try {
390
+ rest = decodeURIComponent(rest);
391
+ } catch {
392
+ // Keep the raw form rather than dropping the entry.
393
+ }
394
+ if (rest) out.push(rest);
395
+ }
396
+ return out;
397
+ }
398
+
399
+ /**
400
+ * Parse an `x-special/gnome-copied-files` payload: the first line is the
401
+ * action (`copy` / `cut`) and the rest are `file://` URIs. The action is
402
+ * dropped on purpose — Clopen always duplicates, never moves, the
403
+ * file-manager sources. Pure for unit tests.
404
+ */
405
+ export function parseGnomeCopiedFiles(output: string): string[] {
406
+ const lines = output.split(/\r?\n/);
407
+ const first = lines[0]?.trim();
408
+ const body = first === 'copy' || first === 'cut' ? lines.slice(1) : lines;
409
+ return parseTextUriList(body.join('\n'));
410
+ }
411
+
412
+ /**
413
+ * Build the PowerShell script that prints the native clipboard FileDropList,
414
+ * one absolute path per line (empty output = no files on the clipboard).
415
+ * Exported (pure, no side effects) for unit tests. Clipboard access needs an
416
+ * STA thread, so callers must spawn PowerShell with `-STA` (same as the
417
+ * write path above).
418
+ */
419
+ export function buildOsClipboardReadPsScript(): string {
420
+ return [
421
+ '$ErrorActionPreference = \'Stop\'',
422
+ 'Add-Type -AssemblyName System.Windows.Forms',
423
+ '$files = [Windows.Forms.Clipboard]::GetFileDropList()',
424
+ 'if ($null -ne $files) { foreach ($f in $files) { Write-Output $f } }'
425
+ ].join('\r\n');
426
+ }
427
+
428
+ /**
429
+ * Build the AppleScript (ASObjC) program that prints Finder-copied file paths
430
+ * (one POSIX path per line) from the general pasteboard.
431
+ *
432
+ * Two things here are load-bearing and were each a runtime failure before:
433
+ * `if … then` must open a block on its own line (a one-line
434
+ * `if … then repeat …` is a syntax error), and the file-URL restriction has
435
+ * to be an `isFileURL()` test rather than a `readObjectsForClasses:options:`
436
+ * dictionary — the ASObjC bridge cannot resolve the option-key constant and
437
+ * fails with "Can't continue". `log` writes to stderr, so callers must scan
438
+ * BOTH stdout and stderr. Exported for unit tests.
439
+ */
440
+ export function buildMacClipboardReadScriptLines(): string[] {
441
+ return [
442
+ 'use framework "AppKit"',
443
+ "set pb to current application's NSPasteboard's generalPasteboard()",
444
+ "set urls to (pb's readObjectsForClasses:{current application's NSURL} options:(missing value))",
445
+ 'if urls is not missing value then',
446
+ 'repeat with u in urls',
447
+ "if (u's isFileURL()) as boolean then log ((u's |path|) as text)",
448
+ 'end repeat',
449
+ 'end if'
450
+ ];
451
+ }
452
+
453
+ async function statClipboardPaths(paths: string[]): Promise<OsClipboardItem[]> {
454
+ const items: OsClipboardItem[] = [];
455
+ for (const p of paths.slice(0, OS_CLIPBOARD_READ_LIMIT)) {
456
+ try {
457
+ const st = await fsStat(p);
458
+ if (st.isFile() || st.isDirectory()) {
459
+ items.push({ path: p, isDirectory: st.isDirectory() });
460
+ }
461
+ } catch {
462
+ // Vanished between copy and paste — skip silently.
463
+ }
464
+ }
465
+ return items;
466
+ }
467
+
468
+ /** Wayland read leg: `wl-paste` with the richer GNOME target first. */
469
+ async function readWaylandClipboard(wlPaste: string): Promise<string[] | null> {
470
+ const types = await runCommand(wlPaste, ['--list-types'], { timeoutMs: 10_000 });
471
+ if (types.exitCode !== 0) return null;
472
+ if (types.stdout.includes(GNOME_COPIED_FILES_TARGET)) {
473
+ const res = await runCommand(wlPaste, ['--no-newline', '--type', GNOME_COPIED_FILES_TARGET], { timeoutMs: 10_000 });
474
+ if (res.exitCode === 0) return parseGnomeCopiedFiles(res.stdout);
475
+ }
476
+ if (types.stdout.includes('text/uri-list')) {
477
+ const res = await runCommand(wlPaste, ['--no-newline', '--type', 'text/uri-list'], { timeoutMs: 10_000 });
478
+ if (res.exitCode === 0) return parseTextUriList(res.stdout);
479
+ }
480
+ return [];
481
+ }
482
+
483
+ /** X11 read leg: `xclip`, same target preference as the Wayland leg. */
484
+ async function readX11Clipboard(xclip: string): Promise<string[]> {
485
+ const targets = await runCommand(xclip, ['-selection', 'clipboard', '-t', 'TARGETS', '-o'], { timeoutMs: 10_000 });
486
+ if (targets.exitCode !== 0) return [];
487
+ if (targets.stdout.includes(GNOME_COPIED_FILES_TARGET)) {
488
+ const res = await runCommand(xclip, ['-selection', 'clipboard', '-t', GNOME_COPIED_FILES_TARGET, '-o'], {
489
+ timeoutMs: 10_000
490
+ });
491
+ if (res.exitCode === 0) return parseGnomeCopiedFiles(res.stdout);
492
+ }
493
+ if (targets.stdout.includes('text/uri-list')) {
494
+ const res = await runCommand(xclip, ['-selection', 'clipboard', '-t', 'text/uri-list', '-o'], { timeoutMs: 10_000 });
495
+ if (res.exitCode === 0) return parseTextUriList(res.stdout);
496
+ }
497
+ return [];
498
+ }
499
+
500
+ /**
501
+ * Read file/folder entries from the native OS clipboard (File Explorer,
502
+ * Finder, or a Linux file manager copy).
503
+ *
504
+ * - Windows: PowerShell FileDropList (same mechanism family as the write
505
+ * path; requires `-STA`).
506
+ * - macOS: AppKit pasteboard file URLs via osascript.
507
+ * - Linux: `wl-paste` on Wayland, `xclip` on X11 (best-effort; a session with
508
+ * neither helper installed reports unsupported).
509
+ *
510
+ * Returns `[]` when the clipboard holds no files (text or images only).
511
+ * Always COPY semantics downstream — callers must duplicate, never move,
512
+ * so the file-manager sources are never modified or deleted.
513
+ */
514
+ export async function readOsClipboardFilePaths(): Promise<OsClipboardItem[]> {
515
+ if (process.platform === 'win32') {
516
+ const psPath = Bun.which('powershell.exe') ?? 'powershell.exe';
517
+ const { stdout, stderr, exitCode } = await runCommand(psPath, [
518
+ '-NoProfile',
519
+ '-NonInteractive',
520
+ '-STA',
521
+ '-Command',
522
+ buildOsClipboardReadPsScript()
523
+ ]);
524
+ if (exitCode !== 0) {
525
+ debug.error('file', 'Read OS clipboard failed:', { exitCode, stderr: stderr.trim() });
526
+ throw new Error(stderr.trim() || 'Failed to read the Windows clipboard');
527
+ }
528
+ return await statClipboardPaths(parseFileDropLines(stdout));
529
+ }
530
+
531
+ if (process.platform === 'darwin') {
532
+ const osaPath = Bun.which('osascript') ?? 'osascript';
533
+ const args: string[] = [];
534
+ for (const line of buildMacClipboardReadScriptLines()) {
535
+ args.push('-e', line);
536
+ }
537
+ try {
538
+ const { stdout, stderr, exitCode } = await runCommand(osaPath, args);
539
+ if (exitCode !== 0) {
540
+ throw new Error((stderr || stdout).trim() || 'osascript failed');
541
+ }
542
+ // `log` writes to stderr; a future osascript could use stdout.
543
+ const candidates = parseFileDropLines(`${stdout}\n${stderr}`).filter((p) => p.startsWith('/'));
544
+ return await statClipboardPaths(candidates);
545
+ } catch (error) {
546
+ debug.error('file', 'Read Finder clipboard failed:', error);
547
+ throw new Error('Reading the Finder clipboard is not available on this Mac');
548
+ }
549
+ }
550
+
551
+ // Linux (Wayland first, then X11 — both best-effort).
552
+ try {
553
+ const wlPaste = preferWayland() ? Bun.which('wl-paste') : null;
554
+ if (wlPaste) {
555
+ const paths = await readWaylandClipboard(wlPaste);
556
+ if (paths !== null) return await statClipboardPaths(paths);
557
+ }
558
+ const xclip = Bun.which('xclip');
559
+ if (!xclip) {
560
+ throw new Error('Reading the system clipboard needs xclip (X11) or wl-clipboard (Wayland)');
561
+ }
562
+ return await statClipboardPaths(await readX11Clipboard(xclip));
563
+ } catch (error) {
564
+ debug.error('file', 'Read Linux clipboard failed:', error);
565
+ throw new Error('Reading the system clipboard is not supported on this Linux session');
566
+ }
567
+ }