aegisone 1.0.34 → 1.0.35

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -575
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,92 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Transcript checkpoints for /rewind. The session loop snapshots the
10
- * transcript after every exchange into ~/.aegiscode/checkpoints/<session>.jsonl
11
- * (bounded to the last CHECKPOINT_LIMIT), and /rewind lists or restores them.
12
- * Checkpoint 0 is the session start (empty transcript).
13
- *
14
- * Ported from the upstream engine reference (ESM → CommonJS). The data dir
15
- * now comes from config.js's shared `aegisDir()` helper.
16
- */
17
-
18
- const fs = require('node:fs');
19
- const path = require('node:path');
20
- const { aegisDir } = require('./config.js');
21
- const { ensurePrivateDir, writePrivateFile } = require('./securefs.js');
22
-
23
- const CHECKPOINT_LIMIT = 8;
24
-
25
- function checkpointsPath(sessionId) {
26
- return path.join(aegisDir(), 'checkpoints', `${sessionId}.jsonl`);
27
- }
28
-
29
- /**
30
- * Snapshot the current transcript. Returns the new checkpoint index.
31
- * Cheap: transcripts are small arrays of messages.
32
- */
33
- function snapshotCheckpoint(sessionId, transcript) {
34
- try {
35
- ensurePrivateDir(path.dirname(checkpointsPath(sessionId)));
36
- const entry = {
37
- ts: new Date().toISOString(),
38
- depth: transcript.length,
39
- words: transcript.reduce((a, m) => a + (m.text || '').split(/\s+/).length, 0),
40
- transcript,
41
- };
42
- const p = checkpointsPath(sessionId);
43
- const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
44
- const lines = [...prev, JSON.stringify(entry)];
45
- const trimmed = lines.slice(Math.max(0, lines.length - CHECKPOINT_LIMIT));
46
- // 0600: a checkpoint is the full transcript at a point in time.
47
- writePrivateFile(p, trimmed.join('\n') + '\n');
48
- return lines.length - 1; // index into the trimmed list
49
- } catch {
50
- return -1;
51
- }
52
- }
53
-
54
- /** Newest-first checkpoint list: [{ idx, ts, depth, words }]. */
55
- function listCheckpoints(sessionId) {
56
- try {
57
- const raw = fs.readFileSync(checkpointsPath(sessionId), 'utf8');
58
- return raw
59
- .split('\n')
60
- .filter(Boolean)
61
- .map((l, idx) => {
62
- try {
63
- const e = JSON.parse(l);
64
- return { idx, ts: e.ts, depth: e.depth || 0, words: e.words || 0 };
65
- } catch { return null; }
66
- })
67
- .filter(Boolean)
68
- .reverse();
69
- } catch {
70
- return [];
71
- }
72
- }
73
-
74
- /** Restore a checkpoint by its stored index. Returns the transcript or null. */
75
- function loadCheckpoint(sessionId, idx) {
76
- try {
77
- const raw = fs.readFileSync(checkpointsPath(sessionId), 'utf8').split('\n').filter(Boolean);
78
- const e = JSON.parse(raw[idx]);
79
- if (!e || !Array.isArray(e.transcript)) return null;
80
- return e.transcript;
81
- } catch {
82
- return null;
83
- }
84
- }
85
-
86
- module.exports = {
87
- CHECKPOINT_LIMIT,
88
- checkpointsPath,
89
- snapshotCheckpoint,
90
- listCheckpoints,
91
- loadCheckpoint,
92
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),CHECKPOINT_LIMIT=8;function checkpointsPath(t){return path.join(aegisDir(),"checkpoints",`${t}.jsonl`)}function snapshotCheckpoint(t,e){try{ensurePrivateDir(path.dirname(checkpointsPath(t)));const r={ts:(new Date).toISOString(),depth:e.length,words:e.reduce(((t,e)=>t+(e.text||"").split(/\s+/).length),0),transcript:e},n=checkpointsPath(t),i=[...fs.existsSync(n)?fs.readFileSync(n,"utf8").split("\n").filter(Boolean):[],JSON.stringify(r)],s=i.slice(Math.max(0,i.length-8));return writePrivateFile(n,s.join("\n")+"\n"),i.length-1}catch{return-1}}function listCheckpoints(t){try{return fs.readFileSync(checkpointsPath(t),"utf8").split("\n").filter(Boolean).map(((t,e)=>{try{const r=JSON.parse(t);return{idx:e,ts:r.ts,depth:r.depth||0,words:r.words||0}}catch{return null}})).filter(Boolean).reverse()}catch{return[]}}function loadCheckpoint(t,e){try{const r=fs.readFileSync(checkpointsPath(t),"utf8").split("\n").filter(Boolean),n=JSON.parse(r[e]);return n&&Array.isArray(n.transcript)?n.transcript:null}catch{return null}}module.exports={CHECKPOINT_LIMIT:8,checkpointsPath:checkpointsPath,snapshotCheckpoint:snapshotCheckpoint,listCheckpoints:listCheckpoints,loadCheckpoint:loadCheckpoint};
@@ -1,426 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Cross-platform clipboard access, both directions — the CLI's half of the
10
- * gesture the user actually performs: mark text, copy it, paste it back.
11
- *
12
- * WRITE (copy): a real clipboard tool first (pbcopy / clip.exe / wl-copy /
13
- * xclip / xsel), then **OSC 52** — the terminal's own "put this in the
14
- * clipboard" escape, which needs no binary at all and works over SSH and inside
15
- * tmux / screen — then a file in the data dir as the last resort. The CLI never
16
- * errors out over clipboard availability.
17
- *
18
- * The OSC 52 rung is what makes copy work on a host with no clipboard binary
19
- * installed. Measured on this host (`XDG_SESSION_TYPE=x11`, `DISPLAY=:0`, none
20
- * of wl-copy / xclip / xsel present): every marking drag ended in
21
- * "Marked N lines → ~/.aegiscode/clipboard.txt" — the text did NOT reach any
22
- * clipboard, the user had to go find a file. The upstream engine fixed exactly
23
- * this with the OSC 52 rung (`aegiscodex-dev/src/clipboard.js`); this module
24
- * had the tool ladder and the file fallback only.
25
- *
26
- * READ (paste): the same tools in reverse — pbpaste / Get-Clipboard / xclip -o
27
- * / wl-paste. Ctrl+V pastes an image from the clipboard (the file path lands in
28
- * the prompt) or, when the clipboard holds no image, its text. Without this the
29
- * CLI had NO clipboard paste at all: it only received what the terminal
30
- * bracketed-paste frame delivered, so Ctrl+V did nothing on every platform.
31
- *
32
- * Two host-specific details this module has to get right, both of them
33
- * previously wrong here:
34
- *
35
- * · **Windows has no mode bits.** The PATH hardening below (a directory is
36
- * trusted only when it is not group/world-writable and is owned by root or
37
- * by us) is a POSIX idea. `fs.statSync` on Windows reports 0o666-ish modes
38
- * for every file, so `mode & 0o022` was true for *everything* — every
39
- * candidate failed, `resolveTrustedTool()` returned null, and copy fell to
40
- * the file rung on every Windows host even with clip.exe present. The
41
- * ownership test is therefore skipped when `platform === 'win32'` (where the
42
- * real guarantee is that PATH is user-owned), and Windows resolution adds
43
- * the executable suffixes (`.exe`, `.cmd`, `.bat`) that a bare `clip` never
44
- * matches.
45
- * · **A tool that is not there is not a copy.** `via: 'file'` means the text
46
- * reached no clipboard; `describeCopy()` says so instead of claiming a copy.
47
- *
48
- * Ported from the upstream engine reference (ESM → CommonJS). The data dir
49
- * comes from the shared `aegisDir()` helper and the env vars are the CLI's own
50
- * (AEGISCODE_*), with AEGISCODE_TRUST_PATH=0 and AEGISCODE_NO_OSC52=1 as the
51
- * documented hatches.
52
- */
53
-
54
- const { spawnSync } = require('node:child_process');
55
- const fs = require('node:fs');
56
- const path = require('node:path');
57
- const { aegisDir } = require('./config.js');
58
- const { writePrivateFile } = require('./securefs.js');
59
-
60
- const ESC = '\u001b';
61
- const realPlatform = () => process.platform;
62
-
63
- // ── tool discovery ─────────────────────────────────────────────────────────
64
-
65
- /**
66
- * The clipboard tools this host could use, best-first.
67
- *
68
- * Platform gates first: pbcopy/pbpaste/pngpaste are macOS, clip.exe and
69
- * PowerShell are Windows, the rest are X11/Wayland. Then env fit: on Linux a
70
- * Wayland session lists wl-copy first and an X11 session lists xclip first, so
71
- * a Wayland terminal with XWayland present doesn't pay a spawn + 4s timeout
72
- * failing wl-copy. `platform` and `env` are injectable so every branch is
73
- * exercisable on this Linux host (the repo's Phase 30 rule: no platform branch
74
- * reachable only on the host it is written for).
75
- */
76
- function clipboardCandidates(kind, { platform = realPlatform(), env = process.env } = {}) {
77
- const isLinux = platform === 'linux';
78
- const isMac = platform === 'darwin';
79
- const isWin = platform === 'win32';
80
- const e = env || {};
81
- const hasWayland = !!e.WAYLAND_DISPLAY;
82
- const linuxWrite = hasWayland
83
- ? [
84
- { name: 'wl-copy', cmd: 'wl-copy', args: [], env: 'wayland' },
85
- { name: 'xclip', cmd: 'xclip', args: ['-selection', 'clipboard'], env: 'x11' },
86
- { name: 'xsel', cmd: 'xsel', args: ['--clipboard', '--input'], env: 'x11' },
87
- ]
88
- : [
89
- { name: 'xclip', cmd: 'xclip', args: ['-selection', 'clipboard'], env: 'x11' },
90
- { name: 'xsel', cmd: 'xsel', args: ['--clipboard', '--input'], env: 'x11' },
91
- { name: 'wl-copy', cmd: 'wl-copy', args: [], env: 'wayland' },
92
- ];
93
- if (kind === 'write') {
94
- return [
95
- isMac && { name: 'pbcopy', cmd: 'pbcopy', args: [], env: 'any' },
96
- isWin && { name: 'clip', cmd: 'clip', args: [], env: 'any' },
97
- ...(isLinux ? linuxWrite : []),
98
- ].filter(Boolean);
99
- }
100
- if (kind === 'text') {
101
- return [
102
- isMac && { name: 'pbpaste', cmd: 'pbpaste', args: [], env: 'any' },
103
- isWin && {
104
- name: 'powershell',
105
- cmd: 'powershell',
106
- args: ['-NoProfile', '-Command', 'Get-Clipboard'],
107
- env: 'any',
108
- winNewline: true,
109
- },
110
- ...(isLinux ? [
111
- { name: 'wl-paste', cmd: 'wl-paste', args: ['--no-newline'], env: 'wayland' },
112
- { name: 'xclip', cmd: 'xclip', args: ['-selection', 'clipboard', '-o'], env: 'x11' },
113
- { name: 'xsel', cmd: 'xsel', args: ['--clipboard', '--output'], env: 'x11' },
114
- ] : []),
115
- ].filter(Boolean);
116
- }
117
- // image
118
- return [
119
- isMac && { name: 'pngpaste', cmd: 'pngpaste', args: ['-'], env: 'any' },
120
- ...(isLinux ? [
121
- { name: 'wl-paste', cmd: 'wl-paste', args: ['--type', 'image/png'], env: 'wayland', mime: 'image/png' },
122
- { name: 'wl-paste', cmd: 'wl-paste', args: ['--type', 'image/jpeg'], env: 'wayland', mime: 'image/jpeg' },
123
- { name: 'xclip', cmd: 'xclip', args: ['-selection', 'clipboard', '-t', 'image/png', '-o'], env: 'x11', mime: 'image/png' },
124
- ] : []),
125
- ].filter(Boolean);
126
- }
127
-
128
- // ── PATH hardening (POSIX) and PATH resolution (Windows) ────────────────────
129
-
130
- /**
131
- * Is `dir` a directory a second local account could write into?
132
- *
133
- * A clipboard tool is handed the complete text of whatever the user copied —
134
- * which in this CLI is usually model output, sometimes containing code, paths,
135
- * or a secret the user was about to paste into a browser. `spawnSync('wl-copy',
136
- * …)` resolves that name against `$PATH`, so whoever owns an earlier PATH entry
137
- * than the real binary owns every byte the user copies: drop a `wl-copy` in a
138
- * group-writable `~/.local/bin`, or rely on `/tmp` or `.` being in PATH, and the
139
- * text arrives at the attacker instead of the clipboard.
140
- *
141
- * A directory is trusted only when it is not group- or world-writable AND is
142
- * owned by root or by us. `/tmp` fails on the first test; `~/bin` that the user
143
- * owns and left at 0755 passes.
144
- *
145
- * On Windows neither test means anything: `stat` reports mode bits that do not
146
- * describe the ACL, so `mode & 0o022` is true for every path and the check
147
- * rejected the whole PATH (every copy fell through to the file rung). There the
148
- * question "can a stranger swap this binary?" is answered by the ACL, not by
149
- * `stat`, and the file this CLI would run is `clip.exe` out of
150
- * `%SystemRoot%\system32` — so the ownership test is skipped and resolution is
151
- * limited to directories on PATH plus the executable suffixes, which is what
152
- * keeps `clip` from being confused with a `clip.cmd` sitting in the cwd.
153
- */
154
- function dirIsTrusted(dir, { platform = realPlatform() } = {}) {
155
- try {
156
- const st = fs.statSync(dir);
157
- if (!st.isDirectory()) return false;
158
- if (platform === 'win32') return true; // ACL-based; mode bits are not evidence
159
- if (st.mode & 0o022) return false;
160
- if (typeof process.getuid === 'function' && st.uid !== 0 && st.uid !== process.getuid()) return false;
161
- return true;
162
- } catch {
163
- return false;
164
- }
165
- }
166
-
167
- const WIN_EXTS = ['', '.exe', '.cmd', '.bat', '.com'];
168
-
169
- /**
170
- * Join a PATH entry and a file name the way the *entry* is spelled.
171
- *
172
- * `path.win32.join('C:\\Windows', 'clip.exe')` is what Windows needs, but a
173
- * win32-style join applied to a POSIX-style entry produces
174
- * `\\tmp\\x\\clip.exe`, which no filesystem resolves — and the whole point of
175
- * taking `platform` as an option is that the win32 branch is exercisable on
176
- * this Linux host with a real temp directory. Windows accepts both separators,
177
- * so choosing by the entry's own spelling is correct on both sides.
178
- */
179
- function joinFor(dir, name, isWin) {
180
- if (!isWin) return path.join(dir, name);
181
- const winStyle = /\\/.test(dir) || /^[A-Za-z]:/.test(dir);
182
- return winStyle ? path.win32.join(dir, name) : path.join(dir, name);
183
- }
184
-
185
- /**
186
- * Resolve `cmd` to an absolute path we are willing to execute, or null.
187
- *
188
- * Replaces the old `sh -c 'command -v <cmd>'` availability probe: that check
189
- * answered "is this name on PATH?" when the question that matters is "is the
190
- * binary PATH would pick one I trust?". Answering the second subsumes the
191
- * first, and does it without a shell in the loop.
192
- *
193
- * Every candidate must survive: a PATH entry that is absolute, trusted, and not
194
- * the empty string or `.` (both of which mean the current directory); a real
195
- * file that is executable (POSIX), not group/world-writable, and owned by root
196
- * or us; and a realpath whose own directory is trusted too, so a link in a good
197
- * directory cannot redirect execution into a bad one. On Windows the mode/owner
198
- * tests are skipped (see `dirIsTrusted`) and each executable suffix is tried,
199
- * because a bare `clip` is `clip.exe` on disk.
200
- */
201
- function resolveTrustedTool(cmd, { platform = realPlatform(), env = process.env } = {}) {
202
- const e = env || {};
203
- const trustPath = e.AEGISCODE_TRUST_PATH !== '0';
204
- const isWin = platform === 'win32';
205
- const p = isWin ? path.win32 : path;
206
- const entries = String((e.PATH != null ? e.PATH : process.env.PATH) || '').split(isWin ? ';' : path.delimiter);
207
- // AEGISCODE_TRUST_PATH=0 restores the old "whatever PATH resolves" behaviour
208
- // for a user whose tool legitimately lives in a group-writable prefix (an
209
- // unusual but real layout: a Nix/Guix profile, a CI image). Secure by
210
- // default; the hatch is documented in the module header rather than being the
211
- // default. It stays on for Windows, where the checks are ACL-based and
212
- // `dirIsTrusted` has nothing to verify anyway.
213
- const harden = trustPath || isWin;
214
- for (const raw of entries) {
215
- const dir = String(raw).trim().replace(/^"|"$/g, '');
216
- if (!dir) continue;
217
- if (!isWin && !p.isAbsolute(dir)) continue; // '' and '.' mean "the cwd"
218
- if (harden && !dirIsTrusted(dir, { platform })) continue;
219
-
220
- for (const ext of isWin ? WIN_EXTS : ['']) {
221
- const full = joinFor(dir, cmd + ext, isWin);
222
- let real;
223
- try {
224
- real = fs.realpathSync(full); // throws on ENOENT and on a symlink loop
225
- } catch {
226
- continue;
227
- }
228
- let st;
229
- try {
230
- st = fs.statSync(real);
231
- } catch {
232
- continue;
233
- }
234
- if (!st.isFile()) continue;
235
- if (!isWin) {
236
- if (!(st.mode & 0o111)) continue; // not executable — always required
237
- if (harden) {
238
- if (st.mode & 0o022) continue; // group/world-writable binary
239
- if (typeof process.getuid === 'function' && st.uid !== 0 && st.uid !== process.getuid()) continue;
240
- if (!dirIsTrusted(path.dirname(real), { platform })) continue; // the realpath may leave `dir`
241
- }
242
- }
243
- return real;
244
- }
245
- }
246
- return null;
247
- }
248
-
249
- // ── OSC 52 — the terminal's own clipboard ──────────────────────────────────
250
- // "ESC ] 52 ; c ; <base64> BEL" sets the system clipboard. Inside tmux or
251
- // screen the sequence has to be wrapped in a DCS passthrough or the
252
- // multiplexer eats it (tmux forwards it with `set-clipboard` at its default).
253
- // The inner ESC bytes are doubled for tmux, per its docs.
254
- const base64 = (s) => Buffer.from(String(s), 'utf8').toString('base64');
255
- /** Terminals that refuse OSC 52 for size need chunks, but the payloads a
256
- * marking produces are small; a fixed cap keeps a giant copy from wedging the
257
- * terminal, and the file rung already covers that case. */
258
- const OSC52_MAX = 100_000;
259
-
260
- function osc52Sequence(text, env = process.env) {
261
- const body = `${ESC}]52;c;${base64(text)}\u0007`;
262
- const e = env || {};
263
- if (e.TMUX) return `${ESC}Ptmux;${ESC}${body.split(ESC).join(ESC + ESC)}${ESC}\\`;
264
- if (e.STY) return `${ESC}P${body}${ESC}\\`;
265
- return body;
266
- }
267
-
268
- /**
269
- * Send `text` to the terminal's clipboard. Only meaningful on a TTY — with
270
- * stdout redirected there is no terminal to hand it to, and the bytes would
271
- * land in the redirected file (which is why `isTTY` is part of the contract and
272
- * why the tests inject a stub stream). Returns true when the sequence was
273
- * written.
274
- */
275
- function writeOsc52(text, { stdout = process.stdout, env = process.env } = {}) {
276
- const e = env || {};
277
- if (e.AEGISCODE_NO_OSC52 === '1') return false;
278
- if (!stdout || !stdout.isTTY || typeof stdout.write !== 'function') return false;
279
- const payload = String(text);
280
- if (!payload || payload.length > OSC52_MAX) return false;
281
- try {
282
- stdout.write(osc52Sequence(payload, e));
283
- return true;
284
- } catch {
285
- return false;
286
- }
287
- }
288
-
289
- // ── copy ───────────────────────────────────────────────────────────────────
290
-
291
- /**
292
- * Copy text to the system clipboard.
293
- * Returns { ok, via, path? } — via is 'tool:<name>', 'osc52:<where>' or 'file'.
294
- * `via: 'file'` means the text did NOT reach any clipboard: the caller is
295
- * expected to say so and hand over the path, not to claim a copy.
296
- */
297
- function copyToClipboard(text, opts = {}) {
298
- const {
299
- stdout = process.stdout,
300
- env = process.env,
301
- platform = realPlatform(),
302
- spawn = spawnSync,
303
- } = opts;
304
- const e = env || {};
305
- const forced = e.AEGISCODE_NO_CLIPBOARD === '1';
306
- if (!forced) {
307
- for (const t of clipboardCandidates('write', { platform, env: e })) {
308
- const exe = resolveTrustedTool(t.cmd, { platform, env: e });
309
- if (!exe) continue; // not installed, or installed somewhere untrusted
310
- const r = spawn(exe, t.args, { input: String(text), encoding: 'utf8', timeout: 4000, windowsHide: true });
311
- if (!r.error && r.status === 0) return { ok: true, via: `tool:${t.name}` };
312
- }
313
- if (writeOsc52(text, { stdout, env: e })) {
314
- const where = e.TMUX ? 'tmux' : e.STY ? 'screen' : 'terminal';
315
- return { ok: true, via: `osc52:${where}` };
316
- }
317
- }
318
- // Fallback: write to the data dir and report the path. 0600 + O_NOFOLLOW via
319
- // securefs — this file holds whatever the user last marked, and neither the
320
- // mode nor a planted symlink may let it double as a way to read or overwrite
321
- // something else.
322
- try {
323
- const p = path.join(aegisDir(), 'clipboard.txt');
324
- writePrivateFile(p, String(text), { atomic: false });
325
- return { ok: true, via: 'file', path: p };
326
- } catch {
327
- return { ok: false, via: 'none' };
328
- }
329
- }
330
-
331
- /** Human sentence for a copy result — one place, so every caller matches. */
332
- function describeCopy(res, subject = 'Copied') {
333
- if (!res || !res.ok) return 'Clipboard unavailable; nothing copied.';
334
- if (res.via === 'file') {
335
- // Not a copy: nothing reached any clipboard, so the sentence must not say
336
- // it did — it names the file the text actually went to instead.
337
- return `${subject} — no clipboard tool on this host; the text is in ${res.path}`;
338
- }
339
- const [kind, detail] = String(res.via).split(':');
340
- if (kind === 'osc52') {
341
- return detail === 'terminal'
342
- ? `${subject} to the clipboard via the terminal.`
343
- : `${subject} to the clipboard (through ${detail}).`;
344
- }
345
- return `${subject} to the clipboard (${detail}).`;
346
- }
347
-
348
- // ── read (paste) ───────────────────────────────────────────────────────────
349
-
350
- const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
351
- const JPEG_MAGIC = Buffer.from([0xff, 0xd8, 0xff]);
352
-
353
- /** Sniff a Buffer's image type from its magic bytes, or null when not an image. */
354
- function sniffImage(buf) {
355
- if (!buf || buf.length < 8) return null;
356
- if (buf.subarray(0, 8).equals(PNG_MAGIC)) return 'image/png';
357
- if (buf.subarray(0, 3).equals(JPEG_MAGIC)) return 'image/jpeg';
358
- return null;
359
- }
360
-
361
- /**
362
- * Read the clipboard's text, if any tool can. Returns { ok, text, via, error? }
363
- * — `ok:false` means no tool answered, never "the clipboard was empty" (an
364
- * empty clipboard returns ok:true and text:''). The caller's message differs for
365
- * the two, which is the whole reason the distinction is in the return value.
366
- */
367
- function readClipboardText(opts = {}) {
368
- const { env = process.env, platform = realPlatform(), spawn = spawnSync } = opts;
369
- const e = env || {};
370
- if (e.AEGISCODE_NO_CLIPBOARD === '1') return { ok: false, via: 'none', error: 'clipboard disabled' };
371
- for (const t of clipboardCandidates('text', { platform, env: e })) {
372
- const exe = resolveTrustedTool(t.cmd, { platform, env: e });
373
- if (!exe) continue;
374
- const r = spawn(exe, t.args, { encoding: 'utf8', timeout: 4000, maxBuffer: 16 * 1024 * 1024, windowsHide: true });
375
- if (r.error || r.status !== 0 || r.stdout == null) continue;
376
- // PowerShell's Get-Clipboard appends its own CRLF per line.
377
- const text = t.winNewline
378
- ? String(r.stdout).replace(/\r\n/g, '\n').replace(/\n$/, '')
379
- : String(r.stdout);
380
- return { ok: true, text, via: `tool:${t.name}` };
381
- }
382
- return { ok: false, via: 'none', error: 'no clipboard reader available' };
383
- }
384
-
385
- /**
386
- * Read an image off the clipboard. Returns { ok, data (Buffer), mime, via,
387
- * error? }. The bytes are magic-checked: a tool that answers with text (an
388
- * empty selection, a type the clipboard does not carry) is not an image, and
389
- * the caller must not write it out as one.
390
- */
391
- function readClipboardImage(opts = {}) {
392
- const { env = process.env, platform = realPlatform(), spawn = spawnSync } = opts;
393
- const e = env || {};
394
- if (e.AEGISCODE_NO_CLIPBOARD === '1') return { ok: false, via: 'none', error: 'clipboard disabled' };
395
- for (const t of clipboardCandidates('image', { platform, env: e })) {
396
- const exe = resolveTrustedTool(t.cmd, { platform, env: e });
397
- if (!exe) continue;
398
- const r = spawn(exe, t.args, { timeout: 5000, maxBuffer: 64 * 1024 * 1024, windowsHide: true });
399
- if (r.error || r.status !== 0 || !r.stdout) continue;
400
- const data = Buffer.isBuffer(r.stdout) ? r.stdout : Buffer.from(String(r.stdout), 'utf8');
401
- const mime = sniffImage(data);
402
- if (mime) return { ok: true, data, mime, via: `tool:${t.name}` };
403
- }
404
- return { ok: false, via: 'none', error: 'no image on the clipboard' };
405
- }
406
-
407
- /** Which clipboard facilities this host actually has — for honest UI hints. */
408
- function clipboardCapabilities({ platform = realPlatform(), env = process.env } = {}) {
409
- const any = (kind) =>
410
- clipboardCandidates(kind, { platform, env }).some((t) => !!resolveTrustedTool(t.cmd, { platform, env }));
411
- return { canWrite: any('write'), canReadText: any('text'), canReadImage: any('image') };
412
- }
413
-
414
- module.exports = {
415
- copyToClipboard,
416
- describeCopy,
417
- readClipboardText,
418
- readClipboardImage,
419
- sniffImage,
420
- clipboardCandidates,
421
- clipboardCapabilities,
422
- osc52Sequence,
423
- writeOsc52,
424
- resolveTrustedTool,
425
- dirIsTrusted,
426
- };
3
+ "use strict";const{spawnSync:spawnSync}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),ESC="",realPlatform=()=>process.platform;function clipboardCandidates(e,{platform:t=realPlatform(),env:r=process.env}={}){const n="linux"===t,o="darwin"===t,i="win32"===t,a=!!(r||{}).WAYLAND_DISPLAY;return"write"===e?[o&&{name:"pbcopy",cmd:"pbcopy",args:[],env:"any"},i&&{name:"clip",cmd:"clip",args:[],env:"any"},...n?a?[{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"}]:[{name:"xclip",cmd:"xclip",args:["-selection","clipboard"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--input"],env:"x11"},{name:"wl-copy",cmd:"wl-copy",args:[],env:"wayland"}]:[]].filter(Boolean):"text"===e?[o&&{name:"pbpaste",cmd:"pbpaste",args:[],env:"any"},i&&{name:"powershell",cmd:"powershell",args:["-NoProfile","-Command","Get-Clipboard"],env:"any",winNewline:!0},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--no-newline"],env:"wayland"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-o"],env:"x11"},{name:"xsel",cmd:"xsel",args:["--clipboard","--output"],env:"x11"}]:[]].filter(Boolean):[o&&{name:"pngpaste",cmd:"pngpaste",args:["-"],env:"any"},...n?[{name:"wl-paste",cmd:"wl-paste",args:["--type","image/png"],env:"wayland",mime:"image/png"},{name:"wl-paste",cmd:"wl-paste",args:["--type","image/jpeg"],env:"wayland",mime:"image/jpeg"},{name:"xclip",cmd:"xclip",args:["-selection","clipboard","-t","image/png","-o"],env:"x11",mime:"image/png"}]:[]].filter(Boolean)}function dirIsTrusted(e,{platform:t=realPlatform()}={}){try{const r=fs.statSync(e);return!(!r.isDirectory()||"win32"!==t&&(18&r.mode||"function"==typeof process.getuid&&0!==r.uid&&r.uid!==process.getuid()))}catch{return!1}}const WIN_EXTS=["",".exe",".cmd",".bat",".com"];function joinFor(e,t,r){return r&&(/\\/.test(e)||/^[A-Za-z]:/.test(e))?path.win32.join(e,t):path.join(e,t)}function resolveTrustedTool(e,{platform:t=realPlatform(),env:r=process.env}={}){const n=r||{},o="0"!==n.AEGISCODE_TRUST_PATH,i="win32"===t,a=i?path.win32:path,s=String((null!=n.PATH?n.PATH:process.env.PATH)||"").split(i?";":path.delimiter),c=o||i;for(const r of s){const n=String(r).trim().replace(/^"|"$/g,"");if(n&&(i||a.isAbsolute(n))&&(!c||dirIsTrusted(n,{platform:t})))for(const r of i?WIN_EXTS:[""]){const o=joinFor(n,e+r,i);let a,s;try{a=fs.realpathSync(o)}catch{continue}try{s=fs.statSync(a)}catch{continue}if(s.isFile()){if(!i){if(!(73&s.mode))continue;if(c){if(18&s.mode)continue;if("function"==typeof process.getuid&&0!==s.uid&&s.uid!==process.getuid())continue;if(!dirIsTrusted(path.dirname(a),{platform:t}))continue}}return a}}}return null}const base64=e=>Buffer.from(String(e),"utf8").toString("base64"),OSC52_MAX=1e5;function osc52Sequence(e,t=process.env){const r=`${ESC}]52;c;${base64(e)}`,n=t||{};return n.TMUX?`${ESC}Ptmux;${ESC}${r.split(ESC).join(ESC+ESC)}${ESC}\\`:n.STY?`${ESC}P${r}${ESC}\\`:r}function writeOsc52(e,{stdout:t=process.stdout,env:r=process.env}={}){const n=r||{};if("1"===n.AEGISCODE_NO_OSC52)return!1;if(!t||!t.isTTY||"function"!=typeof t.write)return!1;const o=String(e);if(!o||o.length>OSC52_MAX)return!1;try{return t.write(osc52Sequence(o,n)),!0}catch{return!1}}function copyToClipboard(e,t={}){const{stdout:r=process.stdout,env:n=process.env,platform:o=realPlatform(),spawn:i=spawnSync}=t,a=n||{};if("1"!==a.AEGISCODE_NO_CLIPBOARD){for(const t of clipboardCandidates("write",{platform:o,env:a})){const r=resolveTrustedTool(t.cmd,{platform:o,env:a});if(!r)continue;const n=i(r,t.args,{input:String(e),encoding:"utf8",timeout:4e3,windowsHide:!0});if(!n.error&&0===n.status)return{ok:!0,via:`tool:${t.name}`}}if(writeOsc52(e,{stdout:r,env:a}))return{ok:!0,via:"osc52:"+(a.TMUX?"tmux":a.STY?"screen":"terminal")}}try{const t=path.join(aegisDir(),"clipboard.txt");return writePrivateFile(t,String(e),{atomic:!1}),{ok:!0,via:"file",path:t}}catch{return{ok:!1,via:"none"}}}function describeCopy(e,t="Copied"){if(!e||!e.ok)return"Clipboard unavailable; nothing copied.";if("file"===e.via)return`${t} — no clipboard tool on this host; the text is in ${e.path}`;const[r,n]=String(e.via).split(":");return"osc52"===r?"terminal"===n?`${t} to the clipboard via the terminal.`:`${t} to the clipboard (through ${n}).`:`${t} to the clipboard (${n}).`}const PNG_MAGIC=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_MAGIC=Buffer.from([255,216,255]);function sniffImage(e){return!e||e.length<8?null:e.subarray(0,8).equals(PNG_MAGIC)?"image/png":e.subarray(0,3).equals(JPEG_MAGIC)?"image/jpeg":null}function readClipboardText(e={}){const{env:t=process.env,platform:r=realPlatform(),spawn:n=spawnSync}=e,o=t||{};if("1"===o.AEGISCODE_NO_CLIPBOARD)return{ok:!1,via:"none",error:"clipboard disabled"};for(const e of clipboardCandidates("text",{platform:r,env:o})){const t=resolveTrustedTool(e.cmd,{platform:r,env:o});if(!t)continue;const i=n(t,e.args,{encoding:"utf8",timeout:4e3,maxBuffer:16777216,windowsHide:!0});if(!i.error&&0===i.status&&null!=i.stdout)return{ok:!0,text:e.winNewline?String(i.stdout).replace(/\r\n/g,"\n").replace(/\n$/,""):String(i.stdout),via:`tool:${e.name}`}}return{ok:!1,via:"none",error:"no clipboard reader available"}}function readClipboardImage(e={}){const{env:t=process.env,platform:r=realPlatform(),spawn:n=spawnSync}=e,o=t||{};if("1"===o.AEGISCODE_NO_CLIPBOARD)return{ok:!1,via:"none",error:"clipboard disabled"};for(const e of clipboardCandidates("image",{platform:r,env:o})){const t=resolveTrustedTool(e.cmd,{platform:r,env:o});if(!t)continue;const i=n(t,e.args,{timeout:5e3,maxBuffer:67108864,windowsHide:!0});if(i.error||0!==i.status||!i.stdout)continue;const a=Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(String(i.stdout),"utf8"),s=sniffImage(a);if(s)return{ok:!0,data:a,mime:s,via:`tool:${e.name}`}}return{ok:!1,via:"none",error:"no image on the clipboard"}}function clipboardCapabilities({platform:e=realPlatform(),env:t=process.env}={}){const r=r=>clipboardCandidates(r,{platform:e,env:t}).some((r=>!!resolveTrustedTool(r.cmd,{platform:e,env:t})));return{canWrite:r("write"),canReadText:r("text"),canReadImage:r("image")}}module.exports={copyToClipboard:copyToClipboard,describeCopy:describeCopy,readClipboardText:readClipboardText,readClipboardImage:readClipboardImage,sniffImage:sniffImage,clipboardCandidates:clipboardCandidates,clipboardCapabilities:clipboardCapabilities,osc52Sequence:osc52Sequence,writeOsc52:writeOsc52,resolveTrustedTool:resolveTrustedTool,dirIsTrusted:dirIsTrusted};