@reason-machines/cli-linux-arm64-musl 0.2.328 → 0.2.330

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 (71) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/connect-cli-4gee1bxs.js +2 -0
  3. package/bin/vm-hands/{custom-endpoint-device-j47avpaq.js → custom-endpoint-device-8yqvpsd7.js} +1 -1
  4. package/bin/vm-hands/desktop-account-s4629ksd.js +2 -0
  5. package/bin/vm-hands/{device-workspace-xnyb7zp2.js → device-workspace-pacdp5tv.js} +1 -1
  6. package/bin/vm-hands/hands-worker-source-fprvxtp8.js +2 -0
  7. package/bin/vm-hands/{index-752q9pdp.js → index-wx03jedr.js} +1 -1
  8. package/bin/vm-hands/local-automation-5gkaj1mg.js +2 -0
  9. package/bin/vm-hands/local-capabilities-px6n9wdf.js +2 -0
  10. package/bin/vm-hands/local-desktop-users-ktbva6me.js +2 -0
  11. package/bin/vm-hands/local-display-mac-kbbrwa0y.js +2 -0
  12. package/bin/vm-hands/local-display-session-qqgjsa3g.js +2 -0
  13. package/bin/vm-hands/local-pty-session-bnhx083p.js +2 -0
  14. package/bin/vm-hands/{network-contract-bv7mj5he.js → network-contract-gb6gk8fg.js} +1 -1
  15. package/bin/vm-hands/package-bzy9agdv.js +2 -0
  16. package/bin/vm-hands/permissions-tj216d4z.js +2 -0
  17. package/bin/vm-hands/{reason-hands-protocol-5zt3ys5t.js → reason-hands-protocol-469gmb0h.js} +1 -1
  18. package/bin/vm-hands/{status-8m39p3xw.js → status-wdwrnxja.js} +2 -2
  19. package/bin/vm-hands/version-5crmvxxa.js +2 -0
  20. package/bin/vm-hands/{vm-hands-entry-lite-9kasrx18.js → vm-hands-entry-lite-0yghpjef.js} +2 -2
  21. package/bin/vm-hands/{vm-hands-entry-lite-v6tkjqb1.js → vm-hands-entry-lite-40t7d4p5.js} +1 -1
  22. package/bin/vm-hands/{vm-hands-entry-lite-cxs89wzv.js → vm-hands-entry-lite-5a0kyaxa.js} +1 -1
  23. package/bin/vm-hands/{vm-hands-entry-lite-psybjyay.js → vm-hands-entry-lite-669hk342.js} +2 -2
  24. package/bin/vm-hands/vm-hands-entry-lite-6g65w75z.js +5 -0
  25. package/bin/vm-hands/{vm-hands-entry-lite-yhz6sv35.js → vm-hands-entry-lite-8afzattm.js} +2 -2
  26. package/bin/vm-hands/{vm-hands-entry-lite-n07kxrd1.js → vm-hands-entry-lite-9y8v419y.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-b2wdaq7x.js → vm-hands-entry-lite-abrbc7gf.js} +2 -2
  28. package/bin/vm-hands/{vm-hands-entry-lite-qwba7w42.js → vm-hands-entry-lite-dj69r683.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-mzxhng4z.js → vm-hands-entry-lite-djy0ww6h.js} +2 -2
  30. package/bin/vm-hands/{vm-hands-entry-lite-14t846kp.js → vm-hands-entry-lite-dyqeaqzb.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-qgse6zav.js → vm-hands-entry-lite-e5fatvff.js} +2 -2
  32. package/bin/vm-hands/vm-hands-entry-lite-ekp1wmw5.js +3 -0
  33. package/bin/vm-hands/{vm-hands-entry-lite-pwzz9ntw.js → vm-hands-entry-lite-g5w3cema.js} +3 -3
  34. package/bin/vm-hands/{vm-hands-entry-lite-7q2gywdm.js → vm-hands-entry-lite-ht03kzr3.js} +3 -3
  35. package/bin/vm-hands/vm-hands-entry-lite-j7ee0rr6.js +181 -0
  36. package/bin/vm-hands/{vm-hands-entry-lite-22jgncrd.js → vm-hands-entry-lite-jz24p4jj.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-cp1wqjs5.js → vm-hands-entry-lite-kbz9zfha.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-ne8kkvk4.js → vm-hands-entry-lite-n5ec0fjy.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-qvrnx0vk.js → vm-hands-entry-lite-n8gsyjq7.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-e0cj5ma7.js → vm-hands-entry-lite-ngtfq7a3.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-fq0zr7an.js → vm-hands-entry-lite-nj8bmc9y.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-xf6schkk.js → vm-hands-entry-lite-pbnx8z9g.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-p40ka01q.js → vm-hands-entry-lite-qq1091m3.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-93ejmwqn.js → vm-hands-entry-lite-rd9vsaew.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-t497ewn2.js → vm-hands-entry-lite-rnwjp0tk.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-wh0qp1gf.js → vm-hands-entry-lite-sggk0bqc.js} +2 -2
  47. package/bin/vm-hands/vm-hands-entry-lite-tav4dt92.js +3 -0
  48. package/bin/vm-hands/{vm-hands-entry-lite-f8f057tx.js → vm-hands-entry-lite-ydjye6jz.js} +3 -3
  49. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  50. package/bin/vm-hands/vm-hands-executor-rt8r46bt.js +10 -0
  51. package/bin/vm-hands/vm-hands-op-runner-m45mtphf.js +2 -0
  52. package/bin/vm-hands/vm-hands-runtime-h7s6zcvq.js +4 -0
  53. package/bin/vm-hands/worker-sandbox-bqwkytj2.js +2 -0
  54. package/package.json +1 -1
  55. package/bin/vm-hands/connect-cli-25a18p4x.js +0 -2
  56. package/bin/vm-hands/desktop-account-emwzhj61.js +0 -2
  57. package/bin/vm-hands/hands-worker-source-ea5ywzxx.js +0 -2
  58. package/bin/vm-hands/local-automation-0tsy8ca8.js +0 -2
  59. package/bin/vm-hands/local-capabilities-bkfwqn2s.js +0 -2
  60. package/bin/vm-hands/local-desktop-users-rn753h90.js +0 -2
  61. package/bin/vm-hands/local-display-mac-9qqvjs82.js +0 -2
  62. package/bin/vm-hands/local-display-session-e02rm1ap.js +0 -2
  63. package/bin/vm-hands/package-xeh4dp97.js +0 -2
  64. package/bin/vm-hands/permissions-96taxgby.js +0 -2
  65. package/bin/vm-hands/version-8qzmmn7c.js +0 -2
  66. package/bin/vm-hands/vm-hands-entry-lite-rv6k8wy8.js +0 -5
  67. package/bin/vm-hands/vm-hands-entry-lite-yjzz85pt.js +0 -181
  68. package/bin/vm-hands/vm-hands-executor-r34x5748.js +0 -10
  69. package/bin/vm-hands/vm-hands-op-runner-yex7kse5.js +0 -2
  70. package/bin/vm-hands/vm-hands-runtime-ck24pzen.js +0 -4
  71. package/bin/vm-hands/worker-sandbox-yt11b09s.js +0 -2
