@reason-machines/cli-linux-arm64-musl 0.2.327 → 0.2.329
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ara +1 -1
- package/bin/vm-hands/connect-cli-tvqpqf33.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-j47avpaq.js → custom-endpoint-device-8yqvpsd7.js} +1 -1
- package/bin/vm-hands/desktop-account-s4629ksd.js +2 -0
- package/bin/vm-hands/{device-workspace-xnyb7zp2.js → device-workspace-pacdp5tv.js} +1 -1
- package/bin/vm-hands/hands-worker-source-fprvxtp8.js +2 -0
- package/bin/vm-hands/{index-752q9pdp.js → index-wx03jedr.js} +1 -1
- package/bin/vm-hands/local-automation-p0ty82xb.js +2 -0
- package/bin/vm-hands/local-capabilities-qyw7cmjt.js +2 -0
- package/bin/vm-hands/local-desktop-users-ktbva6me.js +2 -0
- package/bin/vm-hands/local-display-mac-kbbrwa0y.js +2 -0
- package/bin/vm-hands/local-display-session-dmdw0q7k.js +2 -0
- package/bin/vm-hands/local-pty-session-bnhx083p.js +2 -0
- package/bin/vm-hands/{network-contract-bv7mj5he.js → network-contract-gb6gk8fg.js} +1 -1
- package/bin/vm-hands/package-bzy9agdv.js +2 -0
- package/bin/vm-hands/permissions-14dvc1rh.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-5zt3ys5t.js → reason-hands-protocol-469gmb0h.js} +1 -1
- package/bin/vm-hands/{status-t6acadsj.js → status-ysdt3ep8.js} +2 -2
- package/bin/vm-hands/version-tsq05aw1.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-7t05ea2h.js → vm-hands-entry-lite-0p3hac9d.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9kasrx18.js → vm-hands-entry-lite-0yghpjef.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ep1me9q3.js → vm-hands-entry-lite-18kr0x4w.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v6tkjqb1.js → vm-hands-entry-lite-40t7d4p5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cxs89wzv.js → vm-hands-entry-lite-5a0kyaxa.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-psybjyay.js → vm-hands-entry-lite-669hk342.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-6g65w75z.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-yhz6sv35.js → vm-hands-entry-lite-8afzattm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n07kxrd1.js → vm-hands-entry-lite-9y8v419y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b2wdaq7x.js → vm-hands-entry-lite-abrbc7gf.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cx4z34jh.js → vm-hands-entry-lite-asr8j2d4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mzxhng4z.js → vm-hands-entry-lite-djy0ww6h.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-14t846kp.js → vm-hands-entry-lite-dyqeaqzb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-472z7kjx.js → vm-hands-entry-lite-henbtxfe.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-22jgncrd.js → vm-hands-entry-lite-jz24p4jj.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cp1wqjs5.js → vm-hands-entry-lite-kbz9zfha.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ne8kkvk4.js → vm-hands-entry-lite-n5ec0fjy.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qvrnx0vk.js → vm-hands-entry-lite-n8gsyjq7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fq0zr7an.js → vm-hands-entry-lite-nj8bmc9y.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-7jmj7peg.js → vm-hands-entry-lite-nwcza0v8.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-xf6schkk.js → vm-hands-entry-lite-pbnx8z9g.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-q5thp2ap.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-93ejmwqn.js → vm-hands-entry-lite-rd9vsaew.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-t497ewn2.js → vm-hands-entry-lite-rnwjp0tk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-wh0qp1gf.js → vm-hands-entry-lite-sggk0bqc.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-tav4dt92.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-fbbd8e32.js → vm-hands-entry-lite-wtk1v493.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-xbe3dat0.js +181 -0
- package/bin/vm-hands/{vm-hands-entry-lite-mgx65dde.js → vm-hands-entry-lite-xjyd9xvx.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/vm-hands-executor-n2w3v0fs.js +10 -0
- package/bin/vm-hands/vm-hands-op-runner-p2q67yw9.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-jnz4rqxa.js +4 -0
- package/bin/vm-hands/worker-sandbox-bqwkytj2.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-44va9379.js +0 -2
- package/bin/vm-hands/desktop-account-emwzhj61.js +0 -2
- package/bin/vm-hands/hands-worker-source-ea5ywzxx.js +0 -2
- package/bin/vm-hands/local-automation-7cypstyv.js +0 -2
- package/bin/vm-hands/local-capabilities-nywse9m3.js +0 -2
- package/bin/vm-hands/local-desktop-users-rn753h90.js +0 -2
- package/bin/vm-hands/local-display-mac-9qqvjs82.js +0 -2
- package/bin/vm-hands/local-display-session-gtk92n5e.js +0 -2
- package/bin/vm-hands/package-xeh4dp97.js +0 -2
- package/bin/vm-hands/permissions-rgfr52fz.js +0 -2
- package/bin/vm-hands/version-rm84p9qv.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-28ta42wn.js +0 -181
- package/bin/vm-hands/vm-hands-entry-lite-rm0jf774.js +0 -5
- package/bin/vm-hands/vm-hands-executor-2pqe40rp.js +0 -10
- package/bin/vm-hands/vm-hands-op-runner-b484wkc9.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-mew62849.js +0 -4
- package/bin/vm-hands/worker-sandbox-yt11b09s.js +0 -2
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{if as Z8}from"./vm-hands-entry-lite-wh0qp1gf.js";import{rf as R0}from"./vm-hands-entry-lite-yhz6sv35.js";import{ng as Kq}from"./vm-hands-entry-lite-472z7kjx.js";import{Jg as p,Mg as V0,Pg as F0,Qg as C8,Rg as eq,Tg as g8,Wg as q0,Yg as x0}from"./vm-hands-entry-lite-22jgncrd.js";import{bh as wq}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as o,dh as C0}from"./vm-hands-entry-lite-cp1wqjs5.js";import{qh as B0}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Hh as A0}from"./vm-hands-entry-lite-14t846kp.js";import{Oh as Z}from"./vm-hands-entry-lite-v6tkjqb1.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# 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 X8=32,Zq=76;function v0(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>${X8}</x><y>${X8}</y></position>
|
|
67
|
-
<size><width>${q.width-X8*2}</width><height>${q.height-X8-Zq}</height></size>
|
|
68
|
-
</application>
|
|
69
|
-
</applications>
|
|
70
|
-
</openbox_config>`}var u0=`# 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
|
-
`,c0=`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
|
-
`,m0="/tmp/ara-dock-browser.png",r0=`[Desktop Entry]
|
|
104
|
-
Name=Chrome
|
|
105
|
-
Exec=chromium --no-sandbox %U
|
|
106
|
-
Icon=${m0}
|
|
107
|
-
Type=Application
|
|
108
|
-
Categories=Network;WebBrowser;
|
|
109
|
-
`,l0=`[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
|
-
`,d0=`[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 Gq={"wallpaper.jpg":Bq,"dock-browser.png":Rq,"dock-terminal.png":yq,"dock-files.png":Cq},s0=Sq,a0='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function Aq(q){let x=(J)=>J.replaceAll("DISPLAY=:99",`DISPLAY=${q.display}`).replaceAll("/tmp/ara-",`${q.root}/ara-`),X=new Set(q.absent??[]),Q=u0.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":v0(q.screen),"tint2/tint2rc":x(Q),"picom/picom.conf":c0,...X.has("terminal")?{}:{"ara-terminal.desktop":x(l0)},...X.has("files")?{}:{"ara-files.desktop":x(d0)},"ara-chromium.desktop":x(r0).replace("chromium --no-sandbox %U",q.browserExec),"ara-set-root-wallpaper.py":s0},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"; }',a0,'[ ! -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 Mq}from"crypto";import{once as i0}from"events";import{createWriteStream as n0,existsSync as o0,mkdirSync as t0,mkdtempSync as GX,readFileSync as T8,readdirSync as AX,renameSync as e0,realpathSync as qx,rmSync as xx,statSync as h8,writeFileSync as Xx}from"fs";import{dirname as k8,join as G}from"path";import{finished as Qx}from"stream/promises";var O8="omljlfpmafedpplnpkkahegadhkimdje",PX="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";function NX(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 c={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"}},j8={version:"154.0.8037.57",macArm64Sha256:"0e6b3439469c1b8b95b2e89c72ea29f7af00fb2c28a8878358a0b6002b6d3a64",linux64Sha256:"ceee2972074d441ea7c4ba8bcc0eaab77e7e87680f6653d73d3065851fe10302"};var Q8={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${c.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${c.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${c.obu.version}/open-browser-use-chrome-extension-${c.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},i="pnbmoicbkopffjjgfgfglopechaiemkp";var Px=["none","standard","all"],H8="22.23.3",bx={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53"},f8={"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"}},zq="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",I8={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},Jx={version:I8.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},n="com.ifuryst.open_browser_use.extension",Yq="com.reasonmachines.browser_use.extension",Vq="/tmp/reason-browser-use",p8=["tint2","picom","xterm","pcmanfm"],_q=["fonts-droid-fallback"],Eq=["pulseaudio"],Nx=["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",..._q,"galculator","chromium","ffmpeg","tmux",...Eq,...p8],Wx=new Set([...p8,..._q,...Eq]),Fq=Nx.filter((q)=>q!=="chromium"&&!Wx.has(q)),Lx=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],U8="/usr/bin/chromium",jx=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function $q(q=process.platform,x=process.arch){let X=`${q}-${x}`;return X==="linux-x64"||X==="linux-arm64"||X==="darwin-arm64"?X:null}function D8(q){return{node:{version:H8,url:`https://nodejs.org/dist/v${H8}/node-v${H8}-${q}.tar.gz`,sha256:bx[q]},open_computer_use:{version:c.ocu.version,url:Q8.ocu.url,sha256:Q8.ocu.sha256},open_browser_use:{version:c.obu.version,url:Q8.obu.url,sha256:Q8.obu.sha256},...q==="darwin-arm64"?{chrome_for_testing:{version:j8.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${j8.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:j8.macArm64Sha256}}:{}}}function Ux(q){let x={extension:i};for(let[X,Q]of Object.entries(D8(q)))x[X]=`${Q.version}@${Q.sha256}`;return x}function Oq(q){return G(q,".local","share","reason","desktop")}function Hq(q,x=wq()){let X=Oq(x),Q=(W)=>G(X,W,D8(q)[W]?.version??""),P=Q("open_computer_use"),b=Q("open_browser_use"),J=q==="darwin-arm64",L=G(x,"Library","Application Support"),y=J?G(L,"Google","Chrome","NativeMessagingHosts",`${n}.json`):G(x,".config","google-chrome","NativeMessagingHosts",`${n}.json`);return{root:X,automation:G(k8(X),"automation"),receipt:G(X,"receipt.json"),minimal:u8(x),node:G(Q("node"),"bin","node"),ocuDir:P,ocu:G(P,f8[q].ocu),ocuApp:J?G(P,"dist","Open Computer Use.app"):null,obuDir:b,obu:G(b,"cli","open-browser-use.js"),nativeHost:G(b,f8[q].obu),extensionDir:J?G(L,"OpenBrowserUse","chrome-extension","release"):G(x,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:y,nativeHostManifests:J?[y,G(L,"Google","ChromeForTesting","NativeMessagingHosts",`${n}.json`)]:[G(x,".config","chromium","NativeMessagingHosts",`${n}.json`),G(x,".config","google-chrome-for-testing","NativeMessagingHosts",`${n}.json`)],browser:J?G(Q("chrome_for_testing"),zq):U8,userChromeHost:J?G(X,"user-chrome","reason-browser-use"):null,userChromeRegistration:J?G(L,"Google","Chrome","NativeMessagingHosts",`${Yq}.json`):null,ffmpegDir:G(X,"ffmpeg"),ffmpeg:J?G(X,"ffmpeg",I8.version,"ffmpeg"):null,ffprobe:J?G(X,"ffprobe",Jx.version,"ffprobe"):null}}function fq(q){try{let x=JSON.parse(T8(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")||!Px.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 Tx(q,x,X=384){t0(k8(q),{recursive:!0,mode:448});let Q=`${q}.pending.${process.pid}`;Xx(Q,x,{mode:X}),e0(Q,q)}function m(q){try{return h8(q).isFile()}catch{return!1}}function gq(q){try{let x=h8(q);return x.isFile()&&(x.mode&73)!==0}catch{return!1}}function Dx(q){try{return T8(q,"utf8")}catch{return null}}function l(q){for(let x of jx){let X=G(x,q);try{let Q=h8(X);if(Q.isFile()&&(Q.mode&73)!==0)return X}catch{}}return null}function Bx(q){try{let x=JSON.parse(T8(G(q,"package.json"),"utf8"));return typeof x==="object"&&x!==null&&typeof x.version==="string"?x.version:null}catch{return null}}function Rx(q,x,X){let Q=D8(X)[q];if(!Q)return!1;if(q==="node")return m(G(x,"bin","node"));if(q==="chrome_for_testing")return m(G(x,zq));let P=f8[X][q==="open_computer_use"?"ocu":"obu"];return Bx(x)===Q.version&&m(G(x,P))&&(q==="open_computer_use"||m(G(x,"cli","open-browser-use.js")))}function Cx(q){return Mq("sha256").update(Buffer.from(q,"base64")).digest("hex").slice(0,32).replace(/./g,(x)=>String.fromCharCode(97+Number.parseInt(x,16)))}function v8(q){try{let x=JSON.parse(T8(q,"utf8"));return typeof x==="object"&&x!==null&&!Array.isArray(x)?x:null}catch{return null}}function yx(q){let x=v8(G(q.extensionDir,"manifest.json"));return x!==null&&x.version===c.obu.version&&typeof x.key==="string"&&Cx(x.key)===i}function Sx(q,x){let X=q?.allowed_origins;return q!==null&&q.name===n&&Array.isArray(X)&&X.length===1&&X[0]===`chrome-extension://${i}/`&&(x===void 0||q.path===x)}function Zx(q){return yx(q)&&m(q.nativeHost)&&q.nativeHostManifests.every((x)=>Sx(v8(x),q.nativeHost))}function Gx(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 ${Vq} ;;
|
|
128
|
-
mcp) shift; exec "$obu" mcp --socket-dir ${Vq} "$@" ;;
|
|
129
|
-
esac
|
|
130
|
-
exec "$obu" "$@"
|
|
131
|
-
`}function Ax(q){let x=v8(q),X=x?.allowed_origins;return x!==null&&x.name===Yq&&x.type==="stdio"&&Array.isArray(X)&&X.includes(`chrome-extension://${O8}/`)&&typeof x.path==="string"&&gq(x.path)}function Vx(q,x){if(!q.userChromeHost||!q.userChromeRegistration)return null;if(!x||Dx(q.userChromeHost)!==Gx(q.nativeHost)||!gq(q.userChromeHost))return{code:"user_chrome_browser_use_missing"};return Ax(q.userChromeRegistration)?{host:q.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var Fx={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 r(q={}){let x=q.platform===void 0?$q():q.platform;if(!x)return null;let X=Hq(x,q.home),Q=fq(X.receipt),P=Ux(x),b=Q!==null&&Q.platform===x&&JSON.stringify(Object.entries(Q.pins).sort())===JSON.stringify(Object.entries(P).sort()),J=[],L=D8(x);for(let N of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let S=L[N];if(!S)continue;let F=Rx(N,G(X.root,N,S.version),x),K=Q?.pins[N],$=F&&K===P[N]?"ready":K!==void 0&&K!==P[N]?"outdated":"missing";J.push({name:N,state:$,detail:S.version})}let y=Q?.pins.extension===i&&Zx(X);J.push({name:"browser_extension",state:y?"ready":"missing",detail:i});let W=l("Xvfb"),U=l("x11vnc"),C=l("openbox");if(x!=="darwin-arm64"){J.push(m(U8)?{name:"browser",state:"ready",detail:U8}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${U8}`});let N=W!==null&&U!==null&&C!==null;J.push({name:"display",state:N?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let S=Lx.filter((_)=>l(_)===null),F=(Q?.missing_system_packages??Fq).filter((_)=>Fq.includes(_)),K=S.length===0&&F.length===0;J.push(K?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...F,...S])].join(" ")});let $=p8.filter((_)=>l(_)===null);J.push($.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:$.join(" ")})}let R=X.ffmpeg&&m(X.ffmpeg)?X.ffmpeg:l("ffmpeg"),D=!R?null:R===X.ffmpeg?X.ffprobe:G(k8(qx(R)),"ffprobe"),Y=b&&J.every((N)=>N.state==="ready"),A=(N)=>b&&J.every((S)=>!Fx[N].includes(S.name)||S.state==="ready");return{platform:x,root:X.root,automation:X.automation,ready:Y,features:{display:A("display"),computer:A("computer"),browser:A("browser")},node:X.node,ocu:X.ocu,obu:X.obu,nativeHost:X.nativeHost,extensionDir:X.extensionDir,browser:X.browser,ffmpeg:R,ffprobe:D&&m(D)?D:null,userChrome:Vx(X,b&&["node","open_browser_use"].every((N)=>J.find((S)=>S.name===N)?.state==="ready")),pulseaudio:l("pulseaudio"),xvfb:W,x11vnc:U,openbox:C,components:J}}function hq(q){return wx(q)?Kq():[]}function wx(q){return q?.platform==="darwin-arm64"&&q.ffmpeg===G(q.root,"ffmpeg",I8.version,"ffmpeg")}async function HX(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=Mq("sha256"),J=n0(X,{mode:384});try{let y=P.body.getReader();for(let W=await y.read();!W.done;W=await y.read())if(b.update(W.value),!J.write(W.value))await i0(J,"drain")}finally{J.end(),await Qx(J)}let L=b.digest("hex");if(L!==x)throw Error(`digest mismatch for ${q}: expected ${x}, got ${L}`)}catch(P){throw xx(X,{force:!0}),P}}function u8(q){return G(Oq(q),"minimal.json")}function Kx(q=o()){return o0(u8(q))}function fX(q={}){Tx(u8(q.home??o()),`${JSON.stringify({version:1,minimal_at:(q.now?.()??new Date).toISOString()})}
|
|
132
|
-
`)}function gX(q={}){let x=q.platform===void 0?$q():q.platform;if(x===null)return null;let X=q.home??o();if(fq(Hq(x,X).receipt)!==null)return"refresh";return Kx(X)?null:"install"}import{execFile as Ix,spawn as i8}from"child_process";import{existsSync as px}from"fs";import{connect as vx}from"net";function Mx(){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 kq=Mx();import{spawn as zx}from"child_process";import{existsSync as Yx}from"fs";import{connect as _x}from"net";import{join as B8}from"path";var pq="reason_desktop",P8={sampleRate:48000,channels:2,codec:"opus"},Ex=5000,$x=107,Ox=262144,r8=(q)=>B8(q,"native"),R8=(q)=>`unix:${q}`;function c8(q,x=1000){if(!Yx(q))return Promise.resolve(!1);return new Promise((X)=>{let Q=_x({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 vq(q,x){if(!x)return null;let X=r8(q);if(Buffer.byteLength(X)>$x||/["'\\\s]/.test(X))return null;try{if(await c8(X))return X;let Q=zx(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:${B8(q,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${X}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${pq} rate=${P8.sampleRate} channels=${P8.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:B8(q,"runtime"),PULSE_STATE_PATH:B8(q,"state")}}),P=!1;Q.once("error",()=>{P=!0}),Q.once("exit",()=>{P=!0}),Q.unref();let b=Date.now()+Ex;while(Date.now()<b){if(await c8(X))return X;if(P)return await c8(X)?X:null;await new Promise((J)=>setTimeout(J,50))}if(!P)Q.kill("SIGKILL");return null}catch{return null}}function uq(){let{sampleRate:q,channels:x}=P8;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",`${pq}.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 Hx=[79,103,103,83],fx=Buffer.from("OpusHead"),gx=Buffer.from("OpusTags"),Iq=(q,x)=>q.byteLength>=x.byteLength&&x.every((X,Q)=>q[Q]===X);class m8 extends Error{constructor(q){super(q);this.name="OggProtocolError"}}class l8{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(Hx.some((R,D)=>x[Q+D]!==R)||x[Q+4]!==0)throw new m8("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),L=J.reduce((R,D)=>R+D,0),y=27+b+L;if(x.byteLength-Q<y)break;if(!P&&this.partialBytes>0)this.resetPartial();let W=P&&this.partialBytes===0,U=Q+27+b,C=U;for(let R of J){if(U+=R,R===255)continue;if(this.appendPartial(x.subarray(C,U),W),C=U,!W){let D=this.takePartial();if(D.byteLength>0&&!Iq(D,fx)&&!Iq(D,gx))X.push(D)}W=!1,this.resetPartial()}if(C<U)this.appendPartial(x.subarray(C,U),W);Q+=y}return this.buffer=x.slice(Q),X}appendPartial(q,x){if(x||q.byteLength===0)return;if(this.partialBytes+=q.byteLength,this.partialBytes>Ox)throw new m8("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 hx}from"child_process";var cq=1048576,kx=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")) <= ${p}:
|
|
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")) > ${p} or "\x00" in text:
|
|
164
|
-
sys.exit(1)
|
|
165
|
-
clipboard.set_text(text, -1)
|
|
166
|
-
send("ack")
|
|
167
|
-
if len(pending) > ${p*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 mq(q,x){let X=hx("/usr/bin/python3",["-I","-u","-c",kx],{env:{DISPLAY:q.display,XAUTHORITY:q.xauthority},stdio:["pipe","pipe","ignore"]}),Q=!1,P=!0,b="",J=0,L=[],y=setTimeout(()=>U(),5000),W=()=>{Q=!0,clearTimeout(y),L.length=0,X.kill("SIGKILL")},U=()=>{if(Q)return;W(),x.end({error:new Z("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},C=(R,D=32)=>{if(Q)return;if(!P){R();return}if(J+=D,J>cq)W(),x.end({reason:"input_backpressure"});else L.push({apply:R,bytes:D})};return X.stdout.on("data",(R)=>{if(Q)return;b+=R.toString("ascii");for(let D=b.indexOf(`
|
|
174
|
-
`);D>=0;D=b.indexOf(`
|
|
175
|
-
`)){let Y=b.slice(0,D);b=b.slice(D+1);let A;try{A=JSON.parse(Y)}catch{U();return}if(A==="ready"||A==="ack"){clearTimeout(y),P=!1;while(!P&&!Q&&L.length){let N=L.shift();J-=N.bytes,N.apply()}}else if(A&&typeof A==="object"&&"text"in A&&typeof A.text==="string"&&Buffer.byteLength(A.text)<=p)x.clipboard(A.text);else{U();return}if(Q)return}if(b.length>p*6+32)U()}),X.stdin.on("error",U),X.once("error",U),X.once("exit",U),{apply:C,write(R){if(Buffer.byteLength(R)>p||R.includes("\x00")){U();return}let D=`${JSON.stringify(R)}
|
|
176
|
-
`;C(()=>{if(P=!0,y=setTimeout(()=>U(),5000),X.stdin.write(D),X.stdin.writableLength>cq)W(),x.end({reason:"input_backpressure"})},Buffer.byteLength(D))},close:W}}var t={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}},ux="avc1.4D002A",rq={width:1920,height:1080},cx=262144,mx=0.2,rx=250,lx=1e4,dx=1024,d8=1e4,sx=500,ax=60,ix=1e4,nx=1000,lq=1048576,X0={kind:"mac_screen",sound:null},ox,dq=()=>ox??=r()?.ffmpeg??null,n8=(q,x,X)=>i8(q,x,{env:X,stdio:["ignore","pipe","ignore"]}),tx,o8=()=>tx??=hq(r()),sq=(q,x,X)=>{let[Q,...P]=[...o8(),q];return n8(Q,[...P,...x],X)},aq=()=>L0?.videotoolbox?"h264_videotoolbox":"libx264",ex=()=>Math.round(performance.now()*1000),s8=new Set,iq=!1;function Q0(q){if(s8.add(q),q.once("exit",()=>s8.delete(q)),iq)return;iq=!0,process.once("exit",()=>{for(let x of s8)try{x.kill("SIGKILL")}catch{}})}function P0(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{}},sx);q.once("exit",()=>clearTimeout(x))}function q1(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 x1(q){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(q),"-i","Capture screen 0:none"],size:null}}function X1(q){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(q),"-i","pipe:0"],size:null}}var b0=1700000;function J0(q){return Math.min(1,Math.round(Math.sqrt(b0/(q.width*q.height))*100)/100)}function Q1(q,x,X){let Q=i8(X.axe,["stream-video","--udid",X.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,J0(X.size)))],{stdio:["ignore","pipe","ignore"]}),P=i8(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 P1(q){let x=Math.min(1,rq.width/q.width,rq.height/q.height);return{width:Math.round(q.width*x),height:Math.round(q.height*x)}}function a8(q,x,X,Q="libx264"){let P=t[q],b=(C)=>Math.max(2,Math.floor(C/2)*2),J={width:b(X.width*P.scale),height:b(X.height*P.scale)},L=J.width!==x.size?.width||J.height!==x.size.height,y=Math.max(1,Math.round(P.kbps*2/P.fps)),W=["-g",String(P.fps*ax)],U=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",`${y}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",`${y}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...x.args,"-an",...L?["-vf",`scale=${J.width}:${J.height}:flags=fast_bilinear`]:[],...U,"-flush_packets","1","-f","h264","pipe:1"]}class N0{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 b1(q,x){let X=vx({path:q}),Q=Buffer.alloc(0),P="version",b=0,J=!1,L=[],y=0,W=!1,U=(N)=>{if(W)return;W=!0,X.destroy(),x.end(N)},C=()=>U({reason:"display_protocol"}),R=(N)=>{if(W)return;if(!J){if(y+=N.byteLength,y>lq)U({reason:"input_backpressure"});else L.push(N);return}if(X.write(N),X.writableLength>lq)U({reason:"input_backpressure"})},D=(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 C(),!1;return D(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 C(),!1;if(Q.byteLength<1+N)return!1;if(!Q.subarray(1,1+N).includes(1))return C(),!1;return D(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 C(),!1;if(Q.byteLength<24+N)return!1;let S={width:Q.readUInt16BE(0),height:Q.readUInt16BE(2)};if(D(24+N),S.width===0||S.height===0)return C(),!1;P="messages",J=!0;for(let F of L)X.write(F);return L=[],y=0,x.ready(S),!W}case"skip":{let N=Math.min(b,Q.byteLength);if(D(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 D(N),!0}case 2:return D(1),!0;case 3:{if(Q.byteLength<8)return!1;let N=Q.readUInt32BE(4);if(N>p/2)return D(8),P="skip",b=N,!0;if(Q.byteLength<8+N)return!1;let S=Q.subarray(8,8+N).toString("latin1");return D(8+N),x.clipboard(S),!W}default:return C(),!1}}}},A=!1;return X.once("connect",()=>{A=!0}),X.on("data",(N)=>{if(W)return;Q=Q.byteLength?Buffer.concat([Q,N]):N;while(!W&&Y());}),X.once("error",()=>{if(!A)U({error:new Z("display_unavailable","Reason could not reach this machine's desktop server.")})}),X.once("close",()=>U({reason:"display_closed"})),{pointer(N,S,F){let K=Buffer.alloc(6);K.writeUInt8(5,0),K.writeUInt8(F&255,1),K.writeUInt16BE(N,2),K.writeUInt16BE(S,4),R(K)},key(N,S){let F=Buffer.alloc(8);F.writeUInt8(4,0),F.writeUInt8(N?1:0,1),F.writeUInt32BE(S>>>0,4),R(F)},clipboard(N){if(Array.from(N).some((K)=>K.codePointAt(0)>255)){U({reason:"clipboard_unicode_unsupported"});return}let S=Buffer.from(N,"latin1"),F=Buffer.alloc(8);F.writeUInt8(6,0),F.writeUInt32BE(S.byteLength,4),R(Buffer.concat([F,S]))},close(){W=!0,X.destroy()}}}class t8{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}Q0(P);let b={child:P,splitter:new N0};this.run=b;for(let L of[...this.viewers])L.started(x);P.stdout?.on("data",(L)=>{if(this.run!==b)return;for(let y of b.splitter.push(L,Q()))for(let W of[...this.viewers])W.unit(y)});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;P0(this.run.child),this.run=null}fail(){for(let q of[...this.viewers])q.failed()}}var nq=new WeakMap;function J1(q){let x=nq.get(q);if(!x)nq.set(q,x=new t8);return x}function W0(q,x,X={}){let Q=X.micros??ex,P=new eq,b=x.request.preset,J=null,L=null,y=null,W=!1,U=null,C=!1,R=!1,D=null,Y=0,A=0,N=!1,S=null,F=null,K=0,$=null,_=[],E=0,V=[],g=new Uint32Array(d8+1),v=0,w=null,O=0,k=0,I=0,bq=0,Jq=0,b8=null,F8=0,d={frames:0,bytes:0,since:Q()},s=[],q8=0,w8,K8=!1,Y0=Q(),f={},a=()=>Math.round((Q()-Y0)/1000),Nq=X.control??kq,M8=null,z8=null,h=(T)=>{let j=C8(T);return q.send(j),bq+=j.byteLength,j.byteLength},J8=(T)=>{if(q.done)return;if(q.open)h({type:"error",code:T});q.end({reason:T})},N8=()=>Math.max(cx,t[b].kbps*1000/8*mx),W8=()=>Q()/1000,_0=()=>{while(V.length>1&&V[0].atMs<W8()-lx)V.shift();return V[0]?.rttMs??null},Wq=(T)=>{let j=_0();if(j===null||_.length===0)return!1;let B=(j+rx)*T;return W8()-_[0].sentMs>B||E>B/1000*t[b].kbps*1000/8},E0=(T)=>{if(K===0)return;let j=Math.min(T,K-1);if($!==null&&j<=$)return;$=j;let B=W8();while(_.length&&_[0].seq<=j){let M=_.shift();if(E-=M.bytes,M.seq!==j)continue;let z=Math.max(0,B-M.sentMs);while(V.length&&V.at(-1).rttMs>=z)V.pop();V.push({atMs:B,rttMs:z}),g[Math.min(d8,Math.round(z))]++,v++,w=Math.min(w??z,z)}},$0=()=>{let T=0;for(let j=0;j<=d8;j++)if(T+=g[j],T*2>=v)return j;return 0},O0=()=>q.bufferedAmount<=N8()/2&&!Wq(0.5),Lq=()=>{K8=!0,s=[],q8=0,U?.leave(Y8),U=null},jq=(T)=>{if(q.done)return;if(T.key)f.first_key_ms??=a();if(!W){if(!U||s.length===0&&!T.key)return;if(s.push(T),q8+=T.data.byteLength,q8>N8())Lq();return}if(N){k++;return}if(q.bufferedAmount>N8()||Wq(1)){N=!0,k++,S=setInterval(()=>{if(q.done||!O0())return;if(S)clearInterval(S);S=null,N=!1,E8()},X.drainPollMs??25);return}if(!C){if(!T.key){k++;return}if(h({type:"hello",width:L.width,height:L.height,fps:t[b].fps,preset:b,codec:ux}),C=!0,f.first_frame_ms??=a(),!R&&J?.sound)h({type:"audioHello",...P8}),R=!0}let j=h({type:"frame",key:T.key,seq:K,captureMicros:T.micros,data:T.data});if(_.push({seq:K,sentMs:W8(),bytes:j}),E+=j,_.length>dx)E-=_.shift().bytes;K++,O++,b8??=T.micros,F8=T.micros,d.frames++,d.bytes+=j},Y8={started(T){b=T,C=!1,s=[],q8=0},unit:jq,failed:()=>J8("encoder_failed")},_8=()=>{let T=(X.ffmpeg??dq)();if(!J||!L){J8("encoder_failed");return}let[j,B]=[J,L],M="kind"in j&&j.kind==="simulator"?j.stream:null;if(!T&&!M){J8("encoder_failed");return}if(U??="kind"in j&&j.kind==="mac_screen"?J1(X.spawn??sq):new t8,f.encoder_ms===void 0)f.encoder_ms=a(),f.encoder_shared=U.running;U.start(Y8,b,()=>{let z=t[b].fps;if(M)return M(z,t[b].kbps,b0);if("kind"in j&&j.kind==="simulator"){let u=Math.min(0.99,J0(j.size)),x8={width:j.size.width*u,height:j.size.height*u};return Q1(T,a8(b,X1(Math.min(z,30)),x8,(X.macEncoder??aq)()),j)}return"kind"in j?(X.spawn??sq)(T,a8(b,x1(z),P1(B),(X.macEncoder??aq)()),{}):(X.spawn??n8)(T,a8(b,q1(z,B,j.display),B),{DISPLAY:j.display,XAUTHORITY:j.xauthority})},Q)},L8=()=>{if(!D)return;P0(D.child),D=null},H0=()=>{let T=(X.ffmpeg??dq)();if(D||q.done||!R||!J?.sound||!T)return;let j;try{j=(X.spawn??n8)(T,uq(),{PULSE_SERVER:R8(J.sound)})}catch{return}Q0(j);let B={child:j,reader:new l8};D=B,j.stdout?.on("data",(z)=>{if(D!==B||q.done)return;let u;try{u=B.reader.push(z)}catch{L8();return}let x8=Q();for(let f0 of u){if(q.bufferedAmount>N8()){A++;continue}h({type:"audio",captureMicros:x8,data:f0}),Y++}});let M=()=>{if(D===B)L8()};j.once("exit",M),j.once("error",M)},E8=()=>{if(!U||q.done)return;I++,_8()},Uq=()=>{if(q.done||!L)return;if(!W){if(U||K8)return;_8(),w8=setTimeout(()=>{if(!W)Lq()},ix);return}if(clearTimeout(w8),f.encoder_early===void 0){if(f.encoder_early=U!==null,K8)f.hold_lapsed=!0}if(!U)_8();let T=s;s=[],q8=0;for(let j of T)jq(j);F??=setInterval(()=>{let j=Q(),B=Math.max(0.001,(j-d.since)/1e6);h({type:"stats",stats:{fps:Math.round(d.frames/B*10)/10,kbps:Math.round(d.bytes*8/1000/B),dropped:k,restarts:I,queued_bytes:q.bufferedAmount}}),d={frames:0,bytes:0,since:j}},nx)};x.desktop.then((T)=>{if(q.done)return;J=T;let j={ready(B){L=B,f.desktop_ms??=a(),Uq()},clipboard(B){if(q.open&&Buffer.byteLength(B)<=p)h({type:"serverClipboard",text:B})},end(B){if("reason"in B&&q.open)h({type:"error",code:B.reason});q.end(B)}};if("kind"in T&&T.kind==="simulator")y=T.input,j.ready(T.points);else if("kind"in T)y=(X.macInput??((B)=>x0(B,o8())))(j);else{let B=(X.linuxClipboard??mq)(T,j),M=b1(T.rfbSocket,{...j,clipboard:(z)=>{if(!B)j.clipboard(z)}});y=B?{pointer:(z,u,x8)=>B.apply(()=>M.pointer(z,u,x8)),key:(z,u)=>B.apply(()=>M.key(z,u)),clipboard:(z)=>B.write(z),close(){B.close(),M.close()}}:M}Tq()},(T)=>q.end({error:T}));function Tq(){if(z8||!x.viewerSameNetwork||!W||q.done||!J||!("kind"in J)||J.kind!=="mac_screen")return;z8=(X.macWindows??q0)((T)=>{if(q.open)h({type:"windows",bounds:T})})}let Dq={viewer:x.viewer??null,notify(T){if(q.open)h({type:"control",control:T})}},$8=(T)=>{if(!y)return;if(!J||!("kind"in J)||J.kind!=="simulator")Nq.claim(Dq);T(y)};return{opened(){f.relay_ms??=a()},received(T){Jq+=T.byteLength;let j;try{j=P.push(T)}catch{J8("viewer_protocol");return}for(let B of j){if(q.done)return;switch(B.type){case"ping":h({type:"pong",token:B.token});break;case"pointer":$8((M)=>M.pointer(B.x,B.y,B.buttons));break;case"key":$8((M)=>M.key(B.down,B.keysym));break;case"clientClipboard":$8((M)=>M.clipboard(B.text));break;case"config":if(B.preset!==b)b=B.preset,E8();break;case"keyframeRequest":if(C&&!N)E8();break;case"ack":E0(B.seq);break;case"audioEnable":if(B.on)H0();else L8();break;default:break}}if(!W&&!q.done){if(W=!0,f.viewer_ms=a(),x.viewer)M8=Nq.join(Dq);Uq(),Tq()}},close(){if(M8?.(),M8=null,z8?.close(),S)clearInterval(S);if(F)clearInterval(F);clearTimeout(w8),U?.leave(Y8),L8(),y?.close()},summary:()=>({output_bytes:bq,input_bytes:Jq,video:{preset:b,frames:O,dropped:k,restarts:I,avg_fps:b8!==null&&F8>b8?Math.round((O-1)/((F8-b8)/1e6)*10)/10:0,min_rtt_ms:Math.round(w??0),p50_rtt_ms:v?$0():0,audio_packets:Y,audio_dropped:A,connect:f}})}}var oq=null,L0=null,N1=null;function W1(){let q=r();return q?.features.display?q.ffmpeg:null}function j0(q){return oq??=new Promise((x)=>{Ix(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(L0={x264:P("libx264"),videotoolbox:P("h264_videotoolbox")})})}),oq}var tq=null;function Q9(){return tq??=(async()=>{let q=[r()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((X)=>Boolean(X&&px(X)));if(!q)return null;let x=await j0(q);return x.videotoolbox||x.x264?q:null})(),tq}function U0(q=process.platform,x={}){if(q!=="linux"&&q!=="darwin")return Promise.resolve(!1);let X=(x.ffmpeg??W1)();if(!X)return Promise.resolve(!1);let Q=(x.encoders??j0)(X);if(q==="linux")return Q.then((b)=>b.x264);let P=x.macScreen?x.macScreen():N1??=g8(o8());return Promise.all([Q,P]).then(([b,J])=>(b.x264||b.videotoolbox)&&J?.screen===!0&&J.accessibility)}import{existsSync as e8,realpathSync as y0,statSync as L1}from"fs";import{platform as j1}from"os";import{isAbsolute as S0,sep as U1}from"path";var T1=43200000,T0=R0,D1=4,B1=/^[A-Za-z0-9._:-]{1,160}$/,R1=1000;function Z0(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}function S8(q,x){if(typeof q!=="number"||!Number.isFinite(q)||q<=0)return x;return Math.min(R1,Math.max(1,Math.floor(q)))}function C1(q,x=Date.now()){let X=["relay_url","session_id","expires_at"],Q=new Set([...X,"cols","rows","cwd","workspace"]);if(!Z0(q)||X.some((U)=>!(U in q))||Object.keys(q).some((U)=>!Q.has(U)))throw new Z("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:P,session_id:b,expires_at:J}=q;if(typeof P!=="string")throw new Z("invalid_pty_request","Reason terminal relay URL is missing.");let L;try{L=new URL(P)}catch{throw new Z("invalid_pty_request","Reason terminal relay URL is invalid.")}if(L.protocol!=="wss:"&&L.protocol!=="ws:"||L.username||L.password)throw new Z("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof b!=="string"||!B1.test(b))throw new Z("invalid_pty_request","Reason terminal session identity is invalid.");let y=typeof J==="string"?Date.parse(J):Number.NaN;if(!Number.isFinite(y)||y<=x)throw new Z("invalid_pty_request","Reason terminal session has already expired.");if(q.cwd!==void 0&&typeof q.cwd!=="string")throw new Z("invalid_pty_request","Reason terminal working directory is invalid.");let W=q.workspace===void 0?void 0:B0(q.workspace);if(W===null||W&&q.cwd!==void 0)throw new Z("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:P,session_id:b,expires_at:new Date(Math.min(y,x+T1)).toISOString(),cols:S8(q.cols,80),rows:S8(q.rows,24),...q.cwd===void 0?{}:{cwd:q.cwd},...W?{workspace:W}:{}}}function y1(q,x){return x===q||x.startsWith(q+U1)}function D0(q,x){if(x===void 0)return q;if(!S0(x))throw new Z("pty_cwd_invalid","Reason terminal working directory must be absolute.");let X;try{X=y0(x)}catch{throw new Z("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!y1(q,X))throw new Z("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!L1(X).isDirectory())throw new Z("pty_cwd_invalid","Reason terminal working directory is not a directory.");return X}function S1(q=process.env){let x=q.SHELL;if(x&&S0(x)&&e8(x))return x;for(let X of j1()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(e8(X))return X;return"/bin/sh"}function Z1(){let q=globalThis.Bun;if(!q)throw new Z("pty_unavailable","Reason terminals require the Bun runtime.");return q.spawn}function D9(){return typeof globalThis.Bun<"u"}var G1=(q)=>{let x=Z1()({cmd:[q.shell,"-i","-l"],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(Q,P)=>{q.onData(P)}}}),X=x.terminal;if(!X){try{x.kill()}catch{}throw new Z("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(Q)=>X.write(Q),resize:(Q,P)=>X.resize(Q,P),kill:()=>{try{x.kill()}catch{}},exited:x.exited.then((Q)=>typeof Q==="number"?Q:null,()=>null)}},qq=(q,x)=>{return x===void 0?new WebSocket(q):new WebSocket(q,{proxy:x})},y8=new Set;function A1(q){if(y8.size>=D1||y8.has(q))return null;y8.add(q);let x=!1;return()=>{if(x)return;x=!0,y8.delete(q)}}async function B9(q,x={}){let X=x.now??Date.now,Q=C1(q.payload,X()),P=A1(q.operationId);if(!P)throw new Z("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let b=X(),J,L,y;try{let W=Q.workspace?C0(q.root,Q.workspace):void 0;J=W?D0(e8(W.boundary)?y0(W.boundary):W.boundary,W.path):D0(q.root,Q.cwd),L=x.environment??process.env,y=x.shellPath??S1(L)}catch(W){throw P(),W}return await new Promise((W,U)=>{let C=null,R=null,D=!1,Y=!1,A=!1,N=null,S=0,F=0,K=[],$=0,_=null,E=(w)=>{if(A)return;if(A=!0,_)clearTimeout(_);q.signal.removeEventListener("abort",V);try{C?.kill()}catch{}try{R?.close(1000,"pty_session_over")}catch{}if(P(),w.kind==="rejected"){U(w.error);return}let O={reason:w.reason,exit_code:N,output_bytes:S,input_bytes:F,duration_ms:Math.max(0,X()-b)};q.emitEvent("pty.stopped",{...O}).catch(()=>{return}),W({...O})},V=()=>{let w=q.signal.reason;E({kind:"rejected",error:w instanceof Z?w:new Z("cancelled","Reason closed the terminal session.")})};if(q.signal.aborted){V();return}q.signal.addEventListener("abort",V,{once:!0}),_=setTimeout(()=>E({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(Q.expires_at)-X()));let g=(w)=>{if(S+=w.byteLength,!D||!R){if(K.push(w),$+=w.byteLength,$>T0)E({kind:"resolved",reason:"output_backpressure"});return}try{R.send(w)}catch{E({kind:"resolved",reason:"relay_closed"});return}if(R.bufferedAmount>T0)E({kind:"resolved",reason:"output_backpressure"})};try{C=(x.spawnPty??G1)({shell:y,args:["-i","-l"],cwd:J,cols:Q.cols,rows:Q.rows,environment:L,onData:(w)=>{if(!A)g(w)}})}catch(w){E({kind:"rejected",error:w instanceof Z?w:new Z("pty_spawn_failed","Reason could not start the terminal shell.")});return}C.exited.then((w)=>{if(A)return;if(N=w,D&&R)try{R.send(JSON.stringify({t:"exit",code:w}))}catch{}E({kind:"resolved",reason:"shell_exited"})});let v=(x.loadProxy??Z8)()?.url;try{R=(x.connect??qq)(Q.relay_url,v)}catch{E({kind:"rejected",error:new Z("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}R.binaryType="arraybuffer",R.onopen=()=>{if(A||!R)return;D=!0;try{R.send(JSON.stringify({t:"open",cols:Q.cols,rows:Q.rows}));for(let w of K.splice(0))R.send(w);$=0}catch{E({kind:"resolved",reason:"relay_closed"});return}Y=!0,q.emitEvent("pty.ready",{session_id:Q.session_id,cols:Q.cols,rows:Q.rows}).catch(()=>{return})},R.onmessage=(w)=>{if(A||!C)return;let O=w.data;if(typeof O==="string"){let I;try{I=JSON.parse(O)}catch{return}if(!Z0(I))return;if(I.t==="resize"){try{C.resize(S8(I.cols,Q.cols),S8(I.rows,Q.rows))}catch{}return}if(I.t==="close")E({kind:"resolved",reason:"client_closed"});return}let k=O instanceof ArrayBuffer?new Uint8Array(O):ArrayBuffer.isView(O)?new Uint8Array(O.buffer,O.byteOffset,O.byteLength):null;if(!k||k.byteLength===0)return;F+=k.byteLength;try{C.write(k)}catch{}},R.onclose=()=>{if(A)return;if(!Y){E({kind:"rejected",error:new Z("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}E({kind:"resolved",reason:"relay_closed"})},R.onerror=()=>{if(A||Y)return;E({kind:"rejected",error:new Z("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}var E1=43200000,G8=":99",$1=60000,V8=15000,Qq={width:1280,height:800},O1=/^[A-Za-z0-9._:-]{1,160}$/;function H1(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}var f1=["video","viewer","viewer_same_network","viewer_network"];function g1(q,x=Date.now()){let X=["relay_url","session_id","expires_at"];if(!H1(q)||X.some((L)=>!(L in q))||Object.keys(q).some((L)=>!X.includes(L)&&!f1.includes(L)))throw new Z("invalid_display_request","Reason desktop request is malformed.");let Q="video"in q?F0(q.video):void 0,P="viewer"in q?V0(q.viewer):null;if(Q===null)throw new Z("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 Z("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof q.session_id!=="string"||!O1.test(q.session_id))throw new Z("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 Z("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+E1)).toISOString(),...Q?{video:Q}:{},...P?{viewer:P}:{},...Q&&q.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function h1(q=process.platform){return(q==="linux"||q==="darwin")&&r()?.features.display===!0}async function $9(){if(process.platform!=="darwin")return h1();return await U0()}function A8(q){M1(q,{recursive:!0,mode:448});let x=K1(q);if(!x.isDirectory()||x.isSymbolicLink()||process.getuid&&x.uid!==process.getuid())throw new Z("display_unavailable","Reason desktop state directory is not private.");w1(q,448)}function k1(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 e(q,x,X=2000){return new Promise((Q)=>{let P=_1(q),b="",J=(L)=>{P.destroy(),Q(L)};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",(L)=>{if(b+=L.toString("latin1"),b.length>=4)J(b.startsWith("RFB "))})})}async function M0(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 Pq(q,x,X){return new Promise((Q)=>{let P=w0(q,x,{detached:!0,stdio:"ignore",env:X});P.once("error",()=>Q(-1)),P.once("exit",(b)=>Q(b)),P.unref(),setTimeout(()=>Q(null),V8).unref()})}var xq=null;function I1(q=o()){return xq??=p1(q).finally(()=>{xq=null}),xq}async function p1(q){let x=r({home:q});if(!x?.xvfb||!x.x11vnc||!x.openbox)throw new Z("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");A0({root:x.root,automation:x.automation,extensionDir:x.extensionDir});let X=H(x.root,"display");A8(X);let Q=await u1(q,X,x.x11vnc);if(Q)return Q;let P={display:G8,xauthority:H(X,"Xauthority"),rfbSocket:H(X,"rfb.sock")},b=H(X,"pulse"),J=(async()=>{try{A8(b)}catch{return null}return await vq(b,x.pulseaudio)})(),L=H(X,"home");A8(L);let y={HOME:L,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:P.display,XAUTHORITY:P.xauthority};if(x.pulseaudio)y.PULSE_SERVER=R8(r8(b));let W=async()=>({...P,sound:await J});if(await e({path:P.rfbSocket},!0))return await W();if(!K0(P.xauthority))Xq(P.xauthority,k1(G8.slice(1),F1(16)),{mode:384,flag:"wx"});let U=c1(H(X,"theme"),P.display),C={path:`/tmp/.X11-unix/X${G8.slice(1)}`};if(!await e(C,!1)){if(Pq(x.xvfb,[P.display,"-screen","0",`${Qq.width}x${Qq.height}x24`,"-nolisten","tcp","-auth",P.xauthority],y),!await M0(()=>e(C,!1),V8))throw new Z("display_unavailable","Reason could not start the virtual display.");Pq(x.openbox,["--config-file",U.openboxConfig],y)}if(await m1(U,y),!await z0(x.x11vnc,P,X,"x11vnc.log",y))throw new Z("display_unavailable","Reason could not start the desktop server.");return await W()}async function z0(q,x,X,Q,P){if(await e({path:x.rfbSocket},!0))return!0;Y1(x.rfbSocket,{force:!0});let b=await Pq(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",H(X,Q)],P);if(b!==null&&b!==0)return!1;return await M0(()=>e({path:x.rfbSocket},!0),V8)}async function v1(){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)=>V1("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 G0=new Set;async function u1(q,x,X){let Q=await v1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===G8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??H(q,".Xauthority"),rfbSocket:H(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(G0.has(J)||!await e({path:`/tmp/.X11-unix/X${P}`},!1))return null;let L={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await z0(X,b,x,`x11vnc-${P}.log`,L))return{...b,sound:null};return G0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
|
|
179
|
-
`),null}function c1(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])=>!K0(`/usr/bin/${b}`)).map(([b])=>b),P=Aq({root:q,display:x,screen:Qq,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])A8(H(q,b));for(let[b,J]of Object.entries(P.files))Xq(H(q,b),J,{mode:384});for(let[b,J]of Object.entries(Gq))Xq(H(q,`ara-${b}`),z1(J),{mode:384});return{root:q,openboxConfig:H(q,"openbox","rc.xml"),start:P.start}}async function m1(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=w0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},V8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function O9(q,x={}){let X=x.now??Date.now,Q=g1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new Z("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 Z("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>X0:I1))();return await r1(q.signal,Q,x,X,(L)=>W0(L,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(L)=>C8({type:"error",code:L}))}function r1(q,x,X,Q,P,b){let J=Q();return new Promise((L,y)=>{let W=null,U=!1,C=!1,R,D,Y,A=!1,N=null,S=(V)=>{if(C)return;if(N)V=N;C=!0,clearTimeout(R),clearTimeout(D),q.removeEventListener("abort",K),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in V){y(V.error);return}L({reason:V.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},F=()=>S({error:new Z("display_relay_unavailable","Reason could not reach the desktop relay.")}),K=()=>{let V=q.reason;S({error:V instanceof Z?V:new Z("cancelled","Reason closed the desktop session.")})},$=()=>{if(!N||!W)return;let V=N.error;try{W.send(b(V instanceof Z?V.code:"display_unavailable"))}catch{}S(N)};if(Y=P({get done(){return C||N!==null},get open(){return U&&!C&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(V){if(C||N||!U||!W)return;try{W.send(V)}catch{S({reason:"relay_closed"})}},end:(V)=>{if(C||N)return;if(!("error"in V)){S(V);return}if(N=V,A&&U)$()}}),C){Y.close();return}if(q.aborted){K();return}q.addEventListener("abort",K,{once:!0}),R=setTimeout(()=>S({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),D=setTimeout(()=>S({reason:"viewer_absent"}),X.viewerWaitMs??$1);try{W=(X.connect??qq)(x.relay_url,(X.loadProxy??Z8)()?.url)}catch{F();return}W.binaryType="arraybuffer",W.onopen=()=>{if(C||!W)return;U=!0,Y?.opened()},W.onmessage=(V)=>{if(C)return;let g=V.data,v=g instanceof ArrayBuffer?new Uint8Array(g):ArrayBuffer.isView(g)?new Uint8Array(g.buffer,g.byteOffset,g.byteLength):null;if(!v||v.byteLength===0)return;if(clearTimeout(D),A=!0,N){$();return}Y?.received(v)},W.onclose=()=>{if(C)return;if(!U){F();return}S({reason:"relay_closed"})},W.onerror=()=>{if(C||U)return;F()}})}
|
|
181
|
-
export{T1 as fe,T0 as ge,D1 as he,D9 as ie,B9 as je,O8 as ke,PX as le,NX as me,i as ne,R8 as oe,Q9 as pe,U0 as qe,Vq as re,Hq as se,r as te,HX as ue,fX as ve,gX as we,E1 as xe,G8 as ye,g1 as ze,h1 as Ae,$9 as Be,A8 as Ce,I1 as De,O9 as Ee};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Pd as UJ,ed as jJ,md as OJ}from"./vm-hands-entry-lite-t497ewn2.js";import{createHash as V,randomBytes as $J}from"crypto";import{closeSync as CJ,fsyncSync as LJ,mkdirSync as yJ,openSync as qJ,renameSync as IJ,rmSync as RJ,statSync as NJ,writeSync as DJ,constants as H}from"fs";import{join as d}from"path";var fJ=1;var r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function GJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function BJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function AJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&r.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:GJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var S=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),v=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function y(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(y).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${y(J[Z])}`).join(",")}}`}async function KZ(J){let Z=await crypto.subtle.importKey("pkcs8",v(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=v(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),U=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=V("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:U,fingerprint:L}}var mJ=4;class bJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;verifiedSinceRun=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!r.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let U=this.bound.get(J);if(!U)return!1;if(U.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:fJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:S(this.keys.signingSpki),env_public_key:S(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:S($J(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(y(Z)));return{...Z,device_signature:S(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=S($J(32)),U=UJ({method:"GET",pathAndQuery:jJ,timestamp:z,nonce:K,challenge:J,bodySha256:V("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(U)));return{t:"hello",timestamp:z,nonce:K,signature:S(cJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!r.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(V("sha256").update(y({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=mJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload(),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.verifiedSinceRun=!1,this.servedRun=!0,K=!0;let{launchId:U,applied:L,readyData:P}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),D=null;if(J.env){let O=J.claim?.owner??{},g=BJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof O.device_id==="string"?O.device_id:"",rootId:J.claim?.root_id??""});D=this.hooks.installEnvironment(J.bind_id,g),z=this.writeJobEnvRootOnly(J.bind_id,g)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:D!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:D,layout:E,...P?{ready_data:P}:{},policy_digest:V("sha256").update(y({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(U){if(z)zJ(z);if(K){let P=[...this.bound.keys()];await this.hooks.killAndVerifyPayload(P.length?{bindId:J.bind_id,keep:P}:void 0).then(()=>{if(!P.length)this.verifiedSinceRun=!0,this.unverified.clear()},()=>{this.unverified.add(J.bind_id),this.verifiedSinceRun=!1})}this.binding.delete(J.bind_id);let L=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof W?U:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!r.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=BJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),U=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)zJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${U}`,K),{snapshot_id:J.snapshotId,installed_revision:U,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killAndVerifyPayload(),this.verifiedSinceRun=!0}catch{this.servedRun=!0,this.verifiedSinceRun=!1}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:V("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((K)=>K!==J);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:void 0)}catch(K){throw this.unverified.add(J),this.verifiedSinceRun=!1,K}if(!z.length)this.verifiedSinceRun=!0,this.unverified.clear();if(Z?.envDirectory)zJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",v(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),U=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:v(J.iv),additionalData:new TextEncoder().encode(Z)},U,v(J.ct)).catch(z),P=JSON.parse(new TextDecoder().decode(L));if(!P||typeof P!=="object"||Array.isArray(P))throw new W("vm_hands_env_invalid","env not an object");return P}writeJobEnvRootOnly(J,Z){let z=d(this.options.envRoot,`bind-${J}`);yJ(z,{mode:448});let K=NJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let U=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(U).filter(([D,O])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(D)&&typeof O==="string").map(([D,O])=>`export ${D}='${String(O).replaceAll("'","'\\''")}'`).join(`
|
|
3
|
-
`)+`
|
|
4
|
-
`,P=d(z,`.job.env.${$J(8).toString("hex")}`),E=qJ(P,H.O_WRONLY|H.O_CREAT|H.O_EXCL|H.O_NOFOLLOW,384);try{DJ(E,L),LJ(E)}finally{CJ(E)}return IJ(P,d(z,"job.env")),z}}function zJ(J){try{let Z=d(J,"job.env"),z=NJ(Z).size,K=qJ(Z,H.O_WRONLY|H.O_NOFOLLOW);try{DJ(K,Buffer.alloc(z)),LJ(K)}finally{CJ(K)}}catch{}RJ(J,{recursive:!0,force:!0})}function cJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(U)=>{let L=0;while(L<U.length-1&&U[L]===0)L++;let P=U.subarray(L),E=P[0]&128?Uint8Array.of(0,...P):P;return Uint8Array.of(2,E.length,...E)},z=Z(J.subarray(0,32)),K=Z(J.subarray(32));return Uint8Array.of(48,z.length+K.length,...z,...K)}import{randomUUID as pJ}from"crypto";var lJ="/app/local-runtime/session?register=vm_hands_v1",uJ="/app/local-runtime",xJ=25000,oJ=20000,dJ=1e4,rJ=5000,iJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),KJ=75000,sJ=2000,aJ=1e4,i=20000;function MJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class h extends Error{}var nJ=64;async function _J(J,Z){let z=[...J.modelOps.get(Z)??[]];for(let K of z)K.abort.abort();await Promise.race([Promise.all(z.map((K)=>K.settled)),new Promise((K)=>setTimeout(K,rJ))])}async function I(J,Z,z){return await _J(J,z),Z.unbind(z)}function s(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var EJ=15000,tJ=1e4,eJ=1000;async function PZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map},K=J.log??(()=>{}),U=async(L)=>{for(let[P,E]of[...z.turns]){z.turns.delete(P),J.onTurn?.(P,null),s(E);let D=await I(z,J.agent,P).catch(()=>null);if(D)z.receipts.push({turn:E,failure:"vm_hands_bind_lost",unbound:D});K("vm_hands.bound_dropped",{reason:L})}};try{for(let L=0;!J.signal.aborted;L++){let P=await JZ(J,z).catch((D)=>{if(D instanceof W&&z.deviceId===null&&D.code==="vm_hands_no_session"&&Date.now()-Z<aJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(D instanceof W&&z.deviceId===null)throw D;return{closeCode:0,closeReason:D instanceof Error?D.message:String(D)}});if(K("vm_hands.session_closed",{close_code:P.closeCode,reason:P.closeReason.slice(0,120),registered:z.deviceId!==null}),P.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=KJ)await U("reconnect_deadline");if(z.served)z.served=!1,L=0;let E=P.closeReason==="drain_reconnect"?0:P.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(L,5),2000):z.turns.size?Math.min(250*2**Math.min(L,5),5000,Math.max(0,z.lostAt+KJ-Date.now())):Math.min(500*2**L,30000);if(await new Promise((D)=>setTimeout(D,E)),z.turns.size&&Date.now()-z.lostAt>=KJ)await U("reconnect_deadline")}}finally{await U("session_ended")}}async function JZ(J,Z){let z=Z.deviceId,K=J.log??(()=>{}),U=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:lJ,L=`${J.apiOrigin.replace(/^http/,"ws")}${U}`,P=new WebSocket(L),E=0,D="",O=new Map,g=[],R=null,TJ=new Promise(($)=>{P.onclose=(Y)=>{E=Y.code,D=Y.reason;for(let G of O.values())G.reject(new h(`session closed ${Y.code}`));for(let G of Z.attestWaiters.splice(0))G(!1);O.clear(),$()}});P.onmessage=($)=>{let Y;try{Y=JSON.parse(String($.data))}catch{P.close(4400);return}if(Y.t==="res"){let G=Y;O.get(G.id)?.resolve({status:G.status,body:G.body}),O.delete(G.id);return}if(Y.t==="reconnect"){let G=Math.max(0,Math.min(Number(Y.after_ms)||0,eJ));K("vm_hands.drain_reconnect",{after_ms:G}),setTimeout(()=>{try{P.close(4001,"drain_reconnect")}catch{}},G).unref?.();return}if(!R?.(Y))g.push(Y)};let f=($,Y)=>new Promise((G,X)=>{let j=g.findIndex((C)=>$.includes(C.t));if(j>=0){G(g.splice(j,1)[0]);return}let q=setTimeout(()=>{R=null,X(new W("vm_hands_no_register",`no ${$.join("/")} in ${Y} ms`))},Y);R=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(q),R=null,G(C),!0}}),m=($)=>P.send(JSON.stringify($)),w=($,Y)=>new Promise((G,X)=>{if(P.readyState!==WebSocket.OPEN){X(new h("session closed"));return}let j=pJ(),q=typeof Y.wait_ms==="number"?Y.wait_ms:0,C=setTimeout(()=>{if(!O.delete(j))return;X(new h(`no answer to ${$.split("/").pop()} in ${q+EJ} ms`)),P.close(4000,"request_timeout")},q+EJ);O.set(j,{reject:(Q)=>{clearTimeout(C),X(Q)},resolve:({status:Q,body:F})=>{clearTimeout(C);let B=null;try{B=F?JSON.parse(F):null}catch{}G({status:Q,json:B})}}),m({t:"req",id:j,path:`${uJ}${$}`,body:JSON.stringify(Y)})}),YJ=()=>P.close(1001,"stopping");J.signal.addEventListener("abort",YJ,{once:!0});let a,b=new Map,c=new Map,n=!1,t=new Set,e=new Set,JJ=Promise.resolve(),p=!1;try{await new Promise((Q,F)=>{let B=setTimeout(()=>F(Error("session open timeout")),tJ);P.onopen=()=>{clearTimeout(B),K("vm_hands.ws_open",{}),Q()},P.onerror=()=>{clearTimeout(B),F(Error("session socket error"))}});let $=await f(["challenge"],5000);K("vm_hands.challenge",{});let Y=[],G=null,X;if(z){m(await J.agent.helloFrame($.challenge,Z.connection));let Q=await f(["ready"],1e4);if(typeof Q.vm_hands_connection==="string")Z.connection=Q.vm_hands_connection;if(X={device_id:z,...Q.cadence?{cadence:Q.cadence}:{}},typeof Q.vm_hands_probe_script==="string"){if(G=Q.vm_hands_probe_script,p=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.reconnected",{device_id:z});let F=Array.isArray(Q.vm_hands_binds)?Q.vm_hands_binds:Q.vm_hands_bind?[Q.vm_hands_bind]:[];for(let[B,N]of[...Z.turns]){if(F.some((A)=>A&&A.operation_id===N.claim.operation_id&&A.attempt_id===N.claim.attempt_id)){Y.push(N),K("vm_hands.bound_resumed",{operation_id:N.claim.operation_id});continue}Z.turns.delete(B),J.onTurn?.(B,null),s(N);let M=await I(Z,J.agent,B).catch(()=>null);if(M)Z.receipts.push({turn:N,failure:"vm_hands_bind_lost",unbound:M});K("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{m(await J.agent.registerFrame($.challenge)),K("vm_hands.register_sent",{});let Q=await f(["registered","register_refused"],1e4);if(Q.t==="register_refused")throw new W(Q.code,"register refused");J.agent.registered();let F=Q;if(X=F,Z.deviceId=F.device_id,typeof F.vm_hands_connection==="string")Z.connection=F.vm_hands_connection;if(typeof F.vm_hands_probe_script==="string"){if(G=F.vm_hands_probe_script,p=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.registered",{device_id:X.device_id})}let j=async()=>{let Q=await w("/heartbeat",await J.heartbeat());if(Q.status>=300)throw Error(`heartbeat ${Q.status}`)};await j();let q=X.cadence?.presence_interval_ms??30000;if(a=setInterval(()=>{j().catch(()=>P.close())},q),G&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)wJ(G,$.challenge);let C=(Q,F)=>{c.set(Q,F().catch(async(B)=>{if(await QJ(B,Q),B instanceof h)P.close();else await ZJ().catch(()=>{return})}).finally(()=>{c.delete(Q)}))};try{await ZJ();for(let Q of Y)Q.flush=()=>XJ(Q),Q.flush(),C(Q.claim.attempt_id,()=>FJ(Q));while(!J.signal.aborted&&P.readyState===WebSocket.OPEN){let Q=await w("/operations/claim",{wait_ms:Math.min(X.cadence?.claim_wait_ms??xJ,xJ)});if(Q.status===204||!Q.json)continue;if(Q.status>=300)throw Error(`claim ${Q.status}`);let F=Q.json;if(F.capability==="hands.connect"){if(c.has(F.attempt_id)){_({claim:F,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}C(F.attempt_id,()=>kJ(F))}else gJ(F).catch(()=>{return})}}catch(Q){await QJ(Q,null)}}finally{if(a)clearInterval(a);J.signal.removeEventListener("abort",YJ);for(let $ of Z.turns.values())$.flush=null;P.close(),await TJ,await Promise.all([...c.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let Y=await I(Z,J.agent,$).catch(()=>null),G=b.get($);if(Y&&G)Z.receipts.push({turn:{...G,eventSeq:G.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Y});K("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of t)$.abort()}return{closeCode:E,closeReason:D};async function QJ($,Y){if($ instanceof h){if(!n&&Z.turns.size)Z.lostAt=Date.now();n=!0}else{let G=Y!==null?[Y]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(Y===null)n=!0;for(let X of G){let j=Z.turns.get(X);if(Z.turns.delete(X),j)s(j),J.onTurn?.(X,null);if(J.agent.liveBindIds.includes(X)){let q=await I(Z,J.agent,X).catch(()=>null),C=b.get(X)??j;if(q&&C)Z.receipts.push({turn:{...C,eventSeq:C.eventSeq+1},failure:"vm_hands_bind_lost",unbound:q})}}}K("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turns.size})}function _($){let Y=$.claim,G={attempt_id:Y.attempt_id,attempt_token:Y.attempt_token},X=encodeURIComponent(Y.operation_id);return{fence:G,op:X,complete:(q,C={})=>w(`/operations/${X}/complete`,{...G,status:q,...C}),emit:(q,C)=>{let Q=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>j(q,C));return $.chain=Q,Q}};async function j(q,C){let Q=$.eventSeq,F=(A)=>w(`/operations/${X}/events`,{...G,event_seq_start:A,events:[{kind:q,payload:{sequence:A,capability:String(Y.capability??"hands.connect"),data:C}}]}),B=Q,N=await F(B),M=N.status===409?N.json?.expected_event_seq:void 0;if(typeof M==="number"&&M===Q+1)N={status:200,json:{duplicate:!0}};else if(typeof M==="number"&&M>=0&&M!==Q)B=M,N=await F(B);if(N.status<300)$.eventSeq=B+1;return N}}function hJ($){return(Y,G)=>new Promise((X,j)=>{if(Z.turns.get($.claim.attempt_id)!==$){j(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=nJ){j(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:Y,data:G,resolve:X,reject:j}),$.flush?.()})}function XJ($){if(e.has($))return;e.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&P.readyState===WebSocket.OPEN){let Y=$.outbox[0],G;try{G=await _($).emit(Y.kind,Y.data)}catch(X){if(X instanceof h)return;G={status:500}}if($.outbox.shift(),G.status<300)Y.resolve();else Y.reject(Error(`${Y.kind} refused ${G.status}`))}}finally{e.delete($)}})()}async function wJ($,Y){try{let G=await J.agent.attestFrame($,Y);if(P.readyState!==WebSocket.OPEN)return;m(G);let X=await f(["attested","attest_refused"],15000);Z.attest=X.t==="attested"?"accepted":"refused";for(let j of Z.attestWaiters.splice(0))j(Z.attest==="accepted");if(K("vm_hands.attest",{result:Z.attest,exit_code:G.exit_code,...X.t==="attest_refused"?{code:String(X.code??"")}:{}}),Z.attest==="refused")P.close(4401,"attest_refused")}catch(G){K("vm_hands.attest_failed",{code:G instanceof W?G.code:"probe_error"});for(let X of Z.attestWaiters.splice(0))X(!1);if(Z.attest!=="accepted")P.close(4000,"attest_unanswered")}}async function kJ($){let Y=p&&Z.attest==="pending",G=$.vm_hands_attest,X=G;if(Z.attest==="refused"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(X==="accepted"){if(!Y&&Z.attest!=="accepted"){Z.attest="accepted";for(let A of Z.attestWaiters.splice(0))A(!0)}}else if(X!=="pending"||!Y&&Z.attest!=="accepted"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let A=Date.parse($.lease_until)-Date.now()-5000,l=Math.max(0,Math.min(i,Number.isFinite(A)?A:i));if(!await new Promise((o)=>{let x=setTimeout(()=>o(!1),l);Z.attestWaiters.push((T)=>{clearTimeout(x),o(T)})})){await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let j={claim:$,eventSeq:0},{complete:q,emit:C}=_(j),Q;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");Q=!GJ($)}catch(A){K("vm_hands.bind_refused",{code:A instanceof W?A.code:"unexpected"}),await q("failed",{error_code:A instanceof W?A.code:"vm_hands_bind_invalid"});return}let F;try{F=await J.agent.bind(AJ($))}catch(A){K("vm_hands.bind_refused",{code:A instanceof W?A.code:"unexpected"}),await q("failed",{error_code:A instanceof W?A.code:"vm_hands_bind_failed"});return}let B={...F.ready_data??J.readyData({launchId:F.launch_id,claim:$})};if(Q)delete B.environment_installed;b.set($.attempt_id,{claim:$,launchId:F.launch_id,readyData:B,eventSeq:j.eventSeq,ackSeq:-1});let N=await C("hands.ready",{...B,vm_hands:{layout:F.layout,policy_digest:F.policy_digest,launch_id:F.launch_id}});if(b.delete($.attempt_id),N.status>=300){await _J(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await q("failed",{error_code:MJ(N.json?.error,"vm_hands_probe_failed")});return}let M={claim:$,launchId:F.launch_id,readyData:B,eventSeq:j.eventSeq,ackSeq:-1};Z.turns.set($.attempt_id,M),M.flush=()=>XJ(M),J.onTurn?.($.attempt_id,hJ(M)),await FJ(M)}async function FJ($){let{fence:Y,op:G}=_($),X=null,j=null,q=J.agent.executorExited($.claim.attempt_id).then((C)=>{return j=C,null});J:for(;;){let C=await Promise.race([q,w(`/operations/${G}/heartbeat`,{...Y,control_ack_seq:$.ackSeq,wait_ms:oJ})]);if(!C){X="vm_hands_executor_exited",K("vm_hands.executor_exited",{reason:j});break}if(C.status>=300)break;let Q=(C.json?.controls??[]).slice().sort((F,B)=>F.seq-B.seq);for(let F of Q){if(F.seq<=$.ackSeq)continue;if(F.kind==="operation.cancel"||F.kind==="cancel"){$.ackSeq=F.seq;break J}if(F.kind===OJ)try{await HJ($,F.payload??{})}catch(B){if(B instanceof h)throw B;X=B instanceof W?B.code:"environment_unavailable";let N=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:null;K("vm_hands.environment_refused",{code:X,cause:N});break J}$.ackSeq=F.seq}}await SJ($,X)}async function gJ($){let Y=$,G={claim:Y,eventSeq:0},{complete:X,emit:j,fence:q,op:C}={..._(G)},Q=$.vm_hands_origin==="person"?"person":"model",F=String($.capability??"");if(!J.executeOp){await X("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(p&&Z.attest==="pending")){Z.attest="accepted";for(let x of Z.attestWaiters.splice(0))x(!0)}if(Z.attest!=="accepted"){let x=Date.parse(String($.lease_until??""))-Date.now()-5000,T=Z.attest==="refused"?0:Math.max(0,Math.min(i,Number.isFinite(x)?x:i));if(!(T>0&&await new Promise((PJ)=>{let VJ=setTimeout(()=>PJ(!1),T);Z.attestWaiters.push((vJ)=>{clearTimeout(VJ),PJ(vJ)})}))){await X("failed",{error_code:"vm_hands_unattested"});return}}let B=J.agent.bindIdForRun(Y.run_id);if(Q==="model"&&B===null){await X("failed",{error_code:"vm_hands_not_bound"});return}if(iJ.has(F)&&J.agent.liveBindIds.length===0){await X("failed",{error_code:"vm_hands_not_bound"});return}let N=new AbortController;t.add(N);let M,A=new Promise((x)=>{M=x}),l={abort:N,settled:A};if(Q==="model"&&B){let x=Z.modelOps.get(B)??new Set;x.add(l),Z.modelOps.set(B,x),await J.agent.environmentInstalled(B,sJ,N.signal)}let u=-1,o=setInterval(()=>{w(`/operations/${C}/heartbeat`,{...q,control_ack_seq:u,wait_ms:0}).then((x)=>{if(x.status>=300){N.abort();return}let T=x.json?.controls??[];for(let k of T)if(u=Math.max(u,k.seq),k.kind==="operation.cancel"||k.kind==="cancel")N.abort()},()=>N.abort())},dJ);try{let x=await J.executeOp({kind:Q,claim:$,...Q==="model"&&B?{bindId:B}:{},signal:N.signal,emit:async(k)=>{await j(k.kind,k.data??{})}}),T=await X(x.status,{...x.result?{result:x.result}:{},...x.error_code?{error_code:MJ(x.error_code,"vm_hands_op_failed")}:{}});K("vm_hands.op",{capability:F,kind:Q,status:x.status,code:x.error_code??null,...T.status>=300?{complete_status:T.status,complete_error:String(T.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(o),t.delete(N),B)Z.modelOps.get(B)?.delete(l);M()}}async function SJ($,Y){let G=$.claim.attempt_id;if(Z.turns.get(G)===$)Z.turns.delete(G);J.onTurn?.(G,null),s($);let X=await I(Z,J.agent,G);Z.receipts.push({turn:$,failure:Y,unbound:X}),await ZJ()}function ZJ(){return JJ=JJ.then(WJ,WJ),JJ}async function WJ(){while(Z.receipts.length){let{turn:$,failure:Y,unbound:G}=Z.receipts[0],{complete:X,emit:j}=_($);try{if(await j("hands.stopped",{...$.readyData,reason_code:Y?"failed":"cancelled",killed_verified:G.killed_verified,shredded:G.shredded,...G.srt_fallbacks?{vm_hands_srt_fallbacks:G.srt_fallbacks}:{}}),Y)await X("failed",{error_code:Y});else await X("cancelled",{error_code:"driver_stopped"})}catch(q){if(q instanceof h)return}Z.receipts.shift()}}async function HJ($,Y){let{fence:G,op:X}=_($),j=Y.snapshot_id;if(Y.version!==1||typeof j!=="string"||Object.keys(Y).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let q=await w(`/operations/${X}/environment`,{...G,snapshot_id:j}),C=q.json?.environment_sealed;if(q.status!==200||!C||q.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let Q=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:j,deviceId:Z.deviceId??"",sealed:C});if((await w(`/operations/${X}/environment-ack`,{...G,...Q})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
|
|
5
|
-
export{KZ as u,bJ as v,PZ as w};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ka as Kq,ob as Bq,qa as Yq,sb as Tq}from"./vm-hands-entry-lite-mgx65dde.js";import"./vm-hands-entry-lite-fq0zr7an.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-mzxhng4z.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-cx4z34jh.js";import"./vm-hands-entry-lite-14t846kp.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";import{spawn as wq}from"child_process";import{chmodSync as Pq,chownSync as Dq,existsSync as t,lstatSync as s,mkdirSync as e,mkdtempSync as jq,readdirSync as p,readFileSync as A,realpathSync as Aq,rmdirSync as r,rmSync as fq,writeFileSync as c}from"fs";import{join as L}from"path";var Uq="/sys/fs/cgroup/reason-payload",S="vm-hands",Cq="/run/ara-srt/fallbacks.jsonl",u="/reason-person",qq=5000,vq=1e4,Xq="__VM_HANDS_PROOF_DIR__",Oq="__VM_HANDS_PROBE_NONCE__";class R extends Error{code;constructor(q,z){super(z);this.code=q}}function Vq(q,z){if(!/^[0-9a-f-]{36}$/i.test(z))throw new R("vm_hands_bind_invalid","bad bind id");return L(q,S,`b-${z.toLowerCase()}`)}var bq=5000,Lq=(q)=>`'${q.replaceAll("'","'\\''")}'`;function lq(q){let z=q.cgroup??Uq,K=q.init.layout.payload_uid,X=q.log??(()=>{}),G=new Map,Y=new Map,B=0,O=()=>{try{let Z=A("/run/ara-srt/starts.jsonl","utf8"),$=Z.slice(B>Z.length?0:B).split(`
|
|
3
|
-
`).filter(Boolean);B=Z.length;let Q=$.map((T)=>{try{return Number(JSON.parse(T).elapsed_ms)||0}catch{return 0}});if(Q.length)X("vm_hands.srt_server_starts",{count:Q.length,elapsed_ms:Q.slice(0,8)})}catch{}},j=null,_=!1,h=q.srtCgroup??"/sys/fs/cgroup/reason-srt",f=()=>{j??=Zq()},b=0,x=()=>{try{let Z=A(Cq,"utf8"),$=Z.slice(b>Z.length?0:b);b=Z.length;let Q=$.split(`
|
|
4
|
-
`).filter(Boolean).slice(0,1000);if(!Q.length)return null;let T={},U=0;for(let N of Q)try{let M=JSON.parse(N),F=typeof M.code==="string"&&/^[a-z_]{1,40}$/.test(M.code)?M.code:"other";if(T[F]=(T[F]??0)+1,typeof M.elapsed_ms==="number")U=Math.max(U,M.elapsed_ms)}catch{T.unparsed=(T.unparsed??0)+1}return X("vm_hands.srt_fallbacks",{count:Q.length,codes:T,max_elapsed_ms:U}),{count:Q.length,codes:T,max_elapsed_ms:U}}catch{return null}},w=!1,y=(Z,$,Q)=>{if(w)throw Error("vm_hands_pool_held");return n(Z,$,Q)},i=(Z)=>($,Q,T)=>wq("/bin/sh",["-c",`echo $$ > ${Lq(L(Z,"cgroup.procs"))} || exit 125; exec "$@"`,"vm-hands-join",$,...Q],T),n=i(L(z,S)),g=(Z)=>Vq(z,Z),Mq=(Z)=>{let $=g(Z);try{e($,{mode:493})}catch(Q){if(!(Q&&typeof Q==="object"&&("code"in Q)&&Q.code==="EEXIST"))throw new R("vm_hands_bind_failed","bind cgroup")}return $},Nq=(Z)=>{try{r(g(Z))}catch{}},I=q.prespawn?Kq({spawnProcess:y,...q.relayDependencies?.sourceEntrypoint?{sourceEntrypoint:q.relayDependencies.sourceEntrypoint}:{},log:(Z,$)=>X(Z,$??{})}):null;I?.arm();let a=I?setInterval(()=>{I.arm()},bq):null;a?.unref?.();async function m(Z){let $=G.get(Z);if(G.delete(Z),!$)return;$.abort.abort(),await $.done}return{bindCgroup:g,async startExecutor(Z){if(f(),Y.set(Z.bindId,Zq()),_=!0,!Z.claim)throw new R("vm_hands_bind_invalid","an executor needs the claim it serves");await m(Z.bindId);let{claim:$,bindId:Q}=Z,T=Mq(Q),U=$.owner;if(!U||typeof U.device_id!=="string"||typeof $.root_id!=="string")throw new R("vm_hands_bind_invalid","claim without its owner Device or root");let N=new AbortController,M,F,D=new Promise((W,P)=>{M=W,F=P}),v,C=new Promise((W)=>{v=W}),V=Tq({headless:!0,hostExecution:!0,runtimeDirectory:q.runtimeDirectory,deviceIdentity:{deviceId:U.device_id,rootId:$.root_id,apiOrigin:q.apiOrigin},claimOwner:$.owner,root:q.root,runId:$.run_id,operationId:$.operation_id,attemptId:$.attempt_id,payload:Object.fromEntries(Object.entries($.payload).filter(([W])=>!W.startsWith("vm_hands_"))),signal:N.signal,emitEvent:async(W,P)=>{if(W==="hands.ready"){M(P);return}if(W==="hands.started"||W==="hands.stopped"||W==="hands.failed")return;await q.forward(Q,W,P)}},{...q.relayDependencies,spawnWorker:(W)=>i(T)(W.command,W.args,W.options),...I?{takePrespawnedWorker:(W)=>{let P=I.take(W);if(!P?.pid)return P;try{return c(L(T,"cgroup.procs"),String(P.pid)),P}catch{try{P.kill("SIGKILL")}catch{}return null}},adoptSpawnedWorker:I.adopt}:{}}).then(()=>{v("executor_stopped")},(W)=>{let P=W&&typeof W==="object"&&"code"in W?String(W.code):"executor_failed";F(new R(P,W instanceof Error?W.message:String(W))),v(P)}).finally(()=>F(new R("vm_hands_executor_exited","executor ended before it was ready")));G.set(Q,{abort:N,done:V,exited:C,operationId:$.operation_id,runId:$.run_id,expiresAtMs:Date.parse(String($.payload.expires_at??""))||0});let E=await D,J=E.executor_launch_id;if(typeof J!=="string")throw new R("vm_hands_bind_failed","executor ready without a launch id");return{launchId:J,readyData:E,applied:{hands_confinement:typeof $.payload.hands_confinement==="string"?$.payload.hands_confinement:null,browser_egress:$.payload.browser_egress??null}}},takeSrtFallbacks:x,executorExited(Z){return G.get(Z)?.exited??new Promise(()=>{})},freezeBind(Z){let $=g(Z);if(t(L($,"cgroup.freeze")))c(L($,"cgroup.freeze"),"1")},async killAndVerifyPayload(Z){let $=new Set(Z?.keep??[]);if($.size)return Rq(Z?.bindId??null,$);w=!0;let Q=Wq();try{await Jq();let T=Promise.all([...G.keys()].map((F)=>m(F).catch(()=>{return})));O();let U=Date.now()+qq;await d(z,U,"payload"),await T;let N=(_||q.srtWarmLate?.()===!0)&&t(L(h,"cgroup.events"));if(N)await d(h,U,"srt");let M=Qq(K).filter((F)=>!k(F,u));if(j!==null){let F=$q(j).filter((D)=>D!==process.pid&&!k(D,u));if(F.length)throw X("vm_hands.kill_strays",{strays:F.slice(0,16).map((D)=>{let v="?",C="?";try{v=A(`/proc/${D}/comm`,"utf8").trim().slice(0,32)}catch{}try{C=(A(`/proc/${D}/cgroup`,"utf8").split(`
|
|
5
|
-
`).find((V)=>V.startsWith("0::"))??"").slice(3,80)}catch{}return{pid:D,comm:v,cgroup:C}})}),new R("vm_hands_kill_unverified",`${F.length} process(es) the run started survived it`);j=null}if(_=!1,N)q.onSrtReset?.();if(M.length)throw X("vm_hands.kill_survivors",{pids:M.slice(0,16)}),new R("vm_hands_kill_unverified",`${M.length} payload-uid process(es) outside the payload cgroup`);Y.clear();for(let F of o())try{r(L(z,S,F))}catch{}}finally{w=!1,Q()}if(I)setTimeout(()=>{if(!G.size)I.arm()},100).unref?.()},async runProbe({nonce:Z,script:$}){if(f(),!$.includes(Xq))throw new R("vm_hands_probe_failed","probe names no proof directory");let Q=q.proofParent??"/tmp/reason-vm-hands-proof";e(Q,{mode:457,recursive:!0});let T=s(Q);if(T.isSymbolicLink()||!T.isDirectory()||T.uid!==(process.getuid?.()??-1)||(T.mode&4095)!==457)throw new R("vm_hands_probe_failed","proof parent is not root's 0711 directory");let U=jq(L(Q,"p-")),N=!1;try{if(!/^[A-Za-z0-9/._-]+$/.test(U)||!/^[A-Za-z0-9_-]{1,128}$/.test(Z))throw new R("vm_hands_probe_failed","proof directory path or nonce");Dq(U,K,K),Pq(U,448);let M=s(U).ino,F=n("/bin/bash",["-c",$.replaceAll(Xq,U).replaceAll(Oq,Z)],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:["ignore","pipe","ignore"]}),D="";F.stdout?.on("data",(C)=>{if(D.length<16384)D+=C.toString("utf8").slice(0,16384-D.length)});let v=await new Promise((C)=>{let V=setTimeout(()=>{N=!0,F.kill("SIGKILL"),C(124)},vq);F.once("error",()=>{clearTimeout(V),C(127)}),F.once("close",(E)=>{clearTimeout(V),C(E??1)})});return X("vm_hands.probe",{nonce_len:Z.length,exit_code:v}),{exitCode:v,markers:D,proofDirInode:M}}finally{if(!N)fq(U,{recursive:!0,force:!0})}},restatLayout(){let{session_root:Z,alias:$}=q.init.layout,Q="invalid";try{Bq(Z),Q="0:0:755"}catch{}let T=!1,U=-1;try{let N=s($);U=N.uid,T=Q==="0:0:755"&&$===L(Z,"repo")&&!N.isSymbolicLink()&&N.isDirectory()&&Aq($)===$&&N.uid===K}catch{}return{root_mode:Q,alias_ok:T,owner_uid:U}},installEnvironment(Z,$){let Q=G.get(Z);if(!Q)throw new R("environment_unavailable","no executor owns an environment");return Yq({root:q.root,operationId:Q.operationId,payload:$}).installed_revision},async stop(){if(a)clearInterval(a);I?.close(),await Promise.all([...G.keys()].map((Z)=>m(Z)))}};function o(){try{return p(L(z,S),{withFileTypes:!0}).filter((Z)=>Z.isDirectory()&&/^b-[0-9a-f-]{36}$/.test(Z.name)).map((Z)=>Z.name)}catch{return[]}}async function Rq(Z,$){let Q=new Set([...$].map((U)=>U.toLowerCase())),T=Wq();try{await Jq();let U=Date.now()+qq,N=new Set(o().filter((J)=>!Q.has(J.slice(2))).map((J)=>J.slice(2)));if(Z)N.add(Z.toLowerCase());let M=null;for(let J of N){let W=m(J).catch(()=>{return}),P=Y.get(J);if(P!==void 0)M=M===null?P:Math.min(M,P);if(t(L(g(J),"cgroup.events")))await d(g(J),U,"bind");await W}let F=[...Q].map((J)=>g(J).replace(/^\/sys\/fs\/cgroup/,"")),D=[z,L(z,S)].map((J)=>J.replace(/^\/sys\/fs\/cgroup/,"")),v=h.replace(/^\/sys\/fs\/cgroup/,""),C=(J)=>k(J,u)||F.some((W)=>k(J,W)),V=Qq(K).filter((J)=>!C(J));if(V.length)throw X("vm_hands.kill_survivors",{pids:V.slice(0,16),beside:Q.size}),new R("vm_hands_kill_unverified",`${V.length} payload-uid process(es) outside a live bind`);let E=(J)=>!C(J)&&!k(J,"/reason-vm-hands")&&!k(J,v)&&!D.some((W)=>xq(J,W));if(M!==null){let J=$q(M).filter((W)=>W!==process.pid&&E(W));if(J.length)throw X("vm_hands.kill_strays",{strays:J.slice(0,16).map((W)=>({pid:W})),beside:Q.size}),new R("vm_hands_kill_unverified",`${J.length} process(es) the run started survived it`)}for(let J of N)Y.delete(J),Nq(J)}finally{T()}}}function xq(q,z,K="/proc"){try{return A(L(K,String(q),"cgroup"),"utf8").split(`
|
|
6
|
-
`).find((G)=>G.startsWith("0::"))?.slice(3)===z}catch{return!1}}function k(q,z,K="/proc"){try{let G=A(L(K,String(q),"cgroup"),"utf8").split(`
|
|
7
|
-
`).find((Y)=>Y.startsWith("0::"))?.slice(3)??"";return G===z||G.startsWith(`${z}/`)}catch{return!1}}var Iq=100;function Zq(){try{return Math.floor(Number(A("/proc/uptime","utf8").split(" ")[0])*Iq)}catch{return 0}}async function d(q,z,K){try{c(L(q,"cgroup.freeze"),"1")}catch(X){throw new R("vm_hands_kill_unverified",`${K} cgroup.freeze: ${X instanceof Error?X.message:String(X)}`)}while(!/^populated 0$/m.test(A(L(q,"cgroup.events"),"utf8"))){if(Date.now()>z)throw new R("vm_hands_kill_unverified",`${K} cgroup still populated (left frozen)`);for(let X of hq(q)){if(!_q(X,q))continue;try{process.kill(X,"SIGKILL")}catch{}}await new Promise((X)=>setTimeout(X,10))}try{c(L(q,"cgroup.freeze"),"0")}catch(X){throw new R("vm_hands_kill_unverified",`${K} cgroup thaw: ${X instanceof Error?X.message:String(X)}`)}}function _q(q,z){let K=z.replace(/^\/sys\/fs\/cgroup/,"")||"/",X="";try{X=A(`/proc/${q}/cgroup`,"utf8").split(`
|
|
8
|
-
`).find((Y)=>Y.startsWith("0::"))??""}catch{return!1}let G=X.slice(3);return G===K||G.startsWith(`${K}/`)}function hq(q){let z=[],K=(X)=>{try{for(let Y of A(L(X,"cgroup.procs"),"utf8").split(`
|
|
9
|
-
`))if(/^\d+$/.test(Y))z.push(Number(Y))}catch{}let G=[];try{G=p(X,{withFileTypes:!0}).filter((Y)=>Y.isDirectory()).map((Y)=>Y.name)}catch{}for(let Y of G)K(L(X,Y))};return K(q),z}function $q(q,z="/proc"){let K=[];for(let X of p(z)){if(!/^\d+$/.test(X))continue;let G;try{G=A(L(z,X,"stat"),"utf8")}catch{continue}let Y=G.slice(G.lastIndexOf(")")+2).split(" "),B=Number(Y[1]),O=Number(Y[6]),j=Number(Y[19]);if(!((O&2097152)!==0||B===2||X==="2")&&Y[0]!=="Z"&&j>=q)K.push(Number(X))}return K}function Qq(q,z="/proc"){let K=[];for(let X of p(z)){if(!/^\d+$/.test(X))continue;let G;try{G=A(L(z,X,"status"),"utf8")}catch{continue}let Y=/^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m.exec(G);if(Y&&Y.slice(1).some((B)=>Number(B)===q))K.push(Number(X))}return K}function zq(q="/proc/sys/kernel/yama/ptrace_scope"){try{return Number(A(q,"utf8").trim())>=1}catch{return!1}}var H=0,Fq=[],l=new Set;function Wq(){H++;let q=!1;return()=>{if(q)return;if(q=!0,--H===0)for(let z of Fq.splice(0))z()}}function Hq(){return H===0?Promise.resolve():new Promise((q)=>{Fq.push(q)})}async function Gq(){while(H>0)await Hq()}async function Jq(){let q=Date.now()+1000;while(l.size&&Date.now()<q)await new Promise((z)=>setTimeout(z,2))}function gq(q,z){let K=z.replace(/^\/sys\/fs\/cgroup/,"");l.add(q);let X=()=>{let G="";try{G=A(`/proc/${q}/cgroup`,"utf8").split(`
|
|
10
|
-
`).find((Y)=>Y.startsWith("0::"))??""}catch{l.delete(q);return}if(G.slice(3)===K){l.delete(q);return}setTimeout(X,1)};X()}function cq(q){let z={person:q.personCgroup??L("/sys/fs/cgroup",u,S),model:q.payloadCgroup??L(Uq,S)},K=q.entry??process.argv[1]??"",X={},G=(B)=>B.startsWith("model:")&&q.bindCgroup?q.bindCgroup(B.slice(6)):z[B.startsWith("model")?"model":"person"],Y=(B)=>{let O=B.startsWith("model")?"model":"person",j=new Map,_=String(q.payloadUid),h=String(q.payloadGid),f=Bun.spawn(["/bin/sh","-c",`echo $$ > ${Lq(L(G(B),"cgroup.procs"))} || exit 125; exec /usr/bin/setpriv --no-new-privs --reuid=${_} --regid=${h} --clear-groups -- "$@"`,"vm-hands-op-join",process.execPath,"--no-install",K,"--vm-hands-op-runner"],{cwd:"/",env:{PATH:process.env.PATH??"/usr/bin:/bin",BUN_BE_BUN:"1",HOME:"/home/runner"},stdio:["ignore","ignore","ignore"],ipc(x){let w=x,y=j.get(w.id);if(!y)return;if(w.t==="event"&&w.event)y.onEvent(w.event);if(w.t==="done")j.delete(w.id),y.done(w.completion??{status:"failed",error_code:"vm_hands_op_failed"})}});f.exited.then((x)=>{if(X[B]?.child===f)delete X[B];for(let[,w]of j)w.done({status:"failed",error_code:"vm_hands_op_runner_exited"});j.clear(),q.log?.("vm_hands.op_runner_exited",{kind:O,code:x})}),gq(f.pid,G(B));let b={child:f,pending:j};return X[B]=b,b};return{run(B,O,j,_,h){if(!zq())return Promise.resolve({status:"failed",error_code:"vm_hands_ptrace_unprotected"});let f=B==="model"&&h&&q.bindCgroup?`model:${h.toLowerCase()}`:B,b=async()=>{while(!X[f]&&H>0)await Gq()};return b().then(async()=>{if(!X[f]&&H>0)await b()}).then(()=>new Promise((x)=>{if(!X[f]&&H>0){x({status:"failed",error_code:"vm_hands_op_runner_unavailable"});return}let w=X[f]??Y(f);w.pending.set(O.id,{onEvent:j,done:x}),_.addEventListener("abort",()=>{try{w.child.send({t:"cancel",id:O.id})}catch{}},{once:!0});try{w.child.send({t:"op",...O})}catch{w.pending.delete(O.id),x({status:"failed",error_code:"vm_hands_op_runner_unavailable"})}}))},warm(B){if(!X[B]&&zq())Gq().then(()=>{if(!X[B]&&H===0)Y(B)})},stop(){for(let B of Object.keys(X))X[B]?.child.kill()}}}export{Vq as vmHandsBindCgroup,hq as subtreePids,zq as ptraceProtected,$q as processesStartedSince,Qq as payloadUidProcesses,k as inCgroup,cq as createVmHandsOpRunners,lq as createVmHandsExecutor,R as VmHandsExecutorError,Xq as VM_HANDS_PROOF_DIR_TOKEN,Oq as VM_HANDS_PROBE_NONCE_TOKEN,u as VM_HANDS_PERSON_CGROUP,S as VM_HANDS_PAYLOAD_JOIN,Uq as VM_HANDS_PAYLOAD_CGROUP};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Uh as E}from"./vm-hands-entry-lite-cxs89wzv.js";async function Q(){let[{executeLocalOperation:G},{configureDesktopAccount:H},{configureWorkerSandbox:J}]=await Promise.all([import("./local-capabilities-nywse9m3.js"),import("./desktop-account-emwzhj61.js"),import("./worker-sandbox-yt11b09s.js")]);J();let K=(process.geteuid?.()??0)!==0,z=new Map,y=(B)=>{try{process.send?.(B)}catch{}};process.on("message",(B)=>{let j=B;if(j?.t==="cancel"){z.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!K){y({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=new AbortController;z.set(j.id,F),G(j.state,j.claim,{worker:j.worker,signal:F.signal,emit:(q)=>{let{deliverySignal:N,...M}=q;y({t:"event",id:j.id,event:M})}}).then((q)=>y({t:"done",id:j.id,completion:q}),(q)=>y({t:"done",id:j.id,completion:{status:"failed",error_code:q&&typeof q==="object"&&"code"in q&&typeof q.code==="string"?q.code:"vm_hands_op_failed"}})).finally(()=>z.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}export{Q as runVmHandsOpRunner};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{u as k,v as m,w as l}from"./vm-hands-entry-lite-rm0jf774.js";import{_c as v}from"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import{Uh as G}from"./vm-hands-entry-lite-cxs89wzv.js";import{spawn as a}from"child_process";import{createHash as r}from"crypto";import{lstatSync as T,mkdirSync as s,readFileSync as i,statSync as t,writeFileSync as d}from"fs";var D="/run/reason-vm-hands",O="/run/reason-vm-hands/env",w="/home/runner/.reason/workspace",e=/^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/,p="/sys/fs/cgroup/reason-srt",S="/usr/local/bin/ara-srt-exec",jj=65536,qj=21600000;function Jj(Q,j="/run/ara-srt"){try{if((process.getuid?.()??-1)!==0)return;s(j,{recursive:!0,mode:448});let J=T(j);if(!J.isDirectory()||J.uid!==0||(J.mode&63)!==0){Q("srt_base_keyed_skipped",{reason:"socket_dir_unsafe"});return}d(`${j}/base-keyed`,`1
|
|
3
|
-
`,{mode:420}),Q("srt_base_keyed",{})}catch{Q("srt_base_keyed_skipped",{reason:"error"})}}function R(Q,j){let J=(F)=>{return j("srt_warm_skipped",{reason:F}),Promise.resolve()};if(typeof Q.srt_base_settings!=="string")return J("no_settings");let Z=Buffer.from(Q.srt_base_settings,"base64");if(Z.length===0||Z.length>jj||Z.toString("base64")!==Q.srt_base_settings)return J("settings_invalid");try{let F=T(p);if(!F.isDirectory()||F.uid!==0||(F.mode&18)!==0)return J("cgroup_unsafe");for(let[H,g]of[[S,!1],["/usr/local/bin",!0]]){let Y=T(H);if((g?!Y.isDirectory():!Y.isFile())||Y.uid!==0||(Y.mode&18)!==0)return J("srt_exec_unsafe")}}catch{return J("cgroup_or_exec_missing")}if((process.getuid?.()??-1)!==0)return J("not_root");let z=performance.now(),X=r("sha256").update(Z).digest("hex"),W=`${D}/srt-base-settings.json`;try{d(W,Z,{mode:384,flag:"w"})}catch{return J("settings_write")}let L=a("/bin/sh",["-c",`echo $$ > ${p}/cgroup.procs || exit 125; exec "$@"`,"vm-hands-srt",S,"--settings",W,"--idle-ms",String(qj),"--","/bin/true"],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:"ignore"});return new Promise((F)=>{L.once("error",()=>{j("srt_warm_failed",{reason:"spawn"}),F()}),L.once("close",(H)=>{j(H===0?"srt_warm_done":"srt_warm_failed",{exit_code:H,warm_ms:Math.round(performance.now()-z),settings_sha256:X}),F()})})}var y=3000;function Hj(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let j=Q,J=j.layout,Z=j.device_key,z=j.credential;return typeof j.workspace_id==="string"&&Number.isSafeInteger(j.instance_generation)&&typeof j.api_origin==="string"&&e.test(j.api_origin)&&typeof j.manifest_digest==="string"&&!!z&&typeof z.key_id==="string"&&Number.isSafeInteger(z.expires_at_ms)&&typeof z.signature==="string"&&!!J&&typeof J.session_root==="string"&&typeof J.alias==="string"&&Number.isSafeInteger(J.payload_uid)&&typeof J.kind==="string"&&!!Z&&typeof Z.pkcs8==="string"&&typeof Z.spki==="string"?j:null}function u(Q){s(Q,{recursive:!0,mode:448});let j=t(Q);if(!j.isDirectory()||(j.mode&63)!==0||j.uid!==(process.getuid?.()??-1))throw Error(`vm_hands_runtime_directory_unsafe: ${Q}`)}async function Qj(Q){let[{CLI_VERSION:j},J,Z,z]=await Promise.all([import("./version-rm84p9qv.js"),import("./hands-worker-source-ea5ywzxx.js"),import("./network-contract-bv7mj5he.js"),import("./device-workspace-xnyb7zp2.js")]),{REASON_HANDS_PROTOCOL_VERSION:X}=await import("./reason-hands-protocol-5zt3ys5t.js");return{reason_runtime_version:j,bridge_version:j,protocol_version:v,execution_eligible:!0,instance_generation:Q.instance_generation,capabilities:{supported_operations:["hands.connect"],hands_worker_artifact_sha256:J.REASON_HANDS_WORKER_ARTIFACT_SHA256,hands_worker_entrypoint:J.REASON_HANDS_WORKER_ENTRYPOINT,hands_slots:1,max_payload_bytes:Z.LOCAL_OPERATION_MAX_BYTES,max_result_bytes:Z.LOCAL_OPERATION_MAX_BYTES,operation_constraints:{"hands.connect":{ready:!0,execution_mode:"host",transport:"wss_relay",worker:"ara_hands",slots:1,session_group:Z.HANDS_SESSION_GROUP,worker_version:J.REASON_HANDS_WORKER_VERSION,protocol_version:X,worker_artifact_sha256:J.REASON_HANDS_WORKER_ARTIFACT_SHA256,worker_entrypoint:J.REASON_HANDS_WORKER_ENTRYPOINT,policy_mode:"full_access",policy_version:1,workspace_base:z.REASON_WORKSPACE_BASE,workspace_layout:z.SESSION_WORKSPACE_LAYOUT,browser_state:"optional_headless",desktop:!1,max_session_ms:43200000,environment_delivery:Z.HANDS_ENVIRONMENT_DELIVERY,[Z.HANDS_ENVIRONMENT_AT_CLAIM_KEY]:Z.HANDS_ENVIRONMENT_AT_CLAIM,[Z.HANDS_CLOUD_ACCESS_KEY]:Z.HANDS_CLOUD_ACCESS,[Z.HANDS_LARGE_ENVIRONMENT_KEY]:Z.HANDS_LARGE_ENVIRONMENT,[Z.HANDS_CONFINEMENT_KEY]:Z.HANDS_CONFINEMENT,[Z.HANDS_JOBS_USER_KEY]:Z.HANDS_JOBS_USER,vm_hands:"v1"}}}}}var P=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.list","ports.list","pty.start","jobs.control","automation.call.v1"],Zj=new Set(["pty.start","jobs.control"]);function $j(Q,j){let J=j([{id:"vm-hands",label:"workspace",path:w,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}],{worker:{executionMode:"unsandboxed",readiness:Object.fromEntries(P.map((X)=>[X,!0]))}}),Z=Q.capabilities,z={...Z.operation_constraints};for(let X of P)z[X]={...J.operation_constraints?.[X]??{},ready:!0,execution_mode:J.operation_constraints?.[X]?.execution_mode??"host"};return{...Q,capabilities:{...Z,supported_operations:["hands.connect",...P],operation_constraints:z}}}function zj(Q){for(let j of i("/etc/passwd","utf8").split(`
|
|
4
|
-
`)){let J=j.split(":");if(J.length>=4&&Number(J[2])===Q&&/^\d+$/.test(J[3]??"")&&Number(J[3])>0)return Number(J[3])}throw Error("vm_hands_payload_account_unavailable")}function Xj(Q,j){let J=j.owner;if(!J||typeof J.organization_id!=="string"||typeof J.device_id!=="string"||typeof j.root_id!=="string")return null;return{version:4,apiOrigin:Q.api_origin,orgId:J.organization_id,deviceId:J.device_id,devicePublicKey:"",displayName:"vm-hands",registeredAt:new Date(0).toISOString(),handsSlots:1,roots:[{id:j.root_id,label:"workspace",path:w,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}]}}async function Lj(Q,j){u(D),u(O),Jj(j);let J=R(Q,j),Z=!1,z=async()=>{if(!await Promise.race([J.then(()=>!0),new Promise(($)=>setTimeout(()=>$(!1),y).unref?.())]))Z=!0,j("srt_warm_late",{wait_ms:y})},[{configureDesktopAccount:X},{configureWorkerSandbox:W}]=await Promise.all([import("./desktop-account-emwzhj61.js"),import("./worker-sandbox-yt11b09s.js")]);W();try{X({value:String(Q.layout.payload_uid)})}catch{j("payload_account_unavailable"),await new Promise(()=>{setInterval(()=>{return},1073741824)})}let L=new AbortController;for(let q of["SIGTERM","SIGINT"])process.on(q,()=>L.abort());let F=new Map,H,g=new Promise((q)=>{H=q}),Y=g.then(()=>import("./vm-hands-executor-2pqe40rp.js")).then(({createVmHandsExecutor:q})=>{let $=q({init:Q,root:w,runtimeDirectory:D,apiOrigin:Q.api_origin,prespawn:!0,onSrtReset:()=>{Z=!1,J=R(Q,j)},srtWarmLate:()=>Z,forward:(B,K,N)=>F.get(B)?.(K,N)??Promise.reject(Error("vm_hands_not_bound")),log:(B,K)=>j(B,K)});return j("executor_loaded"),$}),V=(q)=>async(...$)=>(await Y)[q](...$),C=null;Y.then((q)=>{C=($)=>q.executorExited($)});let M={startExecutor:async(...q)=>{return await z(),V("startExecutor")(...q)},killAndVerifyPayload:V("killAndVerifyPayload"),runProbe:async(...q)=>{return await z(),V("runProbe")(...q)},restatLayout:()=>{throw Error("replaced below")},installEnvironment:()=>{throw Error("replaced below")},executorExited:(q)=>C?C(q):new Promise(()=>{}),takeSrtFallbacks:()=>null};Y.then((q)=>{M.restatLayout=()=>q.restatLayout(),M.installEnvironment=($,B)=>q.installEnvironment($,B),M.freezeBind=($)=>q.freezeBind($),M.takeSrtFallbacks=()=>q.takeSrtFallbacks?.()??null});let c=await k(Q),o=new m(Q,c,M,{envRoot:O}),h=Qj(Q),b=null,n=Promise.all([h,import("./local-capabilities-nywse9m3.js")]).then(([q,$])=>{b=$j(q,$.capabilityInventoryForRoots),j("device_ops_loaded")}).catch((q)=>j("device_ops_unavailable",{error:q instanceof Error?q.name:"error"})),f=g.then(()=>import("./vm-hands-executor-2pqe40rp.js")).then(({createVmHandsOpRunners:q,vmHandsBindCgroup:$,VM_HANDS_PAYLOAD_CGROUP:B})=>q({payloadUid:Q.layout.payload_uid,payloadGid:zj(Q.layout.payload_uid),bindCgroup:(K)=>$(B,K),log:(K,N)=>j(K,N)})).catch(()=>null);f.then((q)=>q?.warm("person")),j("agent_ready"),await l({apiOrigin:Q.api_origin,agent:o,signal:L.signal,heartbeat:async()=>b??await h,executeOp:async({kind:q,claim:$,bindId:B,signal:K,emit:N})=>{let x=Xj(Q,$);if(!x)return{status:"failed",error_code:"vm_hands_bind_invalid"};let E={executionMode:"unsandboxed",runtimeDirectory:D,readiness:Object.fromEntries(P.map((U)=>[U,!0]))},_=(U)=>{let A=typeof U.kind==="string"?U.kind:"";if(A)N({kind:A,...U.data&&typeof U.data==="object"?{data:U.data}:{}})};if($.capability==="exec.full"&&q!=="person")return{status:"failed",error_code:"capability_not_granted"};if($.capability==="automation.call.v1"&&q!=="model")return{status:"failed",error_code:"capability_not_granted"};if(Zj.has(String($.capability))){let{executeLocalOperation:U}=await import("./local-capabilities-nywse9m3.js");return U(x,$,{worker:E,signal:K,emit:(A)=>_(A)})}let I=await f;if(!I)return{status:"failed",error_code:"vm_hands_payload_account_unavailable"};return I.run(q,{id:String($.attempt_id),claim:$,state:x,worker:E},_,K,B)},readyData:({launchId:q})=>({executor_launch_id:q}),log:(q,$)=>{if(q==="vm_hands.registered"||q==="vm_hands.reconnected")H();j(q,$)},onTurn:(q,$)=>{if($)F.set(q,$);else F.delete(q)}}),await(await Y).stop(),(await f)?.stop()}export{R as startBaseSrtServer,Lj as runVmHands,Hj as parseVmHandsInit,Qj as heartbeatBody,Jj as enableBaseKeyedSrt};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{t as a}from"./vm-hands-entry-lite-xf6schkk.js";import"./vm-hands-entry-lite-93ejmwqn.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{a as configureWorkerSandbox};
|