@reason-machines/cli-linux-arm64 0.2.406 → 0.2.408

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/THIRD_PARTY_NOTICES.txt +8 -7
  2. package/bin/reason +2 -2
  3. package/bin/runtime/srt/sandbox-runtime.mjs +52 -52
  4. package/bin/vm-hands/api-8d760ppa.js +2 -0
  5. package/bin/vm-hands/api-credentials-eea1g4aw.js +2 -0
  6. package/bin/vm-hands/connect-cli-m8xafyn5.js +2 -0
  7. package/bin/vm-hands/custom-endpoint-device-nfjhs9fv.js +2 -0
  8. package/bin/vm-hands/desktop-account-rx4ajy2j.js +2 -0
  9. package/bin/vm-hands/device-workspace-n9tn4bzw.js +2 -0
  10. package/bin/vm-hands/fsevents-vgg0dny6.js +2 -0
  11. package/bin/vm-hands/hands-worker-source-yxsap3qk.js +2 -0
  12. package/bin/vm-hands/index-kx10kwyx.js +12818 -0
  13. package/bin/vm-hands/install-receipt-rmsjtfqy.js +2 -0
  14. package/bin/vm-hands/local-automation-7qcnytj6.js +2 -0
  15. package/bin/vm-hands/local-capabilities-hchsc804.js +2 -0
  16. package/bin/vm-hands/local-desktop-users-c6858avg.js +2 -0
  17. package/bin/vm-hands/local-display-mac-zmbp9z4c.js +2 -0
  18. package/bin/vm-hands/local-display-session-7bgp7gvf.js +2 -0
  19. package/bin/vm-hands/local-pty-session-8m175hqx.js +2 -0
  20. package/bin/vm-hands/managed-runtime-nkmg5s5h.js +2 -0
  21. package/bin/vm-hands/network-contract-qt2s82ap.js +2 -0
  22. package/bin/vm-hands/package-11mkdcmn.js +2 -0
  23. package/bin/vm-hands/permissions-67xv16a5.js +2 -0
  24. package/bin/vm-hands/reason-hands-protocol-r356wr4t.js +2 -0
  25. package/bin/vm-hands/serve-service-4n7e0b08.js +2 -0
  26. package/bin/vm-hands/status-e7r62q4e.js +10 -0
  27. package/bin/vm-hands/version-vdev7tyq.js +2 -0
  28. package/bin/vm-hands/vm-hands-entry-lite-0n2f3kx7.js +3 -0
  29. package/bin/vm-hands/vm-hands-entry-lite-4aejamqr.js +3 -0
  30. package/bin/vm-hands/vm-hands-entry-lite-4geps3jz.js +5 -0
  31. package/bin/vm-hands/{vm-hands-entry-lite-xqve205b.js → vm-hands-entry-lite-51qvfk93.js} +2 -2
  32. package/bin/vm-hands/vm-hands-entry-lite-5p5h1eng.js +3 -0
  33. package/bin/vm-hands/vm-hands-entry-lite-6p9c8nhf.js +3 -0
  34. package/bin/vm-hands/vm-hands-entry-lite-6whxyzz2.js +52 -0
  35. package/bin/vm-hands/vm-hands-entry-lite-762fbns7.js +14 -0
  36. package/bin/vm-hands/vm-hands-entry-lite-79s23abx.js +7 -0
  37. package/bin/vm-hands/vm-hands-entry-lite-8bzqc4xa.js +2 -0
  38. package/bin/vm-hands/vm-hands-entry-lite-8evzzh7v.js +112 -0
  39. package/bin/vm-hands/vm-hands-entry-lite-8gtgr399.js +4 -0
  40. package/bin/vm-hands/vm-hands-entry-lite-9ym3sx81.js +2 -0
  41. package/bin/vm-hands/vm-hands-entry-lite-dkcm3hyn.js +3 -0
  42. package/bin/vm-hands/vm-hands-entry-lite-dq1m5ykp.js +5 -0
  43. package/bin/vm-hands/vm-hands-entry-lite-e5hbehqn.js +250 -0
  44. package/bin/vm-hands/vm-hands-entry-lite-et2bh990.js +458 -0
  45. package/bin/vm-hands/vm-hands-entry-lite-fyjzrvj5.js +3 -0
  46. package/bin/vm-hands/vm-hands-entry-lite-g3ja0c3y.js +2 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-gc7c22pq.js +2 -0
  48. package/bin/vm-hands/{vm-hands-entry-lite-wer0qzxg.js → vm-hands-entry-lite-hcw5tk5d.js} +2 -2
  49. package/bin/vm-hands/vm-hands-entry-lite-hee1h411.js +105 -0
  50. package/bin/vm-hands/{vm-hands-entry-lite-dsh32j5a.js → vm-hands-entry-lite-hfmydph9.js} +5 -9
  51. package/bin/vm-hands/vm-hands-entry-lite-hzn1hf0p.js +3 -0
  52. package/bin/vm-hands/vm-hands-entry-lite-mvx29q2q.js +3 -0
  53. package/bin/vm-hands/vm-hands-entry-lite-mw0gzbds.js +6 -0
  54. package/bin/vm-hands/vm-hands-entry-lite-pmcz7j7t.js +3 -0
  55. package/bin/vm-hands/vm-hands-entry-lite-pn92kh7b.js +3 -0
  56. package/bin/vm-hands/vm-hands-entry-lite-ppytc9k7.js +3 -0
  57. package/bin/vm-hands/vm-hands-entry-lite-qffs74x1.js +540 -0
  58. package/bin/vm-hands/vm-hands-entry-lite-qy9xg6em.js +3 -0
  59. package/bin/vm-hands/vm-hands-entry-lite-rwr09j4w.js +3 -0
  60. package/bin/vm-hands/vm-hands-entry-lite-saqdrc2w.js +3 -0
  61. package/bin/vm-hands/vm-hands-entry-lite-snmxxhza.js +3 -0
  62. package/bin/vm-hands/{vm-hands-entry-lite-fbpxs065.js → vm-hands-entry-lite-t7an5zg2.js} +2 -2
  63. package/bin/vm-hands/vm-hands-entry-lite-v3xznxcw.js +4 -0
  64. package/bin/vm-hands/vm-hands-entry-lite-w8kc4jtb.js +3 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-w9ckj5k4.js +5 -0
  66. package/bin/vm-hands/{vm-hands-entry-lite-jcd21jpm.js → vm-hands-entry-lite-wd576mgy.js} +54 -54
  67. package/bin/vm-hands/vm-hands-entry-lite-wf7ksh4e.js +9 -0
  68. package/bin/vm-hands/vm-hands-entry-lite-wyh6dp1t.js +4 -0
  69. package/bin/vm-hands/vm-hands-entry-lite-ym1djztp.js +42 -0
  70. package/bin/vm-hands/vm-hands-entry-lite-zg3b0c08.js +3 -0
  71. package/bin/vm-hands/vm-hands-entry-lite-zn0v259d.js +65 -0
  72. package/bin/vm-hands/vm-hands-entry-lite.js +3 -1
  73. package/bin/vm-hands/vm-hands-executor-79av9nam.js +11 -0
  74. package/bin/vm-hands/vm-hands-op-runner-kh1myd15.js +2 -0
  75. package/bin/vm-hands/vm-hands-runtime-yacvv937.js +4 -0
  76. package/bin/vm-hands/worker-sandbox-x8dsz324.js +2 -0
  77. package/package.json +1 -1
  78. package/bin/vm-hands/api-credentials-4e2gypqj.js +0 -2
  79. package/bin/vm-hands/api-f48wa4ym.js +0 -2
  80. package/bin/vm-hands/ask-relay-nydkgmvq.js +0 -8
  81. package/bin/vm-hands/connect-cli-10axcfnk.js +0 -2
  82. package/bin/vm-hands/custom-endpoint-device-8h95wy87.js +0 -2
  83. package/bin/vm-hands/desktop-account-2kkxwv1y.js +0 -2
  84. package/bin/vm-hands/device-workspace-nzz3kd5t.js +0 -2
  85. package/bin/vm-hands/hands-worker-source-as5wepvk.js +0 -2
  86. package/bin/vm-hands/index-2kk983b8.js +0 -12818
  87. package/bin/vm-hands/install-receipt-e6s355j1.js +0 -2
  88. package/bin/vm-hands/local-automation-nr2dg0t3.js +0 -2
  89. package/bin/vm-hands/local-capabilities-ep1d24ne.js +0 -2
  90. package/bin/vm-hands/local-desktop-users-sevkfkye.js +0 -2
  91. package/bin/vm-hands/local-display-mac-jzc0g5ge.js +0 -2
  92. package/bin/vm-hands/local-display-session-0vyd74rj.js +0 -2
  93. package/bin/vm-hands/local-pty-session-fe6jz2zy.js +0 -2
  94. package/bin/vm-hands/managed-runtime-5zrdx8xk.js +0 -2
  95. package/bin/vm-hands/network-contract-9smga6kn.js +0 -2
  96. package/bin/vm-hands/package-qjr5q0bp.js +0 -2
  97. package/bin/vm-hands/permissions-04sm9aq9.js +0 -2
  98. package/bin/vm-hands/reason-hands-protocol-5fhd49en.js +0 -2
  99. package/bin/vm-hands/serve-service-hd0k7s2x.js +0 -2
  100. package/bin/vm-hands/status-n3x94yjb.js +0 -96
  101. package/bin/vm-hands/version-aec5t9wd.js +0 -2
  102. package/bin/vm-hands/vm-hands-entry-lite-0c4nxpza.js +0 -3
  103. package/bin/vm-hands/vm-hands-entry-lite-159860ns.js +0 -52
  104. package/bin/vm-hands/vm-hands-entry-lite-1sc3wc94.js +0 -3
  105. package/bin/vm-hands/vm-hands-entry-lite-2nec0vk1.js +0 -3
  106. package/bin/vm-hands/vm-hands-entry-lite-40nkzw38.js +0 -3
  107. package/bin/vm-hands/vm-hands-entry-lite-5rkakg10.js +0 -4
  108. package/bin/vm-hands/vm-hands-entry-lite-5tgm1m3h.js +0 -458
  109. package/bin/vm-hands/vm-hands-entry-lite-69ray4x8.js +0 -6
  110. package/bin/vm-hands/vm-hands-entry-lite-6berk108.js +0 -3
  111. package/bin/vm-hands/vm-hands-entry-lite-72nn2b4n.js +0 -3
  112. package/bin/vm-hands/vm-hands-entry-lite-8f3px72v.js +0 -3
  113. package/bin/vm-hands/vm-hands-entry-lite-8gjrr6hg.js +0 -3
  114. package/bin/vm-hands/vm-hands-entry-lite-8tcnbfnm.js +0 -5
  115. package/bin/vm-hands/vm-hands-entry-lite-9vf97byd.js +0 -4
  116. package/bin/vm-hands/vm-hands-entry-lite-ac8sdh78.js +0 -105
  117. package/bin/vm-hands/vm-hands-entry-lite-bmywbwj4.js +0 -9
  118. package/bin/vm-hands/vm-hands-entry-lite-c60v3v0v.js +0 -540
  119. package/bin/vm-hands/vm-hands-entry-lite-er3nrbb9.js +0 -3
  120. package/bin/vm-hands/vm-hands-entry-lite-g1wjmmr9.js +0 -346
  121. package/bin/vm-hands/vm-hands-entry-lite-g5c9ec33.js +0 -5
  122. package/bin/vm-hands/vm-hands-entry-lite-h0y0xv5f.js +0 -3
  123. package/bin/vm-hands/vm-hands-entry-lite-h9t84ekh.js +0 -3
  124. package/bin/vm-hands/vm-hands-entry-lite-hd4a0a6f.js +0 -112
  125. package/bin/vm-hands/vm-hands-entry-lite-hepppjp0.js +0 -3
  126. package/bin/vm-hands/vm-hands-entry-lite-hye6r7dy.js +0 -3
  127. package/bin/vm-hands/vm-hands-entry-lite-jw5y1aa5.js +0 -3
  128. package/bin/vm-hands/vm-hands-entry-lite-ky0w7t09.js +0 -42
  129. package/bin/vm-hands/vm-hands-entry-lite-mapxp682.js +0 -4
  130. package/bin/vm-hands/vm-hands-entry-lite-np1fcr2t.js +0 -5
  131. package/bin/vm-hands/vm-hands-entry-lite-nqvb7a2m.js +0 -3
  132. package/bin/vm-hands/vm-hands-entry-lite-q4tcfj61.js +0 -3
  133. package/bin/vm-hands/vm-hands-entry-lite-qpba4sxt.js +0 -3
  134. package/bin/vm-hands/vm-hands-entry-lite-r2xmr627.js +0 -4
  135. package/bin/vm-hands/vm-hands-entry-lite-swwb5mp2.js +0 -3
  136. package/bin/vm-hands/vm-hands-entry-lite-vr38bh6k.js +0 -66
  137. package/bin/vm-hands/vm-hands-entry-lite-vwpraybq.js +0 -251
  138. package/bin/vm-hands/vm-hands-entry-lite-wa261sf8.js +0 -3
  139. package/bin/vm-hands/vm-hands-entry-lite-wn4gvb8w.js +0 -11
  140. package/bin/vm-hands/vm-hands-entry-lite-yg5h9mhm.js +0 -7
  141. package/bin/vm-hands/vm-hands-entry-lite-yqrmr2c8.js +0 -5
  142. package/bin/vm-hands/vm-hands-entry-lite-z5912r1q.js +0 -3
  143. package/bin/vm-hands/vm-hands-executor-m1jwswd0.js +0 -11
  144. package/bin/vm-hands/vm-hands-op-runner-6amaw4zn.js +0 -2
  145. package/bin/vm-hands/vm-hands-runtime-jt4j6362.js +0 -4
  146. package/bin/vm-hands/worker-sandbox-p242st5d.js +0 -2