@@ -0,0 +1,181 @@
1
+ // @bun
2
+ import{Fe as Aq}from"./vm-hands-entry-lite-ht03kzr3.js";import{ef as H,hf as L0,kf as y0,lf as T8,mf as sq,of as $8,rf as iq,tf as nq}from"./vm-hands-entry-lite-jz24p4jj.js";import{Cf as j0}from"./vm-hands-entry-lite-tav4dt92.js";import{hg as U0}from"./vm-hands-entry-lite-sggk0bqc.js";import{oh as Zq}from"./vm-hands-entry-lite-djy0ww6h.js";import{ph as d}from"./vm-hands-entry-lite-kbz9zfha.js";import{Ph as W0}from"./vm-hands-entry-lite-dyqeaqzb.js";import{Wh as M}from"./vm-hands-entry-lite-40t7d4p5.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# 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 e=32,Bq=76;function _0(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>${e}</x><y>${e}</y></position>
67
+ <size><width>${q.width-e*2}</width><height>${q.height-e-Bq}</height></size>
68
+ </application>
69
+ </applications>
70
+ </openbox_config>`}var E0=`# 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
+ `,O0=`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
+ `,$0="/tmp/ara-dock-browser.png",H0=`[Desktop Entry]
104
+ Name=Chrome
105
+ Exec=chromium --no-sandbox %U
106
+ Icon=${$0}
107
+ Type=Application
108
+ Categories=Network;WebBrowser;
109
+ `,f0=`[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
+ `,h0=`[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 Dq={"wallpaper.jpg":Uq,"dock-browser.png":Lq,"dock-terminal.png":jq,"dock-files.png":yq},g0=Tq,p0='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function Rq(q){let x=(J)=>J.replaceAll("DISPLAY=:99",`DISPLAY=${q.display}`).replaceAll("/tmp/ara-",`${q.root}/ara-`),X=new Set(q.absent??[]),Q=E0.split(`
122
+ `).filter((J)=>!(X.has("terminal")&&J.endsWith("/ara-terminal.desktop"))&&!(X.has("files")&&J.endsWith("/ara-files.desktop"))).join(`
123
+ `);return{files:{"openbox/rc.xml":_0(q.screen),"tint2/tint2rc":x(Q),"picom/picom.conf":O0,...X.has("terminal")?{}:{"ara-terminal.desktop":x(f0)},...X.has("files")?{}:{"ara-files.desktop":x(h0)},"ara-chromium.desktop":x(H0).replace("chromium --no-sandbox %U",q.browserExec),"ara-set-root-wallpaper.py":g0},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"; }',p0,'[ ! -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 Gq}from"crypto";import{once as k0}from"events";import{createWriteStream as I0,existsSync as v0,mkdirSync as u0,mkdtempSync as n1,readFileSync as U8,readdirSync as o1,renameSync as c0,realpathSync as l0,rmSync as r0,statSync as H8,writeFileSync as m0}from"fs";import{dirname as f8,join as S}from"path";import{finished as d0}from"stream/promises";var _8="omljlfpmafedpplnpkkahegadhkimdje",f1="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";function p1(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 X of q.managedRootIds){if(typeof X!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(X))return null;x.push(X)}try{let X=new URL(q.apiOrigin);if(X.origin!==q.apiOrigin||X.username||X.password||!(X.protocol==="https:"||X.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(X.hostname)))return null}catch{return null}return{version:1,status:"connected",deviceId:q.deviceId,apiOrigin:q.apiOrigin,managedRootIds:x}}var g={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"}},N8={version:"154.0.8037.57",macArm64Sha256:"0e6b3439469c1b8b95b2e89c72ea29f7af00fb2c28a8878358a0b6002b6d3a64",linux64Sha256:"ceee2972074d441ea7c4ba8bcc0eaab77e7e87680f6653d73d3065851fe10302"};var q8={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${g.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${g.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${g.obu.version}/open-browser-use-chrome-extension-${g.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},r="pnbmoicbkopffjjgfgfglopechaiemkp";var a0=["none","standard","all"],E8="22.23.3",s0={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53"},O8={"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"}},Fq="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",h8={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},i0={version:h8.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},m="com.ifuryst.open_browser_use.extension",wq="com.reasonmachines.browser_use.extension",Cq="/tmp/reason-browser-use",g8=["tint2","picom","xterm","pcmanfm"],Vq=["fonts-droid-fallback"],Kq=["pulseaudio"],n0=["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",...Vq,"galculator","chromium","ffmpeg","tmux",...Kq,...g8],o0=new Set([...g8,...Vq,...Kq]),Sq=n0.filter((q)=>q!=="chromium"&&!o0.has(q)),t0=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],W8="/usr/bin/chromium",e0=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function Mq(q=process.platform,x=process.arch){let X=`${q}-${x}`;return X==="linux-x64"||X==="linux-arm64"||X==="darwin-arm64"?X:null}function L8(q){return{node:{version:E8,url:`https://nodejs.org/dist/v${E8}/node-v${E8}-${q}.tar.gz`,sha256:s0[q]},open_computer_use:{version:g.ocu.version,url:q8.ocu.url,sha256:q8.ocu.sha256},open_browser_use:{version:g.obu.version,url:q8.obu.url,sha256:q8.obu.sha256},...q==="darwin-arm64"?{chrome_for_testing:{version:N8.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${N8.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:N8.macArm64Sha256}}:{}}}function qx(q){let x={extension:r};for(let[X,Q]of Object.entries(L8(q)))x[X]=`${Q.version}@${Q.sha256}`;return x}function Yq(q){return S(q,".local","share","reason","desktop")}function zq(q,x=Zq()){let X=Yq(x),Q=(W)=>S(X,W,L8(q)[W]?.version??""),P=Q("open_computer_use"),b=Q("open_browser_use"),J=q==="darwin-arm64",y=S(x,"Library","Application Support"),C=J?S(y,"Google","Chrome","NativeMessagingHosts",`${m}.json`):S(x,".config","google-chrome","NativeMessagingHosts",`${m}.json`);return{root:X,automation:S(f8(X),"automation"),receipt:S(X,"receipt.json"),minimal:k8(x),node:S(Q("node"),"bin","node"),ocuDir:P,ocu:S(P,O8[q].ocu),ocuApp:J?S(P,"dist","Open Computer Use.app"):null,obuDir:b,obu:S(b,"cli","open-browser-use.js"),nativeHost:S(b,O8[q].obu),extensionDir:J?S(y,"OpenBrowserUse","chrome-extension","release"):S(x,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:C,nativeHostManifests:J?[C,S(y,"Google","ChromeForTesting","NativeMessagingHosts",`${m}.json`)]:[S(x,".config","chromium","NativeMessagingHosts",`${m}.json`),S(x,".config","google-chrome-for-testing","NativeMessagingHosts",`${m}.json`)],browser:J?S(Q("chrome_for_testing"),Fq):W8,userChromeHost:J?S(X,"user-chrome","reason-browser-use"):null,userChromeRegistration:J?S(y,"Google","Chrome","NativeMessagingHosts",`${wq}.json`):null,ffmpegDir:S(X,"ffmpeg"),ffmpeg:J?S(X,"ffmpeg",h8.version,"ffmpeg"):null,ffprobe:J?S(X,"ffprobe",i0.version,"ffprobe"):null}}function _q(q){try{let x=JSON.parse(U8(q,"utf8"));if(typeof x!=="object"||x===null)return null;let X=x,Q=X.pins;if(X.schema_version!==1||typeof X.platform!=="string"||typeof Q!=="object"||Q===null||!Object.values(Q).every((P)=>typeof P==="string")||!a0.includes(X.permissions)||!Array.isArray(X.missing_system_packages)||!X.missing_system_packages.every((P)=>typeof P==="string")||typeof X.updated_at!=="string")return null;return{schema_version:1,platform:X.platform,pins:Q,permissions:X.permissions,missing_system_packages:X.missing_system_packages,updated_at:X.updated_at}}catch{return null}}function xx(q,x,X=384){u0(f8(q),{recursive:!0,mode:448});let Q=`${q}.pending.${process.pid}`;m0(Q,x,{mode:X}),c0(Q,q)}function p(q){try{return H8(q).isFile()}catch{return!1}}function Eq(q){try{let x=H8(q);return x.isFile()&&(x.mode&73)!==0}catch{return!1}}function Xx(q){try{return U8(q,"utf8")}catch{return null}}function v(q){for(let x of e0){let X=S(x,q);try{let Q=H8(X);if(Q.isFile()&&(Q.mode&73)!==0)return X}catch{}}return null}function Qx(q){try{let x=JSON.parse(U8(S(q,"package.json"),"utf8"));return typeof x==="object"&&x!==null&&typeof x.version==="string"?x.version:null}catch{return null}}function Px(q,x,X){let Q=L8(X)[q];if(!Q)return!1;if(q==="node")return p(S(x,"bin","node"));if(q==="chrome_for_testing")return p(S(x,Fq));let P=O8[X][q==="open_computer_use"?"ocu":"obu"];return Qx(x)===Q.version&&p(S(x,P))&&(q==="open_computer_use"||p(S(x,"cli","open-browser-use.js")))}function bx(q){return Gq("sha256").update(Buffer.from(q,"base64")).digest("hex").slice(0,32).replace(/./g,(x)=>String.fromCharCode(97+Number.parseInt(x,16)))}function p8(q){try{let x=JSON.parse(U8(q,"utf8"));return typeof x==="object"&&x!==null&&!Array.isArray(x)?x:null}catch{return null}}function Jx(q){let x=p8(S(q.extensionDir,"manifest.json"));return x!==null&&x.version===g.obu.version&&typeof x.key==="string"&&bx(x.key)===r}function Nx(q,x){let X=q?.allowed_origins;return q!==null&&q.name===m&&Array.isArray(X)&&X.length===1&&X[0]===`chrome-extension://${r}/`&&(x===void 0||q.path===x)}function Wx(q){return Jx(q)&&p(q.nativeHost)&&q.nativeHostManifests.every((x)=>Nx(p8(x),q.nativeHost))}function Ux(q){return`#!/bin/sh
124
+ # Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
125
+ obu=${`'${q.replaceAll("'","'\\''")}'`}
126
+ case "$1" in
127
+ chrome-extension://*) exec "$obu" host --socket-dir ${Cq} ;;
128
+ mcp) shift; exec "$obu" mcp --socket-dir ${Cq} "$@" ;;
129
+ esac
130
+ exec "$obu" "$@"
131
+ `}function Lx(q){let x=p8(q),X=x?.allowed_origins;return x!==null&&x.name===wq&&x.type==="stdio"&&Array.isArray(X)&&X.includes(`chrome-extension://${_8}/`)&&typeof x.path==="string"&&Eq(x.path)}function yx(q,x){if(!q.userChromeHost||!q.userChromeRegistration)return null;if(!x||Xx(q.userChromeHost)!==Ux(q.nativeHost)||!Eq(q.userChromeHost))return{code:"user_chrome_browser_use_missing"};return Lx(q.userChromeRegistration)?{host:q.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var jx={display:["display"],computer:["display","system_packages","node","open_computer_use"],browser:["display","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function k(q={}){let x=q.platform===void 0?Mq():q.platform;if(!x)return null;let X=zq(x,q.home),Q=_q(X.receipt),P=qx(x),b=Q!==null&&Q.platform===x&&JSON.stringify(Object.entries(Q.pins).sort())===JSON.stringify(Object.entries(P).sort()),J=[],y=L8(x);for(let N of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let D=y[N];if(!D)continue;let G=Px(N,S(X.root,N,D.version),x),F=Q?.pins[N],O=G&&F===P[N]?"ready":F!==void 0&&F!==P[N]?"outdated":"missing";J.push({name:N,state:O,detail:D.version})}let C=Q?.pins.extension===r&&Wx(X);J.push({name:"browser_extension",state:C?"ready":"missing",detail:r});let W=v("Xvfb"),j=v("x11vnc"),R=v("openbox");if(x!=="darwin-arm64"){J.push(p(W8)?{name:"browser",state:"ready",detail:W8}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${W8}`});let N=W!==null&&j!==null&&R!==null;J.push({name:"display",state:N?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let D=t0.filter((z)=>v(z)===null),G=(Q?.missing_system_packages??Sq).filter((z)=>Sq.includes(z)),F=D.length===0&&G.length===0;J.push(F?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...G,...D])].join(" ")});let O=g8.filter((z)=>v(z)===null);J.push(O.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:O.join(" ")})}let Z=X.ffmpeg&&p(X.ffmpeg)?X.ffmpeg:v("ffmpeg"),B=!Z?null:Z===X.ffmpeg?X.ffprobe:S(f8(l0(Z)),"ffprobe"),Y=b&&J.every((N)=>N.state==="ready"),w=(N)=>b&&J.every((D)=>!jx[N].includes(D.name)||D.state==="ready");return{platform:x,root:X.root,automation:X.automation,ready:Y,features:{display:w("display"),computer:w("computer"),browser:w("browser")},node:X.node,ocu:X.ocu,obu:X.obu,nativeHost:X.nativeHost,extensionDir:X.extensionDir,browser:X.browser,ffmpeg:Z,ffprobe:B&&p(B)?B:null,userChrome:yx(X,b&&["node","open_browser_use"].every((N)=>J.find((D)=>D.name===N)?.state==="ready")),pulseaudio:v("pulseaudio"),xvfb:W,x11vnc:j,openbox:R,components:J}}function Oq(q){return Tx(q)?Aq():[]}function Tx(q){return q?.platform==="darwin-arm64"&&q.ffmpeg===S(q.root,"ffmpeg",h8.version,"ffmpeg")}async function UX(q,x,X,Q=fetch){try{let P=await Q(q,{redirect:"follow"});if(!P.ok||!P.body)throw Error(`download failed (HTTP ${P.status}): ${q}`);let b=Gq("sha256"),J=I0(X,{mode:384});try{let C=P.body.getReader();for(let W=await C.read();!W.done;W=await C.read())if(b.update(W.value),!J.write(W.value))await k0(J,"drain")}finally{J.end(),await d0(J)}let y=b.digest("hex");if(y!==x)throw Error(`digest mismatch for ${q}: expected ${x}, got ${y}`)}catch(P){throw r0(X,{force:!0}),P}}function k8(q){return S(Yq(q),"minimal.json")}function Bx(q=d()){return v0(k8(q))}function LX(q={}){xx(k8(q.home??d()),`${JSON.stringify({version:1,minimal_at:(q.now?.()??new Date).toISOString()})}
132
+ `)}function yX(q={}){let x=q.platform===void 0?Mq():q.platform;if(x===null)return null;let X=q.home??d();if(_q(zq(x,X).receipt)!==null)return"refresh";return Bx(X)?null:"install"}import{execFile as Yx,spawn as d8}from"child_process";import{existsSync as zx}from"fs";import{connect as _x}from"net";function Dx(){let q=new Set,x=null,X=(P)=>({holder:x?.viewer??null,you:x===P,same_user:Boolean(x?.viewer&&P.viewer&&x.viewer.user_id===P.viewer.user_id)}),Q=()=>{for(let P of q)P.notify(X(P))};return{join(P){return q.add(P),P.notify(X(P)),()=>{if(!q.delete(P))return;if(x!==P)return;x=null,Q()}},claim(P){if(x===P||!q.has(P))return;x=P,Q()}}}var $q=Dx();import{spawn as Rx}from"child_process";import{existsSync as Cx}from"fs";import{connect as Sx}from"net";import{join as y8}from"path";var fq="reason_desktop",x8={sampleRate:48000,channels:2,codec:"opus"},Zx=5000,Ax=107,Gx=262144,u8=(q)=>y8(q,"native"),j8=(q)=>`unix:${q}`;function I8(q,x=1000){if(!Cx(q))return Promise.resolve(!1);return new Promise((X)=>{let Q=Sx({path:q}),P=(b)=>{Q.destroy(),X(b)};Q.setTimeout(x,()=>P(!1)),Q.once("error",()=>P(!1)),Q.once("close",()=>P(!1)),Q.once("connect",()=>P(!0))})}async function hq(q,x){if(!x)return null;let X=u8(q);if(Buffer.byteLength(X)>Ax||/["'\\\s]/.test(X))return null;try{if(await I8(X))return X;let Q=Rx(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:${y8(q,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${X}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${fq} rate=${x8.sampleRate} channels=${x8.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:y8(q,"runtime"),PULSE_STATE_PATH:y8(q,"state")}}),P=!1;Q.once("error",()=>{P=!0}),Q.once("exit",()=>{P=!0}),Q.unref();let b=Date.now()+Zx;while(Date.now()<b){if(await I8(X))return X;if(P)return await I8(X)?X:null;await new Promise((J)=>setTimeout(J,50))}if(!P)Q.kill("SIGKILL");return null}catch{return null}}function gq(){let{sampleRate:q,channels:x}=x8;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",`${fq}.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 Fx=[79,103,103,83],wx=Buffer.from("OpusHead"),Vx=Buffer.from("OpusTags"),Hq=(q,x)=>q.byteLength>=x.byteLength&&x.every((X,Q)=>q[Q]===X);class v8 extends Error{constructor(q){super(q);this.name="OggProtocolError"}}class c8{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 X=[],Q=0;while(x.byteLength-Q>=27){if(Fx.some((Z,B)=>x[Q+B]!==Z)||x[Q+4]!==0)throw new v8("invalid_page");let P=(x[Q+5]&1)!==0,b=x[Q+26];if(x.byteLength-Q<27+b)break;let J=x.subarray(Q+27,Q+27+b),y=J.reduce((Z,B)=>Z+B,0),C=27+b+y;if(x.byteLength-Q<C)break;if(!P&&this.partialBytes>0)this.resetPartial();let W=P&&this.partialBytes===0,j=Q+27+b,R=j;for(let Z of J){if(j+=Z,Z===255)continue;if(this.appendPartial(x.subarray(R,j),W),R=j,!W){let B=this.takePartial();if(B.byteLength>0&&!Hq(B,wx)&&!Hq(B,Vx))X.push(B)}W=!1,this.resetPartial()}if(R<j)this.appendPartial(x.subarray(R,j),W);Q+=C}return this.buffer=x.slice(Q),X}appendPartial(q,x){if(x||q.byteLength===0)return;if(this.partialBytes+=q.byteLength,this.partialBytes>Gx)throw new v8("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 X of this.partial)q.set(X,x),x+=X.byteLength;return q}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as Kx}from"child_process";var pq=1048576,Mx=String.raw`
133
+ import gi, json, os, sys
134
+ gi.require_version("Gtk", "3.0")
135
+ from gi.repository import Gtk, Gdk, GLib
136
+ if not Gtk.init_check()[0]:
137
+ sys.exit(1)
138
+ clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
139
+ pending = b""
140
+ generation = 0
141
+ def send(value):
142
+ print(json.dumps(value, ensure_ascii=True), flush=True)
143
+ def changed(clipboard, event):
144
+ global generation
145
+ generation += 1
146
+ current = generation
147
+ def received(clipboard, text, unused):
148
+ if current == generation and text is not None and len(text.encode("utf-8")) <= ${H}:
149
+ send({"text": text})
150
+ clipboard.request_text(received, None)
151
+ # No request_text on startup: never share the pre-existing clipboard.
152
+ clipboard.connect("owner-change", changed)
153
+ def input_ready(fd, condition):
154
+ global pending
155
+ chunk = os.read(fd, 65536)
156
+ if not chunk:
157
+ Gtk.main_quit()
158
+ return False
159
+ pending += chunk
160
+ while b"\n" in pending:
161
+ line, pending = pending.split(b"\n", 1)
162
+ text = json.loads(line)
163
+ if not isinstance(text, str) or len(text.encode("utf-8")) > ${H} or "\x00" in text:
164
+ sys.exit(1)
165
+ clipboard.set_text(text, -1)
166
+ send("ack")
167
+ if len(pending) > ${H*6+2}:
168
+ sys.exit(1)
169
+ return True
170
+ GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
171
+ send("ready")
172
+ Gtk.main()
173
+ `;function kq(q,x){let X=Kx("/usr/bin/python3",["-I","-u","-c",Mx],{env:{DISPLAY:q.display,XAUTHORITY:q.xauthority},stdio:["pipe","pipe","ignore"]}),Q=!1,P=!0,b="",J=0,y=[],C=setTimeout(()=>j(),5000),W=()=>{Q=!0,clearTimeout(C),y.length=0,X.kill("SIGKILL")},j=()=>{if(Q)return;W(),x.end({error:new M("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},R=(Z,B=32)=>{if(Q)return;if(!P){Z();return}if(J+=B,J>pq)W(),x.end({reason:"input_backpressure"});else y.push({apply:Z,bytes:B})};return X.stdout.on("data",(Z)=>{if(Q)return;b+=Z.toString("ascii");for(let B=b.indexOf(`
174
+ `);B>=0;B=b.indexOf(`
175
+ `)){let Y=b.slice(0,B);b=b.slice(B+1);let w;try{w=JSON.parse(Y)}catch{j();return}if(w==="ready"||w==="ack"){clearTimeout(C),P=!1;while(!P&&!Q&&y.length){let N=y.shift();J-=N.bytes,N.apply()}}else if(w&&typeof w==="object"&&"text"in w&&typeof w.text==="string"&&Buffer.byteLength(w.text)<=H)x.clipboard(w.text);else{j();return}if(Q)return}if(b.length>H*6+32)j()}),X.stdin.on("error",j),X.once("error",j),X.once("exit",j),{apply:R,write(Z){if(Buffer.byteLength(Z)>H||Z.includes("\x00")){j();return}let B=`${JSON.stringify(Z)}
176
+ `;R(()=>{if(P=!0,C=setTimeout(()=>j(),5000),X.stdin.write(B),X.stdin.writableLength>pq)W(),x.end({reason:"input_backpressure"})},Buffer.byteLength(B))},close:W}}var a={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}},Ex="avc1.4D002A",Iq={width:1920,height:1080},Ox=262144,$x=0.2,Hx=250,fx=1e4,hx=1024,l8=1e4,gx=500,px=60,kx=1e4,Ix=1000,vq=1048576,oq={kind:"mac_screen",sound:null},vx,uq=()=>vx??=k()?.ffmpeg??null,a8=(q,x,X)=>d8(q,x,{env:X,stdio:["ignore","pipe","ignore"]}),ux,s8=()=>ux??=Oq(k()),cq=(q,x,X)=>{let[Q,...P]=[...s8(),q];return a8(Q,[...P,...x],X)},lq=()=>P0?.videotoolbox?"h264_videotoolbox":"libx264",cx=()=>Math.round(performance.now()*1000),r8=new Set,rq=!1;function tq(q){if(r8.add(q),q.once("exit",()=>r8.delete(q)),rq)return;rq=!0,process.once("exit",()=>{for(let x of r8)try{x.kill("SIGKILL")}catch{}})}function eq(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{}},gx);q.once("exit",()=>clearTimeout(x))}function lx(q,x,X){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(q),"-video_size",`${x.width}x${x.height}`,"-i",X],size:x}}function rx(q){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(q),"-i","Capture screen 0:none"],size:null}}function mx(q){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(q),"-i","pipe:0"],size:null}}var q0=1700000;function x0(q){return Math.min(1,Math.round(Math.sqrt(q0/(q.width*q.height))*100)/100)}function dx(q,x,X){let Q=d8(X.axe,["stream-video","--udid",X.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,x0(X.size)))],{stdio:["ignore","pipe","ignore"]}),P=d8(q,x,{env:{},stdio:["pipe","pipe","ignore"]});Q.stdout.pipe(P.stdin),P.stdin.on("error",()=>{});let b=()=>{if(Q.exitCode===null&&Q.signalCode===null)Q.kill("SIGTERM")};return P.once("exit",b),P.once("error",b),Q.once("exit",()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")}),Q.once("error",()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")}),P}function ax(q){let x=Math.min(1,Iq.width/q.width,Iq.height/q.height);return{width:Math.round(q.width*x),height:Math.round(q.height*x)}}function m8(q,x,X,Q="libx264"){let P=a[q],b=(R)=>Math.max(2,Math.floor(R/2)*2),J={width:b(X.width*P.scale),height:b(X.height*P.scale)},y=J.width!==x.size?.width||J.height!==x.size.height,C=Math.max(1,Math.round(P.kbps*2/P.fps)),W=["-g",String(P.fps*px)],j=Q==="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",...W,"-b:v",`${P.kbps}k`,"-maxrate",`${P.kbps}k`,"-bufsize",`${C}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",P.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...P.threads?["-threads",String(P.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...W,"-crf",String(P.crf),"-maxrate",`${P.kbps}k`,"-bufsize",`${C}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...x.args,"-an",...y?["-vf",`scale=${J.width}:${J.height}:flags=fast_bilinear`]:[],...j,"-flush_packets","1","-f","h264","pipe:1"]}class X0{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(q,x){if(this.buffer.byteLength===0)this.micros=x;let X=new Uint8Array(this.buffer.byteLength+q.byteLength);X.set(this.buffer),X.set(q,this.buffer.byteLength),this.buffer=X;let Q=[],P=this.scanned;while(P+3<this.buffer.byteLength){if(this.buffer[P]!==0||this.buffer[P+1]!==0||this.buffer[P+2]!==1){P++;continue}let b=this.buffer[P+3]&31,J=P>0&&this.buffer[P-1]===0?P-1:P;if(b===9&&J>0)Q.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,P-=J;if(b===5)this.key=!0;P+=3}return this.scanned=P,Q}}function sx(q,x){let X=_x({path:q}),Q=Buffer.alloc(0),P="version",b=0,J=!1,y=[],C=0,W=!1,j=(N)=>{if(W)return;W=!0,X.destroy(),x.end(N)},R=()=>j({reason:"display_protocol"}),Z=(N)=>{if(W)return;if(!J){if(C+=N.byteLength,C>vq)j({reason:"input_backpressure"});else y.push(N);return}if(X.write(N),X.writableLength>vq)j({reason:"input_backpressure"})},B=(N)=>{Q=Q.subarray(N)},Y=()=>{switch(P){case"version":{if(Q.byteLength<12)return!1;let N=/^RFB (\d{3})\.(\d{3})\n$/.exec(Q.subarray(0,12).toString("latin1"));if(!N||Number(N[1])*1000+Number(N[2])<3007)return R(),!1;return B(12),X.write(`RFB 003.007
177
+ `),P="security",!0}case"security":{if(Q.byteLength<1)return!1;let N=Q[0];if(N===0)return R(),!1;if(Q.byteLength<1+N)return!1;if(!Q.subarray(1,1+N).includes(1))return R(),!1;return B(1+N),X.write(Buffer.from([1,1])),P="init",!0}case"init":{if(Q.byteLength<24)return!1;let N=Q.readUInt32BE(20);if(N>65536)return R(),!1;if(Q.byteLength<24+N)return!1;let D={width:Q.readUInt16BE(0),height:Q.readUInt16BE(2)};if(B(24+N),D.width===0||D.height===0)return R(),!1;P="messages",J=!0;for(let G of y)X.write(G);return y=[],C=0,x.ready(D),!W}case"skip":{let N=Math.min(b,Q.byteLength);if(B(N),b-=N,b>0)return!1;return P="messages",!0}case"messages":{if(Q.byteLength<1)return!1;switch(Q[0]){case 1:{if(Q.byteLength<6)return!1;let N=6+Q.readUInt16BE(4)*6;if(Q.byteLength<N)return!1;return B(N),!0}case 2:return B(1),!0;case 3:{if(Q.byteLength<8)return!1;let N=Q.readUInt32BE(4);if(N>H/2)return B(8),P="skip",b=N,!0;if(Q.byteLength<8+N)return!1;let D=Q.subarray(8,8+N).toString("latin1");return B(8+N),x.clipboard(D),!W}default:return R(),!1}}}},w=!1;return X.once("connect",()=>{w=!0}),X.on("data",(N)=>{if(W)return;Q=Q.byteLength?Buffer.concat([Q,N]):N;while(!W&&Y());}),X.once("error",()=>{if(!w)j({error:new M("display_unavailable","Reason could not reach this machine's desktop server.")})}),X.once("close",()=>j({reason:"display_closed"})),{pointer(N,D,G){let F=Buffer.alloc(6);F.writeUInt8(5,0),F.writeUInt8(G&255,1),F.writeUInt16BE(N,2),F.writeUInt16BE(D,4),Z(F)},key(N,D){let G=Buffer.alloc(8);G.writeUInt8(4,0),G.writeUInt8(N?1:0,1),G.writeUInt32BE(D>>>0,4),Z(G)},clipboard(N){if(Array.from(N).some((F)=>F.codePointAt(0)>255)){j({reason:"clipboard_unicode_unsupported"});return}let D=Buffer.from(N,"latin1"),G=Buffer.alloc(8);G.writeUInt8(6,0),G.writeUInt32BE(D.byteLength,4),Z(Buffer.concat([G,D]))},close(){W=!0,X.destroy()}}}class i8{run=null;viewers=new Set;get running(){return this.run!==null}start(q,x,X,Q){this.viewers.add(q),this.stop();let P;try{P=X()}catch{this.fail();return}tq(P);let b={child:P,splitter:new X0};this.run=b;for(let y of[...this.viewers])y.started(x);P.stdout?.on("data",(y)=>{if(this.run!==b)return;for(let C of b.splitter.push(y,Q()))for(let W of[...this.viewers])W.unit(C)});let J=()=>{if(this.run!==b)return;this.run=null,this.fail()};P.once("exit",J),P.once("error",J)}leave(q){if(!this.viewers.delete(q))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;eq(this.run.child),this.run=null}fail(){for(let q of[...this.viewers])q.failed()}}var mq=new WeakMap;function ix(q){let x=mq.get(q);if(!x)mq.set(q,x=new i8);return x}function Q0(q,x,X={}){let Q=X.micros??cx,P=new sq,b=x.request.preset,J=null,y=null,C=null,W=!1,j=null,R=!1,Z=!1,B=null,Y=0,w=0,N=!1,D=null,G=null,F=0,O=null,z=[],i=0,A=[],f=new Uint32Array(l8+1),I=0,C8=null,S8=0,n=0,Z8=0,qq=0,xq=0,X8=null,A8=0,u={frames:0,bytes:0,since:Q()},c=[],o=0,G8,F8=!1,C0=Q(),E={},l=()=>Math.round((Q()-C0)/1000),Xq=X.control??$q,w8=null,V8=null,$=(L)=>{let U=T8(L);return q.send(U),qq+=U.byteLength,U.byteLength},Q8=(L)=>{if(q.done)return;if(q.open)$({type:"error",code:L});q.end({reason:L})},P8=()=>Math.max(Ox,a[b].kbps*1000/8*$x),b8=()=>Q()/1000,S0=()=>{while(A.length>1&&A[0].atMs<b8()-fx)A.shift();return A[0]?.rttMs??null},Qq=(L)=>{let U=S0();if(U===null||z.length===0)return!1;let T=(U+Hx)*L;return b8()-z[0].sentMs>T||i>T/1000*a[b].kbps*1000/8},Z0=(L)=>{if(F===0)return;let U=Math.min(L,F-1);if(O!==null&&U<=O)return;O=U;let T=b8();while(z.length&&z[0].seq<=U){let V=z.shift();if(i-=V.bytes,V.seq!==U)continue;let K=Math.max(0,T-V.sentMs);while(A.length&&A.at(-1).rttMs>=K)A.pop();A.push({atMs:T,rttMs:K}),f[Math.min(l8,Math.round(K))]++,I++,C8=Math.min(C8??K,K)}},A0=()=>{let L=0;for(let U=0;U<=l8;U++)if(L+=f[U],L*2>=I)return U;return 0},G0=()=>q.bufferedAmount<=P8()/2&&!Qq(0.5),Pq=()=>{F8=!0,c=[],o=0,j?.leave(K8),j=null},bq=(L)=>{if(q.done)return;if(L.key)E.first_key_ms??=l();if(!W){if(!j||c.length===0&&!L.key)return;if(c.push(L),o+=L.data.byteLength,o>P8())Pq();return}if(N){n++;return}if(q.bufferedAmount>P8()||Qq(1)){N=!0,n++,D=setInterval(()=>{if(q.done||!G0())return;if(D)clearInterval(D);D=null,N=!1,Y8()},X.drainPollMs??25);return}if(!R){if(!L.key){n++;return}if($({type:"hello",width:y.width,height:y.height,fps:a[b].fps,preset:b,codec:Ex}),R=!0,E.first_frame_ms??=l(),!Z&&J?.sound)$({type:"audioHello",...x8}),Z=!0}let U=$({type:"frame",key:L.key,seq:F,captureMicros:L.micros,data:L.data});if(z.push({seq:F,sentMs:b8(),bytes:U}),i+=U,z.length>hx)i-=z.shift().bytes;F++,S8++,X8??=L.micros,A8=L.micros,u.frames++,u.bytes+=U},K8={started(L){b=L,R=!1,c=[],o=0},unit:bq,failed:()=>Q8("encoder_failed")},M8=()=>{let L=(X.ffmpeg??uq)();if(!J||!y){Q8("encoder_failed");return}let[U,T]=[J,y],V="kind"in U&&U.kind==="simulator"?U.stream:null;if(!L&&!V){Q8("encoder_failed");return}if(j??="kind"in U&&U.kind==="mac_screen"?ix(X.spawn??cq):new i8,E.encoder_ms===void 0)E.encoder_ms=l(),E.encoder_shared=j.running;j.start(K8,b,()=>{let K=a[b].fps;if(V)return V(K,a[b].kbps,q0);if("kind"in U&&U.kind==="simulator"){let h=Math.min(0.99,x0(U.size)),t={width:U.size.width*h,height:U.size.height*h};return dx(L,m8(b,mx(Math.min(K,30)),t,(X.macEncoder??lq)()),U)}return"kind"in U?(X.spawn??cq)(L,m8(b,rx(K),ax(T),(X.macEncoder??lq)()),{}):(X.spawn??a8)(L,m8(b,lx(K,T,U.display),T),{DISPLAY:U.display,XAUTHORITY:U.xauthority})},Q)},J8=()=>{if(!B)return;eq(B.child),B=null},F0=()=>{let L=(X.ffmpeg??uq)();if(B||q.done||!Z||!J?.sound||!L)return;let U;try{U=(X.spawn??a8)(L,gq(),{PULSE_SERVER:j8(J.sound)})}catch{return}tq(U);let T={child:U,reader:new c8};B=T,U.stdout?.on("data",(K)=>{if(B!==T||q.done)return;let h;try{h=T.reader.push(K)}catch{J8();return}let t=Q();for(let w0 of h){if(q.bufferedAmount>P8()){w++;continue}$({type:"audio",captureMicros:t,data:w0}),Y++}});let V=()=>{if(B===T)J8()};U.once("exit",V),U.once("error",V)},Y8=()=>{if(!j||q.done)return;Z8++,M8()},Jq=()=>{if(q.done||!y)return;if(!W){if(j||F8)return;M8(),G8=setTimeout(()=>{if(!W)Pq()},kx);return}if(clearTimeout(G8),E.encoder_early===void 0){if(E.encoder_early=j!==null,F8)E.hold_lapsed=!0}if(!j)M8();let L=c;c=[],o=0;for(let U of L)bq(U);G??=setInterval(()=>{let U=Q(),T=Math.max(0.001,(U-u.since)/1e6);$({type:"stats",stats:{fps:Math.round(u.frames/T*10)/10,kbps:Math.round(u.bytes*8/1000/T),dropped:n,restarts:Z8,queued_bytes:q.bufferedAmount}}),u={frames:0,bytes:0,since:U}},Ix)};x.desktop.then((L)=>{if(q.done)return;J=L;let U={ready(T){y=T,E.desktop_ms??=l(),Jq()},clipboard(T){if(q.open&&Buffer.byteLength(T)<=H)$({type:"serverClipboard",text:T})},end(T){if("reason"in T&&q.open)$({type:"error",code:T.reason});q.end(T)}};if("kind"in L&&L.kind==="simulator")C=L.input,U.ready(L.points);else if("kind"in L)C=(X.macInput??((T)=>nq(T,s8())))(U);else{let T=(X.linuxClipboard??kq)(L,U),V=sx(L.rfbSocket,{...U,clipboard:(K)=>{if(!T)U.clipboard(K)}});C=T?{pointer:(K,h,t)=>T.apply(()=>V.pointer(K,h,t)),key:(K,h)=>T.apply(()=>V.key(K,h)),clipboard:(K)=>T.write(K),close(){T.close(),V.close()}}:V}Nq()},(L)=>q.end({error:L}));function Nq(){if(V8||!x.viewerSameNetwork||!W||q.done||!J||!("kind"in J)||J.kind!=="mac_screen")return;V8=(X.macWindows??iq)((L)=>{if(q.open)$({type:"windows",bounds:L})})}let Wq={viewer:x.viewer??null,notify(L){if(q.open)$({type:"control",control:L})}},z8=(L)=>{if(!C)return;if(!J||!("kind"in J)||J.kind!=="simulator")Xq.claim(Wq);L(C)};return{opened(){E.relay_ms??=l()},received(L){xq+=L.byteLength;let U;try{U=P.push(L)}catch{Q8("viewer_protocol");return}for(let T of U){if(q.done)return;switch(T.type){case"ping":$({type:"pong",token:T.token});break;case"pointer":z8((V)=>V.pointer(T.x,T.y,T.buttons));break;case"key":z8((V)=>V.key(T.down,T.keysym));break;case"clientClipboard":z8((V)=>V.clipboard(T.text));break;case"config":if(T.preset!==b)b=T.preset,Y8();break;case"keyframeRequest":if(R&&!N)Y8();break;case"ack":Z0(T.seq);break;case"audioEnable":if(T.on)F0();else J8();break;default:break}}if(!W&&!q.done){if(W=!0,E.viewer_ms=l(),x.viewer)w8=Xq.join(Wq);Jq(),Nq()}},close(){if(w8?.(),w8=null,V8?.close(),D)clearInterval(D);if(G)clearInterval(G);clearTimeout(G8),j?.leave(K8),J8(),C?.close()},summary:()=>({output_bytes:qq,input_bytes:xq,video:{preset:b,frames:S8,dropped:n,restarts:Z8,avg_fps:X8!==null&&A8>X8?Math.round((S8-1)/((A8-X8)/1e6)*10)/10:0,min_rtt_ms:Math.round(C8??0),p50_rtt_ms:I?A0():0,audio_packets:Y,audio_dropped:w,connect:E}})}}var dq=null,P0=null,nx=null;function ox(){let q=k();return q?.features.display?q.ffmpeg:null}function b0(q){return dq??=new Promise((x)=>{Yx(q,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(X,Q)=>{let P=(b)=>!X&&new RegExp(`^\\s*V\\S*\\s+${b}\\s`,"m").test(Q);x(P0={x264:P("libx264"),videotoolbox:P("h264_videotoolbox")})})}),dq}var aq=null;function HX(){return aq??=(async()=>{let q=[k()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((X)=>Boolean(X&&zx(X)));if(!q)return null;let x=await b0(q);return x.videotoolbox||x.x264?q:null})(),aq}function J0(q=process.platform,x={}){if(q!=="linux"&&q!=="darwin")return Promise.resolve(!1);let X=(x.ffmpeg??ox)();if(!X)return Promise.resolve(!1);let Q=(x.encoders??b0)(X);if(q==="linux")return Q.then((b)=>b.x264);let P=x.macScreen?x.macScreen():nx??=$8(s8());return Promise.all([Q,P]).then(([b,J])=>(b.x264||b.videotoolbox)&&J?.screen===!0&&J.accessibility)}var J1=43200000,B8=":99",N1=60000,R8=15000,t8={width:1280,height:800},W1=/^[A-Za-z0-9._:-]{1,160}$/;function U1(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}var L1=["video","viewer","viewer_same_network","viewer_network"];function y1(q,x=Date.now()){let X=["relay_url","session_id","expires_at"];if(!U1(q)||X.some((y)=>!(y in q))||Object.keys(q).some((y)=>!X.includes(y)&&!L1.includes(y)))throw new M("invalid_display_request","Reason desktop request is malformed.");let Q="video"in q?y0(q.video):void 0,P="viewer"in q?L0(q.viewer):null;if(Q===null)throw new M("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 M("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof q.session_id!=="string"||!W1.test(q.session_id))throw new M("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 M("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+J1)).toISOString(),...Q?{video:Q}:{},...P?{viewer:P}:{},...Q&&q.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function j1(q=process.platform){return(q==="linux"||q==="darwin")&&k()?.features.display===!0}async function nX(){if(process.platform!=="darwin")return j1();return await J0()}function D8(q){X1(q,{recursive:!0,mode:448});let x=x1(q);if(!x.isDirectory()||x.isSymbolicLink()||process.getuid&&x.uid!==process.getuid())throw new M("display_unavailable","Reason desktop state directory is not private.");q1(q,448)}function T1(q,x){let X=(P)=>{let b=Buffer.alloc(2);return b.writeUInt16BE(P.length),Buffer.concat([b,P])},Q=Buffer.from([255,255]);return Buffer.concat([Q,X(Buffer.alloc(0)),X(Buffer.from(q)),X(Buffer.from("MIT-MAGIC-COOKIE-1")),X(x)])}function s(q,x,X=2000){return new Promise((Q)=>{let P=b1(q),b="",J=(y)=>{P.destroy(),Q(y)};P.setTimeout(X,()=>J(!1)),P.once("error",()=>J(!1)),P.once("close",()=>J(!1)),P.once("connect",()=>{if(!x)J(!0)}),P.on("data",(y)=>{if(b+=y.toString("latin1"),b.length>=4)J(b.startsWith("RFB "))})})}async function D0(q,x){let X=Date.now()+x;while(Date.now()<X){if(await q())return!0;await new Promise((Q)=>setTimeout(Q,100))}return!1}function e8(q,x,X){return new Promise((Q)=>{let P=T0(q,x,{detached:!0,stdio:"ignore",env:X});P.once("error",()=>Q(-1)),P.once("exit",(b)=>Q(b)),P.unref(),setTimeout(()=>Q(null),R8).unref()})}var n8=null;function B1(q=d()){return n8??=D1(q).finally(()=>{n8=null}),n8}async function D1(q){let x=k({home:q});if(!x?.xvfb||!x.x11vnc||!x.openbox)throw new M("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");W0({root:x.root,automation:x.automation,extensionDir:x.extensionDir});let X=_(x.root,"display");D8(X);let Q=await C1(q,X,x.x11vnc);if(Q)return Q;let P={display:B8,xauthority:_(X,"Xauthority"),rfbSocket:_(X,"rfb.sock")},b=_(X,"pulse"),J=(async()=>{try{D8(b)}catch{return null}return await hq(b,x.pulseaudio)})(),y=_(X,"home");D8(y);let C={HOME:y,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:P.display,XAUTHORITY:P.xauthority};if(x.pulseaudio)C.PULSE_SERVER=j8(u8(b));let W=async()=>({...P,sound:await J});if(await s({path:P.rfbSocket},!0))return await W();if(!B0(P.xauthority))o8(P.xauthority,T1(B8.slice(1),ex(16)),{mode:384,flag:"wx"});let j=S1(_(X,"theme"),P.display),R={path:`/tmp/.X11-unix/X${B8.slice(1)}`};if(!await s(R,!1)){if(e8(x.xvfb,[P.display,"-screen","0",`${t8.width}x${t8.height}x24`,"-nolisten","tcp","-auth",P.xauthority],C),!await D0(()=>s(R,!1),R8))throw new M("display_unavailable","Reason could not start the virtual display.");e8(x.openbox,["--config-file",j.openboxConfig],C)}if(await Z1(j,C),!await R0(x.x11vnc,P,X,"x11vnc.log",C))throw new M("display_unavailable","Reason could not start the desktop server.");return await W()}async function R0(q,x,X,Q,P){if(await s({path:x.rfbSocket},!0))return!0;P1(x.rfbSocket,{force:!0});let b=await e8(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",_(X,Q)],P);if(b!==null&&b!==0)return!1;return await D0(()=>s({path:x.rfbSocket},!0),R8)}async function R1(){let q=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],x=(X)=>Object.fromEntries(q.flatMap((Q)=>X[Q]?[[Q,X[Q]]]:[]));if(process.env.DISPLAY)return x(process.env);try{let X=await new Promise((Q,P)=>tx("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(b,J)=>b?P(b):Q(J)));return x(Object.fromEntries(X.split(`
178
+ `).flatMap((Q)=>{let P=Q.indexOf("=");return P>0?[[Q.slice(0,P),Q.slice(P+1)]]:[]})))}catch{return{}}}var N0=new Set;async function C1(q,x,X){let Q=await R1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===B8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??_(q,".Xauthority"),rfbSocket:_(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(N0.has(J)||!await s({path:`/tmp/.X11-unix/X${P}`},!1))return null;let y={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await R0(X,b,x,`x11vnc-${P}.log`,y))return{...b,sound:null};return N0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
179
+ `),null}function S1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!B0(`/usr/bin/${b}`)).map(([b])=>b),P=Rq({root:q,display:x,screen:t8,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])D8(_(q,b));for(let[b,J]of Object.entries(P.files))o8(_(q,b),J,{mode:384});for(let[b,J]of Object.entries(Dq))o8(_(q,`ara-${b}`),Q1(J),{mode:384});return{root:q,openboxConfig:_(q,"openbox","rc.xml"),start:P.start}}async function Z1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
180
+ `);await new Promise((Q)=>{let P=T0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},R8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function oX(q,x={}){let X=x.now??Date.now,Q=y1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new M("display_video_required","Reason desktops stream as video now; this request came without it.");let P=x.platform??process.platform;if(P!=="linux"&&P!=="darwin")throw new M("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>oq:B1))();return await A1(q.signal,Q,x,X,(y)=>Q0(y,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(y)=>T8({type:"error",code:y}))}function A1(q,x,X,Q,P,b){let J=Q();return new Promise((y,C)=>{let W=null,j=!1,R=!1,Z,B,Y,w=!1,N=null,D=(A)=>{if(R)return;if(N)A=N;R=!0,clearTimeout(Z),clearTimeout(B),q.removeEventListener("abort",F),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in A){C(A.error);return}y({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},G=()=>D({error:new M("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;D({error:A instanceof M?A:new M("cancelled","Reason closed the desktop session.")})},O=()=>{if(!N||!W)return;let A=N.error;try{W.send(b(A instanceof M?A.code:"display_unavailable"))}catch{}D(N)};if(Y=P({get done(){return R||N!==null},get open(){return j&&!R&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(A){if(R||N||!j||!W)return;try{W.send(A)}catch{D({reason:"relay_closed"})}},end:(A)=>{if(R||N)return;if(!("error"in A)){D(A);return}if(N=A,w&&j)O()}}),R){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),Z=setTimeout(()=>D({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),B=setTimeout(()=>D({reason:"viewer_absent"}),X.viewerWaitMs??N1);try{W=(X.connect??j0)(x.relay_url,(X.loadProxy??U0)()?.url)}catch{G();return}W.binaryType="arraybuffer",W.onopen=()=>{if(R||!W)return;j=!0,Y?.opened()},W.onmessage=(A)=>{if(R)return;let f=A.data,I=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!I||I.byteLength===0)return;if(clearTimeout(B),w=!0,N){O();return}Y?.received(I)},W.onclose=()=>{if(R)return;if(!j){G();return}D({reason:"relay_closed"})},W.onerror=()=>{if(R||j)return;G()}})}
181
+ export{_8 as ie,f1 as je,p1 as ke,r as le,j8 as me,HX as ne,J0 as oe,Cq as pe,zq as qe,k as re,UX as se,LX as te,yX as ue,J1 as ve,B8 as we,y1 as xe,j1 as ye,nX as ze,D8 as Ae,B1 as Be,oX as Ce};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Oh as l}from"./vm-hands-entry-lite-v6tkjqb1.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
2
+ import{Wh as l}from"./vm-hands-entry-lite-40t7d4p5.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);X>=0;X=B.indexOf(`
110
110
  `)){let S=B.slice(0,X);if(B=B.slice(X+1),!S.startsWith("c "))continue;let O=S.slice(2);if(O.length>Math.ceil(Y/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(O)){K({reason:"display_protocol"});return}let _=Buffer.from(O,"base64");if(_.byteLength<=Y)q.clipboard(_.toString("utf8"));if(z)return}if(B.length>Math.ceil(Y/3)*4+2)K({reason:"display_protocol"})}),G.once("error",()=>W("Reason could not watch this Mac's desktop clipboard.")),G.once("exit",()=>{if(!z)W("Reason could not watch this Mac's desktop clipboard.")})};return J.stdout.on("data",(B)=>{if(z||Z===null)return;Z+=B.toString("utf8");let N=Z.indexOf(`
