@reason-machines/cli-linux-arm64-musl 0.2.277 → 0.2.279

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/connect-cli-m9tjjyvr.js +2 -0
  3. package/bin/vm-hands/custom-endpoint-device-92914wyp.js +2 -0
  4. package/bin/vm-hands/desktop-account-vsrtgkk9.js +2 -0
  5. package/bin/vm-hands/desktop-wallpaper-0pjhgyfk.jpg +0 -0
  6. package/bin/vm-hands/device-workspace-zk5xwd10.js +2 -0
  7. package/bin/vm-hands/dock-browser-afp005mt.png +0 -0
  8. package/bin/vm-hands/dock-files-rywdm96b.png +0 -0
  9. package/bin/vm-hands/dock-terminal-s41cj1jp.png +0 -0
  10. package/bin/vm-hands/hands-worker-source-da93x0qx.js +2 -0
  11. package/bin/vm-hands/index-w9nq2f0p.js +12818 -0
  12. package/bin/vm-hands/local-automation-v1egrx6g.js +2 -0
  13. package/bin/vm-hands/local-capabilities-jpyj1dh1.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-3j79jbyp.js +2 -0
  15. package/bin/vm-hands/local-display-mac-j1v3mcgx.js +2 -0
  16. package/bin/vm-hands/local-display-session-hmqaj491.js +2 -0
  17. package/bin/vm-hands/network-contract-41qanjhp.js +2 -0
  18. package/bin/vm-hands/package-rx9y4bwe.js +2 -0
  19. package/bin/vm-hands/permissions-wbdkvw1s.js +2 -0
  20. package/bin/vm-hands/reason-hands-protocol-51gs8j7v.js +2 -0
  21. package/bin/vm-hands/status-pxc0vwbt.js +96 -0
  22. package/bin/vm-hands/version-n43gjzwa.js +2 -0
  23. package/bin/vm-hands/vm-hands-entry-lite-01dd716a.js +3 -0
  24. package/bin/vm-hands/vm-hands-entry-lite-1hwdab4e.js +3 -0
  25. package/bin/vm-hands/vm-hands-entry-lite-22f3c914.js +43 -0
  26. package/bin/vm-hands/vm-hands-entry-lite-2s3w4m10.js +529 -0
  27. package/bin/vm-hands/vm-hands-entry-lite-65pbrs1x.js +3 -0
  28. package/bin/vm-hands/vm-hands-entry-lite-6tpswr2c.js +459 -0
  29. package/bin/vm-hands/vm-hands-entry-lite-7gh1rbn7.js +3 -0
  30. package/bin/vm-hands/vm-hands-entry-lite-84aq8d12.js +3 -0
  31. package/bin/vm-hands/vm-hands-entry-lite-9jfh56xt.js +343 -0
  32. package/bin/vm-hands/vm-hands-entry-lite-9pmag2qk.js +3 -0
  33. package/bin/vm-hands/vm-hands-entry-lite-anaydk9m.js +4 -0
  34. package/bin/vm-hands/vm-hands-entry-lite-bfwf82rw.js +5 -0
  35. package/bin/vm-hands/vm-hands-entry-lite-bwt3y6wz.js +3 -0
  36. package/bin/vm-hands/vm-hands-entry-lite-c2nrar90.js +4046 -0
  37. package/bin/vm-hands/vm-hands-entry-lite-cq7qt28m.js +179 -0
  38. package/bin/vm-hands/vm-hands-entry-lite-ffg7rf02.js +3 -0
  39. package/bin/vm-hands/vm-hands-entry-lite-fraghb8k.js +5 -0
  40. package/bin/vm-hands/vm-hands-entry-lite-g7faacwr.js +3 -0
  41. package/bin/vm-hands/vm-hands-entry-lite-gqncr2j0.js +42 -0
  42. package/bin/vm-hands/vm-hands-entry-lite-k4c504n7.js +3 -0
  43. package/bin/vm-hands/vm-hands-entry-lite-n07kxrd1.js +3 -0
  44. package/bin/vm-hands/vm-hands-entry-lite-ptmqg51y.js +4 -0
  45. package/bin/vm-hands/vm-hands-entry-lite-qdz95cmv.js +759 -0
  46. package/bin/vm-hands/vm-hands-entry-lite-qvrnx0vk.js +4 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-s2xydt0n.js +112 -0
  48. package/bin/vm-hands/vm-hands-entry-lite-s5qn1k80.js +4 -0
  49. package/bin/vm-hands/vm-hands-entry-lite-sv6xwe0h.js +66 -0
  50. package/bin/vm-hands/vm-hands-entry-lite.js +2 -0
  51. package/bin/vm-hands/vm-hands-executor-xg99mezq.js +9 -0
  52. package/bin/vm-hands/vm-hands-op-runner-b0xkges8.js +2 -0
  53. package/bin/vm-hands/vm-hands-runtime-gnbcsqcy.js +4 -0
  54. package/bin/vm-hands/worker-sandbox-nnce49w0.js +2 -0
  55. package/package.json +1 -1
