@reason-machines/cli-linux-arm64-musl 0.2.359 → 0.2.360

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-credentials-vtpssnm1.js +2 -0
  3. package/bin/vm-hands/api-dvwzjwmh.js +2 -0
  4. package/bin/vm-hands/{ask-relay-fkb3bj30.js → ask-relay-0y716ck6.js} +3 -3
  5. package/bin/vm-hands/connect-cli-sbczes1h.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-8v87dhjx.js +2 -0
  7. package/bin/vm-hands/desktop-account-q57958y1.js +2 -0
  8. package/bin/vm-hands/{device-workspace-fhbpenda.js → device-workspace-c05vq771.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-ze6q6h8b.js → hands-worker-source-wfv9csj2.js} +1 -1
  10. package/bin/vm-hands/{index-tv4kcb2a.js → index-80ep9259.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-3s9amwp3.js → install-receipt-pbfhgaxc.js} +1 -1
  12. package/bin/vm-hands/local-automation-j8402b7e.js +2 -0
  13. package/bin/vm-hands/local-capabilities-yekmdbpc.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-m7rexsex.js +2 -0
  15. package/bin/vm-hands/local-display-mac-9de01n3r.js +2 -0
  16. package/bin/vm-hands/local-display-session-d3hvgjqs.js +2 -0
  17. package/bin/vm-hands/local-pty-session-e7j0kj19.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-mg7kmckn.js → managed-runtime-r1138kvq.js} +1 -1
  19. package/bin/vm-hands/{network-contract-gq8x3ehk.js → network-contract-zjq3w2n3.js} +1 -1
  20. package/bin/vm-hands/package-44a3p8yk.js +2 -0
  21. package/bin/vm-hands/permissions-g0asz6w1.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-67d4b6fm.js → reason-hands-protocol-aj1zwpk0.js} +1 -1
  23. package/bin/vm-hands/serve-service-9jd2zcmb.js +2 -0
  24. package/bin/vm-hands/{status-f146chye.js → status-7v31d0ab.js} +2 -2
  25. package/bin/vm-hands/version-2fvzdbmj.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-5xtkyx25.js → vm-hands-entry-lite-0763vz5v.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-kxdw4myj.js → vm-hands-entry-lite-1hv536wk.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-n867d88m.js → vm-hands-entry-lite-2j67g42s.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-tg2bkah3.js → vm-hands-entry-lite-3qxye8en.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-x4j4058x.js → vm-hands-entry-lite-3tf5zyba.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-qbnz4h30.js → vm-hands-entry-lite-4rd6b2ra.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-r6pap1kh.js → vm-hands-entry-lite-4xfs7y6w.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-3ew5ftk0.js → vm-hands-entry-lite-5y2kfnv2.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-qm18wqgz.js → vm-hands-entry-lite-6fvjbwqq.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-d2hbz0r4.js → vm-hands-entry-lite-7nk0873d.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-sx2gpbap.js → vm-hands-entry-lite-97zxda1y.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-ha1ej910.js → vm-hands-entry-lite-avstvbbc.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-bybpy28m.js → vm-hands-entry-lite-cety9pka.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-22we2jrv.js → vm-hands-entry-lite-cwf21py1.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-w88zkzhr.js → vm-hands-entry-lite-dqnhebfx.js} +1 -1
  41. package/bin/vm-hands/{vm-hands-entry-lite-szfy3kx7.js → vm-hands-entry-lite-fr2k6eah.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-463aheya.js → vm-hands-entry-lite-hfq6jjnh.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-h2xemq1f.js → vm-hands-entry-lite-hw8vgsmm.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-qhgfnhjt.js → vm-hands-entry-lite-jc229h5p.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-jn95s3j4.js → vm-hands-entry-lite-jjkkee8q.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-r5y08n0q.js → vm-hands-entry-lite-jpkf3569.js} +2 -2
  47. package/bin/vm-hands/{vm-hands-entry-lite-kv0qat0x.js → vm-hands-entry-lite-k7fkfytm.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-ygx9kj92.js → vm-hands-entry-lite-kxtjkzzh.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-07er2w8q.js → vm-hands-entry-lite-ne0nrjkn.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-c7krpmd8.js → vm-hands-entry-lite-nnvyvx1n.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-c0m2jewa.js → vm-hands-entry-lite-npqaxsmx.js} +1 -1
  52. package/bin/vm-hands/{vm-hands-entry-lite-5kgvss4p.js → vm-hands-entry-lite-p1nb6n3r.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-pf1gagky.js → vm-hands-entry-lite-qqyrwyfz.js} +3 -3
  54. package/bin/vm-hands/{vm-hands-entry-lite-9z6k7898.js → vm-hands-entry-lite-qy9xzp2m.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-p8662x7z.js → vm-hands-entry-lite-rkt48xf4.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-1j9r1fca.js → vm-hands-entry-lite-tbps80f1.js} +2 -2
  57. package/bin/vm-hands/{vm-hands-entry-lite-gzxxsjmr.js → vm-hands-entry-lite-v1amz3pq.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-v08mjs3f.js → vm-hands-entry-lite-vcm4389c.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-kt4831mq.js → vm-hands-entry-lite-x7204pcv.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-j05685sg.js → vm-hands-entry-lite-xhr0m9r0.js} +1 -1
  61. package/bin/vm-hands/{vm-hands-entry-lite-s98hjhz3.js → vm-hands-entry-lite-xj0p1ax7.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-taw01cp4.js → vm-hands-entry-lite-zn303jrg.js} +1 -1
  63. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  64. package/bin/vm-hands/{vm-hands-executor-5nqmf61x.js → vm-hands-executor-xcscxb3s.js} +1 -1
  65. package/bin/vm-hands/vm-hands-op-runner-tm0sh7y6.js +2 -0
  66. package/bin/vm-hands/{vm-hands-runtime-hnpk8xmf.js → vm-hands-runtime-3yg846f8.js} +3 -3
  67. package/bin/vm-hands/worker-sandbox-wb5thd4n.js +2 -0
  68. package/package.json +1 -1
  69. package/bin/vm-hands/api-credentials-axffq0pk.js +0 -2
  70. package/bin/vm-hands/api-texm6ayv.js +0 -2
  71. package/bin/vm-hands/connect-cli-ev4xex04.js +0 -2
  72. package/bin/vm-hands/custom-endpoint-device-bsanzqj2.js +0 -2
  73. package/bin/vm-hands/desktop-account-jxfva4m1.js +0 -2
  74. package/bin/vm-hands/local-automation-f8f33qpp.js +0 -2
  75. package/bin/vm-hands/local-capabilities-ya6yzxh5.js +0 -2
  76. package/bin/vm-hands/local-desktop-users-3th2aaac.js +0 -2
  77. package/bin/vm-hands/local-display-mac-neweyjpa.js +0 -2
  78. package/bin/vm-hands/local-display-session-v00nv1fm.js +0 -2
  79. package/bin/vm-hands/local-pty-session-2crsy5td.js +0 -2
  80. package/bin/vm-hands/package-s3eg9zrd.js +0 -2
  81. package/bin/vm-hands/permissions-3kjdp3ge.js +0 -2
  82. package/bin/vm-hands/serve-service-nqshfese.js +0 -2
  83. package/bin/vm-hands/version-ss25ccvh.js +0 -2
  84. package/bin/vm-hands/vm-hands-op-runner-zedtdcmk.js +0 -2
  85. package/bin/vm-hands/worker-sandbox-vmp22sk6.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ac as kQ,Bc as fQ,Cc as z4,Dc as K4,Ec as F8}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Fc as MQ,Gc as G8,Hc as n9,Ic as _0,Jc as L9,Kc as n0,Rc as K0}from"./vm-hands-entry-lite-j05685sg.js";import{Wc as b0}from"./vm-hands-entry-lite-f4gvypnx.js";import{Xe as w9,Ye as o0,Ze as B8,_e as m0,cf as q0,ne as $Q,se as QQ}from"./vm-hands-entry-lite-szfy3kx7.js";import{rg as hQ,xg as a9,yg as m8}from"./vm-hands-entry-lite-s98hjhz3.js";import{Dg as Y4}from"./vm-hands-entry-lite-3ew5ftk0.js";import{Fg as OZ,Ig as B9,Rg as ZQ,Sg as XQ,Ug as JQ,Wg as p9,Xg as n$,Yg as i$,Zg as E8,ah as u9,jh as R8,kh as S0,lh as O0,mh as l9,th as b8,uh as YQ,vh as a$}from"./vm-hands-entry-lite-v08mjs3f.js";import{ei as cQ,fi as h8}from"./vm-hands-entry-lite-5kgvss4p.js";import{Ri as M8,Si as s9,Vi as J4}from"./vm-hands-entry-lite-1j9r1fca.js";import{$i as Y8,Wi as L8,Xi as i0,Yi as N8,Zi as a0,_i as H9,aj as $$,bj as s0,cj as p0,dj as s$,oj as B$}from"./vm-hands-entry-lite-w88zkzhr.js";import{tj as UZ}from"./vm-hands-entry-lite-qhgfnhjt.js";import{Oj as x}from"./vm-hands-entry-lite-kv0qat0x.js";import{Uj as G4}from"./vm-hands-entry-lite-jn95s3j4.js";import{Wj as C}from"./vm-hands-entry-lite-ygx9kj92.js";import{Xj as P1,ak as VZ}from"./vm-hands-entry-lite-h2xemq1f.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function v9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function S$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function w$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!v9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(S$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function q9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function E$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function C9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function b$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function k$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!v9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!S$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return C9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&P0(Q.status,200,599)&&E$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&E$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return C9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:q9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function _8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function A8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await A8($)===!0}function c9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function f$($){if(!v9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:c9($.deviceRelayUrl,"device")}}function m$($){if(!v9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as x8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var g$="x-preview-connection";async function y$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=q4(32).toString("base64url"),X=new Set,J=!1,Y=O4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
2
+ import{Ac as kQ,Bc as fQ,Cc as z4,Dc as K4,Ec as F8}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Fc as MQ,Gc as G8,Hc as n9,Ic as _0,Jc as L9,Kc as n0,Rc as K0}from"./vm-hands-entry-lite-xhr0m9r0.js";import{Wc as b0}from"./vm-hands-entry-lite-f4gvypnx.js";import{$e as m0,Ye as w9,Ze as o0,_e as B8,df as q0,oe as $Q,te as QQ}from"./vm-hands-entry-lite-fr2k6eah.js";import{sg as hQ,yg as a9,zg as m8}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Eg as Y4}from"./vm-hands-entry-lite-5y2kfnv2.js";import{Gg as OZ,Jg as B9,Sg as ZQ,Tg as XQ,Vg as JQ,Xg as p9,Yg as n$,Zg as i$,_g as E8,bh as u9,kh as R8,lh as S0,mh as O0,nh as l9,uh as b8,vh as YQ,wh as a$}from"./vm-hands-entry-lite-vcm4389c.js";import{fi as cQ,gi as h8}from"./vm-hands-entry-lite-p1nb6n3r.js";import{Si as M8,Ti as s9,Wi as J4}from"./vm-hands-entry-lite-tbps80f1.js";import{$i as H9,Xi as L8,Yi as i0,Zi as N8,_i as a0,aj as Y8,bj as $$,cj as s0,dj as p0,ej as s$,pj as B$}from"./vm-hands-entry-lite-dqnhebfx.js";import{uj as UZ}from"./vm-hands-entry-lite-jc229h5p.js";import{Pj as x}from"./vm-hands-entry-lite-k7fkfytm.js";import{Vj as G4}from"./vm-hands-entry-lite-jjkkee8q.js";import{Xj as C}from"./vm-hands-entry-lite-kxtjkzzh.js";import{Yj as P1,bk as VZ}from"./vm-hands-entry-lite-hw8vgsmm.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function v9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function S$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function w$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!v9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(S$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function q9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function E$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function C9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function b$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function k$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!v9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!S$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return C9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&P0(Q.status,200,599)&&E$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&E$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return C9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:q9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function _8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function A8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await A8($)===!0}function c9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function f$($){if(!v9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:c9($.deviceRelayUrl,"device")}}function m$($){if(!v9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as x8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var g$="x-preview-connection";async function y$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=q4(32).toString("base64url"),X=new Set,J=!1,Y=O4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
3
3
  \r
4
4
  `);if(W<0){if(B.length>16384)G.destroy();return}if(G.pause(),G.off("data",H),W>16384||B.length>v.upload+16384)return G.destroy();z(B,W).catch(()=>G.destroy())};G.on("data",H);async function z(L,W){let U=L.subarray(0,W).toString("latin1").split(`\r
5
5
  `),j=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(U.shift()??"");if(!j)throw Error("preview_request_invalid");q9(j[2]);let O=!1,q=0,A=[];for(let T of U){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===g$){q++;let m=Buffer.from(S[2].trim());O=m.length===Z.length&&T4(m,Buffer.from(Z))}else if(S[1].toLowerCase()!=="host")A.push(T)}if(!O||q!==1||J||F.signal.aborted)throw Error("preview_connection_denied");let R=await $.connect(F.signal);if(J||F.signal.aborted)throw R.destroy(),Error("preview_closed");X.add(R),R.on("error",()=>G.destroy()),R.once("close",()=>{X.delete(R),G.destroy()}),G.once("close",()=>R.destroy()),G.setTimeout(0);let P=[`${j[1]} ${j[2]} HTTP/1.1`,`Host: 127.0.0.1:${R.remotePort}`,...A,"",""].join(`\r
@@ -303,7 +303,7 @@ async (input) => {
303
303
  if (!bridge || typeof bridge.evaluate !== "function") throw new Error("Reason Hands browser bridge is not installed");
304
304
  return await bridge.evaluate(typeof input === "string" ? input : input && input.code);
305
305
  }