111
111
  `);if(N<0){if(Z.length>4096)K({reason:"display_protocol"});return}let X=y(Z.slice(0,N));if(Z=null,!X)K({reason:"display_protocol"});else if(!X.screen||!X.accessibility)W(j.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else i(),q.ready({width:X.width,height:X.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>W("Reason could not start this Mac's desktop input.")),J.once("exit",()=>{if(Z!==null)W("Reason could not start this Mac's desktop input.");else K({reason:"display_closed"})}),{pointer:(B,N,X)=>L(Q.pointer(B,N,X)),key:(B,N)=>L(Q.key(B,N)),clipboard:(B)=>L([`c ${Buffer.from(B,"utf8").toString("base64")}`]),close(){z=!0,F()}}}
112
- export{Cj as Fg,kj as Gg,h as Hg,Yj as Ig,Y as Jg,Lj as Kg,Aj as Lg,s as Mg,xj as Ng,Mj as Og,fj as Pg,hj as Qg,$j as Rg,y as Sg,Sj as Tg,_j as Ug,Hj as Vg,Tj as Wg,a as Xg,Vj as Yg};
112
+ export{Cj as af,kj as bf,h as cf,Yj as df,Y as ef,Lj as ff,Aj as gf,s as hf,xj as if,Mj as jf,fj as kf,hj as lf,$j as mf,y as nf,Sj as of,_j as pf,Hj as qf,Tj as rf,a as sf,Vj as tf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{lh as X,nh as Y,ph as Z}from"./vm-hands-entry-lite-ne8kkvk4.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
- export{Q as ch,O as dh,_ as eh,b as fh,g as gh};
2
+ import{Ah as Y,Ch as Z,yh as X}from"./vm-hands-entry-lite-n5ec0fjy.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
+ export{Q as ph,O as qh,_ as rh,b as sh,g as th};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var U=".reason/workspace",T="workspace_base",y="sessions",W="workspace_layout",g=".reason/workspace/sessions",B=/^[0-9a-f]{8}$/;function C(j){if(!J(j))return!1;let q=".reason/workspace/sessions/";if(!j.startsWith(q))return!1;let z=j.slice(q.length).split("/");return z.length===2&&B.test(z[0])}var G=4096,X="workspaces/pi";function J(j){if(typeof j!=="string"||!j||j.length>G)return!1;if(j.startsWith("/")||j.includes("\x00")||j.includes("\\"))return!1;return j.split("/").every((q)=>q!==""&&q!=="."&&q!=="..")}function Z(j){if(j.kind==="root"){if(j.path===void 0)return".";if(!J(j.path))throw Error("invalid_device_workspace_identity");return j.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(j.workspaceId)||j.workspaceId==="."||j.workspaceId==="..")throw Error("invalid_device_workspace_identity");let q=j.layout==="sessions"?"sessions":X;return`${j.base?`${j.base}/`:""}${q}/${j.workspaceId}/repo`}function L(j){if(!j||typeof j!=="object"||Array.isArray(j))return null;let q=j;if(q.kind==="root"&&Object.keys(q).length===1)return{kind:"root"};if(q.kind==="root"&&Object.keys(q).length===2&&J(q.path))return{kind:"root",path:q.path};if(q.kind!=="managed"||typeof q.workspaceId!=="string"||Object.keys(q).length!==2+(q.base===void 0?0:1)+(q.layout===void 0?0:1)||q.base!==void 0&&q.base!==".reason/workspace"||q.layout!==void 0&&q.layout!=="sessions")return null;let z={kind:"managed",workspaceId:q.workspaceId,...q.base===".reason/workspace"?{base:".reason/workspace"}:{},...q.layout==="sessions"?{layout:"sessions"}:{}};try{return Z(z),z}catch{return null}}var b="/home/runner",P=10001,x="/run/reason/sessions",f=/^(?:\/[A-Za-z0-9._-]+)+$/,M=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,H=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function K(j){return M.exec(j)?.[1]??H.exec(j)?.[1]??j}var $=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/,A="*/.reason/workspace/workspaces/pi/*|*/.reason/workspace/sessions/*";function N(j,q=b,z="sessions"){if(!f.test(q)||q.split("/").some((V)=>V==="."||V===".."))throw Error("invalid_cloud_payload_home");let Q=`${q}/${Z({kind:"managed",workspaceId:j,base:".reason/workspace",...z?{layout:z}:{}})}`,F=`${x}/${K(j)}`;return{home:q,root:Q.slice(0,-5),checkout:Q,control:F,jobEnv:`${F}/job.env`,cloudAccess:`${F}/cloud-access`,logs:`${F}/logs`,pin:`${F}/ws`}}function Y(j){return $.exec(j.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function D(j){return{kind:"managed",workspaceId:j,layout:"sessions"}}function R(j){let q=$.exec(j.replace(/\/+$/,""));if(!q)return null;try{let z=N(q[3],q[1],Y(j));return z.root===j.replace(/\/+$/,"")?z:null}catch{return null}}
3
- export{U as hh,T as ih,y as jh,W as kh,g as lh,B as mh,C as nh,J as oh,Z as ph,L as qh,b as rh,P as sh,x as th,M as uh,H as vh,$ as wh,A as xh,N as yh,Y as zh,D as Ah,R as Bh};
3
+ export{U as uh,T as vh,y as wh,W as xh,g as yh,B as zh,C as Ah,J as Bh,Z as Ch,L as Dh,b as Eh,P as Fh,x as Gh,M as Hh,H as Ih,$ as Jh,A as Kh,N as Lh,Y as Mh,D as Nh,R as Oh};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Zb as X}from"./vm-hands-entry-lite-n07kxrd1.js";import{spawn as M}from"child_process";import{existsSync as C}from"fs";import{homedir as g}from"os";import{basename as D,join as N}from"path";var Y="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",G=Y.split(":"),f=5000,I=65536,U=new Set(["zsh","bash"]),V=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],j=(J,K)=>new Promise((W,Z)=>{let Q;try{Q=M(J,[...K],{detached:!0,stdio:["ignore","pipe","ignore"]})}catch($){Z($);return}let z=[],x=0,R=null,B=($)=>{R??=Error($);try{if(Q.pid!==void 0)process.kill(-Q.pid,"SIGKILL")}catch{}},F=setTimeout(()=>B("login_shell_timeout"),f);Q.stdout?.on("data",($)=>{if(x+=$.length,x>I)B("login_shell_output_too_large");else z.push($)}),Q.once("error",($)=>{clearTimeout(F),Z($)}),Q.once("close",($)=>{if(clearTimeout(F),R)Z(R);else if($!==0)Z(Error("login_shell_exit_nonzero"));else W(Buffer.concat(z).toString("utf8"))})});function O(J){return typeof J==="string"&&J.startsWith("/")&&!J.includes("\x00")&&U.has(D(J))}function q(J){let K=new Set,W=[];for(let Z of J){if(K.has(Z))continue;K.add(Z),W.push(Z)}return W}function H(J){let K=J.split(`
2
+ import{ac as X}from"./vm-hands-entry-lite-9y8v419y.js";import{spawn as M}from"child_process";import{existsSync as C}from"fs";import{homedir as g}from"os";import{basename as D,join as N}from"path";var Y="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",G=Y.split(":"),f=5000,I=65536,U=new Set(["zsh","bash"]),V=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],j=(J,K)=>new Promise((W,Z)=>{let Q;try{Q=M(J,[...K],{detached:!0,stdio:["ignore","pipe","ignore"]})}catch($){Z($);return}let z=[],x=0,R=null,B=($)=>{R??=Error($);try{if(Q.pid!==void 0)process.kill(-Q.pid,"SIGKILL")}catch{}},F=setTimeout(()=>B("login_shell_timeout"),f);Q.stdout?.on("data",($)=>{if(x+=$.length,x>I)B("login_shell_output_too_large");else z.push($)}),Q.once("error",($)=>{clearTimeout(F),Z($)}),Q.once("close",($)=>{if(clearTimeout(F),R)Z(R);else if($!==0)Z(Error("login_shell_exit_nonzero"));else W(Buffer.concat(z).toString("utf8"))})});function O(J){return typeof J==="string"&&J.startsWith("/")&&!J.includes("\x00")&&U.has(D(J))}function q(J){let K=new Set,W=[];for(let Z of J){if(K.has(Z))continue;K.add(Z),W.push(Z)}return W}function H(J){let K=J.split(`
3
3
  `).at(-1)??"",W=[];for(let Z of K.split(":")){let Q=Z.trim();if(!Q.startsWith("/"))continue;if(Q.includes("\x00"))continue;if(X(Q))continue;W.push(Q)}return q(W)}function k(J){let K=J?.home??g(),W=J?.directoryExists??C,Z=V.map((Q)=>N(K,...Q)).filter((Q)=>{try{return W(Q)}catch{return!1}});return q([...Z,...G]).join(":")}async function S(J){let K=J?.shell??process.env.SHELL,W=()=>({path:k({home:J?.home,directoryExists:J?.directoryExists}),source:"fallback"});if(!O(K))return W();let Z;try{Z=await(J?.runLoginShell??j)(K,["-lic",'printf %s "$PATH"'])}catch{return W()}if(Buffer.byteLength(Z,"utf8")>I)return W();let Q=H(Z);if(Q.length===0)return W();return{path:q([...Q,...G]).join(":"),source:"login_shell"}}function v(J){let K=null;return()=>{return K??=S(J),K}}function w(J){if(J===void 0||J.includes("\x00")||Buffer.byteLength(J,"utf8")>32768)return;return J}function P(J){let K=J.source??process.env,W={HOME:J.home,PATH:J.path??Y,TMPDIR:J.temporaryDirectory,SHELL:w(K.SHELL)??"/bin/zsh",LANG:w(K.LANG)??"C.UTF-8",LC_ALL:w(K.LC_ALL)??w(K.LANG)??"C.UTF-8"},Z=w(K.LC_CTYPE),Q=w(K.TERM),z=w(K.COLORTERM);if(Z)W.LC_CTYPE=Z;if(Q)W.TERM=Q;if(z)W.COLORTERM=z;return W}