@@ -0,0 +1,179 @@
1
+ // @bun
2
+ import{cf as Z8}from"./vm-hands-entry-lite-bfwf82rw.js";import{lf as R0}from"./vm-hands-entry-lite-ptmqg51y.js";import{gg as Kq}from"./vm-hands-entry-lite-22f3c914.js";import{Cg as p,Fg as V0,Ig as F0,Jg as C8,Kg as eq,Mg as f8,Pg as q0,Rg as x0}from"./vm-hands-entry-lite-s2xydt0n.js";import{Wg as wq}from"./vm-hands-entry-lite-s5qn1k80.js";import{Xg as o,Yg as C0}from"./vm-hands-entry-lite-9pmag2qk.js";import{jh as B0}from"./vm-hands-entry-lite-84aq8d12.js";import{zh as A0}from"./vm-hands-entry-lite-anaydk9m.js";import{Gh as S}from"./vm-hands-entry-lite-ffg7rf02.js";import{execFile as A1,spawn as w0}from"child_process";import{randomBytes as V1}from"crypto";import{chmodSync as F1,existsSync as w1,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 f}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 p0(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 v0=`# 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
+ `,u0=`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
+ `,c0="/tmp/ara-dock-browser.png",r0=`[Desktop Entry]
104
+ Name=Chrome
105
+ Exec=chromium --no-sandbox %U
106
+ Icon=${c0}
107
+ Type=Application
108
+ Categories=Network;WebBrowser;
109
+ `,m0=`[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
+ `,l0=`[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},d0=Sq,s0='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=(P)=>P.replaceAll("DISPLAY=:99",`DISPLAY=${q.display}`).replaceAll("/tmp/ara-",`${q.root}/ara-`);return{files:{"openbox/rc.xml":p0(q.screen),"tint2/tint2rc":x(v0),"picom/picom.conf":u0,"ara-terminal.desktop":x(m0),"ara-files.desktop":x(l0),"ara-chromium.desktop":x(r0).replace("chromium --no-sandbox %U",q.browserExec),"ara-set-root-wallpaper.py":d0},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"; [ "$(ticks "$pid")" = "$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"; }',s0,'[ ! -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 a0}from"events";import{createWriteStream as i0,existsSync as n0,mkdirSync as o0,mkdtempSync as GX,readFileSync as D8,readdirSync as AX,renameSync as t0,realpathSync as e0,rmSync as qx,statSync as g8,writeFileSync as xx}from"fs";import{dirname as h8,join as G}from"path";import{finished as Xx}from"stream/promises";var $8="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 Qx=["none","standard","all"],O8="22.23.3",Px={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53"},H8={"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",k8={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},bx={version:k8.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",I8=["tint2","picom","xterm","pcmanfm"],_q=["fonts-droid-fallback"],Eq=["pulseaudio"],Jx=["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,...I8],Nx=new Set([...I8,..._q,...Eq]),Fq=Jx.filter((q)=>q!=="chromium"&&!Nx.has(q)),Wx=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],U8="/usr/bin/chromium",Lx=["/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 T8(q){return{node:{version:O8,url:`https://nodejs.org/dist/v${O8}/node-v${O8}-${q}.tar.gz`,sha256:Px[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 jx(q){let x={extension:i};for(let[X,Q]of Object.entries(T8(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,T8(q)[W]?.version??""),P=Q("open_computer_use"),b=Q("open_browser_use"),J=q==="darwin-arm64",L=G(x,"Library","Application Support"),Z=J?G(L,"Google","Chrome","NativeMessagingHosts",`${n}.json`):G(x,".config","google-chrome","NativeMessagingHosts",`${n}.json`);return{root:X,automation:G(h8(X),"automation"),receipt:G(X,"receipt.json"),minimal:v8(x),node:G(Q("node"),"bin","node"),ocuDir:P,ocu:G(P,H8[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,H8[q].obu),extensionDir:J?G(L,"OpenBrowserUse","chrome-extension","release"):G(x,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:Z,nativeHostManifests:J?[Z,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",k8.version,"ffmpeg"):null,ffprobe:J?G(X,"ffprobe",bx.version,"ffprobe"):null}}function fq(q){try{let x=JSON.parse(D8(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")||!Qx.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 Ux(q,x,X=384){o0(h8(q),{recursive:!0,mode:448});let Q=`${q}.pending.${process.pid}`;xx(Q,x,{mode:X}),t0(Q,q)}function r(q){try{return g8(q).isFile()}catch{return!1}}function gq(q){try{let x=g8(q);return x.isFile()&&(x.mode&73)!==0}catch{return!1}}function Dx(q){try{return D8(q,"utf8")}catch{return null}}function l(q){for(let x of Lx){let X=G(x,q);try{let Q=g8(X);if(Q.isFile()&&(Q.mode&73)!==0)return X}catch{}}return null}function Tx(q){try{let x=JSON.parse(D8(G(q,"package.json"),"utf8"));return typeof x==="object"&&x!==null&&typeof x.version==="string"?x.version:null}catch{return null}}function Bx(q,x,X){let Q=T8(X)[q];if(!Q)return!1;if(q==="node")return r(G(x,"bin","node"));if(q==="chrome_for_testing")return r(G(x,zq));let P=H8[X][q==="open_computer_use"?"ocu":"obu"];return Tx(x)===Q.version&&r(G(x,P))&&(q==="open_computer_use"||r(G(x,"cli","open-browser-use.js")))}function Rx(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 p8(q){try{let x=JSON.parse(D8(q,"utf8"));return typeof x==="object"&&x!==null&&!Array.isArray(x)?x:null}catch{return null}}function Cx(q){let x=p8(G(q.extensionDir,"manifest.json"));return x!==null&&x.version===c.obu.version&&typeof x.key==="string"&&Rx(x.key)===i}function yx(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 Sx(q){return Cx(q)&&r(q.nativeHost)&&q.nativeHostManifests.every((x)=>yx(p8(x),q.nativeHost))}function Zx(q){return`#!/bin/sh
122
+ # Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
123
+ obu=${`'${q.replaceAll("'","'\\''")}'`}
124
+ case "$1" in
125
+ chrome-extension://*) exec "$obu" host --socket-dir ${Vq} ;;
126
+ mcp) shift; exec "$obu" mcp --socket-dir ${Vq} "$@" ;;
127
+ esac
128
+ exec "$obu" "$@"
129
+ `}function Gx(q){let x=p8(q),X=x?.allowed_origins;return x!==null&&x.name===Yq&&x.type==="stdio"&&Array.isArray(X)&&X.includes(`chrome-extension://${$8}/`)&&typeof x.path==="string"&&gq(x.path)}function Ax(q,x){if(!q.userChromeHost||!q.userChromeRegistration)return null;if(!x||Dx(q.userChromeHost)!==Zx(q.nativeHost)||!gq(q.userChromeHost))return{code:"user_chrome_browser_use_missing"};return Gx(q.userChromeRegistration)?{host:q.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var Vx={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 m(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=jx(x),b=Q!==null&&Q.platform===x&&JSON.stringify(Object.entries(Q.pins).sort())===JSON.stringify(Object.entries(P).sort()),J=[],L=T8(x);for(let N of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let y=L[N];if(!y)continue;let F=Bx(N,G(X.root,N,y.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:y.version})}let Z=Q?.pins.extension===i&&Sx(X);J.push({name:"browser_extension",state:Z?"ready":"missing",detail:i});let W=l("Xvfb"),U=l("x11vnc"),C=l("openbox");if(x!=="darwin-arm64"){J.push(r(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 y=Wx.filter((_)=>l(_)===null),F=(Q?.missing_system_packages??Fq).filter((_)=>Fq.includes(_)),K=y.length===0&&F.length===0;J.push(K?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...F,...y])].join(" ")});let $=I8.filter((_)=>l(_)===null);J.push($.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:$.join(" ")})}let R=X.ffmpeg&&r(X.ffmpeg)?X.ffmpeg:l("ffmpeg"),T=!R?null:R===X.ffmpeg?X.ffprobe:G(h8(e0(R)),"ffprobe"),Y=b&&J.every((N)=>N.state==="ready"),A=(N)=>b&&J.every((y)=>!Vx[N].includes(y.name)||y.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:T&&r(T)?T:null,userChrome:Ax(X,b&&["node","open_browser_use"].every((N)=>J.find((y)=>y.name===N)?.state==="ready")),pulseaudio:l("pulseaudio"),xvfb:W,x11vnc:U,openbox:C,components:J}}function hq(q){return Fx(q)?Kq():[]}function Fx(q){return q?.platform==="darwin-arm64"&&q.ffmpeg===G(q.root,"ffmpeg",k8.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=i0(X,{mode:384});try{let Z=P.body.getReader();for(let W=await Z.read();!W.done;W=await Z.read())if(b.update(W.value),!J.write(W.value))await a0(J,"drain")}finally{J.end(),await Xx(J)}let L=b.digest("hex");if(L!==x)throw Error(`digest mismatch for ${q}: expected ${x}, got ${L}`)}catch(P){throw qx(X,{force:!0}),P}}function v8(q){return G(Oq(q),"minimal.json")}function wx(q=o()){return n0(v8(q))}function fX(q={}){Ux(v8(q.home??o()),`${JSON.stringify({version:1,minimal_at:(q.now?.()??new Date).toISOString()})}
130
+ `)}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 wx(X)?null:"install"}import{execFile as kx,spawn as a8}from"child_process";import{existsSync as Ix}from"fs";import{connect as px}from"net";function Kx(){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=Kx();import{spawn as Mx}from"child_process";import{existsSync as zx}from"fs";import{connect as Yx}from"net";import{join as B8}from"path";var pq="reason_desktop",P8={sampleRate:48000,channels:2,codec:"opus"},_x=5000,Ex=107,$x=262144,r8=(q)=>B8(q,"native"),R8=(q)=>`unix:${q}`;function u8(q,x=1000){if(!zx(q))return Promise.resolve(!1);return new Promise((X)=>{let Q=Yx({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)>Ex||/["'\\\s]/.test(X))return null;try{if(await u8(X))return X;let Q=Mx(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()+_x;while(Date.now()<b){if(await u8(X))return X;if(P)return await u8(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 Ox=[79,103,103,83],Hx=Buffer.from("OpusHead"),fx=Buffer.from("OpusTags"),Iq=(q,x)=>q.byteLength>=x.byteLength&&x.every((X,Q)=>q[Q]===X);class c8 extends Error{constructor(q){super(q);this.name="OggProtocolError"}}class m8{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(Ox.some((R,T)=>x[Q+T]!==R)||x[Q+4]!==0)throw new c8("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,T)=>R+T,0),Z=27+b+L;if(x.byteLength-Q<Z)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 T=this.takePartial();if(T.byteLength>0&&!Iq(T,Hx)&&!Iq(T,fx))X.push(T)}W=!1,this.resetPartial()}if(C<U)this.appendPartial(x.subarray(C,U),W);Q+=Z}return this.buffer=x.slice(Q),X}appendPartial(q,x){if(x||q.byteLength===0)return;if(this.partialBytes+=q.byteLength,this.partialBytes>$x)throw new c8("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 gx}from"child_process";var cq=1048576,hx=String.raw`
131
+ import gi, json, os, sys
132
+ gi.require_version("Gtk", "3.0")
133
+ from gi.repository import Gtk, Gdk, GLib
134
+ if not Gtk.init_check()[0]:
135
+ sys.exit(1)
136
+ clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
137
+ pending = b""
138
+ generation = 0
139
+ def send(value):
140
+ print(json.dumps(value, ensure_ascii=True), flush=True)
141
+ def changed(clipboard, event):
142
+ global generation
143
+ generation += 1
144
+ current = generation
145
+ def received(clipboard, text, unused):
146
+ if current == generation and text is not None and len(text.encode("utf-8")) <= ${p}:
147
+ send({"text": text})
148
+ clipboard.request_text(received, None)
149
+ # No request_text on startup: never share the pre-existing clipboard.
150
+ clipboard.connect("owner-change", changed)
151
+ def input_ready(fd, condition):
152
+ global pending
153
+ chunk = os.read(fd, 65536)
154
+ if not chunk:
155
+ Gtk.main_quit()
156
+ return False
157
+ pending += chunk
158
+ while b"\n" in pending:
159
+ line, pending = pending.split(b"\n", 1)
160
+ text = json.loads(line)
161
+ if not isinstance(text, str) or len(text.encode("utf-8")) > ${p} or "\x00" in text:
162
+ sys.exit(1)
163
+ clipboard.set_text(text, -1)
164
+ send("ack")
165
+ if len(pending) > ${p*6+2}:
166
+ sys.exit(1)
167
+ return True
168
+ GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
169
+ send("ready")
170
+ Gtk.main()
171
+ `;function rq(q,x){let X=gx("/usr/bin/python3",["-I","-u","-c",hx],{env:{DISPLAY:q.display,XAUTHORITY:q.xauthority},stdio:["pipe","pipe","ignore"]}),Q=!1,P=!0,b="",J=0,L=[],Z=setTimeout(()=>U(),5000),W=()=>{Q=!0,clearTimeout(Z),L.length=0,X.kill("SIGKILL")},U=()=>{if(Q)return;W(),x.end({error:new S("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},C=(R,T=32)=>{if(Q)return;if(!P){R();return}if(J+=T,J>cq)W(),x.end({reason:"input_backpressure"});else L.push({apply:R,bytes:T})};return X.stdout.on("data",(R)=>{if(Q)return;b+=R.toString("ascii");for(let T=b.indexOf(`
172
+ `);T>=0;T=b.indexOf(`
173
+ `)){let Y=b.slice(0,T);b=b.slice(T+1);let A;try{A=JSON.parse(Y)}catch{U();return}if(A==="ready"||A==="ack"){clearTimeout(Z),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 T=`${JSON.stringify(R)}
174
+ `;C(()=>{if(P=!0,Z=setTimeout(()=>U(),5000),X.stdin.write(T),X.stdin.writableLength>cq)W(),x.end({reason:"input_backpressure"})},Buffer.byteLength(T))},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}},vx="avc1.4D002A",mq={width:1920,height:1080},ux=262144,cx=0.2,rx=250,mx=1e4,lx=1024,l8=1e4,dx=500,sx=60,ax=1e4,ix=1000,lq=1048576,X0={kind:"mac_screen",sound:null},nx,dq=()=>nx??=m()?.ffmpeg??null,i8=(q,x,X)=>a8(q,x,{env:X,stdio:["ignore","pipe","ignore"]}),ox,n8=()=>ox??=hq(m()),sq=(q,x,X)=>{let[Q,...P]=[...n8(),q];return i8(Q,[...P,...x],X)},aq=()=>L0?.videotoolbox?"h264_videotoolbox":"libx264",tx=()=>Math.round(performance.now()*1000),d8=new Set,iq=!1;function Q0(q){if(d8.add(q),q.once("exit",()=>d8.delete(q)),iq)return;iq=!0,process.once("exit",()=>{for(let x of d8)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{}},dx);q.once("exit",()=>clearTimeout(x))}function ex(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 q1(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 X1(q,x,X){let Q=a8(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=a8(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 Q1(q){let x=Math.min(1,mq.width/q.width,mq.height/q.height);return{width:Math.round(q.width*x),height:Math.round(q.height*x)}}function s8(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,Z=Math.max(1,Math.round(P.kbps*2/P.fps)),W=["-g",String(P.fps*sx)],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",`${Z}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",`${Z}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 P1(q,x){let X=px({path:q}),Q=Buffer.alloc(0),P="version",b=0,J=!1,L=[],Z=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(Z+=N.byteLength,Z>lq)U({reason:"input_backpressure"});else L.push(N);return}if(X.write(N),X.writableLength>lq)U({reason:"input_backpressure"})},T=(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 T(12),X.write(`RFB 003.007
175
+ `),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 T(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 y={width:Q.readUInt16BE(0),height:Q.readUInt16BE(2)};if(T(24+N),y.width===0||y.height===0)return C(),!1;P="messages",J=!0;for(let F of L)X.write(F);return L=[],Z=0,x.ready(y),!W}case"skip":{let N=Math.min(b,Q.byteLength);if(T(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 T(N),!0}case 2:return T(1),!0;case 3:{if(Q.byteLength<8)return!1;let N=Q.readUInt32BE(4);if(N>p/2)return T(8),P="skip",b=N,!0;if(Q.byteLength<8+N)return!1;let y=Q.subarray(8,8+N).toString("latin1");return T(8+N),x.clipboard(y),!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 S("display_unavailable","Reason could not reach this machine's desktop server.")})}),X.once("close",()=>U({reason:"display_closed"})),{pointer(N,y,F){let K=Buffer.alloc(6);K.writeUInt8(5,0),K.writeUInt8(F&255,1),K.writeUInt16BE(N,2),K.writeUInt16BE(y,4),R(K)},key(N,y){let F=Buffer.alloc(8);F.writeUInt8(4,0),F.writeUInt8(N?1:0,1),F.writeUInt32BE(y>>>0,4),R(F)},clipboard(N){if(Array.from(N).some((K)=>K.codePointAt(0)>255)){U({reason:"clipboard_unicode_unsupported"});return}let y=Buffer.from(N,"latin1"),F=Buffer.alloc(8);F.writeUInt8(6,0),F.writeUInt32BE(y.byteLength,4),R(Buffer.concat([F,y]))},close(){W=!0,X.destroy()}}}class o8{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 Z of b.splitter.push(L,Q()))for(let W of[...this.viewers])W.unit(Z)});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 b1(q){let x=nq.get(q);if(!x)nq.set(q,x=new o8);return x}function W0(q,x,X={}){let Q=X.micros??tx,P=new eq,b=x.request.preset,J=null,L=null,Z=null,W=!1,U=null,C=!1,R=!1,T=null,Y=0,A=0,N=!1,y=null,F=null,K=0,$=null,_=[],E=0,V=[],g=new Uint32Array(l8+1),v=0,w=null,O=0,k=0,I=0,bq=0,Jq=0,b8=null,V8=0,d={frames:0,bytes:0,since:Q()},s=[],q8=0,F8,w8=!1,z0=Q(),H={},a=()=>Math.round((Q()-z0)/1000),Nq=X.control??kq,K8=null,M8=null,h=(D)=>{let j=C8(D);return q.send(j),bq+=j.byteLength,j.byteLength},J8=(D)=>{if(q.done)return;if(q.open)h({type:"error",code:D});q.end({reason:D})},N8=()=>Math.max(ux,t[b].kbps*1000/8*cx),W8=()=>Q()/1000,Y0=()=>{while(V.length>1&&V[0].atMs<W8()-mx)V.shift();return V[0]?.rttMs??null},Wq=(D)=>{let j=Y0();if(j===null||_.length===0)return!1;let B=(j+rx)*D;return W8()-_[0].sentMs>B||E>B/1000*t[b].kbps*1000/8},_0=(D)=>{if(K===0)return;let j=Math.min(D,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(l8,Math.round(z))]++,v++,w=Math.min(w??z,z)}},E0=()=>{let D=0;for(let j=0;j<=l8;j++)if(D+=g[j],D*2>=v)return j;return 0},$0=()=>q.bufferedAmount<=N8()/2&&!Wq(0.5),Lq=()=>{w8=!0,s=[],q8=0,U?.leave(z8),U=null},jq=(D)=>{if(q.done)return;if(D.key)H.first_key_ms??=a();if(!W){if(!U||s.length===0&&!D.key)return;if(s.push(D),q8+=D.data.byteLength,q8>N8())Lq();return}if(N){k++;return}if(q.bufferedAmount>N8()||Wq(1)){N=!0,k++,y=setInterval(()=>{if(q.done||!$0())return;if(y)clearInterval(y);y=null,N=!1,_8()},X.drainPollMs??25);return}if(!C){if(!D.key){k++;return}if(h({type:"hello",width:L.width,height:L.height,fps:t[b].fps,preset:b,codec:vx}),C=!0,H.first_frame_ms??=a(),!R&&J?.sound)h({type:"audioHello",...P8}),R=!0}let j=h({type:"frame",key:D.key,seq:K,captureMicros:D.micros,data:D.data});if(_.push({seq:K,sentMs:W8(),bytes:j}),E+=j,_.length>lx)E-=_.shift().bytes;K++,O++,b8??=D.micros,V8=D.micros,d.frames++,d.bytes+=j},z8={started(D){b=D,C=!1,s=[],q8=0},unit:jq,failed:()=>J8("encoder_failed")},Y8=()=>{let D=(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(!D&&!M){J8("encoder_failed");return}if(U??="kind"in j&&j.kind==="mac_screen"?b1(X.spawn??sq):new o8,H.encoder_ms===void 0)H.encoder_ms=a(),H.encoder_shared=U.running;U.start(z8,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 X1(D,s8(b,x1(Math.min(z,30)),x8,(X.macEncoder??aq)()),j)}return"kind"in j?(X.spawn??sq)(D,s8(b,q1(z),Q1(B),(X.macEncoder??aq)()),{}):(X.spawn??i8)(D,s8(b,ex(z,B,j.display),B),{DISPLAY:j.display,XAUTHORITY:j.xauthority})},Q)},L8=()=>{if(!T)return;P0(T.child),T=null},O0=()=>{let D=(X.ffmpeg??dq)();if(T||q.done||!R||!J?.sound||!D)return;let j;try{j=(X.spawn??i8)(D,uq(),{PULSE_SERVER:R8(J.sound)})}catch{return}Q0(j);let B={child:j,reader:new m8};T=B,j.stdout?.on("data",(z)=>{if(T!==B||q.done)return;let u;try{u=B.reader.push(z)}catch{L8();return}let x8=Q();for(let H0 of u){if(q.bufferedAmount>N8()){A++;continue}h({type:"audio",captureMicros:x8,data:H0}),Y++}});let M=()=>{if(T===B)L8()};j.once("exit",M),j.once("error",M)},_8=()=>{if(!U||q.done)return;I++,Y8()},Uq=()=>{if(q.done||!L)return;if(!W){if(U||w8)return;Y8(),F8=setTimeout(()=>{if(!W)Lq()},ax);return}if(clearTimeout(F8),H.encoder_early===void 0){if(H.encoder_early=U!==null,w8)H.hold_lapsed=!0}if(!U)Y8();let D=s;s=[],q8=0;for(let j of D)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}},ix)};x.desktop.then((D)=>{if(q.done)return;J=D;let j={ready(B){L=B,H.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 D&&D.kind==="simulator")Z=D.input,j.ready(D.points);else if("kind"in D)Z=(X.macInput??((B)=>x0(B,n8())))(j);else{let B=(X.linuxClipboard??rq)(D,j),M=P1(D.rfbSocket,{...j,clipboard:(z)=>{if(!B)j.clipboard(z)}});Z=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}Dq()},(D)=>q.end({error:D}));function Dq(){if(M8||!x.viewerSameNetwork||!W||q.done||!J||!("kind"in J)||J.kind!=="mac_screen")return;M8=(X.macWindows??q0)((D)=>{if(q.open)h({type:"windows",bounds:D})})}let Tq={viewer:x.viewer??null,notify(D){if(q.open)h({type:"control",control:D})}},E8=(D)=>{if(!Z)return;if(!J||!("kind"in J)||J.kind!=="simulator")Nq.claim(Tq);D(Z)};return{opened(){H.relay_ms??=a()},received(D){Jq+=D.byteLength;let j;try{j=P.push(D)}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":E8((M)=>M.pointer(B.x,B.y,B.buttons));break;case"key":E8((M)=>M.key(B.down,B.keysym));break;case"clientClipboard":E8((M)=>M.clipboard(B.text));break;case"config":if(B.preset!==b)b=B.preset,_8();break;case"keyframeRequest":if(C&&!N)_8();break;case"ack":_0(B.seq);break;case"audioEnable":if(B.on)O0();else L8();break;default:break}}if(!W&&!q.done){if(W=!0,H.viewer_ms=a(),x.viewer)K8=Nq.join(Tq);Uq(),Dq()}},close(){if(K8?.(),K8=null,M8?.close(),y)clearInterval(y);if(F)clearInterval(F);clearTimeout(F8),U?.leave(z8),L8(),Z?.close()},summary:()=>({output_bytes:bq,input_bytes:Jq,video:{preset:b,frames:O,dropped:k,restarts:I,avg_fps:b8!==null&&V8>b8?Math.round((O-1)/((V8-b8)/1e6)*10)/10:0,min_rtt_ms:Math.round(w??0),p50_rtt_ms:v?E0():0,audio_packets:Y,audio_dropped:A,connect:H}})}}var oq=null,L0=null,J1=null;function N1(){let q=m();return q?.features.display?q.ffmpeg:null}function j0(q){return oq??=new Promise((x)=>{kx(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=[m()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((X)=>Boolean(X&&Ix(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??N1)();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():J1??=f8(n8());return Promise.all([Q,P]).then(([b,J])=>(b.x264||b.videotoolbox)&&J?.screen===!0&&J.accessibility)}import{existsSync as t8,realpathSync as y0,statSync as W1}from"fs";import{platform as L1}from"os";import{isAbsolute as S0,sep as j1}from"path";var U1=43200000,D0=R0,D1=4,T1=/^[A-Za-z0-9._:-]{1,160}$/,B1=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(B1,Math.max(1,Math.floor(q)))}function R1(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 S("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 S("invalid_pty_request","Reason terminal relay URL is missing.");let L;try{L=new URL(P)}catch{throw new S("invalid_pty_request","Reason terminal relay URL is invalid.")}if(L.protocol!=="wss:"&&L.protocol!=="ws:"||L.username||L.password)throw new S("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof b!=="string"||!T1.test(b))throw new S("invalid_pty_request","Reason terminal session identity is invalid.");let Z=typeof J==="string"?Date.parse(J):Number.NaN;if(!Number.isFinite(Z)||Z<=x)throw new S("invalid_pty_request","Reason terminal session has already expired.");if(q.cwd!==void 0&&typeof q.cwd!=="string")throw new S("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 S("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:P,session_id:b,expires_at:new Date(Math.min(Z,x+U1)).toISOString(),cols:S8(q.cols,80),rows:S8(q.rows,24),...q.cwd===void 0?{}:{cwd:q.cwd},...W?{workspace:W}:{}}}function C1(q,x){return x===q||x.startsWith(q+j1)}function T0(q,x){if(x===void 0)return q;if(!S0(x))throw new S("pty_cwd_invalid","Reason terminal working directory must be absolute.");let X;try{X=y0(x)}catch{throw new S("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!C1(q,X))throw new S("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!W1(X).isDirectory())throw new S("pty_cwd_invalid","Reason terminal working directory is not a directory.");return X}function y1(q=process.env){let x=q.SHELL;if(x&&S0(x)&&t8(x))return x;for(let X of L1()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(t8(X))return X;return"/bin/sh"}function S1(){let q=globalThis.Bun;if(!q)throw new S("pty_unavailable","Reason terminals require the Bun runtime.");return q.spawn}function T9(){return typeof globalThis.Bun<"u"}var Z1=(q)=>{let x=S1()({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 S("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)}},e8=(q,x)=>{return x===void 0?new WebSocket(q):new WebSocket(q,{proxy:x})},y8=new Set;function G1(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=R1(q.payload,X()),P=G1(q.operationId);if(!P)throw new S("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let b=X(),J,L,Z;try{let W=Q.workspace?C0(q.root,Q.workspace):void 0;J=W?T0(t8(W.boundary)?y0(W.boundary):W.boundary,W.path):T0(q.root,Q.cwd),L=x.environment??process.env,Z=x.shellPath??y1(L)}catch(W){throw P(),W}return await new Promise((W,U)=>{let C=null,R=null,T=!1,Y=!1,A=!1,N=null,y=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:y,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 S?w:new S("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(y+=w.byteLength,!T||!R){if(K.push(w),$+=w.byteLength,$>D0)E({kind:"resolved",reason:"output_backpressure"});return}try{R.send(w)}catch{E({kind:"resolved",reason:"relay_closed"});return}if(R.bufferedAmount>D0)E({kind:"resolved",reason:"output_backpressure"})};try{C=(x.spawnPty??Z1)({shell:Z,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 S?w:new S("pty_spawn_failed","Reason could not start the terminal shell.")});return}C.exited.then((w)=>{if(A)return;if(N=w,T&&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??e8)(Q.relay_url,v)}catch{E({kind:"rejected",error:new S("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}R.binaryType="arraybuffer",R.onopen=()=>{if(A||!R)return;T=!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 S("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 S("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}var E1=43200000,G8=":99",$1=60000,A8=15000,Xq={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 S("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 S("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 S("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof q.session_id!=="string"||!O1.test(q.session_id))throw new S("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 S("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")&&m()?.features.display===!0}async function $9(){if(process.platform!=="darwin")return h1();return await U0()}function Qq(q){M1(q,{recursive:!0,mode:448});let x=K1(q);if(!x.isDirectory()||x.isSymbolicLink()||process.getuid&&x.uid!==process.getuid())throw new S("display_unavailable","Reason desktop state directory is not private.");F1(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 K0(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),A8).unref()})}var qq=null;function I1(q=o()){return qq??=p1(q).finally(()=>{qq=null}),qq}async function p1(q){let x=m({home:q});if(!x?.xvfb||!x.x11vnc||!x.openbox)throw new S("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=f(x.root,"display");Qq(X);let Q=await u1(q,X,x.x11vnc);if(Q)return Q;let P={display:G8,xauthority:f(X,"Xauthority"),rfbSocket:f(X,"rfb.sock")},b=f(X,"pulse"),J=(async()=>{try{Qq(b)}catch{return null}return await vq(b,x.pulseaudio)})(),L={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:P.display,XAUTHORITY:P.xauthority};if(x.pulseaudio)L.PULSE_SERVER=R8(r8(b));let Z=async()=>({...P,sound:await J});if(await e({path:P.rfbSocket},!0))return await Z();if(!w1(P.xauthority))xq(P.xauthority,k1(G8.slice(1),V1(16)),{mode:384,flag:"wx"});let W=c1(f(X,"theme"),P.display),U={path:`/tmp/.X11-unix/X${G8.slice(1)}`};if(!await e(U,!1)){if(Pq(x.xvfb,[P.display,"-screen","0",`${Xq.width}x${Xq.height}x24`,"-nolisten","tcp","-auth",P.xauthority],L),!await K0(()=>e(U,!1),A8))throw new S("display_unavailable","Reason could not start the virtual display.");Pq(x.openbox,["--config-file",W.openboxConfig],L)}if(await r1(W,L),!await M0(x.x11vnc,P,X,"x11vnc.log",L))throw new S("display_unavailable","Reason could not start the desktop server.");return await Z()}async function M0(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",f(X,Q)],P);if(b!==null&&b!==0)return!1;return await K0(()=>e({path:x.rfbSocket},!0),A8)}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)=>A1("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(b,J)=>b?P(b):Q(J)));return x(Object.fromEntries(X.split(`
176
+ `).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??f(q,".Xauthority"),rfbSocket:f(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 M0(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
177
+ `),null}function c1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=Aq({root:q,display:x,screen:Xq,browserExec:X});for(let P of["","openbox","tint2","picom"])Qq(f(q,P));for(let[P,b]of Object.entries(Q.files))xq(f(q,P),b,{mode:384});for(let[P,b]of Object.entries(Gq))xq(f(q,`ara-${P}`),z1(b),{mode:384});return{root:q,openboxConfig:f(q,"openbox","rc.xml"),start:Q.start}}async function r1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
178
+ `);await new Promise((Q)=>{let P=w0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},A8);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 S("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 S("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 m1(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 m1(q,x,X,Q,P,b){let J=Q();return new Promise((L,Z)=>{let W=null,U=!1,C=!1,R,T,Y,A=!1,N=null,y=(V)=>{if(C)return;if(N)V=N;C=!0,clearTimeout(R),clearTimeout(T),q.removeEventListener("abort",K),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in V){Z(V.error);return}L({reason:V.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},F=()=>y({error:new S("display_relay_unavailable","Reason could not reach the desktop relay.")}),K=()=>{let V=q.reason;y({error:V instanceof S?V:new S("cancelled","Reason closed the desktop session.")})},$=()=>{if(!N||!W)return;let V=N.error;try{W.send(b(V instanceof S?V.code:"display_unavailable"))}catch{}y(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{y({reason:"relay_closed"})}},end:(V)=>{if(C||N)return;if(!("error"in V)){y(V);return}if(N=V,A&&U)$()}}),C){Y.close();return}if(q.aborted){K();return}q.addEventListener("abort",K,{once:!0}),R=setTimeout(()=>y({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),T=setTimeout(()=>y({reason:"viewer_absent"}),X.viewerWaitMs??$1);try{W=(X.connect??e8)(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(T),A=!0,N){$();return}Y?.received(v)},W.onclose=()=>{if(C)return;if(!U){F();return}y({reason:"relay_closed"})},W.onerror=()=>{if(C||U)return;F()}})}
179
+ export{U1 as $d,D0 as ae,D1 as be,T9 as ce,B9 as de,$8 as ee,PX as fe,NX as ge,i as he,R8 as ie,Q9 as je,U0 as ke,Vq as le,Hq as me,m as ne,HX as oe,fX as pe,gX as qe,E1 as re,G8 as se,g1 as te,h1 as ue,$9 as ve,Qq as we,I1 as xe,O9 as ye};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ class o extends Error{code;constructor(a,r){super(r);this.code=a;this.name="LocalCapabilityError"}}
3
+ export{o as Gh};
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{Jd as UJ,_c as CJ,gd as qJ}from"./vm-hands-entry-lite-gqncr2j0.js";import{createHash as v,randomBytes as t}from"crypto";import{closeSync as QJ,fsyncSync as FJ,mkdirSync as kJ,openSync as WJ,renameSync as SJ,rmSync as gJ,statSync as BJ,writeSync as PJ,constants as S}from"fs";import{join as V}from"path";var HJ=1;var d=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function e(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 jJ(J,Z){let{payload:z,authority:G}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!G||typeof G!=="object"||Array.isArray(G)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||G.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 NJ(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"&&d.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:e(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var g=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),y=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function R(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(R).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${R(J[Z])}`).join(",")}}`}async function aJ(J){let Z=await crypto.subtle.importKey("pkcs8",y(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=y(J.device_key.spki),G=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),N=new Uint8Array(await crypto.subtle.exportKey("spki",G.publicKey)),D=v("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:G,signingSpki:z,agreementSpki:N,fingerprint:D}}class VJ{init;keys;hooks;options;state="identity_free";lastBrainGeneration=0;bound=null;servedRun=!1;verifiedSinceRun=!1;envDirectory=null;constructor(J,Z,z,G){this.init=J;this.keys=Z;this.hooks=z;this.options=G;if(!d.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(){return this.state}get boundRunId(){return this.state==="bound"?this.bound?.runId??null:null}canSpawn(J){return this.state==="bound"&&this.bound?.runId===J&&this.bound.envInstalled}async registerFrame(J){if(this.state!=="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:HJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:g(this.keys.signingSpki),env_public_key:g(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:g(t(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(R(Z)));return{...Z,device_signature:g(z)}}async helloFrame(J,Z){if(this.state==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),G=g(t(32)),N=UJ({method:"GET",pathAndQuery:CJ,timestamp:z,nonce:G,challenge:J,bodySha256:v("sha256").update("").digest("hex")}),D=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(N)));return{t:"hello",timestamp:z,nonce:G,signature:g(vJ(D)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.state!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.state="registered"}async bind(J){if(this.state!=="registered")throw new W("vm_hands_not_registered","bind before register or while bound");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let G of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(G))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=this.lastBrainGeneration)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(R({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");this.lastBrainGeneration=J.brain_generation;let z=null;try{if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload();this.verifiedSinceRun=!1;let{launchId:G,applied:N,readyData:D}=await this.hooks.startExecutor({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}),B=this.hooks.restatLayout(),M=null;if(J.env){let A=J.claim?.owner??{},x=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof A.device_id==="string"?A.device_id:"",rootId:J.claim?.root_id??""});M=this.hooks.installEnvironment(x),z=this.writeJobEnvRootOnly(J.bind_id,x)}return this.servedRun=!0,this.bound={bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:G,envInstalled:M!==null,rootId:J.claim?.root_id??""},this.state="bound",{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:G,snapshot_revision:M,layout:B,...D?{ready_data:D}:{},policy_digest:v("sha256").update(R({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(G){if(this.servedRun=!0,z)this.shred();let N=G&&typeof G==="object"&&"code"in G&&typeof G.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(G.code)?G.code:"vm_hands_bind_failed";throw G instanceof W?G:new W(N,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound;if(this.state!=="bound"||!Z)throw new W("vm_hands_not_bound","environment delivered while not bound");if(J.attemptId!==Z.bindId)throw new W("vm_hands_env_invalid","environment for another attempt");if(!d.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 G=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),N=this.hooks.installEnvironment(G);return Z.envInstalled=!0,this.shred(),this.writeJobEnvRootOnly(`${Z.bindId}-r${N}`,G),{snapshot_id:J.snapshotId,installed_revision:N,installed:!0}}async attestFrame(J,Z){if(this.state==="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");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(){return this.hooks.executorExited?.()??new Promise(()=>{})}async boundRefused(){await this.unbind()}async unbind(){let J=this.bound?.bindId??null;return this.state="unbinding",this.bound=null,await this.hooks.killAndVerifyPayload(),this.verifiedSinceRun=!0,this.shred(),this.state="registered",{bind_id:J,killed_verified:!0,shredded:!0,srt_fallbacks:this.hooks.takeSrtFallbacks?.()??null}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},G=await crypto.subtle.importKey("spki",y(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),N=await crypto.subtle.deriveKey({name:"ECDH",public:G},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),D=await crypto.subtle.decrypt({name:"AES-GCM",iv:y(J.iv),additionalData:new TextEncoder().encode(Z)},N,y(J.ct)).catch(z),B=JSON.parse(new TextDecoder().decode(D));if(!B||typeof B!=="object"||Array.isArray(B))throw new W("vm_hands_env_invalid","env not an object");return B}writeJobEnvRootOnly(J,Z){let z=V(this.options.envRoot,`bind-${J}`);kJ(z,{mode:448});let G=BJ(z);if(!G.isDirectory()||(G.mode&63)!==0||G.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let N=Z.variables&&typeof Z.variables==="object"?Z.variables:{},D=Object.entries(N).filter(([A,x])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof x==="string").map(([A,x])=>`export ${A}='${String(x).replaceAll("'","'\\''")}'`).join(`
3
+ `)+`
4
+ `,B=V(z,`.job.env.${t(8).toString("hex")}`),M=WJ(B,S.O_WRONLY|S.O_CREAT|S.O_EXCL|S.O_NOFOLLOW,384);try{PJ(M,D),FJ(M)}finally{QJ(M)}return SJ(B,V(z,"job.env")),this.envDirectory=z,V(z,"job.env")}shred(){let J=this.envDirectory;if(this.envDirectory=null,!J)return;try{let Z=V(J,"job.env"),z=BJ(Z).size,G=WJ(Z,S.O_WRONLY|S.O_NOFOLLOW);try{PJ(G,Buffer.alloc(z)),FJ(G)}finally{QJ(G)}}catch{}gJ(J,{recursive:!0,force:!0})}}function vJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(N)=>{let D=0;while(D<N.length-1&&N[D]===0)D++;let B=N.subarray(D),M=B[0]&128?Uint8Array.of(0,...B):B;return Uint8Array.of(2,M.length,...M)},z=Z(J.subarray(0,32)),G=Z(J.subarray(32));return Uint8Array.of(48,z.length+G.length,...z,...G)}import{randomUUID as yJ}from"crypto";var RJ="/app/local-runtime/session?register=vm_hands_v1",fJ="/app/local-runtime",DJ=25000,bJ=20000,mJ=1e4,cJ=5000,pJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),JJ=75000,lJ=1e4,u=20000;class h extends Error{}var dJ=64;async function AJ(J){let Z=[...J.modelOps];for(let z of Z)z.abort.abort();await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,cJ))])}async function f(J,Z){return await AJ(J),Z.unbind()}function o(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var LJ=15000,uJ=1e4;async function zZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turn:null,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],flush:null,modelOps:new Set},G=J.log??(()=>{}),N=async(D)=>{let B=z.turn;if(!B)return;z.turn=null,o(B);let M=await f(z,J.agent).catch(()=>null);if(M)z.receipts.push({turn:B,failure:"vm_hands_bind_lost",unbound:M});G("vm_hands.bound_dropped",{reason:D})};try{for(let D=0;!J.signal.aborted;D++){let B=await oJ(J,z).catch((A)=>{if(A instanceof W&&z.deviceId===null&&A.code==="vm_hands_no_session"&&Date.now()-Z<lJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(A instanceof W&&z.deviceId===null)throw A;return{closeCode:0,closeReason:A instanceof Error?A.message:String(A)}});if(G("vm_hands.session_closed",{close_code:B.closeCode,reason:B.closeReason.slice(0,120),registered:z.deviceId!==null}),B.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turn&&Date.now()-z.lostAt>=JJ)await N("reconnect_deadline");let M=B.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(D,5),2000):z.turn?Math.min(250*2**Math.min(D,5),5000,Math.max(0,z.lostAt+JJ-Date.now())):Math.min(500*2**D,30000);if(await new Promise((A)=>setTimeout(A,M)),z.turn&&Date.now()-z.lostAt>=JJ)await N("reconnect_deadline")}}finally{await N("session_ended")}}async function oJ(J,Z){let z=Z.deviceId,G=J.log??(()=>{}),N=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:RJ,D=`${J.apiOrigin.replace(/^http/,"ws")}${N}`,B=new WebSocket(D),M=0,A="",x=new Map,i=[],b=null,MJ=new Promise(($)=>{B.onclose=(K)=>{M=K.code,A=K.reason;for(let Y of x.values())Y.reject(new h(`session closed ${K.code}`));for(let Y of Z.attestWaiters.splice(0))Y(!1);x.clear(),$()}});B.onmessage=($)=>{let K;try{K=JSON.parse(String($.data))}catch{B.close(4400);return}if(K.t==="res"){let Y=K;x.get(Y.id)?.resolve({status:Y.status,body:Y.body}),x.delete(Y.id);return}if(!b?.(K))i.push(K)};let m=($,K)=>new Promise((Y,F)=>{let P=i.findIndex((C)=>$.includes(C.t));if(P>=0){Y(i.splice(P,1)[0]);return}let U=setTimeout(()=>{b=null,F(new W("vm_hands_no_register",`no ${$.join("/")} in ${K} ms`))},K);b=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(U),b=null,Y(C),!0}}),c=($)=>B.send(JSON.stringify($)),w=($,K)=>new Promise((Y,F)=>{if(B.readyState!==WebSocket.OPEN){F(new h("session closed"));return}let P=yJ(),U=typeof K.wait_ms==="number"?K.wait_ms:0,C=setTimeout(()=>{if(!x.delete(P))return;F(new h(`no answer to ${$.split("/").pop()} in ${U+LJ} ms`)),B.close(4000,"request_timeout")},U+LJ);x.set(P,{reject:(X)=>{clearTimeout(C),F(X)},resolve:({status:X,body:Q})=>{clearTimeout(C);let j=null;try{j=Q?JSON.parse(Q):null}catch{}Y({status:X,json:j})}}),c({t:"req",id:P,path:`${fJ}${$}`,body:JSON.stringify(K)})}),ZJ=()=>B.close(1001,"stopping");J.signal.addEventListener("abort",ZJ,{once:!0});let r,p={turn:null},T=null,$J=!1,s=new Set,n=!1,l=!1;try{await new Promise((X,Q)=>{let j=setTimeout(()=>Q(Error("session open timeout")),uJ);B.onopen=()=>{clearTimeout(j),G("vm_hands.ws_open",{}),X()},B.onerror=()=>{clearTimeout(j),Q(Error("session socket error"))}});let $=await m(["challenge"],5000);G("vm_hands.challenge",{});let K=null,Y=null,F=null,P;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let X=await m(["ready"],1e4);if(typeof X.vm_hands_connection==="string")Z.connection=X.vm_hands_connection;if(P={device_id:z,...X.cadence?{cadence:X.cadence}:{}},typeof X.vm_hands_probe_script==="string"){if(F=X.vm_hands_probe_script,l=!0,J.agent.phase==="registered"&&!Z.turn)Z.attest="pending"}if(G("vm_hands.reconnected",{device_id:z}),Z.turn){let Q=X.vm_hands_bind;if(Q&&Q.operation_id===Z.turn.claim.operation_id&&Q.attempt_id===Z.turn.claim.attempt_id)K=Z.turn,G("vm_hands.bound_resumed",{operation_id:Q.operation_id});else{Y=Z.turn,Z.turn=null,o(Y);let j=await f(Z,J.agent).catch(()=>null);if(j)Z.receipts.push({turn:Y,failure:"vm_hands_bind_lost",unbound:j});G("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}}else{c(await J.agent.registerFrame($.challenge)),G("vm_hands.register_sent",{});let X=await m(["registered","register_refused"],1e4);if(X.t==="register_refused")throw new W(X.code,"register refused");J.agent.registered();let Q=X;if(P=Q,Z.deviceId=Q.device_id,typeof Q.vm_hands_connection==="string")Z.connection=Q.vm_hands_connection;if(typeof Q.vm_hands_probe_script==="string"){if(F=Q.vm_hands_probe_script,l=!0,J.agent.phase==="registered"&&!Z.turn)Z.attest="pending"}G("vm_hands.registered",{device_id:P.device_id})}let U=async()=>{let X=await w("/heartbeat",await J.heartbeat());if(X.status>=300)throw Error(`heartbeat ${X.status}`)};await U();let C=P.cadence?.presence_interval_ms??30000;if(r=setInterval(()=>{U().catch(()=>B.close())},C),F&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turn)IJ(F,$.challenge);try{if(await KJ(),K){let X=K;Z.flush=()=>zJ(X),Z.flush(),T=GJ(X).catch(async(Q)=>{await a(Q),B.close()}).finally(()=>{T=null})}while(!J.signal.aborted&&B.readyState===WebSocket.OPEN){let X=await w("/operations/claim",{wait_ms:Math.min(P.cadence?.claim_wait_ms??DJ,DJ)});if(X.status===204||!X.json)continue;if(X.status>=300)throw Error(`claim ${X.status}`);let Q=X.json;if(Q.capability==="hands.connect"){if(T){_({claim:Q,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}T=EJ(Q).catch(async(j)=>{await a(j),B.close()}).finally(()=>{T=null})}else _J(Q).catch(()=>{return})}}catch(X){await a(X)}}finally{if(r)clearInterval(r);if(J.signal.removeEventListener("abort",ZJ),Z.flush=null,B.close(),await MJ,await T,(J.agent.phase==="bound"||J.agent.phase==="unbinding")&&!Z.turn){let $=await f(Z,J.agent).catch(()=>null),K=p.turn;if($&&K)Z.receipts.push({turn:{...K,eventSeq:K.eventSeq+1},failure:"vm_hands_bind_lost",unbound:$});G("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of s)$.abort()}return{closeCode:M,closeReason:A};async function a($){if($J)return;if($J=!0,Z.turn&&$ instanceof h)Z.lostAt=Date.now();else{let K=Z.turn;if(Z.turn=null,K)o(K),J.onTurn?.(null);if(J.agent.phase==="bound"||J.agent.phase==="unbinding"){let Y=await f(Z,J.agent).catch(()=>null),F=p.turn;if(Y&&F)Z.receipts.push({turn:{...F,eventSeq:F.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Y})}}G("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turn!==null})}function _($){let K=$.claim,Y={attempt_id:K.attempt_id,attempt_token:K.attempt_token},F=encodeURIComponent(K.operation_id);return{fence:Y,op:F,complete:(U,C={})=>w(`/operations/${F}/complete`,{...Y,status:U,...C}),emit:(U,C)=>{let X=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>P(U,C));return $.chain=X,X}};async function P(U,C){let X=$.eventSeq,Q=(L)=>w(`/operations/${F}/events`,{...Y,event_seq_start:L,events:[{kind:U,payload:{sequence:L,capability:String(K.capability??"hands.connect"),data:C}}]}),j=X,E=await Q(j),I=E.status===409?E.json?.expected_event_seq:void 0;if(typeof I==="number"&&I===X+1)E={status:200,json:{duplicate:!0}};else if(typeof I==="number"&&I>=0&&I!==X)j=I,E=await Q(j);if(E.status<300)$.eventSeq=j+1;return E}}function xJ($){return(K,Y)=>new Promise((F,P)=>{if(Z.turn!==$){P(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=dJ){P(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:K,data:Y,resolve:F,reject:P}),Z.flush?.()})}function zJ($){if(n)return;n=!0,(async()=>{try{while($.outbox?.length&&Z.turn===$&&B.readyState===WebSocket.OPEN){let K=$.outbox[0],Y;try{Y=await _($).emit(K.kind,K.data)}catch(F){if(F instanceof h)return;Y={status:500}}if($.outbox.shift(),Y.status<300)K.resolve();else K.reject(Error(`${K.kind} refused ${Y.status}`))}}finally{n=!1}})()}async function IJ($,K){try{let Y=await J.agent.attestFrame($,K);if(B.readyState!==WebSocket.OPEN)return;c(Y);let F=await m(["attested","attest_refused"],15000);Z.attest=F.t==="attested"?"accepted":"refused";for(let P of Z.attestWaiters.splice(0))P(Z.attest==="accepted");if(G("vm_hands.attest",{result:Z.attest,exit_code:Y.exit_code,...F.t==="attest_refused"?{code:String(F.code??"")}:{}}),Z.attest==="refused")B.close(4401,"attest_refused")}catch(Y){G("vm_hands.attest_failed",{code:Y instanceof W?Y.code:"probe_error"});for(let F of Z.attestWaiters.splice(0))F(!1);if(Z.attest!=="accepted")B.close(4000,"attest_unanswered")}}async function EJ($){let K=l&&Z.attest==="pending",Y=$.vm_hands_attest,F=Y;if(Z.attest==="refused"){G("vm_hands.claim_attest_refused",{said:typeof Y==="string"?Y.slice(0,16):typeof Y,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(F==="accepted"){if(!K&&Z.attest!=="accepted"){Z.attest="accepted";for(let L of Z.attestWaiters.splice(0))L(!0)}}else if(F!=="pending"||!K){G("vm_hands.claim_attest_refused",{said:typeof Y==="string"?Y.slice(0,16):typeof Y,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let L=Date.parse($.lease_until)-Date.now()-5000,H=Math.max(0,Math.min(u,Number.isFinite(L)?L:u));if(!await new Promise((q)=>{let O=setTimeout(()=>q(!1),H);Z.attestWaiters.push((k)=>{clearTimeout(O),q(k)})})){await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let P={claim:$,eventSeq:0},{complete:U,emit:C}=_(P),X;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");X=!e($)}catch(L){G("vm_hands.bind_refused",{code:L instanceof W?L.code:"unexpected"}),await U("failed",{error_code:L instanceof W?L.code:"vm_hands_bind_invalid"});return}let Q;try{Q=await J.agent.bind(NJ($))}catch(L){G("vm_hands.bind_refused",{code:L instanceof W?L.code:"unexpected"}),await U("failed",{error_code:L instanceof W?L.code:"vm_hands_bind_failed"});return}let j={...Q.ready_data??J.readyData({launchId:Q.launch_id,claim:$})};if(X)delete j.environment_installed;p.turn={claim:$,launchId:Q.launch_id,readyData:j,eventSeq:P.eventSeq,ackSeq:-1};let E=await C("hands.ready",{...j,vm_hands:{layout:Q.layout,policy_digest:Q.policy_digest,launch_id:Q.launch_id}});if(p.turn=null,E.status>=300){await AJ(Z),await J.agent.boundRefused(),await U("failed",{error_code:String(E.json?.error??"vm_hands_probe_failed")});return}let I={claim:$,launchId:Q.launch_id,readyData:j,eventSeq:P.eventSeq,ackSeq:-1};Z.turn=I,Z.flush=()=>zJ(I),J.onTurn?.(xJ(I)),await GJ(I)}async function GJ($){let{fence:K,op:Y}=_($),F=null,P=null,U=J.agent.executorExited().then((C)=>{return P=C,null});J:for(;;){let C=await Promise.race([U,w(`/operations/${Y}/heartbeat`,{...K,control_ack_seq:$.ackSeq,wait_ms:bJ})]);if(!C){F="vm_hands_executor_exited",G("vm_hands.executor_exited",{reason:P});break}if(C.status>=300)break;let X=(C.json?.controls??[]).slice().sort((Q,j)=>Q.seq-j.seq);for(let Q of X){if(Q.seq<=$.ackSeq)continue;if(Q.kind==="operation.cancel"||Q.kind==="cancel"){$.ackSeq=Q.seq;break J}if(Q.kind===qJ)try{await wJ($,Q.payload??{})}catch(j){if(j instanceof h)throw j;F=j instanceof W?j.code:"environment_unavailable",G("vm_hands.environment_refused",{code:F});break J}$.ackSeq=Q.seq}}await OJ($,F)}async function _J($){let K=$,Y={claim:K,eventSeq:0},{complete:F,emit:P,fence:U,op:C}={..._(Y)},X=$.vm_hands_origin==="person"?"person":"model",Q=String($.capability??"");if(!J.executeOp){await F("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(l&&Z.attest==="pending")){Z.attest="accepted";for(let q of Z.attestWaiters.splice(0))q(!0)}if(Z.attest!=="accepted"){let q=Date.parse(String($.lease_until??""))-Date.now()-5000,O=Z.attest==="refused"?0:Math.max(0,Math.min(u,Number.isFinite(q)?q:u));if(!(O>0&&await new Promise((XJ)=>{let hJ=setTimeout(()=>XJ(!1),O);Z.attestWaiters.push((TJ)=>{clearTimeout(hJ),XJ(TJ)})}))){await F("failed",{error_code:"vm_hands_unattested"});return}}if(X==="model"&&(J.agent.phase!=="bound"||J.agent.boundRunId!==K.run_id)){await F("failed",{error_code:"vm_hands_not_bound"});return}if(pJ.has(Q)&&J.agent.phase!=="bound"){await F("failed",{error_code:"vm_hands_not_bound"});return}let j=new AbortController;s.add(j);let E,I=new Promise((q)=>{E=q}),L={abort:j,settled:I};if(X==="model")Z.modelOps.add(L);let H=-1,YJ=setInterval(()=>{w(`/operations/${C}/heartbeat`,{...U,control_ack_seq:H,wait_ms:0}).then((q)=>{if(q.status>=300){j.abort();return}let O=q.json?.controls??[];for(let k of O)if(H=Math.max(H,k.seq),k.kind==="operation.cancel"||k.kind==="cancel")j.abort()},()=>j.abort())},mJ);try{let q=await J.executeOp({kind:X,claim:$,signal:j.signal,emit:async(O)=>{await P(O.kind,O.data??{})}});await F(q.status,{...q.result?{result:q.result}:{},...q.error_code!==void 0?{error_code:q.error_code}:{}}),G("vm_hands.op",{capability:Q,kind:X,status:q.status,code:q.error_code??null})}finally{clearInterval(YJ),s.delete(j),Z.modelOps.delete(L),E()}}async function OJ($,K){if(Z.turn===$)Z.turn=null;J.onTurn?.(null),o($);let Y=await f(Z,J.agent);Z.receipts.push({turn:$,failure:K,unbound:Y}),await KJ()}async function KJ(){while(Z.receipts.length){let{turn:$,failure:K,unbound:Y}=Z.receipts[0],{complete:F,emit:P}=_($);try{if(await P("hands.stopped",{...$.readyData,reason_code:K?"failed":"cancelled",killed_verified:Y.killed_verified,shredded:Y.shredded,...Y.srt_fallbacks?{vm_hands_srt_fallbacks:Y.srt_fallbacks}:{}}),K)await F("failed",{error_code:K});else await F("cancelled",{error_code:"driver_stopped"})}catch(U){if(U instanceof h)return}Z.receipts.shift()}}async function wJ($,K){let{fence:Y,op:F}=_($),P=K.snapshot_id;if(K.version!==1||typeof P!=="string"||Object.keys(K).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let U=await w(`/operations/${F}/environment`,{...Y,snapshot_id:P}),C=U.json?.environment_sealed;if(U.status!==200||!C||U.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let X=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:P,deviceId:Z.deviceId??"",sealed:C});if((await w(`/operations/${F}/environment-ack`,{...Y,...X})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
+ export{aJ as u,VJ as v,zZ as w};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var r={name:"github-native-engineer-device-worker-production",version:"0.2.279",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
3
+ export{r as yh};
@@ -0,0 +1,42 @@
1
+ // @bun
2
+ import{_d as W}from"./vm-hands-entry-lite-sv6xwe0h.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),g=W.string().regex(/^[a-f0-9]{40}$/),N=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),q={version:W.literal(1),repoFullName:T},c=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),l=W.discriminatedUnion("kind",[W.strictObject({...q,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...q,kind:W.literal("pr_review_context"),number:N,after:W.string().min(1).max(1024).optional()}),W.strictObject({...q,kind:W.literal("prepare"),branch:G,baseSha:g,defaultBranch:G}),W.strictObject({...q,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:g,remoteHeadSha:g.nullable()}),W.strictObject({...q,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...q,kind:W.literal("pr_mutation"),number:N,mutation:c}),W.strictObject({...q,kind:W.literal("pr_merge"),number:N,expectedHeadSha:g,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"])})]),I=245760,u=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(I)}),W.strictObject({kind:W.literal("prepare"),headSha:g}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(I)}),W.strictObject({kind:W.literal("publish"),headSha:g,scannedObjectCount:W.number().int().min(0).max(5000)}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:N,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:N,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=I,"local_device_gh_result_too_large"),y=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),j=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:y.optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function a(Q,Z,$={},H="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return d(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((K)=>K==="."||K===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((K)=>K.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((K,B)=>{if(B==="per_page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(B==="page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(Y==="/pulls"&&B==="state"&&["open","closed","all"].includes(K))return;if(Y==="/pulls"&&B==="sort"&&K==="updated")return;if(Y==="/pulls"&&B==="direction"&&K==="desc")return;if(Y==="/pulls"&&["head","base"].includes(B)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(K))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((B,b)=>{if(b!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(B))throw Error("local_device_gh_header_denied")})}function d(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let H=new URL(Z,"https://api.github.com");if(H.pathname!=="/search/issues"||H.username||H.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;H.searchParams.forEach((X,K)=>{if(K==="q"&&V===null){V=X;return}if(K==="per_page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;if(K==="page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,U=V?.toLowerCase()??"";if(U.length>512||!(U+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(U.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((X,K)=>{if(K!=="accept"||X!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var e=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
3
+ repository(owner: $owner, name: $repo) {
4
+ nameWithOwner
5
+ pullRequest(number: $number) {
6
+ number
7
+ reviewDecision
8
+ headRefOid
9
+ baseRefOid
10
+ baseRef {
11
+ branchProtectionRule {
12
+ requiresApprovingReviews
13
+ requiredApprovingReviewCount
14
+ requiresStatusChecks
15
+ requiredStatusCheckContexts
16
+ requiresConversationResolution
17
+ dismissesStaleReviews
18
+ }
19
+ }
20
+ reviewThreads(first: 100, after: $after) {
21
+ nodes {
22
+ id isResolved isOutdated viewerCanResolve viewerCanUnresolve
23
+ path line originalLine startLine originalStartLine diffSide startDiffSide
24
+ comments(first: 100) {
25
+ nodes {
26
+ id databaseId body createdAt updatedAt url
27
+ author { __typename login }
28
+ replyTo { databaseId }
29
+ }
30
+ pageInfo { hasNextPage }
31
+ }
32
+ }
33
+ pageInfo { hasNextPage endCursor }
34
+ }
35
+ }
36
+ }
37
+ }`;function QQ(Q){return Q.kind==="read"||Q.kind==="pr_review_context"}var E=["inspect_project","fs.read","fs.write","fs.search","fs.watch","fs.upload","fs.export","fs.import","fs.download","exec.run","exec.full","process.run.v1","process.full.v1","pty.start","pty.input","pty.resize","pty.close","git.run","process.list","process.signal","ports.list","tunnel.open","tunnel.close","env.discover","setup.run","mcp.discover","mcp.start","mcp.proxy","browser.snapshot","browser.navigate","browser.act","computer.snapshot","computer.act","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.ollama.v1","inference.custom.v1","delegate.devin.copy.v1","delegate.cursor.copy.v1","display.stream.v1","automation.call.v1","preview.serve.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"];var x=2,m="/app/local-runtime",O=262144,KQ="x-reason-relay-host-alias",FQ="v1";function F(Q,Z){return{path:`${m}${Q}`,routerPath:Q,auth:Z}}function M(Q,Z){return{...F(Q,"device_proof"),forOperation($){return F(`/operations/${encodeURIComponent($)}${Z}`,"device_proof")}}}var wQ={register:F("/register","registration_bearer"),enroll:F("/enroll","none"),authChallenge:F("/auth/challenge","none"),identity:F("/identity","device_proof"),heartbeat:F("/heartbeat","device_proof"),rootsSync:F("/roots/sync","device_proof"),disconnect:F("/disconnect","device_proof"),lifecycle:F("/lifecycle","device_proof"),localSubscription:F("/local-subscription","device_proof"),ownerWorkspaces:F("/owner-workspaces","device_proof"),ownerWorkspaceEnrollment:F("/owner-workspaces/enrollment","device_proof"),sessionWorktrees:F("/session-worktrees","device_proof"),operationClaim:F("/operations/claim","device_proof"),operationHeartbeat:M("/operations/:operationId/heartbeat","/heartbeat"),operationEvents:M("/operations/:operationId/events","/events"),operationComplete:M("/operations/:operationId/complete","/complete"),operationEnvironment:M("/operations/:operationId/environment","/environment"),operationEnvironmentAck:M("/operations/:operationId/environment-ack","/environment-ack"),operationCustomEndpointCredential:M("/operations/:operationId/custom-endpoint-credential","/custom-endpoint-credential")},HQ=`${m}/session`,VQ=4096,YQ=5000,z=[/^\/app\/local-runtime\/heartbeat$/,/^\/app\/local-runtime\/operations\/claim$/,/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/(?:heartbeat|events|complete|environment|environment-ack)$/];function XQ(Q){return z.some((Z)=>Z.test(Q))}var BQ="vm_hands_v1",GQ=60000,qQ={unauthenticated:4401,unavailable:4404,overloaded:4429,serviceRestart:1012},gQ="hands_control_v1",MQ="environment.deliver",NQ="claim_v1",UQ="environment_at_claim",jQ="rebind_v1",JQ="resident_rebind",xQ="hands.rebind",IQ="snapshot_v1",SQ="cloud_access",mQ="playwright_v1",PQ="headless_browser",TQ="v1",CQ="job_env_large_values",AQ="srt_root_v1",EQ="hands_confinement",kQ="gid_v1",LQ="model_jobs_egress",_Q="setpriv_v1",fQ="jobs_user",bQ="spawning_attempt_v1",cQ="hands_session_group",yQ="same_launch_v1",dQ="exit_v1",OQ="start_wait",zQ="user_chrome",RQ="cloud_sessions";function S(Q){if(!D(Q)||Object.keys(Q).length!==5||Q.version!==1)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["boot_generation","recording_operation_id","recording_attempt_id"].every(($)=>typeof Q[$]==="string"&&Z.test(Q[$]))&&typeof Q.root_version==="string"&&/^[0-9]{1,20}(?:\.[0-9]{1,6})?$/.test(Q.root_version)}function J(Q){if(!D(Q)||Object.keys(Q).length!==6)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return typeof Q.device_id==="string"&&Z.test(Q.device_id)&&(Q.binding==="workspace_source"||Q.binding==="mcp_control")&&Number.isSafeInteger(Q.target_revision)&&Number(Q.target_revision)>=0&&Number.isSafeInteger(Q.root_grant_revision)&&Number(Q.root_grant_revision)>0&&Number.isSafeInteger(Q.target_generation)&&Number(Q.target_generation)>0&&typeof Q.target_fence_id==="string"&&Z.test(Q.target_fence_id)}var hQ=86400000,pQ=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"],R=["production","staging"];function k(Q){if(!D(Q)||Object.keys(Q).length!==3)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["organization_id","user_id","device_id"].every(($)=>Object.hasOwn(Q,$)&&typeof Q[$]==="string"&&Z.test(Q[$])&&Q[$]!=="00000000-0000-0000-0000-000000000000")}var h="DEVICE-PROOF-V2",rQ="ARA-DEVICE-V1";function nQ(Q,Z=h){let $=Q.method.toUpperCase();if(!/^[A-Z]+$/.test($)||!Q.pathAndQuery.startsWith(`${m}/`)||Q.pathAndQuery.includes(`
38
+ `)||!/^[0-9]{1,20}$/.test(Q.timestamp)||!/^[A-Za-z0-9_-]{22,43}$/.test(Q.nonce)||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
39
+ `)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
40
+ `),"utf8")}function D(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function p(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function L(Q){return D(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function r(Q){return D(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&D(Q.payload)}function w(Q){throw Error(Q)}function sQ(Q,Z){let $=D(Q)?Q:{},H=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:H,message:V}}function n(Q){if(!D(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
41
+ `)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function _(Q,Z){if(!D(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==x||!Array.isArray(Q.roots)||!Q.roots.every(L)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:x,roots:Q.roots},auth_scheme:"p256"}}function oQ(Q){return _(Q,!1)}function iQ(Q){let Z=_(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function tQ(Q){if(!D(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...o(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var s=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(s.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function vQ(Q){if(!D(Q))return;try{return{...n(Q),...f(Q)}}catch{return}}function o(Q){if(!D(Q))return{};let Z={};for(let $ of R){let H=Q[$];if(typeof H==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(H))Z[$]=H}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function lQ(Q){if(!D(Q)||!Array.isArray(Q.roots)||!Q.roots.every(L))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function uQ(Q){if(!D(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function aQ(Q){if(!D(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function eQ(Q){if(D(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(D(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function QW(Q){if(!D(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function i(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function WW(Q,Z=E){if(!D(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!k(Q.owner)||!p(Q.capability,Z)||!D(Q.payload)||Q.protocol_version!==x||i(Q.payload)>O||Q.authority!==void 0&&!J(Q.authority)||Q.local_github_authority!==void 0&&!j.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!j.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!k(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...J(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:j.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&D(Q.environment)&&D(Q.environment.payload)&&J(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:x};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function ZW(Q){if(!D(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(r)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function $W(Q){if(!D(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function DW(Q){if(!D(Q)||!D(Q.payload)||!J(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function t(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function KW(Q){if(!D(Q)||!t(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
42
+ export{l as Mc,I as Nc,u as Oc,j as Pc,a as Qc,e as Rc,QQ as Sc,E as Tc,x as Uc,m as Vc,O as Wc,KQ as Xc,FQ as Yc,wQ as Zc,HQ as _c,VQ as $c,YQ as ad,XQ as bd,BQ as cd,GQ as dd,qQ as ed,gQ as fd,MQ as gd,NQ as hd,UQ as id,jQ as jd,JQ as kd,xQ as ld,IQ as md,SQ as nd,mQ as od,PQ as pd,TQ as qd,CQ as rd,AQ as sd,EQ as td,kQ as ud,LQ as vd,_Q as wd,fQ as xd,bQ as yd,cQ as zd,yQ as Ad,dQ as Bd,OQ as Cd,zQ as Dd,RQ as Ed,hQ as Fd,pQ as Gd,h as Hd,rQ as Id,nQ as Jd,sQ as Kd,n as Ld,oQ as Md,iQ as Nd,tQ as Od,vQ as Pd,lQ as Qd,uQ as Rd,aQ as Sd,eQ as Td,QW as Ud,WW as Vd,ZW as Wd,$W as Xd,DW as Yd,KW as Zd};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{Kb as j,Lb as q}from"./vm-hands-entry-lite-65pbrs1x.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
3
+ export{y as t};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{resolve as a,sep as i}from"path";var c=[[".ssh"],[".gnupg"],[".aws"],[".azure"],[".kube"],[".docker"],[".infisical"],[".password-store"],[".terraform.d"],[".config","ara"],[".config","reason"],[".config","gh"],[".config","gcloud"],[".config","infisical"],[".config","op"],[".config","1password"],[".config","pass"],[".local","share","keyrings"],["library","keychains"],["library","application support","so.ara.desktop"]],l=[[".codex","config.toml"],[".cursor","mcp.json"],[".claude","settings.json"],[".claude","settings.local.json"],[".cargo","credentials"],[".cargo","credentials.toml"],[".gem","credentials"],[".config","git","config"],[".config","git","credentials"],[".config","pip","pip.conf"]],f=new Set([".bash_login",".bash_profile",".bashrc",".bunfig.toml",".claude.json",".env",".envrc",".git-credentials",".gitconfig",".mcp.json",".netrc",".npmrc",".profile",".pypirc",".terraformrc",".yarnrc",".yarnrc.yml",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","auth.json","credentials.json","credentials.tfrc.json","local-daemon.json","local-device.json","mcp.json"]),g=[".key",".p12",".pfx",".pem"];function t(r,n){if(r.length<n.length)return!1;for(let e=0;e<=r.length-n.length;e+=1)if(n.every((o,s)=>r[e+s]===o))return!0;return!1}function d(r){let n=a(r).split(i).filter(Boolean).map((o)=>o.toLowerCase());if(c.some((o)=>t(n,o)))return!0;if(l.some((o)=>t(n,o)))return!0;let e=n.at(-1)??"";return f.has(e)||e.startsWith(".env.")||g.some((o)=>e.endsWith(o))}
3
+ export{c as Vb,l as Wb,f as Xb,g as Yb,d as Zb};
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{jh as m}from"./vm-hands-entry-lite-84aq8d12.js";var E=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],VA=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&E.includes(A)))return;return x.slice()}var $A="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",JA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,B=Object.keys(A);return B.length===2&&B.includes("template")&&B.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var X=2,P=33554432,K=200000,D=4000000,Q=240000,DA=`
3
+ ...[executor output truncated]`,j=2000,f=1,b=16384,p=32768,w=128,RA=64,i=2097152,h=1,y=16384,d=32768,YA=8388608,s=1000,c=2500,n=2000,LA=c+n,t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,o={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},v=new Map(Object.entries(o).map(([x,A])=>[A,x]));function OA(x,A){return A||(v.get(x)??"")}var l=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],u=new Set(l),a=200,e=2000,AA=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class G extends Error{code;constructor(x){super(x);this.name="HandsProtocolError",this.code=x}}function k(x){return new TextEncoder().encode(x).byteLength}function F(x){return typeof x==="object"&&x!==null&&!Array.isArray(x)}function W(x,A){let B=new Set(A);return Object.keys(x).every((N)=>B.has(N))}function M(x){return typeof x==="string"&&t.test(x)}function V(x){return Number.isSafeInteger(x)&&Number(x)>=1}function $(x){return typeof x==="string"&&r.test(x)}function C(x){return typeof x==="string"&&x.startsWith("pty-")&&$(x.slice(4))}function z(x){return[x.cols,x.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=s)}function H(x){if(typeof x!=="string"||x.length>Math.ceil(y/3)*4||x.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(x))return-1;let A=x.endsWith("==")?2:x.endsWith("=")?1:0;if(A&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(x[x.length-A-1])&(A===2?15:3))return-1;let N=x.length/4*3-A;return N<=y?N:-1}function S(x){return typeof x==="string"&&/^[0-9a-f]{64}$/.test(x)}function Z(x){if(k(x)>P)throw new G("frame_too_large");try{return JSON.parse(x)}catch{throw new G("invalid_json")}}function xA(x){let A=Z(x);if(!F(A)||!W(A,["version","generation","id","tool","input","semanticDigest","lifecycleLeaseId"])||A.version!==X||!V(A.generation)||!M(A.id)||!["bash","repl","resume","read","edit","write","pi_tool"].includes(String(A.tool))||!F(A.input)||A.lifecycleLeaseId!==void 0&&(A.tool!=="bash"||!$(A.lifecycleLeaseId)))throw new G("invalid_request");if(A.tool==="bash"){if(!W(A.input,["script","retainBackground","machineSdk"])||typeof A.input.script!=="string"||A.input.script.length>K||A.input.retainBackground!==void 0&&A.input.retainBackground!==!0||A.input.machineSdk!==void 0&&A.input.machineSdk!==!0||A.semanticDigest!==void 0&&!S(A.semanticDigest))throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"bash",input:{script:A.input.script,...A.input.retainBackground===!0?{retainBackground:!0}:{},...A.input.machineSdk===!0?{machineSdk:!0}:{}},...A.semanticDigest===void 0?{}:{semanticDigest:A.semanticDigest},...A.lifecycleLeaseId===void 0?{}:{lifecycleLeaseId:A.lifecycleLeaseId}}}if(A.tool==="resume"){if(A.semanticDigest!==void 0||!W(A.input,["semanticDigest"])||!S(A.input.semanticDigest))throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"resume",input:{semanticDigest:A.input.semanticDigest}}}if(A.tool==="repl"){if(!W(A.input,["code"])||typeof A.input.code!=="string"||A.input.code.length>K||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"repl",input:{code:A.input.code}}}if(A.tool==="pi_tool"){let B=A.semanticDigest===void 0?BA(A.input):null;if(!B)throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"pi_tool",input:B}}if(A.tool==="read"){if(!W(A.input,["path","offset","limit"])||typeof A.input.path!=="string"||A.input.path.length<1||A.input.path.length>K||A.semanticDigest!==void 0||A.input.offset!==void 0&&(!Number.isSafeInteger(A.input.offset)||Number(A.input.offset)<1)||A.input.limit!==void 0&&(!Number.isSafeInteger(A.input.limit)||Number(A.input.limit)<1||Number(A.input.limit)>2000))throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"read",input:{path:A.input.path,...A.input.offset===void 0?{}:{offset:Number(A.input.offset)},...A.input.limit===void 0?{}:{limit:Number(A.input.limit)}}}}if(A.tool==="edit"){if(!W(A.input,["path","edits"])||typeof A.input.path!=="string"||A.input.path.length<1||!Array.isArray(A.input.edits)||A.input.edits.length<1||A.input.edits.length>128||A.semanticDigest!==void 0)throw new G("invalid_request");let B=A.input.path.length,N=[];for(let I of A.input.edits){if(!F(I)||!W(I,["oldText","newText"])||typeof I.oldText!=="string"||I.oldText.length<1||typeof I.newText!=="string")throw new G("invalid_request");if(B+=I.oldText.length+I.newText.length,B>D)throw new G("invalid_request");N.push({oldText:I.oldText,newText:I.newText})}return{version:X,generation:A.generation,id:A.id,tool:"edit",input:{path:A.input.path,edits:N}}}if(A.tool!=="write"||!W(A.input,["path","content"])||typeof A.input.path!=="string"||A.input.path.length<1||typeof A.input.content!=="string"||A.input.path.length+A.input.content.length>D||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"write",input:{path:A.input.path,content:A.input.content}}}function L(x){return x===void 0||typeof x==="number"&&Number.isFinite(x)}function BA(x){let A=x.args;if(!W(x,["tool","args"])||!F(A))return null;if(x.tool==="bash")return W(A,["command","timeout"])&&typeof A.command==="string"&&A.command.length<=K&&L(A.timeout)?{tool:"bash",args:{command:A.command,...A.timeout===void 0?{}:{timeout:Number(A.timeout)}}}:null;if(typeof A.path!=="string"||A.path.length>K)return null;if(x.tool==="read")return W(A,["path","offset","limit"])&&L(A.offset)&&L(A.limit)?{tool:"read",args:{path:A.path,...A.offset===void 0?{}:{offset:Number(A.offset)},...A.limit===void 0?{}:{limit:Number(A.limit)}}}:null;if(x.tool==="write")return W(A,["path","content"])&&typeof A.content==="string"&&A.path.length+A.content.length<=D?{tool:"write",args:{path:A.path,content:A.content}}:null;if(x.tool!=="edit"||!W(A,["path","edits"])||!Array.isArray(A.edits))return null;let B=A.path.length,N=[];for(let I of A.edits){if(!F(I)||!W(I,["oldText","newText"])||typeof I.oldText!=="string"||typeof I.newText!=="string")return null;if(B+=I.oldText.length+I.newText.length,B>D)return null;N.push({oldText:I.oldText,newText:I.newText})}return{tool:"edit",args:{path:A.path,edits:N}}}function WA(x){if(!F(x))return null;if("thrown"in x)return W(x,["thrown"])&&typeof x.thrown==="string"?{thrown:x.thrown}:null;let A=x.structuredContent;if(!W(x,["content","details","structuredContent","isError"])||!Array.isArray(x.content)||x.isError!==void 0&&x.isError!==!0||A!==void 0&&(!F(A)||!W(A,["output","truncated","full_output_path","exit_code","wall_time_seconds"])||typeof A.output!=="string"||typeof A.truncated!=="boolean"||A.full_output_path!==void 0&&typeof A.full_output_path!=="string"||typeof A.exit_code!=="number"||typeof A.wall_time_seconds!=="number"))return null;let B=[];for(let N of x.content)if(F(N)&&N.type==="text"&&W(N,["type","text"])&&typeof N.text==="string")B.push({type:"text",text:N.text});else if(F(N)&&N.type==="image"&&W(N,["type","data","mimeType"])&&typeof N.data==="string"&&typeof N.mimeType==="string")B.push({type:"image",data:N.data,mimeType:N.mimeType});else return null;return{content:B,...x.details===void 0?{}:{details:x.details},...F(A)?{structuredContent:{output:String(A.output),truncated:A.truncated===!0,...typeof A.full_output_path==="string"?{full_output_path:A.full_output_path}:{},exit_code:Number(A.exit_code),wall_time_seconds:Number(A.wall_time_seconds)}}:{},...x.isError===!0?{isError:!0}:{}}}function GA(x){let A=Z(x);if(!F(A)||!W(A,["version","generation","id","ok","exitCode","stdout","stderr","cwd","error","resumed","browserActions","automaticProgressImage","piToolOutcome","workerElapsedMs","environmentWaitMs"])||A.version!==X||!V(A.generation)||!M(A.id)||typeof A.ok!=="boolean"||!Number.isSafeInteger(A.exitCode)||Number(A.exitCode)<0||Number(A.exitCode)>255||typeof A.stdout!=="string"||A.stdout.length>Q||typeof A.stderr!=="string"||A.stderr.length>Q||A.cwd!==void 0&&(typeof A.cwd!=="string"||A.cwd.length<1||A.cwd.length>4096||!A.cwd.startsWith("/")||A.cwd.includes("\x00"))||A.error!==void 0&&(typeof A.error!=="string"||A.error.length<1||A.error.length>j||!u.has(A.error))||A.browserActions!==void 0&&!R(A.browserActions)||A.automaticProgressImage!==void 0&&(A.automaticProgressImage!==!0||!A.ok)||A.resumed!==void 0&&A.resumed!==!0||A.workerElapsedMs!==void 0&&(!Number.isSafeInteger(A.workerElapsedMs)||Number(A.workerElapsedMs)<0)||A.environmentWaitMs!==void 0&&(!Number.isSafeInteger(A.environmentWaitMs)||Number(A.environmentWaitMs)<0)||A.ok&&(A.exitCode!==0||A.error!==void 0)||!A.ok&&A.exitCode===0)throw new G("invalid_result");let B=A.piToolOutcome===void 0?void 0:WA(A.piToolOutcome);if(B===null||B&&!A.ok)throw new G("invalid_result");return{version:X,generation:A.generation,id:A.id,ok:A.ok,exitCode:Number(A.exitCode),stdout:A.stdout,stderr:A.stderr,...typeof A.cwd==="string"?{cwd:A.cwd}:{},...A.browserActions!==void 0?{browserActions:R(A.browserActions)}:{},...typeof A.error==="string"?{error:A.error}:{},...A.automaticProgressImage===!0?{automaticProgressImage:!0}:{},...A.resumed===!0?{resumed:!0}:{},...B?{piToolOutcome:B}:{},...A.workerElapsedMs!==void 0?{workerElapsedMs:Number(A.workerElapsedMs)}:{},...A.environmentWaitMs!==void 0?{environmentWaitMs:Number(A.environmentWaitMs)}:{}}}function NA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","sequence","stdout","stderr"])||A.type!=="progress"||A.version!==X||!V(A.generation)||!M(A.id)||!Number.isSafeInteger(A.sequence)||Number(A.sequence)<1||typeof A.stdout!=="string"||A.stdout.length>Q||typeof A.stderr!=="string"||A.stderr.length>Q)throw new G("invalid_progress");return{type:"progress",version:X,generation:Number(A.generation),id:A.id,sequence:Number(A.sequence),stdout:A.stdout,stderr:A.stderr}}function UA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","fenceId","executorLaunchId","requestCancelVersion","managedJobsVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinement","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion"])||A.type!=="claim"||A.version!==X||!V(A.generation)||!$(A.fenceId)||!$(A.executorLaunchId)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==f||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinement!==void 0&&(!Y(A.piToolsConfinement)||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1))throw new G("invalid_claim");return{type:"claim",version:X,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{},...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...Y(A.piToolsConfinement)?{piToolsConfinement:{template:A.piToolsConfinement.template,quoteDepth:A.piToolsConfinement.quoteDepth}}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{}}}function FA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","fenceId","executorLaunchId","workerVersion","workerArtifactSha256","requestCancelVersion","managedJobsVersion","lifecycleVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinementVersion","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion"])||A.lifecycleVersion!==void 0&&A.lifecycleVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinementVersion!==void 0&&(A.piToolsConfinementVersion!==1||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.type!=="claim_ack"||A.version!==X||!V(A.generation)||!$(A.fenceId)||!$(A.executorLaunchId)||!Number.isSafeInteger(A.workerVersion)||Number(A.workerVersion)<1||!S(A.workerArtifactSha256)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==f)throw new G("invalid_claim_ack");return{type:"claim_ack",...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.lifecycleVersion===1?{lifecycleVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...A.piToolsConfinementVersion===1?{piToolsConfinementVersion:1}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},version:X,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,workerVersion:Number(A.workerVersion),workerArtifactSha256:A.workerArtifactSha256,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{}}}function zA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","jobId","action","input"])||A.type!=="job"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.jobId)||!F(A.input))throw new G("invalid_job_request");let B=A.input,N=Number.isSafeInteger(B.leaseExpiresAtMs)&&Number(B.leaseExpiresAtMs)>0,I=Number.isSafeInteger(B.sequence)&&Number(B.sequence)>=1;if(!(A.action==="start"?B.mode==="pty"?W(B,["mode","cols","rows","leaseExpiresAtMs"])&&C(A.jobId)&&z(B)&&N:W(B,["script","leaseExpiresAtMs"])&&typeof B.script==="string"&&B.script.length<=K&&N:A.action==="inspect"?W(B,["after"])&&Number.isSafeInteger(B.after)&&Number(B.after)>=0:A.action==="input"?"dataBase64"in B?W(B,["sequence","dataBase64"])&&C(A.jobId)&&I&&H(B.dataBase64)>0:W(B,["sequence","data","eof"])&&I&&typeof B.data==="string"&&B.data.length<=b&&typeof B.eof==="boolean":A.action==="resize"?W(B,["sequence","cols","rows"])&&C(A.jobId)&&I&&z(B):A.action==="renew"?W(B,["leaseExpiresAtMs"])&&N:A.action==="cancel"&&W(B,[])))throw new G("invalid_job_request");return A}function IA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","ok","job","error"])||A.type!=="job_result"||A.version!==X||!V(A.generation)||!M(A.id))throw new G("invalid_job_result");if(A.ok===!1&&A.job===void 0&&typeof A.error==="string"&&AA.some((U)=>U===A.error))return A;let B=A.job;if(A.ok!==!0||A.error!==void 0||!F(B)||!W(B,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!M(B.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(B.state))||!Number.isSafeInteger(B.startedAtMs)||Number(B.startedAtMs)<1||!Number.isSafeInteger(B.leaseExpiresAtMs)||Number(B.leaseExpiresAtMs)<1||B.finishedAtMs!==null&&(!Number.isSafeInteger(B.finishedAtMs)||Number(B.finishedAtMs)<Number(B.startedAtMs))||B.exitCode!==null&&(!Number.isSafeInteger(B.exitCode)||Number(B.exitCode)<0||Number(B.exitCode)>255)||!Number.isSafeInteger(B.inputSequence)||Number(B.inputSequence)<0||!Number.isSafeInteger(B.firstCursor)||Number(B.firstCursor)<1||!Number.isSafeInteger(B.nextCursor)||Number(B.nextCursor)<Number(B.firstCursor)-1||typeof B.truncated!=="boolean"||!Array.isArray(B.output)||B.output.length>w)throw new G("invalid_job_result");if(B.environmentRevision===void 0!==(B.environmentSnapshotId===void 0)||B.environmentRevision!==void 0&&(!Number.isSafeInteger(B.environmentRevision)||Number(B.environmentRevision)<1||!$(B.environmentSnapshotId)))throw new G("invalid_job_result");let N=Number(B.firstCursor)-1,I=0;for(let U of B.output){if(!F(U)||!W(U,["cursor","stream","text"])||!Number.isSafeInteger(U.cursor)||Number(U.cursor)<=N||Number(U.cursor)>Number(B.nextCursor)||!["stdout","stderr"].includes(String(U.stream))||typeof U.text!=="string")throw new G("invalid_job_result");I+=U.text.length,N=Number(U.cursor)}if(I>p)throw new G("invalid_job_result");let _=B.state==="starting"||B.state==="running";if(_&&(B.finishedAtMs!==null||B.exitCode!==null)||!_&&B.finishedAtMs===null||B.state==="uncertain"&&B.exitCode!==null||B.state==="exited"&&B.exitCode===null||B.state==="cancelled"&&B.exitCode!==130||B.state==="expired"&&B.exitCode!==124)throw new G("invalid_job_result");if(B.process!==void 0){let U=B.process;if(!F(U)||!W(U,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(U.pid)||Number(U.pid)<1||U.processGroupId!==U.pid||!$(U.executorLaunchId)||!["starting","running"].includes(String(B.state)))throw new G("invalid_job_result")}if(B.pty!==void 0){let U=B.pty;if(!F(U)||!W(U,["version","cols","rows","output","cleanup"])||U.version!==h||!C(B.jobId)||!z(U)||B.output.length!==0||!Array.isArray(U.output)||U.output.length>w||(_?U.cleanup!=="pending":B.state==="uncertain"?U.cleanup!=="unconfirmed":U.cleanup!=="confirmed")||B.state==="running"&&(B.process===void 0||B.environmentRevision===void 0))throw new G("invalid_job_result");let T=Number(B.firstCursor)-1,g=0;for(let J of U.output){if(!F(J)||!W(J,["cursor","dataBase64"])||!Number.isSafeInteger(J.cursor)||Number(J.cursor)<=T||Number(J.cursor)>Number(B.nextCursor))throw new G("invalid_job_result");let q=H(J.dataBase64);if(q<=0||(g+=q)>d)throw new G("invalid_job_result");T=Number(J.cursor)}}return A}function SA(x){if(k(x)>i)throw new G("frame_too_large");let A=Z(x);if(!F(A)||!W(A,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||A.version!==h||![A.sessionId,A.operationId,A.runId].every(M)||![A.deviceId,A.rootId,A.fenceId,A.executorLaunchId].every($)||!V(A.generation)||!Number.isSafeInteger(A.rootGrantRevision)||Number(A.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(A.binding))||!Number.isSafeInteger(A.targetRevision)||Number(A.targetRevision)<0||A.binding==="workspace_source"&&A.targetRevision!==0||!F(A.workspace))throw new G("invalid_pty_receipt");if(!m(A.workspace))throw new G("invalid_pty_receipt");let B=IA(JSON.stringify({type:"job_result",version:X,generation:A.generation,id:A.operationId,ok:!0,job:A.job}));if(!B.ok||!B.job.pty||B.job.pty.output.length!==0||B.job.process&&B.job.process.executorLaunchId!==A.executorLaunchId)throw new G("invalid_pty_receipt");return A}function TA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","targetId"])||A.type!=="cancel_request"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.targetId))throw new G("invalid_cancel_request");return A}function qA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","targetId","status"])||A.type!=="cancel_ack"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.targetId)||!["cancelled","settled","not_found","unsupported","unconfirmed"].includes(String(A.status)))throw new G("invalid_cancel_ack");return A}function wA(x){let A=JSON.stringify(x);return xA(A),A}function yA(x){let A=JSON.stringify(x);return GA(A),A}function mA(x){let A=JSON.stringify(x);return NA(A),A}function fA(x){let A=JSON.stringify(x);return UA(A),A}function hA(x){let A=JSON.stringify(x);return FA(A),A}function O(x){return typeof x==="string"&&x.length>=1&&x.length<=a&&!x.includes("\x00")}function XA(x){let A=["type","version","generation","id","jobRequestId","verb"];if(x.verb==="help")return W(x,A)?{verb:"help"}:null;if(x.verb==="describe"||x.verb==="namespace")return W(x,[...A,"name"])&&O(x.name)?{verb:x.verb,name:x.name}:null;if(x.verb==="search"){let B=x.args;if(!W(x,[...A,"query","args"])||typeof x.query!=="string"||x.query.trim().length<1||x.query.length>e)return null;if(B===void 0)return{verb:"search",query:x.query};if(!F(B)||!W(B,["namespace","limit"])||B.namespace!==void 0&&!O(B.namespace)||B.limit!==void 0&&(!Number.isSafeInteger(B.limit)||Number(B.limit)<1||Number(B.limit)>50))return null;return{verb:"search",query:x.query,args:{...typeof B.namespace==="string"?{namespace:B.namespace}:{},...B.limit===void 0?{}:{limit:Number(B.limit)}}}}if(x.verb!=="call"||!W(x,[...A,"name","args"])||!O(x.name)||!F(x.args)||JSON.stringify(x.args).length>K)return null;return{verb:"call",name:x.name,args:x.args}}function kA(x){let A=Z(x);if(!F(A)||A.type!=="sdk_request"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.jobRequestId))throw new G("invalid_sdk_request");let B=XA(A);if(!B)throw new G("invalid_sdk_request");return{type:"sdk_request",version:X,generation:Number(A.generation),id:A.id,jobRequestId:A.jobRequestId,...B}}function MA(x){let A=Z(x);if(!F(A)||A.type!=="sdk_response"||A.version!==X||!V(A.generation)||!M(A.id))throw new G("invalid_sdk_response");let B={type:"sdk_response",version:X,generation:Number(A.generation),id:A.id},N=["type","version","generation","id","ok"];if(A.ok===!0&&W(A,[...N,"result"])&&typeof A.result==="string"&&A.result.length<=Q)return{...B,ok:!0,result:A.result};if(A.ok===!1&&W(A,[...N,"error"])&&typeof A.error==="string"&&A.error.length>=1&&A.error.length<=Q)return{...B,ok:!1,error:A.error};throw new G("invalid_sdk_response")}function HA(x){let A=JSON.stringify(x);return MA(A),A}
4
+ export{VA as ef,$A as ff,JA as gf,X as hf,P as if,K as jf,D as kf,Q as lf,DA as mf,j as nf,f as of,b as pf,p as qf,w as rf,RA as sf,i as tf,h as uf,y as vf,d as wf,YA as xf,s as yf,c as zf,n as Af,LA as Bf,o as Cf,OA as Df,l as Ef,a as Ff,e as Gf,AA as Hf,G as If,M as Jf,V as Kf,$ as Lf,C as Mf,S as Nf,xA as Of,GA as Pf,NA as Qf,UA as Rf,FA as Sf,zA as Tf,IA as Uf,SA as Vf,TA as Wf,qA as Xf,wA as Yf,yA as Zf,mA as _f,fA as $f,hA as ag,kA as bg,MA as cg,HA as dg};