306
- `.trim();import{Buffer as X9}from"buffer";import{randomUUID as z1}from"crypto";class tQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var eQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),aQ=/^hands_[A-Za-z0-9_-]{8,128}$/,K1=2048,$Z=32,QZ=1e4,V1=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function F1($){let Q=$.split("+"),Z=(Q.pop()??"").replace(/^Key/,"").toLowerCase();if(Z==="f12")return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(Z))return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&Q.includes("Shift")&&Z==="c")return!0;return Q.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(Z)}var H1=($)=>{let Q=$.closest("a[href],area[href]");return{password:$.tagName==="INPUT"&&$.type==="password",executableLink:Boolean(Q&&!/^(https?:|about:blank)/i.test(Q.href))}},ZZ={browser:{close:{returns:"void"},contexts:{returns:"context[]"},isConnected:{returns:"json"},version:{returns:"json"}},context:{addCookies:{returns:"void"},addInitScript:{returns:"void"},browser:{returns:"browser"},clearCookies:{returns:"void"},clearPermissions:{returns:"void"},close:{returns:"void"},cookies:{returns:"json"},grantPermissions:{returns:"void"},newPage:{returns:"page"},pages:{returns:"page[]"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setGeolocation:{returns:"void"},setHTTPCredentials:{returns:"void"},setOffline:{returns:"void"},setViewportSize:{returns:"void"},storageState:{returns:"json"},viewportSize:{returns:"json",special:"contextViewportSize"}},page:{addInitScript:{returns:"void"},addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},bringToFront:{returns:"void"},close:{returns:"void"},content:{returns:"json"},context:{returns:"context"},emulateMedia:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},frame:{returns:"frame"},frameLocator:{returns:"frameLocator"},frames:{returns:"frame[]"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goBack:{returns:"void"},goForward:{returns:"void"},goto:{returns:"void"},isClosed:{returns:"json"},locator:{returns:"locator"},mainFrame:{returns:"frame"},opener:{returns:"page"},pdf:{returns:"bytes"},reload:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setContent:{returns:"void"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setInputFiles:{returns:"void"},setViewportSize:{returns:"void"},title:{returns:"json"},url:{returns:"json"},viewportSize:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},locator:{all:{returns:"locator[]"},allInnerTexts:{returns:"json"},allTextContents:{returns:"json"},and:{returns:"locator"},ariaSnapshot:{returns:"json"},blur:{returns:"void"},boundingBox:{returns:"json"},check:{returns:"void"},clear:{returns:"void"},click:{returns:"void"},contentFrame:{returns:"frameLocator"},count:{returns:"json"},dblclick:{returns:"void"},dragTo:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},evaluateAll:{returns:"json",requiresStringSource:!0},fill:{returns:"void"},filter:{returns:"locator"},first:{returns:"locator",special:"property"},focus:{returns:"void"},getAttribute:{returns:"json"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},hover:{returns:"void"},innerHTML:{returns:"json"},innerText:{returns:"json"},inputValue:{returns:"json"},isChecked:{returns:"json"},isEditable:{returns:"json"},isEnabled:{returns:"json"},isHidden:{returns:"json"},isVisible:{returns:"json"},last:{returns:"locator",special:"property"},locator:{returns:"locator"},nth:{returns:"locator"},or:{returns:"locator"},page:{returns:"page"},press:{returns:"void"},pressSequentially:{returns:"void"},scrollIntoViewIfNeeded:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setInputFiles:{returns:"void"},tap:{returns:"void"},textContent:{returns:"json"},type:{returns:"void"},uncheck:{returns:"void"},waitFor:{returns:"void"}},frame:{addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},childFrames:{returns:"frame[]"},content:{returns:"json"},evaluate:{returns:"json",requiresStringSource:!0},frameLocator:{returns:"frameLocator"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goto:{returns:"void"},isDetached:{returns:"json"},locator:{returns:"locator"},name:{returns:"json"},page:{returns:"page"},parentFrame:{returns:"frame"},setContent:{returns:"void"},title:{returns:"json"},url:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},frameLocator:{getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},locator:{returns:"locator"},owner:{returns:"locator"}}};function I($){throw new tQ($)}function z0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let Q=Object.getPrototypeOf($);return Q===Object.prototype||Q===null}function J9($,Q=0,Z={nodes:0}){if(Q>$Z||++Z.nodes>QZ)I("hands_repl_json_too_complex");if($===null||typeof $==="boolean"||typeof $==="string")return;if(typeof $==="number"){if(!Number.isFinite($))I("hands_repl_invalid_json");return}if(Array.isArray($)){for(let X of $)J9(X,Q+1,Z);return}if(!z0($))I("hands_repl_invalid_json");for(let[X,J]of Object.entries($)){if(eQ.has(X))I("hands_repl_invalid_json");J9(J,Q+1,Z)}}function v8($){return typeof $==="string"&&Object.hasOwn(ZZ,$)}function U1($){if(!$.endsWith("[]"))return null;let Q=$.slice(0,-2);return v8(Q)?Q:null}function oQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function W1($){return z0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function rQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function t9(){return Object.freeze({$handsRepl:"undefined"})}function B1($){if(!X9.isBuffer($)&&!($ instanceof Uint8Array))I("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:X9.from($).toString("base64")})}function XZ($){if(!k0($.browser)||!k0($.context)||!k0($.page))I("hands_repl_invalid_roots");if(typeof $.a11y!=="function"||typeof $.view!=="function")I("hands_repl_invalid_callbacks");let Q=$.maxHandles??K1;if(!Number.isInteger(Q)||Q<3||Q>1e5)I("hands_repl_invalid_handle_limit");let Z=new Map,X=new WeakMap,J=$.createOpaqueId??z1,Y=(z,L)=>{if(!k0(L))I("hands_repl_expected_target");let W=X.get(L)?.get(z);if(W)return W;if(Z.size>=Q)I("hands_repl_handle_limit");let U="";for(let q=0;q<16;q+=1){let A=`hands_${J()}`;if(aQ.test(A)&&!Z.has(A)){U=A;break}}if(!U)I("hands_repl_invalid_opaque_id");let j=Object.freeze({$handsRepl:"handle",id:U,kind:z});Z.set(U,{kind:z,target:L});let O=X.get(L);if(!O)O=new Map,X.set(L,O);return O.set(z,j),j},K=Object.freeze({browser:Y("browser",$.browser),context:Y("context",$.context),page:Y("page",$.page)}),V=(z)=>{if(!z0(z)||Object.keys(z).length!==3||z.$handsRepl!=="handle"||typeof z.id!=="string"||!aQ.test(z.id)||!v8(z.kind))I("hands_repl_invalid_handle");let L=Z.get(z.id);if(!L||L.kind!==z.kind)I("hands_repl_unknown_handle");return L},G=(z,L=0,W=new Set)=>{if(L>$Z)I("hands_repl_json_too_complex");if(z===void 0)return t9();if(z===null||typeof z==="boolean"||typeof z==="string")return z;if(typeof z==="number"){if(!Number.isFinite(z))I("hands_repl_non_json_result");return z}if(Array.isArray(z)){if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{return z.map((U)=>G(U,L+1,W))}finally{W.delete(z)}}if(!z0(z))I("hands_repl_non_json_result");if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{let U=Object.create(null);for(let j of Object.keys(z)){let O=Object.getOwnPropertyDescriptor(z,j);if(!O||!("value"in O))continue;U[j]=G(O.value,L+1,W)}return U}finally{W.delete(z)}},F=(z,L)=>{if(L==="void")return t9();if(L==="json")return G(z);if(L==="bytes")return B1(z);let W=U1(L);if(W){if(!Array.isArray(z))I("hands_repl_expected_target_list");if(W==="context"&&z.some((U)=>U!==$.context))I("hands_repl_foreign_context");return z.map((U)=>Y(W,U))}if(z===null||z===void 0)return t9();if(!v8(L))I("hands_repl_invalid_return_kind");if(L==="context"&&z!==$.context)I("hands_repl_foreign_context");return Y(L,z)},B=(z)=>{if(z0(z)&&z.$handsRepl==="handle")return V(z).target;if(oQ(z))return X9.from(z.base64,"base64");if(W1(z))return;if(rQ(z))I("hands_repl_route_fulfill_only");if(Array.isArray(z))return z.map(B);if(!z0(z))return z;let L=Object.create(null);for(let[W,U]of Object.entries(z))L[W]=B(U);return L};return Object.freeze({roots:K,dispatch:async(z)=>{if(!z0(z)||typeof z.type!=="string")I("hands_repl_invalid_request");if(z.type==="a11y"){let T=z.target===void 0?Z.get(K.page.id):V(z.target);if(!T||T.kind!=="page"&&T.kind!=="locator")I("hands_repl_invalid_a11y_target");return G(await $.a11y(T.target))}if(z.type==="view"){if(J9(z.source),z.options!==void 0)J9(z.options);let T=oQ(z.source)?X9.from(z.source.base64,"base64"):z.source;if($.privateProfile&&!X9.isBuffer(T))I("hands_repl_profile_requires_image_bytes");return G(await $.view(T,z.options))}if(z.type!=="call")I("hands_repl_invalid_request");if(typeof z.method!=="string"||z.method.length===0||z.method.length>128)I("hands_repl_invalid_method");if(eQ.has(z.method))I("hands_repl_forbidden_method");let L=V(z.target),W=z.args??[];if(!Array.isArray(W))I("hands_repl_invalid_arguments");if(J9(W),L.kind==="page"&&z.method==="captureScreenshot"){if(W.length!==0)I("hands_repl_invalid_arguments");if(!$.screenshotExport)I("hands_repl_screenshot_export_unavailable");return G(await $.screenshotExport(L.target))}if(L.kind==="context"&&["startRecording","stopRecording"].includes(z.method)){if(!$.recording||L.target!==$.context)I("hands_repl_recording_unavailable");if(W.length>(z.method==="startRecording"?1:0))I("hands_repl_invalid_arguments");return G(z.method==="startRecording"?await $.recording.start(W[0]):await $.recording.stop())}if($.privateProfile){let T=z.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(T)||L.kind==="browser"&&T==="close"||L.kind==="context"&&T==="close")I("hands_repl_private_profile_method_denied");if(L.kind==="browser"&&T==="contexts")return F([$.context],"context[]");if((T==="screenshot"||T==="pdf")&&z0(W[0])&&(("path"in W[0])||("style"in W[0])))I("hands_repl_private_profile_path_denied");if(T==="goto"){if(typeof W[0]!=="string")I("hands_repl_private_profile_url_denied");try{let S=new URL(W[0]);if(!["http:","https:"].includes(S.protocol)&&W[0]!=="about:blank")I("hands_repl_private_profile_url_denied")}catch{I("hands_repl_private_profile_url_denied")}}if(T==="getAttribute"&&(typeof W[0]!=="string"||!V1.has(W[0].toLowerCase())))I("hands_repl_private_profile_attribute_denied");if(L.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(T)){let S=[L.target];if(T==="allInnerTexts"){let m=Reflect.get(L.target,"all");if(typeof m!=="function")I("hands_repl_private_profile_probe_unavailable");let E=await Reflect.apply(m,L.target,[]);if(!Array.isArray(E)||E.length>QZ||!E.every(k0))I("hands_repl_private_profile_probe_unavailable");S=E}for(let m of S){let E=Reflect.get(m,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,m,[]))I("hands_repl_private_profile_hidden_value_denied")}}if(T==="press"&&typeof W[0]==="string"&&F1(W[0]))I("hands_repl_private_profile_browser_shortcut_denied");if(L.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(T)){let S=Reflect.get(L.target,"evaluate");if(typeof S!=="function")I("hands_repl_private_profile_probe_unavailable");let m=await Reflect.apply(S,L.target,[H1]);if(!z0(m)||typeof m.password!=="boolean"||typeof m.executableLink!=="boolean")I("hands_repl_private_profile_probe_unavailable");if(T==="inputValue"&&m.password)I("hands_repl_private_profile_password_denied");if(T!=="inputValue"&&m.executableLink)I("hands_repl_private_profile_url_denied");if(T==="inputValue"){let E=Reflect.get(L.target,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,L.target,[]))I("hands_repl_private_profile_hidden_value_denied")}}}let U=ZZ[L.kind][z.method];if(!U)I("hands_repl_method_not_allowed");if(U.requiresStringSource&&typeof W[0]!=="string")I("hands_repl_string_source_required");if(L.kind==="browser"&&z.method==="contexts")return[K.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(z.method)&&W.some((T)=>z0(T)&&("path"in T)))I("hands_repl_file_path_not_allowed");if(z.method==="goto"&&typeof W[0]==="string"){let T;try{T=new URL(W[0]).protocol}catch{I("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(T))I("hands_repl_file_path_not_allowed")}if(U.special==="contextViewportSize"){let T=Reflect.get(L.target,"pages");if(typeof T!=="function")I("hands_repl_method_unavailable");let S=await Reflect.apply(T,L.target,[]),m=Array.isArray(S)?S[0]:void 0,E=k0(m)?Reflect.get(m,"viewportSize"):void 0;if(typeof E!=="function")return t9();return F(await Reflect.apply(E,m,[]),U.returns)}if(U.special==="property"){let T=Reflect.get(L.target,z.method);return F(typeof T==="function"?Reflect.apply(T,L.target,[]):T,U.returns)}let j=Reflect.get(L.target,z.method);if(typeof j!=="function")I("hands_repl_method_unavailable");if(U.special==="route"){let T=W[1];if(!rQ(T))I("hands_repl_invalid_route_handler");J9(T.options);let S=B(T.options),m=async(M)=>{if(!k0(M))I("hands_repl_invalid_route");let D=Reflect.get(M,"fulfill");if(typeof D!=="function")I("hands_repl_invalid_route");await Reflect.apply(D,M,[S])},E=[B(W[0]??null),m],N=await Reflect.apply(j,L.target,E);return F(N,U.returns)}let O=W.map(B);if(z.method==="setInputFiles"){let T=L.kind==="locator"?0:1,S=async(E)=>{if(typeof E!=="string"){if(!z0(E)||typeof E.name!=="string"||typeof E.mimeType!=="string"||!X9.isBuffer(E.buffer))I("hands_repl_invalid_file_input");return E}if(!$.readWorkspaceFile)I("hands_repl_workspace_required");return $.readWorkspaceFile(E)},m=O[T];O[T]=Array.isArray(m)?await Promise.all(m.map(S)):await S(m)}if(z.method==="goto")await $.beforeNavigation?.();let q=$.actionRecorder?.(),A=await Reflect.apply(j,L.target,O),P={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[z.method];if(P){let T=Reflect.get(L.target,"page"),S=L.kind==="page"?L.target:typeof T==="function"?Reflect.apply(T,L.target,[]):void 0;q?.(P,k0(S)?S:void 0)}return F(A,U.returns)}})}import{isIP as KZ}from"net";import{Resolver as L1}from"dns/promises";import{isIP as $8}from"net";var N1=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function c8($){if($8($)!==4)return null;let Q=$.split(".");if(Q.length!==4)return null;let Z=0;for(let X of Q){let J=Number(X);if(!Number.isInteger(J)||J<0||J>255)return null;Z=Z*256+J}return Z>>>0}function M1($,Q,Z){let X=c8(Q);if(X===null)return!1;let J=Z===0?0:4294967295<<32-Z>>>0;return($&J)>>>0===(X&J)>>>0}function JZ($){let Q=c8($);if(Q===null)return!0;return N1.some(([Z,X])=>M1(Q,Z,X))}function j1($){if($8($)!==6)return null;let Q=$.toLowerCase(),Z=Q.indexOf("%");if(Z>=0)Q=Q.slice(0,Z);let X=[],J=Q.lastIndexOf(":"),Y=J>=0?Q.slice(J+1):"";if(Y.includes(".")){let z=c8(Y);if(z===null)return null;X=[z>>>16&65535,z&65535],Q=Q.slice(0,J+1)+"0:0"}let K=Q.split("::");if(K.length>2)return null;let V=(z)=>{if(z==="")return[];let L=[];for(let W of z.split(":")){if(W===""||W.length>4||!/^[0-9a-f]+$/.test(W))return null;L.push(Number.parseInt(W,16))}return L},G=V(K[0]??"");if(G===null)return null;if(K.length===1){let z=G;if(z.length!==8)return null;return X.length>0?z.slice(0,6).concat(X):z}let F=V(K[1]??"");if(F===null)return null;let B=8-G.length-F.length;if(B<0)return null;let H=G.concat(Array(B).fill(0),F);if(H.length!==8)return null;return X.length>0?H.slice(0,6).concat(X):H}function C1($,Q){return`${$>>8&255}.${$&255}.${Q>>8&255}.${Q&255}`}function q1($){let Q=j1($);if(Q===null)return!0;let[Z,X,J]=Q;if((Z&57344)!==8192)return!0;if(Z===8193&&(X&65024)===0)return!0;if(Z===8193&&X===3512)return!0;if(Z===16383&&(X&61440)===0)return!0;if(Z===8194)return JZ(C1(X,J));return!1}function YZ($){return $.replace(/^\[|\]$/g,"")}function e9($){let Q=YZ($.trim()),Z=$8(Q);if(Z===4)return JZ(Q);if(Z===6)return q1(Q);return!0}function GZ($){if($ instanceof Error&&$.name==="TimeoutError")return"dns_timeout";switch(typeof $==="object"&&$!==null&&"code"in $?$.code:void 0){case"ENOTFOUND":return"dns_not_found";case"ENODATA":return"dns_empty";case"EAI_AGAIN":case"ESERVFAIL":case"ECONNREFUSED":return"dns_temporary";case"ETIMEOUT":case"ETIMEDOUT":return"dns_timeout";default:return"dns_failed"}}var zZ=5000;function T1($){return async(Q,Z)=>{if(Z?.aborted)throw Error("aborted");let X=new L1({timeout:zZ,tries:1});if($)X.setServers($);let J=()=>X.cancel();Z?.addEventListener("abort",J,{once:!0});try{let[Y,K]=await Promise.allSettled([X.resolve4(Q),X.resolve6(Q)]),V=[...Y.status==="fulfilled"?Y.value:[],...K.status==="fulfilled"?K.value:[]];if(V.length>0)return V;let G=[Y,K].flatMap((B)=>B.status==="rejected"?[B.reason]:[]);throw G.find((B)=>["dns_temporary","dns_timeout"].includes(GZ(B)))??G[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{Z?.removeEventListener("abort",J)}}}var O1=T1();async function D1($,Q,Z,X){if(X?.aborted)throw Error("aborted");let J=new AbortController,Y,K,V=Q($,J.signal);V.catch(()=>{});try{return await Promise.race([V,new Promise((G,F)=>{if(Y=setTimeout(()=>F(new DOMException("DNS lookup timed out","TimeoutError")),Z),X)K=()=>F(Error("aborted")),X.addEventListener("abort",K,{once:!0})})])}finally{if(Y!==void 0)clearTimeout(Y);if(X&&K)X.removeEventListener("abort",K);J.abort()}}async function XX($,Q=O1,Z){let X=YZ($);if($8(X))return e9(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await D1(X,Q,zZ,Z)}catch(Y){return{ok:!1,reason:Z?.aborted?Z.reason instanceof Error&&Z.reason.name==="TimeoutError"?"dns_timeout":"aborted":GZ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(e9))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:J}}var _1=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function d8($){return $.length<=253&&_1.test($.toLowerCase())}function A1($,Q){let Z=$.trim().toLowerCase();if(!d8(Z))return!1;if(Z.startsWith("*.")){let X=Z.slice(2);return Q===X||Q.endsWith(`.${X}`)}return Z===Q}function x1($){let Q=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec($);if(!Q)return null;let Z=Q.slice(1).map(Number);return Z.some((X)=>X>255)?null:Z}function p8($,Q=[]){let Z=(X)=>{if(X=X.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!X.includes(":"))return X;try{X=new URL(`http://[${X}]/`).hostname.slice(1,-1)}catch{return X}let J=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(X);if(!J)return X;let Y=parseInt(J[1],16),K=parseInt(J[2],16);return`${Y>>8}.${Y&255}.${K>>8}.${K&255}`};return Q.some((X)=>Z(X)===Z($))}function u0($){$=$.toLowerCase().replace(/^\[|\]$/g,"");let Q=x1($);if(Q){let[Y,K,V]=Q;if(Y===127)return"loopback";return Y===0||Y===10||Y>=224||Y===100&&K>=64&&K<=127||Y===169&&K===254||Y===172&&K>=16&&K<=31||Y===192&&(K===168||K===0&&(V===0||V===2)||K===88&&V===99)||Y===198&&(K===18||K===19||K===51&&V===100)||Y===203&&K===0&&V===113?"private":"public"}if(!$.includes(":"))return"hostname";try{$=new URL(`http://[${$}]/`).hostname.slice(1,-1)}catch{return"private"}if($==="::1")return"loopback";let Z=/^::ffff:([\da-f]+):([\da-f]+)$/.exec($);if(Z){let Y=parseInt(Z[1],16),K=parseInt(Z[2],16);return u0(`${Y>>8}.${Y&255}.${K>>8}.${K&255}`)==="public"?"public":"private"}let[X,J=0]=$.split(":").map((Y)=>parseInt(Y||"0",16));return X<8192||X>16383||X===8194||X===8193&&(J<512||J===3512)||X===16383&&J<4096?"private":"public"}function I9($,Q){let Z;try{Z=new URL($)}catch{return{allowed:!1,url:$,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(Z.protocol))return{allowed:!0,url:$,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(Z.protocol))return{allowed:!1,url:$,host:Z.hostname||null,reason:"unsupported_protocol"};let X=Z.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(Q.mode==="off")return{allowed:!0,url:$,host:X,reason:"policy_off"};let J=(V)=>({allowed:!1,url:$,host:X,reason:V});if(Z.username||Z.password)return J("invalid_url");if(Q.mode==="public_web"){let V=u0(X)!=="public"&&u0(X)!=="hostname"||X==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(X)||!X.includes(".")&&!KZ(X)||Boolean(KZ(X)&&e9(X));return{allowed:!V,url:$,host:X,reason:V?"private_network":"public_web"}}let Y=Number(Z.port||(["https:","wss:"].includes(Z.protocol)?443:80));if(Q.deniedPorts?.includes(Y)||p8(X,Q.deniedHosts))return J("destination_not_allowed");let K=u0(X);if(K==="private"||["local","internal","arpa"].some((V)=>X===V||X.endsWith(`.${V}`)))return J("private_network");if(K==="loopback"||X==="localhost"||X.endsWith(".localhost"))return Q.allowedLoopbackPorts?.includes(Y)?{allowed:!0,url:$,host:X,reason:"loopback"}:J("destination_not_allowed");if(Q.allowedDomains.some((V)=>A1(V,X)))return{allowed:!0,url:$,host:X,reason:"allowed_domain"};return{allowed:!1,url:$,host:X,reason:"destination_not_allowed"}}import FZ from"child_process";import{accessSync as I1,constants as R1,readFileSync as E1,statSync as WZ}from"fs";import{createRequire as BZ}from"module";import{homedir as HZ}from"os";import{dirname as S1,isAbsolute as u8,join as Y9,resolve as w1}from"path";var Q8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:UZ.dependencies["playwright-core"],browser:"chromium"}),LZ=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],l8=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function R9($){try{return I1($,R1.X_OK),u8($)&&WZ($).isFile()}catch{return!1}}function s8($,Q=process.platform){let Z=Q==="darwin"?LZ:Q==="linux"?l8:null;return Z?($??Z).find(R9)??null:null}function b1(){if(!process.versions.bun)return;let $=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,$))return;let Q=[];FZ.spawn=new Proxy(FZ.spawn,{apply(Z,X,J){let Y=Reflect.apply(Z,X,J),K=J[1],V=J[2]?.stdio;if(Array.isArray(K)&&K.includes("--remote-debugging-pipe")&&Array.isArray(V)&&V[3]==="pipe"&&V[4]==="pipe")Q.push(Y);return Y}}),Object.defineProperty(globalThis,$,{value:Q})}async function Z8($){if(b1(),$!==void 0){if(!u8($))throw Error("hands_browser_driver_path_must_be_absolute");let X=Y9($,"package.json"),J=JSON.parse(E1(X,"utf8"));if(J.name!==Q8.driver)throw Error("hands_browser_wrong_driver");let Y=BZ(X)($),K=Y.default?.chromium??Y.chromium;if(!K)throw Error("hands_browser_missing_chromium");return{version:J.version,chromium:K}}let[Q,Z]=await Promise.all([import("./index-tv4kcb2a.js"),import("./package-s3eg9zrd.js").then((m)=>P1(m.default,1))]);return{version:Z.default.version,chromium:Q.chromium}}var k1=($,Q=Q8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Q}),f1=($)=>$.loadDriver?.()??Z8($.driverModuleDirectory),m1={"1.60.0":"1223"};function BX(){let $=process.platform,Q=m1[Q8.driverVersion];if(!Q||$!=="linux"&&$!=="darwin")return!1;let Z=(X)=>process.env[X]??process.env[`npm_config_${X.toLowerCase()}`]??process.env[`npm_package_config_${X.toLowerCase()}`];try{let X=Z("PLAYWRIGHT_BROWSERS_PATH"),J=X==="0"?Y9(S1(BZ(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?w1(Z("INIT_CWD")||process.cwd(),X):Y9($==="darwin"?Y9(HZ(),"Library","Caches"):process.env.XDG_CACHE_HOME||Y9(HZ(),".cache"),"ms-playwright");return WZ(Y9(J,`chromium-${Q}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function G9($={}){return NZ($,Q8.driverVersion)}async function n8($,Q={}){if($.driverVersion!=="1.61.1"||!u8($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return NZ({...Q,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function NZ($,Q){let Z=(G)=>k1(G,Q),X=$.platform??process.platform;if(X!=="linux"&&X!=="darwin")return Z("unsupported_platform");let J;try{J=await f1($)}catch{return Z("driver_missing")}if(J.version!==Q)return Z("driver_version_mismatch");let Y=(G,F)=>({status:"resolved",executablePath:G,source:F,driverVersion:J.version});if($.executablePath!==void 0)return R9($.executablePath)?Y($.executablePath,"configured"):Z("executable_missing");let K=J.chromium.executablePath();if(R9(K))return Y(K,"managed");let V=$.allowSystemBrowser===!0?s8($.systemCandidates,X):null;return V?Y(V,"system"):Z("executable_missing")}var a1=["/usr/local/bin/chromium",...l8];function o1($,Q=DZ()){return s8($??(Q==="linux"?a1:void 0),Q)}async function r1(){try{return(await Z8()).chromium}catch{return u1(import.meta.url)("playwright-core").chromium}}var t1=1048576,e1=105000,$7=20000,CZ=5000,Q7=2000,Z7=1000,X7=30000,qZ=81920,J7={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Y7($,Q){let Z=new URL($.url()),X={...await $.allHeaders(),host:Z.host};for(let J of Object.keys(X))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(J))delete X[J];return new Promise((J,Y)=>{let V=(Z.protocol==="https:"?s1:l1)(Z,{method:$.method(),headers:X,agent:!1,lookup:(F,B,H)=>{let z=l0.isIP(Q);if(B.all)H(null,[{address:Q,family:z}]);else H(null,Q,z)}},(F)=>{let B=[],H=0;F.on("data",(z)=>{if(H+=z.length,H>33554432)V.destroy(Error("hands_browser_response_too_large"));else B.push(z)}),F.on("error",Y),F.on("end",()=>{let z={};for(let[L,W]of Object.entries(F.headers))if(W!==void 0&&!["transfer-encoding","connection","content-length"].includes(L))z[L]=Array.isArray(W)?W.join(`
306
+ `.trim();import{Buffer as X9}from"buffer";import{randomUUID as z1}from"crypto";class tQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var eQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),aQ=/^hands_[A-Za-z0-9_-]{8,128}$/,K1=2048,$Z=32,QZ=1e4,V1=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function F1($){let Q=$.split("+"),Z=(Q.pop()??"").replace(/^Key/,"").toLowerCase();if(Z==="f12")return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(Z))return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&Q.includes("Shift")&&Z==="c")return!0;return Q.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(Z)}var H1=($)=>{let Q=$.closest("a[href],area[href]");return{password:$.tagName==="INPUT"&&$.type==="password",executableLink:Boolean(Q&&!/^(https?:|about:blank)/i.test(Q.href))}},ZZ={browser:{close:{returns:"void"},contexts:{returns:"context[]"},isConnected:{returns:"json"},version:{returns:"json"}},context:{addCookies:{returns:"void"},addInitScript:{returns:"void"},browser:{returns:"browser"},clearCookies:{returns:"void"},clearPermissions:{returns:"void"},close:{returns:"void"},cookies:{returns:"json"},grantPermissions:{returns:"void"},newPage:{returns:"page"},pages:{returns:"page[]"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setGeolocation:{returns:"void"},setHTTPCredentials:{returns:"void"},setOffline:{returns:"void"},setViewportSize:{returns:"void"},storageState:{returns:"json"},viewportSize:{returns:"json",special:"contextViewportSize"}},page:{addInitScript:{returns:"void"},addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},bringToFront:{returns:"void"},close:{returns:"void"},content:{returns:"json"},context:{returns:"context"},emulateMedia:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},frame:{returns:"frame"},frameLocator:{returns:"frameLocator"},frames:{returns:"frame[]"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goBack:{returns:"void"},goForward:{returns:"void"},goto:{returns:"void"},isClosed:{returns:"json"},locator:{returns:"locator"},mainFrame:{returns:"frame"},opener:{returns:"page"},pdf:{returns:"bytes"},reload:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setContent:{returns:"void"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setInputFiles:{returns:"void"},setViewportSize:{returns:"void"},title:{returns:"json"},url:{returns:"json"},viewportSize:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},locator:{all:{returns:"locator[]"},allInnerTexts:{returns:"json"},allTextContents:{returns:"json"},and:{returns:"locator"},ariaSnapshot:{returns:"json"},blur:{returns:"void"},boundingBox:{returns:"json"},check:{returns:"void"},clear:{returns:"void"},click:{returns:"void"},contentFrame:{returns:"frameLocator"},count:{returns:"json"},dblclick:{returns:"void"},dragTo:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},evaluateAll:{returns:"json",requiresStringSource:!0},fill:{returns:"void"},filter:{returns:"locator"},first:{returns:"locator",special:"property"},focus:{returns:"void"},getAttribute:{returns:"json"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},hover:{returns:"void"},innerHTML:{returns:"json"},innerText:{returns:"json"},inputValue:{returns:"json"},isChecked:{returns:"json"},isEditable:{returns:"json"},isEnabled:{returns:"json"},isHidden:{returns:"json"},isVisible:{returns:"json"},last:{returns:"locator",special:"property"},locator:{returns:"locator"},nth:{returns:"locator"},or:{returns:"locator"},page:{returns:"page"},press:{returns:"void"},pressSequentially:{returns:"void"},scrollIntoViewIfNeeded:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setInputFiles:{returns:"void"},tap:{returns:"void"},textContent:{returns:"json"},type:{returns:"void"},uncheck:{returns:"void"},waitFor:{returns:"void"}},frame:{addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},childFrames:{returns:"frame[]"},content:{returns:"json"},evaluate:{returns:"json",requiresStringSource:!0},frameLocator:{returns:"frameLocator"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goto:{returns:"void"},isDetached:{returns:"json"},locator:{returns:"locator"},name:{returns:"json"},page:{returns:"page"},parentFrame:{returns:"frame"},setContent:{returns:"void"},title:{returns:"json"},url:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},frameLocator:{getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},locator:{returns:"locator"},owner:{returns:"locator"}}};function I($){throw new tQ($)}function z0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let Q=Object.getPrototypeOf($);return Q===Object.prototype||Q===null}function J9($,Q=0,Z={nodes:0}){if(Q>$Z||++Z.nodes>QZ)I("hands_repl_json_too_complex");if($===null||typeof $==="boolean"||typeof $==="string")return;if(typeof $==="number"){if(!Number.isFinite($))I("hands_repl_invalid_json");return}if(Array.isArray($)){for(let X of $)J9(X,Q+1,Z);return}if(!z0($))I("hands_repl_invalid_json");for(let[X,J]of Object.entries($)){if(eQ.has(X))I("hands_repl_invalid_json");J9(J,Q+1,Z)}}function v8($){return typeof $==="string"&&Object.hasOwn(ZZ,$)}function U1($){if(!$.endsWith("[]"))return null;let Q=$.slice(0,-2);return v8(Q)?Q:null}function oQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function W1($){return z0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function rQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function t9(){return Object.freeze({$handsRepl:"undefined"})}function B1($){if(!X9.isBuffer($)&&!($ instanceof Uint8Array))I("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:X9.from($).toString("base64")})}function XZ($){if(!k0($.browser)||!k0($.context)||!k0($.page))I("hands_repl_invalid_roots");if(typeof $.a11y!=="function"||typeof $.view!=="function")I("hands_repl_invalid_callbacks");let Q=$.maxHandles??K1;if(!Number.isInteger(Q)||Q<3||Q>1e5)I("hands_repl_invalid_handle_limit");let Z=new Map,X=new WeakMap,J=$.createOpaqueId??z1,Y=(z,L)=>{if(!k0(L))I("hands_repl_expected_target");let W=X.get(L)?.get(z);if(W)return W;if(Z.size>=Q)I("hands_repl_handle_limit");let U="";for(let q=0;q<16;q+=1){let A=`hands_${J()}`;if(aQ.test(A)&&!Z.has(A)){U=A;break}}if(!U)I("hands_repl_invalid_opaque_id");let j=Object.freeze({$handsRepl:"handle",id:U,kind:z});Z.set(U,{kind:z,target:L});let O=X.get(L);if(!O)O=new Map,X.set(L,O);return O.set(z,j),j},K=Object.freeze({browser:Y("browser",$.browser),context:Y("context",$.context),page:Y("page",$.page)}),V=(z)=>{if(!z0(z)||Object.keys(z).length!==3||z.$handsRepl!=="handle"||typeof z.id!=="string"||!aQ.test(z.id)||!v8(z.kind))I("hands_repl_invalid_handle");let L=Z.get(z.id);if(!L||L.kind!==z.kind)I("hands_repl_unknown_handle");return L},G=(z,L=0,W=new Set)=>{if(L>$Z)I("hands_repl_json_too_complex");if(z===void 0)return t9();if(z===null||typeof z==="boolean"||typeof z==="string")return z;if(typeof z==="number"){if(!Number.isFinite(z))I("hands_repl_non_json_result");return z}if(Array.isArray(z)){if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{return z.map((U)=>G(U,L+1,W))}finally{W.delete(z)}}if(!z0(z))I("hands_repl_non_json_result");if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{let U=Object.create(null);for(let j of Object.keys(z)){let O=Object.getOwnPropertyDescriptor(z,j);if(!O||!("value"in O))continue;U[j]=G(O.value,L+1,W)}return U}finally{W.delete(z)}},F=(z,L)=>{if(L==="void")return t9();if(L==="json")return G(z);if(L==="bytes")return B1(z);let W=U1(L);if(W){if(!Array.isArray(z))I("hands_repl_expected_target_list");if(W==="context"&&z.some((U)=>U!==$.context))I("hands_repl_foreign_context");return z.map((U)=>Y(W,U))}if(z===null||z===void 0)return t9();if(!v8(L))I("hands_repl_invalid_return_kind");if(L==="context"&&z!==$.context)I("hands_repl_foreign_context");return Y(L,z)},B=(z)=>{if(z0(z)&&z.$handsRepl==="handle")return V(z).target;if(oQ(z))return X9.from(z.base64,"base64");if(W1(z))return;if(rQ(z))I("hands_repl_route_fulfill_only");if(Array.isArray(z))return z.map(B);if(!z0(z))return z;let L=Object.create(null);for(let[W,U]of Object.entries(z))L[W]=B(U);return L};return Object.freeze({roots:K,dispatch:async(z)=>{if(!z0(z)||typeof z.type!=="string")I("hands_repl_invalid_request");if(z.type==="a11y"){let T=z.target===void 0?Z.get(K.page.id):V(z.target);if(!T||T.kind!=="page"&&T.kind!=="locator")I("hands_repl_invalid_a11y_target");return G(await $.a11y(T.target))}if(z.type==="view"){if(J9(z.source),z.options!==void 0)J9(z.options);let T=oQ(z.source)?X9.from(z.source.base64,"base64"):z.source;if($.privateProfile&&!X9.isBuffer(T))I("hands_repl_profile_requires_image_bytes");return G(await $.view(T,z.options))}if(z.type!=="call")I("hands_repl_invalid_request");if(typeof z.method!=="string"||z.method.length===0||z.method.length>128)I("hands_repl_invalid_method");if(eQ.has(z.method))I("hands_repl_forbidden_method");let L=V(z.target),W=z.args??[];if(!Array.isArray(W))I("hands_repl_invalid_arguments");if(J9(W),L.kind==="page"&&z.method==="captureScreenshot"){if(W.length!==0)I("hands_repl_invalid_arguments");if(!$.screenshotExport)I("hands_repl_screenshot_export_unavailable");return G(await $.screenshotExport(L.target))}if(L.kind==="context"&&["startRecording","stopRecording"].includes(z.method)){if(!$.recording||L.target!==$.context)I("hands_repl_recording_unavailable");if(W.length>(z.method==="startRecording"?1:0))I("hands_repl_invalid_arguments");return G(z.method==="startRecording"?await $.recording.start(W[0]):await $.recording.stop())}if($.privateProfile){let T=z.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(T)||L.kind==="browser"&&T==="close"||L.kind==="context"&&T==="close")I("hands_repl_private_profile_method_denied");if(L.kind==="browser"&&T==="contexts")return F([$.context],"context[]");if((T==="screenshot"||T==="pdf")&&z0(W[0])&&(("path"in W[0])||("style"in W[0])))I("hands_repl_private_profile_path_denied");if(T==="goto"){if(typeof W[0]!=="string")I("hands_repl_private_profile_url_denied");try{let S=new URL(W[0]);if(!["http:","https:"].includes(S.protocol)&&W[0]!=="about:blank")I("hands_repl_private_profile_url_denied")}catch{I("hands_repl_private_profile_url_denied")}}if(T==="getAttribute"&&(typeof W[0]!=="string"||!V1.has(W[0].toLowerCase())))I("hands_repl_private_profile_attribute_denied");if(L.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(T)){let S=[L.target];if(T==="allInnerTexts"){let m=Reflect.get(L.target,"all");if(typeof m!=="function")I("hands_repl_private_profile_probe_unavailable");let E=await Reflect.apply(m,L.target,[]);if(!Array.isArray(E)||E.length>QZ||!E.every(k0))I("hands_repl_private_profile_probe_unavailable");S=E}for(let m of S){let E=Reflect.get(m,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,m,[]))I("hands_repl_private_profile_hidden_value_denied")}}if(T==="press"&&typeof W[0]==="string"&&F1(W[0]))I("hands_repl_private_profile_browser_shortcut_denied");if(L.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(T)){let S=Reflect.get(L.target,"evaluate");if(typeof S!=="function")I("hands_repl_private_profile_probe_unavailable");let m=await Reflect.apply(S,L.target,[H1]);if(!z0(m)||typeof m.password!=="boolean"||typeof m.executableLink!=="boolean")I("hands_repl_private_profile_probe_unavailable");if(T==="inputValue"&&m.password)I("hands_repl_private_profile_password_denied");if(T!=="inputValue"&&m.executableLink)I("hands_repl_private_profile_url_denied");if(T==="inputValue"){let E=Reflect.get(L.target,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,L.target,[]))I("hands_repl_private_profile_hidden_value_denied")}}}let U=ZZ[L.kind][z.method];if(!U)I("hands_repl_method_not_allowed");if(U.requiresStringSource&&typeof W[0]!=="string")I("hands_repl_string_source_required");if(L.kind==="browser"&&z.method==="contexts")return[K.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(z.method)&&W.some((T)=>z0(T)&&("path"in T)))I("hands_repl_file_path_not_allowed");if(z.method==="goto"&&typeof W[0]==="string"){let T;try{T=new URL(W[0]).protocol}catch{I("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(T))I("hands_repl_file_path_not_allowed")}if(U.special==="contextViewportSize"){let T=Reflect.get(L.target,"pages");if(typeof T!=="function")I("hands_repl_method_unavailable");let S=await Reflect.apply(T,L.target,[]),m=Array.isArray(S)?S[0]:void 0,E=k0(m)?Reflect.get(m,"viewportSize"):void 0;if(typeof E!=="function")return t9();return F(await Reflect.apply(E,m,[]),U.returns)}if(U.special==="property"){let T=Reflect.get(L.target,z.method);return F(typeof T==="function"?Reflect.apply(T,L.target,[]):T,U.returns)}let j=Reflect.get(L.target,z.method);if(typeof j!=="function")I("hands_repl_method_unavailable");if(U.special==="route"){let T=W[1];if(!rQ(T))I("hands_repl_invalid_route_handler");J9(T.options);let S=B(T.options),m=async(M)=>{if(!k0(M))I("hands_repl_invalid_route");let D=Reflect.get(M,"fulfill");if(typeof D!=="function")I("hands_repl_invalid_route");await Reflect.apply(D,M,[S])},E=[B(W[0]??null),m],N=await Reflect.apply(j,L.target,E);return F(N,U.returns)}let O=W.map(B);if(z.method==="setInputFiles"){let T=L.kind==="locator"?0:1,S=async(E)=>{if(typeof E!=="string"){if(!z0(E)||typeof E.name!=="string"||typeof E.mimeType!=="string"||!X9.isBuffer(E.buffer))I("hands_repl_invalid_file_input");return E}if(!$.readWorkspaceFile)I("hands_repl_workspace_required");return $.readWorkspaceFile(E)},m=O[T];O[T]=Array.isArray(m)?await Promise.all(m.map(S)):await S(m)}if(z.method==="goto")await $.beforeNavigation?.();let q=$.actionRecorder?.(),A=await Reflect.apply(j,L.target,O),P={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[z.method];if(P){let T=Reflect.get(L.target,"page"),S=L.kind==="page"?L.target:typeof T==="function"?Reflect.apply(T,L.target,[]):void 0;q?.(P,k0(S)?S:void 0)}return F(A,U.returns)}})}import{isIP as KZ}from"net";import{Resolver as L1}from"dns/promises";import{isIP as $8}from"net";var N1=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function c8($){if($8($)!==4)return null;let Q=$.split(".");if(Q.length!==4)return null;let Z=0;for(let X of Q){let J=Number(X);if(!Number.isInteger(J)||J<0||J>255)return null;Z=Z*256+J}return Z>>>0}function M1($,Q,Z){let X=c8(Q);if(X===null)return!1;let J=Z===0?0:4294967295<<32-Z>>>0;return($&J)>>>0===(X&J)>>>0}function JZ($){let Q=c8($);if(Q===null)return!0;return N1.some(([Z,X])=>M1(Q,Z,X))}function j1($){if($8($)!==6)return null;let Q=$.toLowerCase(),Z=Q.indexOf("%");if(Z>=0)Q=Q.slice(0,Z);let X=[],J=Q.lastIndexOf(":"),Y=J>=0?Q.slice(J+1):"";if(Y.includes(".")){let z=c8(Y);if(z===null)return null;X=[z>>>16&65535,z&65535],Q=Q.slice(0,J+1)+"0:0"}let K=Q.split("::");if(K.length>2)return null;let V=(z)=>{if(z==="")return[];let L=[];for(let W of z.split(":")){if(W===""||W.length>4||!/^[0-9a-f]+$/.test(W))return null;L.push(Number.parseInt(W,16))}return L},G=V(K[0]??"");if(G===null)return null;if(K.length===1){let z=G;if(z.length!==8)return null;return X.length>0?z.slice(0,6).concat(X):z}let F=V(K[1]??"");if(F===null)return null;let B=8-G.length-F.length;if(B<0)return null;let H=G.concat(Array(B).fill(0),F);if(H.length!==8)return null;return X.length>0?H.slice(0,6).concat(X):H}function C1($,Q){return`${$>>8&255}.${$&255}.${Q>>8&255}.${Q&255}`}function q1($){let Q=j1($);if(Q===null)return!0;let[Z,X,J]=Q;if((Z&57344)!==8192)return!0;if(Z===8193&&(X&65024)===0)return!0;if(Z===8193&&X===3512)return!0;if(Z===16383&&(X&61440)===0)return!0;if(Z===8194)return JZ(C1(X,J));return!1}function YZ($){return $.replace(/^\[|\]$/g,"")}function e9($){let Q=YZ($.trim()),Z=$8(Q);if(Z===4)return JZ(Q);if(Z===6)return q1(Q);return!0}function GZ($){if($ instanceof Error&&$.name==="TimeoutError")return"dns_timeout";switch(typeof $==="object"&&$!==null&&"code"in $?$.code:void 0){case"ENOTFOUND":return"dns_not_found";case"ENODATA":return"dns_empty";case"EAI_AGAIN":case"ESERVFAIL":case"ECONNREFUSED":return"dns_temporary";case"ETIMEOUT":case"ETIMEDOUT":return"dns_timeout";default:return"dns_failed"}}var zZ=5000;function T1($){return async(Q,Z)=>{if(Z?.aborted)throw Error("aborted");let X=new L1({timeout:zZ,tries:1});if($)X.setServers($);let J=()=>X.cancel();Z?.addEventListener("abort",J,{once:!0});try{let[Y,K]=await Promise.allSettled([X.resolve4(Q),X.resolve6(Q)]),V=[...Y.status==="fulfilled"?Y.value:[],...K.status==="fulfilled"?K.value:[]];if(V.length>0)return V;let G=[Y,K].flatMap((B)=>B.status==="rejected"?[B.reason]:[]);throw G.find((B)=>["dns_temporary","dns_timeout"].includes(GZ(B)))??G[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{Z?.removeEventListener("abort",J)}}}var O1=T1();async function D1($,Q,Z,X){if(X?.aborted)throw Error("aborted");let J=new AbortController,Y,K,V=Q($,J.signal);V.catch(()=>{});try{return await Promise.race([V,new Promise((G,F)=>{if(Y=setTimeout(()=>F(new DOMException("DNS lookup timed out","TimeoutError")),Z),X)K=()=>F(Error("aborted")),X.addEventListener("abort",K,{once:!0})})])}finally{if(Y!==void 0)clearTimeout(Y);if(X&&K)X.removeEventListener("abort",K);J.abort()}}async function XX($,Q=O1,Z){let X=YZ($);if($8(X))return e9(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await D1(X,Q,zZ,Z)}catch(Y){return{ok:!1,reason:Z?.aborted?Z.reason instanceof Error&&Z.reason.name==="TimeoutError"?"dns_timeout":"aborted":GZ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(e9))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:J}}var _1=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function d8($){return $.length<=253&&_1.test($.toLowerCase())}function A1($,Q){let Z=$.trim().toLowerCase();if(!d8(Z))return!1;if(Z.startsWith("*.")){let X=Z.slice(2);return Q===X||Q.endsWith(`.${X}`)}return Z===Q}function x1($){let Q=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec($);if(!Q)return null;let Z=Q.slice(1).map(Number);return Z.some((X)=>X>255)?null:Z}function p8($,Q=[]){let Z=(X)=>{if(X=X.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!X.includes(":"))return X;try{X=new URL(`http://[${X}]/`).hostname.slice(1,-1)}catch{return X}let J=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(X);if(!J)return X;let Y=parseInt(J[1],16),K=parseInt(J[2],16);return`${Y>>8}.${Y&255}.${K>>8}.${K&255}`};return Q.some((X)=>Z(X)===Z($))}function u0($){$=$.toLowerCase().replace(/^\[|\]$/g,"");let Q=x1($);if(Q){let[Y,K,V]=Q;if(Y===127)return"loopback";return Y===0||Y===10||Y>=224||Y===100&&K>=64&&K<=127||Y===169&&K===254||Y===172&&K>=16&&K<=31||Y===192&&(K===168||K===0&&(V===0||V===2)||K===88&&V===99)||Y===198&&(K===18||K===19||K===51&&V===100)||Y===203&&K===0&&V===113?"private":"public"}if(!$.includes(":"))return"hostname";try{$=new URL(`http://[${$}]/`).hostname.slice(1,-1)}catch{return"private"}if($==="::1")return"loopback";let Z=/^::ffff:([\da-f]+):([\da-f]+)$/.exec($);if(Z){let Y=parseInt(Z[1],16),K=parseInt(Z[2],16);return u0(`${Y>>8}.${Y&255}.${K>>8}.${K&255}`)==="public"?"public":"private"}let[X,J=0]=$.split(":").map((Y)=>parseInt(Y||"0",16));return X<8192||X>16383||X===8194||X===8193&&(J<512||J===3512)||X===16383&&J<4096?"private":"public"}function I9($,Q){let Z;try{Z=new URL($)}catch{return{allowed:!1,url:$,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(Z.protocol))return{allowed:!0,url:$,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(Z.protocol))return{allowed:!1,url:$,host:Z.hostname||null,reason:"unsupported_protocol"};let X=Z.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(Q.mode==="off")return{allowed:!0,url:$,host:X,reason:"policy_off"};let J=(V)=>({allowed:!1,url:$,host:X,reason:V});if(Z.username||Z.password)return J("invalid_url");if(Q.mode==="public_web"){let V=u0(X)!=="public"&&u0(X)!=="hostname"||X==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(X)||!X.includes(".")&&!KZ(X)||Boolean(KZ(X)&&e9(X));return{allowed:!V,url:$,host:X,reason:V?"private_network":"public_web"}}let Y=Number(Z.port||(["https:","wss:"].includes(Z.protocol)?443:80));if(Q.deniedPorts?.includes(Y)||p8(X,Q.deniedHosts))return J("destination_not_allowed");let K=u0(X);if(K==="private"||["local","internal","arpa"].some((V)=>X===V||X.endsWith(`.${V}`)))return J("private_network");if(K==="loopback"||X==="localhost"||X.endsWith(".localhost"))return Q.allowedLoopbackPorts?.includes(Y)?{allowed:!0,url:$,host:X,reason:"loopback"}:J("destination_not_allowed");if(Q.allowedDomains.some((V)=>A1(V,X)))return{allowed:!0,url:$,host:X,reason:"allowed_domain"};return{allowed:!1,url:$,host:X,reason:"destination_not_allowed"}}import FZ from"child_process";import{accessSync as I1,constants as R1,readFileSync as E1,statSync as WZ}from"fs";import{createRequire as BZ}from"module";import{homedir as HZ}from"os";import{dirname as S1,isAbsolute as u8,join as Y9,resolve as w1}from"path";var Q8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:UZ.dependencies["playwright-core"],browser:"chromium"}),LZ=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],l8=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function R9($){try{return I1($,R1.X_OK),u8($)&&WZ($).isFile()}catch{return!1}}function s8($,Q=process.platform){let Z=Q==="darwin"?LZ:Q==="linux"?l8:null;return Z?($??Z).find(R9)??null:null}function b1(){if(!process.versions.bun)return;let $=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,$))return;let Q=[];FZ.spawn=new Proxy(FZ.spawn,{apply(Z,X,J){let Y=Reflect.apply(Z,X,J),K=J[1],V=J[2]?.stdio;if(Array.isArray(K)&&K.includes("--remote-debugging-pipe")&&Array.isArray(V)&&V[3]==="pipe"&&V[4]==="pipe")Q.push(Y);return Y}}),Object.defineProperty(globalThis,$,{value:Q})}async function Z8($){if(b1(),$!==void 0){if(!u8($))throw Error("hands_browser_driver_path_must_be_absolute");let X=Y9($,"package.json"),J=JSON.parse(E1(X,"utf8"));if(J.name!==Q8.driver)throw Error("hands_browser_wrong_driver");let Y=BZ(X)($),K=Y.default?.chromium??Y.chromium;if(!K)throw Error("hands_browser_missing_chromium");return{version:J.version,chromium:K}}let[Q,Z]=await Promise.all([import("./index-80ep9259.js"),import("./package-44a3p8yk.js").then((m)=>P1(m.default,1))]);return{version:Z.default.version,chromium:Q.chromium}}var k1=($,Q=Q8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Q}),f1=($)=>$.loadDriver?.()??Z8($.driverModuleDirectory),m1={"1.60.0":"1223"};function BX(){let $=process.platform,Q=m1[Q8.driverVersion];if(!Q||$!=="linux"&&$!=="darwin")return!1;let Z=(X)=>process.env[X]??process.env[`npm_config_${X.toLowerCase()}`]??process.env[`npm_package_config_${X.toLowerCase()}`];try{let X=Z("PLAYWRIGHT_BROWSERS_PATH"),J=X==="0"?Y9(S1(BZ(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?w1(Z("INIT_CWD")||process.cwd(),X):Y9($==="darwin"?Y9(HZ(),"Library","Caches"):process.env.XDG_CACHE_HOME||Y9(HZ(),".cache"),"ms-playwright");return WZ(Y9(J,`chromium-${Q}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function G9($={}){return NZ($,Q8.driverVersion)}async function n8($,Q={}){if($.driverVersion!=="1.61.1"||!u8($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return NZ({...Q,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function NZ($,Q){let Z=(G)=>k1(G,Q),X=$.platform??process.platform;if(X!=="linux"&&X!=="darwin")return Z("unsupported_platform");let J;try{J=await f1($)}catch{return Z("driver_missing")}if(J.version!==Q)return Z("driver_version_mismatch");let Y=(G,F)=>({status:"resolved",executablePath:G,source:F,driverVersion:J.version});if($.executablePath!==void 0)return R9($.executablePath)?Y($.executablePath,"configured"):Z("executable_missing");let K=J.chromium.executablePath();if(R9(K))return Y(K,"managed");let V=$.allowSystemBrowser===!0?s8($.systemCandidates,X):null;return V?Y(V,"system"):Z("executable_missing")}var a1=["/usr/local/bin/chromium",...l8];function o1($,Q=DZ()){return s8($??(Q==="linux"?a1:void 0),Q)}async function r1(){try{return(await Z8()).chromium}catch{return u1(import.meta.url)("playwright-core").chromium}}var t1=1048576,e1=105000,$7=20000,CZ=5000,Q7=2000,Z7=1000,X7=30000,qZ=81920,J7={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Y7($,Q){let Z=new URL($.url()),X={...await $.allHeaders(),host:Z.host};for(let J of Object.keys(X))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(J))delete X[J];return new Promise((J,Y)=>{let V=(Z.protocol==="https:"?s1:l1)(Z,{method:$.method(),headers:X,agent:!1,lookup:(F,B,H)=>{let z=l0.isIP(Q);if(B.all)H(null,[{address:Q,family:z}]);else H(null,Q,z)}},(F)=>{let B=[],H=0;F.on("data",(z)=>{if(H+=z.length,H>33554432)V.destroy(Error("hands_browser_response_too_large"));else B.push(z)}),F.on("error",Y),F.on("end",()=>{let z={};for(let[L,W]of Object.entries(F.headers))if(W!==void 0&&!["transfer-encoding","connection","content-length"].includes(L))z[L]=Array.isArray(W)?W.join(`
307
307
  `):W;J({status:F.statusCode??502,headers:z,body:Buffer.concat(B)})})}),G=setTimeout(()=>V.destroy(Error("hands_browser_fetch_timeout")),X7);V.once("close",()=>clearTimeout(G)),V.on("error",Y),V.end($.postDataBuffer()??void 0)})}async function G7($,Q,Z=()=>{},X={lookup:(J)=>p1(J,{all:!0}),fetch:Y7}){let J=new WeakSet,Y=new WeakMap,K=(V)=>{let G=Y.get(V);if(G)return G;let F=(async()=>{if(!$.newCDPSession)return;let B=await $.newCDPSession(V),H=new Map;B.on("Network.loadingFinished",({requestId:z})=>H.delete(z)),B.on("Network.loadingFailed",({requestId:z})=>H.delete(z)),B.on("Fetch.requestPaused",async(z)=>{let L=z.networkId??z.requestId,W=z.redirectedRequestId?(H.get(L)??0)+1:0;H.set(L,W);let U=I9(z.request.url,Q),j=Q.mode==="enforce"&&Boolean(z.redirectedRequestId)&&U.host!==null&&!l0.isIP(U.host),O=!U.allowed?U:j?{...U,allowed:!1,reason:"destination_not_allowed"}:W>20?{...U,allowed:!1,reason:"redirect_not_supported"}:null;try{if(O)Z(O),await B.send("Fetch.failRequest",{requestId:z.requestId,errorReason:"BlockedByClient"});else await B.send("Fetch.continueRequest",{requestId:z.requestId})}catch{await B.send("Fetch.failRequest",{requestId:z.requestId,errorReason:"Failed"}).catch(()=>{})}}),await B.send("Network.enable"),await B.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),J.add(V)})();return Y.set(V,F),F};return await $.route("**/*",async(V)=>{let G=V.request().url(),F=I9(G,Q);if(F.allowed&&Q.mode==="public_web"){await V.continue();return}let B=V.request();if(F.allowed&&F.host&&l0.isIP(F.host)&&B.isNavigationRequest?.()){let H=B.frame();if(J.has(H.page())&&H===H.page().mainFrame()){await V.continue();return}}if(F.allowed&&(Q.mode==="off"||F.reason==="local_document")){await V.continue();return}if(F.allowed&&F.host)try{let H=F.host,z=u0(H),L,W=await(async()=>{if(z!=="hostname")return[{address:H,family:l0.isIP(H)}];if(F.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([X.lookup(H),new Promise((U,j)=>{L=setTimeout(()=>j(Error("hands_browser_dns_timeout")),5000)})])}finally{if(L)clearTimeout(L)}})();if(!W.length||W.some(({address:U})=>{let j=u0(U);return!l0.isIP(U)||Q.mode==="enforce"&&p8(U,Q.deniedHosts)||(F.reason==="loopback"?j!=="loopback":j!=="public")}))F={...F,allowed:!1,reason:"private_network"};else{let U=await X.fetch(V.request(),W[0].address);if(U.status>=300&&U.status<400){let j=U.headers.location??G;try{j=new URL(j,G).href}catch{}let O=I9(j,Q);F=O.allowed?{...O,allowed:!1,reason:"redirect_not_supported"}:O}else{await V.fulfill(U);return}}}catch{await V.abort("failed");return}Z(F),await V.abort("blockedbyclient")}),await $.routeWebSocket("**/*",async(V)=>{let G=I9(V.url(),Q);if(Q.mode==="enforce"&&G.allowed&&(!G.host||!l0.isIP(G.host)))G={...G,allowed:!1,reason:"destination_not_allowed"};if(G.allowed){V.connectToServer();return}Z(G),await V.close({code:1008,reason:"Reason egress policy denied"})}),Q.mode==="off"?void 0:{preparePage:K}}async function _Z($,Q=DZ(),Z){if(Z){let J=await n8(Z,{platform:Q,systemCandidates:$});return J.status==="resolved"?J.executablePath:null}if($!==void 0){let J=o1($,Q);if(J)return J}let X=await G9({platform:Q,systemCandidates:$,allowSystemBrowser:!0});return X.status==="resolved"?X.executablePath:null}function TZ($,Q){if(!$)throw Error("hands_repl_workspace_required");let Z=a8($),X=z9($),J=o8(X,z9(X,Q)),K=J!==".."&&!J.startsWith(`..${r8}`)&&!jZ(J)?z9(Z,J):z9(Z,Q);if(b0(z9(X,Q))||b0(K))throw Error("hands_repl_protected_path");let V=(W)=>{let U=o8(Z,W);return U!==""&&U!==".."&&!U.startsWith(`..${r8}`)&&!jZ(U)},G=a8(K);if(b0(G))throw Error("hands_repl_protected_path");if(!V(K)||!V(G))throw Error("hands_repl_file_outside_workspace");let F=o8(Z,K).split(r8),B=[Z,...F.map((W,U)=>z9(Z,...F.slice(0,U+1)))],H=B.map((W)=>MZ(W));if(H.some((W)=>W.isSymbolicLink()))throw Error("hands_repl_file_symlink");let z=H[H.length-1];if(!z.isFile()||z.nlink!==1||z.size>16777216)throw Error("hands_repl_file_not_regular_or_too_large");let L=v1(K,i8.O_RDONLY|i8.O_NOFOLLOW|i8.O_NONBLOCK);try{let W=h1(L);if(W.dev!==z.dev||W.ino!==z.ino||!W.isFile())throw Error("hands_repl_file_changed");for(let q=0;q<B.length;q++){let A=MZ(B[q]);if(A.dev!==H[q].dev||A.ino!==H[q].ino||A.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!V(a8(K)))throw Error("hands_repl_file_outside_workspace");let U=Buffer.alloc(16777217),j=0;while(j<U.length){let q=c1(L,U,j,U.length-j,null);if(!q)break;j+=q}if(j===U.length)throw Error("hands_repl_file_too_large");let O=U.subarray(0,j);return{name:n1(K),mimeType:J7[i1(K).toLowerCase()]??"application/octet-stream",buffer:O}}finally{y1(L)}}function K9($,Q){$.end(`${JSON.stringify(Q)}
