@reason-machines/cli-linux-x64 0.2.393 → 0.2.395
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +1 -1
- package/bin/vm-hands/api-credentials-200ret9z.js +2 -0
- package/bin/vm-hands/api-jcccjxss.js +2 -0
- package/bin/vm-hands/{ask-relay-q0ysjj22.js → ask-relay-e424fxe1.js} +3 -3
- package/bin/vm-hands/connect-cli-t2cf1fhv.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-3g0rc3wp.js → custom-endpoint-device-qd3zcysz.js} +1 -1
- package/bin/vm-hands/desktop-account-r5fsgx43.js +2 -0
- package/bin/vm-hands/{device-workspace-35hjc1ff.js → device-workspace-ntckpym4.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-msdkfx9x.js → hands-worker-source-p6530nj7.js} +1 -1
- package/bin/vm-hands/{index-m32pjcjr.js → index-z6q2j1e0.js} +1 -1
- package/bin/vm-hands/install-receipt-kqayxfsn.js +2 -0
- package/bin/vm-hands/local-automation-3msswz1s.js +2 -0
- package/bin/vm-hands/local-capabilities-jp7mfe90.js +2 -0
- package/bin/vm-hands/local-desktop-users-7kbrnvba.js +2 -0
- package/bin/vm-hands/local-display-mac-0k5twcjj.js +2 -0
- package/bin/vm-hands/local-display-session-4nz3ps1j.js +2 -0
- package/bin/vm-hands/local-pty-session-a0fz1f9t.js +2 -0
- package/bin/vm-hands/{managed-runtime-bgbzjn5s.js → managed-runtime-jpkvdh9q.js} +1 -1
- package/bin/vm-hands/{network-contract-3h853c6e.js → network-contract-xgbrevt2.js} +1 -1
- package/bin/vm-hands/package-x8ct3epg.js +2 -0
- package/bin/vm-hands/permissions-nhtd0qmb.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-mw7ba8vz.js → reason-hands-protocol-90kpyg4s.js} +1 -1
- package/bin/vm-hands/{serve-service-qqrsrb6k.js → serve-service-sdep4jmp.js} +1 -1
- package/bin/vm-hands/{status-g0yna6nk.js → status-r1k521hh.js} +2 -2
- package/bin/vm-hands/version-svxh3eka.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-180h5amj.js → vm-hands-entry-lite-0nd56w02.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-a1yy1yp3.js → vm-hands-entry-lite-1cs1jy20.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3nr9q3nf.js → vm-hands-entry-lite-29f3m7x2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-5x04hakp.js → vm-hands-entry-lite-2sx1a43v.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3ptq7p60.js → vm-hands-entry-lite-34h6rv5c.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1edhwzhg.js → vm-hands-entry-lite-3ypjvw3e.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-t7g13jac.js → vm-hands-entry-lite-42chrtkc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9rnba1mg.js → vm-hands-entry-lite-4d0szmz0.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-f78n4wqt.js → vm-hands-entry-lite-5d31qv44.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-c7qb87xk.js → vm-hands-entry-lite-6256d8j5.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-g87z5eb6.js → vm-hands-entry-lite-69n9q5f1.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ezahexcb.js → vm-hands-entry-lite-6nj2ejfh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-nnmhnxqs.js → vm-hands-entry-lite-90r926q9.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-8e932j3c.js → vm-hands-entry-lite-bgs4zjkf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-trm3dn8c.js → vm-hands-entry-lite-cfwke54v.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-88h9vwrv.js → vm-hands-entry-lite-e1cbqqqw.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r166b92s.js → vm-hands-entry-lite-e4kdpq0t.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-h0keewxv.js → vm-hands-entry-lite-e99ftdr6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ksz1k1dh.js → vm-hands-entry-lite-eatqxe5y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fb02h1zm.js → vm-hands-entry-lite-ek5r435m.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-pjctaaxx.js → vm-hands-entry-lite-ep2n8nxv.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-0apahx7m.js → vm-hands-entry-lite-errnnc9y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-atg4z1vg.js → vm-hands-entry-lite-f50vcbjg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8pgggvbb.js → vm-hands-entry-lite-f9akybcm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-csecgmaa.js → vm-hands-entry-lite-gk3y60ap.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ebgackey.js → vm-hands-entry-lite-hx4w3r63.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9gjjvcmz.js → vm-hands-entry-lite-k4erfh5k.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-kbjh8x26.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-na1vayq4.js → vm-hands-entry-lite-kjjhcjp9.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3xtndjrw.js → vm-hands-entry-lite-nnggcccf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-z4q7mrn5.js → vm-hands-entry-lite-p3d5j70y.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-n3y7495e.js → vm-hands-entry-lite-ps9gjbs5.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hfv2tsm9.js → vm-hands-entry-lite-q5h859gg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-y99g8x7f.js → vm-hands-entry-lite-q62fwa20.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-02zaqpgh.js → vm-hands-entry-lite-qvj5560v.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mft9ke08.js → vm-hands-entry-lite-sbn9bmf7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-p1s0xyc2.js → vm-hands-entry-lite-sjn5yjvx.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-e73s63fb.js → vm-hands-entry-lite-smrymax6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-yr1n57v6.js → vm-hands-entry-lite-t839nkd2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mc3pkj0q.js → vm-hands-entry-lite-v0kpksbf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-wpcagqfw.js → vm-hands-entry-lite-vqfpryez.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y64x380n.js → vm-hands-entry-lite-vys6qap2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-0seprnh3.js → vm-hands-entry-lite-xhbjkkk5.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-y7yr8pjm.js +105 -0
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-mz0bewc9.js → vm-hands-executor-pm8ns2zs.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-7r51q98t.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-h39vjxh4.js → vm-hands-runtime-h5s04mj9.js} +3 -3
- package/bin/vm-hands/worker-sandbox-ecjj14h5.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-2edgrjpe.js +0 -2
- package/bin/vm-hands/api-credentials-1bfy2pqp.js +0 -2
- package/bin/vm-hands/connect-cli-9xve38p0.js +0 -2
- package/bin/vm-hands/desktop-account-8yf4aqgb.js +0 -2
- package/bin/vm-hands/install-receipt-7qanbz38.js +0 -2
- package/bin/vm-hands/local-automation-svznxf54.js +0 -2
- package/bin/vm-hands/local-capabilities-a2fhpy8v.js +0 -2
- package/bin/vm-hands/local-desktop-users-p6n48895.js +0 -2
- package/bin/vm-hands/local-display-mac-7havkbhd.js +0 -2
- package/bin/vm-hands/local-display-session-42vasad3.js +0 -2
- package/bin/vm-hands/local-pty-session-pe20a847.js +0 -2
- package/bin/vm-hands/package-04cf0m62.js +0 -2
- package/bin/vm-hands/permissions-2ez0eqav.js +0 -2
- package/bin/vm-hands/version-5tfam1n3.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-0z73amf7.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-vc06etcb.js +0 -105
- package/bin/vm-hands/vm-hands-op-runner-6vttwrek.js +0 -2
- package/bin/vm-hands/worker-sandbox-nnk7fq89.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Ag as k0}from"./vm-hands-entry-lite-t839nkd2.js";import{Rg as f0}from"./vm-hands-entry-lite-ps9gjbs5.js";import{Xg as uq}from"./vm-hands-entry-lite-q5h859gg.js";import{jj as cq}from"./vm-hands-entry-lite-kjjhcjp9.js";import{qj as i}from"./vm-hands-entry-lite-2sx1a43v.js";import{Zj as _,ak as g0,dk as h0,ek as G8,fk as y0,hk as l8,kk as G0,mk as A0}from"./vm-hands-entry-lite-hx4w3r63.js";import{ok as H0}from"./vm-hands-entry-lite-sjn5yjvx.js";import{Kk as K}from"./vm-hands-entry-lite-69n9q5f1.js";import{execFile as f1,spawn as I0}from"child_process";import{randomBytes as g1}from"crypto";import{chmodSync as h1,existsSync as p0,lstatSync as k1,mkdirSync as I1,readFileSync as p1,rmSync as v1,writeFileSync as Wq}from"fs";import{connect as u1}from"net";import{join as $}from"path";var Gq="./desktop-wallpaper-0pjhgyfk.jpg";var Aq="./dock-browser-afp005mt.png";var Sq="./dock-files-rywdm96b.png";var Vq="./dock-terminal-s41cj1jp.png";var Fq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -248,4 +248,4 @@ Gtk.main()
|
|
|
248
248
|
`).flatMap((P)=>{let X=P.indexOf("=");return X>0?[[P.slice(0,X),P.slice(X+1)]]:[]})))}catch{return{}}}var E0=new Set;async function t1(q,x,Q){let P=await o1(),X=/^:(\d+)(?:\.\d+)?$/.exec(P.DISPLAY??"")?.[1];if(!X||`:${X}`===A8||P.WAYLAND_DISPLAY||P.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${X}`,xauthority:P.XAUTHORITY??$(q,".Xauthority"),rfbSocket:$(x,`rfb-${X}.sock`)},J=`${b.display} ${b.xauthority}`;if(E0.has(J)||!await o({path:`/tmp/.X11-unix/X${X}`},!1))return null;let N={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await u0(Q,b,x,`x11vnc-${X}.log`,N))return{...b,sound:null};return E0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
|
|
249
249
|
`),null}function e1(q,x){let Q=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,P=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!p0(`/usr/bin/${b}`)).map(([b])=>b),X=Mq({root:q,display:x,screen:Nq,browserExec:Q,absent:P});for(let b of["","openbox","tint2","picom"])S8($(q,b));for(let[b,J]of Object.entries(X.files))Wq($(q,b),J,{mode:384});for(let[b,J]of Object.entries(zq))Wq($(q,`ara-${b}`),p1(J),{mode:384});return{root:q,openboxConfig:$(q,"openbox","rc.xml"),start:X.start}}async function q9(q,x){let Q=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
|
|
250
250
|
`);await new Promise((P)=>{let X=I0("/bin/sh",["-c",Q],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{X.kill(),P()},V8);X.once("error",()=>{clearTimeout(b),P()}),X.once("exit",()=>{clearTimeout(b),P()})})}async function uQ(q,x={}){let Q=x.now??Date.now,P=a1(q.payload,Q());if(q.signal.throwIfAborted(),!P.video)throw new K("display_video_required","Reason desktops stream as video now; this request came without it.");let X=x.platform??process.platform;if(X!=="linux"&&X!=="darwin"&&X!=="win32")throw new K("display_video_unsupported","This machine does not serve desktop video.");let b=P.video,J=(x.video?.desktop??(X==="darwin"?async()=>S0:X==="win32"?async()=>V0:i1))();return await x9(q.signal,P,x,Q,(N)=>w0(N,{request:b,desktop:J,...P.viewer?{viewer:P.viewer}:{},viewerSameNetwork:P.viewer_same_network===!0},x.video),(N)=>G8({type:"error",code:N}))}function x9(q,x,Q,P,X,b){let J=P();return new Promise((N,T)=>{let L=null,C=!1,U=!1,y,R,Y,S=!1,W=null,G=(A)=>{if(U)return;if(W)A=W;U=!0,clearTimeout(y),clearTimeout(R),q.removeEventListener("abort",F),Y?.close();try{L?.close(1000,"display_session_over")}catch{}if("error"in A){T(A.error);return}N({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,P()-J)})},V=()=>G({error:new K("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;G({error:A instanceof K?A:new K("cancelled","Reason closed the desktop session.")})},E=()=>{if(!W||!L)return;let A=W.error;try{L.send(b(A instanceof K?A.code:"display_unavailable"))}catch{}G(W)};if(Y=X({get done(){return U||W!==null},get open(){return C&&!U&&W===null},get bufferedAmount(){return L?.bufferedAmount??0},send(A){if(U||W||!C||!L)return;try{L.send(A)}catch{G({reason:"relay_closed"})}},end:(A)=>{if(U||W)return;if(!("error"in A)){G(A);return}if(W=A,S&&C)E()}}),U){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),y=setTimeout(()=>G({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-P())),R=setTimeout(()=>G({reason:"viewer_absent"}),Q.viewerWaitMs??l1);try{L=(Q.connect??k0)(x.relay_url,(Q.loadProxy??f0)()?.url)}catch{V();return}L.binaryType="arraybuffer",L.onopen=()=>{if(U||!L)return;C=!0,Y?.opened()},L.onmessage=(A)=>{if(U)return;let f=A.data,p=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!p||p.byteLength===0)return;if(clearTimeout(R),S=!0,W){E();return}Y?.received(p)},L.onclose=()=>{if(U)return;if(!C){V();return}G({reason:"relay_closed"})},L.onerror=()=>{if(U||C)return;V()}})}
|
|
251
|
-
export{g8 as
|
|
251
|
+
export{g8 as Yf,D9 as Zf,y9 as _f,d as $f,T8 as ag,FQ as bg,bq as cg,pq as dg,oq as eg,I as fg,t9 as gg,e9 as hg,qQ as ig,c1 as jg,A8 as kg,a1 as lg,O0 as mg,vQ as ng,S8 as og,i1 as pg,uQ as qg};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-vys6qap2.js";import{Dc as p7,Fc as d7,Gc as l7}from"./vm-hands-entry-lite-v0kpksbf.js";import{Lc as g7}from"./vm-hands-entry-lite-e99ftdr6.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-e4kdpq0t.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as t4,bd as e4}from"./vm-hands-entry-lite-0nd56w02.js";import{dd as m7}from"./vm-hands-entry-lite-g7h6wjqy.js";import{hd as H2,id as C2,jd as B4,ld as V4,nd as G4,od as X4,sd as U4,ud as Y7}from"./vm-hands-entry-lite-smrymax6.js";import{Cd as W2,Fd as K9,Od as B9}from"./vm-hands-entry-lite-nnggcccf.js";import{Af as U7,Bf as F7,Ce as g1,De as E1,Ee as n3,Fe as O2,Ge as y6,He as r3,Hf as i8,Ie as _4,If as o8,Je as P4,Jf as t8,Ke as j0,Kf as e8,Lf as $5,Mf as J5,Oe as C0,Of as Z5,Pf as Q5,Qf as K5,Re as s,Rf as B5,Se as c1,Sf as V5,Tf as G5,Uf as X5,Ve as a8,Vf as U5,Wf as F5,Xe as n1,Xf as Y5,Ze as h6,_e as m6,cf as v6,df as u6,ef as p6,ff as d6,gf as l6,hf as s6,if as c6,jf as n6,kf as r6,lf as a6,mf as i6,nf as o6,of as t6,pf as e6,qf as $7,rf as J7,sf as Z7,tf as Q7,vf as K7,wf as B7,xf as V7,yf as G7,zf as X7}from"./vm-hands-entry-lite-qvj5560v.js";import{bg as _6,fg as m5,gg as X6,mg as V9,pg as v5,qg as X2}from"./vm-hands-entry-lite-42chrtkc.js";import{Bg as Q9,sg as e7,tg as $9,ug as J9,yg as Z9}from"./vm-hands-entry-lite-t839nkd2.js";import{Kg as $8,Rg as S7}from"./vm-hands-entry-lite-ps9gjbs5.js";import{Wg as Y2}from"./vm-hands-entry-lite-q5h859gg.js";import{ah as u3,nh as W7}from"./vm-hands-entry-lite-1cs1jy20.js";import{Ji as v7,Ki as u7}from"./vm-hands-entry-lite-6256d8j5.js";import{Wi as A1,Xi as _1,Yi as P1,Zi as T1,_i as k0}from"./vm-hands-entry-lite-sbn9bmf7.js";import{qj as b1,rj as j7,sj as r4,tj as a4}from"./vm-hands-entry-lite-2sx1a43v.js";import{Dj as y8,Ej as k4,vj as v3,xj as B1}from"./vm-hands-entry-lite-29f3m7x2.js";import{$j as i7,Vj as s7,Wj as c7,Xj as n7,Yj as r7,_j as a7,bk as o7,ck as t7}from"./vm-hands-entry-lite-hx4w3r63.js";import{nk as V}from"./vm-hands-entry-lite-f9akybcm.js";import{Dk as z7,Ek as N7,Fk as H7,Gk as n4,Hk as l1,xk as z5,yk as c4}from"./vm-hands-entry-lite-ek5r435m.js";import{Ik as T4}from"./vm-hands-entry-lite-bgs4zjkf.js";import{Kk as H}from"./vm-hands-entry-lite-69n9q5f1.js";import{Qk as g8}from"./vm-hands-entry-lite-5d31qv44.js";import{request as _9}from"http";import{request as P9}from"https";import{lookup as T9}from"dns/promises";import{isIP as R9}from"net";async function q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?P9:_9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),g9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(g9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=Y4(Q,J+1);if(K)return K}return null}async function E9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||R9(Q)!==0)return Z;let K;return await Promise.race([T9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function k9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function S9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,Y=0,F=k9(Q.apiKey),X=S9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await q9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await E9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function f9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>f9(Q.path,J));return Z.length===1?Z[0].path:null}var b9=/^[a-f0-9]{64}$/;var D2=32,x9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!x9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!b9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function y9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function h9($){return y9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?h9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),m9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -34,7 +34,7 @@ Content-Length: 0\r
|
|
|
34
34
|
\r
|
|
35
35
|
`),U8(Y,N,F)})().catch(()=>Y.destroy())}),await new Promise((U,Y)=>{B.once("error",Y),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as l2,randomUUID as k$}from"crypto";import{closeSync as p1,constants as J0,fchownSync as S$,fstatSync as L0,fsyncSync as f$,linkSync as P8,lstatSync as v2,mkdirSync as T8,openSync as v1,readSync as E8,realpathSync as u2,unlinkSync as R8,writeSync as b$}from"fs";import{isAbsolute as x$,join as y$,relative as h$,sep as m$}from"path";import{platform as p2}from"os";import{getSystemErrorName as v$}from"util";var H8={type:"string",format:"uuid"},M8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,x1={type:"string",minLength:1,maxLength:4096,pattern:M8},b2=V.string().min(1).max(4096).regex(new RegExp(M8)),y1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},h1={device_id:H8,root_id:H8,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},iB={read:{schema:V.object({...y1,path:b2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...h1,path:x1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...y1,path:b2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...h1,path:x1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...y1,command:V.string().min(1).max(16000),cwd:b2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...h1,command:{type:"string",minLength:1,maxLength:16000},cwd:x1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},z0=1073741824,Z1=600000,C8=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,j8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${C8}(?:/${C8})*(?![\s\S])`,L8=new RegExp(j8);function O8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&L8.test($)}var x2=V.string().min(1).max(4096).regex(L8),y2={...x1,pattern:j8},I8=V.string().regex(/^[a-f0-9]{64}$/),A8=V.object({kind:V.literal("workspace"),path:x2}).strict(),q$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:I8}).strict()]),m1=1,Q1="cloud_workspace_id",h2="cloud_workspace",m2=1,g$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(z0),sha256:I8}).strict()]),_8=V.object({source_version:V.literal(m1),source:g$,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[Q1]:V.string().min(1).max(160).optional()}).strict(),oB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(m1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var D8=V.object({...y1,timeout_ms:V.number().int().min(1000).max(Z1).optional(),source_path:x2,destination_path:x2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),w8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...h1,timeout_ms:{type:"integer",minimum:1000,maximum:Z1},source_path:y2,destination_path:y2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},E$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:y2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},tB=V.union([D8,D8.omit({source_path:!0}).extend({source:q$}).strict()]),eB={...w8,required:["device_id","root_id","destination_path"],properties:{...w8.properties,source:E$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var s2=65536;function l($){throw new H($,$)}function d1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function u1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return l(Z)}function u$($,J,Z){let Q;switch(d1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return u1($,J,Q)}function p$($){if(typeof $!=="string"||$.length>16384)return l("transfer_url_invalid");let J;try{J=new URL($)}catch{return l("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return l("transfer_url_invalid");return J.href}var d2=J0.O_RDONLY|J0.O_DIRECTORY|J0.O_NOFOLLOW;async function d$(){if(p2()==="win32"){let F=new Map,X,W=-1,z=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(D)=>{let j=h$(X,D);return j===""||j!==".."&&!j.startsWith(`..${m$}`)&&!x$(j)},C=(D)=>{let j=v2(D);if(j.isSymbolicLink())throw z();if(!j.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let O=u2(D);if(X??=O,!N(O))throw z();return F.set(W,{path:D,real:O}),W--},M=(D)=>{let j=F.get(D);if(u2(j.path)!==j.real)throw z();return j.path},w=(D,j)=>{if(l1(j))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return y$(F.get(D).path,j)};return{root:C,openDirectory:(D,j)=>C(w(D,j)),open:(D,j,O,A=384)=>{let b=w(D,j);if(v2(b,{throwIfNoEntry:!1})?.isSymbolicLink())throw z();M(D);let I=v1(b,O,A);try{let R=L0(I),P=v2(b);if(P.isSymbolicLink()||R.ino!==P.ino||R.dev!==P.dev||!N(u2(b)))throw z()}catch(R){throw p1(I),R}return I},mkdir:(D,j)=>{let O=w(D,j);M(D),T8(O)},link:(D,j,O)=>{let A=w(D,j),b=w(D,O);M(D),P8(A,b)},unlink:(D,j)=>R8(w(D,j)),closeDirectory:(D)=>{F.delete(D)},inherit:()=>{},close:()=>{}}}let $={root:(F)=>v1(F,d2),closeDirectory:p1,inherit:l$};if(p2()==="linux")return{...$,openDirectory:(F,X)=>v1(`/proc/self/fd/${F}/${X}`,d2),open:(F,X,W,z=384)=>v1(`/proc/self/fd/${F}/${X}`,W,z),mkdir:(F,X)=>T8(`/proc/self/fd/${F}/${X}`,{mode:448}),link:(F,X,W)=>P8(`/proc/self/fd/${F}/${X}`,`/proc/self/fd/${F}/${W}`),unlink:(F,X)=>R8(`/proc/self/fd/${F}/${X}`),close:()=>{}};if(p2()!=="darwin")return l("transfer_platform_unsupported");let{dlopen:J,FFIType:Z,ptr:Q,read:K}=await import("bun:ffi"),B=J("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:Z.ptr},openat:{args:[Z.i32,Z.ptr,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32],returns:Z.i32},mkdirat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32},linkat:{args:[Z.i32,Z.ptr,Z.i32,Z.ptr,Z.i32],returns:Z.i32},unlinkat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32}}),G=B.symbols.__error();if(G===null)return B.close(),l("transfer_path_unavailable");let U=(F)=>{if(F<0){let X=v$(-K.i32(G));throw Object.assign(Error("transfer_path_unavailable"),{code:X})}return F},Y=(F,X,W,z=384)=>U(B.symbols.openat(F,Q(Buffer.from(`${X}\x00`)),W,z,0,0,0,0,z));return{...$,openDirectory:(F,X)=>Y(F,X,d2),open:Y,mkdir:(F,X)=>{U(B.symbols.mkdirat(F,Q(Buffer.from(`${X}\x00`)),448))},link:(F,X,W)=>{U(B.symbols.linkat(F,Q(Buffer.from(`${X}\x00`)),F,Q(Buffer.from(`${W}\x00`)),0))},unlink:(F,X)=>{U(B.symbols.unlinkat(F,Q(Buffer.from(`${X}\x00`)),0))},close:()=>B.close()}}function l$($,J){let Z=L0($),Q=L0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)S$(J,Z.uid,Z.gid)}function s$($,J,Z,Q){if(!O8(Z))return l("transfer_path_invalid");let K=Z.split("/"),B=$.root(J);try{for(let G of K.slice(0,-1)){let U;try{U=$.openDirectory(B,G)}catch(Y){if(!Q||d1(Y)!=="ENOENT")throw Y;try{$.mkdir(B,G)}catch(F){if(d1(F)!=="EEXIST")throw F}U=$.openDirectory(B,G),$.inherit(B,U)}$.closeDirectory(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw $.closeDirectory(B),G}}function q8($,J){let Z=L0($,{bigint:!0});if(!Z.isFile()||Z.size>z0)return l("transfer_file_invalid");let Q=l2("sha256"),K=Buffer.alloc(s2),B=0;while(!0){J.throwIfAborted();let U=E8($,K,0,K.length,B);if(!U)break;if(B+=U,B>z0)return l("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=L0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return l("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=p$($.payload.url),Z=await d$(),Q,K,B;try{if(Q=s$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK);let z=L0(K,{bigint:!0});if(!z.isFile()||z.size>z0)return l("transfer_file_invalid");let N=l2("sha256"),C=0,M=K,w,D=new ReadableStream({pull(b){try{$.signal.throwIfAborted();let I=Buffer.alloc(s2),R=E8(M,I,0,I.length,C);if(!R){b.close();return}if(C+=R,C>z.size)return l("transfer_source_changed");N.update(I.subarray(0,R)),b.enqueue(I.subarray(0,R))}catch(I){throw w=I,I}}});try{let b=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:D,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(z.size)}},{duplex:"half"}));if(w!==void 0)throw w;if(!b.ok)return l("transfer_upload_failed");await b.body?.cancel()}catch(b){if(w!==void 0)throw w;return u1(b,$.signal,"transfer_upload_failed")}let j=L0(K,{bigint:!0});if(BigInt(C)!==z.size||j.size!==z.size||j.mtimeNs!==z.mtimeNs||j.ctimeNs!==z.ctimeNs)return l("transfer_source_changed");let O=N.digest("hex"),A=q8(K,$.signal);if(A.size_bytes!==C||A.sha256!==O)return l("transfer_source_changed");return{size_bytes:C,sha256:O,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>z0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return l("transfer_receipt_invalid");let Y;try{Y=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK)}catch(z){if(d1(z)!=="ENOENT")throw z}if(Y!==void 0){try{let z=q8(Y,$.signal);if(z.size_bytes===G&&z.sha256===U)return{...z,outcome:"already_present"}}finally{p1(Y)}return l("transfer_destination_exists")}B=`.reason-copy-${k$()}`,K=Z.open(Q.fd,B,J0.O_CREAT|J0.O_EXCL|J0.O_WRONLY|J0.O_NOFOLLOW,384),Z.inherit(Q.fd,K);let F;try{let z=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!z.ok||!z.body)return l("transfer_download_failed");F=z.body.getReader()}catch(z){return u1(z,$.signal,"transfer_download_failed")}let X=l2("sha256"),W=0;try{while(!0){$.signal.throwIfAborted();let z=await F.read().catch((N)=>u1(N,$.signal,"transfer_download_failed"));if(z.done)break;if(W+=z.value.length,W>G)return l("transfer_size_mismatch");X.update(z.value);for(let N=0;N<z.value.length;)$.signal.throwIfAborted(),N+=b$(K,z.value,N,Math.min(s2,z.value.length-N))}}finally{await F.cancel().catch(()=>{})}if(W!==G||X.digest("hex")!==U)return l("transfer_hash_mismatch");return f$(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)p1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}Z.closeDirectory(Q.fd)}}finally{Z.close()}}}}catch(J){return u$(J,$.signal,$.direction)}}import{spawn as n$}from"child_process";import{mkdtempSync as r$,rmSync as a$,writeFileSync as i$}from"fs";import{constants as o$,platform as t$,tmpdir as e$}from"os";import{join as b8}from"path";import{gunzipSync as c$,gzipSync as YV}from"zlib";var S8=900000,zV=S8+60000,K1=49152,k8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),f8=V.object({version:V.literal(1),script_gzip:k8(163840),stdin_gzip:k8(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max(S8)}).strict(),c2=V.string().max(K1+256),NV=V.object({exit_code:V.number().int().min(0).max(255),stdout:c2,stderr:c2,combined:c2.optional()}).strict();function n2($){return c$(Buffer.from($,"base64")).toString("utf8")}var $J="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",JJ=["RUSTUP_HOME","TZ","LC_ALL"],ZJ=2000,QJ=100;function a2(){return t$()==="linux"&&process.geteuid?.()===0}function r2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let Y=U.subarray(0,J-Q);Z.push(Y),Q+=Y.length,U=U.subarray(Y.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
36
36
|
[reason: ${G} bytes of output omitted]
|
|
37
|
-
`:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-3g0rc3wp.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
|
|
37
|
+
`:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-qd3zcysz.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
|
|
38
38
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,M5).split("\x00",1)[0]?.trim();return Q?cJ(Q):null}catch{return null}}async function _5($,J=G3){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function P5($,J=G3){let Z=[];for(let Q of await I5(J)){if(Z.length>=aJ)break;let K=await _5(Q,J);if(!K||!O5($,K))continue;Z.push({pid:Q,command:await A5(Q,J),cwd:QZ($,K)})}return{processes:Z}}function L5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function KZ($){let J=[];for(let Y=0;Y<16;Y+=2)J.push($[Y]<<8|$[Y+1]);if(J.slice(0,5).every((Y)=>Y===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let Y=0;Y<=J.length;Y+=1){if(Y<J.length&&J[Y]===0){if(K<0)K=Y;continue}if(K>=0){let F=Y-K;if(F>Q)Z=K,Q=F;K=-1}}let B=J.map((Y)=>Y.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function BZ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=L5($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...L5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${KZ(Z)}]:${J}`}return null}function VZ($,J){let Z=[];for(let Q of $.split(`
|
|
39
39
|
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=j5)continue;if(K[$Z]?.toUpperCase()!==JZ)continue;let B=K[eJ]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let Y=BZ(B.slice(0,G),U),F=K[j5];if(!Y||!F||!/^[0-9]+$/.test(F))continue;Z.push({inode:F,port:U,address:Y})}return Z}async function GZ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=w5)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...VZ(Q,w5-J.length))}return J}async function XZ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await I5(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,tJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(ZZ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function T5($,J=G3){let Z=await GZ(J),Q=await XZ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let W=Q.get(X.inode);if(W===void 0)continue;K.push({pid:W,port:X.port,address:X.address})}K.sort((X,W)=>X.pid-W.pid||X.port-W.port||(X.address<W.address?-1:X.address>W.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,iJ),G=await Promise.all(B.map(async(X)=>[X,await _5(X,J)])),U=new Map(G),Y=K.filter((X)=>{let W=U.get(X.pid);return Boolean(W&&O5($,W))}),F=new Map(await Promise.all([...new Set(Y.map((X)=>X.pid))].map(async(X)=>[X,await A5(X,J)])));return{ports:Y.slice(0,oJ).map((X)=>({pid:X.pid,command:F.get(X.pid)??null,address:X.address}))}}import{posix as U3}from"path";var i1=200,UZ=250,FZ=250;async function o1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function X3($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var R5="/System/Volumes/Data",YZ=["/tmp","/var","/etc"];function F3($){let J=U3.normalize($);if(J.startsWith(`${R5}/`))J=J.slice(R5.length);return YZ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function q5($){return $&&U3.isAbsolute($)?F3($):null}async function g5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=i1){let K=J.slice(Q,Q+i1).join(",");for(let B of await o1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:q5(B.names[0])})}return Z}async function E5($,J){let Z=F3($),Q=(await o1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=q5(B.names[0]);return G!==null&&X3(Z,G)}).map((B)=>B.pid).slice(0,UZ),K=await g5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&X3(Z,G.cwd)?[{pid:B,command:G.command,cwd:U3.relative(Z,G.cwd)||"."}]:[]})}}async function k5($,J){let Z=F3($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await o1(J,Q),B=await g5(J,K.map((F)=>F.pid)),G=K.map((F)=>F.pid).filter((F)=>{let X=B.get(F)?.cwd;return Boolean(X&&X3(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((F)=>F.names.map((X)=>`${F.pid} ${X}`))),Y=[];for(let F=0;F<G.length;F+=i1){let X=G.slice(F,F+i1).join(",");for(let W of await o1(J,["-a","-p",X,...Q]))for(let z of W.names)if(U.has(`${W.pid} ${z}`))Y.push({pid:W.pid,command:W.command,address:z})}return{ports:Y.slice(0,FZ)}}import{join as AZ}from"path";import{spawn as wZ}from"child_process";import{randomUUID as MZ}from"crypto";import{chmodSync as b5,lstatSync as x5,mkdirSync as jZ,readdirSync as LZ,statSync as OZ,unlinkSync as IZ}from"fs";import{join as W3}from"path";var Y3={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var t1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var I0=()=>{throw Error("proof_visual_contract_invalid")};class S5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function zZ($){if(!X1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new S5;if(!X1($.viewport)||!t1($.viewport.width,1,4096)||!t1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>Y3.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return I0();let J=$.targets.map((Q)=>{if(!X1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return I0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return I0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return I0();Z=$.additionalViewports.map((K)=>{if(!X1(K)||!t1(K.width,1,4096)||!Number.isInteger(K.width)||!t1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return I0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return I0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var HZ=["organizationId","userId","sessionId","runId"],CZ=[...HZ,"prUrl","headSha","skillDigest","evidenceKind"],GG=[...CZ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DZ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function f5($){return DZ[$].directory}var y5=10485760;function h5($={}){let J=$.directory??f5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((w)=>w!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");jZ(J,{recursive:!0,mode:457});let B=x5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");b5(J,457);let G=LZ(J).filter((w)=>/^[a-f0-9-]{36}\.webm$/.test(w)).map((w)=>({name:w,time:OZ(W3(J,w)).mtimeMs})).sort((w,D)=>D.time-w.time);for(let w of G.slice(9))IZ(W3(J,w.name));let U=W3(J,`${MZ()}.webm`),Y=["-f","x11grab","-framerate","12","-i",$.display??":99"],F=($.spawn??wZ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...Y,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(y5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,W,z=!1,N=new Promise((w,D)=>{X=w,W=D});F.stdout.on("data",(w)=>{if(/frame=\s*[1-9]/.test(String(w)))z=!0,X()});let C=new Promise((w,D)=>{F.once("error",()=>{W(Error("cloud_browser_recording_unavailable")),D(Error("cloud_browser_recording_unavailable"))}),F.once("exit",(j)=>{try{if(j!==0&&j!==255)throw Error();let O=x5(U);if(!z||!O.isFile()||O.isSymbolicLink()||O.uid!==process.getuid?.()||O.size<128||O.size>y5+65536)throw Error();b5(U,420),X(),w({path:U,mimeType:"video/webm"})}catch{W(Error("cloud_browser_recording_failed")),D(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let M=setTimeout(()=>F.kill("SIGKILL"),(Number(K)+5)*1000);C.finally(()=>clearTimeout(M)).catch(()=>{}),Z={done:C,stop:()=>{return F.kill("SIGINT"),C}};try{await N}catch(w){throw Z=null,w}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function u5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??m5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AZ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??v5)();return B??=h5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:b1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as E3}from"child_process";import{createHash as lZ,randomUUID as sZ}from"crypto";import{existsSync as Q0,mkdirSync as P3,mkdtempSync as k3,readdirSync as G2,readFileSync as S3,renameSync as cZ,rmSync as Y1,statSync as Q2,writeFileSync as nZ}from"fs";import{homedir as f3,tmpdir as U6}from"os";import{basename as F6,dirname as T3,join as k,relative as Y6,resolve as R3,sep as W6}from"path";var a=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),e1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),p5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),N3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),H3=["home","lock","side_button","siri","apple_pay"],_Z=V.enum(["tree","screenshot","both","none"]),PZ=V.object({...N3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),D0={observe:_Z.optional(),wait_for:PZ.optional(),timeout:V.number().min(0).max(20).optional()},z3=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(H3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),C3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:a}).strict(),V.object({action:V.literal("shutdown"),device:a}).strict(),V.object({action:V.literal("build"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:a.optional(),app_path:e1.optional(),bundle_id:p5.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:a.optional(),bundle_id:p5}).strict(),V.object({action:V.literal("logs"),device:a.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:a.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:e1.optional()}).strict(),V.object({action:V.literal("chrome"),device:a.optional()}).strict(),V.object({action:V.literal("inspect"),device:a.optional()}).strict(),V.object({action:V.literal("tap"),device:a.optional(),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional(),...D0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:a.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...D0}).strict(),V.object({action:V.literal("type"),device:a.optional(),text:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("button"),device:a.optional(),name:V.enum(H3),...D0}).strict(),V.object({action:V.literal("open_url"),device:a.optional(),url:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("steps"),device:a.optional(),steps:V.array(z3).min(1).max(30),...D0}).strict(),V.object({action:V.literal("appearance"),device:a.optional(),mode:V.enum(["light","dark"])}).strict()]),d5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),PG=V.object({text:V.string(),error:V.string().optional(),device:d5.optional(),devices:V.array(d5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var TG=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),$2={device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name. Required for boot and shutdown; for other actions omit it for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string",description:"build_status (required): the build_id a build or run returned."},app_path:{type:"string",description:"launch: the built .app from build_status (or pass bundle_id instead)."},bundle_id:{type:"string",description:"terminate (required); launch: an installed app's bundle id instead of app_path."},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number",description:"tap (with y, unless id or label is given) or swipe (required): start point in device points."},y:{type:"number"},x2:{type:"number",description:"swipe (required, with y2): end point in device points."},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect (instead of x and y)."},label:{type:"string",description:"tap: accessibility label from inspect (instead of x and y)."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string",description:"type (required): the text to type."},name:{type:"string",enum:[...H3],description:"button (required)."},url:{type:"string",description:"open_url (required): the URL or deep link."},mode:{type:"string",enum:["light","dark"],description:"appearance (required)."},steps:{type:"array",maxItems:30,description:"steps (required, at least one) or launch and run: run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},s5=C3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),TZ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},l5=new Set;function RZ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...$2.steps,minItems:1}:$2[$];if(Z===void 0||l5.has($))return Q;return l5.add($),{...Q,description:Z}}var qZ=s5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn($2,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(TZ[J]??[{required:[]}]).map((K)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((B)=>!K.without?.includes(B)).map((B)=>[B,RZ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),gZ={type:"object",properties:{action:{type:"string",enum:s5.map(($)=>$.action.value)},...$2},required:["action"],additionalProperties:!1},RG={...gZ,anyOf:qZ};import{spawn as j3}from"child_process";import{createHash as kZ}from"crypto";import{existsSync as w3,mkdirSync as J2,mkdtempSync as SZ,readdirSync as c5,readFileSync as n5,renameSync as fZ,rmSync as r5,symlinkSync as M3,writeFileSync as U1}from"fs";import{homedir as bZ}from"os";import{dirname as t5,join as x}from"path";import{createInterface as xZ}from"readline";var D3=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
40
40
|
//
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var n=Object.create;var{getPrototypeOf:o,defineProperty:e,getOwnPropertyNames:k,getOwnPropertyDescriptor:p}=Object,l=Object.prototype.hasOwnProperty;function m(a){return this[a]}var q,r,u=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?q??=new WeakMap:r??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?n(o(a)):{};let f=b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c;for(let g of k(a))if(!l.call(f,g))e(f,g,{get:m.bind(a,g),enumerable:!0});if(d)h.set(a,f);return f},v=(a)=>{var b=(j??=new WeakMap).get(a),c;if(b)return b;if(b=e({},"__esModule",{value:!0}),a&&typeof a==="object"||typeof a==="function"){for(var d of k(a))if(!l.call(b,d))e(b,d,{get:m.bind(a,d),enumerable:!(c=p(a,d))||c.enumerable})}return j.set(a,b),b},j,w=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=(a)=>a;function t(a,b){this[a]=s.bind(null,b)}var x=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0,configurable:!0,set:t.bind(b,c)})};var y=(a,b)=>()=>(a&&(b=a(a=0)),b);var z=import.meta.require;
|
|
3
|
-
export{u as
|
|
3
|
+
export{u as Lk,v as Mk,w as Nk,x as Ok,y as Pk,z as Qk};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{_i as F}from"./vm-hands-entry-lite-sbn9bmf7.js";import{bj as T,ej as d,gj as p,kj as n,lj as a}from"./vm-hands-entry-lite-kjjhcjp9.js";import{qj as j,sj as v}from"./vm-hands-entry-lite-2sx1a43v.js";import{Qj as l}from"./vm-hands-entry-lite-3ypjvw3e.js";import{hk as m,ik as h}from"./vm-hands-entry-lite-hx4w3r63.js";import{Qk as y}from"./vm-hands-entry-lite-5d31qv44.js";import{spawnSync as Eq}from"child_process";import{dirname as I}from"path";import{spawn as r}from"child_process";import{accessSync as e,constants as qq}from"fs";import{basename as zq,join as Jq}from"path";var V=null;function O(q){if(V===q)V=null;if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}var _=(q,z)=>{if(V)O(V);let Q=Jq(q,T);try{e(Q,qq.X_OK)}catch{return()=>{}}let J;try{J=r(Q,["--app",q,"--name",zq(q,".app"),"--permission",z==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return J.on("error",()=>{if(V===J)V=null}),J.once("exit",()=>{if(V===J)V=null}),J.unref(),V=J,()=>O(J)};import{chmodSync as Qq,existsSync as x,mkdirSync as Xq,readFileSync as Zq,realpathSync as k,renameSync as $q,statSync as G,writeFileSync as Kq}from"fs";import{dirname as P,isAbsolute as Rq,join as Vq,resolve as S,sep as W}from"path";function U(q=j()){return Vq(v(q),"reason","protected-path-grants.json")}var B=null;function Yq(q){let z=JSON.parse(q);if(!Array.isArray(z?.grants))return[];return z.grants.flatMap((Q)=>{let J=Q;return J&&typeof J.path==="string"&&Rq(J.path)&&(J.kind==="file"||J.kind==="folder")&&typeof J.grantedAt==="number"?[{path:J.path,kind:J.kind,grantedAt:J.grantedAt}]:[]})}function D(q=U()){try{let{mtimeMs:z}=G(q);if(B&&B.file===q&&B.mtimeMs===z)return B.grants;let Q=Yq(Zq(q,"utf8"));return B={file:q,mtimeMs:z,grants:Q},Q}catch{return[]}}function Bq(q,z){return q.kind==="file"?z===q.path:z===q.path||z.startsWith(`${q.path}${W}`)}function Dq(q,z){let Q=S(q);return D(z).some((J)=>Bq(J,Q))}function Sq(q,z){return F(q)&&!Dq(q,z)}function w(q,z){Xq(P(z),{recursive:!0,mode:448});let Q=`${z}.${process.pid}.tmp`;Kq(Q,`${JSON.stringify({version:1,grants:q},null,2)}
|
|
3
3
|
`,{mode:384}),Qq(Q,384),$q(Q,z),B=null}function b(q,z=U(),Q=Date.now()){if(!x(q))throw Error(`No file or folder at ${q}.`);let J=k(q),X=P(z);if(X===J||X.startsWith(`${J}${W}`)||J.startsWith(`${X}${W}`))throw Error("Reason's own configuration folder cannot be allowed.");let Z={path:J,kind:G(J).isDirectory()?"folder":"file",grantedAt:Q},$=D(z).filter((R)=>R.path!==J);return w([...$,Z],z),Z}function u(q,z=U()){let Q=x(q)?k(q):S(q),J=D(z),X=J.filter((Z)=>Z.path!==Q);if(X.length===J.length)return!1;return w(X,z),!0}function wq(q,z,Q){let J=z?"file-read* file-write*":"file-read*";return D(Q).filter((X)=>X.path===q||X.path.startsWith(`${q}${W}`)).map((X)=>`(allow ${J} (${X.kind==="file"?"literal":"subpath"} ${JSON.stringify(X.path)}))`)}var f=`Reason permissions
|
|
4
4
|
|
|
5
5
|
Usage:
|
|
@@ -20,7 +20,7 @@ this Mac may open. Only you can change this list; Sessions cannot.
|
|
|
20
20
|
allow asks for each missing one, or the one named. macOS cannot ask for Full
|
|
21
21
|
Disk Access: allow disk opens its pane, shows the file to add in Finder and
|
|
22
22
|
waits until the worker has it.
|
|
23
|
-
`,M="x-apple.systempreferences:com.apple.preference.security",Nq="curl -fsSL https://reasonmachines.com/install.sh | bash",Hq=180000,Wq=2000,A=["screen","accessibility","disk"],L={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${M}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${M}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${M}?Privacy_AllFiles`}};function s(q){return q.executable}function jq(q,z){if(q==="computer_use_identity_missing")return`Reason's background identity is not installed (${q}); reinstall Reason: ${Nq}`;if(q==="computer_use_identity_outdated")return`Reason's background identity is outdated (${p(z)??"unknown"}; this CLI is ${l}) (${q}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${q}); run the installed \`reason\``}function Cq(q=j()){let z=n(q);if(z.length>0)return{state:"ready",path:I(I(I(z[0]))),prefix:z};let Q=a(z,q)??"computer_use_identity_unavailable";return{state:Q,path:d(q),detail:jq(Q,q)}}function o(){return{identity:()=>Cq(),grants:(q)=>m(q),request:(q,z)=>h(q,z),worker:async()=>(await import("./status-
|
|
23
|
+
`,M="x-apple.systempreferences:com.apple.preference.security",Nq="curl -fsSL https://reasonmachines.com/install.sh | bash",Hq=180000,Wq=2000,A=["screen","accessibility","disk"],L={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${M}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${M}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${M}?Privacy_AllFiles`}};function s(q){return q.executable}function jq(q,z){if(q==="computer_use_identity_missing")return`Reason's background identity is not installed (${q}); reinstall Reason: ${Nq}`;if(q==="computer_use_identity_outdated")return`Reason's background identity is outdated (${p(z)??"unknown"}; this CLI is ${l}) (${q}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${q}); run the installed \`reason\``}function Cq(q=j()){let z=n(q);if(z.length>0)return{state:"ready",path:I(I(I(z[0]))),prefix:z};let Q=a(z,q)??"computer_use_identity_unavailable";return{state:Q,path:d(q),detail:jq(Q,q)}}function o(){return{identity:()=>Cq(),grants:(q)=>m(q),request:(q,z)=>h(q,z),worker:async()=>(await import("./status-r1k521hh.js")).connectionMacState(),open:(q)=>{Eq("/usr/bin/open",q,{stdio:"ignore",timeout:1e4})},tile:_,restartConnection:async()=>(await import("./connect-cli-t2cf1fhv.js")).restartConnection(),sleep:(q)=>new Promise((z)=>setTimeout(z,q)),now:()=>Date.now()}}function c(q,z,Q){if(q.state!=="ready"||!z)return"unknown";return z[Q]?"granted":"missing"}async function i(q){let z=q.identity(),Q=z.state==="ready"?await q.grants(z.prefix):null,J=await q.worker(),X=J?s(J):null,Z=!X||J?.full_disk_access==="unknown"?"unknown":J?.full_disk_access==="granted"?"granted":"missing",$=(R,Y,K)=>{let{label:E,purpose:H,level:N}=L[R];return{id:R,label:E,purpose:H,level:N,state:Y,holder:K}};return{identity:{state:z.state,path:z.path,detail:z.state==="ready"?null:z.detail},worker_detail:X?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[$("screen",c(z,Q,"screen"),z.path),$("accessibility",c(z,Q,"accessibility"),z.path),$("disk",Z,X)]}}function dq(q){let z=q.identity.state==="ready"?null:q.identity.state,Q=q.permissions.filter((Z)=>Z.state==="granted").length,J=[...z?[z]:[],...q.permissions.filter((Z)=>Z.state!=="granted"&&!(z&&Z.id!=="disk")).map((Z)=>`${Z.label} ${Z.state}`)],X=!z&&q.permissions.some((Z)=>Z.state==="missing");return`Permissions: ${Q} of ${q.permissions.length}${J.length>0?` (${J.join(", ")})`:""}`+(X?" \u2014 reason permissions allow":J.length>0?" \u2014 reason permissions":"")}function Uq(q){let z=[];if(q.identity.detail)z.push(q.identity.detail);z.push(`Reason: ${q.identity.path}`);let Q=q.permissions.find((J)=>J.id==="disk");z.push(Q?.holder?`Worker: ${Q.holder}`:`Worker: ${q.worker_detail}`),z.push("");for(let J of q.permissions){let X=`${J.label}${J.level==="recommended"?" (recommended)":""}`;z.push(` ${J.id.padEnd(13)} ${J.state.padEnd(7)} ${X}: ${J.purpose}`)}if(q.permissions.some((J)=>J.state==="missing"))z.push("","Allow the missing ones: reason permissions allow");return`${z.join(`
|
|
24
24
|
`)}
|
|
25
25
|
`}async function g(q,z){let Q=z.now()+Hq;for(;;){if(await q())return!0;if(z.now()>=Q)return!1;await z.sleep(Wq)}}async function Iq(q,z){let Q=z.host??o(),{io:J}=z,X=await i(Q),Z=X.permissions.filter((K)=>q.includes(K.id)&&K.state!=="granted");if(Z.length===0)return J.stdout.write(`Reason permissions: ${q.map((K)=>L[K].label).join(", ")} already allowed.
|
|
26
26
|
`),0;let $=!1,R=!1,Y=Q.identity();for(let K of Z){let{label:E,pane:H}=L[K.id];if(K.id!=="disk"){if(Y.state!=="ready"){if(!$)J.stderr.write(`Reason permissions: ${Y.detail}
|
|
@@ -49,4 +49,4 @@ ${f}`),1;if(J.command==="help")return Q.stdout.write(f),0;if(J.command==="protec
|
|
|
49
49
|
`).join(""):`No protected paths are allowed on this computer.
|
|
50
50
|
`),0}catch(Q){return z.stderr.write(`${Q instanceof Error?Q.message:String(Q)}
|
|
51
51
|
`),1}}
|
|
52
|
-
export{Sq as
|
|
52
|
+
export{Sq as Ji,wq as Ki,_ as Li,f as Mi,A as Ni,s as Oi,Cq as Pi,i as Qi,dq as Ri,Uq as Si,Iq as Ti,Mq as Ui,pq as Vi};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Df as jJ,Oe as _J,We as gJ,Xe as OJ,Ye as RJ,Ze as IJ}from"./vm-hands-entry-lite-02zaqpgh.js";import{createHash as m,randomBytes as WJ}from"crypto";import{closeSync as MJ,fsyncSync as TJ,mkdirSync as aJ,openSync as DJ,renameSync as nJ,rmSync as tJ,statSync as qJ,writeSync as xJ,constants as y}from"fs";import{join as t}from"path";var eJ=1;var e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function FJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new F("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function AJ(J,Q){let{payload:$,authority:z}=J;if(!$||typeof $!=="object"||Array.isArray($)||!z||typeof z!=="object"||Array.isArray(z)||!Q.deviceId||!Q.rootId||$.run_id!==Q.runId||$.device_id!==Q.deviceId||z.device_id!==Q.deviceId||$.root_id!==Q.rootId||Q.snapshotId!==void 0&&$.snapshot_id!==Q.snapshotId)throw new F("vm_hands_env_invalid","environment does not match this Hands");return $}function SJ(J){if(J.capability!=="hands.connect")throw new F("vm_hands_bind_invalid","not a hands.connect claim");let Q=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 Q.workspace_id==="string"&&e.test(Q.workspace_id)?Q.workspace_id:J.run_id,brain_generation:Q.target_generation,fence_id:Q.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Q.hands_confinement??""),browser_egress:Q.browser_egress??null,policy_digest:Q.vm_hands_policy_digest},cwd:typeof Q.cwd==="string"?Q.cwd:"",claim:J,env:FJ(J)?J.environment_sealed:null,workspace_deferred:JQ(J)}}function JQ(J){let Q=J.payload[OJ];if(Q===void 0)return!1;if(Q!==!0||J.payload.vm_hands_env_deferred!==!0||J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class F extends Error{code;constructor(J,Q){super(Q);this.code=J}}var I=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),b=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function c(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(c).join(",")}]`;return`{${Object.keys(J).sort().map((Q)=>`${JSON.stringify(Q)}:${c(J[Q])}`).join(",")}}`}async function SQ(J){let Q=await crypto.subtle.importKey("pkcs8",b(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),$=b(J.device_key.spki),z=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),L=new Uint8Array(await crypto.subtle.exportKey("spki",z.publicKey)),U=m("sha256").update($).digest("base64url");return{signing:{privateKey:Q},agreement:z,signingSpki:$,agreementSpki:L,fingerprint:U}}var QQ=4;class ZQ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;commandsSinceVerified=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(J){let Q=this.structural.then(J,J);return this.structural=Q.catch(()=>{return}),Q}constructor(J,Q,$,z){this.init=J;this.keys=Q;this.hooks=$;this.options=z;if(!e.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new F("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new F("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Q of this.bound.values())if(Q.runId===J)return!0;return!1}bindIdForRun(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Q,$){for(let z=Date.now()+Q;;){let L=this.bound.get(J);if(!L)return!1;if(L.envInstalled)return!0;if(Date.now()>=z||$?.aborted)return!1;await new Promise((U)=>setTimeout(U,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new F("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new F("vm_hands_challenge_invalid","bad register challenge");let Q={challenge:J,t:"register",v:eJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:I(this.keys.signingSpki),env_public_key:I(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:I(WJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},$=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(c(Q)));return{...Q,device_signature:I($)}}async helloFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","hello before register");let $=String((this.options.now??Date.now)()),z=I(WJ(32)),L=jJ({method:"GET",pathAndQuery:_J,timestamp:$,nonce:z,challenge:J,bodySha256:m("sha256").update("").digest("hex")}),U=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(L)));return{t:"hello",timestamp:$,nonce:z,signature:I($Q(U)),...Q?{vm_hands_previous_connection:Q}:{}}}registered(){if(this.identity!=="identity_free")throw new F("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new F("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new F("vm_hands_bind_invalid","bad bind");for(let $ of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!e.test($))throw new F("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new F("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 F("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new F("vm_hands_bind_invalid","bad policy or nonce");if(m("sha256").update(c({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new F("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some(($)=>$.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new F("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=QQ)throw new F("vm_hands_busy","every bind slot is held");if(this.grants.size)throw new F("vm_hands_busy","a bind waits for its workspace beside the setup");if(J.workspace_deferred&&(this.liveBindIds.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),J.workspace_deferred){let $,z,L=new Promise((U,N)=>{$=U,z=N});L.catch(()=>{return}),this.grants.set(J.bind_id,{promise:L,resolve:$,reject:z})}return this.exclusive(()=>this.setUp(J))}async setUp(J){let Q=[...this.bound.keys()],$=null,z=!1,L=this.grants.get(J.bind_id);try{if(L&&(Q.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(Q.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new F("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.commandsSinceVerified)await this.hooks.killAndVerifyPayload(),this.unverified.clear(),this.commandsSinceVerified=!1;else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({own:!0}),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Q}),this.unverified.clear();this.servedRun=!0,z=!0;let{launchId:U,applied:N,readyData:O}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim,...L?{workspaceGrant:L.promise}:{}}),T=this.hooks.restatLayout();this.hooks.verifyMounts?.();let D=null,A=null;if(J.env){let w=J.claim?.owner??{},v=AJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,D=this.hooks.installEnvironment(J.bind_id,v),A=typeof v.snapshot_id==="string"&&v.snapshot_id?v.snapshot_id:null,$=this.writeJobEnvRootOnly(J.bind_id,v)}if(this.unbinding.has(J.bind_id))throw new F("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:D!==null,rootId:J.claim?.root_id??"",envDirectory:$}),this.binding.delete(J.bind_id),this.grants.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:D,snapshot_id:A,layout:T,...O?{ready_data:O}:{},policy_digest:m("sha256").update(c({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(U){if($)KJ($);if(z){let O=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:O,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id),this.grants.delete(J.bind_id);let N=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof F?U:new F(N,"executor refused the bind")}}grantWorkspace(J){let Q=this.grants.get(J);if(!Q)throw new F("vm_hands_not_binding","no pre-bind waits for a workspace grant");Q.resolve()}abandonWorkspaceGrant(J){this.grants.get(J)?.reject(new F("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(J){let Q=this.bound.get(J.attemptId);if(!Q||this.unbinding.has(J.attemptId))throw new F("vm_hands_not_bound","environment delivered while not bound");if(!e.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new F("vm_hands_env_invalid","bad snapshot id");let $=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==$)throw new F("vm_hands_env_invalid","bad env envelope");let z=AJ(await this.openSealed(J.sealed,$),{runId:Q.runId,deviceId:J.deviceId,rootId:Q.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let L=this.hooks.installEnvironment(Q.bindId,z);if(Q.envInstalled=!0,Q.envDirectory)KJ(Q.envDirectory);return Q.envDirectory=null,Q.envDirectory=this.writeJobEnvRootOnly(`${Q.bindId}-r${L}`,z),{snapshot_id:J.snapshotId,installed_revision:L,installed:!0}}async attestFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new F("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new F("vm_hands_attest_invalid","attest beside a bind");let $=await this.hooks.runProbe({nonce:Q,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Q,exit_code:$.exitCode,markers:$.markers,proof_dir_inode:$.proofDirInode,script_sha256:m("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Q=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),this.abandonWorkspaceGrant(J),Q)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Q))}async retryUnbind(J){if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(J,this.unverifiedTeardowns.get(J)??null,!0)})}async tearDown(J,Q,$=!1){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((U)=>U!==J),L=!z.length&&($||!this.commandsSinceVerified);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:L?{bindId:J,own:!0}:void 0)}catch(U){if(this.unverified.add(J),!this.unverifiedTeardowns.has(J))this.unverifiedTeardowns.set(J,Q);throw U}if(this.unverified.delete(J),!z.length&&!$)this.unverified.clear(),this.commandsSinceVerified=!1;if(Q?.envDirectory)KJ(Q.envDirectory);return this.unverifiedTeardowns.delete(J),{bind_id:Q?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length||$?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Q){let $=()=>{throw new F("vm_hands_env_invalid","env did not decrypt")},z=await crypto.subtle.importKey("spki",b(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch($),L=await crypto.subtle.deriveKey({name:"ECDH",public:z},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),U=await crypto.subtle.decrypt({name:"AES-GCM",iv:b(J.iv),additionalData:new TextEncoder().encode(Q)},L,b(J.ct)).catch($),N=JSON.parse(new TextDecoder().decode(U));if(!N||typeof N!=="object"||Array.isArray(N))throw new F("vm_hands_env_invalid","env not an object");return N}writeJobEnvRootOnly(J,Q){let $=t(this.options.envRoot,`bind-${J}`);aJ($,{mode:448});let z=qJ($);if(!z.isDirectory()||(z.mode&63)!==0||z.uid!==(process.getuid?.()??-1))throw new F("vm_hands_env_dir_unsafe","env directory is not root's 0700");let L=Q.variables&&typeof Q.variables==="object"?Q.variables:{},U=Object.entries(L).filter(([T,D])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(T)&&typeof D==="string").map(([T,D])=>`export ${T}='${String(D).replaceAll("'","'\\''")}'`).join(`
|
|
2
|
+
import{$e as OJ,Hf as jJ,Se as _J,_e as gJ,af as RJ,bf as IJ}from"./vm-hands-entry-lite-qvj5560v.js";import{createHash as m,randomBytes as WJ}from"crypto";import{closeSync as MJ,fsyncSync as TJ,mkdirSync as aJ,openSync as DJ,renameSync as nJ,rmSync as tJ,statSync as qJ,writeSync as xJ,constants as y}from"fs";import{join as t}from"path";var eJ=1;var e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function FJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new F("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function AJ(J,Q){let{payload:$,authority:z}=J;if(!$||typeof $!=="object"||Array.isArray($)||!z||typeof z!=="object"||Array.isArray(z)||!Q.deviceId||!Q.rootId||$.run_id!==Q.runId||$.device_id!==Q.deviceId||z.device_id!==Q.deviceId||$.root_id!==Q.rootId||Q.snapshotId!==void 0&&$.snapshot_id!==Q.snapshotId)throw new F("vm_hands_env_invalid","environment does not match this Hands");return $}function SJ(J){if(J.capability!=="hands.connect")throw new F("vm_hands_bind_invalid","not a hands.connect claim");let Q=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 Q.workspace_id==="string"&&e.test(Q.workspace_id)?Q.workspace_id:J.run_id,brain_generation:Q.target_generation,fence_id:Q.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Q.hands_confinement??""),browser_egress:Q.browser_egress??null,policy_digest:Q.vm_hands_policy_digest},cwd:typeof Q.cwd==="string"?Q.cwd:"",claim:J,env:FJ(J)?J.environment_sealed:null,workspace_deferred:JQ(J)}}function JQ(J){let Q=J.payload[OJ];if(Q===void 0)return!1;if(Q!==!0||J.payload.vm_hands_env_deferred!==!0||J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class F extends Error{code;constructor(J,Q){super(Q);this.code=J}}var I=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),b=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function c(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(c).join(",")}]`;return`{${Object.keys(J).sort().map((Q)=>`${JSON.stringify(Q)}:${c(J[Q])}`).join(",")}}`}async function SQ(J){let Q=await crypto.subtle.importKey("pkcs8",b(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),$=b(J.device_key.spki),z=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),L=new Uint8Array(await crypto.subtle.exportKey("spki",z.publicKey)),U=m("sha256").update($).digest("base64url");return{signing:{privateKey:Q},agreement:z,signingSpki:$,agreementSpki:L,fingerprint:U}}var QQ=4;class ZQ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;commandsSinceVerified=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(J){let Q=this.structural.then(J,J);return this.structural=Q.catch(()=>{return}),Q}constructor(J,Q,$,z){this.init=J;this.keys=Q;this.hooks=$;this.options=z;if(!e.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new F("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new F("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Q of this.bound.values())if(Q.runId===J)return!0;return!1}bindIdForRun(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Q,$){for(let z=Date.now()+Q;;){let L=this.bound.get(J);if(!L)return!1;if(L.envInstalled)return!0;if(Date.now()>=z||$?.aborted)return!1;await new Promise((U)=>setTimeout(U,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new F("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new F("vm_hands_challenge_invalid","bad register challenge");let Q={challenge:J,t:"register",v:eJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:I(this.keys.signingSpki),env_public_key:I(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:I(WJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},$=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(c(Q)));return{...Q,device_signature:I($)}}async helloFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","hello before register");let $=String((this.options.now??Date.now)()),z=I(WJ(32)),L=jJ({method:"GET",pathAndQuery:_J,timestamp:$,nonce:z,challenge:J,bodySha256:m("sha256").update("").digest("hex")}),U=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(L)));return{t:"hello",timestamp:$,nonce:z,signature:I($Q(U)),...Q?{vm_hands_previous_connection:Q}:{}}}registered(){if(this.identity!=="identity_free")throw new F("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new F("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new F("vm_hands_bind_invalid","bad bind");for(let $ of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!e.test($))throw new F("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new F("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 F("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new F("vm_hands_bind_invalid","bad policy or nonce");if(m("sha256").update(c({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new F("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some(($)=>$.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new F("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=QQ)throw new F("vm_hands_busy","every bind slot is held");if(this.grants.size)throw new F("vm_hands_busy","a bind waits for its workspace beside the setup");if(J.workspace_deferred&&(this.liveBindIds.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),J.workspace_deferred){let $,z,L=new Promise((U,N)=>{$=U,z=N});L.catch(()=>{return}),this.grants.set(J.bind_id,{promise:L,resolve:$,reject:z})}return this.exclusive(()=>this.setUp(J))}async setUp(J){let Q=[...this.bound.keys()],$=null,z=!1,L=this.grants.get(J.bind_id);try{if(L&&(Q.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(Q.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new F("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.commandsSinceVerified)await this.hooks.killAndVerifyPayload(),this.unverified.clear(),this.commandsSinceVerified=!1;else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({own:!0}),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Q}),this.unverified.clear();this.servedRun=!0,z=!0;let{launchId:U,applied:N,readyData:O}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim,...L?{workspaceGrant:L.promise}:{}}),T=this.hooks.restatLayout();this.hooks.verifyMounts?.();let D=null,A=null;if(J.env){let w=J.claim?.owner??{},v=AJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,D=this.hooks.installEnvironment(J.bind_id,v),A=typeof v.snapshot_id==="string"&&v.snapshot_id?v.snapshot_id:null,$=this.writeJobEnvRootOnly(J.bind_id,v)}if(this.unbinding.has(J.bind_id))throw new F("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:D!==null,rootId:J.claim?.root_id??"",envDirectory:$}),this.binding.delete(J.bind_id),this.grants.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:D,snapshot_id:A,layout:T,...O?{ready_data:O}:{},policy_digest:m("sha256").update(c({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(U){if($)KJ($);if(z){let O=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:O,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id),this.grants.delete(J.bind_id);let N=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof F?U:new F(N,"executor refused the bind")}}grantWorkspace(J){let Q=this.grants.get(J);if(!Q)throw new F("vm_hands_not_binding","no pre-bind waits for a workspace grant");Q.resolve()}abandonWorkspaceGrant(J){this.grants.get(J)?.reject(new F("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(J){let Q=this.bound.get(J.attemptId);if(!Q||this.unbinding.has(J.attemptId))throw new F("vm_hands_not_bound","environment delivered while not bound");if(!e.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new F("vm_hands_env_invalid","bad snapshot id");let $=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==$)throw new F("vm_hands_env_invalid","bad env envelope");let z=AJ(await this.openSealed(J.sealed,$),{runId:Q.runId,deviceId:J.deviceId,rootId:Q.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let L=this.hooks.installEnvironment(Q.bindId,z);if(Q.envInstalled=!0,Q.envDirectory)KJ(Q.envDirectory);return Q.envDirectory=null,Q.envDirectory=this.writeJobEnvRootOnly(`${Q.bindId}-r${L}`,z),{snapshot_id:J.snapshotId,installed_revision:L,installed:!0}}async attestFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new F("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new F("vm_hands_attest_invalid","attest beside a bind");let $=await this.hooks.runProbe({nonce:Q,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Q,exit_code:$.exitCode,markers:$.markers,proof_dir_inode:$.proofDirInode,script_sha256:m("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Q=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),this.abandonWorkspaceGrant(J),Q)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Q))}async retryUnbind(J){if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(J,this.unverifiedTeardowns.get(J)??null,!0)})}async tearDown(J,Q,$=!1){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((U)=>U!==J),L=!z.length&&($||!this.commandsSinceVerified);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:L?{bindId:J,own:!0}:void 0)}catch(U){if(this.unverified.add(J),!this.unverifiedTeardowns.has(J))this.unverifiedTeardowns.set(J,Q);throw U}if(this.unverified.delete(J),!z.length&&!$)this.unverified.clear(),this.commandsSinceVerified=!1;if(Q?.envDirectory)KJ(Q.envDirectory);return this.unverifiedTeardowns.delete(J),{bind_id:Q?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length||$?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Q){let $=()=>{throw new F("vm_hands_env_invalid","env did not decrypt")},z=await crypto.subtle.importKey("spki",b(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch($),L=await crypto.subtle.deriveKey({name:"ECDH",public:z},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),U=await crypto.subtle.decrypt({name:"AES-GCM",iv:b(J.iv),additionalData:new TextEncoder().encode(Q)},L,b(J.ct)).catch($),N=JSON.parse(new TextDecoder().decode(U));if(!N||typeof N!=="object"||Array.isArray(N))throw new F("vm_hands_env_invalid","env not an object");return N}writeJobEnvRootOnly(J,Q){let $=t(this.options.envRoot,`bind-${J}`);aJ($,{mode:448});let z=qJ($);if(!z.isDirectory()||(z.mode&63)!==0||z.uid!==(process.getuid?.()??-1))throw new F("vm_hands_env_dir_unsafe","env directory is not root's 0700");let L=Q.variables&&typeof Q.variables==="object"?Q.variables:{},U=Object.entries(L).filter(([T,D])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(T)&&typeof D==="string").map(([T,D])=>`export ${T}='${String(D).replaceAll("'","'\\''")}'`).join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,N=t($,`.job.env.${WJ(8).toString("hex")}`),O=DJ(N,y.O_WRONLY|y.O_CREAT|y.O_EXCL|y.O_NOFOLLOW,384);try{xJ(O,U),TJ(O)}finally{MJ(O)}return nJ(N,t($,"job.env")),$}}function KJ(J){try{let Q=t(J,"job.env"),$=qJ(Q).size,z=DJ(Q,y.O_WRONLY|y.O_NOFOLLOW);try{xJ(z,Buffer.alloc($)),TJ(z)}finally{MJ(z)}}catch{}tJ(J,{recursive:!0,force:!0})}function $Q(J){if(J.length!==64)throw new F("vm_hands_signature_invalid","unexpected ECDSA signature length");let Q=(L)=>{let U=0;while(U<L.length-1&&L[U]===0)U++;let N=L.subarray(U),O=N[0]&128?Uint8Array.of(0,...N):N;return Uint8Array.of(2,O.length,...O)},$=Q(J.subarray(0,32)),z=Q(J.subarray(32));return Uint8Array.of(48,$.length+z.length,...$,...z)}import{randomUUID as zQ}from"crypto";var XQ="/app/local-runtime/session?register=vm_hands_v1",YQ="/app/local-runtime",wJ=25000,hJ=20000,GQ=1e4,yJ=5000,kJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),PJ=75000,WQ=2000,KQ=1e4,FQ=new Set(["vm_hands_no_register","vm_hands_register_failed"]),PQ=3,CQ=20000,NQ=250,UQ=2000;function fJ(J){let Q=Math.min(NQ*2**(J-1),UQ);return Math.round(Q/2+Math.random()*Q/2)}var EQ=5000;function BQ(J){return J>=500||J===408||J===429}var JJ=20000;function HJ(J,Q){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Q}class V extends Error{}var LQ=64,VJ=[1000,2000,4000,8000,15000,30000,60000,120000];function mJ(J){let Q=J&&typeof J==="object"&&"code"in J?J.code:null;return typeof Q==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(Q)?Q:"vm_hands_unbind_failed"}function AQ(J,Q,$,z,L){let U=$.turn.claim.attempt_id,N=J.healing??=new Set;if(N.has(U))return;N.add(U);let O=$.turn.claim.operation_id;(async()=>{for(let[T,D]of VJ.entries()){if(z.aborted)return;if(await new Promise((A)=>{let w=setTimeout(A,D);w.unref?.(),z.addEventListener("abort",()=>{clearTimeout(w),A()},{once:!0})}),z.aborted)return;try{let A=await Q.retryUnbind(U);L("vm_hands.unbind_healed",{operation_id:O,attempt:T+1}),J.receipts.push({...$,unbound:A}),J.flushReceipts?.();return}catch(A){let w=mJ(A);if(L("vm_hands.unbind_unverified",{operation_id:O,code:w,attempt:T+1}),w==="vm_hands_unbind_unknown")return}}L("vm_hands.unbind_heal_exhausted",{operation_id:O,attempts:VJ.length})})().finally(()=>N.delete(U))}async function bJ(J,Q){let $=[...J.modelOps.get(Q)??[]];for(let z of $)z.abort.abort();await Promise.race([Promise.all($.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,yJ))])}async function _Q(J){let Q=[...J.personTerminals];for(let $ of Q)$.abort.abort();if(Q.length)await Promise.race([Promise.all(Q.map(($)=>$.settled)),new Promise(($)=>setTimeout($,yJ))]);return Q.length}async function p(J,Q,$){return await bJ(J,$),Q.unbind($)}function QJ(J){for(let Q of J.outbox?.splice(0)??[])Q.reject(Error("vm_hands_attempt_ended"))}var vJ=15000,OQ=1e4,jQ=1000;async function vQ(J){let Q=Date.now(),$={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:0},z=J.log??(()=>{}),L=async(O)=>{for(let[T,D]of[...$.turns]){$.turns.delete(T),J.onTurn?.(T,null),QJ(D);let A=await p($,J.agent,T).catch(()=>null);if(A)$.receipts.push({turn:D,failure:"vm_hands_bind_lost",unbound:A});z("vm_hands.bound_dropped",{reason:O})}},U=0,N=0;try{for(let O=0;!J.signal.aborted;O++){let T=await MQ(J,$).catch((A)=>{if(A instanceof F&&$.deviceId===null&&A.code==="vm_hands_no_session"&&Date.now()-Q<KQ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(A instanceof F&&$.deviceId===null&&FQ.has(A.code)&&U<PQ&&Date.now()-Q<CQ)return U++,N=fJ(U),z("vm_hands.register_retry",{attempt:U,code:A.code,delay_ms:N}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(A instanceof F&&$.deviceId===null)throw A;return{closeCode:0,closeReason:A instanceof Error?A.message:String(A)}});if(z("vm_hands.session_closed",{close_code:T.closeCode,reason:T.closeReason.slice(0,120),registered:$.deviceId!==null}),T.closeCode===4401||$.attest==="refused")return;if(J.signal.aborted)return;if($.turns.size&&Date.now()-$.lostAt>=PJ)await L("reconnect_deadline");if($.served)$.served=!1,O=0;let D=T.closeReason==="drain_reconnect"?0:T.closeReason==="vm_hands_register_retry"?N:T.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(O,5),2000):$.turns.size?Math.min(250*2**Math.min(O,5),5000,Math.max(0,$.lostAt+PJ-Date.now())):Math.min(500*2**O,30000);if(await new Promise((A)=>setTimeout(A,D)),$.turns.size&&Date.now()-$.lostAt>=PJ)await L("reconnect_deadline")}}finally{await L("session_ended")}}async function MQ(J,Q){let $=Q.deviceId,z=J.log??(()=>{}),L=$?`/app/local-runtime/session?device_id=${encodeURIComponent($)}`:XQ,U=`${J.apiOrigin.replace(/^http/,"ws")}${L}`,N=new WebSocket(U),O=0,T="",D=new Map,A=[],w=null,v=new Promise((Z)=>{N.onclose=(Y)=>{O=Y.code,T=Y.reason;for(let X of D.values())X.reject(new V(`session closed ${Y.code}`));for(let X of Q.attestWaiters.splice(0))X(!1);D.clear(),Z()}});N.onmessage=(Z)=>{let Y;try{Y=JSON.parse(String(Z.data))}catch{N.close(4400);return}if(Y.t==="res"){let X=Y;D.get(X.id)?.resolve({status:X.status,body:X.body}),D.delete(X.id);return}if(Y.t==="reconnect"){let X=Math.max(0,Math.min(Number(Y.after_ms)||0,jQ));z("vm_hands.drain_reconnect",{after_ms:X}),setTimeout(()=>{try{N.close(4001,"drain_reconnect")}catch{}},X).unref?.();return}if(!w?.(Y))A.push(Y)};let l=(Z,Y)=>new Promise((X,K)=>{let C=A.findIndex((B)=>Z.includes(B.t));if(C>=0){X(A.splice(C,1)[0]);return}let E=setTimeout(()=>{w=null,K(new F("vm_hands_no_register",`no ${Z.join("/")} in ${Y} ms`))},Y);w=(B)=>{if(!Z.includes(B.t))return!1;return clearTimeout(E),w=null,X(B),!0}}),u=(Z)=>N.send(JSON.stringify(Z)),k=(Z,Y)=>new Promise((X,K)=>{if(N.readyState!==WebSocket.OPEN){K(new V("session closed"));return}let C=zQ(),E=typeof Y.wait_ms==="number"?Y.wait_ms:0,B=setTimeout(()=>{if(!D.delete(C))return;K(new V(`no answer to ${Z.split("/").pop()} in ${E+vJ} ms`)),N.close(4000,"request_timeout")},E+vJ);D.set(C,{reject:(G)=>{clearTimeout(B),K(G)},resolve:({status:G,body:W})=>{clearTimeout(B);let P=null;try{P=W?JSON.parse(W):null}catch{}X({status:G,json:P})}}),u({t:"req",id:C,path:`${YQ}${Z}`,body:JSON.stringify(Y)})}),CJ=()=>N.close(1001,"stopping");J.signal.addEventListener("abort",CJ,{once:!0});let ZJ,o=new Map,d=new Map,$J=!1,zJ=new Set,XJ=new Set,YJ=Promise.resolve(),NJ=()=>{r().catch(()=>{return})},i=!1;try{await new Promise((G,W)=>{let P=setTimeout(()=>W(Error("session open timeout")),OQ);N.onopen=()=>{clearTimeout(P),z("vm_hands.ws_open",{}),G()},N.onerror=()=>{clearTimeout(P),W(Error("session socket error"))}});let Z=await l(["challenge"],5000);z("vm_hands.challenge",{});let Y=[],X=null,K;if($){u(await J.agent.helloFrame(Z.challenge,Q.connection));let G=await l(["ready"],1e4);if(typeof G.vm_hands_connection==="string")Q.connection=G.vm_hands_connection;if(K={device_id:$,...G.cadence?{cadence:G.cadence}:{}},typeof G.vm_hands_probe_script==="string"){if(X=G.vm_hands_probe_script,i=!0,J.agent.phase==="registered"&&!Q.turns.size)Q.attest="pending"}Q.served=!0,z("vm_hands.reconnected",{device_id:$});let W=Array.isArray(G.vm_hands_binds)?G.vm_hands_binds:G.vm_hands_bind?[G.vm_hands_bind]:[];for(let[P,M]of[...Q.turns]){if(W.some((x)=>x&&x.operation_id===M.claim.operation_id&&x.attempt_id===M.claim.attempt_id)){Y.push(M),z("vm_hands.bound_resumed",{operation_id:M.claim.operation_id});continue}Q.turns.delete(P),J.onTurn?.(P,null),QJ(M);let q=await p(Q,J.agent,P).catch((x)=>s(x,M,"vm_hands_bind_lost"));if(q)Q.receipts.push({turn:M,failure:"vm_hands_bind_lost",unbound:q});z("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{u(await J.agent.registerFrame(Z.challenge)),z("vm_hands.register_sent",{});let G=await Promise.race([l(["registered","register_refused"],1e4),v.then(()=>{throw new F(T==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(G.t==="register_refused")throw new F(G.code,"register refused");J.agent.registered();let W=G;if(K=W,Q.deviceId=W.device_id,typeof W.vm_hands_connection==="string")Q.connection=W.vm_hands_connection;if(typeof W.vm_hands_probe_script==="string"){if(X=W.vm_hands_probe_script,i=!0,J.agent.phase==="registered"&&!Q.turns.size)Q.attest="pending"}Q.served=!0,z("vm_hands.registered",{device_id:K.device_id})}let C=async()=>{let G=await k("/heartbeat",await J.heartbeat());if(G.status>=300)throw Error(`heartbeat ${G.status}`)};await C();let E=K.cadence?.presence_interval_ms??30000;if(ZJ=setInterval(()=>{C().catch(()=>N.close())},E),X&&Q.attest!=="accepted"&&J.agent.phase==="registered"&&!Q.turns.size)pJ(X,Z.challenge);let B=(G,W)=>{d.set(G,W().catch(async(P)=>{if(await UJ(P,G),P instanceof V)N.close();else await r().catch(()=>{return})}).finally(()=>{d.delete(G)}))};Q.flushReceipts=NJ;try{await r();for(let G of Y)G.flush=()=>EJ(G),G.flush(),B(G.claim.attempt_id,()=>BJ(G));while(!J.signal.aborted&&N.readyState===WebSocket.OPEN){let G=await k("/operations/claim",{wait_ms:Math.min(K.cadence?.claim_wait_ms??wJ,wJ)});if(G.status===204||!G.json)continue;if(G.status>=300)throw Error(`claim ${G.status}`);let W=G.json;if(W.capability==="hands.connect"){if(d.has(W.attempt_id)){h({claim:W,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}B(W.attempt_id,()=>lJ(W))}else oJ(W).catch(()=>{return})}}catch(G){await UJ(G,null)}}finally{if(ZJ)clearInterval(ZJ);J.signal.removeEventListener("abort",CJ);for(let Z of Q.turns.values())Z.flush=null;if(Q.flushReceipts===NJ)Q.flushReceipts=null;N.close(),await v,await Promise.all([...d.values()]);for(let Z of J.agent.liveBindIds){if(Q.turns.has(Z))continue;let Y=o.get(Z),X=Y?{...Y,eventSeq:Y.eventSeq+1}:null,K=await p(Q,J.agent,Z).catch((C)=>X?s(C,X,"vm_hands_bind_lost"):null);if(K&&X)Q.receipts.push({turn:X,failure:"vm_hands_bind_lost",unbound:K});z("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let Z of zJ)Z.abort()}return{closeCode:O,closeReason:T};async function UJ(Z,Y){if(Z instanceof V){if(!$J&&Q.turns.size)Q.lostAt=Date.now();$J=!0}else{let X=Y!==null?[Y]:[...new Set([...Q.turns.keys(),...J.agent.liveBindIds])];if(Y===null)$J=!0;for(let K of X){let C=Q.turns.get(K);if(Q.turns.delete(K),C)QJ(C),J.onTurn?.(K,null);if(J.agent.liveBindIds.includes(K)){let E=o.get(K)??C,B=E?{...E,eventSeq:E.eventSeq+1}:null,G=await p(Q,J.agent,K).catch((W)=>B?s(W,B,"vm_hands_bind_lost"):null);if(G&&B)Q.receipts.push({turn:B,failure:"vm_hands_bind_lost",unbound:G})}}}z("vm_hands.session_lost",{error:Z instanceof Error?Z.message:String(Z),bound_kept:Q.turns.size})}function h(Z){let Y=Z.claim,X={attempt_id:Y.attempt_id,attempt_token:Y.attempt_token},K=encodeURIComponent(Y.operation_id);return{fence:X,op:K,complete:(E,B={})=>k(`/operations/${K}/complete`,{...X,status:E,...B}),emit:(E,B)=>{let G=(Z.chain??Promise.resolve()).catch(()=>{return}).then(()=>C(E,B));return Z.chain=G,G}};async function C(E,B){let G=Z.eventSeq,W=(x)=>k(`/operations/${K}/events`,{...X,event_seq_start:x,events:[{kind:E,payload:{sequence:x,capability:String(Y.capability??"hands.connect"),data:B}}]}),P=G,M=await W(P),q=M.status===409?M.json?.expected_event_seq:void 0;if(typeof q==="number"&&q===G+1)M={status:200,json:{duplicate:!0}};else if(typeof q==="number"&&q>=0&&q!==G)P=q,M=await W(P);if(M.status<300)Z.eventSeq=P+1;return M}}function cJ(Z){return(Y,X)=>new Promise((K,C)=>{if(Q.turns.get(Z.claim.attempt_id)!==Z){C(Error("vm_hands_attempt_ended"));return}if(Z.outbox??=[],Z.outbox.length>=LQ){C(Error("vm_hands_outbox_full"));return}Z.outbox.push({kind:Y,data:X,resolve:K,reject:C}),Z.flush?.()})}function EJ(Z){if(XJ.has(Z))return;XJ.add(Z),(async()=>{try{while(Z.outbox?.length&&Q.turns.get(Z.claim.attempt_id)===Z&&N.readyState===WebSocket.OPEN){let Y=Z.outbox[0],X;try{X=await h(Z).emit(Y.kind,Y.data)}catch(K){if(K instanceof V)return;X={status:500}}if(Z.outbox.shift(),X.status<300)Y.resolve();else Y.reject(Error(`${Y.kind} refused ${X.status}`))}}finally{XJ.delete(Z)}})()}async function pJ(Z,Y){try{let X=await J.agent.attestFrame(Z,Y);if(N.readyState!==WebSocket.OPEN)return;u(X);let K=await l(["attested","attest_refused"],15000);Q.attest=K.t==="attested"?"accepted":"refused";for(let C of Q.attestWaiters.splice(0))C(Q.attest==="accepted");if(z("vm_hands.attest",{result:Q.attest,exit_code:X.exit_code,...K.t==="attest_refused"?{code:String(K.code??"")}:{}}),Q.attest==="refused")N.close(4401,"attest_refused")}catch(X){z("vm_hands.attest_failed",{code:X instanceof F?X.code:"probe_error"});for(let K of Q.attestWaiters.splice(0))K(!1);if(Q.attest!=="accepted")N.close(4000,"attest_unanswered")}}async function lJ(Z){let Y=i&&Q.attest==="pending",X=Z.vm_hands_attest,K=X;if(Q.attest==="refused"){z("vm_hands.claim_attest_refused",{said:typeof X==="string"?X.slice(0,16):typeof X,local:Q.attest}),await h({claim:Z,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(K==="accepted"){if(!Y&&Q.attest!=="accepted"){Q.attest="accepted";for(let _ of Q.attestWaiters.splice(0))_(!0)}}else if(K!=="pending"||!Y&&Q.attest!=="accepted"){z("vm_hands.claim_attest_refused",{said:typeof X==="string"?X.slice(0,16):typeof X,local:Q.attest}),await h({claim:Z,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Q.attest!=="accepted"){let _=Date.parse(Z.lease_until)-Date.now()-5000,H=Math.max(0,Math.min(JJ,Number.isFinite(_)?_:JJ));if(!await new Promise((n)=>{let sJ=setTimeout(()=>n(!1),H);Q.attestWaiters.push((rJ)=>{clearTimeout(sJ),n(rJ)})})){await h({claim:Z,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let C={claim:Z,eventSeq:0},{complete:E,emit:B}=h(C),G;try{if(Z.capability!=="hands.connect")throw new F("vm_hands_bind_invalid","not hands.connect");G=!FJ(Z)}catch(_){z("vm_hands.bind_refused",{code:_ instanceof F?_.code:"unexpected"}),await E("failed",{error_code:_ instanceof F?_.code:"vm_hands_bind_invalid"});return}let W,P=null,M=!1;Q.bindsStarting++;try{let _=await _Q(Q);if(_)z("vm_hands.person_terminals_closed",{count:_});let H=SJ(Z),a=J.agent.bind(H);if(H.workspace_deferred)M=!0,P=uJ(C,()=>M);W=await a}catch(_){z("vm_hands.bind_refused",{code:_ instanceof F?_.code:"unexpected"}),await E("failed",{error_code:_ instanceof F?_.code:"vm_hands_bind_failed"});return}finally{M=!1,Q.bindsStarting--}let q=P?await P:-1,x={...W.ready_data??J.readyData({launchId:W.launch_id,claim:Z})};if(G)delete x.environment_installed;let GJ=!G&&W.snapshot_revision!==null&&W.snapshot_id!==null?{environment_installed:{snapshot_id:W.snapshot_id,installed_revision:W.snapshot_revision}}:{};o.set(Z.attempt_id,{claim:Z,launchId:W.launch_id,readyData:x,eventSeq:C.eventSeq,ackSeq:-1});let g={...x,...GJ,vm_hands:{layout:W.layout,policy_digest:W.policy_digest,launch_id:W.launch_id}},f=Date.now()+EQ,R=1,j=await B("hands.ready",g);while(BQ(j.status)&&!J.signal.aborted){let _=fJ(R);if(Date.now()+_>=f)break;await new Promise((H)=>setTimeout(H,_)),R++,j=await B("hands.ready",g)}if(R>1)z("vm_hands.ready_retried",{attempts:R,status_class:`${Math.floor(j.status/100)}xx`});if(o.delete(Z.attempt_id),j.status>=300){await bJ(Q,Z.attempt_id),await J.agent.boundRefused(Z.attempt_id),await E("failed",{error_code:HJ(j.json?.error,"vm_hands_probe_failed")});return}let S={claim:Z,launchId:W.launch_id,readyData:x,eventSeq:C.eventSeq,ackSeq:q};Q.turns.set(Z.attempt_id,S),S.flush=()=>EJ(S),J.onTurn?.(Z.attempt_id,cJ(S)),await BJ(S)}async function uJ(Z,Y){let{fence:X,op:K}=h(Z),C=Z.claim.attempt_id,E=-1;try{for(;;){let B=await k(`/operations/${K}/heartbeat`,{...X,control_ack_seq:E,wait_ms:hJ});if(!Y())return E;if(B.status>=300)return J.agent.abandonWorkspaceGrant(C),E;let G=(B.json?.controls??[]).slice().sort((W,P)=>W.seq-P.seq);for(let W of G){if(W.seq<=E)continue;if(E=W.seq,W.kind===RJ)return z("vm_hands.workspace_granted",{}),J.agent.grantWorkspace(C),E;return z("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(W.kind)?W.kind:"other"}),J.agent.abandonWorkspaceGrant(C),E}}}catch{return J.agent.abandonWorkspaceGrant(C),E}}async function BJ(Z){let{fence:Y,op:X}=h(Z),K=null,C=null,E=J.agent.executorExited(Z.claim.attempt_id).then((B)=>{return C=B,null});J:for(;;){let B=await Promise.race([E,k(`/operations/${X}/heartbeat`,{...Y,control_ack_seq:Z.ackSeq,wait_ms:hJ})]);if(!B){K="vm_hands_executor_exited",z("vm_hands.executor_exited",{reason:C});break}if(B.status>=300)break;let G=(B.json?.controls??[]).slice().sort((W,P)=>W.seq-P.seq);for(let W of G){if(W.seq<=Z.ackSeq)continue;if(W.kind==="operation.cancel"||W.kind==="cancel"){Z.ackSeq=W.seq;break J}if(W.kind===gJ)try{await iJ(Z,W.payload??{})}catch(P){if(P instanceof V)throw P;K=P instanceof F?P.code:"environment_unavailable";let M=P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(P.code)?P.code:null;z("vm_hands.environment_refused",{code:K,cause:M});break J}Z.ackSeq=W.seq}}await dJ(Z,K)}async function oJ(Z){let Y=Z,X={claim:Y,eventSeq:0},{complete:K,emit:C,fence:E,op:B}={...h(X)},G=Z.vm_hands_origin==="person"?"person":"model",W=String(Z.capability??"");if(!J.executeOp){await K("failed",{error_code:"vm_hands_op_unsupported"});return}if(Z.vm_hands_attest==="accepted"&&Q.attest==="pending"&&!(i&&Q.attest==="pending")){Q.attest="accepted";for(let j of Q.attestWaiters.splice(0))j(!0)}if(Q.attest!=="accepted"){let j=Date.parse(String(Z.lease_until??""))-Date.now()-5000,S=Q.attest==="refused"?0:Math.max(0,Math.min(JJ,Number.isFinite(j)?j:JJ));if(!(S>0&&await new Promise((H)=>{let a=setTimeout(()=>H(!1),S);Q.attestWaiters.push((n)=>{clearTimeout(a),H(n)})}))){await K("failed",{error_code:"vm_hands_unattested"});return}}let P=J.agent.bindIdForRun(Y.run_id);if(G==="model"&&P===null){await K("failed",{error_code:"vm_hands_not_bound"});return}let M=W==="pty.start"&&G==="person"&&!Z.authority;if(M&&(J.agent.liveBindIds.length>0||Q.bindsStarting>0)){await K("failed",{error_code:"vm_hands_bound"});return}if(kJ.has(W)&&!M&&J.agent.liveBindIds.length===0){await K("failed",{error_code:"vm_hands_not_bound"});return}if(G==="model"&&P||kJ.has(W)&&!M)J.agent.opServed();let q=new AbortController;zJ.add(q);let x,GJ=new Promise((j)=>{x=j}),g={abort:q,settled:GJ};if(M)Q.personTerminals.add(g);if(G==="model"&&P){let j=Q.modelOps.get(P)??new Set;j.add(g),Q.modelOps.set(P,j),await J.agent.environmentInstalled(P,WQ,q.signal)}let f=-1,R=setInterval(()=>{k(`/operations/${B}/heartbeat`,{...E,control_ack_seq:f,wait_ms:0}).then((j)=>{if(j.status>=300){q.abort();return}let S=j.json?.controls??[];for(let _ of S)if(f=Math.max(f,_.seq),_.kind==="operation.cancel"||_.kind==="cancel")q.abort()},()=>q.abort())},GQ);try{let j=await J.executeOp({kind:G,claim:Z,...G==="model"&&P?{bindId:P}:{},signal:q.signal,emit:async(_)=>{await C(_.kind,_.data??{})}}),S=await K(j.status,{...j.result?{result:j.result}:{},...j.error_code?{error_code:HJ(j.error_code,"vm_hands_op_failed")}:{}});z("vm_hands.op",{capability:W,kind:G,status:j.status,code:j.error_code??null,...S.status>=300?{complete_status:S.status,complete_error:String(S.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(R),zJ.delete(q),P)Q.modelOps.get(P)?.delete(g);Q.personTerminals.delete(g),x()}}async function dJ(Z,Y){let X=Z.claim.attempt_id;if(Q.turns.get(X)===Z)Q.turns.delete(X);J.onTurn?.(X,null),QJ(Z);let K=await p(Q,J.agent,X).catch((C)=>s(C,Z,Y));if(!K)return;Q.receipts.push({turn:Z,failure:Y,unbound:K}),await r()}function s(Z,Y,X){let K=mJ(Z);return z("vm_hands.unbind_unverified",{operation_id:Y.claim.operation_id,code:K,attempt:0}),h(Y).emit(IJ,{code:K}).catch(()=>{return}),AQ(Q,J.agent,{turn:Y,failure:X},J.signal,z),null}function r(){return YJ=YJ.then(LJ,LJ),YJ}async function LJ(){while(Q.receipts.length){let{turn:Z,failure:Y,unbound:X}=Q.receipts[0],{complete:K,emit:C}=h(Z);try{if(await C("hands.stopped",{...Z.readyData,reason_code:Y?"failed":"cancelled",killed_verified:X.killed_verified,shredded:X.shredded,...X.srt_fallbacks?{vm_hands_srt_fallbacks:X.srt_fallbacks}:{}}),Y)await K("failed",{error_code:Y});else await K("cancelled",{error_code:"driver_stopped"})}catch(E){if(E instanceof V)return}Q.receipts.shift()}}async function iJ(Z,Y){let{fence:X,op:K}=h(Z),C=Y.snapshot_id;if(Y.version!==1||typeof C!=="string"||Object.keys(Y).length!==2)throw new F("vm_hands_env_invalid","invalid environment delivery");let E=await k(`/operations/${K}/environment`,{...X,snapshot_id:C}),B=E.json?.environment_sealed;if(E.status!==200||!B||E.json?.payload!==void 0)throw new F("vm_hands_env_invalid","environment not delivered sealed");let G=await J.agent.deliverEnvironment({attemptId:Z.claim.attempt_id,snapshotId:C,deviceId:Q.deviceId??"",sealed:B});if((await k(`/operations/${K}/environment-ack`,{...X,...G})).status>=300)throw new F("vm_hands_env_ack_refused","environment ack refused")}}
|
|
5
5
|
export{SQ as xa,ZQ as ya,vQ as za};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var r={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
3
|
-
export{r as
|
|
2
|
+
var r={name:"github-native-engineer-device-worker-production",version:"0.2.395",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
|
+
export{r as Uj};
|