@reason-machines/cli-linux-x64 0.2.419 → 0.2.420
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.
- package/THIRD_PARTY_NOTICES.txt +8 -7
- package/bin/reason +2 -2
- package/bin/runtime/srt/sandbox-runtime.mjs +52 -52
- package/bin/vm-hands/api-18d75dfn.js +2 -0
- package/bin/vm-hands/api-credentials-3vhge1ap.js +2 -0
- package/bin/vm-hands/connect-cli-s5smpb2n.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-17t4efc4.js +2 -0
- package/bin/vm-hands/desktop-account-6sjrxy69.js +2 -0
- package/bin/vm-hands/device-workspace-s50q53sz.js +2 -0
- package/bin/vm-hands/fsevents-p3d8kd0p.js +2 -0
- package/bin/vm-hands/hands-worker-source-kddz4y15.js +2 -0
- package/bin/vm-hands/index-wrw65904.js +12818 -0
- package/bin/vm-hands/install-receipt-ysa70fvh.js +2 -0
- package/bin/vm-hands/local-automation-3amth2kd.js +2 -0
- package/bin/vm-hands/local-capabilities-hgmepv53.js +2 -0
- package/bin/vm-hands/local-desktop-users-cppjjr81.js +2 -0
- package/bin/vm-hands/local-display-mac-0qz3b627.js +2 -0
- package/bin/vm-hands/local-display-session-e4n5hx0v.js +2 -0
- package/bin/vm-hands/local-display-video-28gmymr4.js +2 -0
- package/bin/vm-hands/local-managed-process-2313kw42.js +2 -0
- package/bin/vm-hands/local-pty-session-rpk05ap5.js +2 -0
- package/bin/vm-hands/managed-runtime-3z71qd28.js +2 -0
- package/bin/vm-hands/network-contract-trkxqc0w.js +2 -0
- package/bin/vm-hands/package-xqbhdf15.js +2 -0
- package/bin/vm-hands/permissions-9yn6rcvc.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-xn3ddz70.js +2 -0
- package/bin/vm-hands/serve-service-s57v1tq2.js +2 -0
- package/bin/vm-hands/status-grxd9vg7.js +10 -0
- package/bin/vm-hands/version-bqwnackx.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-004yshd1.js +452 -0
- package/bin/vm-hands/vm-hands-entry-lite-1xwxazmz.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-agsp101y.js → vm-hands-entry-lite-21qpxvt8.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-2n4n9cs8.js +126 -0
- package/bin/vm-hands/vm-hands-entry-lite-2rd6t7ry.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-37kgczw8.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-3krzmhkk.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-4vgwtn85.js +52 -0
- package/bin/vm-hands/vm-hands-entry-lite-4vks5phw.js +42 -0
- package/bin/vm-hands/vm-hands-entry-lite-50zbqwkv.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-5dtfehjv.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-60pg3wxj.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-6b0dxpkm.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-6c67a3jc.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-8r31b0ps.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-aj139v8j.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-avc65bd7.js +65 -0
- package/bin/vm-hands/{vm-hands-entry-lite-vsa7t6m9.js → vm-hands-entry-lite-beyyy1gz.js} +54 -54
- package/bin/vm-hands/vm-hands-entry-lite-bx5zy5bd.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-fzkfajew.js → vm-hands-entry-lite-cbrtaz8j.js} +5 -9
- package/bin/vm-hands/vm-hands-entry-lite-dk79tnax.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-ec9jemny.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-ev1k9x73.js +539 -0
- package/bin/vm-hands/vm-hands-entry-lite-f2qkz14f.js +128 -0
- package/bin/vm-hands/vm-hands-entry-lite-fbhqfzbq.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-4k4h9rcq.js → vm-hands-entry-lite-fcvf8md1.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-g4zd2d5n.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-hbs3tpdg.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-hk6trmwa.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-hqmyd73s.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-jev771b3.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-jzz73e3f.js +112 -0
- package/bin/vm-hands/vm-hands-entry-lite-m2bswqxe.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-np07qyeq.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-nzmkyezg.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-pf5qtbj5.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-qy9xg6em.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-6y6pz2yw.js → vm-hands-entry-lite-rfz60hb3.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-s4bharcb.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-s5qkb1fk.js +6 -0
- package/bin/vm-hands/vm-hands-entry-lite-sbtjmy0e.js +14 -0
- package/bin/vm-hands/vm-hands-entry-lite-tdgtpx8e.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-vpz54vwj.js +7 -0
- package/bin/vm-hands/vm-hands-entry-lite-wx4ax7wg.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-z76nfb19.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-zjxzm61j.js +105 -0
- package/bin/vm-hands/vm-hands-entry-lite-zp6naptr.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite.js +3 -1
- package/bin/vm-hands/vm-hands-executor-p92kw8nz.js +11 -0
- package/bin/vm-hands/vm-hands-op-runner-ekgtqc07.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-tj93a1pm.js +4 -0
- package/bin/vm-hands/worker-preview-readiness-w62n91kr.js +2 -0
- package/bin/vm-hands/worker-sandbox-2r5nseff.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-s4897qxy.js +0 -2
- package/bin/vm-hands/api-m73x3da5.js +0 -2
- package/bin/vm-hands/ask-relay-4kwcx2b7.js +0 -8
- package/bin/vm-hands/connect-cli-34b18gjs.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-j012b4bd.js +0 -2
- package/bin/vm-hands/desktop-account-0q0arpzk.js +0 -2
- package/bin/vm-hands/device-workspace-3jxhs54b.js +0 -2
- package/bin/vm-hands/hands-worker-source-y64axsw3.js +0 -2
- package/bin/vm-hands/index-194s4vz0.js +0 -12818
- package/bin/vm-hands/install-receipt-1g68b446.js +0 -2
- package/bin/vm-hands/local-automation-k2w46hn2.js +0 -2
- package/bin/vm-hands/local-capabilities-tdzbqmrb.js +0 -2
- package/bin/vm-hands/local-desktop-users-6thzvydd.js +0 -2
- package/bin/vm-hands/local-display-mac-59ma7sxa.js +0 -2
- package/bin/vm-hands/local-display-session-4833qq7h.js +0 -2
- package/bin/vm-hands/local-display-video-c1143mz6.js +0 -2
- package/bin/vm-hands/local-managed-process-mr0zpk7c.js +0 -2
- package/bin/vm-hands/local-pty-session-bwarwpsd.js +0 -2
- package/bin/vm-hands/managed-runtime-vz1wqwwg.js +0 -2
- package/bin/vm-hands/network-contract-gprc37sw.js +0 -2
- package/bin/vm-hands/package-ej9snd47.js +0 -2
- package/bin/vm-hands/permissions-7sfghef4.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-jsrkawe2.js +0 -2
- package/bin/vm-hands/serve-service-kngyzh74.js +0 -2
- package/bin/vm-hands/status-jz29fb95.js +0 -96
- package/bin/vm-hands/version-g29vt13t.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-0h4qmgm2.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-0k13wmzm.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-1exfjv79.js +0 -52
- package/bin/vm-hands/vm-hands-entry-lite-26q3hbdc.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-28s7v15d.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-2m5dwrdf.js +0 -6
- package/bin/vm-hands/vm-hands-entry-lite-37hvds7z.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-3rqdzqhk.js +0 -112
- package/bin/vm-hands/vm-hands-entry-lite-4gh5kfr4.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-6nwbqg37.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-714wspqb.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-7zk0r3p9.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-9qep7pka.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-am6kj1n1.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-as1tkffn.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-bxt4n1nj.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-c2g3wmkp.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-d2w8tghq.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-d98m00b8.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-daxcxjze.js +0 -344
- package/bin/vm-hands/vm-hands-entry-lite-dcnyve97.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-e1b89x66.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ej5ffjck.js +0 -105
- package/bin/vm-hands/vm-hands-entry-lite-ejkba2nk.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-f3wh0dza.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-f5xb489y.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-feybcq63.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-fpp2bs9y.js +0 -452
- package/bin/vm-hands/vm-hands-entry-lite-gt497d5x.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-gxper06w.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-j2ng164q.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-jp9q2vsx.js +0 -127
- package/bin/vm-hands/vm-hands-entry-lite-magmzx9c.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ntx8fdyq.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-pfzczmaa.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-pkc4ry5x.js +0 -539
- package/bin/vm-hands/vm-hands-entry-lite-pp7jfqzr.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-q8wkrzer.js +0 -66
- package/bin/vm-hands/vm-hands-entry-lite-s823n1q9.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-s9xf5z69.js +0 -7
- package/bin/vm-hands/vm-hands-entry-lite-tchc7z17.js +0 -128
- package/bin/vm-hands/vm-hands-entry-lite-tytfs183.js +0 -42
- package/bin/vm-hands/vm-hands-entry-lite-v4jtxgaj.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-vgpt2n1v.js +0 -11
- package/bin/vm-hands/vm-hands-entry-lite-xp3qzxk5.js +0 -3
- package/bin/vm-hands/vm-hands-executor-epyhpjv3.js +0 -11
- package/bin/vm-hands/vm-hands-op-runner-fn1qph82.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-8vt9etvv.js +0 -4
- package/bin/vm-hands/worker-preview-readiness-yfjgban2.js +0 -2
- package/bin/vm-hands/worker-sandbox-z0t69av8.js +0 -2
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Gn,Ao,Jt}from"./vm-hands-entry-lite-jzz73e3f.js";import{Pn,Ve,ao,Tn,Rn,On,Pr,x}from"./vm-hands-entry-lite-2n4n9cs8.js";import{kt}from"./vm-hands-entry-lite-fbhqfzbq.js";import{Ir}from"./vm-hands-entry-lite-nzmkyezg.js";import{j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as Y,spawn as z}from"child_process";import{randomBytes as Te}from"crypto";import{chmodSync as he,existsSync as H,lstatSync as Qe,mkdirSync as _e,readFileSync as De,rmSync as I,writeFileSync as C}from"fs";import{connect as we}from"net";import{join as y}from"path";var P=32,w=76;var W="./desktop-wallpaper-0pjhgyfk.jpg";var B="./dock-browser-afp005mt.png";var O="./dock-files-rywdm96b.png";var F="./dock-terminal-s41cj1jp.png";var k=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
|
+
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
|
+
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
|
+
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
6
|
+
import ctypes, sys
|
|
7
|
+
import gi
|
|
8
|
+
gi.require_version("GdkPixbuf", "2.0")
|
|
9
|
+
from gi.repository import GdkPixbuf
|
|
10
|
+
x = ctypes.cdll.LoadLibrary("libX11.so.6")
|
|
11
|
+
x.XOpenDisplay.restype = ctypes.c_void_p
|
|
12
|
+
x.XOpenDisplay.argtypes = [ctypes.c_char_p]
|
|
13
|
+
d = x.XOpenDisplay(None)
|
|
14
|
+
if not d: sys.exit("no display")
|
|
15
|
+
for name, res, args in [
|
|
16
|
+
("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
|
|
17
|
+
("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
|
|
18
|
+
("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
19
|
+
("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
20
|
+
("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
21
|
+
("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
|
|
22
|
+
("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
|
|
23
|
+
("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
|
|
24
|
+
("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
|
|
25
|
+
("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
|
|
26
|
+
("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
|
|
27
|
+
("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
|
|
28
|
+
("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
|
|
29
|
+
("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
|
|
30
|
+
("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
31
|
+
("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
|
|
32
|
+
]:
|
|
33
|
+
f = getattr(x, name); f.restype = res; f.argtypes = args
|
|
34
|
+
s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
|
|
35
|
+
w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
|
|
36
|
+
if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
|
|
37
|
+
# Scale to cover the screen, then crop the centre.
|
|
38
|
+
src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
|
|
39
|
+
k = max(w / src.get_width(), h / src.get_height())
|
|
40
|
+
sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
|
|
41
|
+
pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
|
|
42
|
+
if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
|
|
43
|
+
rgb, stride = pb.get_pixels(), pb.get_rowstride()
|
|
44
|
+
bgrx = bytearray(w * h * 4)
|
|
45
|
+
for y in range(h):
|
|
46
|
+
row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
|
|
47
|
+
bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
|
|
48
|
+
buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
|
|
49
|
+
pix = x.XCreatePixmap(d, root, w, h, 24)
|
|
50
|
+
img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
|
|
51
|
+
x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
|
|
52
|
+
ref = ctypes.c_ulong(pix)
|
|
53
|
+
for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
|
|
54
|
+
x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
|
|
55
|
+
x.XSetWindowBackgroundPixmap(d, root, pix)
|
|
56
|
+
x.XClearWindow(d, root)
|
|
57
|
+
x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
|
|
58
|
+
x.XCloseDisplay(d)
|
|
59
|
+
`;function ce(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
60
|
+
<openbox_config xmlns="http://openbox.org/3.4/rc">
|
|
61
|
+
<theme><keepBorder>no</keepBorder></theme>
|
|
62
|
+
<applications>
|
|
63
|
+
<!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
|
|
64
|
+
<application class="Chromium*">
|
|
65
|
+
<decor>no</decor>
|
|
66
|
+
<position force="yes"><x>${P}</x><y>${P}</y></position>
|
|
67
|
+
<size><width>${e.width-P*2}</width><height>${e.height-P-w}</height></size>
|
|
68
|
+
</application>
|
|
69
|
+
</applications>
|
|
70
|
+
</openbox_config>`}var be=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
|
|
71
|
+
panel_items = L
|
|
72
|
+
panel_size = 100% 46
|
|
73
|
+
panel_margin = 0 10
|
|
74
|
+
panel_padding = 0 0 10
|
|
75
|
+
panel_position = bottom center horizontal
|
|
76
|
+
panel_shrink = 1
|
|
77
|
+
panel_background_id = 0
|
|
78
|
+
panel_layer = top
|
|
79
|
+
mouse_effects = 1
|
|
80
|
+
mouse_hover_icon_asb = 100 0 12
|
|
81
|
+
mouse_pressed_icon_asb = 100 0 -12
|
|
82
|
+
|
|
83
|
+
launcher_icon_size = 46
|
|
84
|
+
launcher_padding = 0 0 10
|
|
85
|
+
launcher_background_id = 0
|
|
86
|
+
launcher_tooltip = 1
|
|
87
|
+
|
|
88
|
+
launcher_item_app = /tmp/ara-chromium.desktop
|
|
89
|
+
launcher_item_app = /tmp/ara-terminal.desktop
|
|
90
|
+
launcher_item_app = /tmp/ara-files.desktop
|
|
91
|
+
`,ye=`corner-radius = 12;
|
|
92
|
+
rounded-corners-exclude = [
|
|
93
|
+
"class_g = 'tint2'",
|
|
94
|
+
"window_type = 'dock'",
|
|
95
|
+
"window_type = 'desktop'"
|
|
96
|
+
];
|
|
97
|
+
backend = "xrender";
|
|
98
|
+
shadow = false;
|
|
99
|
+
fading = false;
|
|
100
|
+
vsync = false;
|
|
101
|
+
inactive-opacity = 1.0;
|
|
102
|
+
active-opacity = 1.0;
|
|
103
|
+
`,le="/tmp/ara-dock-browser.png",ue=`[Desktop Entry]
|
|
104
|
+
Name=Chrome
|
|
105
|
+
Exec=chromium --no-sandbox %U
|
|
106
|
+
Icon=${le}
|
|
107
|
+
Type=Application
|
|
108
|
+
Categories=Network;WebBrowser;
|
|
109
|
+
`,Pe=`[Desktop Entry]
|
|
110
|
+
Name=Terminal
|
|
111
|
+
Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
|
|
112
|
+
Icon=/tmp/ara-dock-terminal.png
|
|
113
|
+
Type=Application
|
|
114
|
+
Categories=System;TerminalEmulator;
|
|
115
|
+
`,Se=`[Desktop Entry]
|
|
116
|
+
Name=Files
|
|
117
|
+
Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
|
|
118
|
+
Icon=/tmp/ara-dock-files.png
|
|
119
|
+
Type=Application
|
|
120
|
+
Categories=System;FileManager;
|
|
121
|
+
`;var K={"wallpaper.jpg":W,"dock-browser.png":B,"dock-terminal.png":F,"dock-files.png":O},Xe=k,fe='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function v(e){let s=(i)=>i.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),p=new Set(e.absent??[]),n=be.split(`
|
|
122
|
+
`).filter((i)=>!(p.has("terminal")&&i.endsWith("/ara-terminal.desktop"))&&!(p.has("files")&&i.endsWith("/ara-files.desktop"))).join(`
|
|
123
|
+
`);return{files:{"openbox/rc.xml":ce(e.screen),"tint2/tint2rc":s(n),"picom/picom.conf":ye,...p.has("terminal")?{}:{"ara-terminal.desktop":s(Pe)},...p.has("files")?{}:{"ara-files.desktop":s(Se)},"ara-chromium.desktop":s(ue).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Xe},start:['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }',fe,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true','if ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi']}}var Re=43200000,_=":99",de=60000,D=15000,L={width:1280,height:800},Ae=/^[A-Za-z0-9._:-]{1,160}$/;function Ne(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Ee=["video","viewer","viewer_same_network","viewer_network"];function Le(e,s=Date.now()){let p=["relay_url","session_id","expires_at"];if(!Ne(e)||p.some((c)=>!(c in e))||Object.keys(e).some((c)=>!p.includes(c)&&!Ee.includes(c)))throw new r("invalid_display_request","Reason desktop request is malformed.");let n="video"in e?Ao(e.video):void 0,t="viewer"in e?Gn(e.viewer):null;if(n===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let o=null;try{o=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!o||o.protocol!=="wss:"&&o.protocol!=="ws:"||o.username||o.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!Ae.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let i=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(i)||i<=s)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(i,s+Re)).toISOString(),...n?{video:n}:{},...t?{viewer:t}:{},...n&&e.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function $t(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function Ls(){if(process.platform==="win32")return $t()&&await Pr();if(process.platform!=="darwin")return $t();return await Pr()}function G(e){_e(e,{recursive:!0,mode:448});let s=Qe(e);if(!s.isDirectory()||s.isSymbolicLink()||process.getuid&&s.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");he(e,448)}function Je(e,s){let p=(t)=>{let o=Buffer.alloc(2);return o.writeUInt16BE(t.length),Buffer.concat([o,t])},n=Buffer.from([255,255]);return Buffer.concat([n,p(Buffer.alloc(0)),p(Buffer.from(e)),p(Buffer.from("MIT-MAGIC-COOKIE-1")),p(s)])}function f(e,s,p=2000){return new Promise((n)=>{let t=we(e),o="",i=(c)=>{t.destroy(),n(c)};t.setTimeout(p,()=>i(!1)),t.once("error",()=>i(!1)),t.once("close",()=>i(!1)),t.once("connect",()=>{if(!s)i(!0)}),t.on("data",(c)=>{if(o+=c.toString("latin1"),o.length>=4)i(o.startsWith("RFB "))})})}async function U(e,s){let p=Date.now()+s;while(Date.now()<p){if(await e())return!0;await new Promise((n)=>setTimeout(n,100))}return!1}function R(e,s,p){return new Promise((n)=>{let t=z(e,s,{detached:!0,stdio:"ignore",env:p});t.once("error",()=>n(-1)),t.once("exit",(o)=>n(o)),t.unref(),setTimeout(()=>n(null),D).unref()})}var J=null;function qe(e=a()){return J??=Ce(e).finally(()=>{J=null}),J}async function Ce(e){let s=x({home:e});if(!s?.xvfb||!s.x11vnc||!s.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");kt({root:s.root,automation:s.automation,extensionDir:s.extensionDir});let p=y(s.root,"display");G(p);let n=await ge(e,p,s.x11vnc);if(n)return n;let t={display:_,xauthority:y(p,"Xauthority"),rfbSocket:y(p,"rfb.sock")},o=y(p,"pulse"),i=(async()=>{try{G(o)}catch{return null}return await ao(o,s.pulseaudio)})();G(y(p,"home"));let c=ee(p,t,s.pulseaudio),T=async()=>({...t,sound:await i});if(await f({path:t.rfbSocket},!0))return await T();if(!H(t.xauthority))C(t.xauthority,Je(_.slice(1),Te(16)),{mode:384,flag:"wx"});let l=se(y(p,"theme"),t.display,L),S={path:`/tmp/.X11-unix/X${_.slice(1)}`};if(!await f(S,!1)){let q=`${L.width}x${L.height}`;if(s.xvnc)I(t.rfbSocket,{force:!0}),R(s.xvnc,[t.display,"-geometry",q,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-AlwaysShared","-desktop","Reason"],c);else R(s.xvfb,[t.display,"-screen","0",`${q}x24`,"-nolisten","tcp","-auth",t.xauthority],c);if(!await U(()=>f(S,!1),D)||s.xvnc&&!await U(()=>f({path:t.rfbSocket},!0),D))throw new r("display_unavailable","Reason could not start the virtual display.");R(s.openbox,["--config-file",l.openboxConfig],c)}if(await te(l,c),!await re(s.x11vnc,t,p,"x11vnc.log",c))throw new r("display_unavailable","Reason could not start the desktop server.");return await T()}function ee(e,s,p){let n={HOME:y(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:s.display,XAUTHORITY:s.xauthority};if(p)n.PULSE_SERVER=Ve(Pn(y(e,"pulse")));return n}async function re(e,s,p,n,t){if(await f({path:s.rfbSocket},!0))return!0;I(s.rfbSocket,{force:!0});let o=await R(e,["-display",s.display,"-auth",s.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",s.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",y(p,n)],t);if(o!==null&&o!==0)return!1;return await U(()=>f({path:s.rfbSocket},!0),D)}async function Ue(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],s=(p)=>Object.fromEntries(e.flatMap((n)=>p[n]?[[n,p[n]]]:[]));if(process.env.DISPLAY)return s(process.env);try{let p=await new Promise((n,t)=>Y("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(o,i)=>o?t(o):n(i)));return s(Object.fromEntries(p.split(`
|
|
124
|
+
`).flatMap((n)=>{let t=n.indexOf("=");return t>0?[[n.slice(0,t),n.slice(t+1)]]:[]})))}catch{return{}}}var V=new Set;async function ge(e,s,p){let n=await Ue(),t=/^:(\d+)(?:\.\d+)?$/.exec(n.DISPLAY??"")?.[1];if(!t||`:${t}`===_||n.WAYLAND_DISPLAY||n.XDG_SESSION_TYPE==="wayland")return null;let o={display:`:${t}`,xauthority:n.XAUTHORITY??y(e,".Xauthority"),rfbSocket:y(s,`rfb-${t}.sock`)},i=`${o.display} ${o.xauthority}`;if(V.has(i)||!await f({path:`/tmp/.X11-unix/X${t}`},!1))return null;let c={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:o.display,XAUTHORITY:o.xauthority};if(await re(p,o,s,`x11vnc-${t}.log`,c))return{...o,sound:null};return V.add(i),process.stderr.write(`Reason worker: your screen ${o.display} could not be served; using the virtual desktop
|
|
125
|
+
`),null}function se(e,s,p){let n=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,t=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!H(`/usr/bin/${i}`)).map(([i])=>i),o=v({root:e,display:s,screen:p,browserExec:n,absent:t});for(let i of["","openbox","tint2","picom"])G(y(e,i));for(let[i,c]of Object.entries(o.files))C(y(e,i),c,{mode:384});for(let[i,c]of Object.entries(K))C(y(e,`ara-${i}`),De(c),{mode:384});return{root:e,openboxConfig:y(e,"openbox","rc.xml"),start:o.start}}async function te(e,s){let p=[`ROOT=${JSON.stringify(e.root)}`,...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
|
|
126
|
+
`);await new Promise((n)=>{let t=z("/bin/sh",["-c",p],{stdio:"ignore",env:{...s,PATH:"/usr/bin:/bin"}}),o=setTimeout(()=>{t.kill(),n()},D);t.once("error",()=>{clearTimeout(o),n()}),t.once("exit",()=>{clearTimeout(o),n()})})}var me=2073600,Me=320;function We(e,s){let p=Math.min(1,Math.sqrt(me/(e.width*e.height))),n=(t,o)=>Math.min(Math.floor(o/8)*8,Math.max(Me,Math.round(t*p/8)*8));return{width:n(e.width,s.width),height:n(e.height,s.height)}}function ne(e,s,p){return new Promise((n)=>Y(e,s,{env:p,encoding:"utf8",timeout:5000},(t,o)=>n(t?null:o)))}function je(e){let s=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),p=e.split(`
|
|
127
|
+
`),n=p.findIndex((o)=>/^\S+ connected/.test(o));if(!s||n<0)return null;let t=[];for(let o of p.slice(n+1)){let i=/^\s+(\d+x\d+)\s/.exec(o);if(!i)break;t.push(i[1])}return{current:{width:Number(s[1]),height:Number(s[2])},maximum:{width:Number(s[3]),height:Number(s[4])},output:p[n].split(" ")[0],modes:t}}async function Be(e,s,p){if(e.display!==_)return null;let n={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(T)=>ne("xrandr",T,n),o=je(await t(["--query"])??"");if(!o||o.maximum.width<=o.current.width&&o.maximum.height<=o.current.height)return null;let i=We(s,o.maximum);if(i.width===o.current.width&&i.height===o.current.height)return{size:i,changed:!1};let c=`${i.width}x${i.height}`;if(!o.modes.includes(c)){if(await t(["--newmode",c,"60",...[i.width,i.width,i.width,i.width,i.height,i.height,i.height,i.height].map(String)]),await t(["--addmode",o.output,c])===null)return null}return p(),await t(["--output",o.output,"--mode",c])===null?null:{size:i,changed:!0}}async function Oe(e,s){let p=x({home:a()});if(!p)return;let n=y(p.root,"display"),t=ee(n,e,p.pulseaudio);await te(se(y(n,"theme"),e.display,s),t);let o=s.width-P*2,i=s.height-P-w;await ne("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(o),String(i),"windowmove","%@",String(P),String(P)],{...t,PATH:"/usr/bin:/bin"})}var Z=Promise.resolve();function Fe(e,s,p=()=>{}){let n=Z.then(()=>Be(e,s,p));return Z=n.then((t)=>t?.changed?Oe(e,t.size):void 0).catch(()=>{}),n.then((t)=>t?.size??null,()=>null)}async function Bt(e,s={}){let p=s.now??Date.now,n=Le(e.payload,p());if(e.signal.throwIfAborted(),!n.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=s.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let o=n.video,i=(s.video?.desktop??(t==="darwin"?async()=>Tn:t==="win32"?async()=>Rn:qe))();return await ke(e.signal,n,s,p,(c)=>On(c,{request:o,desktop:i,...n.viewer?{viewer:n.viewer}:{},viewerSameNetwork:n.viewer_same_network===!0},{resizeDesktop:Fe,...s.video}),(c)=>Jt({type:"error",code:c}))}function ke(e,s,p,n,t,o){let i=n();return new Promise((c,T)=>{let l=null,S=!1,q=!1,g,d,h,m=!1,u=null,X=(b)=>{if(q)return;if(u)b=u;q=!0,clearTimeout(g),clearTimeout(d),e.removeEventListener("abort",N),h?.close();try{l?.close(1000,"display_session_over")}catch{}if("error"in b){T(b.error);return}c({reason:b.reason,...h?.summary(),duration_ms:Math.max(0,n()-i)})},A=()=>X({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),N=()=>{let b=e.reason;X({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},M=()=>{if(!u||!l)return;let b=u.error;try{l.send(o(b instanceof r?b.code:"display_unavailable"))}catch{}X(u)};if(h=t({get done(){return q||u!==null},get open(){return S&&!q&&u===null},get bufferedAmount(){return l?.bufferedAmount??0},send(b){if(q||u||!S||!l)return;try{l.send(b)}catch{X({reason:"relay_closed"})}},end:(b)=>{if(q||u)return;if(!("error"in b)){X(b);return}if(u=b,m&&S)M()}}),q){h.close();return}if(e.aborted){N();return}e.addEventListener("abort",N,{once:!0}),g=setTimeout(()=>X({reason:"session_expired"}),Math.max(1,Date.parse(s.expires_at)-n())),d=setTimeout(()=>X({reason:"viewer_absent"}),p.viewerWaitMs??de);try{l=(p.connect??Ir)(s.relay_url,(p.loadProxy??j)()?.url)}catch{A();return}l.binaryType="arraybuffer",l.onopen=()=>{if(q||!l)return;S=!0,h?.opened()},l.onmessage=(b)=>{if(q)return;let Q=b.data,E=Q instanceof ArrayBuffer?new Uint8Array(Q):ArrayBuffer.isView(Q)?new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength):null;if(!E||E.byteLength===0)return;if(clearTimeout(d),m=!0,u){M();return}h?.received(E)},l.onclose=()=>{if(q)return;if(!S){A();return}X({reason:"relay_closed"})},l.onerror=()=>{if(q||S)return;A()}})}
|
|
128
|
+
export{$t,Ls,G,qe,Bt};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{C}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFileSync as b}from"child_process";import{mkdirSync as y,readdirSync as h,readFileSync as D,rmSync as f,statSync as k,writeFileSync as w}from"fs";import{join as p,sep as S}from"path";import{setTimeout as x}from"timers/promises";var L=3000,u=null;function g(e){return p(e,"users")}function kt(e){if(u?.root===e.root)return;let t=g(e.root);y(t,{recursive:!0,mode:448}),w(p(t,String(process.pid)),"",{mode:384}),u=e}function da(){if(!u)return;f(p(g(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}}function _(){let e=process.getuid?.();if(process.platform==="linux")return h("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(k(`/proc/${n}`).uid!==e)return[];let s=D(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return b(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let c=/^(\d+) (.+)$/.exec(s.trim());return c?[{pid:Number(c[1]),command:c[2]}]:[]});return b("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
|
|
3
|
+
`).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function pa(){let e=u;if(!e)return{released:"unused",stopped:0};let t=g(e.root);f(p(t,String(process.pid)),{force:!0}),u=null;let n=!1;for(let o of h(t)){let i=Number(o);if(Number.isSafeInteger(i)&&i>0&&m(i))n=!0;else f(p(t,o),{force:!0})}if(n)return{released:"shared",stopped:0};let s=_().filter((o)=>o.pid!==process.pid&&(o.command.includes(`${e.root}${S}`)||o.command.includes(`${e.automation}${S}`)||o.command.includes(e.extensionDir))),c=(o,i)=>{try{process.kill(o,i)}catch{}};for(let o of s)c(o.pid,"SIGTERM");for(let o=Date.now()+L;Date.now()<o&&s.some((i)=>m(i.pid));)await new Promise((i)=>setTimeout(i,100));for(let o of s)if(m(o.pid))c(o.pid,"SIGKILL");return{released:"stopped",stopped:s.length}}var P=20000,E=30000,M=100,a=new Map,l=null,d=[];function Ii(e){a.set(e,(a.get(e)??0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(a.get(e)??1)-1;if(n>0){a.set(e,n);return}if(a.delete(e),l?.run===e)l.idleUntil=0}}function N(){return new r("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function O(e,t){return l!==null&&l.run!==e&&(l.calls>0||t<l.idleUntil)}async function Di(e,t,n=Date.now){let s=Symbol(e);d.push(s);try{let i=n()+E;for(;;){if(!O(e,n())&&(l?.run===e||d[0]===s))break;if(n()>=i)throw N();await x(M,void 0,{signal:t}).catch(()=>t.throwIfAborted())}}finally{d.splice(d.indexOf(s),1)}if(l?.run!==e)l={run:e,calls:0,idleUntil:0};let c=l;c.calls+=1;let o=!1;return()=>{if(o)return;o=!0,c.calls-=1,c.idleUntil=n()+P}}
|
|
4
|
+
export{kt,da,pa,Ii,Di};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
export{
|
|
2
|
+
var n={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},t=Object.values(n),E=new Set;function T(e,A){let N=e[A];if(N?.trim())return N;let _=e[n[A]];if(_?.trim())E.add(n[A]);return _}
|
|
3
|
+
export{T};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{pt,g,ht}from"./vm-hands-entry-lite-aj139v8j.js";import{chmodSync as Q,existsSync as C,mkdirSync as Z,readlinkSync as S,readFileSync as b,renameSync as nn,unlinkSync as tn,writeFileSync as en}from"fs";import{homedir as u}from"os";import{basename as _,dirname as h,isAbsolute as p,join as o,normalize as A,relative as O,resolve as N}from"path";var c=3,P=1,D=2,x=1,T=1,L="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",M="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",F=[M,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function B(n){return typeof n==="string"&&F.includes(n)}var U=["future_device","updates_only","cli_only"];function f(n){return typeof n==="string"&&U.some((t)=>t===n)}function V(n=process.env,t=u()){return n.XDG_CONFIG_HOME?.trim()||o(t,".config")}function Wr(n=process.env,t=u()){let r=g({env:n}),e=V(n,t);return o(e,ht(e).state==="kept"?"ara":"reason",...r==="staging"?["staging"]:[],"installation.json")}function a(n){return typeof n==="string"&&n.trim().length>0}var K=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function z(n){return typeof n==="string"&&K.test(n)}function l(n){return a(n)&&p(n)&&A(n)===n}function y(n){if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return l(t.path)&&(t.role==="launcher"&&(t.kind==="file"||t.kind==="symlink")||t.role==="worker_root"&&t.kind==="directory"||t.role==="alias"&&t.kind==="symlink"&&l(t.target))}function m(n){return n==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}function qn(n){let t=n.owned_paths.filter((e)=>e.role==="launcher").map((e)=>e.path),[r]=m(n.channel);return t.find((e)=>_(e)===r)??t[0]??null}function I(n){let[t,r]=m(n.channel==="staging"?"staging":"production"),e=[[t,r],[r,t]];return n.owned_paths?.every((i)=>i.role!=="alias"||n.installer==="shell"&&e.some(([s,R])=>i.path===o(n.install_dir,s)&&i.target===o(n.install_dir,R))&&n.owned_paths?.some((s)=>s.role==="launcher"&&s.path===i.target))??!1}function d(n,t){try{return N(h(n),S(n))===t}catch{return!1}}function Vr(n){let t=_(n),r=t==="ara"?"reason":t==="ara-staging"?"reason-staging":null;if(!r)return n;let e=o(h(n),r);return d(e,n)||d(n,e)?e:n}function w(n,t){let r=O(n,t);return r.length>0&&!r.startsWith("..")&&!p(r)}function E(n){if(n===null)return!0;if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return(t.kind==="shell_profile"||t.kind==="windows_user_path")&&a(t.location)&&a(t.value)&&(typeof t.added_by_installer==="boolean"||typeof t.added_by_ara==="boolean")&&(t.added_by_installer===void 0||typeof t.added_by_installer==="boolean")&&(t.added_by_ara===void 0||typeof t.added_by_ara==="boolean")}function k(n,t){if(t===null)return n==="cli_only";if(!t||typeof t!=="object"||Array.isArray(t))return!1;let r=t;if(r.version!==x||!a(r.recorded_at))return!1;if(n==="future_device")return r.decision==="authorized"&&B(r.scope);return r.scope===null&&r.decision===(n==="updates_only"?"ask":"disabled")}function G(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==P||!pt.includes(t.channel)||t.install_method!=="curl"||t.installer!=="shell"&&t.installer!=="powershell"||!a(t.installed_at)||!a(t.version)||!a(t.target)||!l(t.install_dir)||!Array.isArray(t.owned_paths)||!t.owned_paths.every(y)||!t.owned_paths.every((r)=>w(t.install_dir,r.path))||!I(t)||!E(t.path_entry))return null;return{...t,schema_version:c,installation_id:null,background_mode:"cli_only",device_consent:null}}function j(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==D||!v(t)||!f(t.background_mode)||!k(t.background_mode,t.device_consent))return null;return{...t,schema_version:c,installation_id:null}}function v(n){return pt.includes(n.channel)&&(n.install_method==="curl"&&(n.installer==="shell"||n.installer==="powershell")||n.install_method==="desktop"&&n.installer==="desktop"&&Array.isArray(n.owned_paths)&&n.owned_paths.length===0&&n.path_entry===null)&&a(n.installed_at)&&a(n.version)&&a(n.target)&&l(n.install_dir)&&Array.isArray(n.owned_paths)&&n.owned_paths.every(y)&&n.owned_paths.every((t)=>w(n.install_dir,t.path))&&I(n)&&E(n.path_entry)}function H(n){let t=G(n);if(t)return t;let r=j(n);if(r)return r;if(!n||typeof n!=="object"||Array.isArray(n))return null;let e=n;if(e.schema_version!==c||!z(e.installation_id)||!v(e)||!f(e.background_mode)||!k(e.background_mode,e.device_consent)||e.desktop_account_access!==void 0&&(e.desktop_account_access===null||typeof e.desktop_account_access!=="object"||Array.isArray(e.desktop_account_access)||e.desktop_account_access.version!==T||e.desktop_account_access.scope!==L||!a(e.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(e.desktop_account_access.recorded_at))))return null;return e}function Wn(n=Wr()){if(!C(n))return null;try{return H(JSON.parse(b(n,"utf8")))}catch{return null}}export{Wr,qn,Vr,Wn};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,Oi=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var he=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var os=(a,b)=>{for(var c in b)h(a,c,{get:b[c],enumerable:!0,configurable:!0,set:s.bind(b,c)})};var ss=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var e=import.meta.require;
|
|
3
|
+
export{Oi,he,os,ss,e};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{a}from"./vm-hands-entry-lite-jev771b3.js";import{readFileSync as c}from"fs";import{isAbsolute as l,normalize as i}from"path";var m="REASON_WORKER_DESKTOP_USER",u=null;function p(t,o){for(let s of o.split(`
|
|
3
|
+
`)){let e=s.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!l(n)||i(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function Ms(t={}){let o="value"in t?t.value:process.env[m];if(u=null,o===void 0||o==="")return null;let s=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=s==="linux"&&e===0&&Number.isSafeInteger(n)?p(n,(t.passwd??(()=>c("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function K(){return u}function Un(){return u?.home??a()}
|
|
4
|
+
export{Ms,K,Un};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{de,Qe,O}from"./vm-hands-entry-lite-3krzmhkk.js";import{execFileSync as p}from"child_process";import{existsSync as s,realpathSync as c}from"fs";import{userInfo as l}from"os";import{isAbsolute as u,join as t,normalize as f,parse as d}from"path";function a(){let r=f(l().homedir);if(!u(r)||r===d(r).root)throw Error("Could not resolve the canonical user home.");return r}function ie(r,n,e=a()){let i=O(n);if(n.kind==="managed"&&n.base){let o=c(e);return{anchor:o,boundary:t(o,n.base),path:t(o,i)}}if(n.kind==="root"&&Qe(n.path)){let o=c(e);return{anchor:o,boundary:t(o,de),path:t(o,i)}}return{anchor:r,boundary:r,path:t(r,i)}}function tr(r=a()){return t(r,".config")}function Io(){if(process.platform!=="darwin")return null;try{let r=p("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return u(r)?c(r):null}catch{return null}}function Do(r=a()){let n=t(r,"Library","Application Support","Ara"),e=t(r,"Library","Application Support","Reason");return s(n)&&!s(e)?n:e}
|
|
3
|
+
export{a,ie,tr,Io,Do};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ie,spawn as E}from"child_process";var bo="h264_ws_v1",vo="video",ft=["smooth","sharp","data_saver","balanced"];var So="video_presets";var L=8388608,S=65536,Eo="control",xo="v1",X=200;function Gn(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t,n=(i)=>typeof i==="string"&&i.length>0&&i.length<=X;if(Object.keys(e).length!==2||!n(e.user_id)||!n(e.name))return null;return{user_id:e.user_id,name:e.name}}var ko="windows",Co="v1",D=200,J=(t)=>typeof t==="string"&&ft.includes(t);function Ao(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(Object.keys(e).length!==2||e.format!=="h264_ws_v1"||!J(e.preset))return null;return{format:"h264_ws_v1",preset:e.preset}}var o={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23,resize:24};class l extends Error{constructor(t){super(t);this.name="DisplayVideoProtocolError"}}var Z=new TextEncoder,Q=new TextDecoder("utf-8",{fatal:!0});function p(t,e){if(e.byteLength+1>L)throw new l("message_too_large");let n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,e.byteLength+1),i.setUint8(4,t),n.set(e,5),n}function w(t){let e=Z.encode(t);if(e.byteLength>S)throw new l("text_too_large");return e}function _(t,e){if(!Number.isInteger(t)||t<0||t>65535)throw new l(`invalid_${e}`);return t}function ee(t){if(!Number.isFinite(t))throw new l("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(t)))}function Jt(t){switch(t.type){case"hello":{let e=w(t.codec),n=new Uint8Array(6+e.byteLength),i=new DataView(n.buffer);return i.setUint16(0,_(t.width,"width")),i.setUint16(2,_(t.height,"height")),i.setUint8(4,Math.max(1,Math.min(240,Math.round(t.fps)))),i.setUint8(5,ft.indexOf(t.preset)),n.set(e,6),p(o.hello,n)}case"frame":{let e=new Uint8Array(13+t.data.byteLength),n=new DataView(e.buffer);return n.setUint8(0,t.key?1:0),n.setUint32(1,t.seq>>>0),n.setBigUint64(5,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,13),p(o.frame,e)}case"stats":return p(o.stats,w(JSON.stringify(t.stats)));case"pong":case"ping":{let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.token),p(t.type==="ping"?o.ping:o.pong,e)}case"serverClipboard":return p(o.serverClipboard,w(t.text));case"clientClipboard":return p(o.clientClipboard,w(t.text));case"error":return p(o.error,w(t.code));case"pointer":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint16(0,_(t.x,"x")),n.setUint16(2,_(t.y,"y")),n.setUint8(4,t.buttons&255),p(o.pointer,e)}case"key":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint8(0,t.down?1:0),n.setUint32(1,t.keysym>>>0),p(o.key,e)}case"config":return p(o.config,Uint8Array.of(ft.indexOf(t.preset)));case"keyframeRequest":return p(o.keyframeRequest,new Uint8Array(0));case"audioHello":{let e=w(t.codec),n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,t.sampleRate>>>0),i.setUint8(4,t.channels&255),n.set(e,5),p(o.audioHello,n)}case"audio":{let e=new Uint8Array(8+t.data.byteLength);return new DataView(e.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,8),p(o.audio,e)}case"control":return p(o.control,w(JSON.stringify(t.control)));case"windows":{let e=t.bounds.slice(0,D),n=new Uint8Array(e.length*16),i=new DataView(n.buffer);return e.forEach((s,a)=>{[s.x,s.y,s.width,s.height].forEach((c,d)=>i.setInt32(a*16+d*4,ee(c)))}),p(o.windows,n)}case"audioEnable":return p(o.audioEnable,Uint8Array.of(t.on?1:0));case"resize":{let e=new Uint8Array(4),n=new DataView(e.buffer);return n.setUint16(0,_(t.width,"width")),n.setUint16(2,_(t.height,"height")),p(o.resize,e)}case"ack":{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t.seq>>>0),p(o.ack,e)}}}function M(t){let e=ft[t];if(!e)throw new l("invalid_preset");return e}function y(t,e){if(t.byteLength!==e)throw new l("invalid_length")}function x(t){if(t.byteLength>S)throw new l("text_too_large");try{return Q.decode(t)}catch{throw new l("invalid_text")}}function te(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_stats")}let n=e;if(!n||typeof n!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((s)=>typeof n[s]!=="number"||!Number.isFinite(n[s])))throw new l("invalid_stats");return{fps:n.fps,kbps:n.kbps,dropped:n.dropped,restarts:n.restarts,queued_bytes:n.queued_bytes}}function ne(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_control")}let n=e;if(!n||typeof n!=="object"||typeof n.you!=="boolean"||typeof n.same_user!=="boolean")throw new l("invalid_control");let i=n.holder===null?null:Gn(n.holder);if(i===null&&n.holder!==null)throw new l("invalid_control");return{holder:i,you:n.you,same_user:n.same_user}}function re(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(t){case o.hello:if(e.byteLength<6)throw new l("invalid_length");return{type:"hello",width:n.getUint16(0),height:n.getUint16(2),fps:n.getUint8(4),preset:M(n.getUint8(5)),codec:x(e.subarray(6))};case o.frame:if(e.byteLength<14)throw new l("invalid_length");if(n.getUint8(0)>1)throw new l("invalid_frame_flags");return{type:"frame",key:n.getUint8(0)===1,seq:n.getUint32(1),captureMicros:Number(n.getBigUint64(5)),data:e.subarray(13)};case o.stats:return{type:"stats",stats:te(e)};case o.ping:case o.pong:return y(e,8),{type:t===o.ping?"ping":"pong",token:n.getFloat64(0)};case o.serverClipboard:return{type:"serverClipboard",text:x(e)};case o.clientClipboard:return{type:"clientClipboard",text:x(e)};case o.error:return{type:"error",code:x(e)};case o.pointer:return y(e,5),{type:"pointer",x:n.getUint16(0),y:n.getUint16(2),buttons:n.getUint8(4)};case o.key:if(y(e,5),n.getUint8(0)>1)throw new l("invalid_key_flags");return{type:"key",down:n.getUint8(0)===1,keysym:n.getUint32(1)};case o.config:return y(e,1),{type:"config",preset:M(n.getUint8(0))};case o.keyframeRequest:return y(e,0),{type:"keyframeRequest"};case o.audioHello:if(e.byteLength<5)throw new l("invalid_length");return{type:"audioHello",sampleRate:n.getUint32(0),channels:n.getUint8(4),codec:x(e.subarray(5))};case o.audio:if(e.byteLength<9)throw new l("invalid_length");return{type:"audio",captureMicros:Number(n.getBigUint64(0)),data:e.subarray(8)};case o.audioEnable:if(y(e,1),n.getUint8(0)>1)throw new l("invalid_audio_flags");return{type:"audioEnable",on:n.getUint8(0)===1};case o.resize:return y(e,4),{type:"resize",width:n.getUint16(0),height:n.getUint16(2)};case o.control:return{type:"control",control:ne(e)};case o.windows:{if(e.byteLength%16!==0||e.byteLength>D*16)throw new l("invalid_length");let i=[];for(let s=0;s<e.byteLength;s+=16)i.push({x:n.getInt32(s),y:n.getInt32(s+4),width:n.getInt32(s+8),height:n.getInt32(s+12)});return{type:"windows",bounds:i}}case o.ack:return y(e,4),{type:"ack",seq:n.getUint32(0)};default:return null}}class Kn{buffer=new Uint8Array(0);push(t){let e=new Uint8Array(this.buffer.byteLength+t.byteLength);e.set(this.buffer),e.set(t,this.buffer.byteLength);let n=[],i=0;while(e.byteLength-i>=4){let s=new DataView(e.buffer,e.byteOffset+i,4).getUint32(0);if(s<1||s>L)throw new l("invalid_message_length");if(e.byteLength-i-4<s)break;let a=e[i+4],c=e.slice(i+5,i+4+s),d=re(a,c);if(d)n.push(d);i+=4+s}return this.buffer=e.slice(i),n}}var Y="/usr/bin/osascript",se=5000,oe=1048576,ae=String.raw`
|
|
3
|
+
ObjC.import("CoreGraphics");
|
|
4
|
+
ObjC.import("ApplicationServices");
|
|
5
|
+
ObjC.import("AppKit");
|
|
6
|
+
ObjC.bindFunction("CGPreflightScreenCaptureAccess", ["bool", []]);
|
|
7
|
+
ObjC.bindFunction("CGRequestScreenCaptureAccess", ["bool", []]);
|
|
8
|
+
ObjC.bindFunction("getppid", ["int", []]);
|
|
9
|
+
function run(argv) {
|
|
10
|
+
const bounds = $.CGDisplayBounds($.CGMainDisplayID());
|
|
11
|
+
const stdout = $.NSFileHandle.fileHandleWithStandardOutput;
|
|
12
|
+
const screen = $.CGPreflightScreenCaptureAccess(), accessibility = $.AXIsProcessTrusted();
|
|
13
|
+
stdout.writeData($(JSON.stringify({ screen, accessibility,
|
|
14
|
+
width: bounds.size.width, height: bounds.size.height }) + "\n").dataUsingEncoding($.NSUTF8StringEncoding));
|
|
15
|
+
if (argv[0] === "request") {
|
|
16
|
+
if (!screen && argv[1] !== "accessibility") $.CGRequestScreenCaptureAccess();
|
|
17
|
+
if (!accessibility && argv[1] !== "screen") $.AXIsProcessTrustedWithOptions($({ AXTrustedCheckOptionPrompt: true }));
|
|
18
|
+
}
|
|
19
|
+
if (argv[0] === "probe" || argv[0] === "request") return;
|
|
20
|
+
if (argv[0] === "clipboard") {
|
|
21
|
+
const parent = $.getppid(), clipboard = $.NSPasteboard.generalPasteboard;
|
|
22
|
+
// Only changes made during this pairing: never export the initial pasteboard.
|
|
23
|
+
let last = Number(clipboard.changeCount);
|
|
24
|
+
while ($.getppid() === parent) {
|
|
25
|
+
$.NSThread.sleepForTimeInterval(0.1);
|
|
26
|
+
const count = Number(clipboard.changeCount);
|
|
27
|
+
if (count === last) continue;
|
|
28
|
+
last = count;
|
|
29
|
+
const text = clipboard.stringForType($.NSPasteboardTypeString);
|
|
30
|
+
if (!text) continue;
|
|
31
|
+
const bytes = text.dataUsingEncoding($.NSUTF8StringEncoding);
|
|
32
|
+
if (Number(bytes.length) > ${S}) continue;
|
|
33
|
+
stdout.writeData($("c " + bytes.base64EncodedStringWithOptions(0).js + "\n").dataUsingEncoding($.NSUTF8StringEncoding));
|
|
34
|
+
}
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const stdin = $.NSFileHandle.fileHandleWithStandardInput;
|
|
38
|
+
let pending = "";
|
|
39
|
+
for (;;) {
|
|
40
|
+
const data = stdin.availableData;
|
|
41
|
+
if (Number(data.length) === 0) return;
|
|
42
|
+
pending += $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js;
|
|
43
|
+
for (let end = pending.indexOf("\n"); end >= 0; end = pending.indexOf("\n")) {
|
|
44
|
+
const [kind, ...rest] = pending.slice(0, end).split(" ");
|
|
45
|
+
pending = pending.slice(end + 1);
|
|
46
|
+
const n = rest.map(Number);
|
|
47
|
+
let event = null;
|
|
48
|
+
if (kind === "m") {
|
|
49
|
+
event = $.CGEventCreateMouseEvent($(), n[0], { x: n[1], y: n[2] }, n[3]);
|
|
50
|
+
$.CGEventSetIntegerValueField(event, $.kCGMouseEventClickState, n[4]);
|
|
51
|
+
} else if (kind === "w") {
|
|
52
|
+
event = $.CGEventCreateScrollWheelEvent($(), $.kCGScrollEventUnitPixel, 2, n[0], n[1]);
|
|
53
|
+
} else if (kind === "k") {
|
|
54
|
+
event = $.CGEventCreateKeyboardEvent($(), n[0], n[1] === 1);
|
|
55
|
+
} else if (kind === "u") {
|
|
56
|
+
event = $.CGEventCreateKeyboardEvent($(), 0, n[0] === 1);
|
|
57
|
+
const unit = Ref("unsigned short");
|
|
58
|
+
unit[0] = n[1];
|
|
59
|
+
$.CGEventKeyboardSetUnicodeString(event, 1, unit);
|
|
60
|
+
} else if (kind === "c") {
|
|
61
|
+
const bytes = $.NSData.alloc.initWithBase64EncodedStringOptions($(rest[0] || ""), 0);
|
|
62
|
+
$.NSPasteboard.generalPasteboard.clearContents;
|
|
63
|
+
$.NSPasteboard.generalPasteboard.setStringForType($.NSString.alloc.initWithDataEncoding(bytes, $.NSUTF8StringEncoding), $.NSPasteboardTypeString);
|
|
64
|
+
}
|
|
65
|
+
if (event) {
|
|
66
|
+
$.CGEventSetFlags(event, n[n.length - 1]);
|
|
67
|
+
$.CGEventPost($.kCGHIDEventTap, event);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`;function q(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!=="object")return null;let n=e,i=(c)=>typeof c==="number"&&Number.isFinite(c)?Math.min(65535,Math.round(c)):0;if(typeof n.screen!=="boolean"||typeof n.accessibility!=="boolean")return null;let s=i(n.width),a=i(n.height);return s>0&&a>0?{screen:n.screen,accessibility:n.accessibility,width:s,height:a}:null}function k(t,...e){let[n,...i]=[...t,Y,"-l","JavaScript","-e",ae,...e];return[n,i]}function H(t,...e){return new Promise((n)=>{ie(...k(t,...e),{env:{},timeout:se,killSignal:"SIGKILL",maxBuffer:65536,encoding:"utf8"},(i,s)=>n(i?null:q(s.split(`
|
|
73
|
+
`)[0]??"")))})}function Ye(t=[]){return H(t,"probe")}function mt(t,e){return H(t,"request",...e?[e]:[])}var N=2,ce=8,ue=String.raw`
|
|
74
|
+
ObjC.import("CoreGraphics");
|
|
75
|
+
ObjC.import("Foundation");
|
|
76
|
+
ObjC.bindFunction("getppid", ["int", []]);
|
|
77
|
+
function run() {
|
|
78
|
+
const stdout = $.NSFileHandle.fileHandleWithStandardOutput;
|
|
79
|
+
const parent = $.getppid();
|
|
80
|
+
let last = "";
|
|
81
|
+
let wait = ${N};
|
|
82
|
+
// Ends with the worker that started it, even one that never got to kill it.
|
|
83
|
+
while ($.getppid() === parent) {
|
|
84
|
+
const list = ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements, 0));
|
|
85
|
+
const bounds = [];
|
|
86
|
+
const count = Number(list.count);
|
|
87
|
+
for (let i = 0; i < count && bounds.length < ${D}; i++) {
|
|
88
|
+
const window = list.objectAtIndex(i);
|
|
89
|
+
if (Number(window.objectForKey("kCGWindowLayer").js) !== 0) continue;
|
|
90
|
+
const b = window.objectForKey("kCGWindowBounds");
|
|
91
|
+
bounds.push(["X", "Y", "Width", "Height"].map((key) => Math.round(Number(b.objectForKey(key).js))));
|
|
92
|
+
}
|
|
93
|
+
const line = JSON.stringify(bounds);
|
|
94
|
+
if (line !== last) {
|
|
95
|
+
last = line;
|
|
96
|
+
wait = ${N};
|
|
97
|
+
stdout.writeData($(line + "\n").dataUsingEncoding($.NSUTF8StringEncoding));
|
|
98
|
+
} else {
|
|
99
|
+
wait = Math.min(wait * 2, ${ce});
|
|
100
|
+
}
|
|
101
|
+
$.NSThread.sleepForTimeInterval(wait);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
`;function le(t){let e;try{e=JSON.parse(t)}catch{return null}if(!Array.isArray(e))return null;let n=[];for(let i of e.slice(0,D)){if(!Array.isArray(i)||i.length!==4||!i.every((u)=>typeof u==="number"&&Number.isFinite(u)))return null;let[s,a,c,d]=i.map(Math.round);if(c>0&&d>0)n.push({x:s,y:a,width:c,height:d})}return n}function Jn(t){let e=Date.now(),n=0,i=!1,s=(u,b={})=>{try{process.stderr.write(`${JSON.stringify({event:"display.windows_helper",state:u,...b})}
|
|
105
|
+
`)}catch{}},a=(u,b={})=>{if(i)return;i=!0,s(u,{updates:n,duration_ms:Date.now()-e,...b})},c=E(Y,["-l","JavaScript","-e",ue],{env:{},stdio:["ignore","pipe","ignore"]});s("started");let d="";return c.stdout.on("data",(u)=>{if(i)return;d+=u.toString("utf8");for(let b=d.indexOf(`
|
|
106
|
+
`);b>=0;b=d.indexOf(`
|
|
107
|
+
`)){let m=le(d.slice(0,b));if(d=d.slice(b+1),m)n++,t(m)}if(d.length>65536)d=""}),c.once("error",(u)=>a("failed",{code:u.code??"spawn_failed"})),c.once("exit",(u,b)=>a("failed",{code:"exited",exit_code:u,signal:b})),{close(){a("stopped"),c.kill("SIGKILL")}}}var T=5,R=[{bit:1,button:0,down:1,up:2,drag:6},{bit:4,button:1,down:3,up:4,drag:7},{bit:2,button:2,down:25,up:26,drag:27}],de=[[8,1,0],[16,-1,0],[32,0,1],[64,0,-1]],P=50,fe=500,V=4,I=131072,W=262144,O=524288,F=1048576,B=new Map([[65505,[56,I]],[65506,[60,I]],[65507,[59,W]],[65508,[62,W]],[65511,[58,O]],[65512,[61,O]],[65513,[58,O]],[65514,[61,O]],[65027,[61,O]],[65515,[55,F]],[65516,[54,F]]]),pe=new Map([[65288,51],[65289,48],[65056,48],[65293,36],[65307,53],[65535,117],[65509,57],[65360,115],[65361,123],[65362,126],[65363,124],[65364,125],[65365,116],[65366,121],[65367,119],[65379,114],[65386,114],[65291,71],[65408,49],[65421,76],[65429,115],[65430,123],[65431,126],[65432,124],[65433,125],[65434,116],[65435,121],[65436,119],[65437,71],[65438,114],[65439,117],[65450,67],[65451,69],[65452,65],[65453,78],[65454,65],[65455,75],[65469,81],...[82,83,84,85,86,87,88,89,91,92].map((t,e)=>[65456+e,t]),...[122,120,99,118,96,97,98,100,101,109,103,111,105,107,113,106,64,79,80,90].map((t,e)=>[65470+e,t])]),G="asdfhgzxcv\x00bqweryt123465=97-80]ou[ip\x00lj'k;\\,/nm.\x00 `",j='~!@#$%^&*()_+{}|:"<>?',be="`1234567890-=[]\\;',./",v=new Map;for(let t=0;t<G.length;t++){let e=G[t];if(e==="\x00")continue;if(v.set(e.charCodeAt(0),[t,!1]),e>="a"&&e<="z")v.set(e.toUpperCase().charCodeAt(0),[t,!0])}for(let t=0;t<j.length;t++)v.set(j.charCodeAt(t),[v.get(be.charCodeAt(t))[0],!0]);class K{now;x=-1;y=-1;mask=0;clicks=0;lastDown=null;held=new Set;constructor(t=()=>performance.now()){this.now=t}flags(){let t=0;for(let e of this.held)t|=B.get(e)[1];return t}mouse(t,e){return`m ${t} ${this.x} ${this.y} ${e} ${t===T?0:this.clicks} ${this.flags()}`}pointer(t,e,n){let i=[];if(t!==this.x||e!==this.y){this.x=t,this.y=e;let s=R.find((a)=>this.mask&a.bit);i.push(s?this.mouse(s.drag,s.button):this.mouse(T,0))}for(let s of R){let a=(this.mask&s.bit)!==0,c=(n&s.bit)!==0;if(!a&&c){let d=this.now(),u=this.lastDown;this.clicks=u&&u.button===s.button&&d-u.at<=fe&&Math.abs(t-u.x)<=V&&Math.abs(e-u.y)<=V?this.clicks+1:1,this.lastDown={button:s.button,at:d,x:t,y:e},i.push(this.mouse(s.down,s.button))}else if(a&&!c)i.push(this.mouse(s.up,s.button))}for(let[s,a,c]of de)if(!(this.mask&s)&&n&s)i.push(`w ${a*P} ${c*P} ${this.flags()}`);return this.mask=n,i}key(t,e){let n=t?1:0,i=B.get(e);if(i){if(t)this.held.add(e);else this.held.delete(e);return[`k ${i[0]} ${n} ${this.flags()}`]}let s=pe.get(e);if(s!==void 0)return[`k ${s} ${n} ${this.flags()}`];let a=e<256?e:(e&4278190080)===16777216?e&16777215:0,c=v.get(a);if(c)return[`k ${c[0]} ${n} ${this.flags()|(c[1]?I:0)}`];if(a<160||a>65535||a>=55296&&a<57344)return[];return[`u ${n} ${a} ${this.flags()}`]}}function Zn(t,e=[]){let n=E(...k(e),{env:{},stdio:["pipe","pipe","ignore"]}),i=new K,s="",a=!1,c=null,d=()=>{n.kill("SIGKILL"),c?.kill("SIGKILL")},u=(f)=>{if(a)return;a=!0,d(),t.end(f)},b=(f)=>u({error:new r("display_unavailable",f)}),m=(f)=>{if(a||f.length===0)return;if(n.stdin.write(f.map((g)=>`${g}
|
|
108
|
+
`).join("")),n.stdin.writableLength>oe)u({reason:"input_backpressure"})},z=()=>{c=E(...k(e,"clipboard"),{env:{},stdio:["ignore","pipe","ignore"]});let f="";c.stdout?.on("data",(g)=>{if(a)return;f+=g.toString("ascii");for(let h=f.indexOf(`
|
|
109
|
+
`);h>=0;h=f.indexOf(`
|
|
110
|
+
`)){let U=f.slice(0,h);if(f=f.slice(h+1),!U.startsWith("c "))continue;let A=U.slice(2);if(A.length>Math.ceil(S/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(A)){u({reason:"display_protocol"});return}let C=Buffer.from(A,"base64");if(C.byteLength<=S)t.clipboard(C.toString("utf8"));if(a)return}if(f.length>Math.ceil(S/3)*4+2)u({reason:"display_protocol"})}),c.once("error",()=>b("Reason could not watch this Mac's desktop clipboard.")),c.once("exit",()=>{if(!a)b("Reason could not watch this Mac's desktop clipboard.")})};return n.stdout.on("data",(f)=>{if(a||s===null)return;s+=f.toString("utf8");let g=s.indexOf(`
|
|
111
|
+
`);if(g<0){if(s.length>4096)u({reason:"display_protocol"});return}let h=q(s.slice(0,g));if(s=null,!h)u({reason:"display_protocol"});else if(!h.screen||!h.accessibility)b(e.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else z(),t.ready({width:h.width,height:h.height})}),n.stdin.on("error",()=>{return}),n.once("error",()=>b("Reason could not start this Mac's desktop input.")),n.once("exit",()=>{if(s!==null)b("Reason could not start this Mac's desktop input.");else u({reason:"display_closed"})}),{pointer:(f,g,h)=>m(i.pointer(f,g,h)),key:(f,g)=>m(i.key(f,g)),clipboard:(f)=>m([`c ${Buffer.from(f,"utf8").toString("base64")}`]),close(){a=!0,d()}}}
|
|
112
|
+
export{bo,vo,ft,So,S,Eo,xo,Gn,ko,Co,Ao,Jt,Kn,Ye,mt,Jn,Zn};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-3krzmhkk.js";import{D,R,b}from"./vm-hands-entry-lite-beyyy1gz.js";import{je,pr,hr,gn,_n,ot}from"./vm-hands-entry-lite-004yshd1.js";import{Nr}from"./vm-hands-entry-lite-pf5qtbj5.js";import{p,at,yn,_e,we}from"./vm-hands-entry-lite-s4bharcb.js";import{v,h}from"./vm-hands-entry-lite-wx4ax7wg.js";import{a,tr,Io}from"./vm-hands-entry-lite-jev771b3.js";import{nn,y,t,k,o,d,rs,Ie,Ri,u,i,W,_,ee,s,n,on}from"./vm-hands-entry-lite-avc65bd7.js";import{se,A}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=_("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=nn(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let f=e.first_cursor-1;for(let l of e.output){if(l.cursor<=f||l.cursor>e.next_cursor)return!1;f=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Ie())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var De=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:rs(),output:u(Ri()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Ce=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=nn(Ce),Qe=W([J,De.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Bi="preview.serve.v1",Fi=43200000;var ce="preview.open.v1",de=1,dn="gid_proxy_v1",ji="egress",pn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ae=i({version:n(dn),allowed_domains:u(t().max(260).regex(pn)).max(1024)}).strict(),ke=on((e)=>H(e)!==null,"invalid workspace"),Oe=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:ke,egress:Ae.optional()}).strict(),Ui=Oe.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,f){let l=null;try{l=at(e)}catch{}yn({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?f:"binding_invalid"})}function le(e){let c=new Map;return{open(f){let l=(x)=>Y(f,e.claim.operation_id,x),C;try{C=at(f)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=C,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let I=x instanceof Error?x.message:"preview_failed";if(I!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:I})}
|
|
3
|
+
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let f of c.values())f.abort();c.clear()}}}class nt extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let f={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,f),f}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let f=Ue(Nr({},e)),l=qe(tr(e),f),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(f,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Io();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function ur(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw M("process_authority_lost");let c=be(e.claim);if(c.executing)throw M("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let f=e.journals??ze();We(f.directory,{recursive:!0,mode:448});let l=pr({runtimeDirectory:G(f.directory),previousRuntimeDirectories:(f.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let C=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:C.ino,dev:C.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:R,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=gn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[_n,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let I=!1,F=new Promise((m,S)=>{x.once("exit",(g)=>{I=!0,m(g)}),x.once("error",(g)=>{I=!0,S(g)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await hr(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw M(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ot(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let T,oe=0,ve=async(m)=>{let S=[...m.output],g={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(g))>90000&&S.length)S.shift(),g.truncated=!0,g.first_cursor=S[0]?.cursor??g.next_cursor+1;T=J.parse(g),await e.emit(T),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(I)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw M("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw M();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let g;try{q=!0,g=await N("start")}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown")throw O;g=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!I?await N("probe"):null});if(c.cancelRequested)await c.cancel(),g=await N("inspect");for(;;){if(!["starting","running"].includes(g.state))c.phase="settling",c.cancel=void 0;if(!T||T.state!==g.state||T.next_cursor!==g.nextCursor&&Date.now()-oe>=5000)await ve(g);if(!["starting","running"].includes(g.state))break;if(e.signal.aborted||I)throw M();await ue(1000);try{g=await N("inspect"),te=void 0}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown"||e.signal.aborted||I||Date.now()-(te??=Date.now())>120000)throw O}}if(!T||T.state==="uncertain")throw M();return T}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!I&&!U)ot(x,"SIGTERM");let m,S=await Promise.race([F.then((g)=>({code:g})),new Promise((g)=>{m=setTimeout(()=>g(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ot(x,"SIGKILL")}catch{}try{await F}finally{if(I)l.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let g=JSON.parse(h(P.directTerminalReceiptPath)),O=X.safeParse(g.observation);if(Object.keys(g).length===4&&g.launch_id===P.launchId&&g.fence_id===P.fenceId&&g.scope_id===l.scopeId&&O.success&&O.data.process_id===e.claim.operation_id){if(w)z();throw new nt(O.data)}}}catch(g){if(g instanceof nt)throw g}finally{if(I)l.disposeSocket()}if(S.code!==0&&!U&&q)throw M("process_cleanup_unconfirmed");if(!U&&S.code===0&&(T&&["exited","cancelled","expired"].includes(T.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function Ts(e,c){if(c.kind===ce&&e.capability===he){let C=V.get(e.operation_id);if(C?.claim===e&&C.tunnels)C.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let f=V.get(e.operation_id);if(f&&f.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Rs(e,c){V.delete(e);let f=B.get(e);if(!f||c!=="succeeded"&&!f.anyCompletion)return B.delete(e),!1;try{let l=me(f.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==f.ino||l.dev!==f.dev||!A(l)||G(f.path)!==f.path||Z(j(f.path,"owner.lock")))return!1;return Ve(f.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
|
|
4
|
+
export{Bi,Fi,dn,ji,pn,Ui,nt,ur,Ts,Rs};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{statSync as f}from"fs";import{delimiter as l,join as d}from"path";function Nt(e,o=process.env.PATH??"",i=process.env,u=process.platform){let r=u==="win32",a=e.includes("/")||r&&e.includes("\\");if(!e||a||e.includes("\x00"))return!1;let c=r?["",...(i.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";")]:[""];return o.split(l).some((t)=>{if(!t)return!1;return c.some((n)=>{if(n===void 0)return!1;try{let s=f(d(t,`${e}${n}`));if(!s.isFile())return!1;return r||(s.mode&73)!==0}catch{return!1}})})}
|
|
3
|
+
export{Nt};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-3krzmhkk.js";import{ut}from"./vm-hands-entry-lite-tdgtpx8e.js";import{qt}from"./vm-hands-entry-lite-21qpxvt8.js";import{j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{ie}from"./vm-hands-entry-lite-jev771b3.js";import{Be}from"./vm-hands-entry-lite-zp6naptr.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as q,statSync as K}from"fs";import{platform as h}from"os";import{isAbsolute as z,sep as G}from"path";import{existsSync as X}from"fs";import{createRequire as Y}from"module";var k=Be(qt)(()=>Y(import.meta.url)("bun:ffi"),X);function E(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function C(e=process.env){return k.defaultShell(e)}function M(e){return k.shellArgs(e)}function N(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var Rr=43200000,jt=ut,Or=4,Q=/^[A-Za-z0-9._:-]{1,160}$/,V=1000;function I(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(V,Math.max(1,Math.floor(e)))}function Z(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!I(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Q.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:H(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+Rr)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function ee(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+G)}function W(e,n){if(n===void 0)return e;if(!z(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=q(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!ee(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!K(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function Xo(e=process.env){if(h()==="win32")return C(e);let n=e.SHELL;if(n&&z(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function ne(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Dn(){if(h()==="win32")return E();return typeof globalThis.Bun<"u"}var re=(e)=>{if(h()==="win32")try{return N({...e,file:e.shell,args:M(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=ne()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},Ir=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function te(e){if(v.size>=Or||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function Nn(e,n={}){let o=n.now??Date.now,t=Z(e.payload,o()),c=te(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?ie(e.root,t.workspace):void 0;g=a?W(D(a.boundary)?q(a.boundary):a.boundary,a.path):W(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??Xo(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let F=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>jt)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>jt)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??re)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)F(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let J=(n.loadProxy??j)()?.url;try{i=(n.connect??Ir)(t.relay_url,J)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!I(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
|
|
3
|
+
export{Rr,jt,Or,Xo,Dn,Ir,Nn};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{g,Kr,ht,xe}from"./vm-hands-entry-lite-aj139v8j.js";import{fo}from"./vm-hands-entry-lite-5dtfehjv.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{t,i,s,n}from"./vm-hands-entry-lite-avc65bd7.js";import{createHmac as _t,createPublicKey as be,randomBytes as bt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as ke,statSync as It,unlinkSync as De,writeFileSync as Le}from"fs";import{basename as Dt,dirname as w,isAbsolute as we,join as m,resolve as Lt}from"path";var Be=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as f,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as y}from"path";var O=1,ue=16384,v=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Ut(r=process.execPath){let e=r;try{e=te(r)}catch{}return fo(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!f(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function _(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ge{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Ut(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!_(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(v),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>v)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>v)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!_(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||y(le(),".config");ht(r);let e=y(r,"ara");return Kr(e)?e:y(r,"reason")}class Dr{directory;constructor(r=_e()){this.directory=r}keyPath(){return y(this.directory,"local-device.key")}bindingPath(){return y(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!f(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!f(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!f(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>v)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(f(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>v)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!f(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(f(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!f(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ge:new Dr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Ae=1,Pe=`ARA-DEVICE-BINDING-V1
|
|
3
|
+
`;function Ee(r){return r===void 0||typeof r==="number"&&Number.isInteger(r)&&r>=1&&r<=4}function G(r,e=Date.now()){let o=B.safeParse(r);if(!o.success)return!1;let c=o.data,d=typeof c.occurredAt==="string"?Date.parse(c.occurredAt):NaN,p=typeof c.expiresAt==="string"?Date.parse(c.expiresAt):NaN;return c.kind==="permission_denied"&&["bash","read","write","edit"].includes(c.operation)&&["sandbox_policy","os_permission_unknown"].includes(c.provenance)&&Number.isFinite(d)&&d<=e&&p>e&&p>d&&p-d<=600000}function Ht(r,e,o=Date.now()){if(!r||!e||r.state!=="connected"||r.deviceId!==e.deviceId)return null;let c=Date.parse(r.lastHeartbeatAt??""),d=r.permissionRecovery;if(!(o-c>=0&&o-c<30000)||!G(d,o)||d.deviceId!==e.deviceId||d.organizationId!==e.orgId)return null;try{process.kill(r.pid,0)}catch{return null}return d}function H(r={},e=a()){let o=g({env:{...process.env,...r}}),c=r.XDG_CONFIG_HOME?.trim()||m(e,".config");return xe(c,...o==="staging"?["staging"]:[])}function Nr(r={},e=a()){return m(H(r,e),"local-device.json")}function Re(r={},e=a()){return m(H(r,e),"local-daemon.json")}function Ne(r,e){Se(w(r),{recursive:!0,mode:448}),L(w(r),448);let o=`${r}.${process.pid}.${me()}.tmp`;try{Le(o,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,{mode:384,flag:"wx"}),L(o,384),ke(o,r),L(r,384)}finally{if(z(o))De(o)}return r}function E(r){if(!z(r))return null;try{return JSON.parse(Ie(r,"utf8"))}catch{return null}}function Oe(r){if(!Array.isArray(r))return null;let e=[];for(let o of r){if(!o||typeof o!=="object")return null;let c=o;if(typeof c.id!=="string"||typeof c.label!=="string"||typeof c.path!=="string"||typeof c.pathFingerprint!=="string"||!c.permissions||typeof c.permissions.read!=="boolean"||typeof c.permissions.write!=="boolean"||typeof c.permissions.execute!=="boolean"||typeof c.permissions.discover_environment!=="boolean"||typeof c.permissions.expose_mcp!=="boolean")return null;e.push({id:c.id,label:c.label,path:c.path,pathFingerprint:c.pathFingerprint,permissions:c.permissions})}return e}function J(r,e,o=[]){let c=Object.keys(r);return e.every((d)=>Object.hasOwn(r,d))&&c.every((d)=>e.includes(d)||o.includes(d))}function Ke(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost")return null;return e.origin}catch{return null}}function Y(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r,o=Oe(e.roots),c=Ke(e.apiOrigin);if(!c||typeof e.orgId!=="string"||typeof e.deviceId!=="string"||typeof e.displayName!=="string"||typeof e.registeredAt!=="string"||!Ee(e.handsSlots)||e.worker!==void 0&&(!e.worker||!/^[a-f0-9]{64}$/.test(e.worker.configDigest)||!["persistent","ephemeral"].includes(e.worker.lifetime)||!Number.isFinite(Date.parse(e.worker.expiresAt)))||!o)return null;return{apiOrigin:c,orgId:e.orgId,deviceId:e.deviceId,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:o}}function Ce(r){return{version:A,apiOrigin:r.apiOrigin,orgId:r.orgId,deviceId:r.deviceId,devicePublicKey:r.devicePublicKey,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:r.roots.map((e)=>({id:e.id,label:e.label,path:e.path,pathFingerprint:e.pathFingerprint,permissions:{read:e.permissions.read,write:e.permissions.write,execute:e.permissions.execute,discover_environment:e.permissions.discover_environment,expose_mcp:e.permissions.expose_mcp}})),credentialStorage:P}}function X(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r;if(!J(e,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Y(e);if(!o||e.version!==A||e.credentialStorage!==P||!_(e.devicePublicKey))return null;return{version:A,...o,devicePublicKey:e.devicePublicKey,credentialStorage:P}}function Te(r){return new TextEncoder().encode(`${Pe}${JSON.stringify(Ce(r))}`)}function Ue(r){let e=Buffer.from(r,"base64url");return be({format:"jwk",key:{kty:"EC",crv:"P-256",x:e.subarray(1,33).toString("base64url"),y:e.subarray(33,65).toString("base64url")}})}function Fe(r){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new l("invalid_binding")}if(!e||typeof e!=="object"||Array.isArray(e))throw new l("invalid_binding");let o=e;if(!J(o,["version","state","signature"])||o.version!==Ae||typeof o.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test(o.signature))throw new l("invalid_binding");let c=X(o.state);if(!c)throw new l("invalid_binding");let d=!1;try{d=he("sha256",Te(c),Ue(c.devicePublicKey),Buffer.from(o.signature,"base64url"))}catch{d=!1}if(!d)throw new l("invalid_binding");return c}function Me(r){let{credentialStorage:e,...o}=r;return o}function Lr(r=Nr(),e={}){let o=E(r),c=e.proofStore??e.credentialStore??V(),d=c.loadBinding();if(!d){if(o&&typeof o==="object"&&!Array.isArray(o)&&je(o))return null;if(o!==null)throw new l("invalid_binding");return null}let p=Fe(d),W=c.loadPublicKey();if(c.privateKeyIsNonExtractable(),W!==p.devicePublicKey)throw new l("invalid_public_key");let R=X(o);if(e.repair!==!1&&(!R||JSON.stringify(R)!==JSON.stringify(p)))Ne(r,p);return Me(p)}function je(r){let e=r,o=Y(r);if(!o)return null;if(e.version===2){if(typeof e.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(e.deviceCredential)||e.deviceCredential.length>4096)return null;return{state:o,credentialSource:"plaintext-v2"}}if(e.version!==3||e.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in e)return null;return{state:o,credentialSource:"keychain-v3"}}function lt(r=Re()){let e=E(r);if(!e||typeof e!=="object")return null;let o=e;if(o.version!==1||typeof o.pid!=="number"||!Number.isInteger(o.pid)||!["starting","connected","stopped","error"].includes(o.state??"")||typeof o.startedAt!=="string"||o.lastHeartbeatAt!==void 0&&typeof o.lastHeartbeatAt!=="string"||o.lastUsedAt!==void 0&&typeof o.lastUsedAt!=="string"||o.organizationId!==void 0&&typeof o.organizationId!=="string"||o.organizationName!==void 0&&typeof o.organizationName!=="string"||o.organizationSlug!==void 0&&typeof o.organizationSlug!=="string"||o.error!==void 0&&typeof o.error!=="string"||o.reconnectingSince!==void 0&&typeof o.reconnectingSince!=="string"||o.workspace!==void 0&&typeof o.workspace!=="string")return null;if(o.permissionRecovery!==void 0&&!G(o.permissionRecovery))delete o.permissionRecovery;return o}var zt=1;function Ve(r=Nr()){return m(w(r),"local-device.proxy.json")}function j(r=Ve()){let e=E(r);if(!e||typeof e!=="object"||Array.isArray(e))return null;let o=e;if(o.version!==zt||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!we(o.caFile)))return null;return{version:zt,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}
|
|
5
|
+
export{l,Ut,Ge,Dr,Ht,Nr,Lr,lt,zt,j};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var sr=String.raw`(function(require) {
|
|
3
3
|
if (process.platform !== "win32") return null;
|
|
4
4
|
let ffi, kernel32;
|
|
5
5
|
try {
|
|
@@ -64,4 +64,4 @@ var e=String.raw`(function(require) {
|
|
|
64
64
|
},
|
|
65
65
|
};
|
|
66
66
|
})`;
|
|
67
|
-
export{
|
|
67
|
+
export{sr};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{De,Ne}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{request as Le}from"http";import{pipeline as Ce}from"stream";import{constants as te,createBrotliCompress as $e,createGzip as Me}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as We,timingSafeEqual as Re}from"crypto";import{createServer as Be}from"net";var p={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function Z(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function pe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function fe(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!Z(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(pe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function He(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function ue(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=p.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function ge(e){if(Buffer.byteLength(e)>p.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!Z(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,p.chunk,p.upload)?{messages:t.messages}:{},...L(t.window,1,p.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!pe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,p.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&ue(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&ue(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,p.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function ee(e){let t=[...e],n=new Set(t.filter(([s])=>s.toLowerCase()==="connection").flatMap(([,s])=>s.toLowerCase().split(",").map((i)=>i.trim()))),o=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return t.filter(([s])=>!o.has(s.toLowerCase())&&!n.has(s.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(s))}async function re(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),p.authorizationMs)})])}finally{clearTimeout(t)}}async function Dt(e){return await re(e)===!0}function J(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function at(e){if(!Z(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:J(e.deviceRelayUrl,"device")}}function Yi(e){if(!Z(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var be="x-preview-connection";async function he(e,t){if(t.aborted)throw Error("preview_closed");let n=We(32).toString("base64url"),o=new Set,s=!1,i=Be((c)=>{if(s||t.aborted||o.size>=p.streams*2)return c.destroy();o.add(c);let d=new AbortController;c.once("close",()=>{o.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let b=Buffer.alloc(0),m=(g)=>{b=Buffer.concat([b,g]);let w=b.indexOf(`\r
|
|
3
|
+
\r
|
|
4
|
+
`);if(w<0){if(b.length>16384)c.destroy();return}if(c.pause(),c.off("data",m),w>16384||b.length>p.upload+16384)return c.destroy();l(b,w).catch(()=>c.destroy())};c.on("data",m);async function l(g,w){let y=g.subarray(0,w).toString("latin1").split(`\r
|
|
5
|
+
`),_=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(y.shift()??"");if(!_)throw Error("preview_request_invalid");H(_[2]);let k=!1,O=0,T=[];for(let B of y){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(B);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===be){O++;let N=Buffer.from(S[2].trim());k=N.length===n.length&&Re(N,Buffer.from(n))}else if(S[1].toLowerCase()!=="host")T.push(B)}if(!k||O!==1||s||d.signal.aborted)throw Error("preview_connection_denied");let v=await e.connect(d.signal);if(s||d.signal.aborted)throw v.destroy(),Error("preview_closed");o.add(v),v.on("error",()=>c.destroy()),v.once("close",()=>{o.delete(v),c.destroy()}),c.once("close",()=>v.destroy()),c.setTimeout(0);let P=[`${_[1]} ${_[2]} HTTP/1.1`,`Host: 127.0.0.1:${v.remotePort}`,...T,"",""].join(`\r
|
|
6
|
+
`);v.write(Buffer.concat([Buffer.from(P,"latin1"),g.subarray(w+4)])),v.pipe(c),c.pipe(v),c.resume()}});await new Promise((c,d)=>{i.once("error",d),i.listen(0,"127.0.0.1",c)});let a=i.address();if(!a||typeof a==="string")throw i.close(),Error("preview_bind_failed");function u(){if(s)return;s=!0,t.removeEventListener("abort",u);for(let c of o)c.destroy();o.clear(),i.close()}if(t.addEventListener("abort",u,{once:!0}),t.aborted)u();return{port:a.port,headers:{[be]:n},close:u}}var Oe=60000,Fe=1e4,ze=5000,Ue=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function je(e,t,n,o){let s=(c)=>t.find(([d])=>d.toLowerCase()===c)?.[1],i=(c)=>o.find(([d])=>d.toLowerCase()===c)?.[1],a=Number(i("content-length")??Number.NaN);if(e!=="GET"||n!==200||s("range")!==void 0||i("content-encoding")!==void 0||!Ue.test(i("content-type")??"")||/\bno-transform\b/i.test(i("cache-control")??"")||a<1024)return null;let u=(c)=>new RegExp(`(?:^|,)\\s*${c}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test(s("accept-encoding")??"");return u("br")?"br":u("gzip")?"gzip":null}function qe(e,t){let n=e.filter(([o])=>o.toLowerCase()==="vary").map(([,o])=>o).join(", ");return[...e.filter(([o])=>!["vary","etag","content-md5"].includes(o.toLowerCase())),...e.filter(([o])=>o.toLowerCase()==="etag").map(([o,s])=>[o,s.startsWith("W/")?s:`W/${s}`]),["Content-Encoding",t],["Vary",n.split(",").some((o)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(o))?n:n?`${n}, Accept-Encoding`:"Accept-Encoding"]]}async function yn(e){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:e.jobId,port:e.port,reason_code:e.reason})}
|
|
7
|
+
`);let t=e.binding,n;try{n=J(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((o)=>{let s=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{s.terminate(),o()},p.authorizationMs*2);s.addEventListener("open",()=>{s.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),s.close(1000,`worker_refused_${e.reason}`)}),s.addEventListener("error",()=>{clearTimeout(i),o()}),s.addEventListener("close",()=>{clearTimeout(i),o()})})}async function Ke(e,t){let n=Date.now()+Fe,o;for(;;){if(!t())return"closed";let s=o??=e.refusal().finally(()=>{o=void 0}),i,a=await Promise.race([s.catch(()=>"port_unproved"),new Promise((u)=>{i=setTimeout(()=>u("port_check_timeout"),p.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((u)=>setTimeout(u,500))}}async function _e(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,o=t.expiresAtMs>Date.now()+p.lifetimeMs+ze?"binding_mismatch":await Ke(e.port,n);if(o)throw await yn({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:o}),Error("preview_not_authorized",{cause:o});let s=J(e.deviceRelayUrl,"device"),i=await he(e.port,e.signal),a;try{a=new U(s,{followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload*1.4+300000})}catch(f){throw i.close(),f}let u=new Map,c=!1,d=!1,b=0,m=!1,l,g,w,y=new Promise((f)=>{w=f}),_,k,O=new Promise((f,h)=>{_=f,k=h}),T=!1,v=(f)=>{let h=Buffer.isBuffer(f)?f:JSON.stringify(f);if(b+=Buffer.byteLength(h),!n()||d||a.readyState!==U.OPEN)return P(n()?"relay_closed":"expired");if(a.bufferedAmount>p.relayBuffered)return P("relay_backlog");if(b>p.total)return P("quota");a.send(h)};function P(f="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let h of u.values())h.stop();u.clear(),i.close(),a.close(1000,`worker_${f}`),k(Error("preview_closed")),w()}let B=()=>P("aborted"),S=setTimeout(()=>P("pair_timeout"),p.requestMs),N=setInterval(async()=>{if(!n())return P(e.signal.aborted?"aborted":"expired");if(m)return;m=!0;try{let f=l??=Promise.resolve().then(()=>e.port.check()).finally(()=>{l=void 0}),h=await re(()=>f);if(h===!1)return P("port_refused");if(h){g=void 0;return}if(Date.now()-(g??=Date.now())>Oe)return P("port_unknown");for(let E of u.values())E.stop()}finally{m=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())P(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>v({type:"hello",binding:t,messages:p.upload,window:p.window})),a.addEventListener("close",()=>P("relay_closed")),a.addEventListener("error",()=>P("relay_error")),a.addEventListener("message",(f)=>{try{if(!n()||d)return P(e.signal.aborted?"aborted":"expired");if(typeof f.data!=="string")throw Error("preview_frame_invalid");if(b+=Buffer.byteLength(f.data),b>p.total)return P("quota");let h=ge(f.data);if(!c){if(h.type!=="hello"||!He(t,h.binding))return P("binding_mismatch");c=!0,T=h.bytes===!0,clearTimeout(S),_();return}if(h.type==="hello"||h.type==="refused")return P("invalid_frame");if(h.type==="request"){D(h).catch(()=>P("invalid_request"));return}let E=u.get(h.id);if(!E)return;if(h.type==="cancel"||h.type==="end")E.stop();else if(h.type==="credit"&&E.credit)E.credit();else if(h.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>p.buffered)return E.stop();let I=z(h.data,p.upload);E.ws.send(h.binary?I:I.toString("utf8"))}else P("invalid_frame")}catch{P("invalid_frame")}});async function D(f){if(u.has(f.id)||u.size>=p.streams)return P("stream_limit");if(!n())return P(e.signal.aborted?"aborted":"expired");let h=new AbortController,E,I,q,Y=0,R=(W=!1)=>{if(!u.delete(f.id))return;clearTimeout(E),h.abort(),I?.close(1000,"preview_closed"),q?.(),v({type:W?"end":"cancel",id:f.id})},ie={stop:()=>R(),credit:()=>{Y++,q?.()}};if(u.set(f.id,ie),E=setTimeout(R,p.requestMs),!await Dt(()=>e.port.check())||!n()||h.signal.aborted)return R();let ae=H(f.path);if(f.upgrade){if(f.method!=="GET"||f.body)return R();let W=f.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${ae}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload}),ie.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),v({type:"ws",id:f.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let K=typeof A.data!=="string",M=me(A.data);if(M.length>p.upload)return R();v({type:"data",id:f.id,data:M.toString("base64"),binary:K})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let Te=z(f.body,p.upload),de=Le({hostname:"127.0.0.1",port:i.port,path:ae,method:f.method,headers:{...Object.fromEntries(ee(f.headers)),...i.headers,connection:"close"},signal:h.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let K=W.statusCode??502,M=je(f.method,f.headers,K,A),Q=M==="br"?$e({flush:te.BROTLI_OPERATION_FLUSH,params:{[te.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Me({level:6,flush:te.Z_SYNC_FLUSH}):void 0;if(v({type:"head",id:f.id,status:K,headers:ee(M?qe(A,M):A)}),clearTimeout(E),Q)Ce(W,Q,()=>{});for await(let F of Q??W){let ce=Buffer.from(F);for(let G=0;G<ce.length;G+=p.chunk){if(Y===0&&!h.signal.aborted)await new Promise((Ie)=>{q=Ie});if(q=void 0,h.signal.aborted)return;Y--;let le=ce.subarray(G,G+p.chunk);v(T?fe(f.id,le):{type:"data",id:f.id,data:le.toString("base64"),binary:!0})}}R(!0)}catch{R()}});de.on("error",()=>R()),de.end(Te)}return await O,{close:P,closed:y}}import{execFile as Ge}from"child_process";import{createRequire as Ze}from"module";import{win32 as V}from"path";var Je=250,Ve=50,Xe=250,Ye=4194304;function Pe(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Qe(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim().split(/\s+/);if(o[0]!=="TCP"||o.length<5)continue;let s=Pe(o[1]),i=Pe(o[2]),a=Number(o.at(-1));if(!s||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:s.address,localPort:s.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function er(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var ke=(e)=>new Promise((t,n)=>Ge(V.join(De("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:Ye,encoding:"utf8",windowsHide:!0,env:Ne()},(o,s)=>o?n(o):t(s)));function ne(e){let t=V.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function rr(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return o===n||o.startsWith(n.endsWith("\\")?n:`${n}\\`)}function xe(e,t,n){let o=e.cwd(n),s=o?ne(o):null;return s&&V.isAbsolute(s)&&rr(t,s)?s:null}var j;function ye(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=Ze(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,o,s;try{o=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,s=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,u=1040,c=568,d=(b,m,l)=>{let g=Buffer.alloc(l);return o.ReadProcessMemory(b,m,n(g),l,null)?g:null};return j={processes(){let b=BigInt(o.CreateToolhelp32Snapshot(a,0));if(b===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let m=Buffer.alloc(c);m.writeUInt32LE(c,0);let l=n(m),g=[];for(let w=o.Process32FirstW(b,l);w;w=o.Process32NextW(b,l)){let y=m.toString("utf16le",44,c),_=y.slice(0,y.includes("\x00")?y.indexOf("\x00"):void 0),k=m.readUInt32LE(8);if(k>0)g.push({pid:k,parentPid:m.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return g}finally{o.CloseHandle(b)}},cwd(b){let m=BigInt(o.OpenProcess(u,0,b));if(m===0n)return null;try{let l=Buffer.alloc(48);if(s.NtQueryInformationProcess(m,0,n(l),l.length,null)!==0)return null;let g=d(m,l.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),w=g?d(m,g+0x38n,16):null,y=w?.readUInt16LE(0)??0;if(!w||y===0||y%2!==0)return null;return d(m,w.readBigUInt64LE(8),y)?.toString("utf16le")??null}finally{o.CloseHandle(m)}}},j}function oe(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function Se(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Qe(n)}async function Qi(e,t=ye()){let n=oe(t),o=ne(e),s=[];for(let i of n.processes()){if(s.length>=Je)break;let a=xe(n,o,i.pid);if(a)s.push({pid:i.pid,command:i.command,cwd:V.relative(o,a)||"."})}return{processes:s}}async function eo(e,t=ye(),n=ke){let o=oe(t),s=ne(e),i=(await Se(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:er(d)})).sort((d,b)=>d.pid-b.pid||d.port-b.port||(d.address<b.address?-1:d.address>b.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,Ve),u=new Set(a.filter((d)=>xe(o,s,d)!==null));if(u.size===0)return{ports:[]};let c=new Map(o.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>u.has(d.pid)).slice(0,Xe).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function ve(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let s of e)if(!n.has(s.pid)&&n.has(s.parentPid)&&s.pid!==s.parentPid)n.add(s.pid),o=!0}return n}function tr(e,t,n,o){let s=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==o)return[];let a=i.listening&&(s(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),u=!i.listening&&s(i.localAddress)&&s(i.remoteAddress);if(!a&&!u)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:o,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function Ee(e,t,n=ye(),o=ke){let s=oe(n),i=ve(s.processes(),e),a=await Se(o,1000),u=ve(s.processes(),e);return tr(a,new Set([...i].filter((c)=>u.has(c))),e,t)}import{execFile as nr}from"child_process";import{readFile as or,readdir as sr,readlink as ir}from"fs/promises";import{connect as ar}from"net";import{setTimeout as dr}from"timers/promises";var cr={directory:sr,text:(e)=>or(e,"utf8"),link:ir};class se extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new se(e),X="preview_listener_unproved",Ae="00000000000000000000000001000000";async function lr(e,t,n=cr){let o=new Map;for(let a of["tcp","tcp6"]){let u=await n.text(`/proc/net/${a}`);if(u.length>4194304)throw x();for(let c of u.split(`
|
|
8
|
+
`).slice(1)){let d=c.trim().split(/\s+/);if(d.length<10||!["0A","01"].includes(d[3]))continue;let[b,m]=d[1].split(":"),[l,g]=d[2].split(":");if(Number.parseInt(m,16)!==t)continue;let w=(k)=>k==="0100007F"||k==="0000000000000000FFFF00000100007F"||k===Ae,y=d[3]==="0A";if(!(w(b)||y&&/^0+$/.test(b??"")))continue;if(!y&&!w(l))continue;let _=d[9];if(!/^[1-9][0-9]*$/.test(_))continue;o.set(_,{kernelId:_,port:t,peerPort:y?null:Number.parseInt(g,16),state:y?"listen":"established",host:b===Ae?"::1":"127.0.0.1"})}}let s=await n.directory("/proc");if(s.length>8192)throw x();let i=[];for(let a of s){if(!/^[1-9][0-9]*$/.test(a))continue;try{let u=await n.text(`/proc/${a}/stat`),c=u.slice(u.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(c[2])!==e)continue;let d=await n.directory(`/proc/${a}/fd`);if(d.length>1024)throw x();let b=[];for(let g of d){if(!/^[0-9]+$/.test(g))continue;let w=await n.link(`/proc/${a}/fd/${g}`).catch(()=>""),y=/^socket:\[([0-9]+)\]$/.exec(w)?.[1],_=y?o.get(y):void 0;if(_)b.push({..._,pid:Number(a),processGroupId:e,descriptor:g})}let m=await n.text(`/proc/${a}/stat`),l=m.slice(m.lastIndexOf(")")+2).trim().split(/\s+/);if(c[19]===l[19]&&c[2]===l[2])i.push(...b)}catch(u){if(u instanceof Error&&u.message==="preview_port_ownership_unproved")throw u}}return i}function ur(e,t,n){if(e.length>2097152)throw x();let o=0,s=0,i="",a="",u="",c="",d=[],b=()=>{if(o<1||s!==t||!/^\d+$/.test(i)||!/^0x[0-9a-f]+$/i.test(a))return;let m=c==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((g)=>u===`${g}:${n}`),l=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${n}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(u);if(m||c==="ESTABLISHED"&&l)d.push({pid:o,processGroupId:s,descriptor:i,kernelId:a,state:m?"listen":"established",port:n,peerPort:m?null:Number(l[1]),host:u.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let m of e.split(/[\0\n]/)){let l=m.slice(1);if(m[0]==="p")b(),o=Number(l),s=0,i=a=u=c="";else if(m[0]==="g")s=Number(l);else if(m[0]==="f")b(),i=l,a=u=c="";else if(m[0]==="d")a=l;else if(m[0]==="n")u=l;else if(m.startsWith("TST="))c=m.slice(4)}return b(),d}async function pr(e,t){if(process.platform==="linux")return lr(e,t);if(process.platform==="win32")return Ee(e,t);if(process.platform!=="darwin")throw x();let n=await new Promise((o,s)=>nr("/usr/sbin/lsof",["-nP","-a","-g",String(e),`-iTCP:${t}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(i,a)=>i?s(x()):o(a)));return ur(n,e,t)}function we(e,t={}){let n=C(e.binding),o=t.inspectSockets??pr,s=t.monotonicNow??(()=>performance.now());async function i(){let l=()=>{if(Date.now()>=n.expiresAtMs)throw x("binding_expired");if(e.deniedPorts.has(n.port))throw x("port_denied")};l();let g=await e.readCurrentJob(),w=g?.job,y=w?.process;if(l(),!g)throw x("server_stopped");if(!He(n,g.binding)||w?.jobId!==n.jobId)throw x("binding_changed");if(w.state!=="running"||w.finishedAtMs!==null||w.leaseExpiresAtMs<n.expiresAtMs)throw x("job_not_running");if(!y||y.pid<1||y.pid!==y.processGroupId||y.executorLaunchId!==g.executorLaunchId)throw x("process_unproved");return{pid:y.pid,launch:y.executorLaunchId,started:w.startedAtMs}}let a,u;async function c(){let l=await i(),g=await o(l.pid,n.port).catch(()=>{throw Error(X)}),w=await i();if(l.pid!==w.pid||l.launch!==w.launch||l.started!==w.started)throw x("job_restarted");return g}async function d(l){for(;;){if(u&&u.startedAt>=l)return u.sockets;if(a&&a.startedAt>=l)return await a.sockets;if(a){await a.sockets.catch(()=>{});continue}let g={startedAt:s(),sockets:c()};a=g;try{let w=await g.sockets;if(!u||u.startedAt<=g.startedAt)u={startedAt:g.startedAt,sockets:w};return w}finally{if(a===g)a=void 0}}}async function b(l=()=>{},g=s()){l();let w=await d(g);if(l(),Date.now()>=n.expiresAtMs)throw x("binding_expired");if(!w.some((y)=>y.state==="listen"))throw Error(X);return w}async function m(){try{return await b(()=>{},s()-1000),null}catch(l){if(l instanceof Error&&l.message===X)return"listener_unproved";return l instanceof se?l.code:"port_unproved"}}return{refusal:m,async check(){let l=await m();if(l==="listener_unproved")throw Error(X);return l===null},async connect(l){if(l.aborted)throw x();let g=s()+2000,w=new AbortController,y=new Promise((P)=>w.signal.addEventListener("abort",()=>P(null),{once:!0})),_,k=()=>{w.abort(),_?.destroy()},O=setTimeout(k,2000);l.addEventListener("abort",k,{once:!0});let T=()=>{if(w.signal.aborted||l.aborted||s()>=g||_?.destroyed)throw k(),x()};async function v(P){T();let B=await Promise.race([P().then((S)=>({value:S})),y]);if(T(),!B)throw x();return B.value}try{let P=await v(()=>b(T,s()-1000));T();let B=P.some((f)=>f.state==="listen"&&f.host==="127.0.0.1")?"127.0.0.1":"::1",S=ar({host:B,port:n.port,signal:l});_=S,S.once("close",k),await v(()=>new Promise((f,h)=>{S.once("connect",f),S.once("error",h)}));let N=S.localPort;if(!N)throw x();let D=s();while(!(await v(()=>b(T,D))).some((f)=>f.state==="established"&&f.peerPort===N))await v(()=>dr(Math.min(20,Math.max(1,g-s())),void 0,{signal:w.signal})),D=s();return T(),S}catch(P){throw k(),P}finally{clearTimeout(O),l.removeEventListener("abort",k),_?.off("close",k),w.abort()}}}}
|
|
9
|
+
export{p,He,Dt,at,Yi,yn,_e,ye,Qi,eo,we};
|