308
308
  `)}function X8($){try{d1($)}catch{}}async function AZ($){if($.managedBrowser&&$.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let Q=$.launch||$.targetContext?null:$.managedBrowser?await n8($.managedBrowser,{executablePath:$.browserExecutablePath}):await G9({executablePath:$.browserExecutablePath,driverModuleDirectory:$.driverModuleDirectory});if(Q?.status==="unavailable")throw Error(`hands_browser_${Q.reason}`);let Z=Q?.status==="resolved"?Q.executablePath:$.browserExecutablePath;if(!Z||!R9(Z))throw Error("hands_browser_unavailable");let X=$.launch??(async(N)=>($.targetContext?await r1():(await Z8($.managedBrowser?.driverModuleDirectory??$.driverModuleDirectory)).chromium).launch(N)),J=[],Y={},K=null,V=null,G=null,F=null,B=!1,H=null,z=new Map,L=new WeakMap,W=null,U=()=>{if(B)throw Error("hands_repl_stopped");if(F)throw F},j=(N)=>{let M=L.get(N);if(M)return M;let D=Promise.resolve().then(()=>N.close()).then(()=>{z.delete(N)});return L.set(N,D),D},O=async()=>{let N=[...z.entries()].reverse(),M=W??=performance.now()+Z7,D=Promise.allSettled(N.filter(([,_])=>_==="context").map(([_])=>j(_))),w;try{await Promise.race([D,new Promise((_)=>{w=setTimeout(_,Math.max(0,M-performance.now()))})])}finally{if(w)clearTimeout(w)}let k=await Promise.allSettled(N.map(([_])=>j(_))),f=[];for(let[_,g]of k.entries()){if(g.status!=="rejected")continue;let c=g.reason instanceof Error&&["Error","TimeoutError","ProtocolError"].includes(g.reason.name)?g.reason.name:"unknown";f.push(Error(`hands_repl_close_failed: ${N[_][1]}: ${c}`))}if(f.length)throw AggregateError(f,"hands_repl_stop_unconfirmed")},q=(N,M)=>{if(z.set(N,M),B||F)j(N).catch(()=>{return}),U();return N},A=async()=>{let N=await X({executablePath:Z,headless:!0,chromiumSandbox:$.managedBrowser===void 0,args:["--disable-background-networking","--disable-quic","--disable-dev-shm-usage","--disable-gpu","--disable-software-rasterizer","--dns-prefetch-disable","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--no-pings"]}),M=null;try{q(N,"browser"),M=$.targetContext??q(await N.newContext({viewport:{width:1440,height:900},screen:{width:1440,height:900},serviceWorkers:"block",acceptDownloads:!1}),"context");let D=await G7(M,$.networkPolicy??{mode:"off"},$.onEgressDenied);if(U(),D){let b=M.newPage.bind(M);M.newPage=async()=>{let h=await b();return await D.preparePage(h),h}}let k=M.pages()[0]??await M.newPage();await D?.preparePage(k),U();let f=async(b=k)=>{let h=b;if(typeof h.ariaSnapshot==="function")return h.ariaSnapshot({timeout:1e4});return k.locator("body").innerText({timeout:1e4})},_=async(b,h={})=>{let d=h&&typeof h==="object"&&!Array.isArray(h)?h:{},l,G0="image/png";if(Buffer.isBuffer(b)||b instanceof Uint8Array)l=Buffer.from(b);else if(typeof b==="string"&&(b.startsWith("data:")||/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(b)))l=Buffer.from(b.replace(/^data:[^,]*,/,""),"base64");else if(typeof b==="string"){let T0=TZ($.workspaceRoot,b);l=T0.buffer,G0=T0.mimeType}else throw Error("view() needs a Buffer, a base64 string, or a path to an image file");if(l.length===0)throw Error("view(): the image is empty");let M0=String(d.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),U0=Number(d.maxWidth)||1024,W0=Number(d.quality)||72,y0=$.targetContext?await N.newPage():await M.newPage();try{let T0=`data:${G0};base64,${l.toString("base64")}`;for(let r=0;r<5;r+=1){let j0=await y0.evaluate(async(B0)=>{let C0=new Image;C0.src=B0.url,await C0.decode();let h0=Math.min(1,B0.maxWidth/C0.naturalWidth),Y0=document.createElement("canvas");Y0.width=Math.max(1,Math.round(C0.naturalWidth*h0)),Y0.height=Math.max(1,Math.round(C0.naturalHeight*h0));let X0=Y0.getContext("2d");if(!X0)throw Error("view(): canvas unavailable");return X0.fillStyle="#ffffff",X0.fillRect(0,0,Y0.width,Y0.height),X0.drawImage(C0,0,0,Y0.width,Y0.height),{data:Y0.toDataURL("image/jpeg",B0.q/100).split(",")[1]??"",width:Y0.width,height:Y0.height,sourceWidth:C0.naturalWidth,sourceHeight:C0.naturalHeight}},{url:T0,maxWidth:U0,q:W0}),r0=Buffer.from(j0.data,"base64");if(r0.length<=qZ){let B0=M0||"image";return`<<<ARA_VIEW_IMAGE ${j0.data} image/jpeg ${B0}>>>