4
- export{Y as Qb,H as Rb,k as Sb,v as Tb,P as Ub};
4
+ export{Y as Tb,H as Ub,k as Vb,v as Wb,P as Xb};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var r={name:"github-native-engineer-device-worker-production",version:"0.2.328",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.13",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 Gh};
2
+ var r={name:"github-native-engineer-device-worker-production",version:"0.2.330",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.13",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 $e};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Vb as i,Wb as l,Xb as g,Yb as y}from"./vm-hands-entry-lite-n07kxrd1.js";import{Bf as S,Cf as _,Ef as P,Ff as C,Gf as I,If as O,Lf as A,lf as Q,mf as J,nf as z,of as Z,pf as K,qf as $,rf as k,tf as G,vf as X,wf as M,xf as Y,yf as H,zf as V}from"./vm-hands-entry-lite-yhz6sv35.js";import{th as L,uh as W,vh as F,wh as j}from"./vm-hands-entry-lite-ne8kkvk4.js";var d=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var a=String.raw`(function(fs, path) {
2
+ import{$b as y,Yb as i,Zb as l,_b as g}from"./vm-hands-entry-lite-9y8v419y.js";import{Ag as S,Bg as _,Dg as P,Eg as C,Fg as I,Hg as O,Kg as A,kg as Q,lg as J,mg as z,ng as Z,og as K,pg as $,qg as k,sg as G,ug as X,vg as M,wg as Y,xg as H,yg as V}from"./vm-hands-entry-lite-8afzattm.js";import{Gh as L,Hh as W,Ih as F,Jh as j}from"./vm-hands-entry-lite-n5ec0fjy.js";var d=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var a=String.raw`(function(fs, path) {
3
3
  const fail = (message, reasonCode) => { throw Object.assign(Error(message), {reasonCode}); };
4
4
  const read = (p, reasonCode, trim=true) => { try { const text=fs.readFileSync(p, "utf8"); return trim?text.trim():text; }
5
5
  catch { fail("memory_read", reasonCode); } };
@@ -4080,4 +4080,4 @@ void startJobControl().then(() => {
4080
4080
  if (validPrivateJob) markReady(); else connect();
4081
4081
  }, () => process.exit(45));
4082
4082
  `.trimStart(),vt=ut("sha256").update(xt,"utf8").digest("hex");
4083
- export{n as tb,h as ub,bt as vb,o as wb,Gt as xb,b as yb,m as zb,ct as Ab,ft as Bb,dt as Cb,at as Db,Rt as Eb,gt as Fb,yt as Gb,xt as Hb,vt as Ib};
4083
+ export{n as wb,h as xb,bt as yb,o as zb,Gt as Ab,b as Bb,m as Cb,ct as Db,ft as Eb,dt as Fb,at as Gb,Rt as Hb,gt as Ib,yt as Jb,xt as Kb,vt as Lb};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Kb as j,Lb as q}from"./vm-hands-entry-lite-93ejmwqn.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
2
+ import{Nb as j,Ob as q}from"./vm-hands-entry-lite-rd9vsaew.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
3
3
  export{y as t};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{t as d0}from"./vm-hands-entry-lite-xf6schkk.js";import{A as G5,B as B5,C as R7,D as C7,E as v3,F as i5,G as H5,H as _0,I as l$,J as p$,K as S0,L as J2,M as n5,N as n0,O as M6,P as Z3,Q as Z6,U as Q6,ba as x7,ca as E7,da as S7,ea as w7,fa as u3,y as l6,z as p6}from"./vm-hands-entry-lite-f8f057tx.js";import{Aa as K5,Ba as V5,Ca as L7,Da as D7,Fa as u,Ga as e,Ha as s,Ia as c,Ja as W5,Ka as z7,La as W$,Oa as V4,Pa as H4,Qa as CJ,Ra as PJ,Sa as IJ,Ta as y0,Ua as J0,Va as g,Wa as g3,Xa as E$,Ya as K2,Za as U0,_a as O7,db as U6,fb as h8,ha as r7,ib as u2,ka as z5,kb as a5,la as O5,lb as T3,nb as h5,oa as F5,qa as E5,rb as A7,sb as N3,ta as S5,ya as y5,za as f5}from"./vm-hands-entry-lite-pwzz9ntw.js";import{Ab as w5,Bb as b5,Ib as k5}from"./vm-hands-entry-lite-fq0zr7an.js";import{Nb as N5}from"./vm-hands-entry-lite-93ejmwqn.js";import{Ub as s5}from"./vm-hands-entry-lite-qvrnx0vk.js";import{mc as Y5}from"./vm-hands-entry-lite-b2wdaq7x.js";import{Ac as bJ,Bc as Y4,Cc as F1,Dc as E8,Ec as G4,Ic as t5,Lc as P7,Oc as c6,Pc as s6,qc as i1,rc as G1,sc as I1,tc as L$,uc as HJ,vc as EJ,wc as SJ,xc as D$,yc as wJ,zc as e3}from"./vm-hands-entry-lite-qwba7w42.js";import{Fd as X5,Ld as $$,Vd as F2,Zc as b2,bd as F7,cd as W7}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as G}from"./vm-hands-entry-lite-psybjyay.js";import{Be as J6,me as xJ,ne as o2,qe as I7,te as n$,ve as tJ,we as oJ}from"./vm-hands-entry-lite-yjzz85pt.js";import{$e as e1,Fe as k0,Ge as k$,Ie as x0,Je as j4,Le as e0,Me as z0,Ne as y9,Oe as AJ,Pe as RJ,Qe as E2,Re as q2,Se as f3,Te as I8,Ue as x8,Ve as Y$,We as v$,Xe as G0,Ye as T2,Ze as y7,_e as f7,af as R4,cf as Q3,df as h1,ef as v0,ff as y$,gf as X3,jf as m1}from"./vm-hands-entry-lite-wh0qp1gf.js";import{nf as x5}from"./vm-hands-entry-lite-yhz6sv35.js";import{mg as LJ,pg as r5,qg as h3,sg as U5}from"./vm-hands-entry-lite-7q2gywdm.js";import{$g as Z2,ah as c5}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as V0,eh as V7}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Ch as r}from"./vm-hands-entry-lite-qgse6zav.js";import{Jh as j7}from"./vm-hands-entry-lite-14t846kp.js";import{Oh as g0}from"./vm-hands-entry-lite-v6tkjqb1.js";import{spawn as kJ,spawnSync as $V}from"child_process";import{closeSync as yJ,mkdirSync as JV,openSync as fJ,readdirSync as ZV,realpathSync as B1,rmSync as z$}from"fs";import{hostname as QV}from"os";import{dirname as $9,join as F0,resolve as XV}from"path";var $Z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function U9($){let J=typeof $==="string"?$Z.exec($):null;return J?{major:Number(J[1]),minor:Number(J[2])}:null}import{createHash as KZ,randomBytes as z9}from"crypto";import{createInterface as VZ}from"readline";import{randomBytes as JZ}from"crypto";import{chmodSync as M9,existsSync as T9,lstatSync as ZZ,mkdirSync as QZ,readFileSync as _9,renameSync as XZ,unlinkSync as F9,writeFileSync as W9}from"fs";import{homedir as YZ}from"os";import{dirname as GZ,join as q9}from"path";function $1($=process.env,J=YZ()){let Z=$.XDG_CONFIG_HOME?.trim()||q9(J,".config"),X=x0({env:$})==="staging"?["staging"]:[];return q9(q2(Z,...X),"credentials.json")}function L9($,J=$1()){return QZ(GZ(J),{recursive:!0,mode:448}),W9(J,`${JSON.stringify($,null,2)}
2
+ import{t as d0}from"./vm-hands-entry-lite-pbnx8z9g.js";import{B as l6,C as p6,D as G5,E as B5,F as R7,G as C7,H as v3,I as i5,J as H5,K as _0,L as l$,M as p$,N as S0,O as J2,P as n5,Q as n0,R as M6,S as Z3,T as Z6,X as Q6,ea as x7,fa as E7,ga as S7,ha as w7,ia as u3}from"./vm-hands-entry-lite-ydjye6jz.js";import{$a as K2,Ba as y5,Ca as f5,Da as K5,Ea as V5,Fa as L7,Ga as D7,Ia as u,Ja as e,Ka as s,La as c,Ma as W5,Na as z7,Oa as W$,Ra as V4,Sa as H4,Ta as CJ,Ua as PJ,Va as IJ,Wa as y0,Xa as J0,Ya as g,Za as g3,_a as E$,ab as U0,bb as O7,gb as U6,ib as h8,ka as r7,lb as u2,na as z5,nb as a5,oa as O5,ob as T3,qb as h5,ra as F5,ta as E5,ub as A7,vb as N3,wa as S5}from"./vm-hands-entry-lite-g5w3cema.js";import{Db as w5,Eb as b5,Lb as k5}from"./vm-hands-entry-lite-nj8bmc9y.js";import{Qb as N5}from"./vm-hands-entry-lite-rd9vsaew.js";import{Xb as s5}from"./vm-hands-entry-lite-n8gsyjq7.js";import{pc as Y5}from"./vm-hands-entry-lite-abrbc7gf.js";import{Ac as D$,Bc as wJ,Cc as e3,Dc as bJ,Ec as Y4,Fc as F1,Gc as E8,Hc as G4,Lc as t5,Oc as P7,Rc as c6,Sc as s6,tc as i1,uc as G1,vc as I1,wc as L$,xc as HJ,yc as EJ,zc as SJ}from"./vm-hands-entry-lite-dj69r683.js";import{Id as X5,Od as $$,Yd as F2,ad as b2,ed as F7,fd as W7}from"./vm-hands-entry-lite-rnwjp0tk.js";import{he as G}from"./vm-hands-entry-lite-669hk342.js";import{ke as xJ,le as o2,oe as I7,re as n$,te as tJ,ue as oJ,ze as J6}from"./vm-hands-entry-lite-j7ee0rr6.js";import{Ee as LJ,He as r5,Ie as h3,Ke as U5}from"./vm-hands-entry-lite-ht03kzr3.js";import{Xe as r}from"./vm-hands-entry-lite-e5fatvff.js";import{$f as R4,Ef as k0,Ff as k$,Hf as x0,If as j4,Kf as e0,Lf as z0,Mf as y9,Nf as AJ,Of as RJ,Pf as E2,Qf as q2,Rf as f3,Sf as I8,Tf as x8,Uf as Y$,Vf as v$,Wf as G0,Xf as T2,Yf as y7,Zf as f7,_f as e1,bg as Q3,cg as h1,dg as v0,eg as y$,fg as X3,ig as m1}from"./vm-hands-entry-lite-sggk0bqc.js";import{mg as x5}from"./vm-hands-entry-lite-8afzattm.js";import{mh as Z2,nh as c5}from"./vm-hands-entry-lite-djy0ww6h.js";import{ph as V0,rh as V7}from"./vm-hands-entry-lite-kbz9zfha.js";import{Rh as j7}from"./vm-hands-entry-lite-dyqeaqzb.js";import{Wh as g0}from"./vm-hands-entry-lite-40t7d4p5.js";import{spawn as kJ,spawnSync as $V}from"child_process";import{closeSync as yJ,mkdirSync as JV,openSync as fJ,readdirSync as ZV,realpathSync as B1,rmSync as z$}from"fs";import{hostname as QV}from"os";import{dirname as $9,join as F0,resolve as XV}from"path";var $Z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function U9($){let J=typeof $==="string"?$Z.exec($):null;return J?{major:Number(J[1]),minor:Number(J[2])}:null}import{createHash as KZ,randomBytes as z9}from"crypto";import{createInterface as VZ}from"readline";import{randomBytes as JZ}from"crypto";import{chmodSync as M9,existsSync as T9,lstatSync as ZZ,mkdirSync as QZ,readFileSync as _9,renameSync as XZ,unlinkSync as F9,writeFileSync as W9}from"fs";import{homedir as YZ}from"os";import{dirname as GZ,join as q9}from"path";function $1($=process.env,J=YZ()){let Z=$.XDG_CONFIG_HOME?.trim()||q9(J,".config"),X=x0({env:$})==="staging"?["staging"]:[];return q9(q2(Z,...X),"credentials.json")}function L9($,J=$1()){return QZ(GZ(J),{recursive:!0,mode:448}),W9(J,`${JSON.stringify($,null,2)}
3
3
  `,{mode:384}),M9(J,384),J}function I$($=$1()){if(!T9($))return null;try{let J=_9($,"utf8"),Z=JSON.parse(J);if(typeof Z.apiOrigin!=="string"||typeof Z.clientId!=="string"||typeof Z.accessToken!=="string"||typeof Z.refreshToken!=="string"||typeof Z.expiresAt!=="string"||typeof Z.orgId!=="string"||!Array.isArray(Z.scopes))return null;let Q=new URL(Z.apiOrigin).origin,X=e0(Q);if(X!==Q)BZ($,J,X);return{apiOrigin:X,clientId:Z.clientId,accessToken:Z.accessToken,refreshToken:Z.refreshToken,expiresAt:Z.expiresAt,scopes:Z.scopes.filter((Y)=>typeof Y==="string"),orgId:Z.orgId}}catch{return null}}function BZ($,J,Z){let Q=`${$}.${process.pid}.${JZ(6).toString("hex")}.tmp`;try{let X=ZZ($);if(!X.isFile()||X.uid!==process.geteuid?.())return;let Y=JSON.parse(J);if(W9(Q,`${JSON.stringify({...Y,apiOrigin:Z},null,2)}
4
4
  `,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");XZ(Q,$)}catch{try{F9(Q)}catch{}}}function D9($=$1()){if(!T9($))return!1;return F9($),!0}var j9=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var pV=j9.filter(($)=>$!=="network:read"&&$!=="network:write");class x$ extends Error{oauthCode;constructor($,J=null){super($);this.oauthCode=J;this.name="LoginError"}}function A9(){let $=z9(48).toString("base64url"),J=KZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function HZ($,J){let Z=typeof $.error==="string"?$.error:null,Q=typeof $.error_description==="string"?$.error_description:Z?Z:J;return new x$(Q,Z)}async function NZ($,J,Z,Q){let X=await Z(`${$}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:J,signal:Q}),Y=await X.json().catch(()=>({}));if(!X.ok)throw HZ(Y,`OAuth token request failed (${X.status})`);return Y}var UZ=1e4;async function qZ($,J={}){let Z=J.fetchImpl??fetch,Q=await NZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(UZ)).catch((Y)=>{if(Y instanceof Error&&Y.name==="TimeoutError")throw new x$("Reason did not answer the login refresh in time. Check the network and retry.");throw Y});if(typeof Q.access_token!=="string"||typeof Q.refresh_token!=="string"||typeof Q.expires_in!=="number")throw new x$("Reason returned an incomplete refreshed login.");let X={...$,accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresAt:new Date(Date.now()+Q.expires_in*1000).toISOString(),scopes:typeof Q.scope==="string"?Q.scope.split(/\s+/).filter(Boolean):$.scopes};return L9(X,J.path??$1()),X}var M2=new Map;function O9($,J){if(!J)return $;if(J.aborted)return Promise.reject(J.reason);return new Promise((Z,Q)=>{let X=()=>Q(J.reason);J.addEventListener("abort",X,{once:!0}),$.then(Z,Q).finally(()=>J.removeEventListener("abort",X))})}async function k1($={}){let J=$.path??$1(),Z=I$(J);if(!Z)return null;let Q=$.apiOrigin??k0(process.env,"REASON_API_URL")?.trim();if(Q&&!z0(Z.apiOrigin,new URL(Q).origin))return null;let X=Date.parse(Z.expiresAt)<=Date.now()+60000;if(!$.forceRefresh&&!X)return Z;let Y=[J,Z.apiOrigin,Z.clientId,Z.refreshToken].join("\x00"),B=M2.get(Y);if(B)return O9(B,$.signal);let V;return V=qZ(Z,{fetchImpl:$.fetchImpl,path:J}).catch(async(K)=>{if(!(K instanceof x$)||K.oauthCode!=="invalid_grant"&&K.oauthCode!=="invalid_client")throw K;let N=I$(J),q=K.oauthCode==="invalid_client"?N?.clientId!==Z.clientId:N?.refreshToken!==Z.refreshToken;if(N&&q)return k1({fetchImpl:$.fetchImpl,path:J});return D9(J),null}).finally(()=>{if(M2.get(Y)===V)M2.delete(Y)}),M2.set(Y,V),O9(V,$.signal)}function R9($,J){return new Promise((Z)=>{let Q=VZ({input:$}),X=!1,Y=(V)=>{if(X)return;X=!0,J.removeEventListener("abort",B),Q.close(),$.pause(),Z(V)},B=()=>Y(null);J.addEventListener("abort",B,{once:!0}),Q.once("line",(V)=>Y(V)),Q.once("close",()=>Y(null))})}var MZ=G.object({label:G.string(),used_percent:G.number().min(0).max(100).nullable(),resets_at:G.string().nullable(),exhausted:G.boolean().nullable()}),TZ=G.object({groups:G.array(G.object({selectable:G.boolean().optional(),accounts:G.array(G.object({source_id:G.string().min(1),model_ids:G.array(G.string().min(1)).optional()}))}))});function _Z($){let J=TZ.safeParse($);if(!J.success)return;return J.data.groups.some((Z)=>Z.selectable!==!1&&Z.accounts.some((Q)=>Q.model_ids===void 0||Q.model_ids.length>0))}class Y0 extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor($,J,Z,Q,X,Y){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.resolutionReason=Y;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof Y0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var FZ=["minimal","low","medium","high","xhigh","max"],WZ=G.object({id:G.string().min(1),kind:G.string(),name:G.string(),custom_name:G.string().nullish(),status:G.string(),online:G.boolean(),compatible:G.boolean().optional(),compatibility_reason:G.string().nullish(),folder_lane_of:G.string().nullish(),roots:G.array(G.object({id:G.string().min(1),label:G.string()}))}),LZ=G.object({devices:G.array(WZ),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),DZ=G.object({id:G.string().min(1),name:G.string()}),jZ=G.object({items:G.array(DZ)}),zZ=G.object({id:G.string().min(1),name:G.string(),main:G.boolean(),mine:G.boolean(),session_id:G.string().nullish(),appearance:G.object({color:G.string().nullish()}).nullish().catch(null)}),OZ=G.object({items:G.array(zZ)}),AZ=G.object({skill_id:G.string().min(1),name:G.string(),description:G.string().nullish(),activation_keywords:G.array(G.string()).default([]),is_enabled:G.boolean().default(!0)}),RZ=G.object({items:G.array(AZ).default([])}),CZ=G.object({id:G.string().min(1),kind:G.string(),enabled:G.boolean(),schedule:G.object({expression:G.string().nullish(),every_seconds:G.number().nullish(),next_run_at:G.string().nullish()}).nullish(),github:G.object({event:G.string().nullish(),action:G.string().nullish(),repo:G.string().nullish()}).nullish(),last_fired_at:G.string().nullish()}),P9=G.object({id:G.string().min(1),name:G.string().nullish(),instructions:G.string().nullish(),enabled:G.boolean(),triggers:G.array(CZ).default([])}),PZ=G.object({items:G.array(P9).default([]),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),IZ=G.object({id:G.string().min(1),slug:G.string().nullish(),name:G.string(),description:G.string().nullish(),transport:G.string().nullish(),url:G.string().nullish(),enabled:G.boolean()}),xZ=G.object({items:G.array(IZ).default([])}),EZ=G.object({status:G.string(),summary:G.string().nullish(),category:G.string().nullish(),outcome:G.string().nullish(),message_count:G.number().nullish(),pr_url:G.string().nullish(),cost_usd:G.number().nullish(),generated_at:G.string().nullish()}),C9=G.object({tags:G.array(G.string()).default([])}),SZ=G.enum(["linux","macos"]),I9=G.object({id:G.string().min(1),name:G.string().min(1),platform:SZ.nullable(),workers:G.object({total:G.number().int(),online:G.number().int(),busy:G.number().int(),idle:G.number().int()}),sessions:G.object({queued:G.number().int(),running:G.number().int()})}),wZ=G.object({machines:G.array(I9)}),bZ=G.object({machine:I9}),kZ=G.object({deleted:G.literal(!0),revoked_workers:G.number().int(),revoked_tokens:G.number().int()}),yZ=G.object({token:G.object({id:G.string().min(1),machine_id:G.string().min(1),token_prefix:G.string()}),secret:G.string().startsWith("rmt_")}),x9=G.looseObject({machine_id:G.string().min(1),machine_name:G.string().min(1)}),fZ=x9.extend({organization_id:G.string().min(1)}),nV=G.object({id:G.string().min(1),name:G.string().min(1),state:G.enum(["waiting","placed"]),queue_position:G.number().int().nullable()});var rV=G.union([G.object({kind:G.literal("cloud")}),G.object({kind:G.enum(["mac","headless"]),device_id:G.string().min(1),root_id:G.string().min(1)})]);function P0($,J,Z){let Q=$.safeParse(J);if(!Q.success)throw new Y0(502,Z,"Reason returned an unexpected response.");return Q.data}var hZ=G.object({error:G.object({type:G.string(),message:G.string()})});function E9($,J,Z){let Q=hZ.safeParse(J),X=typeof J.error==="string"?J.error:Q.success?Q.data.error.type:`http_${$}`,Y=typeof J.detail==="string"?J.detail:typeof J.message==="string"?J.message:Q.success?Q.data.error.message:`Reason request failed (${$}${typeof J.error==="string"?` ${J.error}`:""})`,B=X==="github_connection_required"&&typeof J.connect_url==="string"&&/^https?:\/\//.test(J.connect_url)?` Connect it at ${J.connect_url}`:"",V=Z===null||Z.trim()===""?NaN:Number(Z);return new Y0($,X,`${Y}${B}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000:void 0,typeof J.resolution_reason==="string"?J.resolution_reason:void 0)}async function S9($){let J=await($.fetchImpl??fetch)(`${$.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${$.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify($.body),signal:AbortSignal.timeout(30000),redirect:"error"}),Z=await J.json().catch(()=>({}));if(!J.ok)throw E9(J.status,Z,J.headers.get("retry-after"));return P0(fZ,Z,"invalid_machine_ticket")}class U1{options;credentials;constructor($,J={}){this.options=J;this.credentials=$}trackEvent($,J={}){}async request($,J={},Z=!1){let Q=this.options.fetchImpl??fetch,X=await Q(`${this.credentials.apiOrigin}/v3${$}`,{method:J.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...J.raw?{"content-type":J.raw.contentType}:J.body===void 0?{}:{"content-type":"application/json"},...J.headers},body:J.raw?J.raw.bytes:J.body===void 0?void 0:JSON.stringify(J.body),signal:J.signal,redirect:"error"}),Y=await X.json().catch(()=>({}));if(X.status===401&&!Z&&J.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let B=await k1({fetchImpl:Q,path:this.options.credentialsPath,forceRefresh:!0,signal:J.signal});if(B)return this.credentials=B,this.request($,J,!0)}if(!X.ok)throw E9(X.status,Y,X.headers.get("retry-after"));return Y}createHeadlessDeviceEnrollmentTicket($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice($){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(J){if(J instanceof Y0&&(J.status===404||J.status===405||J.status===403&&J.code==="endpoint_not_available"))return null;throw J}}addDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots`,{method:"POST",body:J,signal:AbortSignal.timeout(30000)})}removeDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots/${encodeURIComponent(J)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath($,J=""){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return $===void 0?Z:`${Z}/${encodeURIComponent($)}${J}`}async listMachines(){return P0(wZ,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine($){let J=await this.request(this.machinePath(),{method:"POST",body:{name:$.name,...$.platform?{platform:$.platform}:{}}});return P0(bZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return P0(kZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return P0(yZ,J,"invalid_machine_token")}async createMachineEnrollmentTicket($,J){let Z=await this.request(this.machinePath($,"/enrollment-tickets"),{method:"POST",body:J,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return P0(x9,Z,"invalid_machine_ticket")}self($){return this.request("/self",{signal:$})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:$,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:$,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((J)=>typeof J.email==="string"?[{email:J.email,role:typeof J.role==="string"?J.role:"member"}]:[])}claimExistingCliPairing($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:$}})}connectAnthropicProvider($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:Z.retryUnauthorized,signal:Z.signal,body:{access_token:$.access,refresh_token:$.refresh,expires_at:new Date($.expires).toISOString(),...J?{account_key:J}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((J)=>{let Z=typeof J.full_name==="string"?J.full_name:typeof J.repo_full_name==="string"?J.repo_full_name:null;if(!Z)return[];return[{repo_id:typeof J.repo_id==="string"?J.repo_id:void 0,full_name:Z,provider:J.provider==="gitlab"?"gitlab":"github",default_branch:typeof J.default_branch==="string"?J.default_branch:null,private:typeof J.private==="boolean"?J.private:void 0}]})}async listProjects(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),J=jZ.safeParse($);if(!J.success)throw new Y0(502,"invalid_project_list","Reason returned an unexpected project list.");return J.data.items}async listReasons(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return P0(OZ,$,"invalid_reason_list").items}async openReasonConversation($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent($)}/conversation`,{method:"POST"});return P0(G.object({session_id:G.string().min(1)}),J,"invalid_reason_conversation").session_id}async listSkills(){try{let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return P0(RZ,$,"invalid_skill_list").items}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return[];throw $}}async listDevices(){let $=[],J=null;for(let Z=0;Z<50;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${J?`?after=${encodeURIComponent(J)}`:""}`),X=LZ.safeParse(Q);if(!X.success)throw new Y0(502,"invalid_device_list","Reason returned an unexpected machine list.");if($.push(...X.data.devices),J=X.data.has_next_page?X.data.end_cursor??null:null,!J)break}return $}async listModels(){try{let J=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((X)=>X.hidden!==!0),Z=J.filter((X)=>X.available!==!1).map(({reasoning_efforts:X,hidden:Y,available:B,...V})=>({...V,...Array.isArray(X)?{reasoning_efforts:FZ.filter((K)=>X.includes(K))}:{}})),Q=new Set(Z.map((X)=>X.detail));return{models:Z.length>1&&Q.size===1?Z.map(({detail:X,...Y})=>Y):Z,runnable:Z.length>0||J.length===0}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return{models:[],runnable:!0};throw $}}async getAgentVersion($){try{let J=await this.request("/deployment",{signal:$,retryUnauthorized:!1});return U9(J.reason_version)?J.reason_version:null}catch{return null}}async getUsageQuota(){try{let $=MZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=_Z(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return null;throw $}}async listSessions($=50,J,Z={}){let Q=new URLSearchParams({first:String(Math.min(Math.max($,1),200)),status:Z.status??"active"});if(J)Q.set("project_id",J);if(Z.origin)Q.set("origin",Z.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${Q.toString()}`)).items??[]}getSession($,J){let Z=J?.fields.length?`?fields=${encodeURIComponent(J.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${Z}`)}async prestartSession($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:$}});return J?.status==="starting"||J?.status==="ready"}async createSession($){let J=$.mode==="ephemeral"||$.workspaceOwnership==="externally-managed";if($.attachments?.length)await this.requireSessionAttachments();if(J||$.runtimeProfile){let X=await this.request("/deployment");if(J&&(!Array.isArray(X.session_modes)||!X.session_modes.includes($.mode??"standard")||!Array.isArray(X.workspace_ownerships)||!X.workspace_ownerships.includes($.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if($.runtimeProfile&&(!Array.isArray(X.experimental_runtime_profiles)||!X.experimental_runtime_profiles.includes($.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:$.prompt,...$.attachments?.length?{attachments:$.attachments}:{},...$.mode?{mode:$.mode}:{},...$.workspaceOwnership?{workspace_ownership:$.workspaceOwnership}:{},...$.target?{target:$.target}:{},...$.repo?{repo:$.repo}:{},...$.provider?{provider:$.provider}:{},...$.model?{model:$.model}:{},...$.reasoningEffort?{reasoning_effort:$.reasoningEffort}:{},...$.runtimeProfile?{experimental_runtime_profile:$.runtimeProfile}:{},...$.ref?{ref:$.ref}:{},...$.branch?{branch:$.branch}:{},...$.completionMode?{completion_mode:$.completionMode}:{},...$.env&&Object.keys($.env).length>0?{env:$.env}:{},...$.clientSessionId?{client_session_id:$.clientSessionId}:{},...$.longRunning?{long_running:{enabled:!0}}:{},...$.spendLimitRcu?{spend_limit_rcu:$.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),Q=await this.getSession(Z.session_id);if(J){let X=Q.session_policy,Y=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!X||X.version!==1||X.mode!==($.mode??"standard")||X.workspaceOwnership!==($.workspaceOwnership??"managed")||!X.components||Y.some((B)=>X.components[B]!==!0))throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if($.runtimeProfile&&Q.experimental_runtime_profile!==$.runtimeProfile)throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return Q}async getEvents($,J=-1,Z={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/events?after_seq=${J}&limit=500${Z.waitMs?`&wait_ms=${Z.waitMs}`:""}`,Z.signal?{signal:Z.signal}:{})}catch(Q){if(!(Q instanceof Y0)||Q.status!==403&&Q.status!==404)throw Q;return{session:await this.getSession($),items:[],next_seq:J}}}async getMessages($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages?first=500${J===void 0?"":`&after_seq=${J}`}`)}async getAttachments($,J){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/attachments${J?`?view=${J}`:""}`)).items??[]}catch(Z){if(Z instanceof Y0&&(Z.status===403||Z.status===404))return[];throw Z}}async requireSessionAttachments(){let $=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if($.session_attachments!==!0){let J=typeof $.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test($.reason_version)?`Agent ${$.reason_version}`:null,Z=typeof $.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test($.commit_sha)?`server ${$.commit_sha.slice(0,12)}`:null,Q=[J,Z].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${Q?` (${Q})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage($,J,Z={}){if(Z.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages`,{method:"POST",body:{message:J,...Z.attachments?.length?{attachments:Z.attachments}:{},...Z.model?{model:Z.model}:{},...Z.reasoningEffort?{reasoning_effort:Z.reasoningEffort}:{},...Z.target?{target:Z.target}:{},...Z.delivery?{delivery:Z.delivery}:{}}})}async steerQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/queued`,{method:"DELETE"})}async getConversation($){let J=[],Z=null;for(let Q=0;Q<50;Q+=1){let X=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/conversation${Z?`?after=${encodeURIComponent(Z)}`:""}`);if(J.push(...X.items??[]),!X.has_next_page||!X.end_cursor)break;Z=X.end_cursor}return J}createSharedLink($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/shared-links`,{method:"POST",body:{url:J.url,...J.label?{label:J.label}:{},...J.expiresInSeconds!==void 0?{expires_in_seconds:J.expiresInSeconds}:{}}})}sessionAction($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/${J}`,{method:"POST",body:Z})}renameSession($,J){return this.sessionAction($,"rename",{title:J||null})}moveSessionToProject($,J){return this.sessionAction($,"project",{project_id:J})}compactSession($){return this.sessionAction($,"compact")}retrySession($){return this.sessionAction($,"retry")}rewindSession($,J){return this.sessionAction($,"rewind",{message_id:J.messageId,content:J.content,request_id:J.requestId})}forkSession($,J){return this.sessionAction($,"fork",{...J.message?{message:J.message}:{},client_session_id:J.clientSessionId})}cancelSession($,J={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/cancel`,{method:"POST",body:J.mode==="hard"?{mode:"hard"}:{}})}sessionPath($,J=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${J}`}async archiveSession($){await this.request(this.sessionPath($,"/archive"),{method:"POST",body:{}})}async unarchiveSession($){await this.request(this.sessionPath($,"/unarchive"),{method:"POST",body:{}})}async deleteSession($){await this.request(this.sessionPath($),{method:"DELETE"})}async listSessionTags($){return P0(C9,await this.request(this.sessionPath($,"/tags")),"invalid_session_tags").tags}async appendSessionTags($,J){let Z=await this.request(this.sessionPath($,"/tags"),{method:"POST",body:{tags:J}});return P0(C9,Z,"invalid_session_tags").tags}async sessionInsight($,J=!1){let Z=await this.request(this.sessionPath($,J?"/insights/generate":"/insights"),J?{method:"POST",body:{}}:{});return P0(EZ,Z,"invalid_session_insight")}async listAutomations(){let $=[],J=null;for(let Z=0;Z<20;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${J?`&after=${encodeURIComponent(J)}`:""}`),X=P0(PZ,Q,"invalid_automation_list");if($.push(...X.items),J=X.has_next_page?X.end_cursor??null:null,!J)break}return $}async createScheduledAutomation($,J){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,Q=P0(P9,await this.request(Z,{method:"POST",body:{name:$.name,instructions:$.instructions,...$.repo?{repo:$.repo.full_name,provider:$.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${Z}/${encodeURIComponent(Q.id)}/triggers`,{method:"POST",body:J})}catch(X){throw await this.deleteAutomation(Q.id).catch(()=>{return}),X}return Q}async setAutomationEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"PATCH",body:{enabled:J}})}async deleteAutomation($){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"DELETE"})}async transcribe($,J){let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:$,contentType:J}});return P0(G.object({transcript:G.string()}),Z,"invalid_transcript").transcript}async listMcpServers(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return P0(xZ,$,"invalid_mcp_server_list").items}async setSkillEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent($)}`,{method:"PUT",body:{is_enabled:J}})}}function y1($,J){let Z=k0($,"REASON_API_URL")?.trim();if(!Z)return j4(J);let Q=new URL(Z);if(Q.protocol!=="https:"&&!(Q.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(Q.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return Q.origin}function mZ($){return k0($,"REASON_API_URL")?.trim()?y1($,"production"):void 0}function z4($){return k0($,"REASON_API_KEY")?.trim()||void 0}async function w9($,J){let Z=$.env??process.env,Q=z4(Z);if(!Q)return($.getCredentials??k1)({apiOrigin:mZ(Z),signal:J});let X=y1(Z,$.channel??x0({env:Z})),Y=await($.fetchImpl??fetch)(X+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+Q,accept:"application/json"},signal:J}),B=await Y.json().catch(()=>({})),V=n0(B)?B:{};if(!Y.ok){let N=typeof V.detail==="string"?V.detail:typeof V.message==="string"?V.message:"API key authentication failed ("+Y.status+")";throw new Y0(Y.status,typeof V.error==="string"?V.error:"api_key_auth_failed",N)}if(typeof V.org_id!=="string"||!V.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let K=Array.isArray(V.scopes)?V.scopes.filter((N)=>typeof N==="string"):[];return{credentialKind:"api_key",apiOrigin:X,accessToken:Q,orgId:V.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:K}}import{createHash as vZ}from"crypto";import{unlinkSync as gZ}from"fs";import{platform as uZ}from"os";import{join as dZ}from"path";var b9=G.discriminatedUnion("store",[G.strictObject({version:G.literal(1),store:G.literal("keychain")}),G.strictObject({version:G.literal(1),store:G.literal("file"),api_key:G.string().min(1).max(4096)})]),f1=($)=>dZ($,"api-key.json");function z1($){let J=vZ("sha256").update(`reason-connect-api-key
5
5
  ${$}`).digest("hex");return new e1(T2(),uZ(),J)}function O4($,J,Z=z1($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(f1($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof G0))throw Q}c(f1($),{version:1,store:"file",api_key:J})}function p0($,J=z1($)){if(!u(f1($)))return null;let Z=b9.parse(JSON.parse(s(f1($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof G0))throw Q;throw Error("worker_api_key_unreadable")}}function k9($,J=z1($)){if(!u(f1($)))return;if(b9.parse(JSON.parse(s(f1($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof G0))throw Z}gZ(f1($))}async function A4($,J){let Z;try{Z=await w9({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:y0($.proxy)})}catch(Q){if(Q instanceof Y0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as BQ,renameSync as KQ,rmSync as v1}from"fs";import{join as M0}from"path";import{createHash as lZ}from"crypto";import{realpathSync as pZ,statSync as cZ,unlinkSync as _2}from"fs";import{platform as sZ}from"os";import{join as f0}from"path";function d($){return{state:f0(g($),"device.json"),control:f0(g($),"control.json"),lock:f0(g($),"lifecycle.lock"),socket:f0(g($),"control.sock"),daemon:f0(g($),"daemon.json"),releaseCheck:f0(g($),"release-check.json"),updateDeferral:f0(g($),"update-deferral.json"),firstHeartbeat:f0(g($),"first-heartbeat.json")}}var aZ=G.object({version:G.literal(1),device_id:G.string().min(1).max(160),offer:G.unknown().optional(),enrollment_ms:G.number().int().nonnegative().max($$).optional()});function f9($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function C4($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=aZ.safeParse(JSON.parse(s(Z)));if(_2(Z),!Q.success||Q.data.device_id!==J)return null;let X=F2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=f0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?P4($):new R4(g($))}function W2($,J){T0($,!0),rZ($);let Z=J??P4($),Q=new R4(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof G0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function P4($){return new e1(T2(),sZ(),iZ($))}function iZ($){let J=I4($);return lZ("sha256").update(`reason-worker
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Qb as D}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Oh as j}from"./vm-hands-entry-lite-v6tkjqb1.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
3
- export{_ as Jb,fq as Kb,xq as Lb,c as Mb,Rq as Nb,p as Ob,Dq as Pb};
2
+ import{Tb as D}from"./vm-hands-entry-lite-n8gsyjq7.js";import{Wh as j}from"./vm-hands-entry-lite-40t7d4p5.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
3
+ export{_ as Mb,fq as Nb,xq as Ob,c as Pb,Rq as Qb,p as Rb,Dq as Sb};