@@ -1,251 +0,0 @@
1
- // @bun
2
- import{Gg as k0}from"./vm-hands-entry-lite-1sc3wc94.js";import{Xg as f0}from"./vm-hands-entry-lite-yqrmr2c8.js";import{bh as uq}from"./vm-hands-entry-lite-9vf97byd.js";import{qj as cq}from"./vm-hands-entry-lite-bmywbwj4.js";import{xj as i}from"./vm-hands-entry-lite-hye6r7dy.js";import{ek as _,hk as g0,kk as h0,lk as G8,mk as y0,ok as l8,rk as G0,tk as A0}from"./vm-hands-entry-lite-hd4a0a6f.js";import{vk as H0}from"./vm-hands-entry-lite-r2xmr627.js";import{Rk as K}from"./vm-hands-entry-lite-40nkzw38.js";import{execFile as f1,spawn as I0}from"child_process";import{randomBytes as g1}from"crypto";import{chmodSync as h1,existsSync as p0,lstatSync as k1,mkdirSync as I1,readFileSync as p1,rmSync as v1,writeFileSync as Wq}from"fs";import{connect as u1}from"net";import{join as $}from"path";var Gq="./desktop-wallpaper-0pjhgyfk.jpg";var Aq="./dock-browser-afp005mt.png";var Sq="./dock-files-rywdm96b.png";var Vq="./dock-terminal-s41cj1jp.png";var Fq=`# 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
- `;var Q8=32,Kq=76;function qx(q){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>${Q8}</x><y>${Q8}</y></position>
67
- <size><width>${q.width-Q8*2}</width><height>${q.height-Q8-Kq}</height></size>
68
- </application>
69
- </applications>
70
- </openbox_config>`}var xx=`# 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
- `,Qx=`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
- `,Xx="/tmp/ara-dock-browser.png",Px=`[Desktop Entry]
104
- Name=Chrome
105
- Exec=chromium --no-sandbox %U
106
- Icon=${Xx}
107
- Type=Application
108
- Categories=Network;WebBrowser;
109
- `,bx=`[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
- `,Jx=`[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 zq={"wallpaper.jpg":Gq,"dock-browser.png":Aq,"dock-terminal.png":Vq,"dock-files.png":Sq},Wx=Fq,Nx='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function Mq(q){let x=(J)=>J.replaceAll("DISPLAY=:99",`DISPLAY=${q.display}`).replaceAll("/tmp/ara-",`${q.root}/ara-`),Q=new Set(q.absent??[]),P=xx.split(`
122
- `).filter((J)=>!(Q.has("terminal")&&J.endsWith("/ara-terminal.desktop"))&&!(Q.has("files")&&J.endsWith("/ara-files.desktop"))).join(`
123
- `);return{files:{"openbox/rc.xml":qx(q.screen),"tint2/tint2rc":x(P),"picom/picom.conf":Qx,...Q.has("terminal")?{}:{"ara-terminal.desktop":x(bx)},...Q.has("files")?{}:{"ara-files.desktop":x(Jx)},"ara-chromium.desktop":x(Px).replace("chromium --no-sandbox %U",q.browserExec),"ara-set-root-wallpaper.py":Wx},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"; }',Nx,'[ ! -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']}}import{createHash as lq}from"crypto";import{once as Gx}from"events";import{createWriteStream as Ax,existsSync as Sx,mkdirSync as Vx,mkdtempSync as k9,readFileSync as C8,readdirSync as I9,renameSync as Fx,realpathSync as Kx,rmSync as zx,statSync as r8,writeFileSync as Mx}from"fs";import{delimiter as v9,dirname as m8,join as Z}from"path";import{finished as Yx}from"stream/promises";var g8="omljlfpmafedpplnpkkahegadhkimdje",D9="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";function y9(q){if(!q||typeof q!=="object"||Array.isArray(q)||!("version"in q)||q.version!==1||!("status"in q))return null;if(q.status==="unavailable")return Object.keys(q).length===2?{version:1,status:"unavailable"}:null;if(q.status!=="connected"||Object.keys(q).length!==5||!("deviceId"in q)||typeof q.deviceId!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(q.deviceId)||!("apiOrigin"in q)||typeof q.apiOrigin!=="string"||q.apiOrigin.length>2048||!("managedRootIds"in q)||!Array.isArray(q.managedRootIds)||q.managedRootIds.length>32)return null;let x=[];for(let Q of q.managedRootIds){if(typeof Q!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(Q))return null;x.push(Q)}try{let Q=new URL(q.apiOrigin);if(Q.origin!==q.apiOrigin||Q.username||Q.password||!(Q.protocol==="https:"||Q.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(Q.hostname)))return null}catch{return null}return{version:1,status:"connected",deviceId:q.deviceId,apiOrigin:q.apiOrigin,managedRootIds:x}}var h={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},v={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var X8={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${h.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${h.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${h.obu.version}/open-browser-use-chrome-extension-${h.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},d="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as k8}from"child_process";import{createRequire as Ux}from"module";import{join as Lx}from"path";var jx=30000,Bx=1048576;function I8(){return process.env.SystemRoot??"C:\\Windows"}function Cx(){return Lx(I8(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var Rx=String.raw`
124
- $ErrorActionPreference = "Stop"
125
- Add-Type -TypeDefinition @"
126
- using System;
127
- using System.Runtime.InteropServices;
128
- public static class ReasonInput {
129
- [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
130
- [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
131
- [StructLayout(LayoutKind.Explicit)] public struct UNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
132
- [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public UNION u; }
133
- [DllImport("user32.dll")] static extern uint SendInput(uint count, INPUT[] inputs, int size);
134
- [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
135
- [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
136
- [DllImport("user32.dll")] static extern uint MapVirtualKey(uint code, uint type);
137
- [DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
138
- static void Send(INPUT input) { SendInput(1, new INPUT[] { input }, Marshal.SizeOf(typeof(INPUT))); }
139
- public static void Mouse(uint flags, int x, int y, int data) {
140
- INPUT input = new INPUT(); input.type = 0;
141
- input.u.mi.dx = x; input.u.mi.dy = y; input.u.mi.mouseData = data; input.u.mi.dwFlags = flags; Send(input);
142
- }
143
- public static void Key(ushort vk, ushort unit, uint flags) {
144
- INPUT input = new INPUT(); input.type = 1;
145
- input.u.ki.wVk = vk; input.u.ki.wScan = vk != 0 ? (ushort)MapVirtualKey(vk, 0) : unit; input.u.ki.dwFlags = flags; Send(input);
146
- }
147
- }
148
- "@
149
- [void][ReasonInput]::SetProcessDPIAware()
150
- $width = [ReasonInput]::GetSystemMetrics(0)
151
- $height = [ReasonInput]::GetSystemMetrics(1)
152
- $session = [Diagnostics.Process]::GetCurrentProcess().SessionId
153
- [Console]::Out.WriteLine('{"session":' + $session + ',"width":' + $width + ',"height":' + $height + '}')
154
- [Console]::Out.Flush()
155
- $mode = "__MODE__"
156
- if ($mode -eq "probe") { exit 0 }
157
- if ($mode -eq "clipboard") {
158
- # Only changes made during this pairing: never export the initial clipboard.
159
- $parent = Get-Process -Id __PARENT__
160
- $last = [ReasonInput]::GetClipboardSequenceNumber()
161
- while (-not $parent.HasExited) {
162
- Start-Sleep -Milliseconds 100
163
- $count = [ReasonInput]::GetClipboardSequenceNumber()
164
- if ($count -eq $last) { continue }
165
- $last = $count
166
- try { $text = Get-Clipboard -Raw } catch { continue }
167
- if (-not $text) { continue }
168
- $bytes = [Text.Encoding]::UTF8.GetBytes($text)
169
- if ($bytes.Length -gt __MAX_TEXT_BYTES__) { continue }
170
- [Console]::Out.WriteLine("c " + [Convert]::ToBase64String($bytes))
171
- [Console]::Out.Flush()
172
- }
173
- exit 0
174
- }
175
- $scaleX = 65535.0 / [Math]::Max(1, $width - 1)
176
- $scaleY = 65535.0 / [Math]::Max(1, $height - 1)
177
- while ($null -ne ($line = [Console]::In.ReadLine())) {
178
- $n = $line.Split(" ")
179
- try {
180
- switch ($n[0]) {
181
- "p" { [ReasonInput]::Mouse(0x8001, [int]([int]$n[1] * $scaleX), [int]([int]$n[2] * $scaleY), 0) }
182
- "b" { [ReasonInput]::Mouse([uint32]$n[1], 0, 0, [int]$n[2]) }
183
- "k" { [ReasonInput]::Key([uint16]$n[1], [uint16]$n[2], [uint32]$n[3]) }
184
- "c" { Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($n[1]))) }
185
- }
186
- } catch { [Console]::Error.WriteLine("input: $_") }
187
- }
188
- `;function p8(q){let x=Rx.replace("__MODE__",q).replace("__PARENT__",String(process.pid)).replace("__MAX_TEXT_BYTES__",String(_));return[Cx(),["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(x,"utf16le").toString("base64")]]}var Dx=["USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP","PSModuleAnalysisCachePath"];function v8(){let q=Dx.flatMap((x)=>process.env[x]?[[x,process.env[x]]]:[]);return{...Object.fromEntries(q),SystemRoot:I8(),windir:I8()}}function Hq(q){let x;try{x=JSON.parse(q)}catch{return null}if(!x||typeof x!=="object")return null;let Q=x,P=(X,b)=>typeof X==="number"&&Number.isSafeInteger(X)&&X>=b;return P(Q.session,0)&&P(Q.width,1)&&P(Q.height,1)?{session:Q.session,width:Q.width,height:Q.height}:null}function fq(){return new Promise((q)=>{let x=k8(...p8("probe"),{env:v8(),stdio:["ignore","pipe","ignore"],windowsHide:!0}),Q="",P=setTimeout(()=>{x.kill("SIGKILL"),q(null)},jx);x.stdout.setEncoding("utf8").on("data",(X)=>{Q+=X}),x.once("error",()=>{clearTimeout(P),q(null)}),x.once("close",()=>{clearTimeout(P),q(Hq(Q.split(/\r?\n/)[0]??""))})})}var P8;function gq(){if(P8!==void 0)return P8;if(process.platform!=="win32")return P8=!1;try{let q=Ux(import.meta.url)("bun:ffi"),{symbols:x}=q.dlopen("kernel32.dll",{GetCurrentProcessId:{args:[],returns:q.FFIType.u32},ProcessIdToSessionId:{args:[q.FFIType.u32,q.FFIType.ptr],returns:q.FFIType.i32}}),Q=new Uint32Array(1);return P8=x.ProcessIdToSessionId(x.GetCurrentProcessId(),Q)!==0&&Q[0]>0}catch{return P8=!1}}var Yq=[{bit:1,down:2,up:4},{bit:2,down:32,up:64},{bit:4,down:8,up:16}],wq=2048,_q=4096,Tx=[[8,wq,120],[16,wq,-120],[32,_q,-120],[64,_q,120]],$q=1,h8=2,Zx=4,yx=new Set([65505,65506]),Oq=new Set([65507,65508,65511,65512,65513,65514,65027,65515,65516]),Eq=new Map([[65505,[160,!1]],[65506,[161,!1]],[65507,[162,!1]],[65508,[163,!0]],[65511,[164,!1]],[65512,[165,!0]],[65513,[164,!1]],[65514,[165,!0]],[65027,[165,!0]],[65515,[91,!0]],[65516,[92,!0]],[65288,[8,!1]],[65289,[9,!1]],[65056,[9,!1]],[65293,[13,!1]],[65307,[27,!1]],[65535,[46,!0]],[65379,[45,!0]],[65360,[36,!0]],[65367,[35,!0]],[65365,[33,!0]],[65366,[34,!0]],[65361,[37,!0]],[65362,[38,!0]],[65363,[39,!0]],[65364,[40,!0]],[65383,[93,!0]],[65509,[20,!1]],[65299,[19,!1]],[65300,[145,!1]],[65377,[44,!0]],[65407,[144,!0]],[32,[32,!1]],[65421,[13,!0]],[65408,[32,!1]],[65450,[106,!1]],[65451,[107,!1]],[65452,[108,!1]],[65453,[109,!1]],[65454,[110,!1]],[65455,[111,!0]],[65429,[36,!1]],[65430,[37,!1]],[65431,[38,!1]],[65432,[39,!1]],[65433,[40,!1]],[65434,[33,!1]],[65435,[34,!1]],[65436,[35,!1]],[65438,[45,!1]],[65439,[46,!1]],...Array.from({length:10},(q,x)=>[65456+x,[96+x,!1]]),...Array.from({length:24},(q,x)=>[65470+x,[112+x,!1]])]);class hq{x=-1;y=-1;mask=0;held=new Set;pressed=new Set;pointer(q,x,Q){let P=[];if(q!==this.x||x!==this.y)this.x=q,this.y=x,P.push(`p ${q} ${x}`);for(let X of Yq){let b=(this.mask&X.bit)!==0,J=(Q&X.bit)!==0;if(b!==J)P.push(`b ${J?X.down:X.up} 0`)}for(let[X,b,J]of Tx)if(!(this.mask&X)&&Q&X)P.push(`b ${b} ${J}`);return this.mask=Q,P}key(q,x){let Q=q?0:h8;if(yx.has(x)||Oq.has(x))if(q)this.held.add(x);else this.held.delete(x);let P=Eq.get(x);if(P)return[`k ${P[0]} 0 ${Q|(P[1]?$q:0)}`];let X=x<256?x:(x&4278190080)===16777216?x&16777215:0,b=String.fromCharCode(X),J=[...this.held].some((T)=>Oq.has(T)),N=/^[A-Za-z0-9]$/.test(b)?b.toUpperCase().charCodeAt(0):0;if(N&&(q?J:this.pressed.has(N))){if(q)this.pressed.add(N);else this.pressed.delete(N);return[`k ${N} 0 ${Q}`]}if(X<33||X>=127&&X<160||X>65535||X>=55296&&X<57344)return[];return[`k 0 ${X} ${Q|Zx}`]}release(){let q=Yq.filter((x)=>this.mask&x.bit).map((x)=>`b ${x.up} 0`);for(let x of this.pressed)q.push(`k ${x} 0 ${h8}`);for(let x of this.held){let[Q,P]=Eq.get(x);q.push(`k ${Q} 0 ${h8|(P?$q:0)}`)}return this.mask=0,this.pressed.clear(),this.held.clear(),q}}function kq(q){let x=k8(...p8("input"),{env:v8(),stdio:["pipe","pipe","ignore"],windowsHide:!0}),Q=new hq,P="",X=!1,b=null,J=()=>{if(b?.kill("SIGKILL"),x.exitCode!==null||x.signalCode!==null)return;x.stdin.end(Q.release().map((U)=>`${U}
189
- `).join("")),setTimeout(()=>x.kill("SIGKILL"),2000).unref()},N=(U)=>{if(X)return;X=!0,J(),q.end(U)},T=(U)=>N({error:new K("display_unavailable",U)}),L=(U)=>{if(X||U.length===0)return;if(x.stdin.write(U.map((y)=>`${y}
190
- `).join("")),x.stdin.writableLength>Bx)N({reason:"input_backpressure"})},C=()=>{b=k8(...p8("clipboard"),{env:v8(),stdio:["ignore","pipe","ignore"],windowsHide:!0});let U="";b.stdout?.on("data",(y)=>{if(X)return;U+=y.toString("ascii");for(let R=U.indexOf(`
191
- `);R>=0;R=U.indexOf(`
192
- `)){let Y=U.slice(0,R).replace(/\r$/,"");if(U=U.slice(R+1),!Y.startsWith("c "))continue;let S=Y.slice(2);if(S.length>Math.ceil(_/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(S)){N({reason:"display_protocol"});return}let W=Buffer.from(S,"base64");if(W.byteLength<=_)q.clipboard(W.toString("utf8"));if(X)return}if(U.length>Math.ceil(_/3)*4+4)N({reason:"display_protocol"})}),b.once("error",()=>T("Reason could not watch this computer's desktop clipboard.")),b.once("exit",()=>{if(!X)T("Reason could not watch this computer's desktop clipboard.")})};return x.stdout.on("data",(U)=>{if(X||P===null)return;P+=U.toString("utf8");let y=P.indexOf(`
193
- `);if(y<0){if(P.length>4096)N({reason:"display_protocol"});return}let R=Hq(P.slice(0,y).trim());if(P=null,!R)N({reason:"display_protocol"});else if(R.session===0)T("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else C(),q.ready({width:R.width,height:R.height})}),x.stdin.on("error",()=>{return}),x.once("error",()=>T("Reason could not start this computer's desktop input.")),x.once("exit",()=>{if(P!==null)T("Reason could not start this computer's desktop input.");else N({reason:"display_closed"})}),{pointer:(U,y,R)=>L(Q.pointer(U,y,R)),key:(U,y)=>L(Q.key(U,y)),clipboard:(U)=>L([`c ${Buffer.from(U,"utf8").toString("base64")}`]),close(){X=!0,J()}}}var wx=["none","standard","all"],B8="22.23.3",_x={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53","win32-x64":"2b0ff57b049cda1bbcea2240eec20467018713c1efe1f7360c2681859b90ed71","win32-arm64":"33dad22e4cef5ee8f9fbb1b0d037fdacd0e56d12a4580f0d63f68b894deab535"},u8={"linux-x64":{ocu:"dist/linux/amd64/open-computer-use",obu:"native/linux-amd64/open-browser-use"},"linux-arm64":{ocu:"dist/linux/arm64/open-computer-use",obu:"native/linux-arm64/open-browser-use"},"darwin-arm64":{ocu:"dist/Open Computer Use.app/Contents/MacOS/OpenComputerUse",obu:"native/darwin-arm64/open-browser-use"},"win32-x64":{ocu:"dist/windows/amd64/open-computer-use.exe",obu:"native/windows-amd64/open-browser-use.exe"},"win32-arm64":{ocu:"dist/windows/arm64/open-computer-use.exe",obu:"native/windows-arm64/open-browser-use.exe"}},rq="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",mq="chrome-win64/chrome.exe",a={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},$x={version:a.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},c8={version:a.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${a.version}/ffmpeg-${a.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},Iq=`ffmpeg-${c8.version}-essentials_build/bin`,c="com.ifuryst.open_browser_use.extension",dq="com.reasonmachines.browser_use.extension",pq="/tmp/reason-browser-use",d8=["tint2","picom","xterm","pcmanfm"],aq=["fonts-droid-fallback"],sq=["pulseaudio"],Ox=["xvfb","openbox","x11vnc","x11-utils","x11-xserver-utils","xdotool","dbus-x11","at-spi2-core","python3","python3-gi","gir1.2-atspi-2.0","gir1.2-gtk-3.0","fonts-dejavu-core",...aq,"galculator","chromium","ffmpeg","tmux",...sq,...d8],Ex=new Set([...d8,...aq,...sq]),vq=Ox.filter((q)=>q!=="chromium"&&!Ex.has(q)),Hx=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],j8="/usr/bin/chromium",fx=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function iq(q=process.platform,x=process.arch){let Q=`${q}-${x}`;return Q==="linux-x64"||Q==="linux-arm64"||Q==="darwin-arm64"||Q==="win32-x64"||Q==="win32-arm64"?Q:null}function s(q){return q==="win32-x64"||q==="win32-arm64"}function a8(q){return s(q)?`node-v${B8}-${q.replace("win32","win")}`:`node-v${B8}-${q}`}function R8(q){return{node:{version:B8,url:`https://nodejs.org/dist/v${B8}/${a8(q)}${s(q)?".zip":".tar.gz"}`,sha256:_x[q]},open_computer_use:{version:h.ocu.version,url:X8.ocu.url,sha256:X8.ocu.sha256},open_browser_use:{version:h.obu.version,url:X8.obu.url,sha256:X8.obu.sha256},...q==="darwin-arm64"?{chrome_for_testing:{version:v.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${v.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:v.macArm64Sha256}}:s(q)?{chrome_for_testing:{version:v.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${v.version}/win64/chrome-win64.zip`,sha256:v.win64Sha256}}:{}}}function gx(q){let x={extension:d};for(let[Q,P]of Object.entries(R8(q)))x[Q]=`${P.version}@${P.sha256}`;return x}function nq(q){return Z(q,".local","share","reason","desktop")}function oq(q,x=uq()){let Q=nq(x),P=(U)=>Z(Q,U,R8(q)[U]?.version??""),X=P("open_computer_use"),b=P("open_browser_use"),J=q==="darwin-arm64",N=s(q),T=Z(x,"Library","Application Support"),L=Z(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:Z(x,"AppData","Local"),"OpenBrowserUse"),C=J?Z(T,"Google","Chrome","NativeMessagingHosts",`${c}.json`):N?Z(L,"NativeMessagingHosts",`${c}.json`):Z(x,".config","google-chrome","NativeMessagingHosts",`${c}.json`);return{root:Q,automation:Z(m8(Q),"automation"),receipt:Z(Q,"receipt.json"),minimal:i8(x),node:N?Z(P("node"),a8(q),"node.exe"):Z(P("node"),"bin","node"),ocuDir:X,ocu:Z(X,u8[q].ocu),ocuApp:J?Z(X,"dist","Open Computer Use.app"):null,obuDir:b,obu:Z(b,"cli","open-browser-use.js"),nativeHost:Z(b,u8[q].obu),extensionDir:J?Z(T,"OpenBrowserUse","chrome-extension","release"):N?Z(L,"chrome-extension","release"):Z(x,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:C,nativeHostManifests:J?[C,Z(T,"Google","ChromeForTesting","NativeMessagingHosts",`${c}.json`)]:N?[C]:[Z(x,".config","chromium","NativeMessagingHosts",`${c}.json`),Z(x,".config","google-chrome-for-testing","NativeMessagingHosts",`${c}.json`)],browser:J?Z(P("chrome_for_testing"),rq):N?Z(P("chrome_for_testing"),mq):j8,userChromeHost:J?Z(Q,"user-chrome","reason-browser-use"):null,userChromeRegistration:J?Z(T,"Google","Chrome","NativeMessagingHosts",`${dq}.json`):null,ffmpegDir:Z(Q,"ffmpeg"),ffmpeg:J?Z(Q,"ffmpeg",a.version,"ffmpeg"):N?Z(Q,"ffmpeg",c8.version,Iq,"ffmpeg.exe"):null,ffprobe:J?Z(Q,"ffprobe",$x.version,"ffprobe"):N?Z(Q,"ffmpeg",c8.version,Iq,"ffprobe.exe"):null}}function tq(q){try{let x=JSON.parse(C8(q,"utf8"));if(typeof x!=="object"||x===null)return null;let Q=x,P=Q.pins;if(Q.schema_version!==1||typeof Q.platform!=="string"||typeof P!=="object"||P===null||!Object.values(P).every((X)=>typeof X==="string")||!wx.includes(Q.permissions)||!Array.isArray(Q.missing_system_packages)||!Q.missing_system_packages.every((X)=>typeof X==="string")||typeof Q.updated_at!=="string")return null;return{schema_version:1,platform:Q.platform,pins:P,permissions:Q.permissions,missing_system_packages:Q.missing_system_packages,updated_at:Q.updated_at}}catch{return null}}function hx(q,x,Q=384){Vx(m8(q),{recursive:!0,mode:448});let P=`${q}.pending.${process.pid}`;Mx(P,x,{mode:Q}),Fx(P,q)}function k(q){try{return r8(q).isFile()}catch{return!1}}function eq(q){try{let x=r8(q);return x.isFile()&&(x.mode&73)!==0}catch{return!1}}function kx(q){try{return C8(q,"utf8")}catch{return null}}function u(q){for(let x of fx){let Q=Z(x,q);try{let P=r8(Q);if(P.isFile()&&(P.mode&73)!==0)return Q}catch{}}return null}function Ix(q){try{let x=JSON.parse(C8(Z(q,"package.json"),"utf8"));return typeof x==="object"&&x!==null&&typeof x.version==="string"?x.version:null}catch{return null}}function px(q,x,Q){let P=R8(Q)[q];if(!P)return!1;let X=s(Q);if(q==="node")return k(X?Z(x,a8(Q),"node.exe"):Z(x,"bin","node"));if(q==="chrome_for_testing")return k(Z(x,X?mq:rq));let b=u8[Q][q==="open_computer_use"?"ocu":"obu"];return Ix(x)===P.version&&k(Z(x,b))&&(q==="open_computer_use"||k(Z(x,"cli","open-browser-use.js")))}function vx(q){return lq("sha256").update(Buffer.from(q,"base64")).digest("hex").slice(0,32).replace(/./g,(x)=>String.fromCharCode(97+Number.parseInt(x,16)))}function s8(q){try{let x=JSON.parse(C8(q,"utf8"));return typeof x==="object"&&x!==null&&!Array.isArray(x)?x:null}catch{return null}}function ux(q){let x=s8(Z(q.extensionDir,"manifest.json"));return x!==null&&x.version===h.obu.version&&typeof x.key==="string"&&vx(x.key)===d}function cx(q,x){let Q=q?.allowed_origins;return q!==null&&q.name===c&&Array.isArray(Q)&&Q.length===1&&Q[0]===`chrome-extension://${d}/`&&(x===void 0||q.path===x)}function lx(q){return ux(q)&&k(q.nativeHost)&&q.nativeHostManifests.every((x)=>cx(s8(x),q.nativeHost))}function rx(q){return`#!/bin/sh
194
- # Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
195
- obu=${`'${q.replaceAll("'","'\\''")}'`}
196
- case "$1" in
197
- chrome-extension://*) exec "$obu" host --socket-dir ${pq} ;;
198
- mcp) shift; exec "$obu" mcp --socket-dir ${pq} "$@" ;;
199
- esac
200
- exec "$obu" "$@"
201
- `}function mx(q){let x=s8(q),Q=x?.allowed_origins;return x!==null&&x.name===dq&&x.type==="stdio"&&Array.isArray(Q)&&Q.includes(`chrome-extension://${g8}/`)&&typeof x.path==="string"&&eq(x.path)}function dx(q,x){if(!q.userChromeHost||!q.userChromeRegistration)return null;if(!x||kx(q.userChromeHost)!==rx(q.nativeHost)||!eq(q.userChromeHost))return{code:"user_chrome_browser_use_missing"};return mx(q.userChromeRegistration)?{host:q.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var ax={display:["display","desktop_session","desktop_video"],computer:["display","desktop_session","system_packages","node","open_computer_use"],browser:["display","desktop_session","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function I(q={}){let x=q.platform===void 0?iq():q.platform;if(!x)return null;let Q=oq(x,q.home),P=tq(Q.receipt),X=gx(x),b=P!==null&&P.platform===x&&JSON.stringify(Object.entries(P.pins).sort())===JSON.stringify(Object.entries(X).sort()),J=[],N=R8(x);for(let W of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let G=N[W];if(!G)continue;let V=px(W,Z(Q.root,W,G.version),x),F=P?.pins[W],E=V&&F===X[W]?"ready":F!==void 0&&F!==X[W]?"outdated":"missing";J.push({name:W,state:E,detail:G.version})}let T=P?.pins.extension===d&&lx(Q);J.push({name:"browser_extension",state:T?"ready":"missing",detail:d});let L=u("Xvfb"),C=u("x11vnc"),U=u("openbox");if(s(x))J.push(gq()?{name:"desktop_session",state:"ready",detail:"signed-in desktop session"}:{name:"desktop_session",state:"missing",detail:"run the worker in the signed-in desktop session, not as a service"}),J.push(Q.ffmpeg&&k(Q.ffmpeg)?{name:"desktop_video",state:"ready",detail:Q.ffmpeg}:{name:"desktop_video",state:"missing",detail:"run `reason desktop install` for desktop video"});else if(x!=="darwin-arm64"){J.push(k(j8)?{name:"browser",state:"ready",detail:j8}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${j8}`});let W=L!==null&&C!==null&&U!==null;J.push({name:"display",state:W?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let G=Hx.filter((w)=>u(w)===null),V=(P?.missing_system_packages??vq).filter((w)=>vq.includes(w)),F=G.length===0&&V.length===0;J.push(F?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...V,...G])].join(" ")});let E=d8.filter((w)=>u(w)===null);J.push(E.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:E.join(" ")})}let y=Q.ffmpeg&&k(Q.ffmpeg)?Q.ffmpeg:u("ffmpeg"),R=!y?null:y===Q.ffmpeg?Q.ffprobe:Z(m8(Kx(y)),"ffprobe"),Y=b&&J.every((W)=>W.state==="ready"),S=(W)=>b&&J.every((G)=>!ax[W].includes(G.name)||G.state==="ready");return{platform:x,root:Q.root,automation:Q.automation,ready:Y,features:{display:S("display"),computer:S("computer"),browser:S("browser")},node:Q.node,ocu:Q.ocu,obu:Q.obu,nativeHost:Q.nativeHost,extensionDir:Q.extensionDir,browser:Q.browser,ffmpeg:y,ffprobe:R&&k(R)?R:null,userChrome:dx(Q,b&&["node","open_browser_use"].every((W)=>J.find((G)=>G.name===W)?.state==="ready")),pulseaudio:u("pulseaudio"),xvfb:L,x11vnc:C,openbox:U,components:J}}function q0(q){return sx(q)?cq():[]}function sx(q){return q?.platform==="darwin-arm64"&&q.ffmpeg===Z(q.root,"ffmpeg",a.version,"ffmpeg")}async function t9(q,x,Q,P=fetch){try{let X=await P(q,{redirect:"follow"});if(!X.ok||!X.body)throw Error(`download failed (HTTP ${X.status}): ${q}`);let b=lq("sha256"),J=Ax(Q,{mode:384});try{let T=X.body.getReader();for(let L=await T.read();!L.done;L=await T.read())if(b.update(L.value),!J.write(L.value))await Gx(J,"drain")}finally{J.end(),await Yx(J)}let N=b.digest("hex");if(N!==x)throw Error(`digest mismatch for ${q}: expected ${x}, got ${N}`)}catch(X){throw zx(Q,{force:!0}),X}}function i8(q){return Z(nq(q),"minimal.json")}function ix(q=i()){return Sx(i8(q))}function e9(q={}){hx(i8(q.home??i()),`${JSON.stringify({version:1,minimal_at:(q.now?.()??new Date).toISOString()})}
202
- `)}function qQ(q={}){let x=q.platform===void 0?iq():q.platform;if(x===null)return null;let Q=q.home??i();if(tq(oq(x,Q).receipt)!==null)return"refresh";return ix(Q)?null:"install"}import{execFile as N1,spawn as Qq}from"child_process";import{existsSync as U1}from"fs";import{connect as L1}from"net";function nx(){let q=new Set,x=null,Q=(X)=>({holder:x?.viewer??null,you:x===X,same_user:Boolean(x?.viewer&&X.viewer&&x.viewer.user_id===X.viewer.user_id)}),P=()=>{for(let X of q)X.notify(Q(X))};return{join(X){return q.add(X),X.notify(Q(X)),()=>{if(!q.delete(X))return;if(x!==X)return;x=null,P()}},claim(X){if(x===X||!q.has(X))return;x=X,P()}}}var x0=nx();import{spawn as ox}from"child_process";import{existsSync as tx}from"fs";import{connect as ex}from"net";import{join as D8}from"path";var X0="reason_desktop",b8={sampleRate:48000,channels:2,codec:"opus"},q1=5000,x1=107,Q1=262144,t8=(q)=>D8(q,"native"),T8=(q)=>`unix:${q}`;function n8(q,x=1000){if(!tx(q))return Promise.resolve(!1);return new Promise((Q)=>{let P=ex({path:q}),X=(b)=>{P.destroy(),Q(b)};P.setTimeout(x,()=>X(!1)),P.once("error",()=>X(!1)),P.once("close",()=>X(!1)),P.once("connect",()=>X(!0))})}async function P0(q,x){if(!x)return null;let Q=t8(q);if(Buffer.byteLength(Q)>x1||/["'\\\s]/.test(Q))return null;try{if(await n8(Q))return Q;let P=ox(x,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${D8(q,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${Q}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${X0} rate=${b8.sampleRate} channels=${b8.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:q,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:q,PULSE_RUNTIME_PATH:D8(q,"runtime"),PULSE_STATE_PATH:D8(q,"state")}}),X=!1;P.once("error",()=>{X=!0}),P.once("exit",()=>{X=!0}),P.unref();let b=Date.now()+q1;while(Date.now()<b){if(await n8(Q))return Q;if(X)return await n8(Q)?Q:null;await new Promise((J)=>setTimeout(J,50))}if(!X)P.kill("SIGKILL");return null}catch{return null}}function b0(){let{sampleRate:q,channels:x}=b8;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(q),"-channels",String(x),"-fragment_size",String(q*x*2/50),"-i",`${X0}.monitor`,"-vn","-ac",String(x),"-ar",String(q),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var X1=[79,103,103,83],P1=Buffer.from("OpusHead"),b1=Buffer.from("OpusTags"),Q0=(q,x)=>q.byteLength>=x.byteLength&&x.every((Q,P)=>q[P]===Q);class o8 extends Error{constructor(q){super(q);this.name="OggProtocolError"}}class e8{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(q){let x=new Uint8Array(this.buffer.byteLength+q.byteLength);x.set(this.buffer),x.set(q,this.buffer.byteLength);let Q=[],P=0;while(x.byteLength-P>=27){if(X1.some((y,R)=>x[P+R]!==y)||x[P+4]!==0)throw new o8("invalid_page");let X=(x[P+5]&1)!==0,b=x[P+26];if(x.byteLength-P<27+b)break;let J=x.subarray(P+27,P+27+b),N=J.reduce((y,R)=>y+R,0),T=27+b+N;if(x.byteLength-P<T)break;if(!X&&this.partialBytes>0)this.resetPartial();let L=X&&this.partialBytes===0,C=P+27+b,U=C;for(let y of J){if(C+=y,y===255)continue;if(this.appendPartial(x.subarray(U,C),L),U=C,!L){let R=this.takePartial();if(R.byteLength>0&&!Q0(R,P1)&&!Q0(R,b1))Q.push(R)}L=!1,this.resetPartial()}if(U<C)this.appendPartial(x.subarray(U,C),L);P+=T}return this.buffer=x.slice(P),Q}appendPartial(q,x){if(x||q.byteLength===0)return;if(this.partialBytes+=q.byteLength,this.partialBytes>Q1)throw new o8("packet_too_large");this.partial.push(q.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let q=new Uint8Array(this.partialBytes),x=0;for(let Q of this.partial)q.set(Q,x),x+=Q.byteLength;return q}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as J1}from"child_process";var J0=1048576,W1=String.raw`
203
- import gi, json, os, sys
204
- gi.require_version("Gtk", "3.0")
205
- from gi.repository import Gtk, Gdk, GLib
206
- if not Gtk.init_check()[0]:
207
- sys.exit(1)
208
- clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
209
- pending = b""
210
- generation = 0
211
- def send(value):
212
- print(json.dumps(value, ensure_ascii=True), flush=True)
213
- def changed(clipboard, event):
214
- global generation
215
- generation += 1
216
- current = generation
217
- def received(clipboard, text, unused):
218
- if current == generation and text is not None and len(text.encode("utf-8")) <= ${_}:
219
- send({"text": text})
220
- clipboard.request_text(received, None)
221
- # No request_text on startup: never share the pre-existing clipboard.
222
- clipboard.connect("owner-change", changed)
223
- def input_ready(fd, condition):
224
- global pending
225
- chunk = os.read(fd, 65536)
226
- if not chunk:
227
- Gtk.main_quit()
228
- return False
229
- pending += chunk
230
- while b"\n" in pending:
231
- line, pending = pending.split(b"\n", 1)
232
- text = json.loads(line)
233
- if not isinstance(text, str) or len(text.encode("utf-8")) > ${_} or "\x00" in text:
234
- sys.exit(1)
235
- clipboard.set_text(text, -1)
236
- send("ack")
237
- if len(pending) > ${_*6+2}:
238
- sys.exit(1)
239
- return True
240
- GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
241
- send("ready")
242
- Gtk.main()
243
- `;function W0(q,x){let Q=J1("/usr/bin/python3",["-I","-u","-c",W1],{env:{DISPLAY:q.display,XAUTHORITY:q.xauthority},stdio:["pipe","pipe","ignore"]}),P=!1,X=!0,b="",J=0,N=[],T=setTimeout(()=>C(),5000),L=()=>{P=!0,clearTimeout(T),N.length=0,Q.kill("SIGKILL")},C=()=>{if(P)return;L(),x.end({error:new K("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},U=(y,R=32)=>{if(P)return;if(!X){y();return}if(J+=R,J>J0)L(),x.end({reason:"input_backpressure"});else N.push({apply:y,bytes:R})};return Q.stdout.on("data",(y)=>{if(P)return;b+=y.toString("ascii");for(let R=b.indexOf(`
244
- `);R>=0;R=b.indexOf(`
245
- `)){let Y=b.slice(0,R);b=b.slice(R+1);let S;try{S=JSON.parse(Y)}catch{C();return}if(S==="ready"||S==="ack"){clearTimeout(T),X=!1;while(!X&&!P&&N.length){let W=N.shift();J-=W.bytes,W.apply()}}else if(S&&typeof S==="object"&&"text"in S&&typeof S.text==="string"&&Buffer.byteLength(S.text)<=_)x.clipboard(S.text);else{C();return}if(P)return}if(b.length>_*6+32)C()}),Q.stdin.on("error",C),Q.once("error",C),Q.once("exit",C),{apply:U,write(y){if(Buffer.byteLength(y)>_||y.includes("\x00")){C();return}let R=`${JSON.stringify(y)}
246
- `;U(()=>{if(X=!0,T=setTimeout(()=>C(),5000),Q.stdin.write(R),Q.stdin.writableLength>J0)L(),x.end({reason:"input_backpressure"})},Buffer.byteLength(R))},close:L}}var n={smooth:{fps:60,crf:23,kbps:8000,x264Preset:"ultrafast",threads:2,scale:1},sharp:{fps:30,crf:19,kbps:1e4,x264Preset:"superfast",scale:1},data_saver:{fps:20,crf:28,kbps:2000,x264Preset:"ultrafast",scale:0.75},balanced:{fps:30,crf:23,kbps:4000,x264Preset:"ultrafast",threads:2,scale:1}},j1="avc1.4D002A",N0={width:1920,height:1080},B1=262144,C1=0.2,R1=250,D1=1e4,T1=1024,qq=1e4,Z1=500,y1=60,G1=1e4,A1=1000,U0=1048576,S0={kind:"mac_screen",sound:null},V0={kind:"windows_screen",sound:null},S1,L0=()=>S1??=I()?.ffmpeg??null,y8=(q,x,Q)=>Qq(q,x,{env:Q,stdio:["ignore","pipe","ignore"],windowsHide:!0}),V1,Xq=()=>V1??=q0(I()),j0=(q,x,Q)=>{let[P,...X]=[...Xq(),q];return y8(P,[...X,...x],Q)},B0=()=>_0?.videotoolbox?"h264_videotoolbox":"libx264",F1=()=>Math.round(performance.now()*1000),xq=new Set,C0=!1;function F0(q){if(xq.add(q),q.once("exit",()=>xq.delete(q)),C0)return;C0=!0,process.once("exit",()=>{for(let x of xq)try{x.kill("SIGKILL")}catch{}})}function K0(q){try{q.stdout?.destroy()}catch{}if(q.exitCode!==null||q.signalCode!==null)return;try{q.kill("SIGTERM")}catch{return}let x=setTimeout(()=>{if(q.exitCode===null&&q.signalCode===null)try{q.kill("SIGKILL")}catch{}},Z1);q.once("exit",()=>clearTimeout(x))}function K1(q,x,Q){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(q),"-video_size",`${x.width}x${x.height}`,"-i",Q],size:x}}function z1(q){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(q),"-i","Capture screen 0:none"],size:null}}function M1(q,x){return{args:["-f","gdigrab","-draw_mouse","1","-framerate",String(q),"-offset_x","0","-offset_y","0","-video_size",`${x.width}x${x.height}`,"-i","desktop"],size:x}}function Y1(q){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(q),"-i","pipe:0"],size:null}}var z0=1700000;function M0(q){return Math.min(1,Math.round(Math.sqrt(z0/(q.width*q.height))*100)/100)}function w1(q,x,Q){let P=Qq(Q.axe,["stream-video","--udid",Q.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,M0(Q.size)))],{stdio:["ignore","pipe","ignore"]}),X=Qq(q,x,{env:{},stdio:["pipe","pipe","ignore"]});P.stdout.pipe(X.stdin),X.stdin.on("error",()=>{});let b=()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")};return X.once("exit",b),X.once("error",b),P.once("exit",()=>{if(X.exitCode===null&&X.signalCode===null)X.kill("SIGTERM")}),P.once("error",()=>{if(X.exitCode===null&&X.signalCode===null)X.kill("SIGTERM")}),X}function R0(q){let x=Math.min(1,N0.width/q.width,N0.height/q.height);return{width:Math.round(q.width*x),height:Math.round(q.height*x)}}function Z8(q,x,Q,P="libx264"){let X=n[q],b=(U)=>Math.max(2,Math.floor(U/2)*2),J={width:b(Q.width*X.scale),height:b(Q.height*X.scale)},N=J.width!==x.size?.width||J.height!==x.size.height,T=Math.max(1,Math.round(X.kbps*2/X.fps)),L=["-g",String(X.fps*y1)],C=P==="h264_videotoolbox"?["-c:v","h264_videotoolbox","-realtime","1","-prio_speed","1","-allow_sw","1","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","nv12",...L,"-b:v",`${X.kbps}k`,"-maxrate",`${X.kbps}k`,"-bufsize",`${T}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",X.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...X.threads?["-threads",String(X.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...L,"-crf",String(X.crf),"-maxrate",`${X.kbps}k`,"-bufsize",`${T}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...x.args,"-an",...N?["-vf",`scale=${J.width}:${J.height}:flags=fast_bilinear`]:[],...C,"-flush_packets","1","-f","h264","pipe:1"]}class Y0{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(q,x){if(this.buffer.byteLength===0)this.micros=x;let Q=new Uint8Array(this.buffer.byteLength+q.byteLength);Q.set(this.buffer),Q.set(q,this.buffer.byteLength),this.buffer=Q;let P=[],X=this.scanned;while(X+3<this.buffer.byteLength){if(this.buffer[X]!==0||this.buffer[X+1]!==0||this.buffer[X+2]!==1){X++;continue}let b=this.buffer[X+3]&31,J=X>0&&this.buffer[X-1]===0?X-1:X;if(b===9&&J>0)P.push({data:this.buffer.slice(0,J),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(J),this.key=!1,this.micros=x,X-=J;if(b===5)this.key=!0;X+=3}return this.scanned=X,P}}function _1(q,x){let Q=L1({path:q}),P=Buffer.alloc(0),X="version",b=0,J=!1,N=[],T=0,L=!1,C=(W)=>{if(L)return;L=!0,Q.destroy(),x.end(W)},U=()=>C({reason:"display_protocol"}),y=(W)=>{if(L)return;if(!J){if(T+=W.byteLength,T>U0)C({reason:"input_backpressure"});else N.push(W);return}if(Q.write(W),Q.writableLength>U0)C({reason:"input_backpressure"})},R=(W)=>{P=P.subarray(W)},Y=()=>{switch(X){case"version":{if(P.byteLength<12)return!1;let W=/^RFB (\d{3})\.(\d{3})\n$/.exec(P.subarray(0,12).toString("latin1"));if(!W||Number(W[1])*1000+Number(W[2])<3007)return U(),!1;return R(12),Q.write(`RFB 003.007
247
- `),X="security",!0}case"security":{if(P.byteLength<1)return!1;let W=P[0];if(W===0)return U(),!1;if(P.byteLength<1+W)return!1;if(!P.subarray(1,1+W).includes(1))return U(),!1;return R(1+W),Q.write(Buffer.from([1,1])),X="init",!0}case"init":{if(P.byteLength<24)return!1;let W=P.readUInt32BE(20);if(W>65536)return U(),!1;if(P.byteLength<24+W)return!1;let G={width:P.readUInt16BE(0),height:P.readUInt16BE(2)};if(R(24+W),G.width===0||G.height===0)return U(),!1;X="messages",J=!0;for(let V of N)Q.write(V);return N=[],T=0,x.ready(G),!L}case"skip":{let W=Math.min(b,P.byteLength);if(R(W),b-=W,b>0)return!1;return X="messages",!0}case"messages":{if(P.byteLength<1)return!1;switch(P[0]){case 1:{if(P.byteLength<6)return!1;let W=6+P.readUInt16BE(4)*6;if(P.byteLength<W)return!1;return R(W),!0}case 2:return R(1),!0;case 3:{if(P.byteLength<8)return!1;let W=P.readUInt32BE(4);if(W>_/2)return R(8),X="skip",b=W,!0;if(P.byteLength<8+W)return!1;let G=P.subarray(8,8+W).toString("latin1");return R(8+W),x.clipboard(G),!L}default:return U(),!1}}}},S=!1;return Q.once("connect",()=>{S=!0}),Q.on("data",(W)=>{if(L)return;P=P.byteLength?Buffer.concat([P,W]):W;while(!L&&Y());}),Q.once("error",()=>{if(!S)C({error:new K("display_unavailable","Reason could not reach this machine's desktop server.")})}),Q.once("close",()=>C({reason:"display_closed"})),{pointer(W,G,V){let F=Buffer.alloc(6);F.writeUInt8(5,0),F.writeUInt8(V&255,1),F.writeUInt16BE(W,2),F.writeUInt16BE(G,4),y(F)},key(W,G){let V=Buffer.alloc(8);V.writeUInt8(4,0),V.writeUInt8(W?1:0,1),V.writeUInt32BE(G>>>0,4),y(V)},clipboard(W){if(Array.from(W).some((F)=>F.codePointAt(0)>255)){C({reason:"clipboard_unicode_unsupported"});return}let G=Buffer.from(W,"latin1"),V=Buffer.alloc(8);V.writeUInt8(6,0),V.writeUInt32BE(G.byteLength,4),y(Buffer.concat([V,G]))},close(){L=!0,Q.destroy()}}}class Pq{run=null;viewers=new Set;get running(){return this.run!==null}start(q,x,Q,P){this.viewers.add(q),this.stop();let X;try{X=Q()}catch{this.fail();return}F0(X);let b={child:X,splitter:new Y0};this.run=b;for(let N of[...this.viewers])N.started(x);X.stdout?.on("data",(N)=>{if(this.run!==b)return;for(let T of b.splitter.push(N,P()))for(let L of[...this.viewers])L.unit(T)});let J=()=>{if(this.run!==b)return;this.run=null,this.fail()};X.once("exit",J),X.once("error",J)}leave(q){if(!this.viewers.delete(q))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;K0(this.run.child),this.run=null}fail(){for(let q of[...this.viewers])q.failed()}}var D0=new WeakMap;function $1(q){let x=D0.get(q);if(!x)D0.set(q,x=new Pq);return x}function w0(q,x,Q={}){let P=Q.micros??F1,X=new y0,b=x.request.preset,J=null,N=null,T=null,L=!1,C=null,U=!1,y=!1,R=null,Y=0,S=0,W=!1,G=null,V=null,F=0,E=null,w=[],t=0,A=[],f=new Uint32Array(qq+1),p=0,F8=null,K8=0,e=0,z8=0,Lq=0,jq=0,J8=null,M8=0,l={frames:0,bytes:0,since:P()},r=[],q8=0,Y8,w8=!1,c0=P(),O={},m=()=>Math.round((P()-c0)/1000),Bq=Q.control??x0,_8=null,$8=null,H=(B)=>{let j=G8(B);return q.send(j),Lq+=j.byteLength,j.byteLength},W8=(B)=>{if(q.done)return;if(q.open)H({type:"error",code:B});q.end({reason:B})},N8=()=>Math.max(B1,n[b].kbps*1000/8*C1),U8=()=>P()/1000,l0=()=>{while(A.length>1&&A[0].atMs<U8()-D1)A.shift();return A[0]?.rttMs??null},Cq=(B)=>{let j=l0();if(j===null||w.length===0)return!1;let D=(j+R1)*B;return U8()-w[0].sentMs>D||t>D/1000*n[b].kbps*1000/8},r0=(B)=>{if(F===0)return;let j=Math.min(B,F-1);if(E!==null&&j<=E)return;E=j;let D=U8();while(w.length&&w[0].seq<=j){let z=w.shift();if(t-=z.bytes,z.seq!==j)continue;let M=Math.max(0,D-z.sentMs);while(A.length&&A.at(-1).rttMs>=M)A.pop();A.push({atMs:D,rttMs:M}),f[Math.min(qq,Math.round(M))]++,p++,F8=Math.min(F8??M,M)}},m0=()=>{let B=0;for(let j=0;j<=qq;j++)if(B+=f[j],B*2>=p)return j;return 0},d0=()=>q.bufferedAmount<=N8()/2&&!Cq(0.5),Rq=()=>{w8=!0,r=[],q8=0,C?.leave(O8),C=null},Dq=(B)=>{if(q.done)return;if(B.key)O.first_key_ms??=m();if(!L){if(!C||r.length===0&&!B.key)return;if(r.push(B),q8+=B.data.byteLength,q8>N8())Rq();return}if(W){e++;return}if(q.bufferedAmount>N8()||Cq(1)){W=!0,e++,G=setInterval(()=>{if(q.done||!d0())return;if(G)clearInterval(G);G=null,W=!1,H8()},Q.drainPollMs??25);return}if(!U){if(!B.key){e++;return}if(H({type:"hello",width:N.width,height:N.height,fps:n[b].fps,preset:b,codec:j1}),U=!0,O.first_frame_ms??=m(),!y&&J?.sound)H({type:"audioHello",...b8}),y=!0}let j=H({type:"frame",key:B.key,seq:F,captureMicros:B.micros,data:B.data});if(w.push({seq:F,sentMs:U8(),bytes:j}),t+=j,w.length>T1)t-=w.shift().bytes;F++,K8++,J8??=B.micros,M8=B.micros,l.frames++,l.bytes+=j},O8={started(B){b=B,U=!1,r=[],q8=0},unit:Dq,failed:()=>W8("encoder_failed")},E8=()=>{let B=(Q.ffmpeg??L0)();if(!J||!N){W8("encoder_failed");return}let[j,D]=[J,N],z="kind"in j&&j.kind==="simulator"?j.stream:null;if(!B&&!z){W8("encoder_failed");return}if(C??="kind"in j&&j.kind==="mac_screen"?$1(Q.spawn??j0):new Pq,O.encoder_ms===void 0)O.encoder_ms=m(),O.encoder_shared=C.running;C.start(O8,b,()=>{let M=n[b].fps;if(z)return z(M,n[b].kbps,z0);if("kind"in j&&j.kind==="simulator"){let g=Math.min(0.99,M0(j.size)),x8={width:j.size.width*g,height:j.size.height*g};return w1(B,Z8(b,Y1(Math.min(M,30)),x8,(Q.macEncoder??B0)()),j)}if("kind"in j&&j.kind==="windows_screen")return(Q.spawn??y8)(B,Z8(b,M1(M,D),R0(D)),{SystemRoot:process.env.SystemRoot??"C:\\Windows"});return"kind"in j?(Q.spawn??j0)(B,Z8(b,z1(M),R0(D),(Q.macEncoder??B0)()),{}):(Q.spawn??y8)(B,Z8(b,K1(M,D,j.display),D),{DISPLAY:j.display,XAUTHORITY:j.xauthority})},P)},L8=()=>{if(!R)return;K0(R.child),R=null},a0=()=>{let B=(Q.ffmpeg??L0)();if(R||q.done||!y||!J?.sound||!B)return;let j;try{j=(Q.spawn??y8)(B,b0(),{PULSE_SERVER:T8(J.sound)})}catch{return}F0(j);let D={child:j,reader:new e8};R=D,j.stdout?.on("data",(M)=>{if(R!==D||q.done)return;let g;try{g=D.reader.push(M)}catch{L8();return}let x8=P();for(let s0 of g){if(q.bufferedAmount>N8()){S++;continue}H({type:"audio",captureMicros:x8,data:s0}),Y++}});let z=()=>{if(R===D)L8()};j.once("exit",z),j.once("error",z)},H8=()=>{if(!C||q.done)return;z8++,E8()},Tq=()=>{if(q.done||!N)return;if(!L){if(C||w8)return;E8(),Y8=setTimeout(()=>{if(!L)Rq()},G1);return}if(clearTimeout(Y8),O.encoder_early===void 0){if(O.encoder_early=C!==null,w8)O.hold_lapsed=!0}if(!C)E8();let B=r;r=[],q8=0;for(let j of B)Dq(j);V??=setInterval(()=>{let j=P(),D=Math.max(0.001,(j-l.since)/1e6);H({type:"stats",stats:{fps:Math.round(l.frames/D*10)/10,kbps:Math.round(l.bytes*8/1000/D),dropped:e,restarts:z8,queued_bytes:q.bufferedAmount}}),l={frames:0,bytes:0,since:j}},A1)};x.desktop.then((B)=>{if(q.done)return;J=B;let j={ready(D){N=D,O.desktop_ms??=m(),Tq()},clipboard(D){if(q.open&&Buffer.byteLength(D)<=_)H({type:"serverClipboard",text:D})},end(D){if("reason"in D&&q.open)H({type:"error",code:D.reason});q.end(D)}};if("kind"in B&&B.kind==="simulator")T=B.input,j.ready(B.points);else if("kind"in B&&B.kind==="windows_screen")T=(Q.windowsInput??kq)(j);else if("kind"in B)T=(Q.macInput??((D)=>A0(D,Xq())))(j);else{let D=(Q.linuxClipboard??W0)(B,j),z=_1(B.rfbSocket,{...j,clipboard:(M)=>{if(!D)j.clipboard(M)}});T=D?{pointer:(M,g,x8)=>D.apply(()=>z.pointer(M,g,x8)),key:(M,g)=>D.apply(()=>z.key(M,g)),clipboard:(M)=>D.write(M),close(){D.close(),z.close()}}:z}Zq()},(B)=>q.end({error:B}));function Zq(){if($8||!x.viewerSameNetwork||!L||q.done||!J||!("kind"in J)||J.kind!=="mac_screen")return;$8=(Q.macWindows??G0)((B)=>{if(q.open)H({type:"windows",bounds:B})})}let yq={viewer:x.viewer??null,notify(B){if(q.open)H({type:"control",control:B})}},f8=(B)=>{if(!T)return;if(!J||!("kind"in J)||J.kind!=="simulator")Bq.claim(yq);B(T)};return{opened(){O.relay_ms??=m()},received(B){jq+=B.byteLength;let j;try{j=X.push(B)}catch{W8("viewer_protocol");return}for(let D of j){if(q.done)return;switch(D.type){case"ping":H({type:"pong",token:D.token});break;case"pointer":f8((z)=>z.pointer(D.x,D.y,D.buttons));break;case"key":f8((z)=>z.key(D.down,D.keysym));break;case"clientClipboard":f8((z)=>z.clipboard(D.text));break;case"config":if(D.preset!==b)b=D.preset,H8();break;case"keyframeRequest":if(U&&!W)H8();break;case"ack":r0(D.seq);break;case"audioEnable":if(D.on)a0();else L8();break;default:break}}if(!L&&!q.done){if(L=!0,O.viewer_ms=m(),x.viewer)_8=Bq.join(yq);Tq(),Zq()}},close(){if(_8?.(),_8=null,$8?.close(),G)clearInterval(G);if(V)clearInterval(V);clearTimeout(Y8),C?.leave(O8),L8(),T?.close()},summary:()=>({output_bytes:Lq,input_bytes:jq,video:{preset:b,frames:K8,dropped:e,restarts:z8,avg_fps:J8!==null&&M8>J8?Math.round((K8-1)/((M8-J8)/1e6)*10)/10:0,min_rtt_ms:Math.round(F8??0),p50_rtt_ms:p?m0():0,audio_packets:Y,audio_dropped:S,connect:O}})}}var T0=null,_0=null,O1=null,E1=null;function H1(){let q=I();return q?.features.display?q.ffmpeg:null}function $0(q){return T0??=new Promise((x)=>{N1(q,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(Q,P)=>{let X=(b)=>!Q&&new RegExp(`^\\s*V\\S*\\s+${b}\\s`,"m").test(P);x(_0={x264:X("libx264"),videotoolbox:X("h264_videotoolbox")})})}),T0}var Z0=null;function FQ(){return Z0??=(async()=>{let q=[I()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((Q)=>Boolean(Q&&U1(Q)));if(!q)return null;let x=await $0(q);return x.videotoolbox||x.x264?q:null})(),Z0}function bq(q=process.platform,x={}){if(q!=="linux"&&q!=="darwin"&&q!=="win32")return Promise.resolve(!1);let Q=(x.ffmpeg??H1)();if(!Q)return Promise.resolve(!1);let P=(x.encoders??$0)(Q);if(q==="linux")return P.then((b)=>b.x264);if(q==="win32"){let b=x.windowsScreen?x.windowsScreen():E1??=fq();return Promise.all([P,b]).then(([J,N])=>J.x264&&(N?.session??0)>0)}let X=x.macScreen?x.macScreen():O1??=l8(Xq());return Promise.all([P,X]).then(([b,J])=>(b.x264||b.videotoolbox)&&J?.screen===!0&&J.accessibility)}var c1=43200000,A8=":99",l1=60000,V8=15000,Nq={width:1280,height:800},r1=/^[A-Za-z0-9._:-]{1,160}$/;function m1(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}var d1=["video","viewer","viewer_same_network","viewer_network"];function a1(q,x=Date.now()){let Q=["relay_url","session_id","expires_at"];if(!m1(q)||Q.some((N)=>!(N in q))||Object.keys(q).some((N)=>!Q.includes(N)&&!d1.includes(N)))throw new K("invalid_display_request","Reason desktop request is malformed.");let P="video"in q?h0(q.video):void 0,X="viewer"in q?g0(q.viewer):null;if(P===null)throw new K("invalid_display_request","Reason desktop video request is invalid.");let b=null;try{b=typeof q.relay_url==="string"?new URL(q.relay_url):null}catch{}if(!b||b.protocol!=="wss:"&&b.protocol!=="ws:"||b.username||b.password)throw new K("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof q.session_id!=="string"||!r1.test(q.session_id))throw new K("invalid_display_request","Reason desktop session identity is invalid.");let J=typeof q.expires_at==="string"?Date.parse(q.expires_at):Number.NaN;if(!Number.isFinite(J)||J<=x)throw new K("invalid_display_request","Reason desktop session has already expired.");return{relay_url:q.relay_url,session_id:q.session_id,expires_at:new Date(Math.min(J,x+c1)).toISOString(),...P?{video:P}:{},...X?{viewer:X}:{},...P&&q.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function O0(q=process.platform){return(q==="linux"||q==="darwin"||q==="win32")&&I()?.features.display===!0}async function vQ(){if(process.platform==="win32")return O0()&&await bq();if(process.platform!=="darwin")return O0();return await bq()}function S8(q){I1(q,{recursive:!0,mode:448});let x=k1(q);if(!x.isDirectory()||x.isSymbolicLink()||process.getuid&&x.uid!==process.getuid())throw new K("display_unavailable","Reason desktop state directory is not private.");h1(q,448)}function s1(q,x){let Q=(X)=>{let b=Buffer.alloc(2);return b.writeUInt16BE(X.length),Buffer.concat([b,X])},P=Buffer.from([255,255]);return Buffer.concat([P,Q(Buffer.alloc(0)),Q(Buffer.from(q)),Q(Buffer.from("MIT-MAGIC-COOKIE-1")),Q(x)])}function o(q,x,Q=2000){return new Promise((P)=>{let X=u1(q),b="",J=(N)=>{X.destroy(),P(N)};X.setTimeout(Q,()=>J(!1)),X.once("error",()=>J(!1)),X.once("close",()=>J(!1)),X.once("connect",()=>{if(!x)J(!0)}),X.on("data",(N)=>{if(b+=N.toString("latin1"),b.length>=4)J(b.startsWith("RFB "))})})}async function v0(q,x){let Q=Date.now()+x;while(Date.now()<Q){if(await q())return!0;await new Promise((P)=>setTimeout(P,100))}return!1}function Uq(q,x,Q){return new Promise((P)=>{let X=I0(q,x,{detached:!0,stdio:"ignore",env:Q});X.once("error",()=>P(-1)),X.once("exit",(b)=>P(b)),X.unref(),setTimeout(()=>P(null),V8).unref()})}var Jq=null;function i1(q=i()){return Jq??=n1(q).finally(()=>{Jq=null}),Jq}async function n1(q){let x=I({home:q});if(!x?.xvfb||!x.x11vnc||!x.openbox)throw new K("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");H0({root:x.root,automation:x.automation,extensionDir:x.extensionDir});let Q=$(x.root,"display");S8(Q);let P=await t1(q,Q,x.x11vnc);if(P)return P;let X={display:A8,xauthority:$(Q,"Xauthority"),rfbSocket:$(Q,"rfb.sock")},b=$(Q,"pulse"),J=(async()=>{try{S8(b)}catch{return null}return await P0(b,x.pulseaudio)})(),N=$(Q,"home");S8(N);let T={HOME:N,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:X.display,XAUTHORITY:X.xauthority};if(x.pulseaudio)T.PULSE_SERVER=T8(t8(b));let L=async()=>({...X,sound:await J});if(await o({path:X.rfbSocket},!0))return await L();if(!p0(X.xauthority))Wq(X.xauthority,s1(A8.slice(1),g1(16)),{mode:384,flag:"wx"});let C=e1($(Q,"theme"),X.display),U={path:`/tmp/.X11-unix/X${A8.slice(1)}`};if(!await o(U,!1)){if(Uq(x.xvfb,[X.display,"-screen","0",`${Nq.width}x${Nq.height}x24`,"-nolisten","tcp","-auth",X.xauthority],T),!await v0(()=>o(U,!1),V8))throw new K("display_unavailable","Reason could not start the virtual display.");Uq(x.openbox,["--config-file",C.openboxConfig],T)}if(await q9(C,T),!await u0(x.x11vnc,X,Q,"x11vnc.log",T))throw new K("display_unavailable","Reason could not start the desktop server.");return await L()}async function u0(q,x,Q,P,X){if(await o({path:x.rfbSocket},!0))return!0;v1(x.rfbSocket,{force:!0});let b=await Uq(q,["-display",x.display,"-auth",x.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",x.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",$(Q,P)],X);if(b!==null&&b!==0)return!1;return await v0(()=>o({path:x.rfbSocket},!0),V8)}async function o1(){let q=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],x=(Q)=>Object.fromEntries(q.flatMap((P)=>Q[P]?[[P,Q[P]]]:[]));if(process.env.DISPLAY)return x(process.env);try{let Q=await new Promise((P,X)=>f1("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(b,J)=>b?X(b):P(J)));return x(Object.fromEntries(Q.split(`
248
- `).flatMap((P)=>{let X=P.indexOf("=");return X>0?[[P.slice(0,X),P.slice(X+1)]]:[]})))}catch{return{}}}var E0=new Set;async function t1(q,x,Q){let P=await o1(),X=/^:(\d+)(?:\.\d+)?$/.exec(P.DISPLAY??"")?.[1];if(!X||`:${X}`===A8||P.WAYLAND_DISPLAY||P.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${X}`,xauthority:P.XAUTHORITY??$(q,".Xauthority"),rfbSocket:$(x,`rfb-${X}.sock`)},J=`${b.display} ${b.xauthority}`;if(E0.has(J)||!await o({path:`/tmp/.X11-unix/X${X}`},!1))return null;let N={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await u0(Q,b,x,`x11vnc-${X}.log`,N))return{...b,sound:null};return E0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
249
- `),null}function e1(q,x){let Q=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,P=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!p0(`/usr/bin/${b}`)).map(([b])=>b),X=Mq({root:q,display:x,screen:Nq,browserExec:Q,absent:P});for(let b of["","openbox","tint2","picom"])S8($(q,b));for(let[b,J]of Object.entries(X.files))Wq($(q,b),J,{mode:384});for(let[b,J]of Object.entries(zq))Wq($(q,`ara-${b}`),p1(J),{mode:384});return{root:q,openboxConfig:$(q,"openbox","rc.xml"),start:X.start}}async function q9(q,x){let Q=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
250
- `);await new Promise((P)=>{let X=I0("/bin/sh",["-c",Q],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{X.kill(),P()},V8);X.once("error",()=>{clearTimeout(b),P()}),X.once("exit",()=>{clearTimeout(b),P()})})}async function uQ(q,x={}){let Q=x.now??Date.now,P=a1(q.payload,Q());if(q.signal.throwIfAborted(),!P.video)throw new K("display_video_required","Reason desktops stream as video now; this request came without it.");let X=x.platform??process.platform;if(X!=="linux"&&X!=="darwin"&&X!=="win32")throw new K("display_video_unsupported","This machine does not serve desktop video.");let b=P.video,J=(x.video?.desktop??(X==="darwin"?async()=>S0:X==="win32"?async()=>V0:i1))();return await x9(q.signal,P,x,Q,(N)=>w0(N,{request:b,desktop:J,...P.viewer?{viewer:P.viewer}:{},viewerSameNetwork:P.viewer_same_network===!0},x.video),(N)=>G8({type:"error",code:N}))}function x9(q,x,Q,P,X,b){let J=P();return new Promise((N,T)=>{let L=null,C=!1,U=!1,y,R,Y,S=!1,W=null,G=(A)=>{if(U)return;if(W)A=W;U=!0,clearTimeout(y),clearTimeout(R),q.removeEventListener("abort",F),Y?.close();try{L?.close(1000,"display_session_over")}catch{}if("error"in A){T(A.error);return}N({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,P()-J)})},V=()=>G({error:new K("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;G({error:A instanceof K?A:new K("cancelled","Reason closed the desktop session.")})},E=()=>{if(!W||!L)return;let A=W.error;try{L.send(b(A instanceof K?A.code:"display_unavailable"))}catch{}G(W)};if(Y=X({get done(){return U||W!==null},get open(){return C&&!U&&W===null},get bufferedAmount(){return L?.bufferedAmount??0},send(A){if(U||W||!C||!L)return;try{L.send(A)}catch{G({reason:"relay_closed"})}},end:(A)=>{if(U||W)return;if(!("error"in A)){G(A);return}if(W=A,S&&C)E()}}),U){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),y=setTimeout(()=>G({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-P())),R=setTimeout(()=>G({reason:"viewer_absent"}),Q.viewerWaitMs??l1);try{L=(Q.connect??k0)(x.relay_url,(Q.loadProxy??f0)()?.url)}catch{V();return}L.binaryType="arraybuffer",L.onopen=()=>{if(U||!L)return;C=!0,Y?.opened()},L.onmessage=(A)=>{if(U)return;let f=A.data,p=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!p||p.byteLength===0)return;if(clearTimeout(R),S=!0,W){E();return}Y?.received(p)},L.onclose=()=>{if(U)return;if(!C){V();return}G({reason:"relay_closed"})},L.onerror=()=>{if(U||C)return;V()}})}
251
- export{g8 as cg,D9 as dg,y9 as eg,d as fg,T8 as gg,FQ as hg,bq as ig,pq as jg,oq as kg,I as lg,t9 as mg,e9 as ng,qQ as og,c1 as pg,A8 as qg,a1 as rg,O0 as sg,vQ as tg,S8 as ug,i1 as vg,uQ as wg};
@@ -1,3 +0,0 @@
1
- // @bun
2
- import{Ec as v,zc as q}from"./vm-hands-entry-lite-yg5h9mhm.js";function A(j=process.platform){if(q(),j==="linux"||j==="win32")v("strict")}
3
- export{A as r};
@@ -1,11 +0,0 @@
1
- // @bun
2
- import{gd as hq,hd as lq}from"./vm-hands-entry-lite-nqvb7a2m.js";import{ei as Nq,fi as vq,ji as Wq,ki as Xq,li as X,oi as dq,qi as Aq,ri as cq,ti as c,ui as P,vi as Bq}from"./vm-hands-entry-lite-2nec0vk1.js";import{Ni as Kq}from"./vm-hands-entry-lite-fbpxs065.js";import{gj as oq,hj as sq,jj as uq,mj as pq,nj as rq,oj as nq,pj as Dq}from"./vm-hands-entry-lite-bmywbwj4.js";import{xj as d}from"./vm-hands-entry-lite-hye6r7dy.js";import{Nk as Gq}from"./vm-hands-entry-lite-8gjrr6hg.js";import{randomUUID as T}from"crypto";import{chmodSync as Jq,closeSync as u,constants as m,existsSync as E,fstatSync as iq,lstatSync as A,mkdirSync as n,openSync as aq,readFileSync as g,readdirSync as Oq,readlinkSync as I,realpathSync as S,renameSync as k,rmSync as v,statSync as x,symlinkSync as Qq,unlinkSync as C,writeFileSync as h}from"fs";import{basename as r,dirname as D,isAbsolute as BG,join as K,relative as DG,resolve as O,sep as eq}from"path";import{spawnSync as Eq}from"child_process";import{createRequire as tq}from"module";var Zq=1,qG=1,GG=128,OG=65536,EG="https://reasonmachines.com/api/runtime-manifest-v2",IG=30000,CG=600000,Vq=1e4,TG=60000,SG=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var Pq=/^[a-z0-9_.-]{1,80}$/,FG=64,LG="so.ara.device-broker",JG=[LG,"com.reasonmachines.device-broker"],mJ=sq(JG),gq=["com.apple.security.cs.allow-jit","com.apple.security.cs.allow-unsigned-executable-memory"],wG=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function t(q){if(q?.aborted)throw new X("update_cancelled","Managed runtime update request was cancelled.")}function Iq(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}function Cq(q,G,J=[]){let Q=new Set([...G,...J]);return G.every((R)=>(R in q))&&Object.keys(q).every((R)=>Q.has(R))}function B(q){return typeof q==="string"&&SG.test(q)}function QG(q){return typeof q==="string"&&!Number.isNaN(Date.parse(q))&&new Date(q).toISOString()===q}function kG(q){return Xq.includes(q)}function b(q){n(q,{recursive:!0,mode:448}),Jq(q,448)}function RG(q,G){b(D(q));let J=`${q}.${process.pid}.${T()}.tmp`;try{h(J,G,{mode:384,flag:"wx"}),Jq(J,384),k(J,q)}finally{if(E(J))C(J)}}function Tq(q={}){if((q.platform??process.platform)!=="darwin")throw new X("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let J=q.environment??process.env,Q=Kq(J,"REASON_CLI_CHANNEL")==="staging",R=Q?Kq(J,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,W=q.root!==void 0||Boolean(R&&BG(R))?null:K(q.home??d(),"Library","Application Support"),_=q.root??(W?K(W,Q?"Reason Staging":"Reason","CLI"):R);return{executableName:"reason",root:_,...W?{legacyRoot:K(W,"Ara",...Q?["staging","runtime"]:["runtime"])}:{},versions:K(_,"versions"),current:K(_,"current"),previous:K(_,"previous"),brokerLock:K(_,"broker.lock"),transitionLock:K(_,"transition.lock"),lifecycleEvents:K(_,"lifecycle-events")}}function vJ(q){let G=q.legacyRoot;if(!G)return null;return{root:G,versions:K(G,"versions"),current:K(G,"current"),previous:K(G,"previous"),brokerLock:K(G,"broker.lock"),transitionLock:K(G,"transition.lock"),lifecycleEvents:K(G,"lifecycle-events")}}function F(q,G){if(!B(G))throw new X("invalid_version","Invalid managed Reason runtime version.");let J=K(q.versions,G,"ara");if(!q.executableName)return J;let Q=K(q.versions,G,q.executableName),R=(_)=>{try{return A(_),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}},U=R(J),W=R(Q);if(U&&W)throw new X("installed_artifact_mismatch","Ambiguous managed runtime executable layout.");return U?J:Q}function i(q,G){if(!B(G))throw new X("invalid_version","Invalid managed Reason runtime version.");return Sq(F(q,G))}function Sq(q){return K(D(q),r(q)==="reason"?vq:Nq)}function UG(q,G){if(!B(q)||!B(G))throw new X("invalid_version","Invalid managed Reason runtime version.");let[J,Q]=q.split("-",2),[R,U]=G.split("-",2),W=J.split(".").map(Number),_=R.split(".").map(Number);for(let H=0;H<3;H+=1){let j=W[H]-_[H];if(j!==0)return j<0?-1:1}if(Q===void 0||U===void 0){if(Q===U)return 0;return Q===void 0?1:-1}let Z=Q.split("."),$=U.split("."),Y=Math.max(Z.length,$.length);for(let H=0;H<Y;H+=1){let j=Z[H],z=$[H];if(j===void 0||z===void 0){if(j===z)return 0;return j===void 0?-1:1}if(j===z)continue;let M=/^\d+$/.test(j),w=/^\d+$/.test(z);if(M&&w)return Number(j)<Number(z)?-1:1;if(M!==w)return M?-1:1;return j<z?-1:1}return 0}function xG(q=process.arch){let G=`darwin-${q}`;if(!kG(G))throw new X("unsupported_architecture","The managed Reason runtime supports only Apple Silicon and Intel Macs.");return G}function bq(q){return[...q.matchAll(/<key>\s*([^<]+?)\s*<\/key>/g)].map((G)=>G[1].trim())}function yq(q){let G=q.match(/^CodeDirectory .*$/gm)??[];return G.length>0&&G.every((J)=>{return(/ flags=0x[0-9a-f]+\(([^)]*)\)(?: |$)/.exec(J)?.[1]?.split(/[ ,]+/).filter(Boolean)??[]).includes("runtime")})}function VG(q){let G=`TeamIdentifier=${oq}`,J=JG.map((U)=>`Identifier=${U}`),Q=bq(q.brokerEntitlements),R=bq(q.credentialLibraryEntitlements);if(!q.brokerDetail.split(`
3
- `).includes(G)||!q.brokerDetail.split(`
4
- `).some((U)=>J.includes(U))||!yq(q.brokerDetail)||Q.length!==gq.length||gq.some((U)=>!new RegExp(`<key>\\s*${U.replaceAll(".","\\.")}\\s*</key>\\s*<true\\s*/>`).test(q.brokerEntitlements)))throw new X("invalid_code_signature","Managed runtime broker has an invalid Reason signature, identifier, or entitlement set.");if(!q.credentialLibraryDetail.split(`
5
- `).includes(G)||!yq(q.credentialLibraryDetail)||R.length!==0)throw new X("invalid_code_signature","Managed runtime credential library has an invalid signature or entitlement.")}function y(q,G){let J=Eq("/usr/bin/codesign",q,{stdio:["ignore","pipe","pipe"]});if(J.status!==0)throw new X("invalid_code_signature",G);return[new TextDecoder().decode(J.stdout??new Uint8Array),new TextDecoder().decode(J.stderr??new Uint8Array)].join("")}var Fq=(q,G)=>{y(["--verify","--strict","--verbose=2",q],"Managed runtime broker code signature is invalid."),y(["--verify","--strict","--verbose=2",G],"Managed runtime credential library code signature is invalid."),VG({brokerDetail:y(["-d","--verbose=4",q],"Managed runtime broker signer could not be inspected."),brokerEntitlements:y(["-d","--entitlements",":-",q],"Managed runtime broker entitlements could not be inspected."),credentialLibraryDetail:y(["-d","--verbose=4",G],"Managed runtime credential library signer could not be inspected."),credentialLibraryEntitlements:y(["-d","--entitlements",":-",G],"Managed runtime credential library entitlements could not be inspected.")})};async function PG(q,G,J){let Q=q.headers.get("content-length");if(Q!==null){let Y=Number(Q);if(!Number.isSafeInteger(Y)||Y<0||Y>G)throw new X("response_too_large","Managed runtime response exceeded its size limit.")}if(!q.body){let Y=new Uint8Array(await q.arrayBuffer());if(Y.byteLength>G)throw new X("response_too_large","Managed runtime response exceeded its size limit.");return Y}let R=q.body.getReader(),U=[],W=0,_=()=>{if(!J)return R.read();return new Promise((Y,H)=>{let j=()=>{J.removeEventListener("abort",j),R.cancel(J.reason).catch(()=>{}),H(J.reason??new DOMException("Aborted","AbortError"))};if(J.aborted){j();return}J.addEventListener("abort",j,{once:!0}),R.read().then((z)=>{J.removeEventListener("abort",j),Y(z)},(z)=>{J.removeEventListener("abort",j),H(z)})})};try{while(!0){let Y=await _();if(Y.done)break;if(W+=Y.value.byteLength,W>G)throw await R.cancel(),new X("response_too_large","Managed runtime response exceeded its size limit.");U.push(Y.value)}}finally{try{R.releaseLock()}catch{}}let Z=new Uint8Array(W),$=0;for(let Y of U)Z.set(Y,$),$+=Y.byteLength;return Z}async function p(q){let G;try{G=new URL(q.url)}catch{throw new X("invalid_update_url","Managed runtime update URL is invalid.")}if(G.protocol!=="https:"||G.username||G.password||G.hash)throw new X("invalid_update_url","Managed runtime update URL must use HTTPS.");let J=new AbortController,Q,R=()=>{Q??="caller",J.abort(q.signal?.reason)};if(q.signal?.aborted)R();else q.signal?.addEventListener("abort",R,{once:!0});let U=setTimeout(()=>{Q??="timeout",J.abort(Error("managed runtime fetch timed out"))},q.timeoutMs),W=(_,Z)=>{if(_ instanceof X)return _;if(Q==="caller")return new X("update_cancelled","Managed runtime update request was cancelled.");if(Q==="timeout")return new X("update_fetch_timeout","Managed runtime update request timed out.");return new X("update_fetch_failed",Z)};try{let _;try{if(_=await q.fetchImpl(G,{headers:{accept:q.accept},signal:J.signal}),J.signal.aborted)throw W(J.signal.reason,"Managed runtime update request was cancelled.")}catch(Z){throw W(Z,"Managed runtime update request failed.")}if(!_.ok)throw new X("update_http_error","Managed runtime update request was rejected.");if(_.url&&new URL(_.url).protocol!=="https:")throw new X("insecure_redirect","Managed runtime update redirected to an insecure URL.");try{let Z=await PG(_,q.maximumBytes,J.signal);if(J.signal.aborted)throw W(J.signal.reason,"Managed runtime update response was cancelled.");return Z}catch(Z){throw W(Z,"Managed runtime update response failed.")}}finally{clearTimeout(U),q.signal?.removeEventListener("abort",R)}}async function WG(q,G,J=Vq,Q){let R=typeof J==="number"?J:Vq,U=typeof J==="number"?Q:J;if(U?.aborted)return!1;let W=await hq([q,"--version"],{timeoutMs:R,...U?{signal:U}:{}});return W.exitCode===0&&W.stdout.trim().replace(/^v/,"")===G}async function gG(q){let G=!1,J=null,Q=null,R=(U)=>{try{N(q.paths,U,{now:q.now})}catch{}};try{let U=q.home??d();if(!nq(q.manifest.version,U))return{status:"current"};Q=rq(U);let W=await p({url:new URL(dq,q.manifest.artifacts[q.target].broker.url).toString(),maximumBytes:Wq,fetchImpl:async(j,z)=>{let M=await q.fetchImpl(j,z);return G=M.status===404,M},timeoutMs:q.timeoutMs,accept:"application/json",signal:q.signal}),{manifest:_}=cq(new TextDecoder().decode(W),q.trustedKeys);if(_.version!==q.manifest.version||_.published_at!==q.manifest.published_at)throw new X("identity_manifest_mismatch","Background identity manifest names another release.");let Z=_.artifacts[q.target],$=await p({url:Z.url,maximumBytes:Z.size_bytes,fetchImpl:q.fetchImpl,timeoutMs:q.timeoutMs,accept:"application/octet-stream",signal:q.signal});P($,Z),b(q.workDirectory),J=K(q.workDirectory,`.identity-${process.pid}-${T()}`),n(J,{mode:448});let Y=K(J,"identity.tgz");if(h(Y,$,{mode:384,flag:"wx"}),Eq("/usr/bin/tar",["-xzf",Y,"-C",J],{stdio:"ignore",timeout:60000}).status!==0)throw new X("identity_extract_failed","Background identity archive could not be extracted.");return Dq({sourceApp:K(J,"Reason.app"),home:U,releaseSigned:!0,...q.command?{command:q.command}:{}}),R({event:"identity.refresh_completed",runtime_version:q.manifest.version,...Q?{from_version:Q}:{},to_version:q.manifest.version}),{status:"installed"}}catch(U){if(G)return{status:"unpublished"};let W=U instanceof X||U instanceof uq?U.code:"identity_install_failed";return process.stderr.write(`Reason background identity: identity_update_failed (${W})
6
- `),R({event:"identity.refresh_failed",runtime_version:q.manifest.version,...Q?{from_version:Q}:{},to_version:q.manifest.version,reason_code:W}),{status:"failed",code:W}}finally{if(J)v(J,{recursive:!0,force:!0})}}async function dJ(q){if(!B(q.currentVersion))throw new X("invalid_version","Invalid current managed runtime version.");let G=q.paths??Tq(),J=q.target??xG(),Q=q.fetchImpl??fetch,R=q.timeoutMs??IG,U=q.timeoutMs??CG,W=q.healthCheck??((H,j,z)=>WG(H,j,TG,z)),_=q.verifyCodeSignatures??Fq,Z=q.now?.()??new Date,$,Y=!1;N(G,{event:"update.check_started",runtime_version:q.currentVersion,from_version:q.currentVersion},{now:()=>Z});try{await sG({paths:G,verifyCodeSignatures:_,healthCheck:W});let H=await p({url:q.manifestUrl??EG,maximumBytes:Wq,fetchImpl:Q,timeoutMs:R,accept:"application/json",signal:q.signal}),j=Aq(new TextDecoder().decode(H),q.trustedKeys);$=j.manifest.version;let z=()=>gG({paths:G,...q.now?{now:q.now}:{},manifest:j.manifest,target:J,trustedKeys:q.trustedKeys,fetchImpl:Q,timeoutMs:U,workDirectory:G.versions,...q.home?{home:q.home}:{},...q.identityCommand?{command:q.identityCommand}:{},...q.signal?{signal:q.signal}:{}});if(UG($,q.currentVersion)<=0)return N(G,{event:"update.not_available",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-Z.getTime())},{now:q.now}),Yq(G),{status:"not_available",currentVersion:q.currentVersion,offeredVersion:$,...$===q.currentVersion?{identity:await z()}:{}};let M=j.manifest.artifacts[J];N(G,{event:"update.download_started",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$},{now:q.now});let w=await p({url:M.broker.url,maximumBytes:M.broker.size_bytes,fetchImpl:Q,timeoutMs:U,accept:"application/octet-stream",signal:q.signal});P(w,M.broker),t(q.signal);let e=await p({url:M.credential_library.url,maximumBytes:M.credential_library.size_bytes,fetchImpl:Q,timeoutMs:U,accept:"application/octet-stream",signal:q.signal});P(e,M.credential_library),N(G,{event:"update.downloaded",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$},{now:q.now}),N(G,{event:"update.verified",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$},{now:q.now}),t(q.signal);let kq=XG({paths:G,version:$,artifact:M.broker,bytes:w,credentialLibraryArtifact:M.credential_library,credentialLibraryBytes:e,verifyCodeSignatures:_}),xq;try{xq=await W(kq.executablePath,$,q.signal)}catch(l){throw t(q.signal),l}if(t(q.signal),!xq)throw new X("pre_activation_health_failed","Managed runtime preflight failed.");let V=cG(G,$);if(!V.changed&&V.toVersion!==$)return N(G,{event:"update.not_available",runtime_version:V.toVersion,from_version:V.toVersion,to_version:$,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-Z.getTime())},{now:q.now}),{status:"not_available",currentVersion:V.toVersion,offeredVersion:$};if(Y=V.changed,!await W(G.current,$)){if(V.fromVersion){let l=jG(G,$);N(G,{event:"update.rollback",runtime_version:l.toVersion,from_version:l.fromVersion,to_version:l.toVersion,reason_code:"post_activation_health_failed"},{now:q.now})}else HG(G,$);throw f(G),Y=!1,new X("post_activation_health_failed","Managed runtime activation failed.")}return f(G),Yq(G),N(G,{event:"update.activated",runtime_version:$,from_version:q.currentVersion,to_version:$,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-Z.getTime())},{now:q.now}),{status:"activated",fromVersion:q.currentVersion,toVersion:$,installed:kq.installed,identity:await z()}}catch(H){throw N(G,{event:"update.failed",runtime_version:Y?$??q.currentVersion:q.currentVersion,from_version:q.currentVersion,...$?{to_version:$}:{},reason_code:H instanceof X?H.code:"update_failed",duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-Z.getTime())},{now:q.now}),H}}function fq(q,G,J){try{let Q=A(D(q));if(!Q.isDirectory()||Q.isSymbolicLink())return!1;let R=A(q);if(!R.isFile()||R.isSymbolicLink()||R.size!==G.size_bytes)return!1;let U=Sq(q),W=A(U);return W.isFile()&&!W.isSymbolicLink()&&W.size===J.size_bytes&&c(g(q))===G.sha256&&c(g(U))===J.sha256}catch{return!1}}function XG(q){let G=F(q.paths,q.version);P(q.bytes,q.artifact),P(q.credentialLibraryBytes,q.credentialLibraryArtifact);let J=q.verifyCodeSignatures??Fq;if(b(q.paths.root),b(q.paths.versions),E(D(G))){if(!fq(G,q.artifact,q.credentialLibraryArtifact))throw new X("installed_artifact_mismatch","The installed runtime version does not match the verified artifact.");return J(G,i(q.paths,q.version)),{installed:!1,executablePath:G}}let Q=K(q.paths.versions,`.install-${q.version}-${process.pid}-${T()}`),R=K(Q,r(G)),U=Sq(R);n(Q,{mode:448});try{h(R,q.bytes,{mode:448,flag:"wx"}),Jq(R,448),h(U,q.credentialLibraryBytes,{mode:448,flag:"wx"}),Jq(U,448),J(R,U);try{k(Q,D(G))}catch(W){if(!fq(G,q.artifact,q.credentialLibraryArtifact))throw W;return{installed:!1,executablePath:G}}return{installed:!0,executablePath:G}}finally{v(Q,{recursive:!0,force:!0})}}function bG(q,G){if(!B(G))throw new X("invalid_version","Invalid managed Reason runtime version.");return`versions/${G}/${r(F(q,G))}`}function Rq(q,G){b(D(q));let J=`${q}.${process.pid}.${T()}.tmp`;try{Qq(G,J),k(J,q)}finally{if(E(J))C(J)}}var yG=/^\.(?:ara|reason)-worker-(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)-(darwin-(?:arm64|x64))\.([0-9A-Za-z]{6})$/,fG=new Set(["reason","ara"]);function ZG(q,G){let J=D(q),Q=O(J,G),R=D(Q),U=yG.exec(r(R));if(!fG.has(r(Q))||D(R)!==J||!U||!B(U[1])||!Xq.includes(U[2]))return!1;try{return A(R).isDirectory()&&D(S(R))===S(J)&&A(Q).isFile()&&A(Bq(R)).isFile()}catch(W){if(W.code==="ENOENT")return!1;throw W}}function _G(q,G,J){try{if(I(q)!==G)return!1;C(q)}catch(Q){if(Q.code==="ENOENT")return!1;throw Q}try{return Qq(J,q),!0}catch(Q){if(Q.code==="EEXIST")return!1;try{Qq(G,q)}catch(R){if(R.code!=="EEXIST")throw R}throw Q}}function $G(q,G){if(!q.legacyRoot)return!1;let J;try{if(!A(G).isSymbolicLink())return!1;J=I(G)}catch(R){if(R.code==="ENOENT")return!1;throw R}if(O(D(G),J)!==K(q.legacyRoot,"current"))return!1;if(!_G(G,J,q.current))return!1;let Q=L(q);if(Q)N(q,{event:"service.launcher_adopted",runtime_version:Q,to_version:Q,reason_code:"legacy_runtime_root"});return!0}function mG(q,G){let J=K(q,".local","bin"),Q=K(J,"ara"),R=K(J,"reason"),U=A(Q,{throwIfNoEntry:!1});if(U?.isSymbolicLink()&&I(Q)==="reason")return R;if(U||!A(R,{throwIfNoEntry:!1})?.isSymbolicLink())return Q;let W=I(R);return W===G.current||ZG(R,W)?R:Q}function vG(q){let G=q.launcherPath??mG(q.home??d(),q.paths);try{if(A(G).isSymbolicLink()){let Q=I(G);if(Q===q.paths.current)return"managed";if(ZG(G,Q)&&_G(G,Q,q.paths.current)){let R=_q(q.paths.current,q.paths.executableName)??"unknown";return N(q.paths,{event:"service.launcher_adopted",runtime_version:R,to_version:R,reason_code:"legacy_curl_entrypoint"}),"adopted"}if($G(q.paths,G))return"adopted"}return"conflict"}catch(J){if(J.code!=="ENOENT")throw J}n(D(G),{recursive:!0,mode:448});for(let J=0;J<4;J+=1)try{return Qq(q.paths.current,G),"created"}catch(Q){if(Q.code!=="EEXIST")throw Q;try{return A(G).isSymbolicLink()&&I(G)===q.paths.current?"managed":"conflict"}catch(R){if(R.code!=="ENOENT")throw R}}return"conflict"}function _q(q,G){let J;try{if(!A(q).isSymbolicLink())return null;J=I(q)}catch{return null}let Q=J.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return Q&&(Q[2]==="ara"||Q[2]===G)?Q[1]:null}function L(q){return _q(q.current,q.executableName)}function cJ(q,G=process.execPath){try{return S(q.current)===S(G)}catch{return!1}}function Uq(q,G,J){let R=DG(G,q).split(eq);return R.length===2&&B(R[0])&&(R[1]==="ara"||J!==void 0&&R[1]===J)?R[0]:null}function KG(q,G){try{return A(G).isSymbolicLink()&&O(D(G),I(G))===O(q.current)}catch{return!1}}function hJ(q,G=process.execPath){try{return Uq(S(G),S(q.versions),q.executableName)!==null}catch{let J=O(G);return J===O(q.current)||KG(q,J)||Uq(J,O(q.versions),q.executableName)!==null}}function lJ(q,G=process.execPath){try{return Uq(S(G),S(q.versions),q.executableName)}catch{let J=O(G);if(J===O(q.current)||KG(q,J))return L(q);return Uq(J,O(q.versions),q.executableName)}}function dG(q,G,J={}){let Q=F(q,G),R=i(q,G);if(!E(Q)||!x(Q).isFile()||!E(R)||!x(R).isFile())throw new X("runtime_not_installed","Managed Reason runtime version is not installed.");let U=Lq(q,G,J.allowDowngrade);if(U)return U;return a(q,G,()=>{return YG(q,G,void 0,J.allowDowngrade)})}function Lq(q,G,J=!1){let Q=L(q);if(!Q)return null;if(Q===G)return{changed:!1,fromVersion:Q,toVersion:Q};if(!J&&UG(G,Q)<=0&&!(/^\d+\.\d+\.\d+-desktop\.v1\.\d+\.\d+\.\d+$/.test(G)&&/^\d+\.\d+\.\d+-desktopdev\./.test(Q)))return{changed:!1,fromVersion:Q,toVersion:Q};return null}function YG(q,G,J,Q=!1){let R=Lq(q,G,Q);if(R)return R;let U=L(q);if(J?.(U),U)Rq(q.previous,I(q.current));else if(E(q.previous))C(q.previous);return Rq(q.current,bG(q,G)),{changed:!0,fromVersion:U,toVersion:G}}function cG(q,G){let J=F(q,G),Q=i(q,G);if(!E(J)||!x(J).isFile()||!E(Q)||!x(Q).isFile())throw new X("runtime_not_installed","Managed Reason runtime version is not installed.");return a(q,G,()=>YG(q,G,(R)=>{oG(q,{schema_version:Zq,from_version:R,to_version:G})}))}function jG(q,G){return a(q,G,()=>{if(L(q)!==G)throw new X("rollback_fence_failed","Managed runtime changed before rollback could be applied.");let J=_q(q.previous,q.executableName);if(!J||J===G)throw new X("rollback_unavailable","No previous managed runtime is available.");let Q=F(q,J),R=i(q,J);if(!E(Q)||!x(Q).isFile()||!E(R)||!x(R).isFile())throw new X("rollback_unavailable","Previous managed runtime is not installed.");let U=I(q.previous),W=I(q.current);if(O(D(q.previous),U)!==O(Q))throw new X("rollback_fence_failed","Previous runtime pointer does not match its installed layout.");return Rq(q.current,U),Rq(q.previous,W),{fromVersion:G,toVersion:J}})}function hG(){let q=Eq("/bin/ps",["-axww","-o","args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000,maxBuffer:16777216});return q.status===0&&typeof q.stdout==="string"?q.stdout:null}function Yq(q){let G=[];try{let J=L(q);if(!J||jq(q))return G;let Q=Oq(q.versions).filter((U)=>B(U));if(Q.length<=2)return G;let R=hG();if(R===null)return G;a(q,J,()=>{let U=new Set([L(q),_q(q.previous,q.executableName)]);if(jq(q))return;for(let W of Q){if(U.has(W))continue;let _=K(q.versions,W);if(R.includes(`${_}${eq}`))continue;try{v(_,{recursive:!0,force:!0}),G.push(W)}catch{}}})}catch{}return G}function HG(q,G){a(q,G,()=>{if(L(q)!==G)throw new X("rollback_fence_failed","Managed runtime changed before rollback could be applied.");C(q.current)})}function wq(q){return q.activationState??K(q.root,"activation.json")}function lG(q){return Iq(q)&&Cq(q,["schema_version","from_version","to_version"])&&q.schema_version===Zq&&(q.from_version===null||B(q.from_version))&&B(q.to_version)}function jq(q){try{let G=wq(q),J=A(G);if(!J.isFile()||J.isSymbolicLink()||J.nlink!==1||(J.mode&63)!==0||J.size>4096)throw new X("invalid_activation_state","Managed runtime activation state is invalid.");let Q=JSON.parse(g(G,"utf8"));if(!lG(Q))throw new X("invalid_activation_state","Managed runtime activation state is invalid.");return Q}catch(G){if(G instanceof X)throw G;if(G.code==="ENOENT")return null;throw new X("invalid_activation_state","Managed runtime activation state is invalid.")}}function oG(q,G){RG(wq(q),JSON.stringify(G)+`
7
- `)}function f(q){try{C(wq(q))}catch(G){if(G.code!=="ENOENT")throw G}}async function sG(q){let G=jq(q.paths);if(!G)return"none";let J=L(q.paths);if(J===G.from_version)return f(q.paths),"cleared";if(J!==G.to_version)throw new X("rollback_fence_failed","Managed runtime changed before activation recovery could be applied.");let Q=q.verifyCodeSignatures??Fq,R=q.healthCheck??WG,U=!1;try{let W=F(q.paths,G.to_version);Q(W,i(q.paths,G.to_version)),U=await R(W,G.to_version)}catch{U=!1}if(U)return f(q.paths),N(q.paths,{event:"update.activated",runtime_version:G.to_version,...G.from_version?{from_version:G.from_version}:{},to_version:G.to_version,reason_code:"restart_recovery"}),"committed";if(G.from_version){let W=jG(q.paths,G.to_version);return f(q.paths),N(q.paths,{event:"update.rollback",runtime_version:W.toVersion,from_version:W.fromVersion,to_version:W.toVersion,reason_code:"restart_recovery"}),"rolled_back"}return HG(q.paths,G.to_version),f(q.paths),N(q.paths,{event:"update.rollback",runtime_version:G.to_version,from_version:G.to_version,reason_code:"restart_recovery"}),"rolled_back"}function uG(q){return Iq(q)&&Cq(q,["schema_version","pid","nonce","started_at","runtime_version"])&&q.schema_version===Zq&&typeof q.pid==="number"&&Number.isSafeInteger(q.pid)&&q.pid>0&&typeof q.nonce==="string"&&/^[0-9a-f-]{36}$/.test(q.nonce)&&QG(q.started_at)&&B(q.runtime_version)}function zG(q,G){try{let J=A(q);if(!J.isDirectory()||!Gq(J))return null;let Q=aq(K(q,G),m.O_RDONLY|m.O_NOFOLLOW|m.O_NONBLOCK);try{let R=iq(Q);if(!R.isFile()||R.nlink!==1||!Gq(R)||R.size>4096)return null;return g(Q,"utf8")}finally{u(Q)}}catch{return null}}function Hq(q){try{let G=JSON.parse(zG(q,"owner.json")??"null");return uG(G)?G:null}catch{return null}}function MG(q){try{return process.kill(q,0),!0}catch(G){return!(G instanceof Error&&("code"in G)&&G.code==="ESRCH")}}var mq="lease",pG=2,rG=4,o;function nG(){if(o!==void 0)return o;if(o=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let q;try{q=tq(import.meta.url)("bun:ffi")}catch{return null}let G=process.platform==="darwin"?"__error":"__errno_location",J=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let Q of J)try{let R=q.dlopen(Q,{flock:{args:[q.FFIType.i32,q.FFIType.i32],returns:q.FFIType.i32},[G]:{args:[],returns:q.FFIType.ptr}}),U=R.symbols[G]();if(U===null)continue;return o={flock:(W,_)=>R.symbols.flock(W,_),errno:()=>q.read.i32(U),wouldBlock:process.platform==="darwin"?35:11},o}catch{}return null}var s,iG=3221225472,aG=4,eG=128,tG=32;function qJ(q){if(s===void 0){s=null;try{let U=tq(import.meta.url)("bun:ffi"),{FFIType:W}=U;s={kernel:U.dlopen("kernel32.dll",{CreateFileW:{args:[W.ptr,W.u32,W.u32,W.ptr,W.u32,W.u32,W.ptr],returns:W.i64_fast},CloseHandle:{args:[W.i64_fast],returns:W.i32},GetLastError:{args:[],returns:W.u32}}).symbols,ptr:(Z)=>U.ptr(Z)}}catch{return null}}if(!s)return null;let{kernel:G,ptr:J}=s,Q=Buffer.from(`${q}\x00`,"utf16le"),R=G.CreateFileW(J(Q),iG,0,null,aG,eG,null);if(Number(R)===-1)return G.GetLastError()===tG?"busy":null;return{release:()=>{G.CloseHandle(R)}}}function GJ(q){if(process.platform==="win32")return qJ(`${q}.lease`);let G=nG();if(!G)return null;let J=aq(`${q}.lease`,m.O_RDWR|m.O_CREAT|m.O_NOFOLLOW,384);try{let Q=iq(J);if(!Q.isFile()||Q.nlink!==1||!Gq(Q))return u(J),"busy";if(G.flock(J,pG|rG)===0)return{release:()=>u(J)};let R=G.errno();return u(J),R===G.wouldBlock?"busy":null}catch(Q){throw u(J),Q}}function zq(q){b(D(q.path));let G=GJ(q.path);if(G==="busy")return{acquired:!1,owner:Hq(q.path),recoveredStaleOwner:!1};let J=G!==null;try{let Q=JJ(q,G);if(Q.acquired)J=!1;return Q}finally{if(J)G.release()}}function JJ(q,G){let J=q.alive??MG,Q=!1;for(let R=0;R<4;R+=1){let U={schema_version:Zq,pid:q.pid??process.pid,nonce:q.nonce?.()??T(),started_at:(q.now?.()??new Date).toISOString(),runtime_version:q.runtimeVersion},W=`${q.path}.init-${process.pid}-${T()}`,_=!1;try{if(n(W,{mode:448}),h(K(W,"owner.json"),`${JSON.stringify(U)}
8
- `,{mode:384,flag:"wx"}),G!==null)h(K(W,mq),`flock
9
- `,{mode:384,flag:"wx"});q.beforePublish?.();try{throw A(q.path),Object.assign(Error("Managed runtime lock exists."),{code:"EEXIST"})}catch($){if($.code!=="ENOENT")throw $}k(W,q.path),_=!0;let Z=!1;return{acquired:!0,owner:U,recoveredStaleOwner:Q,release(){if(Z)return;if(Z=!0,Hq(q.path)?.nonce===U.nonce)v(q.path,{recursive:!0,force:!0});G?.release()}}}catch(Z){let $=Z.code;if(!["EEXIST","ENOTEMPTY"].includes($??""))throw Z;let Y=Hq(q.path),H=(q.now?.()??new Date).getTime(),j=Y&&q.staleAfterMs!==void 0?H-Date.parse(Y.started_at)<q.staleAfterMs:!1,z=Y!==null&&!(G!==null&&zG(q.path,mq)!==null)&&J(Y.pid);if(!Y||z||j)return{acquired:!1,owner:Y,recoveredStaleOwner:!1};let M=`${q.path}.stale-${process.pid}-${T()}`;try{k(q.path,M),v(M,{recursive:!0,force:!0}),Q=!0}catch(w){let e=w.code;if(!["ENOENT","EEXIST"].includes(e??""))throw w}}finally{if(!_)v(W,{recursive:!0,force:!0})}}throw new X("lock_unavailable","Could not acquire the managed Reason runtime lock.")}var QJ=20000;function a(q,G,J){if(!B(G))throw new X("invalid_version","Invalid managed Reason runtime version.");let Q=Date.now()+QJ,R=zq({path:q.transitionLock,runtimeVersion:G,staleAfterMs:60000});while(!R.acquired&&Date.now()<Q)lq(100),R=zq({path:q.transitionLock,runtimeVersion:G,staleAfterMs:60000});if(!R.acquired)throw new X("transition_busy","Another managed Reason runtime transition is in progress.");try{return J()}finally{R.release()}}function oJ(q){if(!B(q.runtimeVersion))throw new X("invalid_version","Invalid managed Reason runtime version.");let G=q.paths??Tq();return zq({path:G.brokerLock,runtimeVersion:q.runtimeVersion,...q.pid===void 0?{}:{pid:q.pid},...q.now===void 0?{}:{now:q.now},...q.nonce===void 0?{}:{nonce:q.nonce},...q.alive===void 0?{}:{alive:q.alive},...q.beforePublish===void 0?{}:{beforePublish:q.beforePublish}})}function NG(q){return Iq(q)&&Cq(q,["schema_version","event_id","occurred_at","event","runtime_version"],["from_version","to_version","reason_code","duration_ms","attempt_count","retry_in_ms","capabilities"])&&q.schema_version===qG&&typeof q.event_id==="string"&&/^[0-9a-f-]{36}$/.test(q.event_id)&&QG(q.occurred_at)&&typeof q.event==="string"&&wG.includes(q.event)&&B(q.runtime_version)&&(q.from_version===void 0||B(q.from_version))&&(q.to_version===void 0||B(q.to_version))&&(q.reason_code===void 0||typeof q.reason_code==="string"&&Pq.test(q.reason_code))&&(q.duration_ms===void 0||typeof q.duration_ms==="number"&&Number.isSafeInteger(q.duration_ms)&&q.duration_ms>=0&&q.duration_ms<=86400000)&&(q.attempt_count===void 0||typeof q.attempt_count==="number"&&Number.isSafeInteger(q.attempt_count)&&q.attempt_count>=1&&q.attempt_count<=1e5)&&(q.retry_in_ms===void 0||typeof q.retry_in_ms==="number"&&Number.isSafeInteger(q.retry_in_ms)&&q.retry_in_ms>=0&&q.retry_in_ms<=30000)&&(q.capabilities===void 0||Array.isArray(q.capabilities)&&q.capabilities.length<=FG&&q.capabilities.every((G)=>typeof G==="string"&&Pq.test(G)))}var RJ=/^(\d{22}-[0-9a-f-]{36}\.json)$/,UJ=/^(\d{22}-[0-9a-f-]{36}\.json)\.sending-(\d+)-[0-9a-f-]{36}$/,WJ=300000,qq=0n;function XJ(q){let G=BigInt(new Date(q.occurred_at).getTime())*1000000n;return qq=G>qq?G:qq+1n,`${String(qq).padStart(22,"0")}-${q.event_id}.json`}function $q(q){try{return Oq(q.lifecycleEvents).filter((G)=>RJ.test(G)).sort()}catch{return[]}}function Mq(q){try{let G=JSON.parse(g(q,"utf8"));return NG(G)?G:null}catch{return null}}function AG(q,G=MG,J=Date.now()){let Q;try{Q=Oq(q.lifecycleEvents)}catch{return}for(let R of Q){let U=R.match(UJ);if(!U)continue;let W=K(q.lifecycleEvents,R),_=K(q.lifecycleEvents,U[1]),Z=!G(Number(U[2]));if(!Z)try{Z=J-x(W).mtimeMs>=WJ}catch{continue}if(!Z)continue;try{k(W,_)}catch($){let Y=$.code;if(Y==="EEXIST")C(W);else if(Y!=="ENOENT")throw $}}}function ZJ(q){let J=$q(q).flatMap((R)=>{try{return[{name:R,size:x(K(q.lifecycleEvents,R)).size}]}catch{return[]}}),Q=J.reduce((R,U)=>R+U.size,0);while(J.length>GG||Q>OG){let R=J.shift();if(!R)break;try{C(K(q.lifecycleEvents,R.name)),Q-=R.size}catch(U){if(U.code!=="ENOENT")throw U}}}function sJ(q){return AG(q),$q(q).map((G)=>Mq(K(q.lifecycleEvents,G))).filter((G)=>G!==null).slice(-GG)}function N(q,G,J={}){let Q={schema_version:qG,event_id:J.eventId?.()??T(),occurred_at:(J.now?.()??new Date).toISOString(),...G};if(!NG(Q))throw new X("invalid_lifecycle_event","Managed runtime lifecycle event is invalid.");return b(q.lifecycleEvents),RG(K(q.lifecycleEvents,XJ(Q)),`${JSON.stringify(Q)}
10
- `),ZJ(q),Q}function uJ(q,G){if(G.length===0)return 0;let J=new Set(G),Q=0;for(let R of $q(q)){let U=R.slice(23,-5);if(!J.has(U))continue;try{C(K(q.lifecycleEvents,R)),Q+=1}catch(W){if(W.code!=="ENOENT")throw W}}return Q}async function pJ(q,G,J){AG(q);let Q=0;for(let R of $q(q)){let U=K(q.lifecycleEvents,R);if(J){let Z=Mq(U);if(!Z||!J(Z))continue}let W=`${U}.sending-${process.pid}-${T()}`;try{k(U,W)}catch(Z){if(Z.code==="ENOENT")continue;throw Z}let _=Mq(W);if(!_){C(W);continue}try{await G(_),C(W),Q+=1}catch{try{k(W,U)}catch(Z){if(Z.code!=="ENOENT")throw Z}break}}return Q}function rJ(q){let G=q.paths??Tq(),J=q.sourceExecutable??process.execPath,Q=q.sourceCredentialLibrary??Bq(D(S(J))),R=q.now?.()??new Date,U=E(F(G,q.version))&&Lq(G,q.version,q.allowDowngrade)!==null;if(!U)N(G,{event:"service.install_started",runtime_version:q.version,to_version:q.version},{now:()=>R});try{let W=g(J),_;try{_=g(Q)}catch{throw new X("credential_boundary_unavailable","Managed runtime credential boundary is unavailable.")}let Z={url:"https://bootstrap.invalid/ara",sha256:c(W),size_bytes:W.byteLength},$={url:`https://bootstrap.invalid/${Nq}`,sha256:c(_),size_bytes:_.byteLength},Y=XG({paths:G,version:q.version,artifact:Z,bytes:W,credentialLibraryArtifact:$,credentialLibraryBytes:_,...q.verifyCodeSignatures?{verifyCodeSignatures:q.verifyCodeSignatures}:{}}),H=pq(J);if(E(H))Dq({sourceApp:H,home:q.home??d()});let j=dG(G,q.version,{allowDowngrade:q.allowDowngrade});if(!U)Yq(G);let z=q.home??d(),M=q.installLauncher===!1?"skipped":vG({paths:G,...q.launcherPath?{launcherPath:q.launcherPath}:{home:z}});if(q.installLauncher!==!1&&!q.launcherPath)$G(G,K(z,".local","bin","reason"));if(M==="conflict")N(G,{event:"service.launcher_conflict",runtime_version:q.version,to_version:q.version,reason_code:"existing_entrypoint"},{now:q.now});if(!U)N(G,{event:"service.install_completed",runtime_version:q.version,to_version:q.version,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-R.getTime())},{now:q.now});return{installed:Y.installed,activated:j.changed,activeVersion:j.toVersion,executablePath:F(G,j.toVersion),launcher:M}}catch(W){throw N(G,{event:"service.install_failed",runtime_version:q.version,to_version:q.version,reason_code:W instanceof X?W.code:"install_failed",duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-R.getTime())},{now:q.now}),W}}
11
- export{Zq as L,qG as M,GG as N,OG as O,EG as P,IG as Q,CG as R,Vq as S,TG as T,LG as U,mJ as V,wG as W,Tq as X,vJ as Y,F as Z,i as _,UG as $,xG as aa,VG as ba,Fq as ca,p as da,WG as ea,dJ as fa,XG as ga,vG as ha,_q as ia,L as ja,cJ as ka,hJ as la,lJ as ma,dG as na,jG as oa,sG as pa,zq as qa,oJ as ra,sJ as sa,N as ta,uJ as ua,pJ as va,rJ as wa};
@@ -1,7 +0,0 @@
1
- // @bun
2
- import{Jc as n}from"./vm-hands-entry-lite-69ray4x8.js";import{fd as r}from"./vm-hands-entry-lite-nqvb7a2m.js";import{Ek as a,Fk as s,Ik as i}from"./vm-hands-entry-lite-8gjrr6hg.js";import{Rk as B}from"./vm-hands-entry-lite-40nkzw38.js";import{spawn as f,spawnSync as v}from"child_process";import{existsSync as U,mkdtempSync as o,readFileSync as t,readdirSync as _j,realpathSync as Sj,rmSync as e,statSync as jj}from"fs";import{platform as h,tmpdir as qj}from"os";import{dirname as E,join as H,win32 as T}from"path";import{fileURLToPath as Mj,pathToFileURL as y}from"url";var kj=["bwrap","socat","rg"],Fj=2000,g=20000,Pj=3,w=4000,Ej=new Set([".git",".hg",".svn","node_modules"]),Rj=["runAsHostUid","sysrq-trigger"],zj=H(E(E(Mj(import.meta.url))),"packages","sandbox-runtime"),Dj=H(zj,"src","index.ts"),Gj=!1;function oj(){Gj=!0}function Jj(){return Gj?H(E(Sj(process.execPath)),"runtime","srt"):void 0}function C(){let j=H(Jj()??zj,"vendor","srt-win"),q=H(j,process.arch,"srt-win.exe"),G=H(j,"arm64","srt-win.exe");return process.arch==="x64"&&!U(q)&&U(G)?G:q}var tj="confined commands need the Windows sandbox: run `reason connect` and approve the Windows prompt.";function ej(j=C()){let q=v(j,["status"],{encoding:"utf8",timeout:15000,windowsHide:!0});try{let G=JSON.parse(q.stdout??"");return q.status===0&&G.user?.user?.exists===!0&&G.user.cred_present===!0}catch{return!1}}function jq(j=C()){let q=v(j,["install"],{stdio:["ignore","ignore","ignore"],timeout:120000,windowsHide:!0});return q.status===0?"installed":q.status===10?"cancelled":"failed"}async function Kj(){let j=Jj();if(j&&process.platform==="linux"&&!U(H(j,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(j&&process.platform==="win32"&&!U(C()))throw Error("packaged_sandbox_runtime_vendor_missing");if(j){let J=t(H(j,"sandbox-runtime.mjs"),"utf8");for(let K of Rj)if(!J.includes(K))throw Error(`packaged_sandbox_runtime_fork_missing:${K}`)}let z=(await import(j?y(H(j,"sandbox-runtime.mjs")).href:y(Dj).href)).SandboxManager;if(!z||typeof z.initialize!=="function"||typeof z.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:z}}function Wj(j={}){if((j.platformName??h())!=="linux")return!1;let G=j.fileExists??U,z=j.readFile??((J)=>t(J,"utf8"));for(let J of["/.dockerenv","/run/.containerenv"])try{if(G(J))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(z("/proc/1/cgroup"))}catch{return!1}}function Qj(j){return["/bin/true","/usr/bin/true"].find((q)=>j(q))??null}function xj(j,q){return j==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",q]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",q]}function Oj(j,q){try{let G=v("bwrap",xj(j,q),{stdio:"ignore",timeout:Fj});return!G.error&&G.status===0}catch{return!1}}function fj(j){let q=j.platformName??h(),G=j.fileExists??U;if(q==="win32")return(j.bash??a)()&&G(C())?X??"strict":null;if(q!=="linux")return null;let z=j.hasExecutable??r;if(!kj.every((V)=>z(V)))return null;let J=Qj(G);if(!J)return null;let K=X??(j.containerized??Wj({platformName:q})?"weak":"strict");return(j.probeNamespaces??((V)=>Oj(V,J)))(K)?K:null}var _=null,R=!1,Y=null,c=null,u=null,X=null,S=null,P=null,M=null,D=[],N=new Map;function W(){throw A("sandbox_mode_conflict"),new B("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function qq(j){if(X!==null&&X!==j||R&&_!==null&&_!==j||S!==null&&S!==j)W();X=j}function A(j){if(!Y)process.stderr.write(`Reason worker: confined commands are off (${j})
3
- `);Y=j}function Vj(j){if(Y)return!1;if(!R){if(_=fj(j??{}),R=!0,_&&!j)Yj()}return _!==null}function vj(){return Vj()?_:null}var k=null,I=0;function x(j,q){if(Y)throw new B("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(X&&j.sandboxMode&&X!==j.sandboxMode)W();let G=X??j.sandboxMode??vj();if(!G)throw new B("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(S&&S!==G)W();return S=G,k??=(async()=>{let{SandboxManager:z}=await(j.loadSandboxRuntime??Kj)();return await z.initialize(uj(G,q)),z})().catch((z)=>{if(k=null,q)P=null,process.stderr.write(`Reason worker: the Windows sandbox did not start for this folder (${String(z).slice(0,500)})
4
- `);else A(`initialize_failed: ${String(z)}`);throw z instanceof B?z:new B("sandbox_unavailable","The confined execution sandbox failed to start.")}),k.then((z)=>{if(Y)throw new B("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return z})}function O(){if(I-=1,I===0)for(let j of D.splice(0))j()}async function Zj(j,q=!0,G,z){let J=z===void 0?1/0:Date.now()+z;await Bj();let K=bj();if(q)await K;let Q=JSON.stringify(j),V=!1,$=()=>{if(!V)return;V=!1;let Z=(N.get(Q)??1)-1;if(Z>0)N.set(Q,Z);else N.delete(Q)};try{for(;;){if(G?.aborted)throw new B("cancelled","Operation was cancelled.");if(Date.now()>=J)return!1;if(M){await M;continue}let Z=N.keys().next().value;if(P??=Z??Q,P===Q&&(Z===void 0||Z===Q))break;if(!V){V=!0,N.set(Q,(N.get(Q)??0)+1);continue}if(I===0&&Z===Q){$j();continue}await new Promise((L)=>{if(D.push(L),G?.addEventListener("abort",()=>L(),{once:!0}),J!==1/0)setTimeout(L,Math.max(0,J-Date.now())).unref?.()})}return I+=1,!0}finally{if(V&&I===0)for(let Z of D.splice(0))Z();$()}}function $j(){return M??=Xj().finally(()=>{M=null}),M}function Hj(j,q,G=process.env){let z=G.USERPROFILE?T.resolve(G.USERPROFILE).toLowerCase():null,J=T.resolve(j).toLowerCase(),K=z!==null&&J.startsWith(`${z}\\`),Q=q?Lj(G).filter((V)=>V.toLowerCase()===J||V.toLowerCase().startsWith(`${J}\\`)):[];return{denyRead:[],allowRead:[j],allowWrite:q?[j]:[],denyWrite:q?Q:K?[]:[j]}}function Lj(j,q=process.execPath){let G=new Map;for(let z of[...(j.PATH??j.Path??"").split(";"),T.dirname(q)]){if(!z||!T.isAbsolute(z))continue;let J=T.resolve(z);if(!G.has(J.toLowerCase()))G.set(J.toLowerCase(),J)}return[...G.values()]}function hj(j=process.env,q=process.execPath){let G=[j.SystemRoot,j.ProgramFiles,j["ProgramFiles(x86)"],j.ProgramW6432,j.ProgramData,j.USERPROFILE].filter((z)=>!!z).map((z)=>T.resolve(z).toLowerCase());return Lj(j,q).filter((z)=>{let J=z.toLowerCase();return!G.some((K)=>J===K||J.startsWith(`${K}\\`))})}var l=null,m=null;function Bj(j=C()){return m??=(async()=>{let q;try{q=JSON.parse((await Uj(j,["status"])).stdout).user?.user?.sid}catch{return null}if(typeof q!=="string"||!/^S-1-[0-9-]+$/.test(q))return null;if(!await new Promise((z)=>{let J=f(i("icacls"),[j,"/grant",`*${q}:(RX)`],{stdio:"ignore",windowsHide:!0,timeout:30000});J.on("error",()=>z(!1)),J.on("close",(K)=>z(K===0))}))process.stderr.write(`Reason worker: could not let the Windows sandbox user run srt-win.exe
5
- `);return q})(),m}function Uj(j,q,G){return new Promise((z)=>{let J=f(j,q,{stdio:["pipe","pipe","ignore"],windowsHide:!0,timeout:120000}),K="";J.stdout?.setEncoding("utf8").on("data",(Q)=>{K+=Q}),J.on("error",()=>z({status:null,stdout:K})),J.on("close",(Q)=>z({status:Q,stdout:K})),J.stdin?.end(G??"")})}function bj(j=C()){return l??=(async()=>{let q=hj();if(q.length===0)return;let G=await Bj(j),z=G?await Uj(j,["acl","stamp","--holder-pid",String(process.ppid),"--sandbox-user-sid",G],JSON.stringify({denyRead:[],denyWrite:q})):null;if(!z||z.status!==0&&z.status!==2)A(`program_folder_deny_failed: ${z?`exit ${z.status}`:"no sandbox user"}`),process.stderr.write(`Reason worker: could not deny the Windows sandbox writes to PATH folders (${z?`exit ${z.status}`:"no sandbox user"}); confined commands are off
6
- `)})(),l}var yj=`h=$(mktemp -d) || exit 125; trap 'rm -rf "$h"' EXIT; mkdir -p "$h/AppData/Roaming" "$h/AppData/Local"; w=$(cygpath -w "$h"); export HOME="$h" USERPROFILE="$w" APPDATA="$w\\AppData\\Roaming" LOCALAPPDATA="$w\\AppData\\Local" TEMP="$w" TMP="$w"; `;async function Xj(){let j=k;if(k=null,P=null,!j)return;try{await(await j).reset()}catch{}}async function Yj(j={}){if(Y)return!1;if(j.loadSandboxRuntime)return d(j.loadSandboxRuntime);if(!Vj())return!1;return c??=d(Kj),c}async function d(j){try{let{SandboxManager:q}=await j();if(process.platform==="win32"){if(!U(C()))A("dependencies_missing: srt-win.exe");return!Y}let G=q.checkDependencies().errors;if(G.length>0)return A(`dependencies_missing: ${G.join(", ")}`),!1;return!Y}catch(q){return A(`load_failed: ${String(q)}`),!1}}async function zq(j={}){if(!j.loadSandboxRuntime&&!j.sandboxMode){if(!await Yj())return!1;return u??=p({}),u}return p(j)}async function p(j){let q=process.platform==="win32",G=o(H(qj(),"reason-device-probe-"));try{let z=q?Hj(G,!1):void 0;if(z)await Zj(z,!1);let J;try{J=await gj(await x(j,z),G)}catch{return!1}finally{if(q)O()}if(!J)A("confined_command_failed");if(I===0)await(q?$j():Xj());return J}finally{e(G,{recursive:!0,force:!0})}}async function gj(j,q){let G=process.platform==="win32",z=G?"true":Qj(U);if(!z)return!1;try{let{argv:J,env:K}=await j.wrapWithSandboxArgv(Aj([z]),Cj(),{filesystem:G?Nj([],q):Ij({root:q,allowWrite:!1,temporaryDirectory:q,protectedPaths:[]})},void 0,q),[Q,...V]=J;if(!Q)return!1;return await wj(Q,V,q,G?{env:K}:{})}catch{return!1}finally{try{j.cleanupAfterCommand()}catch{}}}function wj(j,q,G,z={}){return new Promise((J)=>{let K=!1,Q,V=(L)=>{if(K)return;K=!0,clearTimeout(Q),J(L)},$;try{$=(z.spawnChild??f)(j,q,{cwd:G,env:z.env??{PATH:n,HOME:G,TMPDIR:G},stdio:"ignore",windowsHide:!0})}catch{V(!1);return}$.once("error",()=>V(!1));let Z=(L,F)=>V(L===0&&F===null);if($.once("exit",Z),$.once("close",Z),$.exitCode!==null||$.signalCode!==null)Z($.exitCode,$.signalCode);if(K)return;Q=setTimeout(()=>{V(!1);try{$.kill("SIGKILL")}catch{}},Math.min(z.timeoutMs??g,g))})}function Cj(j=U,q=h()){if(q==="win32")return s("win32");return["/bin/bash","/bin/sh"].find((G)=>j(G))??"/bin/sh"}function Aj(j){return j.map((q)=>`'${q.replaceAll("'","'\\''")}'`).join(" ")}function cj(j,q,G=(z)=>_j(z,{withFileTypes:!0}).filter((J)=>J.isDirectory()||J.isFile()).map((J)=>J.name)){let z=[],J=[{path:j,depth:0}],K=0;while(J.length>0&&K<w){let Q=J.pop(),V;try{V=G(Q.path)}catch{continue}for(let $ of V){if(K+=1,K>w)break;let Z=H(Q.path,$);if(q(Z)){z.push(Z);continue}if(Q.depth+1<Pj&&!Ej.has($))J.push({path:Z,depth:Q.depth+1})}}return z}function Ij(j){let q=H(j.root,".git"),G=[];try{if(jj(q).isDirectory())G=[H(q,"config"),H(q,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...j.protectedPaths],allowRead:[j.root,j.temporaryDirectory],allowWrite:[...j.allowWrite?[j.root]:[],j.temporaryDirectory],denyWrite:[...j.protectedPaths,...G]}}function Nj(j,q){let G=H(q,".git"),z=[];try{if(jj(G).isDirectory())z=[H(G,"config"),H(G,"hooks")]}catch{}return{denyRead:[...j],allowRead:[],allowWrite:[],denyWrite:[...j,...z]}}function uj(j,q){if(q)return{network:{allowedDomains:[],deniedDomains:[]},filesystem:q,windows:{srtWin:{path:C()}}};return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...j==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Gq(j){let q=j.createTemporaryDirectory??(()=>o(H(qj(),"reason-device-"))),G=j.removeTemporaryDirectory??((z)=>e(z,{recursive:!0,force:!0}));return async(z,J,K)=>{let Q=process.platform==="win32",V;if(Q){let Z=Hj(K.root,K.allowWrite);if(!await Zj(Z,!K.workerProbe,K.signal,K.timeoutMs))return{exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!0,truncated:!1};try{V=await x(j,Z)}catch(L){throw O(),L}}else V=await x(j),I+=1;let $;try{$=q();let Z=cj(K.root,j.isProtectedPath),L;try{L=await V.wrapWithSandboxArgv((Q?yj:"")+Aj([z,...J]),j.shell??Cj(),{filesystem:Q?Nj(Z,K.root):Ij({root:K.root,allowWrite:K.allowWrite,temporaryDirectory:$,protectedPaths:Z})},K.signal,K.cwd)}catch(b){throw b instanceof B?b:new B("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[F,...Tj]=L.argv;if(!F)throw new B("sandbox_unavailable","The confined execution sandbox produced no command.");return await j.spawnCaptured(F,Tj,{cwd:K.cwd,timeoutMs:K.timeoutMs,signal:K.signal,env:Q?L.env:j.scrubEnvironment(K.root,$)})}finally{O();try{V.cleanupAfterCommand()}catch{}if($!==void 0)G($)}}}
7
- export{oj as zc,C as Ac,tj as Bc,ej as Cc,jq as Dc,qq as Ec,Vj as Fc,zq as Gc,Cj as Hc,Gq as Ic};
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{vi as v}from"./vm-hands-entry-lite-2nec0vk1.js";import{Di as o,Gi as g,Hi as h,Ii as a,xi as r}from"./vm-hands-entry-lite-q4tcfj61.js";import{xj as V}from"./vm-hands-entry-lite-hye6r7dy.js";import{uk as U}from"./vm-hands-entry-lite-vr38bh6k.js";import{createHmac as mQ,createPublicKey as CQ,randomBytes as LQ,randomUUID as t,verify as EQ}from"crypto";import{chmodSync as _,existsSync as e,mkdirSync as IQ,readFileSync as gQ,realpathSync as hQ,renameSync as vQ,statSync as yQ,unlinkSync as uQ,writeFileSync as pQ}from"fs";import{basename as cQ,dirname as F,isAbsolute as QQ,join as A,resolve as lQ}from"path";var WZ=[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 zQ="REASON_DESKTOP_RUNTIME",UQ="REASON_DESKTOP_RUNTIME_CHANNEL",JQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",zZ={[zQ]:"ARA_DESKTOP_RUNTIME",[UQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[JQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function m(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as N,existsSync as z,mkdirSync as O,readFileSync as C,realpathSync as xQ,renameSync as wQ,unlinkSync as R,writeFileSync as f}from"fs";import{createPrivateKey as KQ,createPublicKey as VQ,generateKeyPairSync as AQ,randomUUID as NQ,sign as OQ}from"crypto";import{createRequire as RQ}from"module";import{homedir as fQ,platform as y}from"os";import{dirname as kQ,join as J}from"path";var L=1,BQ=16384,M=65536,_Q=128,TQ=128,u=65536;class q extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function p(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var k=null;function c(){if(!k)try{k=RQ(import.meta.url)("bun:ffi")}catch{throw new q("native_boundary_unavailable")}return k}function FQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function PQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new q("invalid_credential_record");let Z=Q,$=FQ(Z.apiOrigin);if(Z.version!==L||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new q("invalid_credential_record");return{version:L,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function DQ(Q=process.execPath){let Z=Q;try{Z=xQ(Q)}catch{}return v(kQ(Z))}function j(Q){return c().ptr(Q)}function bQ(Q){if(!z(Q))throw new q("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=c();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(W){if(W instanceof q)throw W;throw new q("native_boundary_unavailable")}}function E(Q){return Buffer.from(Q).toString("base64url")}function x(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function l(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class d{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=DQ(),Z=y(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;m($)}symbols(){if(this.runtimePlatform!=="darwin")throw new q("unsupported_platform");this.library??=bQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(j(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new q("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(_Q),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(j(Z),BigInt(Z.byteLength),j($)):this.symbols().ara_device_key_create_fresh_public(j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X!==65)throw new q("invalid_public_key");let Y=E(Z.subarray(0,X));if(!x(Y))throw new q("invalid_public_key");return Y}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=new Uint8Array(TQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(j(Q),BigInt(Q.byteLength),j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q("proof_sign_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X<1||X>Z.byteLength)throw new q("invalid_signature");let Y=Z.subarray(0,X);if(!l(Y))throw new q("invalid_signature");return E(Y)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(j(Q));if(Z!==0||Q[0]!==1)throw new q("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(j(Q));if(Z!==0)throw new q("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(M),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_create(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_update(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(j(Q));if(Z!==0)throw new q("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(BQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_credential_record");try{let X=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return PQ(JSON.parse(X))}catch(X){if(X instanceof q)throw X;throw new q("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(j(Q));if(Z!==0)throw new q("legacy_credential_delete_failed",Z);return Q[0]===1}}function I(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new q("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new q("invalid_public_key");let X=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(X))throw new q("invalid_public_key");return X}function SQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||J(fQ(),".config");h(Q);let Z=J(Q,"ara");return g(Z)?Z:J(Q,"reason")}class i{directory;constructor(Q=SQ()){this.directory=Q}keyPath(){return J(this.directory,"local-device.key")}bindingPath(){return J(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!z(Q))throw new q("proof_key_read_failed");try{let Z=C(Q,"utf8");return KQ({key:Z,format:"pem"})}catch{throw new q("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=VQ(Q);return I(Z)}createFreshPublicKey(){O(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return f(W,$,{mode:384}),N(W,384),I(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=OQ("sha256",Q,Z)}catch{throw new q("proof_sign_failed")}if(!l($))throw new q("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!z(Q))return!1;return R(Q),!0}loadBinding(){let Q=this.bindingPath();if(!z(Q))return null;try{return new Uint8Array(C(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(z(Z))throw new q("binding_create_failed");f(Z,Q,{mode:384}),N(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!z(Z))throw new q("binding_update_failed");let $=`${Z}.${NQ()}`;try{f($,Q,{mode:384,flag:"wx"}),N($,384),wQ($,Z)}finally{if(z($))R($)}}deleteBinding(){let Q=this.bindingPath();if(!z(Q))return!1;return R(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function B(){return y()==="darwin"?new d:new i}var w=U.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),s=U.object({id:w,kind:U.literal("permission_denied"),operation:U.enum(["bash","read","write","edit"]),provenance:U.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:U.string().datetime(),expiresAt:U.string().datetime(),sessionId:w,deviceId:w,organizationId:w}).strict();var P=4;var K="macos-keychain-p256-v1",ZQ=1,dQ=`ARA-DEVICE-BINDING-V1
3
- `;function iQ(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function $Q(Q,Z=Date.now()){let $=s.safeParse(Q);if(!$.success)return!1;let W=$.data,X=typeof W.occurredAt==="string"?Date.parse(W.occurredAt):NaN,Y=typeof W.expiresAt==="string"?Date.parse(W.expiresAt):NaN;return W.kind==="permission_denied"&&["bash","read","write","edit"].includes(W.operation)&&["sandbox_policy","os_permission_unknown"].includes(W.provenance)&&Number.isFinite(X)&&X<=Z&&Y>Z&&Y>X&&Y-X<=600000}function LZ(Q,Z,$=Date.now()){if(!Q||!Z||Q.state!=="connected"||Q.deviceId!==Z.deviceId)return null;let W=Date.parse(Q.lastHeartbeatAt??""),X=Q.permissionRecovery;if(!($-W>=0&&$-W<30000)||!$Q(X,$)||X.deviceId!==Z.deviceId||X.organizationId!==Z.orgId)return null;try{process.kill(Q.pid,0)}catch{return null}return X}function WQ(Q={},Z=V()){let $=r({env:{...process.env,...Q}}),W=Q.XDG_CONFIG_HOME?.trim()||A(Z,".config");return a(W,...$==="staging"?["staging"]:[])}function D(Q={},Z=V()){return A(WQ(Q,Z),"local-device.json")}function qQ(Q={},Z=V()){return A(WQ(Q,Z),"local-daemon.json")}function b(Q,Z){IQ(F(Q),{recursive:!0,mode:448}),_(F(Q),448);let $=`${Q}.${process.pid}.${t()}.tmp`;try{pQ($,`${JSON.stringify(Z,null,2)}
4
- `,{mode:384,flag:"wx"}),_($,384),vQ($,Q),_(Q,384)}finally{if(e($))uQ($)}return Q}function S(Q){if(!e(Q))return null;try{return JSON.parse(gQ(Q,"utf8"))}catch{return null}}function T(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function sQ(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||typeof W.label!=="string"||typeof W.path!=="string"||typeof W.pathFingerprint!=="string"||!W.permissions||typeof W.permissions.read!=="boolean"||typeof W.permissions.write!=="boolean"||typeof W.permissions.execute!=="boolean"||typeof W.permissions.discover_environment!=="boolean"||typeof W.permissions.expose_mcp!=="boolean")return null;Z.push({id:W.id,label:W.label,path:W.path,pathFingerprint:W.pathFingerprint,permissions:W.permissions})}return Z}function XQ(Q,Z,$=[]){let W=Object.keys(Q);return Z.every((X)=>Object.hasOwn(Q,X))&&W.every((X)=>Z.includes(X)||$.includes(X))}function nQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost")return null;return Z.origin}catch{return null}}function YQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=sQ(Z.roots),W=nQ(Z.apiOrigin);if(!W||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!iQ(Z.handsSlots)||Z.worker!==void 0&&(!Z.worker||!/^[a-f0-9]{64}$/.test(Z.worker.configDigest)||!["persistent","ephemeral"].includes(Z.worker.lifetime)||!Number.isFinite(Date.parse(Z.worker.expiresAt)))||!$)return null;return{apiOrigin:W,orgId:Z.orgId,deviceId:Z.deviceId,displayName:Z.displayName,registeredAt:Z.registeredAt,...Z.handsSlots!==void 0?{handsSlots:Z.handsSlots}:{},...Z.worker!==void 0?{worker:Z.worker}:{},roots:$}}function rQ(Q){return{...Q,credentialStorage:K}}function oQ(Q){return{version:P,apiOrigin:Q.apiOrigin,orgId:Q.orgId,deviceId:Q.deviceId,devicePublicKey:Q.devicePublicKey,displayName:Q.displayName,registeredAt:Q.registeredAt,...Q.handsSlots!==void 0?{handsSlots:Q.handsSlots}:{},...Q.worker!==void 0?{worker:Q.worker}:{},roots:Q.roots.map((Z)=>({id:Z.id,label:Z.label,path:Z.path,pathFingerprint:Z.pathFingerprint,permissions:{read:Z.permissions.read,write:Z.permissions.write,execute:Z.permissions.execute,discover_environment:Z.permissions.discover_environment,expose_mcp:Z.permissions.expose_mcp}})),credentialStorage:K}}function jQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!XQ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=YQ(Z);if(!$||Z.version!==P||Z.credentialStorage!==K||!x(Z.devicePublicKey))return null;return{version:P,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:K}}function GQ(Q){return new TextEncoder().encode(`${dQ}${JSON.stringify(oQ(Q))}`)}function aQ(Q){let Z=Buffer.from(Q,"base64url");return CQ({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function tQ(Q,Z){let $={version:ZQ,state:Q,signature:Z.sign(GQ(Q))};return new TextEncoder().encode(JSON.stringify($))}function HQ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new q("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new q("invalid_binding");let $=Z;if(!XQ($,["version","state","signature"])||$.version!==ZQ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new q("invalid_binding");let W=jQ($.state);if(!W)throw new q("invalid_binding");let X=!1;try{X=EQ("sha256",GQ(W),aQ(W.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{X=!1}if(!X)throw new q("invalid_binding");return W}function eQ(Q){let{credentialStorage:Z,...$}=Q;return $}function QZ(Q){return Q instanceof q?p(Q):"credential_boundary_failed"}function EZ(Q=D(),Z={}){let $=S(Q),W=Z.proofStore??Z.credentialStore??B(),X=W.loadBinding();if(!X){if($&&typeof $==="object"&&!Array.isArray($)&&ZZ($))return null;if($!==null)throw new q("invalid_binding");return null}let Y=HQ(X),G=W.loadPublicKey();if(W.privateKeyIsNonExtractable(),G!==Y.devicePublicKey)throw new q("invalid_public_key");let H=jQ($);if(Z.repair!==!1&&(!H||JSON.stringify(H)!==JSON.stringify(Y)))b(Q,Y);return eQ(Y)}function ZZ(Q){let Z=Q,$=YQ(Q);if(!$)return null;if(Z.version===2){if(typeof Z.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.deviceCredential)||Z.deviceCredential.length>4096)return null;return{state:$,credentialSource:"plaintext-v2"}}if(Z.version!==3||Z.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in Z)return null;return{state:$,credentialSource:"keychain-v3"}}function IZ(Q,Z=D(),$={}){let W=$.proofStore??$.credentialStore??B();T($,"credential.store_started");try{if(!x(Q.devicePublicKey)||W.loadPublicKey()!==Q.devicePublicKey)throw new q("invalid_public_key");W.privateKeyIsNonExtractable();let X=rQ(Q),Y=W.loadBinding();if(Y){let H=HQ(Y);if(H.devicePublicKey!==Q.devicePublicKey||H.orgId!==Q.orgId||H.deviceId!==Q.deviceId||H.apiOrigin!==Q.apiOrigin&&!o(H.apiOrigin,Q.apiOrigin))throw new q("invalid_binding")}let G=tQ(X,W);if(Y)W.updateBinding(G);else W.createBinding(G);return b(Z,X),T($,"credential.store_completed"),Z}catch(X){throw T($,"credential.store_failed",QZ(X)),X}}function gZ(Q=qQ()){let Z=S(Q);if(!Z||typeof Z!=="object")return null;let $=Z;if($.version!==1||typeof $.pid!=="number"||!Number.isInteger($.pid)||!["starting","connected","stopped","error"].includes($.state??"")||typeof $.startedAt!=="string"||$.lastHeartbeatAt!==void 0&&typeof $.lastHeartbeatAt!=="string"||$.lastUsedAt!==void 0&&typeof $.lastUsedAt!=="string"||$.organizationId!==void 0&&typeof $.organizationId!=="string"||$.organizationName!==void 0&&typeof $.organizationName!=="string"||$.organizationSlug!==void 0&&typeof $.organizationSlug!=="string"||$.error!==void 0&&typeof $.error!=="string"||$.reconnectingSince!==void 0&&typeof $.reconnectingSince!=="string"||$.workspace!==void 0&&typeof $.workspace!=="string")return null;if($.permissionRecovery!==void 0&&!$Q($.permissionRecovery))delete $.permissionRecovery;return $}function hZ(Q,Z=qQ()){return b(Z,Q)}var n=1;function $Z(Q=D()){return A(F(Q),"local-device.proxy.json")}function vZ(Q=$Z()){let Z=S(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==n||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!QQ($.caFile)))return null;return{version:n,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function yZ(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=LQ(32)){let W=new Set,X=[];for(let Y of Q){let G=hQ(QQ(Y)?Y:lQ(Y));if(!yQ(G).isDirectory())throw Error(`Local execution root is not a directory: ${Y}`);if(W.has(G))continue;W.add(G),X.push({id:t(),label:cQ(G)||G,path:G,pathFingerprint:mQ("sha256",$).update(G).digest("hex"),permissions:{...Z}})}if(X.length===0)throw Error("At least one explicit local execution root is required.");return X}
5
- export{q as Ig,DQ as Jg,x as Kg,l as Lg,d as Mg,i as Ng,$Q as Og,LZ as Pg,D as Qg,qQ as Rg,EZ as Sg,IZ as Tg,gZ as Ug,hZ as Vg,n as Wg,vZ as Xg,yZ as Yg};
@@ -1,3 +0,0 @@
1
- // @bun
2
- var r={name:"github-native-engineer-device-worker-production",version:"0.2.406",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
3
- export{r as $j};