309
309
  Viewing ${B0} (${j0.sourceWidth}x${j0.sourceHeight} source, sent at ${j0.width}x${j0.height}, ${Math.round(r0.length/1024)}KB).`}if(U0>640)U0=Math.round(U0*0.75);else W0=Math.max(30,W0-15)}throw Error(`view(): could not reduce the image under ${Math.round(qZ/1024)}KB`)}finally{await y0.close().catch(()=>{return})}},g=XZ({browser:$.targetContext?.browser()??N,context:M,page:k,a11y:f,view:_,readWorkspaceFile:(b)=>TZ($.workspaceRoot,b),privateProfile:$.privateProfile,beforeNavigation:$.beforeNavigation,recording:$.recording,screenshotExport:$.screenshotExport,actionRecorder:()=>{let b=J,h=Y;return(d,l)=>{if(b.length<OZ)b.push(d);if(l)h.page=l}}}),c=async(b)=>{U();let h=q(await N.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await h.route("**/*",(l)=>l.abort()),U(),await h.routeWebSocket("**/*",(l)=>l.close({code:1008,reason:"Reason evaluator network denied"})),U(),await h.exposeBinding("__araHandsRpc",async(l,G0)=>$.onBrowserOperation?$.onBrowserOperation(b,()=>g.dispatch(G0)):g.dispatch(G0)),U();let d=await h.newPage();return U(),await d.goto("data:text/html,<title>Reason Hands evaluator</title>"),U(),await d.evaluate(`(${nQ})(${JSON.stringify(g.roots)})`),{context:h,page:d,runId:b}}catch(d){throw await j(h).catch(()=>{return}),d}},u=await c(),o={browser:N,context:M,page:k,evaluator:u,async captureProgressFrame(b){return _(await b.screenshot({type:"jpeg",quality:65,timeout:2000}),{label:"Screen after browser action"})},async resetEvaluator(b){await j(o.evaluator.context),o.evaluator=await c(b)}};return U(),o}catch(D){throw await O().catch(()=>{return}),D}},R=async()=>{if(U(),K)return K;if(!G){V=A();let N;G=Promise.race([V,new Promise((M,D)=>{N=setTimeout(()=>D(Error("hands_browser_unavailable: startup timed out")),$7)})]).then((M)=>{return U(),K=M,M}).catch(async()=>{F=Error("hands_browser_unavailable: startup failed or timed out");let M;try{await Promise.race([O(),new Promise((D,w)=>{M=setTimeout(()=>w(Error("hands_repl_stop_timeout")),CZ)})])}catch{F=Error("hands_browser_unavailable: startup cleanup unconfirmed")}finally{if(M)clearTimeout(M)}throw F}).finally(()=>{if(N)clearTimeout(N)})}return G},P=async(N,M,D=!1)=>{let w=await R(),k=Y;if($.onBrowserOperation&&w.evaluator.runId!==M)await w.resetEvaluator(M);let _=(async()=>{let u=await w.evaluator.page.evaluate(`(${iQ})(${JSON.stringify({code:N})})`);if(typeof u!=="string")throw Error("hands_repl_invalid_evaluator_output");let o=k.page;if(D&&o&&!u.includes("<<<ARA_VIEW_IMAGE")){let b=()=>w.captureProgressFrame(o);try{let h=await($.onBrowserOperation?$.onBrowserOperation(M,b):b());return k.automaticProgressImage=!0,`${u}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var p={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},z=Object.values(p),x=new Set;function B(k,j){let q=k[j];if(q?.trim())return q;let w=k[p[j]];if(w?.trim())x.add(p[j]);return w}function D(k,j){return{[k]:j,[p[k]]:j}}
3
- export{B as ni,D as oi};
3
+ export{B as oi,D as pi};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Ri as J}from"./vm-hands-entry-lite-1j9r1fca.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
2
+ import{Si as J}from"./vm-hands-entry-lite-tbps80f1.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
3
3
  `)){let j=I.split(":");if(j.length<7||Number(j[2])!==q||!/^\d+$/.test(j[2])||!/^\d+$/.test(j[3]))continue;let x=j[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(j[0])||!M(x)||Q(x)!==x||x==="/")return null;return{username:j[0],uid:q,gid:Number(j[3]),home:x}}return null}function b(q={}){let B="value"in q?q.value:process.env[W];if(G=null,B===void 0||B==="")return null;let I=q.platform??process.platform,j="euid"in q?q.euid:process.geteuid?.(),x=/^[1-9]\d{0,9}$/.test(B)?Number(B):NaN,C=I==="linux"&&j===0&&Number.isSafeInteger(x)?X(x,(q.passwd??(()=>L("/etc/passwd","utf8")))()):null;if(!C||C.gid===0)throw Error("worker_desktop_user_invalid");return G=C,C}function k(){return G}function y(){return G?.home??J()}
4
- export{W as Ag,X as Bg,b as Cg,k as Dg,y as Eg};
4
+ export{W as Bg,X as Cg,b as Dg,k as Eg,y as Fg};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Oj as q}from"./vm-hands-entry-lite-kv0qat0x.js";var u=25,U=q.object({machine:q.string().min(1).max(200),person:q.string().min(1).max(200),team:q.string().min(1).max(200),version:q.string().max(64).optional(),wait_seconds:q.number().int().min(0).max(u).optional()}),x=q.discriminatedUnion("kind",[q.object({id:q.string(),kind:q.literal("who"),all:q.boolean().optional()}),q.object({id:q.string(),kind:q.literal("send"),to:q.string(),body:q.string(),from_name:q.string(),from_agent:q.string(),wake:q.boolean(),reply_to:q.string().max(100).optional(),notify:q.boolean().optional()})]),V=q.object({job:x.nullable(),retry_after_seconds:q.number().optional()}),B=q.object({address:q.string(),person:q.string(),machine:q.string(),agent:q.string(),repo:q.string().nullable(),branch:q.string().nullable(),status:q.string(),since:q.number().nullable(),doing:q.string().nullable(),worker:q.boolean(),tier:q.string().max(10).optional()}),F=q.object({person:q.string(),machine:q.string(),online:q.boolean()}),G=q.object({team:q.string().nullable(),sessions:q.array(B).max(2000),machines:q.array(F).max(500),all:q.boolean().optional()}),H=q.object({address:q.string().max(300),state:q.string().max(40),note:q.string().max(500)}),X=q.union([q.object({who:G}),q.object({sent:q.object({ids:q.array(q.string().max(100)).max(500),recipients:q.array(q.string().max(300)).max(500),from:q.string().max(300),deliveries:q.array(H).max(500).optional()})}),q.object({error:q.string().min(1).max(2000)})]),K=q.object({id:q.string().max(100),from:q.string().max(300),from_agent:q.string().max(100).nullable(),to:q.string().max(300),reply_to:q.string().max(100).nullable(),body:q.string().max(64000),sent_at:q.number()}),Z=q.object({messages:q.array(K).max(100)});
2
+ import{Pj as q}from"./vm-hands-entry-lite-k7fkfytm.js";var u=25,U=q.object({machine:q.string().min(1).max(200),person:q.string().min(1).max(200),team:q.string().min(1).max(200),version:q.string().max(64).optional(),wait_seconds:q.number().int().min(0).max(u).optional()}),x=q.discriminatedUnion("kind",[q.object({id:q.string(),kind:q.literal("who"),all:q.boolean().optional()}),q.object({id:q.string(),kind:q.literal("send"),to:q.string(),body:q.string(),from_name:q.string(),from_agent:q.string(),wake:q.boolean(),reply_to:q.string().max(100).optional(),notify:q.boolean().optional()})]),V=q.object({job:x.nullable(),retry_after_seconds:q.number().optional()}),B=q.object({address:q.string(),person:q.string(),machine:q.string(),agent:q.string(),repo:q.string().nullable(),branch:q.string().nullable(),status:q.string(),since:q.number().nullable(),doing:q.string().nullable(),worker:q.boolean(),tier:q.string().max(10).optional()}),F=q.object({person:q.string(),machine:q.string(),online:q.boolean()}),G=q.object({team:q.string().nullable(),sessions:q.array(B).max(2000),machines:q.array(F).max(500),all:q.boolean().optional()}),H=q.object({address:q.string().max(300),state:q.string().max(40),note:q.string().max(500)}),X=q.union([q.object({who:G}),q.object({sent:q.object({ids:q.array(q.string().max(100)).max(500),recipients:q.array(q.string().max(300)).max(500),from:q.string().max(300),deliveries:q.array(H).max(500).optional()})}),q.object({error:q.string().min(1).max(2000)})]),K=q.object({id:q.string().max(100),from:q.string().max(300),from_agent:q.string().max(100).nullable(),to:q.string().max(300),reply_to:q.string().max(100).nullable(),body:q.string().max(64000),sent_at:q.number()}),Z=q.object({messages:q.array(K).max(100)});
3
3
  export{u as va,V as wa};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Zj as e}from"./vm-hands-entry-lite-h2xemq1f.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
2
+ import{_j as e}from"./vm-hands-entry-lite-hw8vgsmm.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
3
  export{i as Aa};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{De as UJ,Le as TJ,pf as CJ}from"./vm-hands-entry-lite-szfy3kx7.js";import{createHash as I,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as fJ,openSync as NJ,renameSync as mJ,rmSync as bJ,statSync as DJ,writeSync as AJ,constants as y}from"fs";import{join as r}from"path";var cJ=1;var i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function BJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&i.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var v=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),R=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function f(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(f).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${f(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",R(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=R(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),B=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=I("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:B,fingerprint:L}}var pJ=4;class lJ{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;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!i.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let B=this.bound.get(J);if(!B)return!1;if(B.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:cJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:v(this.keys.signingSpki),env_public_key:v(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:v(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(f(Z)));return{...Z,device_signature:v(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=v(zJ(32)),B=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:I("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(B)));return{t:"hello",timestamp:z,nonce:K,signature:v(uJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!i.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(I("sha256").update(f({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=pJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new W("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:Z}),this.unverified.clear();this.servedRun=!0,K=!0;let{launchId:B,applied:L,readyData:j}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),N=null,_=null;if(J.env){let H=J.claim?.owner??{},T=BJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof H.device_id==="string"?H.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,N=this.hooks.installEnvironment(J.bind_id,T),_=typeof T.snapshot_id==="string"&&T.snapshot_id?T.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,T)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:B,envInstalled:N!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:B,snapshot_revision:N,snapshot_id:_,layout:E,...j?{ready_data:j}:{},policy_digest:I("sha256").update(f({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(B){if(z)GJ(z);if(K){let j=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:j,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id);let L=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:"vm_hands_bind_failed";throw B instanceof W?B:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!i.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=BJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let B=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${B}`,K),{snapshot_id:J.snapshotId,installed_revision:B,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:I("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((B)=>B!==J),K=!z.length&&!this.commandsSinceVerified;try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:K?{bindId:J,own:!0}:void 0)}catch(B){throw this.unverified.add(J),B}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",R(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),B=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:R(J.iv),additionalData:new TextEncoder().encode(Z)},B,R(J.ct)).catch(z),j=JSON.parse(new TextDecoder().decode(L));if(!j||typeof j!=="object"||Array.isArray(j))throw new W("vm_hands_env_invalid","env not an object");return j}writeJobEnvRootOnly(J,Z){let z=r(this.options.envRoot,`bind-${J}`);fJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let B=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(B).filter(([N,_])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(N)&&typeof _==="string").map(([N,_])=>`export ${N}='${String(_).replaceAll("'","'\\''")}'`).join(`
2
+ import{Ee as UJ,Me as TJ,qf as CJ}from"./vm-hands-entry-lite-fr2k6eah.js";import{createHash as I,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as fJ,openSync as NJ,renameSync as mJ,rmSync as bJ,statSync as DJ,writeSync as AJ,constants as y}from"fs";import{join as r}from"path";var cJ=1;var i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function BJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&i.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var v=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),R=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function f(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(f).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${f(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",R(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=R(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),B=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=I("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:B,fingerprint:L}}var pJ=4;class lJ{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;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!i.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let B=this.bound.get(J);if(!B)return!1;if(B.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:cJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:v(this.keys.signingSpki),env_public_key:v(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:v(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(f(Z)));return{...Z,device_signature:v(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=v(zJ(32)),B=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:I("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(B)));return{t:"hello",timestamp:z,nonce:K,signature:v(uJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!i.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(I("sha256").update(f({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=pJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new W("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:Z}),this.unverified.clear();this.servedRun=!0,K=!0;let{launchId:B,applied:L,readyData:j}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),N=null,_=null;if(J.env){let H=J.claim?.owner??{},T=BJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof H.device_id==="string"?H.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,N=this.hooks.installEnvironment(J.bind_id,T),_=typeof T.snapshot_id==="string"&&T.snapshot_id?T.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,T)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:B,envInstalled:N!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:B,snapshot_revision:N,snapshot_id:_,layout:E,...j?{ready_data:j}:{},policy_digest:I("sha256").update(f({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(B){if(z)GJ(z);if(K){let j=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:j,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id);let L=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:"vm_hands_bind_failed";throw B instanceof W?B:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!i.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=BJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let B=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${B}`,K),{snapshot_id:J.snapshotId,installed_revision:B,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:I("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((B)=>B!==J),K=!z.length&&!this.commandsSinceVerified;try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:K?{bindId:J,own:!0}:void 0)}catch(B){throw this.unverified.add(J),B}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",R(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),B=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:R(J.iv),additionalData:new TextEncoder().encode(Z)},B,R(J.ct)).catch(z),j=JSON.parse(new TextDecoder().decode(L));if(!j||typeof j!=="object"||Array.isArray(j))throw new W("vm_hands_env_invalid","env not an object");return j}writeJobEnvRootOnly(J,Z){let z=r(this.options.envRoot,`bind-${J}`);fJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let B=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(B).filter(([N,_])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(N)&&typeof _==="string").map(([N,_])=>`export ${N}='${String(_).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,j=r(z,`.job.env.${zJ(8).toString("hex")}`),E=NJ(j,y.O_WRONLY|y.O_CREAT|y.O_EXCL|y.O_NOFOLLOW,384);try{AJ(E,L),qJ(E)}finally{LJ(E)}return mJ(j,r(z,"job.env")),z}}function GJ(J){try{let Z=r(J,"job.env"),z=DJ(Z).size,K=NJ(Z,y.O_WRONLY|y.O_NOFOLLOW);try{AJ(K,Buffer.alloc(z)),qJ(K)}finally{LJ(K)}}catch{}bJ(J,{recursive:!0,force:!0})}function uJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(B)=>{let L=0;while(L<B.length-1&&B[L]===0)L++;let j=B.subarray(L),E=j[0]&128?Uint8Array.of(0,...j):j;return Uint8Array.of(2,E.length,...E)},z=Z(J.subarray(0,32)),K=Z(J.subarray(32));return Uint8Array.of(48,z.length+K.length,...z,...K)}import{randomUUID as oJ}from"crypto";var dJ="/app/local-runtime/session?register=vm_hands_v1",rJ="/app/local-runtime",MJ=25000,iJ=20000,sJ=1e4,wJ=5000,EJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),YJ=75000,aJ=2000,nJ=1e4,s=20000;function OJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class k extends Error{}var tJ=64;async function hJ(J,Z){let z=[...J.modelOps.get(Z)??[]];for(let K of z)K.abort.abort();await Promise.race([Promise.all(z.map((K)=>K.settled)),new Promise((K)=>setTimeout(K,wJ))])}async function eJ(J){let Z=[...J.personTerminals];for(let z of Z)z.abort.abort();if(Z.length)await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,wJ))]);return Z.length}async function m(J,Z,z){return await hJ(J,z),Z.unbind(z)}function a(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var _J=15000,JZ=1e4,ZZ=1000;async function BZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:0},K=J.log??(()=>{}),B=async(L)=>{for(let[j,E]of[...z.turns]){z.turns.delete(j),J.onTurn?.(j,null),a(E);let N=await m(z,J.agent,j).catch(()=>null);if(N)z.receipts.push({turn:E,failure:"vm_hands_bind_lost",unbound:N});K("vm_hands.bound_dropped",{reason:L})}};try{for(let L=0;!J.signal.aborted;L++){let j=await $Z(J,z).catch((N)=>{if(N instanceof W&&z.deviceId===null&&N.code==="vm_hands_no_session"&&Date.now()-Z<nJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(N instanceof W&&z.deviceId===null)throw N;return{closeCode:0,closeReason:N instanceof Error?N.message:String(N)}});if(K("vm_hands.session_closed",{close_code:j.closeCode,reason:j.closeReason.slice(0,120),registered:z.deviceId!==null}),j.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=YJ)await B("reconnect_deadline");if(z.served)z.served=!1,L=0;let E=j.closeReason==="drain_reconnect"?0:j.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(L,5),2000):z.turns.size?Math.min(250*2**Math.min(L,5),5000,Math.max(0,z.lostAt+YJ-Date.now())):Math.min(500*2**L,30000);if(await new Promise((N)=>setTimeout(N,E)),z.turns.size&&Date.now()-z.lostAt>=YJ)await B("reconnect_deadline")}}finally{await B("session_ended")}}async function $Z(J,Z){let z=Z.deviceId,K=J.log??(()=>{}),B=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:dJ,L=`${J.apiOrigin.replace(/^http/,"ws")}${B}`,j=new WebSocket(L),E=0,N="",_=new Map,H=[],T=null,kJ=new Promise(($)=>{j.onclose=(Q)=>{E=Q.code,N=Q.reason;for(let G of _.values())G.reject(new k(`session closed ${Q.code}`));for(let G of Z.attestWaiters.splice(0))G(!1);_.clear(),$()}});j.onmessage=($)=>{let Q;try{Q=JSON.parse(String($.data))}catch{j.close(4400);return}if(Q.t==="res"){let G=Q;_.get(G.id)?.resolve({status:G.status,body:G.body}),_.delete(G.id);return}if(Q.t==="reconnect"){let G=Math.max(0,Math.min(Number(Q.after_ms)||0,ZZ));K("vm_hands.drain_reconnect",{after_ms:G}),setTimeout(()=>{try{j.close(4001,"drain_reconnect")}catch{}},G).unref?.();return}if(!T?.(Q))H.push(Q)};let b=($,Q)=>new Promise((G,X)=>{let U=H.findIndex((C)=>$.includes(C.t));if(U>=0){G(H.splice(U,1)[0]);return}let q=setTimeout(()=>{T=null,X(new W("vm_hands_no_register",`no ${$.join("/")} in ${Q} ms`))},Q);T=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(q),T=null,G(C),!0}}),c=($)=>j.send(JSON.stringify($)),g=($,Q)=>new Promise((G,X)=>{if(j.readyState!==WebSocket.OPEN){X(new k("session closed"));return}let U=oJ(),q=typeof Q.wait_ms==="number"?Q.wait_ms:0,C=setTimeout(()=>{if(!_.delete(U))return;X(new k(`no answer to ${$.split("/").pop()} in ${q+_J} ms`)),j.close(4000,"request_timeout")},q+_J);_.set(U,{reject:(Y)=>{clearTimeout(C),X(Y)},resolve:({status:Y,body:F})=>{clearTimeout(C);let P=null;try{P=F?JSON.parse(F):null}catch{}G({status:Y,json:P})}}),c({t:"req",id:U,path:`${rJ}${$}`,body:JSON.stringify(Q)})}),QJ=()=>j.close(1001,"stopping");J.signal.addEventListener("abort",QJ,{once:!0});let n,p=new Map,l=new Map,t=!1,e=new Set,JJ=new Set,ZJ=Promise.resolve(),u=!1;try{await new Promise((Y,F)=>{let P=setTimeout(()=>F(Error("session open timeout")),JZ);j.onopen=()=>{clearTimeout(P),K("vm_hands.ws_open",{}),Y()},j.onerror=()=>{clearTimeout(P),F(Error("session socket error"))}});let $=await b(["challenge"],5000);K("vm_hands.challenge",{});let Q=[],G=null,X;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let Y=await b(["ready"],1e4);if(typeof Y.vm_hands_connection==="string")Z.connection=Y.vm_hands_connection;if(X={device_id:z,...Y.cadence?{cadence:Y.cadence}:{}},typeof Y.vm_hands_probe_script==="string"){if(G=Y.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.reconnected",{device_id:z});let F=Array.isArray(Y.vm_hands_binds)?Y.vm_hands_binds:Y.vm_hands_bind?[Y.vm_hands_bind]:[];for(let[P,D]of[...Z.turns]){if(F.some((O)=>O&&O.operation_id===D.claim.operation_id&&O.attempt_id===D.claim.attempt_id)){Q.push(D),K("vm_hands.bound_resumed",{operation_id:D.claim.operation_id});continue}Z.turns.delete(P),J.onTurn?.(P,null),a(D);let x=await m(Z,J.agent,P).catch(()=>null);if(x)Z.receipts.push({turn:D,failure:"vm_hands_bind_lost",unbound:x});K("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{c(await J.agent.registerFrame($.challenge)),K("vm_hands.register_sent",{});let Y=await b(["registered","register_refused"],1e4);if(Y.t==="register_refused")throw new W(Y.code,"register refused");J.agent.registered();let F=Y;if(X=F,Z.deviceId=F.device_id,typeof F.vm_hands_connection==="string")Z.connection=F.vm_hands_connection;if(typeof F.vm_hands_probe_script==="string"){if(G=F.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.registered",{device_id:X.device_id})}let U=async()=>{let Y=await g("/heartbeat",await J.heartbeat());if(Y.status>=300)throw Error(`heartbeat ${Y.status}`)};await U();let q=X.cadence?.presence_interval_ms??30000;if(n=setInterval(()=>{U().catch(()=>j.close())},q),G&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)SJ(G,$.challenge);let C=(Y,F)=>{l.set(Y,F().catch(async(P)=>{if(await XJ(P,Y),P instanceof k)j.close();else await $J().catch(()=>{return})}).finally(()=>{l.delete(Y)}))};try{await $J();for(let Y of Q)Y.flush=()=>FJ(Y),Y.flush(),C(Y.claim.attempt_id,()=>WJ(Y));while(!J.signal.aborted&&j.readyState===WebSocket.OPEN){let Y=await g("/operations/claim",{wait_ms:Math.min(X.cadence?.claim_wait_ms??MJ,MJ)});if(Y.status===204||!Y.json)continue;if(Y.status>=300)throw Error(`claim ${Y.status}`);let F=Y.json;if(F.capability==="hands.connect"){if(l.has(F.attempt_id)){w({claim:F,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}C(F.attempt_id,()=>HJ(F))}else VJ(F).catch(()=>{return})}}catch(Y){await XJ(Y,null)}}finally{if(n)clearInterval(n);J.signal.removeEventListener("abort",QJ);for(let $ of Z.turns.values())$.flush=null;j.close(),await kJ,await Promise.all([...l.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let Q=await m(Z,J.agent,$).catch(()=>null),G=p.get($);if(Q&&G)Z.receipts.push({turn:{...G,eventSeq:G.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Q});K("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of e)$.abort()}return{closeCode:E,closeReason:N};async function XJ($,Q){if($ instanceof k){if(!t&&Z.turns.size)Z.lostAt=Date.now();t=!0}else{let G=Q!==null?[Q]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(Q===null)t=!0;for(let X of G){let U=Z.turns.get(X);if(Z.turns.delete(X),U)a(U),J.onTurn?.(X,null);if(J.agent.liveBindIds.includes(X)){let q=await m(Z,J.agent,X).catch(()=>null),C=p.get(X)??U;if(q&&C)Z.receipts.push({turn:{...C,eventSeq:C.eventSeq+1},failure:"vm_hands_bind_lost",unbound:q})}}}K("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turns.size})}function w($){let Q=$.claim,G={attempt_id:Q.attempt_id,attempt_token:Q.attempt_token},X=encodeURIComponent(Q.operation_id);return{fence:G,op:X,complete:(q,C={})=>g(`/operations/${X}/complete`,{...G,status:q,...C}),emit:(q,C)=>{let Y=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>U(q,C));return $.chain=Y,Y}};async function U(q,C){let Y=$.eventSeq,F=(O)=>g(`/operations/${X}/events`,{...G,event_seq_start:O,events:[{kind:q,payload:{sequence:O,capability:String(Q.capability??"hands.connect"),data:C}}]}),P=Y,D=await F(P),x=D.status===409?D.json?.expected_event_seq:void 0;if(typeof x==="number"&&x===Y+1)D={status:200,json:{duplicate:!0}};else if(typeof x==="number"&&x>=0&&x!==Y)P=x,D=await F(P);if(D.status<300)$.eventSeq=P+1;return D}}function gJ($){return(Q,G)=>new Promise((X,U)=>{if(Z.turns.get($.claim.attempt_id)!==$){U(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=tJ){U(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:Q,data:G,resolve:X,reject:U}),$.flush?.()})}function FJ($){if(JJ.has($))return;JJ.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&j.readyState===WebSocket.OPEN){let Q=$.outbox[0],G;try{G=await w($).emit(Q.kind,Q.data)}catch(X){if(X instanceof k)return;G={status:500}}if($.outbox.shift(),G.status<300)Q.resolve();else Q.reject(Error(`${Q.kind} refused ${G.status}`))}}finally{JJ.delete($)}})()}async function SJ($,Q){try{let G=await J.agent.attestFrame($,Q);if(j.readyState!==WebSocket.OPEN)return;c(G);let X=await b(["attested","attest_refused"],15000);Z.attest=X.t==="attested"?"accepted":"refused";for(let U of Z.attestWaiters.splice(0))U(Z.attest==="accepted");if(K("vm_hands.attest",{result:Z.attest,exit_code:G.exit_code,...X.t==="attest_refused"?{code:String(X.code??"")}:{}}),Z.attest==="refused")j.close(4401,"attest_refused")}catch(G){K("vm_hands.attest_failed",{code:G instanceof W?G.code:"probe_error"});for(let X of Z.attestWaiters.splice(0))X(!1);if(Z.attest!=="accepted")j.close(4000,"attest_unanswered")}}async function HJ($){let Q=u&&Z.attest==="pending",G=$.vm_hands_attest,X=G;if(Z.attest==="refused"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await w({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(X==="accepted"){if(!Q&&Z.attest!=="accepted"){Z.attest="accepted";for(let M of Z.attestWaiters.splice(0))M(!0)}}else if(X!=="pending"||!Q&&Z.attest!=="accepted"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await w({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let M=Date.parse($.lease_until)-Date.now()-5000,V=Math.max(0,Math.min(s,Number.isFinite(M)?M:s));if(!await new Promise((d)=>{let A=setTimeout(()=>d(!1),V);Z.attestWaiters.push((h)=>{clearTimeout(A),d(h)})})){await w({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let U={claim:$,eventSeq:0},{complete:q,emit:C}=w(U),Y;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");Y=!KJ($)}catch(M){K("vm_hands.bind_refused",{code:M instanceof W?M.code:"unexpected"}),await q("failed",{error_code:M instanceof W?M.code:"vm_hands_bind_invalid"});return}let F;Z.bindsStarting++;try{let M=await eJ(Z);if(M)K("vm_hands.person_terminals_closed",{count:M});F=await J.agent.bind(xJ($))}catch(M){K("vm_hands.bind_refused",{code:M instanceof W?M.code:"unexpected"}),await q("failed",{error_code:M instanceof W?M.code:"vm_hands_bind_failed"});return}finally{Z.bindsStarting--}let P={...F.ready_data??J.readyData({launchId:F.launch_id,claim:$})};if(Y)delete P.environment_installed;let D=!Y&&F.snapshot_revision!==null&&F.snapshot_id!==null?{environment_installed:{snapshot_id:F.snapshot_id,installed_revision:F.snapshot_revision}}:{};p.set($.attempt_id,{claim:$,launchId:F.launch_id,readyData:P,eventSeq:U.eventSeq,ackSeq:-1});let x=await C("hands.ready",{...P,...D,vm_hands:{layout:F.layout,policy_digest:F.policy_digest,launch_id:F.launch_id}});if(p.delete($.attempt_id),x.status>=300){await hJ(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await q("failed",{error_code:OJ(x.json?.error,"vm_hands_probe_failed")});return}let O={claim:$,launchId:F.launch_id,readyData:P,eventSeq:U.eventSeq,ackSeq:-1};Z.turns.set($.attempt_id,O),O.flush=()=>FJ(O),J.onTurn?.($.attempt_id,gJ(O)),await WJ(O)}async function WJ($){let{fence:Q,op:G}=w($),X=null,U=null,q=J.agent.executorExited($.claim.attempt_id).then((C)=>{return U=C,null});J:for(;;){let C=await Promise.race([q,g(`/operations/${G}/heartbeat`,{...Q,control_ack_seq:$.ackSeq,wait_ms:iJ})]);if(!C){X="vm_hands_executor_exited",K("vm_hands.executor_exited",{reason:U});break}if(C.status>=300)break;let Y=(C.json?.controls??[]).slice().sort((F,P)=>F.seq-P.seq);for(let F of Y){if(F.seq<=$.ackSeq)continue;if(F.kind==="operation.cancel"||F.kind==="cancel"){$.ackSeq=F.seq;break J}if(F.kind===TJ)try{await yJ($,F.payload??{})}catch(P){if(P instanceof k)throw P;X=P instanceof W?P.code:"environment_unavailable";let D=P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(P.code)?P.code:null;K("vm_hands.environment_refused",{code:X,cause:D});break J}$.ackSeq=F.seq}}await vJ($,X)}async function VJ($){let Q=$,G={claim:Q,eventSeq:0},{complete:X,emit:U,fence:q,op:C}={...w(G)},Y=$.vm_hands_origin==="person"?"person":"model",F=String($.capability??"");if(!J.executeOp){await X("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(u&&Z.attest==="pending")){Z.attest="accepted";for(let A of Z.attestWaiters.splice(0))A(!0)}if(Z.attest!=="accepted"){let A=Date.parse(String($.lease_until??""))-Date.now()-5000,h=Z.attest==="refused"?0:Math.max(0,Math.min(s,Number.isFinite(A)?A:s));if(!(h>0&&await new Promise((jJ)=>{let IJ=setTimeout(()=>jJ(!1),h);Z.attestWaiters.push((RJ)=>{clearTimeout(IJ),jJ(RJ)})}))){await X("failed",{error_code:"vm_hands_unattested"});return}}let P=J.agent.bindIdForRun(Q.run_id);if(Y==="model"&&P===null){await X("failed",{error_code:"vm_hands_not_bound"});return}let D=F==="pty.start"&&Y==="person"&&!$.authority;if(D&&(J.agent.liveBindIds.length>0||Z.bindsStarting>0)){await X("failed",{error_code:"vm_hands_bound"});return}if(EJ.has(F)&&!D&&J.agent.liveBindIds.length===0){await X("failed",{error_code:"vm_hands_not_bound"});return}if(Y==="model"&&P||EJ.has(F)&&!D)J.agent.opServed();let x=new AbortController;e.add(x);let O,M=new Promise((A)=>{O=A}),V={abort:x,settled:M};if(D)Z.personTerminals.add(V);if(Y==="model"&&P){let A=Z.modelOps.get(P)??new Set;A.add(V),Z.modelOps.set(P,A),await J.agent.environmentInstalled(P,aJ,x.signal)}let o=-1,d=setInterval(()=>{g(`/operations/${C}/heartbeat`,{...q,control_ack_seq:o,wait_ms:0}).then((A)=>{if(A.status>=300){x.abort();return}let h=A.json?.controls??[];for(let S of h)if(o=Math.max(o,S.seq),S.kind==="operation.cancel"||S.kind==="cancel")x.abort()},()=>x.abort())},sJ);try{let A=await J.executeOp({kind:Y,claim:$,...Y==="model"&&P?{bindId:P}:{},signal:x.signal,emit:async(S)=>{await U(S.kind,S.data??{})}}),h=await X(A.status,{...A.result?{result:A.result}:{},...A.error_code?{error_code:OJ(A.error_code,"vm_hands_op_failed")}:{}});K("vm_hands.op",{capability:F,kind:Y,status:A.status,code:A.error_code??null,...h.status>=300?{complete_status:h.status,complete_error:String(h.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(d),e.delete(x),P)Z.modelOps.get(P)?.delete(V);Z.personTerminals.delete(V),O()}}async function vJ($,Q){let G=$.claim.attempt_id;if(Z.turns.get(G)===$)Z.turns.delete(G);J.onTurn?.(G,null),a($);let X=await m(Z,J.agent,G);Z.receipts.push({turn:$,failure:Q,unbound:X}),await $J()}function $J(){return ZJ=ZJ.then(PJ,PJ),ZJ}async function PJ(){while(Z.receipts.length){let{turn:$,failure:Q,unbound:G}=Z.receipts[0],{complete:X,emit:U}=w($);try{if(await U("hands.stopped",{...$.readyData,reason_code:Q?"failed":"cancelled",killed_verified:G.killed_verified,shredded:G.shredded,...G.srt_fallbacks?{vm_hands_srt_fallbacks:G.srt_fallbacks}:{}}),Q)await X("failed",{error_code:Q});else await X("cancelled",{error_code:"driver_stopped"})}catch(q){if(q instanceof k)return}Z.receipts.shift()}}async function yJ($,Q){let{fence:G,op:X}=w($),U=Q.snapshot_id;if(Q.version!==1||typeof U!=="string"||Object.keys(Q).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let q=await g(`/operations/${X}/environment`,{...G,snapshot_id:U}),C=q.json?.environment_sealed;if(q.status!==200||!C||q.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let Y=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:U,deviceId:Z.deviceId??"",sealed:C});if((await g(`/operations/${X}/environment-ack`,{...G,...Y})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{QZ as xa,lJ as ya,BZ as za};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Wj as l}from"./vm-hands-entry-lite-ygx9kj92.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
2
+ import{Xj as l}from"./vm-hands-entry-lite-kxtjkzzh.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);X>=0;X=B.indexOf(`
110
110
  `)){let S=B.slice(0,X);if(B=B.slice(X+1),!S.startsWith("c "))continue;let O=S.slice(2);if(O.length>Math.ceil(Y/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(O)){K({reason:"display_protocol"});return}let _=Buffer.from(O,"base64");if(_.byteLength<=Y)q.clipboard(_.toString("utf8"));if(z)return}if(B.length>Math.ceil(Y/3)*4+2)K({reason:"display_protocol"})}),G.once("error",()=>W("Reason could not watch this Mac's desktop clipboard.")),G.once("exit",()=>{if(!z)W("Reason could not watch this Mac's desktop clipboard.")})};return J.stdout.on("data",(B)=>{if(z||Z===null)return;Z+=B.toString("utf8");let N=Z.indexOf(`
111
111
  `);if(N<0){if(Z.length>4096)K({reason:"display_protocol"});return}let X=y(Z.slice(0,N));if(Z=null,!X)K({reason:"display_protocol"});else if(!X.screen||!X.accessibility)W(j.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else i(),q.ready({width:X.width,height:X.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>W("Reason could not start this Mac's desktop input.")),J.once("exit",()=>{if(Z!==null)W("Reason could not start this Mac's desktop input.");else K({reason:"display_closed"})}),{pointer:(B,N,X)=>L(Q.pointer(B,N,X)),key:(B,N)=>L(Q.key(B,N)),clipboard:(B)=>L([`c ${Buffer.from(B,"utf8").toString("base64")}`]),close(){z=!0,F()}}}
112
- export{Cj as uj,kj as vj,h as wj,Yj as xj,Y as yj,Lj as zj,Aj,s as Bj,xj as Cj,Mj as Dj,fj as Ej,hj as Fj,$j as Gj,y as Hj,Sj as Ij,_j as Jj,Hj as Kj,Tj as Lj,a as Mj,Vj as Nj};
112
+ export{Cj as vj,kj as wj,h as xj,Yj as yj,Y as zj,Lj as Aj,Aj as Bj,s as Cj,xj as Dj,Mj as Ej,fj as Fj,hj as Gj,$j as Hj,y as Ij,Sj as Jj,_j as Kj,Hj as Lj,Tj as Mj,a as Nj,Vj as Oj};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Yh as A,Zh as w,_h as c,hi as x}from"./vm-hands-entry-lite-5kgvss4p.js";import{ni as l}from"./vm-hands-entry-lite-r6pap1kh.js";import{randomUUID as y}from"crypto";import{chmodSync as o,existsSync as u,mkdirSync as jJ,readlinkSync as YJ,readFileSync as GJ,renameSync as OJ,unlinkSync as VJ,writeFileSync as FJ}from"fs";import{homedir as m}from"os";import{basename as P,dirname as H,isAbsolute as d,join as I,normalize as p,relative as HJ,resolve as LJ}from"path";import{unlinkSync as WJ}from"fs";import{dirname as XJ,join as ZJ}from"path";function $J(J){return ZJ(XJ(J),"future-device-grant.json")}function s(J){try{WJ($J(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var N=3,NJ=1,TJ=2,K=1,n=1,a="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",b="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",zJ=[b,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function r(J){return typeof J==="string"&&zJ.includes(J)}var BJ=["future_device","updates_only","cli_only"];function v(J){return typeof J==="string"&&BJ.some((Q)=>Q===J)}function SJ(J=process.env,Q=m()){return J.XDG_CONFIG_HOME?.trim()||I(Q,".config")}function D(J=process.env,Q=m()){let U=w({env:J}),W=SJ(J,Q);return I(W,x(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function Y(J){return typeof J==="string"&&J.trim().length>0}var _J=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function IJ(J){return typeof J==="string"&&_J.test(J)}function C(J){return Y(J)&&d(J)&&p(J)===J}function i(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return C(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&C(Q.target))}function h(J){return J.owned_paths?.every((Q)=>Q.role!=="alias"||J.installer==="shell"&&Q.path===I(J.install_dir,J.channel==="staging"?"reason-staging":"reason")&&Q.target===I(J.install_dir,J.channel==="staging"?"ara-staging":"ara")&&J.owned_paths?.some((U)=>U.role==="launcher"&&U.path===Q.target))??!1}function t(J,Q){try{return LJ(H(J),YJ(J))===Q}catch{return!1}}function vJ(J){let Q=P(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=I(H(J),U);return t(W,J)?W:J}function M(J,Q){let U=HJ(J,Q);return U.length>0&&!U.startsWith("..")&&!d(U)}function e(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return Q.kind==="shell_profile"&&Y(Q.location)&&Y(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function JJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==K||!Y(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&r(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function AJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==NJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"||!Y(Q.installed_at)||!Y(Q.version)||!Y(Q.target)||!C(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(i)||!Q.owned_paths.every((U)=>M(Q.install_dir,U.path))||!h(Q)||!e(Q.path_entry))return null;return{...Q,schema_version:N,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==TJ||!QJ(Q)||!v(Q.background_mode)||!JJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:N,installation_id:null}}function QJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&J.installer==="shell"||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&Y(J.installed_at)&&Y(J.version)&&Y(J.target)&&C(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(i)&&J.owned_paths.every((Q)=>M(J.install_dir,Q.path))&&h(J)&&e(J.path_entry)}function DJ(J){let Q=AJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==N||!IJ(W.installation_id)||!QJ(W)||!v(W.background_mode)||!JJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==n||W.desktop_account_access.scope!==a||!Y(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function E(J=D()){if(!u(J))return null;try{return DJ(JSON.parse(GJ(J,"utf8")))}catch{return null}}function f(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===K&&J.device_consent.decision==="authorized"&&r(J.device_consent.scope))}function g(J,Q){let U=E(Q);if(!(f(U)&&f(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))s(Q);jJ(H(Q),{recursive:!0,mode:448}),o(H(Q),448);let X=`${Q}.${process.pid}.${y()}.tmp`;try{FJ(X,`${JSON.stringify(J,null,2)}
2
+ import{$h as c,Zh as A,_h as w,ii as x}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as l}from"./vm-hands-entry-lite-4xfs7y6w.js";import{randomUUID as y}from"crypto";import{chmodSync as o,existsSync as u,mkdirSync as jJ,readlinkSync as YJ,readFileSync as GJ,renameSync as OJ,unlinkSync as VJ,writeFileSync as FJ}from"fs";import{homedir as m}from"os";import{basename as P,dirname as H,isAbsolute as d,join as I,normalize as p,relative as HJ,resolve as LJ}from"path";import{unlinkSync as WJ}from"fs";import{dirname as XJ,join as ZJ}from"path";function $J(J){return ZJ(XJ(J),"future-device-grant.json")}function s(J){try{WJ($J(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var N=3,NJ=1,TJ=2,K=1,n=1,a="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",b="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",zJ=[b,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function r(J){return typeof J==="string"&&zJ.includes(J)}var BJ=["future_device","updates_only","cli_only"];function v(J){return typeof J==="string"&&BJ.some((Q)=>Q===J)}function SJ(J=process.env,Q=m()){return J.XDG_CONFIG_HOME?.trim()||I(Q,".config")}function D(J=process.env,Q=m()){let U=w({env:J}),W=SJ(J,Q);return I(W,x(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function Y(J){return typeof J==="string"&&J.trim().length>0}var _J=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function IJ(J){return typeof J==="string"&&_J.test(J)}function C(J){return Y(J)&&d(J)&&p(J)===J}function i(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return C(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&C(Q.target))}function h(J){return J.owned_paths?.every((Q)=>Q.role!=="alias"||J.installer==="shell"&&Q.path===I(J.install_dir,J.channel==="staging"?"reason-staging":"reason")&&Q.target===I(J.install_dir,J.channel==="staging"?"ara-staging":"ara")&&J.owned_paths?.some((U)=>U.role==="launcher"&&U.path===Q.target))??!1}function t(J,Q){try{return LJ(H(J),YJ(J))===Q}catch{return!1}}function vJ(J){let Q=P(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=I(H(J),U);return t(W,J)?W:J}function M(J,Q){let U=HJ(J,Q);return U.length>0&&!U.startsWith("..")&&!d(U)}function e(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return Q.kind==="shell_profile"&&Y(Q.location)&&Y(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function JJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==K||!Y(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&r(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function AJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==NJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"||!Y(Q.installed_at)||!Y(Q.version)||!Y(Q.target)||!C(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(i)||!Q.owned_paths.every((U)=>M(Q.install_dir,U.path))||!h(Q)||!e(Q.path_entry))return null;return{...Q,schema_version:N,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==TJ||!QJ(Q)||!v(Q.background_mode)||!JJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:N,installation_id:null}}function QJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&J.installer==="shell"||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&Y(J.installed_at)&&Y(J.version)&&Y(J.target)&&C(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(i)&&J.owned_paths.every((Q)=>M(J.install_dir,Q.path))&&h(J)&&e(J.path_entry)}function DJ(J){let Q=AJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==N||!IJ(W.installation_id)||!QJ(W)||!v(W.background_mode)||!JJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==n||W.desktop_account_access.scope!==a||!Y(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function E(J=D()){if(!u(J))return null;try{return DJ(JSON.parse(GJ(J,"utf8")))}catch{return null}}function f(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===K&&J.device_consent.decision==="authorized"&&r(J.device_consent.scope))}function g(J,Q){let U=E(Q);if(!(f(U)&&f(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))s(Q);jJ(H(Q),{recursive:!0,mode:448}),o(H(Q),448);let X=`${Q}.${process.pid}.${y()}.tmp`;try{FJ(X,`${JSON.stringify(J,null,2)}
3
3
  `,{mode:384,flag:"wx"}),o(X,384),OJ(X,Q)}finally{if(u(X))VJ(X)}let j=H(Q),$=P(j)==="staging"?H(j):j;if(P($)==="reason")x(H($));return J}function RJ(J=D(),Q=new Date){let U=E(J);if(!U?.installation_id)throw Error("Reason installation ownership is missing; reinstall the current CLI before enabling Device execution");if(f(U))return U;let W={...U,background_mode:"future_device",device_consent:{version:K,decision:"authorized",scope:b,recorded_at:Q.toISOString()}};return delete W.desktop_account_access,g(W,J)}function hJ(J,Q=D(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=S(J.installDir,"install directory"),X=E(Q);if(X?.installation_id&&!J.accountAccess)return RJ(Q,U);return g({...X??{schema_version:N,channel:J.channel,install_method:"desktop",installer:"desktop",installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:[],path_entry:null},schema_version:N,installation_id:X?.installation_id??y(),background_mode:"future_device",...J.accountAccess?{desktop_account_access:{version:n,scope:a,recorded_at:U.toISOString()}}:{},device_consent:{version:K,decision:"authorized",scope:b,recorded_at:U.toISOString()}},Q)}function qJ(J,Q){return J.kind===Q.kind&&J.location===Q.location&&J.value===Q.value}function S(J,Q){let U=p(J);if(!d(U))throw Error(`${Q} must be an absolute path`);return U}function CJ(J,Q=D(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=S(J.install_dir,"install directory"),X=E(Q),j=J.backgroundMode??"preserve",$=j==="preserve"?X?.background_mode??"cli_only":j,T=X?.channel===J.channel&&f(X)&&$==="future_device",z=j==="preserve"&&!X||X?.channel===J.channel&&(j==="preserve"||T),O={path:S(J.launcherPath,"launcher path"),kind:J.launcherKind,role:"launcher"};if(!M(W,O.path))throw Error("launcher path must be inside the install directory");let V=J.workerRoot?S(J.workerRoot,"worker root"):null;if(V&&!M(W,V))throw Error("worker root must be inside the install directory");let B=[];if(J.aliasPath){let F={path:S(J.aliasPath,"alias path"),kind:"symlink",role:"alias",target:O.path};if(!h({installer:J.installer,channel:J.channel,install_dir:W,owned_paths:[O,F]})||!t(F.path,F.target))throw Error("alias must be the channel's symlink to its canonical launcher");B.push(F)}let R=[...X?.channel===J.channel&&X.install_dir===W?X.owned_paths:[],O,...B,...V?[{path:V,kind:"directory",role:"worker_root"}]:[]],k=Array.from(new Map(R.map((F)=>[F.path,F])).values()),Z=J.pathEntry??null,L=Z?X?.path_entry&&qJ(Z,X.path_entry)?{...Z,added_by_installer:q(Z)||q(X.path_entry),added_by_ara:q(Z)||q(X.path_entry)}:Z:X?.path_entry??null,UJ={schema_version:N,installation_id:X?.installation_id??y(),channel:J.channel,install_method:"curl",installer:J.installer,installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:k,path_entry:L,background_mode:$,device_consent:z?X?.device_consent??null:{version:K,decision:$==="future_device"?"authorized":$==="updates_only"?"ask":"disabled",scope:$==="future_device"?b:null,recorded_at:U.toISOString()},...T&&X.desktop_account_access?{desktop_account_access:X.desktop_account_access}:{}};return g(UJ,Q)}function _(J,Q){let U=J.indexOf(Q);if(U===-1)return;let W=J[U+1];if(!W||W.startsWith("--"))throw Error(`${Q} needs a value`);return W}function G(J,Q){let U=_(J,Q);if(!U)throw Error(`${Q} is required`);return U}function gJ(J,Q={}){let U=Q.io??{stdout:process.stdout,stderr:process.stderr};try{let W=new Set(["--channel","--installer","--version","--target","--install-dir","--launcher-path","--launcher-kind","--worker-root","--path-kind","--path-location","--path-value","--background-mode"]);for(let Z=0;Z<J.length;Z+=1){let L=J[Z];if(L==="--path-added")continue;if(!W.has(L))throw Error(`unknown option: ${L}`);if(Z+=1,Z>=J.length)throw Error(`${L} needs a value`)}let X=Q.env??process.env,j=G(J,"--channel"),$=w({env:X,executablePath:Q.executablePath});if(j!==$)throw Error(`installer channel ${j} does not match running ${$} CLI`);let T=G(J,"--installer");if(T!=="shell")throw Error("--installer must be shell");let z=G(J,"--launcher-kind");if(z!=="file"&&z!=="symlink")throw Error("--launcher-kind must be file or symlink");let O=_(J,"--path-kind"),V=null;if(O){if(O!=="shell_profile")throw Error("--path-kind must be shell_profile");V={kind:O,location:G(J,"--path-location"),value:G(J,"--path-value"),added_by_installer:J.includes("--path-added"),added_by_ara:J.includes("--path-added")}}else if(J.includes("--path-location")||J.includes("--path-value")||J.includes("--path-added"))throw Error("path entry flags require --path-kind");let B={channel:$,install_method:"curl",installer:T,version:G(J,"--version"),target:G(J,"--target"),install_dir:G(J,"--install-dir"),launcherPath:G(J,"--launcher-path"),launcherKind:z,..._(J,"--worker-root")?{workerRoot:_(J,"--worker-root")}:{},pathEntry:V,backgroundMode:(()=>{let Z=_(J,"--background-mode")??"preserve";if(Z!=="preserve"&&!v(Z))throw Error("--background-mode must be future_device, updates_only, cli_only, or preserve");return Z})()},R=l(X,"REASON_INSTALL_ALIAS_PATH");if(R)B.aliasPath=R;let k=D(c(X,$),Q.home??m());return(Q.writeReceipt??CJ)(B,k,Q.now?.()??new Date),0}catch(W){return U.stderr.write(`Reason installer receipt: ${W instanceof Error?W.message:String(W)}
4
4
  `),1}}
5
- export{N as Xd,K as Yd,n as Zd,a as _d,b as $d,BJ as ae,SJ as be,D as ce,t as de,vJ as ee,q as fe,DJ as ge,E as he,f as ie,RJ as je,hJ as ke,CJ as le,gJ as me};
5
+ export{N as Yd,K as Zd,n as _d,a as $d,b as ae,BJ as be,SJ as ce,D as de,t as ee,vJ as fe,q as ge,DJ as he,E as ie,f as je,RJ as ke,hJ as le,CJ as me,gJ as ne};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Ac as R}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Yc as D}from"./vm-hands-entry-lite-wej1p1ry.js";import{Wj as $}from"./vm-hands-entry-lite-ygx9kj92.js";import{spawn as i,spawnSync as n}from"child_process";import{existsSync as I,mkdtempSync as E,readFileSync as O,readdirSync as t,realpathSync as r,rmSync as y,statSync as o}from"fs";import{platform as b,tmpdir as h}from"os";import{dirname as N,join as Y}from"path";import{fileURLToPath as e,pathToFileURL as M}from"url";var jj=["bwrap","socat","rg"],qj=2000,_=20000,zj=3,S=4000,Gj=new Set([".git",".hg",".svn","node_modules"]),Hj=["runAsHostUid","sysrq-trigger"],Jj=Y(N(N(e(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),l=!1;function Cj(){l=!0}async function g(){let q=l?Y(N(r(process.execPath)),"runtime","srt"):void 0;if(q&&process.platform==="linux"&&!I(Y(q,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(q){let H=O(Y(q,"sandbox-runtime.mjs"),"utf8");for(let W of Hj)if(!H.includes(W))throw Error(`packaged_sandbox_runtime_fork_missing:${W}`)}let G=(await import(q?M(Y(q,"sandbox-runtime.mjs")).href:M(Jj).href)).SandboxManager;if(!G||typeof G.initialize!=="function"||typeof G.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:G}}function Qj(j={}){if((j.platformName??b())!=="linux")return!1;let z=j.fileExists??I,J=j.readFile??((G)=>O(G,"utf8"));for(let G of["/.dockerenv","/run/.containerenv"])try{if(z(G))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(J("/proc/1/cgroup"))}catch{return!1}}function u(j){return["/bin/true","/usr/bin/true"].find((q)=>j(q))??null}function Vj(j,q){return j==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",q]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",q]}function Wj(j,q){try{let z=n("bwrap",Vj(j,q),{stdio:"ignore",timeout:qj});return!z.error&&z.status===0}catch{return!1}}function Yj(j){let q=j.platformName??b();if(q!=="linux")return null;let z=j.hasExecutable??D;if(!jj.every((Q)=>z(Q)))return null;let J=j.fileExists??I,G=u(J);if(!G)return null;let H=B??(j.containerized??Qj({platformName:q})?"weak":"strict");return(j.probeNamespaces??((Q)=>Wj(Q,G)))(H)?H:null}var L=null,w=!1,k=null,T=null,f=null,B=null,U=null;function A(){throw F("sandbox_mode_conflict"),new $("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function Mj(j){if(B!==null&&B!==j||w&&L!==null&&L!==j||U!==null&&U!==j)A();B=j}function F(j){k=j}function c(j){if(k)return!1;if(!w){if(L=Yj(j??{}),w=!0,L&&!j)d()}return L!==null}function Zj(){return c()?L:null}var X=null,C=0;function m(j){if(k)throw new $("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&j.sandboxMode&&B!==j.sandboxMode)A();let q=B??j.sandboxMode??Zj();if(!q)throw new $("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(U&&U!==q)A();return U=q,X??=(async()=>{let{SandboxManager:z}=await(j.loadSandboxRuntime??g)();return await z.initialize(Kj(q)),z})().catch((z)=>{throw X=null,F(`initialize_failed: ${String(z)}`),z instanceof $?z:new $("sandbox_unavailable","The confined execution sandbox failed to start.")}),X.then((z)=>{if(k)throw new $("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return z})}async function $j(){let j=X;if(X=null,!j)return;try{await(await j).reset()}catch{}}async function d(j={}){if(k)return!1;if(j.loadSandboxRuntime)return P(j.loadSandboxRuntime);if(!c())return!1;return T??=P(g),T}async function P(j){try{let{SandboxManager:q}=await j(),z=q.checkDependencies().errors;if(z.length>0)return F(`dependencies_missing: ${z.join(", ")}`),!1;return!k}catch(q){return F(`load_failed: ${String(q)}`),!1}}async function _j(j={}){if(!j.loadSandboxRuntime&&!j.sandboxMode){if(!await d())return!1;return f??=x({}),f}return x(j)}async function x(j){let q;try{q=await m(j)}catch{return!1}let z=await Bj(q);if(!z)F("confined_command_failed");if(C===0)await $j();return z}async function Bj(j){let q=u(I);if(!q)return!1;let z=E(Y(h(),"reason-device-probe-"));try{let{argv:J}=await j.wrapWithSandboxArgv(s([q]),p(),{filesystem:a({root:z,allowWrite:!1,temporaryDirectory:z,protectedPaths:[]})},void 0,z),[G,...H]=J;if(!G)return!1;return await Lj(G,H,z)}catch{return!1}finally{try{j.cleanupAfterCommand()}catch{}y(z,{recursive:!0,force:!0})}}function Lj(j,q,z,J={}){return new Promise((G)=>{let H=!1,W,Q=(K)=>{if(H)return;H=!0,clearTimeout(W),G(K)},V;try{V=(J.spawnChild??i)(j,q,{cwd:z,env:{PATH:R,HOME:z,TMPDIR:z},stdio:"ignore"})}catch{Q(!1);return}V.once("error",()=>Q(!1));let Z=(K,v)=>Q(K===0&&v===null);if(V.once("exit",Z),V.once("close",Z),V.exitCode!==null||V.signalCode!==null)Z(V.exitCode,V.signalCode);if(H)return;W=setTimeout(()=>{Q(!1);try{V.kill("SIGKILL")}catch{}},Math.min(J.timeoutMs??_,_))})}function p(j=I){return["/bin/bash","/bin/sh"].find((q)=>j(q))??"/bin/sh"}function s(j){return j.map((q)=>`'${q.replaceAll("'","'\\''")}'`).join(" ")}function kj(j,q,z=(J)=>t(J,{withFileTypes:!0}).filter((G)=>G.isDirectory()||G.isFile()).map((G)=>G.name)){let J=[],G=[{path:j,depth:0}],H=0;while(G.length>0&&H<S){let W=G.pop(),Q;try{Q=z(W.path)}catch{continue}for(let V of Q){if(H+=1,H>S)break;let Z=Y(W.path,V);if(q(Z)){J.push(Z);continue}if(W.depth+1<zj&&!Gj.has(V))G.push({path:Z,depth:W.depth+1})}}return J}function a(j){let q=Y(j.root,".git"),z=[];try{if(o(q).isDirectory())z=[Y(q,"config"),Y(q,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...j.protectedPaths],allowRead:[j.root,j.temporaryDirectory],allowWrite:[...j.allowWrite?[j.root]:[],j.temporaryDirectory],denyWrite:[...j.protectedPaths,...z]}}function Kj(j){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...j==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Sj(j){let q=j.createTemporaryDirectory??(()=>E(Y(h(),"reason-device-"))),z=j.removeTemporaryDirectory??((J)=>y(J,{recursive:!0,force:!0}));return async(J,G,H)=>{let W=await m(j),Q=q();C+=1;try{let V;try{V=await W.wrapWithSandboxArgv(s([J,...G]),j.shell??p(),{filesystem:a({root:H.root,allowWrite:H.allowWrite,temporaryDirectory:Q,protectedPaths:kj(H.root,j.isProtectedPath)})},H.signal,H.cwd)}catch(v){throw v instanceof $?v:new $("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[Z,...K]=V.argv;if(!Z)throw new $("sandbox_unavailable","The confined execution sandbox produced no command.");return await j.spawnCaptured(Z,K,{cwd:H.cwd,timeoutMs:H.timeoutMs,signal:H.signal,env:j.scrubEnvironment(H.root,Q)})}finally{C-=1;try{W.cleanupAfterCommand()}catch{}z(Q)}}}
2
+ import{Ac as R}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Yc as D}from"./vm-hands-entry-lite-wej1p1ry.js";import{Xj as $}from"./vm-hands-entry-lite-kxtjkzzh.js";import{spawn as i,spawnSync as n}from"child_process";import{existsSync as I,mkdtempSync as E,readFileSync as O,readdirSync as t,realpathSync as r,rmSync as y,statSync as o}from"fs";import{platform as b,tmpdir as h}from"os";import{dirname as N,join as Y}from"path";import{fileURLToPath as e,pathToFileURL as M}from"url";var jj=["bwrap","socat","rg"],qj=2000,_=20000,zj=3,S=4000,Gj=new Set([".git",".hg",".svn","node_modules"]),Hj=["runAsHostUid","sysrq-trigger"],Jj=Y(N(N(e(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),l=!1;function Cj(){l=!0}async function g(){let q=l?Y(N(r(process.execPath)),"runtime","srt"):void 0;if(q&&process.platform==="linux"&&!I(Y(q,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(q){let H=O(Y(q,"sandbox-runtime.mjs"),"utf8");for(let W of Hj)if(!H.includes(W))throw Error(`packaged_sandbox_runtime_fork_missing:${W}`)}let G=(await import(q?M(Y(q,"sandbox-runtime.mjs")).href:M(Jj).href)).SandboxManager;if(!G||typeof G.initialize!=="function"||typeof G.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:G}}function Qj(j={}){if((j.platformName??b())!=="linux")return!1;let z=j.fileExists??I,J=j.readFile??((G)=>O(G,"utf8"));for(let G of["/.dockerenv","/run/.containerenv"])try{if(z(G))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(J("/proc/1/cgroup"))}catch{return!1}}function u(j){return["/bin/true","/usr/bin/true"].find((q)=>j(q))??null}function Vj(j,q){return j==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",q]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",q]}function Wj(j,q){try{let z=n("bwrap",Vj(j,q),{stdio:"ignore",timeout:qj});return!z.error&&z.status===0}catch{return!1}}function Yj(j){let q=j.platformName??b();if(q!=="linux")return null;let z=j.hasExecutable??D;if(!jj.every((Q)=>z(Q)))return null;let J=j.fileExists??I,G=u(J);if(!G)return null;let H=B??(j.containerized??Qj({platformName:q})?"weak":"strict");return(j.probeNamespaces??((Q)=>Wj(Q,G)))(H)?H:null}var L=null,w=!1,k=null,T=null,f=null,B=null,U=null;function A(){throw F("sandbox_mode_conflict"),new $("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function Mj(j){if(B!==null&&B!==j||w&&L!==null&&L!==j||U!==null&&U!==j)A();B=j}function F(j){k=j}function c(j){if(k)return!1;if(!w){if(L=Yj(j??{}),w=!0,L&&!j)d()}return L!==null}function Zj(){return c()?L:null}var X=null,C=0;function m(j){if(k)throw new $("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&j.sandboxMode&&B!==j.sandboxMode)A();let q=B??j.sandboxMode??Zj();if(!q)throw new $("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(U&&U!==q)A();return U=q,X??=(async()=>{let{SandboxManager:z}=await(j.loadSandboxRuntime??g)();return await z.initialize(Kj(q)),z})().catch((z)=>{throw X=null,F(`initialize_failed: ${String(z)}`),z instanceof $?z:new $("sandbox_unavailable","The confined execution sandbox failed to start.")}),X.then((z)=>{if(k)throw new $("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return z})}async function $j(){let j=X;if(X=null,!j)return;try{await(await j).reset()}catch{}}async function d(j={}){if(k)return!1;if(j.loadSandboxRuntime)return P(j.loadSandboxRuntime);if(!c())return!1;return T??=P(g),T}async function P(j){try{let{SandboxManager:q}=await j(),z=q.checkDependencies().errors;if(z.length>0)return F(`dependencies_missing: ${z.join(", ")}`),!1;return!k}catch(q){return F(`load_failed: ${String(q)}`),!1}}async function _j(j={}){if(!j.loadSandboxRuntime&&!j.sandboxMode){if(!await d())return!1;return f??=x({}),f}return x(j)}async function x(j){let q;try{q=await m(j)}catch{return!1}let z=await Bj(q);if(!z)F("confined_command_failed");if(C===0)await $j();return z}async function Bj(j){let q=u(I);if(!q)return!1;let z=E(Y(h(),"reason-device-probe-"));try{let{argv:J}=await j.wrapWithSandboxArgv(s([q]),p(),{filesystem:a({root:z,allowWrite:!1,temporaryDirectory:z,protectedPaths:[]})},void 0,z),[G,...H]=J;if(!G)return!1;return await Lj(G,H,z)}catch{return!1}finally{try{j.cleanupAfterCommand()}catch{}y(z,{recursive:!0,force:!0})}}function Lj(j,q,z,J={}){return new Promise((G)=>{let H=!1,W,Q=(K)=>{if(H)return;H=!0,clearTimeout(W),G(K)},V;try{V=(J.spawnChild??i)(j,q,{cwd:z,env:{PATH:R,HOME:z,TMPDIR:z},stdio:"ignore"})}catch{Q(!1);return}V.once("error",()=>Q(!1));let Z=(K,v)=>Q(K===0&&v===null);if(V.once("exit",Z),V.once("close",Z),V.exitCode!==null||V.signalCode!==null)Z(V.exitCode,V.signalCode);if(H)return;W=setTimeout(()=>{Q(!1);try{V.kill("SIGKILL")}catch{}},Math.min(J.timeoutMs??_,_))})}function p(j=I){return["/bin/bash","/bin/sh"].find((q)=>j(q))??"/bin/sh"}function s(j){return j.map((q)=>`'${q.replaceAll("'","'\\''")}'`).join(" ")}function kj(j,q,z=(J)=>t(J,{withFileTypes:!0}).filter((G)=>G.isDirectory()||G.isFile()).map((G)=>G.name)){let J=[],G=[{path:j,depth:0}],H=0;while(G.length>0&&H<S){let W=G.pop(),Q;try{Q=z(W.path)}catch{continue}for(let V of Q){if(H+=1,H>S)break;let Z=Y(W.path,V);if(q(Z)){J.push(Z);continue}if(W.depth+1<zj&&!Gj.has(V))G.push({path:Z,depth:W.depth+1})}}return J}function a(j){let q=Y(j.root,".git"),z=[];try{if(o(q).isDirectory())z=[Y(q,"config"),Y(q,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...j.protectedPaths],allowRead:[j.root,j.temporaryDirectory],allowWrite:[...j.allowWrite?[j.root]:[],j.temporaryDirectory],denyWrite:[...j.protectedPaths,...z]}}function Kj(j){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...j==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Sj(j){let q=j.createTemporaryDirectory??(()=>E(Y(h(),"reason-device-"))),z=j.removeTemporaryDirectory??((J)=>y(J,{recursive:!0,force:!0}));return async(J,G,H)=>{let W=await m(j),Q=q();C+=1;try{let V;try{V=await W.wrapWithSandboxArgv(s([J,...G]),j.shell??p(),{filesystem:a({root:H.root,allowWrite:H.allowWrite,temporaryDirectory:Q,protectedPaths:kj(H.root,j.isProtectedPath)})},H.signal,H.cwd)}catch(v){throw v instanceof $?v:new $("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[Z,...K]=V.argv;if(!Z)throw new $("sandbox_unavailable","The confined execution sandbox produced no command.");return await j.spawnCaptured(Z,K,{cwd:H.cwd,timeoutMs:H.timeoutMs,signal:H.signal,env:j.scrubEnvironment(H.root,Q)})}finally{C-=1;try{W.cleanupAfterCommand()}catch{}z(Q)}}}
3
3
  export{Cj as uc,Mj as vc,c as wc,_j as xc,p as yc,Sj as zc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var U=".reason/workspace",T="workspace_base",y="sessions",W="workspace_layout",g=".reason/workspace/sessions",B=/^[0-9a-f]{8}$/;function C(j){if(!J(j))return!1;let q=".reason/workspace/sessions/";if(!j.startsWith(q))return!1;let z=j.slice(q.length).split("/");return z.length===2&&B.test(z[0])}var G=4096,X="workspaces/pi";function J(j){if(typeof j!=="string"||!j||j.length>G)return!1;if(j.startsWith("/")||j.includes("\x00")||j.includes("\\"))return!1;return j.split("/").every((q)=>q!==""&&q!=="."&&q!=="..")}function Z(j){if(j.kind==="root"){if(j.path===void 0)return".";if(!J(j.path))throw Error("invalid_device_workspace_identity");return j.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(j.workspaceId)||j.workspaceId==="."||j.workspaceId==="..")throw Error("invalid_device_workspace_identity");let q=j.layout==="sessions"?"sessions":X;return`${j.base?`${j.base}/`:""}${q}/${j.workspaceId}/repo`}function L(j){if(!j||typeof j!=="object"||Array.isArray(j))return null;let q=j;if(q.kind==="root"&&Object.keys(q).length===1)return{kind:"root"};if(q.kind==="root"&&Object.keys(q).length===2&&J(q.path))return{kind:"root",path:q.path};if(q.kind!=="managed"||typeof q.workspaceId!=="string"||Object.keys(q).length!==2+(q.base===void 0?0:1)+(q.layout===void 0?0:1)||q.base!==void 0&&q.base!==".reason/workspace"||q.layout!==void 0&&q.layout!=="sessions")return null;let z={kind:"managed",workspaceId:q.workspaceId,...q.base===".reason/workspace"?{base:".reason/workspace"}:{},...q.layout==="sessions"?{layout:"sessions"}:{}};try{return Z(z),z}catch{return null}}var b="/home/runner",P=10001,x="/run/reason/sessions",f=/^(?:\/[A-Za-z0-9._-]+)+$/,M=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,H=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function K(j){return M.exec(j)?.[1]??H.exec(j)?.[1]??j}var $=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/,A="*/.reason/workspace/workspaces/pi/*|*/.reason/workspace/sessions/*";function N(j,q=b,z="sessions"){if(!f.test(q)||q.split("/").some((V)=>V==="."||V===".."))throw Error("invalid_cloud_payload_home");let Q=`${q}/${Z({kind:"managed",workspaceId:j,base:".reason/workspace",...z?{layout:z}:{}})}`,F=`${x}/${K(j)}`;return{home:q,root:Q.slice(0,-5),checkout:Q,control:F,jobEnv:`${F}/job.env`,cloudAccess:`${F}/cloud-access`,logs:`${F}/logs`,pin:`${F}/ws`}}function Y(j){return $.exec(j.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function D(j){return{kind:"managed",workspaceId:j,layout:"sessions"}}function R(j){let q=$.exec(j.replace(/\/+$/,""));if(!q)return null;try{let z=N(q[3],q[1],Y(j));return z.root===j.replace(/\/+$/,"")?z:null}catch{return null}}
3
- export{U as Wi,T as Xi,y as Yi,W as Zi,g as _i,B as $i,C as aj,J as bj,Z as cj,L as dj,b as ej,P as fj,x as gj,M as hj,H as ij,$ as jj,A as kj,N as lj,Y as mj,D as nj,R as oj};
3
+ export{U as Xi,T as Yi,y as Zi,W as _i,g as $i,B as aj,C as bj,J as cj,Z as dj,L as ej,b as fj,P as gj,x as hj,M as ij,H as jj,$ as kj,A as lj,N as mj,Y as nj,D as oj,R as pj};