@reason-machines/cli-linux-x64 0.2.561 → 0.2.565

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 (129) hide show
  1. package/bin/reason +2 -2
  2. package/bin/vm-hands/agent-network-mnv1fm1c.js +2 -0
  3. package/bin/vm-hands/api-credentials-082cnpn9.js +2 -0
  4. package/bin/vm-hands/api-sq672f51.js +2 -0
  5. package/bin/vm-hands/{ask-relay-xx0rzpch.js → ask-relay-v5btnjvb.js} +2 -2
  6. package/bin/vm-hands/connect-cli-rxb3qtra.js +2 -0
  7. package/bin/vm-hands/credentials-sk4sag42.js +2 -0
  8. package/bin/vm-hands/custom-endpoint-device-3jscber1.js +2 -0
  9. package/bin/vm-hands/desktop-account-xma0330a.js +2 -0
  10. package/bin/vm-hands/desktop-components-099xyxmz.js +2 -0
  11. package/bin/vm-hands/desktop-delegate-tch2qzx0.js +2 -0
  12. package/bin/vm-hands/device-workspace-4bj43nxq.js +2 -0
  13. package/bin/vm-hands/{fsevents-vxv56sp5.js → fsevents-ezcg3e40.js} +1 -1
  14. package/bin/vm-hands/hands-worker-source-8pe7yv0m.js +2 -0
  15. package/bin/vm-hands/{index-03p9c17x.js → index-w92ys6ra.js} +16 -16
  16. package/bin/vm-hands/install-receipt-68xxg7hn.js +2 -0
  17. package/bin/vm-hands/local-automation-7pjd5nc1.js +2 -0
  18. package/bin/vm-hands/local-capabilities-ha0ey4zh.js +2 -0
  19. package/bin/vm-hands/local-desktop-users-jpf0resr.js +2 -0
  20. package/bin/vm-hands/local-display-mac-h5yz0ydd.js +2 -0
  21. package/bin/vm-hands/local-display-session-0mkswxgk.js +2 -0
  22. package/bin/vm-hands/local-display-video-c3fk87c5.js +2 -0
  23. package/bin/vm-hands/local-managed-process-ahr2jync.js +2 -0
  24. package/bin/vm-hands/local-pty-session-tqn2xmph.js +2 -0
  25. package/bin/vm-hands/managed-runtime-shzb3tr3.js +2 -0
  26. package/bin/vm-hands/network-auto-update-3m94436w.js +3 -0
  27. package/bin/vm-hands/network-contract-nkwcf4r9.js +2 -0
  28. package/bin/vm-hands/{network-sign-in-61gmpmaa.js → network-sign-in-xm79s170.js} +2 -2
  29. package/bin/vm-hands/package-9w0mmxb5.js +2 -0
  30. package/bin/vm-hands/permissions-scffy1px.js +2 -0
  31. package/bin/vm-hands/reason-hands-protocol-pck5har9.js +2 -0
  32. package/bin/vm-hands/serve-service-grp91ybk.js +2 -0
  33. package/bin/vm-hands/{status-khqk4cjw.js → status-89999mdn.js} +7 -7
  34. package/bin/vm-hands/version-wyshazh7.js +2 -0
  35. package/bin/vm-hands/{vm-hands-entry-lite-zawytz09.js → vm-hands-entry-lite-12ck5swp.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-j10cw3d9.js → vm-hands-entry-lite-13nx02p7.js} +7 -7
  37. package/bin/vm-hands/{vm-hands-entry-lite-vdv4nm5f.js → vm-hands-entry-lite-1b21avcs.js} +2 -2
  38. package/bin/vm-hands/vm-hands-entry-lite-1eyg750p.js +48 -0
  39. package/bin/vm-hands/{vm-hands-entry-lite-2dak7e1h.js → vm-hands-entry-lite-1xhpn3hw.js} +3 -5
  40. package/bin/vm-hands/{vm-hands-entry-lite-ms99mzp0.js → vm-hands-entry-lite-284z7ct8.js} +3 -3
  41. package/bin/vm-hands/{vm-hands-entry-lite-a7bf7xr7.js → vm-hands-entry-lite-2qfmabqn.js} +3 -3
  42. package/bin/vm-hands/{vm-hands-entry-lite-q9s1e2y1.js → vm-hands-entry-lite-33at6g06.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-jgk5z8zc.js → vm-hands-entry-lite-34b4tws6.js} +6 -6
  44. package/bin/vm-hands/{vm-hands-entry-lite-e3fn8ys2.js → vm-hands-entry-lite-3gc2bn5a.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-hxfxs7r9.js → vm-hands-entry-lite-3q2ng4e9.js} +2 -2
  46. package/bin/vm-hands/vm-hands-entry-lite-432khjd5.js +150 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-6vnjgy77.js +81 -0
  48. package/bin/vm-hands/{vm-hands-entry-lite-ht6hzkgj.js → vm-hands-entry-lite-7r27208j.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-hs6sdn60.js → vm-hands-entry-lite-88dxn9b5.js} +2 -2
  50. package/bin/vm-hands/vm-hands-entry-lite-997y1m1r.js +3 -0
  51. package/bin/vm-hands/{vm-hands-entry-lite-zh6ncdjn.js → vm-hands-entry-lite-a3gq377t.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-m1we91g4.js → vm-hands-entry-lite-af45ma9p.js} +10 -10
  53. package/bin/vm-hands/{vm-hands-entry-lite-0wb1n769.js → vm-hands-entry-lite-b1vanmtv.js} +5 -5
  54. package/bin/vm-hands/{vm-hands-entry-lite-5y4phfv1.js → vm-hands-entry-lite-bsk184m7.js} +3 -3
  55. package/bin/vm-hands/{vm-hands-entry-lite-q9djb28r.js → vm-hands-entry-lite-cc8hwgxc.js} +3 -3
  56. package/bin/vm-hands/vm-hands-entry-lite-chq0qx9f.js +12 -0
  57. package/bin/vm-hands/{vm-hands-entry-lite-84mc1f7h.js → vm-hands-entry-lite-cmmb9k3g.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-gxpw14jv.js → vm-hands-entry-lite-dy204qh4.js} +7 -7
  59. package/bin/vm-hands/{vm-hands-entry-lite-ptycjmkc.js → vm-hands-entry-lite-fccn6s4j.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-qf990rxw.js → vm-hands-entry-lite-fn2805g8.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-71ebge0c.js → vm-hands-entry-lite-fxptf351.js} +5 -5
  62. package/bin/vm-hands/{vm-hands-entry-lite-vkhacd00.js → vm-hands-entry-lite-gcqqnnze.js} +19 -19
  63. package/bin/vm-hands/{vm-hands-entry-lite-57ajjwmh.js → vm-hands-entry-lite-gxf2r5en.js} +1 -1
  64. package/bin/vm-hands/{vm-hands-entry-lite-hjjbjpd7.js → vm-hands-entry-lite-jj7873n8.js} +3 -3
  65. package/bin/vm-hands/{vm-hands-entry-lite-9g52kxyj.js → vm-hands-entry-lite-kbnxk71q.js} +2 -2
  66. package/bin/vm-hands/vm-hands-entry-lite-ncyrz48z.js +4 -0
  67. package/bin/vm-hands/{vm-hands-entry-lite-y3nz20wb.js → vm-hands-entry-lite-ngn4tafr.js} +105 -105
  68. package/bin/vm-hands/{vm-hands-entry-lite-52qz0n30.js → vm-hands-entry-lite-ngry8nkq.js} +4 -4
  69. package/bin/vm-hands/{vm-hands-entry-lite-8xv6c0rm.js → vm-hands-entry-lite-pg7nnyc6.js} +2 -2
  70. package/bin/vm-hands/{vm-hands-entry-lite-h7nk2848.js → vm-hands-entry-lite-pt19vacn.js} +42 -42
  71. package/bin/vm-hands/{vm-hands-entry-lite-tcmye5ny.js → vm-hands-entry-lite-q62g6sx0.js} +2 -2
  72. package/bin/vm-hands/{vm-hands-entry-lite-v4hr9x9h.js → vm-hands-entry-lite-qjrgvdbj.js} +34 -34
  73. package/bin/vm-hands/{vm-hands-entry-lite-bj3w2ven.js → vm-hands-entry-lite-rqfhfp09.js} +2 -2
  74. package/bin/vm-hands/{vm-hands-entry-lite-krpqqx12.js → vm-hands-entry-lite-rxydyqke.js} +2 -2
  75. package/bin/vm-hands/{vm-hands-entry-lite-weqam12f.js → vm-hands-entry-lite-s93f3pbv.js} +3 -3
  76. package/bin/vm-hands/{vm-hands-entry-lite-z0ht62s4.js → vm-hands-entry-lite-sh4mqy93.js} +3 -3
  77. package/bin/vm-hands/{vm-hands-entry-lite-xvccy3z4.js → vm-hands-entry-lite-sz7z1qby.js} +2 -2
  78. package/bin/vm-hands/{vm-hands-entry-lite-wcgm41jq.js → vm-hands-entry-lite-t43bz0ey.js} +7 -7
  79. package/bin/vm-hands/{vm-hands-entry-lite-6jxshhps.js → vm-hands-entry-lite-t86kt9jz.js} +6 -6
  80. package/bin/vm-hands/{vm-hands-entry-lite-7pfhwxn5.js → vm-hands-entry-lite-tnj3483k.js} +1 -1
  81. package/bin/vm-hands/vm-hands-entry-lite-wnqqjsew.js +3 -0
  82. package/bin/vm-hands/{vm-hands-entry-lite-pxtycfdv.js → vm-hands-entry-lite-xfak34av.js} +4 -4
  83. package/bin/vm-hands/{vm-hands-entry-lite-sy7dcccg.js → vm-hands-entry-lite-y0jtj8zz.js} +1 -1
  84. package/bin/vm-hands/{vm-hands-entry-lite-yvws5zpx.js → vm-hands-entry-lite-yg4dk99m.js} +1 -1
  85. package/bin/vm-hands/{vm-hands-entry-lite-2rgf8866.js → vm-hands-entry-lite-z65xva21.js} +2 -2
  86. package/bin/vm-hands/{vm-hands-entry-lite-jpvmkce5.js → vm-hands-entry-lite-zp7chzcc.js} +1 -1
  87. package/bin/vm-hands/{vm-hands-entry-lite-k5ytpgzz.js → vm-hands-entry-lite-zpvr7wc6.js} +19 -19
  88. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  89. package/bin/vm-hands/vm-hands-executor-kyb5t371.js +12 -0
  90. package/bin/vm-hands/vm-hands-op-runner-gkt79hcp.js +2 -0
  91. package/bin/vm-hands/{vm-hands-runtime-1qxf96z7.js → vm-hands-runtime-tdr6j55n.js} +3 -3
  92. package/bin/vm-hands/worker-preview-readiness-h96yr4wf.js +2 -0
  93. package/bin/vm-hands/worker-sandbox-6kkhvryn.js +2 -0
  94. package/package.json +1 -1
  95. package/bin/vm-hands/agent-network-kk36zca7.js +0 -2
  96. package/bin/vm-hands/api-credentials-mtfdk175.js +0 -2
  97. package/bin/vm-hands/api-w6w7vfp3.js +0 -2
  98. package/bin/vm-hands/connect-cli-dmwph620.js +0 -2
  99. package/bin/vm-hands/credentials-s7ps7y6s.js +0 -2
  100. package/bin/vm-hands/custom-endpoint-device-3xnrp33e.js +0 -2
  101. package/bin/vm-hands/desktop-account-eg8thn79.js +0 -2
  102. package/bin/vm-hands/device-workspace-h5rsecq8.js +0 -2
  103. package/bin/vm-hands/hands-worker-source-vk664w8p.js +0 -2
  104. package/bin/vm-hands/install-receipt-j04hdw1k.js +0 -2
  105. package/bin/vm-hands/local-automation-vvt9d9xb.js +0 -2
  106. package/bin/vm-hands/local-capabilities-pwv76ns5.js +0 -2
  107. package/bin/vm-hands/local-desktop-users-sq4trh07.js +0 -2
  108. package/bin/vm-hands/local-display-mac-yxcxvg2z.js +0 -2
  109. package/bin/vm-hands/local-display-session-axh9mfdk.js +0 -2
  110. package/bin/vm-hands/local-display-video-pxhztqk7.js +0 -2
  111. package/bin/vm-hands/local-managed-process-4mgqn7tg.js +0 -2
  112. package/bin/vm-hands/local-pty-session-edd8ttf9.js +0 -2
  113. package/bin/vm-hands/managed-runtime-pcagtyfz.js +0 -2
  114. package/bin/vm-hands/network-auto-update-wkzb91qz.js +0 -3
  115. package/bin/vm-hands/network-contract-8mxtma3w.js +0 -2
  116. package/bin/vm-hands/package-vwvzjtn0.js +0 -2
  117. package/bin/vm-hands/permissions-348prrcx.js +0 -2
  118. package/bin/vm-hands/reason-hands-protocol-1nkpw1v3.js +0 -2
  119. package/bin/vm-hands/serve-service-3dkyznay.js +0 -2
  120. package/bin/vm-hands/version-c1hen0wn.js +0 -2
  121. package/bin/vm-hands/vm-hands-entry-lite-9yfmkd1f.js +0 -3
  122. package/bin/vm-hands/vm-hands-entry-lite-ab1pq3xg.js +0 -3
  123. package/bin/vm-hands/vm-hands-entry-lite-hn9pq7zj.js +0 -127
  124. package/bin/vm-hands/vm-hands-entry-lite-nn6zcvmp.js +0 -3
  125. package/bin/vm-hands/vm-hands-entry-lite-z213y4pj.js +0 -150
  126. package/bin/vm-hands/vm-hands-executor-csdtg7kj.js +0 -12
  127. package/bin/vm-hands/vm-hands-op-runner-z7tsd84c.js +0 -2
  128. package/bin/vm-hands/worker-preview-readiness-06tygyjs.js +0 -2
  129. package/bin/vm-hands/worker-sandbox-e1cpkzfz.js +0 -2
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Rt,Tt}from"./vm-hands-entry-lite-8xv6c0rm.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{request as Ie}from"http";import{pipeline as We}from"stream";import{constants as ne,createBrotliCompress as Re,createGzip as Be}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as Ee,timingSafeEqual as Ae}from"crypto";import{createServer as Te}from"net";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 J(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function fe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function we(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!J(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(fe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function Mt(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function pe(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=v.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function di(e){if(Buffer.byteLength(e)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!J(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,v.chunk,v.upload)?{messages:t.messages}:{},...L(t.window,1,v.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!fe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,v.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&pe(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&pe(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,v.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function re(e){let t=[...e],n=new Set(t.filter(([o])=>o.toLowerCase()==="connection").flatMap(([,o])=>o.toLowerCase().split(",").map((i)=>i.trim()))),s=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 t.filter(([o])=>!s.has(o.toLowerCase())&&!n.has(o.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(o))}async function te(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),v.authorizationMs)})])}finally{clearTimeout(t)}}async function en(e){return await te(e)===!0}function V(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function dr(e){if(!J(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:V(e.deviceRelayUrl,"device")}}function Ya(e){if(!J(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var ge="x-preview-connection";async function be(e,t){if(t.aborted)throw Error("preview_closed");let n=Ee(32).toString("base64url"),s=new Set,o=!1,i=Te((c)=>{if(o||t.aborted||s.size>=v.streams*2)return c.destroy();s.add(c);let d=new AbortController;c.once("close",()=>{s.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let g=Buffer.alloc(0),w=(m)=>{g=Buffer.concat([g,m]);let f=g.indexOf(`\r
2
+ import{Tt,It}from"./vm-hands-entry-lite-pg7nnyc6.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{request as Ie}from"http";import{pipeline as We}from"stream";import{constants as ne,createBrotliCompress as Re,createGzip as Be}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as Ee,timingSafeEqual as Ae}from"crypto";import{createServer as Te}from"net";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 J(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function fe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function we(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!J(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(fe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function Bt(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function pe(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=v.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function mi(e){if(Buffer.byteLength(e)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!J(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,v.chunk,v.upload)?{messages:t.messages}:{},...L(t.window,1,v.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!fe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,v.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&pe(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&pe(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,v.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function re(e){let t=[...e],n=new Set(t.filter(([o])=>o.toLowerCase()==="connection").flatMap(([,o])=>o.toLowerCase().split(",").map((i)=>i.trim()))),s=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 t.filter(([o])=>!s.has(o.toLowerCase())&&!n.has(o.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(o))}async function te(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),v.authorizationMs)})])}finally{clearTimeout(t)}}async function cn(e){return await te(e)===!0}function V(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function pr(e){if(!J(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:V(e.deviceRelayUrl,"device")}}function oc(e){if(!J(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var ge="x-preview-connection";async function be(e,t){if(t.aborted)throw Error("preview_closed");let n=Ee(32).toString("base64url"),s=new Set,o=!1,i=Te((c)=>{if(o||t.aborted||s.size>=v.streams*2)return c.destroy();s.add(c);let d=new AbortController;c.once("close",()=>{s.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let g=Buffer.alloc(0),w=(m)=>{g=Buffer.concat([g,m]);let f=g.indexOf(`\r
3
3
  \r
4
4
  `);if(f<0){if(g.length>16384)c.destroy();return}if(c.pause(),c.off("data",w),f>16384||g.length>v.upload+16384)return c.destroy();u(g,f).catch(()=>c.destroy())};c.on("data",w);async function u(m,f){let b=m.subarray(0,f).toString("latin1").split(`\r
5
5
  `),_=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(b.shift()??"");if(!_)throw Error("preview_request_invalid");H(_[2]);let k=!1,O=0,T=[];for(let B of b){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(B);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===ge){O++;let N=Buffer.from(S[2].trim());k=N.length===n.length&&Ae(N,Buffer.from(n))}else if(S[1].toLowerCase()!=="host")T.push(B)}if(!k||O!==1||o||d.signal.aborted)throw Error("preview_connection_denied");let P=await e.connect(d.signal);if(o||d.signal.aborted)throw P.destroy(),Error("preview_closed");s.add(P),P.on("error",()=>c.destroy()),P.once("close",()=>{s.delete(P),c.destroy()}),c.once("close",()=>P.destroy()),c.setTimeout(0);let h=[`${_[1]} ${_[2]} HTTP/1.1`,`Host: 127.0.0.1:${P.remotePort}`,...T,"",""].join(`\r
6
- `);P.write(Buffer.concat([Buffer.from(h,"latin1"),m.subarray(f+4)])),P.pipe(c),c.pipe(P),c.resume()}});await new Promise((c,d)=>{i.once("error",d),i.listen(0,"127.0.0.1",c)});let a=i.address();if(!a||typeof a==="string")throw i.close(),Error("preview_bind_failed");function l(){if(o)return;o=!0,t.removeEventListener("abort",l);for(let c of s)c.destroy();s.clear(),i.close()}if(t.addEventListener("abort",l,{once:!0}),t.aborted)l();return{port:a.port,headers:{[ge]:n},close:l}}var Le=60000,Ce=1e4,Ne=5000,$e=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function Me(e,t,n,s){let o=(c)=>t.find(([d])=>d.toLowerCase()===c)?.[1],i=(c)=>s.find(([d])=>d.toLowerCase()===c)?.[1],a=Number(i("content-length")??Number.NaN);if(e!=="GET"||n!==200||o("range")!==void 0||i("content-encoding")!==void 0||!$e.test(i("content-type")??"")||/\bno-transform\b/i.test(i("cache-control")??"")||a<1024)return null;let l=(c)=>new RegExp(`(?:^|,)\\s*${c}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test(o("accept-encoding")??"");return l("br")?"br":l("gzip")?"gzip":null}function Oe(e,t){let n=e.filter(([s])=>s.toLowerCase()==="vary").map(([,s])=>s).join(", ");return[...e.filter(([s])=>!["vary","etag","content-md5"].includes(s.toLowerCase())),...e.filter(([s])=>s.toLowerCase()==="etag").map(([s,o])=>[s,o.startsWith("W/")?o:`W/${o}`]),["Content-Encoding",t],["Vary",n.split(",").some((s)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(s))?n:n?`${n}, Accept-Encoding`:"Accept-Encoding"]]}async function Co(e){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:e.jobId,port:e.port,reason_code:e.reason})}
7
- `);let t=e.binding,n;try{n=V(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((s)=>{let o=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{o.terminate(),s()},v.authorizationMs*2);o.addEventListener("open",()=>{o.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),o.close(1000,`worker_refused_${e.reason}`)}),o.addEventListener("error",()=>{clearTimeout(i),s()}),o.addEventListener("close",()=>{clearTimeout(i),s()})})}async function Fe(e,t){let n=Date.now()+Ce,s;for(;;){if(!t())return"closed";let o=s??=e.refusal().finally(()=>{s=void 0}),i,a=await Promise.race([o.catch(()=>"port_unproved"),new Promise((l)=>{i=setTimeout(()=>l("port_check_timeout"),v.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((l)=>setTimeout(l,500))}}async function pt(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,s=t.expiresAtMs>Date.now()+v.lifetimeMs+Ne?"binding_mismatch":await Fe(e.port,n);if(s)throw await Co({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:s}),Error("preview_not_authorized",{cause:s});let o=V(e.deviceRelayUrl,"device"),i=await be(e.port,e.signal),a;try{a=new U(o,{followRedirects:!1,perMessageDeflate:!1,maxPayload:v.upload*1.4+300000})}catch(p){throw i.close(),p}let l=new Map,c=!1,d=!1,g=0,w=!1,u,m,f,b=new Promise((p)=>{f=p}),_,k,O=new Promise((p,y)=>{_=p,k=y}),T=!1,P=(p)=>{let y=Buffer.isBuffer(p)?p:JSON.stringify(p);if(g+=Buffer.byteLength(y),!n()||d||a.readyState!==U.OPEN)return h(n()?"relay_closed":"expired");if(a.bufferedAmount>v.relayBuffered)return h("relay_backlog");if(g>v.total)return h("quota");a.send(y)};function h(p="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let y of l.values())y.stop();l.clear(),i.close(),a.close(1000,`worker_${p}`),k(Error("preview_closed")),f()}let B=()=>h("aborted"),S=setTimeout(()=>h("pair_timeout"),v.requestMs),N=setInterval(async()=>{if(!n())return h(e.signal.aborted?"aborted":"expired");if(w)return;w=!0;try{let p=u??=Promise.resolve().then(()=>e.port.check()).finally(()=>{u=void 0}),y=await te(()=>p);if(y===!1)return h("port_refused");if(y){m=void 0;return}if(Date.now()-(m??=Date.now())>Le)return h("port_unknown");for(let E of l.values())E.stop()}finally{w=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())h(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>P({type:"hello",binding:t,messages:v.upload,window:v.window})),a.addEventListener("close",()=>h("relay_closed")),a.addEventListener("error",()=>h("relay_error")),a.addEventListener("message",(p)=>{try{if(!n()||d)return h(e.signal.aborted?"aborted":"expired");if(typeof p.data!=="string")throw Error("preview_frame_invalid");if(g+=Buffer.byteLength(p.data),g>v.total)return h("quota");let y=di(p.data);if(!c){if(y.type!=="hello"||!Mt(t,y.binding))return h("binding_mismatch");c=!0,T=y.bytes===!0,clearTimeout(S),_();return}if(y.type==="hello"||y.type==="refused")return h("invalid_frame");if(y.type==="request"){q(y).catch(()=>h("invalid_request"));return}let E=l.get(y.id);if(!E)return;if(y.type==="cancel"||y.type==="end")E.stop();else if(y.type==="credit"&&E.credit)E.credit();else if(y.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>v.buffered)return E.stop();let I=z(y.data,v.upload);E.ws.send(y.binary?I:I.toString("utf8"))}else h("invalid_frame")}catch{h("invalid_frame")}});async function q(p){if(l.has(p.id)||l.size>=v.streams)return h("stream_limit");if(!n())return h(e.signal.aborted?"aborted":"expired");let y=new AbortController,E,I,K,Q=0,R=(W=!1)=>{if(!l.delete(p.id))return;clearTimeout(E),y.abort(),I?.close(1000,"preview_closed"),K?.(),P({type:W?"end":"cancel",id:p.id})},ae={stop:()=>R(),credit:()=>{Q++,K?.()}};if(l.set(p.id,ae),E=setTimeout(R,v.requestMs),!await en(()=>e.port.check())||!n()||y.signal.aborted)return R();let de=H(p.path);if(p.upgrade){if(p.method!=="GET"||p.body)return R();let W=p.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${de}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:v.upload}),ae.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),P({type:"ws",id:p.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let G=typeof A.data!=="string",M=me(A.data);if(M.length>v.upload)return R();P({type:"data",id:p.id,data:M.toString("base64"),binary:G})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let xe=z(p.body,v.upload),ce=Ie({hostname:"127.0.0.1",port:i.port,path:de,method:p.method,headers:{...Object.fromEntries(re(p.headers)),...i.headers,connection:"close"},signal:y.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let G=W.statusCode??502,M=Me(p.method,p.headers,G,A),ee=M==="br"?Re({flush:ne.BROTLI_OPERATION_FLUSH,params:{[ne.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Be({level:6,flush:ne.Z_SYNC_FLUSH}):void 0;if(P({type:"head",id:p.id,status:G,headers:re(M?Oe(A,M):A)}),clearTimeout(E),ee)We(W,ee,()=>{});for await(let F of ee??W){let le=Buffer.from(F);for(let Z=0;Z<le.length;Z+=v.chunk){if(Q===0&&!y.signal.aborted)await new Promise((Se)=>{K=Se});if(K=void 0,y.signal.aborted)return;Q--;let ue=le.subarray(Z,Z+v.chunk);P(T?we(p.id,ue):{type:"data",id:p.id,data:ue.toString("base64"),binary:!0})}}R(!0)}catch{R()}});ce.on("error",()=>R()),ce.end(xe)}return await O,{close:h,closed:b}}import{execFile as ze}from"child_process";import{createRequire as He}from"module";import{win32 as X}from"path";var Ue=250,je=50,De=250,qe=4194304;function ye(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Ke(e){let t=[];for(let n of e.split(/\r?\n/)){let s=n.trim().split(/\s+/);if(s[0]!=="TCP"||s.length<5)continue;let o=ye(s[1]),i=ye(s[2]),a=Number(s.at(-1));if(!o||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:o.address,localPort:o.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function Ge(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var oe=(e)=>new Promise((t,n)=>ze(X.join(Rt("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:qe,encoding:"utf8",windowsHide:!0,env:Tt()},(s,o)=>s?n(s):t(o)));function D(e){let t=X.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function Ze(e,t){let n=e.toLowerCase(),s=t.toLowerCase();return s===n||s.startsWith(n.endsWith("\\")?n:`${n}\\`)}function Pe(e,t,n){let s=e.cwd(n),o=s?D(s):null;return o&&X.isAbsolute(o)&&Ze(t,o)?o:null}var j;function et(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=He(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,s,o;try{s=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,o=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,l=1040,c=568,d=(g,w,u)=>{let m=Buffer.alloc(u);return s.ReadProcessMemory(g,w,n(m),u,null)?m:null};return j={processes(){let g=BigInt(s.CreateToolhelp32Snapshot(a,0));if(g===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let w=Buffer.alloc(c);w.writeUInt32LE(c,0);let u=n(w),m=[];for(let f=s.Process32FirstW(g,u);f;f=s.Process32NextW(g,u)){let b=w.toString("utf16le",44,c),_=b.slice(0,b.includes("\x00")?b.indexOf("\x00"):void 0),k=w.readUInt32LE(8);if(k>0)m.push({pid:k,parentPid:w.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return m}finally{s.CloseHandle(g)}},cwd(g){let w=BigInt(s.OpenProcess(l,0,g));if(w===0n)return null;try{let u=Buffer.alloc(48);if(o.NtQueryInformationProcess(w,0,n(u),u.length,null)!==0)return null;let m=d(w,u.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),f=m?d(w,m+0x38n,16):null,b=f?.readUInt16LE(0)??0;if(!f||b===0||b%2!==0)return null;return d(w,f.readBigUInt64LE(8),b)?.toString("utf16le")??null}finally{s.CloseHandle(w)}}},j}function se(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function ve(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Ke(n)}async function Za(e,t=et()){let n=se(t),s=D(e),o=[];for(let i of n.processes()){if(o.length>=Ue)break;let a=Pe(n,s,i.pid);if(a)o.push({pid:i.pid,command:i.command,cwd:X.relative(s,a)||"."})}return{processes:o}}async function Qa(e,t=et(),n=oe){let s=se(t),o=D(e),i=(await ve(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:Ge(d)})).sort((d,g)=>d.pid-g.pid||d.port-g.port||(d.address<g.address?-1:d.address>g.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,je),l=new Set(a.filter((d)=>Pe(s,o,d)!==null));if(l.size===0)return{ports:[]};let c=new Map(s.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>l.has(d.pid)).slice(0,De).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function he(e,t){let n=new Set([t]);for(let s=!0;s;){s=!1;for(let o of e)if(!n.has(o.pid)&&n.has(o.parentPid)&&o.pid!==o.parentPid)n.add(o.pid),s=!0}return n}function Je(e,t,n,s){let o=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==s)return[];let a=i.listening&&(o(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),l=!i.listening&&o(i.localAddress)&&o(i.remoteAddress);if(!a&&!l)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:s,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function _e(e,t,n=et(),s=oe){let o=se(n),i=he(o.processes(),e),a=await ve(s,1000),l=he(o.processes(),e);return Je(a,new Set([...i].filter((c)=>l.has(c))),e,t)}async function ec(e,t=et(),n=oe){if(!t||e.aborted)return!1;let s=t.processes().some((l)=>l.pid===process.pid),o=t.cwd(process.pid),i=o!==null&&D(o).toLowerCase()===D(process.cwd()).toLowerCase(),a=await n(5000).then((l)=>/^\s*TCP\s/m.test(l),()=>!1);return s&&i&&a&&!e.aborted}import{execFile as Ve}from"child_process";import{readFile as Xe,readdir as Ye,readlink as Qe}from"fs/promises";import{connect as er}from"net";import{setTimeout as rr}from"timers/promises";var tr={directory:Ye,text:(e)=>Xe(e,"utf8"),link:Qe};class ie extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new ie(e),Y="preview_listener_unproved",ke="00000000000000000000000001000000";async function nr(e,t,n=tr){let s=new Map;for(let a of["tcp","tcp6"]){let l=await n.text(`/proc/net/${a}`);if(l.length>4194304)throw x();for(let c of l.split(`
8
- `).slice(1)){let d=c.trim().split(/\s+/);if(d.length<10||!["0A","01"].includes(d[3]))continue;let[g,w]=d[1].split(":"),[u,m]=d[2].split(":");if(Number.parseInt(w,16)!==t)continue;let f=(k)=>k==="0100007F"||k==="0000000000000000FFFF00000100007F"||k===ke,b=d[3]==="0A";if(!(f(g)||b&&/^0+$/.test(g??"")))continue;if(!b&&!f(u))continue;let _=d[9];if(!/^[1-9][0-9]*$/.test(_))continue;s.set(_,{kernelId:_,port:t,peerPort:b?null:Number.parseInt(m,16),state:b?"listen":"established",host:g===ke?"::1":"127.0.0.1"})}}let o=await n.directory("/proc");if(o.length>8192)throw x();let i=[];for(let a of o){if(!/^[1-9][0-9]*$/.test(a))continue;try{let l=await n.text(`/proc/${a}/stat`),c=l.slice(l.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(c[2])!==e)continue;let d=await n.directory(`/proc/${a}/fd`);if(d.length>1024)throw x();let g=[];for(let m of d){if(!/^[0-9]+$/.test(m))continue;let f=await n.link(`/proc/${a}/fd/${m}`).catch(()=>""),b=/^socket:\[([0-9]+)\]$/.exec(f)?.[1],_=b?s.get(b):void 0;if(_)g.push({..._,pid:Number(a),processGroupId:e,descriptor:m})}let w=await n.text(`/proc/${a}/stat`),u=w.slice(w.lastIndexOf(")")+2).trim().split(/\s+/);if(c[19]===u[19]&&c[2]===u[2])i.push(...g)}catch(l){if(l instanceof Error&&l.message==="preview_port_ownership_unproved")throw l}}return i}function or(e,t,n){if(e.length>2097152)throw x();let s=0,o=0,i="",a="",l="",c="",d=[],g=()=>{if(s<1||o!==t||!/^\d+$/.test(i)||!/^0x[0-9a-f]+$/i.test(a))return;let w=c==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((m)=>l===`${m}:${n}`),u=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${n}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(l);if(w||c==="ESTABLISHED"&&u)d.push({pid:s,processGroupId:o,descriptor:i,kernelId:a,state:w?"listen":"established",port:n,peerPort:w?null:Number(u[1]),host:l.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let w of e.split(/[\0\n]/)){let u=w.slice(1);if(w[0]==="p")g(),s=Number(u),o=0,i=a=l=c="";else if(w[0]==="g")o=Number(u);else if(w[0]==="f")g(),i=u,a=l=c="";else if(w[0]==="d")a=u;else if(w[0]==="n")l=u;else if(w.startsWith("TST="))c=w.slice(4)}return g(),d}async function sr(e,t){if(process.platform==="linux")return nr(e,t);if(process.platform==="win32")return _e(e,t);if(process.platform!=="darwin")throw x();let n=await new Promise((s,o)=>Ve("/usr/sbin/lsof",["-nP","-a","-g",String(e),`-iTCP:${t}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(i,a)=>i?o(x()):s(a)));return or(n,e,t)}function ht(e,t={}){let n=C(e.binding),s=t.inspectSockets??sr,o=t.monotonicNow??(()=>performance.now());async function i(){let u=()=>{if(Date.now()>=n.expiresAtMs)throw x("binding_expired");if(e.deniedPorts.has(n.port))throw x("port_denied")};u();let m=await e.readCurrentJob(),f=m?.job,b=f?.process;if(u(),!m)throw x("server_stopped");if(!Mt(n,m.binding)||f?.jobId!==n.jobId)throw x("binding_changed");if(f.state!=="running"||f.finishedAtMs!==null||f.leaseExpiresAtMs<n.expiresAtMs)throw x("job_not_running");if(!b||b.pid<1||b.pid!==b.processGroupId||b.executorLaunchId!==m.executorLaunchId)throw x("process_unproved");return{pid:b.pid,launch:b.executorLaunchId,started:f.startedAtMs}}let a,l;async function c(){let u=await i(),m=await s(u.pid,n.port).catch(()=>{throw Error(Y)}),f=await i();if(u.pid!==f.pid||u.launch!==f.launch||u.started!==f.started)throw x("job_restarted");return m}async function d(u){for(;;){if(l&&l.startedAt>=u)return l.sockets;if(a&&a.startedAt>=u)return await a.sockets;if(a){await a.sockets.catch(()=>{});continue}let m={startedAt:o(),sockets:c()};a=m;try{let f=await m.sockets;if(!l||l.startedAt<=m.startedAt)l={startedAt:m.startedAt,sockets:f};return f}finally{if(a===m)a=void 0}}}async function g(u=()=>{},m=o()){u();let f=await d(m);if(u(),Date.now()>=n.expiresAtMs)throw x("binding_expired");if(!f.some((b)=>b.state==="listen"))throw Error(Y);return f}async function w(){try{return await g(()=>{},o()-1000),null}catch(u){if(u instanceof Error&&u.message===Y)return"listener_unproved";return u instanceof ie?u.code:"port_unproved"}}return{refusal:w,async check(){let u=await w();if(u==="listener_unproved")throw Error(Y);return u===null},async connect(u){if(u.aborted)throw x();let m=o()+2000,f=new AbortController,b=new Promise((h)=>f.signal.addEventListener("abort",()=>h(null),{once:!0})),_,k=()=>{f.abort(),_?.destroy()},O=setTimeout(k,2000);u.addEventListener("abort",k,{once:!0});let T=()=>{if(f.signal.aborted||u.aborted||o()>=m||_?.destroyed)throw k(),x()};async function P(h){T();let B=await Promise.race([h().then((S)=>({value:S})),b]);if(T(),!B)throw x();return B.value}try{let h=await P(()=>g(T,o()-1000));T();let B=h.some((p)=>p.state==="listen"&&p.host==="127.0.0.1")?"127.0.0.1":"::1",S=er({host:B,port:n.port,signal:u});_=S,S.once("close",k),await P(()=>new Promise((p,y)=>{S.once("connect",p),S.once("error",y)}));let N=S.localPort;if(!N)throw x();let q=o();while(!(await P(()=>g(T,q))).some((p)=>p.state==="established"&&p.peerPort===N))await P(()=>rr(Math.min(20,Math.max(1,m-o())),void 0,{signal:f.signal})),q=o();return T(),S}catch(h){throw k(),h}finally{clearTimeout(O),u.removeEventListener("abort",k),_?.off("close",k),f.abort()}}}}
9
- export{v,Mt,di,en,dr,Ya,Co,pt,et,Za,Qa,ec,ht};
6
+ `);P.write(Buffer.concat([Buffer.from(h,"latin1"),m.subarray(f+4)])),P.pipe(c),c.pipe(P),c.resume()}});await new Promise((c,d)=>{i.once("error",d),i.listen(0,"127.0.0.1",c)});let a=i.address();if(!a||typeof a==="string")throw i.close(),Error("preview_bind_failed");function l(){if(o)return;o=!0,t.removeEventListener("abort",l);for(let c of s)c.destroy();s.clear(),i.close()}if(t.addEventListener("abort",l,{once:!0}),t.aborted)l();return{port:a.port,headers:{[ge]:n},close:l}}var Le=60000,Ce=1e4,Ne=5000,$e=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function Me(e,t,n,s){let o=(c)=>t.find(([d])=>d.toLowerCase()===c)?.[1],i=(c)=>s.find(([d])=>d.toLowerCase()===c)?.[1],a=Number(i("content-length")??Number.NaN);if(e!=="GET"||n!==200||o("range")!==void 0||i("content-encoding")!==void 0||!$e.test(i("content-type")??"")||/\bno-transform\b/i.test(i("cache-control")??"")||a<1024)return null;let l=(c)=>new RegExp(`(?:^|,)\\s*${c}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test(o("accept-encoding")??"");return l("br")?"br":l("gzip")?"gzip":null}function Oe(e,t){let n=e.filter(([s])=>s.toLowerCase()==="vary").map(([,s])=>s).join(", ");return[...e.filter(([s])=>!["vary","etag","content-md5"].includes(s.toLowerCase())),...e.filter(([s])=>s.toLowerCase()==="etag").map(([s,o])=>[s,o.startsWith("W/")?o:`W/${o}`]),["Content-Encoding",t],["Vary",n.split(",").some((s)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(s))?n:n?`${n}, Accept-Encoding`:"Accept-Encoding"]]}async function To(e){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:e.jobId,port:e.port,reason_code:e.reason})}
7
+ `);let t=e.binding,n;try{n=V(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((s)=>{let o=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{o.terminate(),s()},v.authorizationMs*2);o.addEventListener("open",()=>{o.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),o.close(1000,`worker_refused_${e.reason}`)}),o.addEventListener("error",()=>{clearTimeout(i),s()}),o.addEventListener("close",()=>{clearTimeout(i),s()})})}async function Fe(e,t){let n=Date.now()+Ce,s;for(;;){if(!t())return"closed";let o=s??=e.refusal().finally(()=>{s=void 0}),i,a=await Promise.race([o.catch(()=>"port_unproved"),new Promise((l)=>{i=setTimeout(()=>l("port_check_timeout"),v.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((l)=>setTimeout(l,500))}}async function ht(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,s=t.expiresAtMs>Date.now()+v.lifetimeMs+Ne?"binding_mismatch":await Fe(e.port,n);if(s)throw await To({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:s}),Error("preview_not_authorized",{cause:s});let o=V(e.deviceRelayUrl,"device"),i=await be(e.port,e.signal),a;try{a=new U(o,{followRedirects:!1,perMessageDeflate:!1,maxPayload:v.upload*1.4+300000})}catch(p){throw i.close(),p}let l=new Map,c=!1,d=!1,g=0,w=!1,u,m,f,b=new Promise((p)=>{f=p}),_,k,O=new Promise((p,y)=>{_=p,k=y}),T=!1,P=(p)=>{let y=Buffer.isBuffer(p)?p:JSON.stringify(p);if(g+=Buffer.byteLength(y),!n()||d||a.readyState!==U.OPEN)return h(n()?"relay_closed":"expired");if(a.bufferedAmount>v.relayBuffered)return h("relay_backlog");if(g>v.total)return h("quota");a.send(y)};function h(p="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let y of l.values())y.stop();l.clear(),i.close(),a.close(1000,`worker_${p}`),k(Error("preview_closed")),f()}let B=()=>h("aborted"),S=setTimeout(()=>h("pair_timeout"),v.requestMs),N=setInterval(async()=>{if(!n())return h(e.signal.aborted?"aborted":"expired");if(w)return;w=!0;try{let p=u??=Promise.resolve().then(()=>e.port.check()).finally(()=>{u=void 0}),y=await te(()=>p);if(y===!1)return h("port_refused");if(y){m=void 0;return}if(Date.now()-(m??=Date.now())>Le)return h("port_unknown");for(let E of l.values())E.stop()}finally{w=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())h(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>P({type:"hello",binding:t,messages:v.upload,window:v.window})),a.addEventListener("close",()=>h("relay_closed")),a.addEventListener("error",()=>h("relay_error")),a.addEventListener("message",(p)=>{try{if(!n()||d)return h(e.signal.aborted?"aborted":"expired");if(typeof p.data!=="string")throw Error("preview_frame_invalid");if(g+=Buffer.byteLength(p.data),g>v.total)return h("quota");let y=mi(p.data);if(!c){if(y.type!=="hello"||!Bt(t,y.binding))return h("binding_mismatch");c=!0,T=y.bytes===!0,clearTimeout(S),_();return}if(y.type==="hello"||y.type==="refused")return h("invalid_frame");if(y.type==="request"){q(y).catch(()=>h("invalid_request"));return}let E=l.get(y.id);if(!E)return;if(y.type==="cancel"||y.type==="end")E.stop();else if(y.type==="credit"&&E.credit)E.credit();else if(y.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>v.buffered)return E.stop();let I=z(y.data,v.upload);E.ws.send(y.binary?I:I.toString("utf8"))}else h("invalid_frame")}catch{h("invalid_frame")}});async function q(p){if(l.has(p.id)||l.size>=v.streams)return h("stream_limit");if(!n())return h(e.signal.aborted?"aborted":"expired");let y=new AbortController,E,I,K,Q=0,R=(W=!1)=>{if(!l.delete(p.id))return;clearTimeout(E),y.abort(),I?.close(1000,"preview_closed"),K?.(),P({type:W?"end":"cancel",id:p.id})},ae={stop:()=>R(),credit:()=>{Q++,K?.()}};if(l.set(p.id,ae),E=setTimeout(R,v.requestMs),!await cn(()=>e.port.check())||!n()||y.signal.aborted)return R();let de=H(p.path);if(p.upgrade){if(p.method!=="GET"||p.body)return R();let W=p.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${de}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:v.upload}),ae.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),P({type:"ws",id:p.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let G=typeof A.data!=="string",M=me(A.data);if(M.length>v.upload)return R();P({type:"data",id:p.id,data:M.toString("base64"),binary:G})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let xe=z(p.body,v.upload),ce=Ie({hostname:"127.0.0.1",port:i.port,path:de,method:p.method,headers:{...Object.fromEntries(re(p.headers)),...i.headers,connection:"close"},signal:y.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let G=W.statusCode??502,M=Me(p.method,p.headers,G,A),ee=M==="br"?Re({flush:ne.BROTLI_OPERATION_FLUSH,params:{[ne.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Be({level:6,flush:ne.Z_SYNC_FLUSH}):void 0;if(P({type:"head",id:p.id,status:G,headers:re(M?Oe(A,M):A)}),clearTimeout(E),ee)We(W,ee,()=>{});for await(let F of ee??W){let le=Buffer.from(F);for(let Z=0;Z<le.length;Z+=v.chunk){if(Q===0&&!y.signal.aborted)await new Promise((Se)=>{K=Se});if(K=void 0,y.signal.aborted)return;Q--;let ue=le.subarray(Z,Z+v.chunk);P(T?we(p.id,ue):{type:"data",id:p.id,data:ue.toString("base64"),binary:!0})}}R(!0)}catch{R()}});ce.on("error",()=>R()),ce.end(xe)}return await O,{close:h,closed:b}}import{execFile as ze}from"child_process";import{createRequire as He}from"module";import{win32 as X}from"path";var Ue=250,je=50,De=250,qe=4194304;function ye(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Ke(e){let t=[];for(let n of e.split(/\r?\n/)){let s=n.trim().split(/\s+/);if(s[0]!=="TCP"||s.length<5)continue;let o=ye(s[1]),i=ye(s[2]),a=Number(s.at(-1));if(!o||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:o.address,localPort:o.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function Ge(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var oe=(e)=>new Promise((t,n)=>ze(X.join(Tt("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:qe,encoding:"utf8",windowsHide:!0,env:It()},(s,o)=>s?n(s):t(o)));function D(e){let t=X.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function Ze(e,t){let n=e.toLowerCase(),s=t.toLowerCase();return s===n||s.startsWith(n.endsWith("\\")?n:`${n}\\`)}function Pe(e,t,n){let s=e.cwd(n),o=s?D(s):null;return o&&X.isAbsolute(o)&&Ze(t,o)?o:null}var j;function tt(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=He(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,s,o;try{s=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,o=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,l=1040,c=568,d=(g,w,u)=>{let m=Buffer.alloc(u);return s.ReadProcessMemory(g,w,n(m),u,null)?m:null};return j={processes(){let g=BigInt(s.CreateToolhelp32Snapshot(a,0));if(g===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let w=Buffer.alloc(c);w.writeUInt32LE(c,0);let u=n(w),m=[];for(let f=s.Process32FirstW(g,u);f;f=s.Process32NextW(g,u)){let b=w.toString("utf16le",44,c),_=b.slice(0,b.includes("\x00")?b.indexOf("\x00"):void 0),k=w.readUInt32LE(8);if(k>0)m.push({pid:k,parentPid:w.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return m}finally{s.CloseHandle(g)}},cwd(g){let w=BigInt(s.OpenProcess(l,0,g));if(w===0n)return null;try{let u=Buffer.alloc(48);if(o.NtQueryInformationProcess(w,0,n(u),u.length,null)!==0)return null;let m=d(w,u.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),f=m?d(w,m+0x38n,16):null,b=f?.readUInt16LE(0)??0;if(!f||b===0||b%2!==0)return null;return d(w,f.readBigUInt64LE(8),b)?.toString("utf16le")??null}finally{s.CloseHandle(w)}}},j}function se(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function ve(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Ke(n)}async function sc(e,t=tt()){let n=se(t),s=D(e),o=[];for(let i of n.processes()){if(o.length>=Ue)break;let a=Pe(n,s,i.pid);if(a)o.push({pid:i.pid,command:i.command,cwd:X.relative(s,a)||"."})}return{processes:o}}async function ac(e,t=tt(),n=oe){let s=se(t),o=D(e),i=(await ve(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:Ge(d)})).sort((d,g)=>d.pid-g.pid||d.port-g.port||(d.address<g.address?-1:d.address>g.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,je),l=new Set(a.filter((d)=>Pe(s,o,d)!==null));if(l.size===0)return{ports:[]};let c=new Map(s.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>l.has(d.pid)).slice(0,De).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function he(e,t){let n=new Set([t]);for(let s=!0;s;){s=!1;for(let o of e)if(!n.has(o.pid)&&n.has(o.parentPid)&&o.pid!==o.parentPid)n.add(o.pid),s=!0}return n}function Je(e,t,n,s){let o=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==s)return[];let a=i.listening&&(o(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),l=!i.listening&&o(i.localAddress)&&o(i.remoteAddress);if(!a&&!l)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:s,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function _e(e,t,n=tt(),s=oe){let o=se(n),i=he(o.processes(),e),a=await ve(s,1000),l=he(o.processes(),e);return Je(a,new Set([...i].filter((c)=>l.has(c))),e,t)}async function cc(e,t=tt(),n=oe){if(!t||e.aborted)return!1;let s=t.processes().some((l)=>l.pid===process.pid),o=t.cwd(process.pid),i=o!==null&&D(o).toLowerCase()===D(process.cwd()).toLowerCase(),a=await n(5000).then((l)=>/^\s*TCP\s/m.test(l),()=>!1);return s&&i&&a&&!e.aborted}import{execFile as Ve}from"child_process";import{readFile as Xe,readdir as Ye,readlink as Qe}from"fs/promises";import{connect as er}from"net";import{setTimeout as rr}from"timers/promises";var tr={directory:Ye,text:(e)=>Xe(e,"utf8"),link:Qe};class ie extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new ie(e),Y="preview_listener_unproved",ke="00000000000000000000000001000000";async function nr(e,t,n=tr){let s=new Map;for(let a of["tcp","tcp6"]){let l=await n.text(`/proc/net/${a}`);if(l.length>4194304)throw x();for(let c of l.split(`
8
+ `).slice(1)){let d=c.trim().split(/\s+/);if(d.length<10||!["0A","01"].includes(d[3]))continue;let[g,w]=d[1].split(":"),[u,m]=d[2].split(":");if(Number.parseInt(w,16)!==t)continue;let f=(k)=>k==="0100007F"||k==="0000000000000000FFFF00000100007F"||k===ke,b=d[3]==="0A";if(!(f(g)||b&&/^0+$/.test(g??"")))continue;if(!b&&!f(u))continue;let _=d[9];if(!/^[1-9][0-9]*$/.test(_))continue;s.set(_,{kernelId:_,port:t,peerPort:b?null:Number.parseInt(m,16),state:b?"listen":"established",host:g===ke?"::1":"127.0.0.1"})}}let o=await n.directory("/proc");if(o.length>8192)throw x();let i=[];for(let a of o){if(!/^[1-9][0-9]*$/.test(a))continue;try{let l=await n.text(`/proc/${a}/stat`),c=l.slice(l.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(c[2])!==e)continue;let d=await n.directory(`/proc/${a}/fd`);if(d.length>1024)throw x();let g=[];for(let m of d){if(!/^[0-9]+$/.test(m))continue;let f=await n.link(`/proc/${a}/fd/${m}`).catch(()=>""),b=/^socket:\[([0-9]+)\]$/.exec(f)?.[1],_=b?s.get(b):void 0;if(_)g.push({..._,pid:Number(a),processGroupId:e,descriptor:m})}let w=await n.text(`/proc/${a}/stat`),u=w.slice(w.lastIndexOf(")")+2).trim().split(/\s+/);if(c[19]===u[19]&&c[2]===u[2])i.push(...g)}catch(l){if(l instanceof Error&&l.message==="preview_port_ownership_unproved")throw l}}return i}function or(e,t,n){if(e.length>2097152)throw x();let s=0,o=0,i="",a="",l="",c="",d=[],g=()=>{if(s<1||o!==t||!/^\d+$/.test(i)||!/^0x[0-9a-f]+$/i.test(a))return;let w=c==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((m)=>l===`${m}:${n}`),u=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${n}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(l);if(w||c==="ESTABLISHED"&&u)d.push({pid:s,processGroupId:o,descriptor:i,kernelId:a,state:w?"listen":"established",port:n,peerPort:w?null:Number(u[1]),host:l.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let w of e.split(/[\0\n]/)){let u=w.slice(1);if(w[0]==="p")g(),s=Number(u),o=0,i=a=l=c="";else if(w[0]==="g")o=Number(u);else if(w[0]==="f")g(),i=u,a=l=c="";else if(w[0]==="d")a=u;else if(w[0]==="n")l=u;else if(w.startsWith("TST="))c=w.slice(4)}return g(),d}async function sr(e,t){if(process.platform==="linux")return nr(e,t);if(process.platform==="win32")return _e(e,t);if(process.platform!=="darwin")throw x();let n=await new Promise((s,o)=>Ve("/usr/sbin/lsof",["-nP","-a","-g",String(e),`-iTCP:${t}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(i,a)=>i?o(x()):s(a)));return or(n,e,t)}function ft(e,t={}){let n=C(e.binding),s=t.inspectSockets??sr,o=t.monotonicNow??(()=>performance.now());async function i(){let u=()=>{if(Date.now()>=n.expiresAtMs)throw x("binding_expired");if(e.deniedPorts.has(n.port))throw x("port_denied")};u();let m=await e.readCurrentJob(),f=m?.job,b=f?.process;if(u(),!m)throw x("server_stopped");if(!Bt(n,m.binding)||f?.jobId!==n.jobId)throw x("binding_changed");if(f.state!=="running"||f.finishedAtMs!==null||f.leaseExpiresAtMs<n.expiresAtMs)throw x("job_not_running");if(!b||b.pid<1||b.pid!==b.processGroupId||b.executorLaunchId!==m.executorLaunchId)throw x("process_unproved");return{pid:b.pid,launch:b.executorLaunchId,started:f.startedAtMs}}let a,l;async function c(){let u=await i(),m=await s(u.pid,n.port).catch(()=>{throw Error(Y)}),f=await i();if(u.pid!==f.pid||u.launch!==f.launch||u.started!==f.started)throw x("job_restarted");return m}async function d(u){for(;;){if(l&&l.startedAt>=u)return l.sockets;if(a&&a.startedAt>=u)return await a.sockets;if(a){await a.sockets.catch(()=>{});continue}let m={startedAt:o(),sockets:c()};a=m;try{let f=await m.sockets;if(!l||l.startedAt<=m.startedAt)l={startedAt:m.startedAt,sockets:f};return f}finally{if(a===m)a=void 0}}}async function g(u=()=>{},m=o()){u();let f=await d(m);if(u(),Date.now()>=n.expiresAtMs)throw x("binding_expired");if(!f.some((b)=>b.state==="listen"))throw Error(Y);return f}async function w(){try{return await g(()=>{},o()-1000),null}catch(u){if(u instanceof Error&&u.message===Y)return"listener_unproved";return u instanceof ie?u.code:"port_unproved"}}return{refusal:w,async check(){let u=await w();if(u==="listener_unproved")throw Error(Y);return u===null},async connect(u){if(u.aborted)throw x();let m=o()+2000,f=new AbortController,b=new Promise((h)=>f.signal.addEventListener("abort",()=>h(null),{once:!0})),_,k=()=>{f.abort(),_?.destroy()},O=setTimeout(k,2000);u.addEventListener("abort",k,{once:!0});let T=()=>{if(f.signal.aborted||u.aborted||o()>=m||_?.destroyed)throw k(),x()};async function P(h){T();let B=await Promise.race([h().then((S)=>({value:S})),b]);if(T(),!B)throw x();return B.value}try{let h=await P(()=>g(T,o()-1000));T();let B=h.some((p)=>p.state==="listen"&&p.host==="127.0.0.1")?"127.0.0.1":"::1",S=er({host:B,port:n.port,signal:u});_=S,S.once("close",k),await P(()=>new Promise((p,y)=>{S.once("connect",p),S.once("error",y)}));let N=S.localPort;if(!N)throw x();let q=o();while(!(await P(()=>g(T,q))).some((p)=>p.state==="established"&&p.peerPort===N))await P(()=>rr(Math.min(20,Math.max(1,m-o())),void 0,{signal:f.signal})),q=o();return T(),S}catch(h){throw k(),h}finally{clearTimeout(O),u.removeEventListener("abort",k),_?.off("close",k),f.abort()}}}}
9
+ export{v,Bt,mi,cn,pr,oc,To,ht,tt,sc,ac,cc,ft};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{te}from"./vm-hands-entry-lite-9g52kxyj.js";import{U,H,R}from"./vm-hands-entry-lite-v4hr9x9h.js";import{ge,Lt,ti,ko,xo,ur}from"./vm-hands-entry-lite-vkhacd00.js";import{mt}from"./vm-hands-entry-lite-pxtycfdv.js";import{v,dr,Co,pt,ht}from"./vm-hands-entry-lite-0wb1n769.js";import{b,m}from"./vm-hands-entry-lite-yvws5zpx.js";import{s,St,Mc}from"./vm-hands-entry-lite-zawytz09.js";import{Vi,I,t,V,o,_,tl,Pt,ca,d,n,we,A,$e,c,i,Gi}from"./vm-hands-entry-lite-k5ytpgzz.js";import{Xe,G}from"./vm-hands-entry-lite-8xv6c0rm.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as X}from"crypto";import{spawn as ke}from"child_process";import{existsSync as Y,lstatSync as de,mkdirSync as Oe,readFileSync as Me,realpathSync as q,rmSync as Te,writeFileSync as je}from"fs";import{dirname as Le,join as k,relative as We,sep as Ne}from"path";var he=["process.run.v1","process.full.v1"],be=600000,ve=1800000,ye=20000,re="process.cancel.v1",oe=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:c(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(ve).default(be).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),B={device_id:t().uuid(),root_id:t().uuid()},Se=A("action",[oe.extend(B),n({...B,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(ye).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...B,action:i("cancel"),process_id:t().uuid()}).strict()]),qe=Vi(Se,{io:"input"}),Je=oe.extend({process_brain_fence:t().uuid(),process_expires_at:I.datetime()}).strict(),W=n({version:i(1),process_id:t().uuid(),state:c(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:_(),observed_at:I.datetime(),output:d(n({cursor:o().int().min(1),stream:c(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let p=e.first_cursor-1;for(let l of e.output){if(l.cursor<=p||l.cursor>e.next_cursor)return!1;p=l.cursor}return!0});function Jn(e){return he.includes(e)}var ze=n({operation_constraints:$e(t(),Pt())}),Ge=n({ready:i(!0),version:i(1),execution_mode:c(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var xe=n({version:i(1),process_id:t().uuid(),state:c(["queued","cancelled_before_start","not_started"]),exit_code:tl(),output:d(ca()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:c(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Pe=n({...W.shape,state:c(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:I.datetime().optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:_(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:_(),next_step:c(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:W.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),Be=Vi(Pe),Fe=we([W,xe.refine((e)=>e.state==="cancelled_before_start")]),F=n({version:i(1),process_id:t().uuid(),state:c(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:I.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ee=n({process_terminal_observation:F}).strict();function Ra(e,a){let p=Ee.safeParse(e);return p.success&&p.data.process_terminal_observation.process_id===a?p.data:null}var Ta="preview.serve.v1",Ia=43200000;var Da=3,ne="preview.open.v1",se=1,fo="gid_proxy_v1",Oa="egress",mo=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Re=n({version:i(fo),allowed_domains:d(t().max(260).regex(mo)).max(1024)}).strict(),Ie=Gi((e)=>te(e)!==null,"invalid workspace"),De=n({version:i(1),request_id:V(),session_id:V(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ie,egress:Re.optional()}).strict(),Na=De.extend({expires_at:I.datetime()}).strict();var Ce=4,Ae=5000;function K(e,a,p){let l=null;try{l=dr(e)}catch{}Co({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:a,port:l?.binding.port??0,reason:l?p:"binding_invalid"})}function ie(e){let a=new Map;return{open(p){let l=(w)=>K(p,e.claim.operation_id,w),P;try{P=dr(p)}catch{return l("binding_invalid")}let{binding:h,deviceRelayUrl:N}=P,S=e.claim.owner;if(!S||h.organizationId!==S.organization_id||h.userId!==S.user_id||h.deviceId!==S.device_id||h.rootId!==e.claim.root_id||h.jobId!==e.claim.operation_id||h.fenceId!==e.claim.operation_id||h.generation!==se||h.expiresAtMs>Math.min(Date.now()+v.lifetimeMs+Ae,e.expiresAtMs))return l("binding_mismatch");if(h.expiresAtMs<=Date.now())return l("binding_expired");if(a.get(h.port)?.abort(),a.delete(h.port),a.size>=Ce)return l("preview_capacity");let O=new AbortController;a.set(h.port,O);let y=ht({binding:h,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(O.signal.aborted)return null;let w=await e.inspect();return w?{binding:h,executorLaunchId:e.executorLaunchId,job:w}:null}});pt({binding:h,deviceRelayUrl:N,port:y,signal:O.signal}).then((w)=>w.closed,(w)=>{let x=w instanceof Error?w.message:"preview_failed";if(x!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:h.jobId,port:h.port,reason_code:x})}
3
- `)}).finally(()=>{if(a.get(h.port)===O)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",T=new Map;function ue(e){let a=T.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(T.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return T.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(mt({},e)),l=We(St(e),p),[P,...h]=l.split(Ne);return{directory:k(a,l,"processes"),previous:[k(p,"processes"),...P==="reason"?[k(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Mc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function Xn(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw D("process_authority_lost");let a=ue(e.claim);if(a.executing)throw D("process_busy");if(a.executing=!0,a.cancelRequested)return a.phase="settling",ae(e.claim.operation_id);a.phase="starting";let p=e.journals??Ve();Oe(p.directory,{recursive:!0,mode:448});let l=Lt({runtimeDirectory:q(p.directory),previousRuntimeDirectories:(p.previous??[]).filter((u)=>Y(u)).map((u)=>q(u)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:le,folders:[e.root,e.cwd]});try{for(let u of[e.root,e.cwd])if(!ge(q(u),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(u){throw l.disposeSocket(),u}let P=de(l.journalDirectory),h=e.claim.capability===pe,N=()=>J.set(e.claim.operation_id,{path:l.journalDirectory,ino:P.ino,dev:P.dev,anyCompletion:h}),S=l.launchDirectory,O=k(S,"config.json"),y={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:U,protocolVersion:2,workerArtifactSha256:R,workerEntrypoint:H,targetGeneration:1,fenceId:X(),...process.platform==="win32"?{bashExecutable:Xe()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:k(S,"unused.env"),replSocketPath:k(S,"unused.sock"),readyPath:k(S,"ready.json"),directTerminalReceiptPath:k(S,"terminal.json"),launchId:X(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},w;try{je(O,JSON.stringify(y),{mode:384});let u=ko({configPath:O,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:S});w=e.spawnWorker?.(O,y)??ke(u.command,u.args,{...u.options,env:e.environment,stdio:[xo,"ignore","ignore"]})}catch(u){throw l.disposeSocket(),u}let x=!1,z=new Promise((u,g)=>{w.once("exit",(f)=>{x=!0,u(f)}),w.once("error",(f)=>{x=!0,g(f)})});z.catch(()=>{});let me={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:y.fenceId,executorLaunchId:y.launchId,expiresAtMs:y.expiresAtMs},M=async(u)=>{let g=await ti(me,{type:"job",version:2,generation:1,id:X(),jobId:e.claim.operation_id,...u==="start"?{action:u,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:u==="inspect"?{action:u,input:{after:0}}:u==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:u,input:{}}},new AbortController().signal);if(!g.ok)throw D(g.error);return g.job},j=!1,L=!1,Q,Z=()=>{j=!0,ur(w,"SIGTERM")};e.signal.addEventListener("abort",Z,{once:!0});let C,ee=0,_e=async(u)=>{let g=[...u.output],f={version:1,process_id:e.claim.operation_id,state:u.state,exit_code:u.exitCode,first_cursor:u.firstCursor,next_cursor:u.nextCursor,truncated:u.truncated,output:g,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&g.length)g.shift(),f.truncated=!0,f.first_cursor=g[0]?.cursor??f.next_cursor+1;C=W.parse(f),await e.emit(C),ee=Date.now()};try{let u=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Y(y.readyPath)){if(x)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=u)throw D("process_start_unconfirmed");await ce(25)}let g=JSON.parse(Me(y.readyPath,"utf8"));if(g.launchId!==y.launchId||g.fenceId!==y.fenceId||g.workerArtifactSha256!==R)throw D();if(e.signal.throwIfAborted(),a.cancelRequested)return ae(e.claim.operation_id);let f;try{L=!0,f=await M("start")}catch(E){if(!(E instanceof r)||E.code!=="hands_job_result_unknown")throw E;f=await M("inspect")}if(a.phase="running",a.cancel=async()=>{await M("cancel")},h&&e.preview)a.tunnels=ie({claim:e.claim,executorLaunchId:y.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>a.phase==="running"&&!x?await M("probe"):null});if(a.cancelRequested)await a.cancel(),f=await M("inspect");for(;;){if(!["starting","running"].includes(f.state))a.phase="settling",a.cancel=void 0;if(!C||C.state!==f.state||C.next_cursor!==f.nextCursor&&Date.now()-ee>=5000)await _e(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||x)throw D();await ce(1000);try{f=await M("inspect"),Q=void 0}catch(E){if(!(E instanceof r)||E.code!=="hands_job_result_unknown"||e.signal.aborted||x||Date.now()-(Q??=Date.now())>120000)throw E}}if(!C||C.state==="uncertain")throw D();return C}finally{if(a.phase="settling",a.cancel=void 0,a.tunnels?.dispose(),a.tunnels=void 0,await a.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",Z),!x&&!j)ur(w,"SIGTERM");let u,g=await Promise.race([z.then((f)=>({code:f})),new Promise((f)=>{u=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(u)});if(!g){try{ur(w,"SIGKILL")}catch{}try{await z}finally{if(x)l.disposeSocket()}throw D("process_cleanup_unconfirmed")}try{if((j||e.signal.aborted)&&g.code===0&&L){b(S);let f=JSON.parse(m(y.directTerminalReceiptPath)),E=F.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===y.launchId&&f.fence_id===y.fenceId&&f.scope_id===l.scopeId&&E.success&&E.data.process_id===e.claim.operation_id){if(h)N();throw new lr(E.data)}}}catch(f){if(f instanceof lr)throw f}finally{if(x)l.disposeSocket()}if(g.code!==0&&!j&&L)throw D("process_cleanup_unconfirmed");if(!j&&g.code===0&&(C&&["exited","cancelled","expired"].includes(C.state)||!L&&a.cancelRequested)||h&&g.code===0&&!L)N()}}async function go(e,a){if(a.kind===ne&&e.capability===pe){let P=T.get(e.operation_id);if(P?.claim===e&&P.tunnels)P.tunnels.open(a.payload);else K(a.payload,e.operation_id,"server_not_running");return!0}if(a.kind!==re||!Jn(e.capability)||!e.owner||a.payload.process_id!==e.operation_id)return!1;let p=T.get(e.operation_id);if(p&&p.claim!==e)return!1;let l=ue(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Yn(e,a){T.delete(e);let p=J.get(e);if(!p||a!=="succeeded"&&!p.anyCompletion)return J.delete(e),!1;try{let l=de(p.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==p.ino||l.dev!==p.dev||!G(l)||q(p.path)!==p.path||Y(k(p.path,"owner.lock")))return!1;return Te(p.path,{recursive:!0}),J.delete(e),!0}catch{return!1}}
4
- export{Jn,Ra,Ta,Ia,Da,fo,Oa,mo,Na,lr,Xn,go,Yn};
2
+ import{te}from"./vm-hands-entry-lite-kbnxk71q.js";import{U,H,T}from"./vm-hands-entry-lite-qjrgvdbj.js";import{ge,$t,ii,Ao,Po,ur}from"./vm-hands-entry-lite-gcqqnnze.js";import{gt}from"./vm-hands-entry-lite-xfak34av.js";import{v,pr,To,ht,ft}from"./vm-hands-entry-lite-b1vanmtv.js";import{b,m}from"./vm-hands-entry-lite-yg4dk99m.js";import{s,Et,qc}from"./vm-hands-entry-lite-12ck5swp.js";import{Ji,I,t,V,o,_,cl,Rt,ga,d,n,we,P,$e,c,i,Xi}from"./vm-hands-entry-lite-zpvr7wc6.js";import{Ye,G}from"./vm-hands-entry-lite-pg7nnyc6.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as X}from"crypto";import{spawn as ke}from"child_process";import{existsSync as Y,lstatSync as de,mkdirSync as Oe,readFileSync as Me,realpathSync as q,rmSync as Te,writeFileSync as je}from"fs";import{dirname as Le,join as A,relative as We,sep as Ne}from"path";var he=["process.run.v1","process.full.v1"],be=600000,ve=1800000,ye=20000,re="process.cancel.v1",oe=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:c(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(ve).default(be).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),B={device_id:t().uuid(),root_id:t().uuid()},Se=P("action",[oe.extend(B),n({...B,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(ye).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...B,action:i("cancel"),process_id:t().uuid()}).strict()]),qe=Ji(Se,{io:"input"}),Je=oe.extend({process_brain_fence:t().uuid(),process_expires_at:I.datetime()}).strict(),W=n({version:i(1),process_id:t().uuid(),state:c(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:_(),observed_at:I.datetime(),output:d(n({cursor:o().int().min(1),stream:c(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let p=e.first_cursor-1;for(let l of e.output){if(l.cursor<=p||l.cursor>e.next_cursor)return!1;p=l.cursor}return!0});function Zn(e){return he.includes(e)}var ze=n({operation_constraints:$e(t(),Rt())}),Ge=n({ready:i(!0),version:i(1),execution_mode:c(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var xe=n({version:i(1),process_id:t().uuid(),state:c(["queued","cancelled_before_start","not_started"]),exit_code:cl(),output:d(ga()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:c(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Pe=n({...W.shape,state:c(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:I.datetime().optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:_(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:_(),next_step:c(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:W.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),Be=Ji(Pe),Fe=we([W,xe.refine((e)=>e.state==="cancelled_before_start")]),F=n({version:i(1),process_id:t().uuid(),state:c(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:I.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ee=n({process_terminal_observation:F}).strict();function Ma(e,a){let p=Ee.safeParse(e);return p.success&&p.data.process_terminal_observation.process_id===a?p.data:null}var Ba="preview.serve.v1",Fa=43200000;var ja=3,ne="preview.open.v1",se=1,_o="gid_proxy_v1",Ha="egress",yo=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Re=n({version:i(_o),allowed_domains:d(t().max(260).regex(yo)).max(1024)}).strict(),Ie=Xi((e)=>te(e)!==null,"invalid workspace"),De=n({version:i(1),request_id:V(),session_id:V(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ie,egress:Re.optional()}).strict(),Ua=De.extend({expires_at:I.datetime()}).strict();var Ce=4,Ae=5000;function K(e,a,p){let l=null;try{l=pr(e)}catch{}To({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:a,port:l?.binding.port??0,reason:l?p:"binding_invalid"})}function ie(e){let a=new Map;return{open(p){let l=(w)=>K(p,e.claim.operation_id,w),E;try{E=pr(p)}catch{return l("binding_invalid")}let{binding:h,deviceRelayUrl:N}=E,S=e.claim.owner;if(!S||h.organizationId!==S.organization_id||h.userId!==S.user_id||h.deviceId!==S.device_id||h.rootId!==e.claim.root_id||h.jobId!==e.claim.operation_id||h.fenceId!==e.claim.operation_id||h.generation!==se||h.expiresAtMs>Math.min(Date.now()+v.lifetimeMs+Ae,e.expiresAtMs))return l("binding_mismatch");if(h.expiresAtMs<=Date.now())return l("binding_expired");if(a.get(h.port)?.abort(),a.delete(h.port),a.size>=Ce)return l("preview_capacity");let k=new AbortController;a.set(h.port,k);let y=ft({binding:h,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(k.signal.aborted)return null;let w=await e.inspect();return w?{binding:h,executorLaunchId:e.executorLaunchId,job:w}:null}});ht({binding:h,deviceRelayUrl:N,port:y,signal:k.signal}).then((w)=>w.closed,(w)=>{let x=w instanceof Error?w.message:"preview_failed";if(x!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:h.jobId,port:h.port,reason_code:x})}
3
+ `)}).finally(()=>{if(a.get(h.port)===k)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",M=new Map;function ue(e){let a=M.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(M.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return M.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(gt({},e)),l=We(Et(e),p),[E,...h]=l.split(Ne);return{directory:A(a,l,"processes"),previous:[A(p,"processes"),...E==="reason"?[A(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function Qn(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw D("process_authority_lost");let a=ue(e.claim);if(a.executing)throw D("process_busy");if(a.executing=!0,a.cancelRequested)return a.phase="settling",ae(e.claim.operation_id);a.phase="starting";let p=e.journals??Ve();Oe(p.directory,{recursive:!0,mode:448});let l=$t({runtimeDirectory:q(p.directory),previousRuntimeDirectories:(p.previous??[]).filter((u)=>Y(u)).map((u)=>q(u)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:le,folders:[e.root,e.cwd]});try{for(let u of[e.root,e.cwd])if(!ge(q(u),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(u){throw l.disposeSocket(),u}let E=de(l.journalDirectory),h=e.claim.capability===pe,N=()=>J.set(e.claim.operation_id,{path:l.journalDirectory,ino:E.ino,dev:E.dev,anyCompletion:h}),S=l.launchDirectory,k=A(S,"config.json"),y={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:U,protocolVersion:2,workerArtifactSha256:T,workerEntrypoint:H,targetGeneration:1,fenceId:X(),...process.platform==="win32"?{bashExecutable:Ye()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:A(S,"unused.env"),replSocketPath:A(S,"unused.sock"),readyPath:A(S,"ready.json"),directTerminalReceiptPath:A(S,"terminal.json"),launchId:X(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},w;try{je(k,JSON.stringify(y),{mode:384});let u=Ao({configPath:k,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:S});w=e.spawnWorker?.(k,y)??ke(u.command,u.args,{...u.options,env:e.environment,stdio:[Po,"ignore","ignore"]})}catch(u){throw l.disposeSocket(),u}let x=!1,z=new Promise((u,g)=>{w.once("exit",(f)=>{x=!0,u(f)}),w.once("error",(f)=>{x=!0,g(f)})});z.catch(()=>{});let me={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:y.fenceId,executorLaunchId:y.launchId,expiresAtMs:y.expiresAtMs},O=async(u)=>{let g=await ii(me,{type:"job",version:2,generation:1,id:X(),jobId:e.claim.operation_id,...u==="start"?{action:u,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:u==="inspect"?{action:u,input:{after:0}}:u==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:u,input:{}}},new AbortController().signal);if(!g.ok)throw D(g.error);return g.job},j=!1,L=!1,Q,Z=()=>{j=!0,ur(w,"SIGTERM")};e.signal.addEventListener("abort",Z,{once:!0});let C,ee=0,_e=async(u)=>{let g=[...u.output],f={version:1,process_id:e.claim.operation_id,state:u.state,exit_code:u.exitCode,first_cursor:u.firstCursor,next_cursor:u.nextCursor,truncated:u.truncated,output:g,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&g.length)g.shift(),f.truncated=!0,f.first_cursor=g[0]?.cursor??f.next_cursor+1;C=W.parse(f),await e.emit(C),ee=Date.now()};try{let u=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Y(y.readyPath)){if(x)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=u)throw D("process_start_unconfirmed");await ce(25)}let g=JSON.parse(Me(y.readyPath,"utf8"));if(g.launchId!==y.launchId||g.fenceId!==y.fenceId||g.workerArtifactSha256!==T)throw D();if(e.signal.throwIfAborted(),a.cancelRequested)return ae(e.claim.operation_id);let f;try{L=!0,f=await O("start")}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown")throw R;f=await O("inspect")}if(a.phase="running",a.cancel=async()=>{await O("cancel")},h&&e.preview)a.tunnels=ie({claim:e.claim,executorLaunchId:y.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>a.phase==="running"&&!x?await O("probe"):null});if(a.cancelRequested)await a.cancel(),f=await O("inspect");for(;;){if(!["starting","running"].includes(f.state))a.phase="settling",a.cancel=void 0;if(!C||C.state!==f.state||C.next_cursor!==f.nextCursor&&Date.now()-ee>=5000)await _e(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||x)throw D();await ce(1000);try{f=await O("inspect"),Q=void 0}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown"||e.signal.aborted||x||Date.now()-(Q??=Date.now())>120000)throw R}}if(!C||C.state==="uncertain")throw D();return C}finally{if(a.phase="settling",a.cancel=void 0,a.tunnels?.dispose(),a.tunnels=void 0,await a.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",Z),!x&&!j)ur(w,"SIGTERM");let u,g=await Promise.race([z.then((f)=>({code:f})),new Promise((f)=>{u=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(u)});if(!g){try{ur(w,"SIGKILL")}catch{}try{await z}finally{if(x)l.disposeSocket()}throw D("process_cleanup_unconfirmed")}try{if((j||e.signal.aborted)&&g.code===0&&L){b(S);let f=JSON.parse(m(y.directTerminalReceiptPath)),R=F.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===y.launchId&&f.fence_id===y.fenceId&&f.scope_id===l.scopeId&&R.success&&R.data.process_id===e.claim.operation_id){if(h)N();throw new lr(R.data)}}}catch(f){if(f instanceof lr)throw f}finally{if(x)l.disposeSocket()}if(g.code!==0&&!j&&L)throw D("process_cleanup_unconfirmed");if(!j&&g.code===0&&(C&&["exited","cancelled","expired"].includes(C.state)||!L&&a.cancelRequested)||h&&g.code===0&&!L)N()}}async function wo(e,a){if(a.kind===ne&&e.capability===pe){let E=M.get(e.operation_id);if(E?.claim===e&&E.tunnels)E.tunnels.open(a.payload);else K(a.payload,e.operation_id,"server_not_running");return!0}if(a.kind!==re||!Zn(e.capability)||!e.owner||a.payload.process_id!==e.operation_id)return!1;let p=M.get(e.operation_id);if(p&&p.claim!==e)return!1;let l=ue(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function ei(e,a){M.delete(e);let p=J.get(e);if(!p||a!=="succeeded"&&!p.anyCompletion)return J.delete(e),!1;try{let l=de(p.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==p.ino||l.dev!==p.dev||!G(l)||q(p.path)!==p.path||Y(A(p.path,"owner.lock")))return!1;return Te(p.path,{recursive:!0}),J.delete(e),!0}catch{return!1}}
4
+ export{Zn,Ma,Ba,Fa,ja,_o,Ha,yo,Ua,lr,Qn,wo,ei};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{s}from"./vm-hands-entry-lite-zawytz09.js";import{readFileSync as l}from"fs";import{isAbsolute as i,normalize as m}from"path";var p="REASON_WORKER_DESKTOP_USER",u=null;function d(t,o){for(let c of o.split(`
3
- `)){let e=c.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!i(n)||m(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function wr(t={}){let o="value"in t?t.value:process.env[p];if(u=null,o===void 0||o==="")return null;let c=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=c==="linux"&&e===0&&Number.isSafeInteger(n)?d(n,(t.passwd??(()=>l("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function ue(){return u}function Ko(){return u?.home??s()}
4
- export{wr,ue,Ko};
2
+ import{s}from"./vm-hands-entry-lite-12ck5swp.js";import{readFileSync as l}from"fs";import{isAbsolute as i,normalize as m}from"path";var p="REASON_WORKER_DESKTOP_USER",u=null;function d(t,o){for(let c of o.split(`
3
+ `)){let e=c.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!i(n)||m(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function kr(t={}){let o="value"in t?t.value:process.env[p];if(u=null,o===void 0||o==="")return null;let c=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=c==="linux"&&e===0&&Number.isSafeInteger(n)?d(n,(t.passwd??(()=>l("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function ue(){return u}function rs(){return u?.home??s()}
4
+ export{kr,ue,rs};
@@ -0,0 +1,12 @@
1
+ // @bun
2
+ import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{spawn as Q}from"child_process";import{lstatSync as C,readdirSync as ee,readFileSync as w,readlinkSync as te,rmSync as oe,writeFileSync as O}from"fs";import{basename as re,join as D}from"path";var ne="__desktop-call",se="/usr/bin/setpriv",ie=27262976,P=8192,le=2000;function N(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function ae(e){try{return JSON.parse(e)}catch{return null}}function ce(){return[process.execPath,...re(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],ne]}function pe(e){let o=(s)=>{try{return C(s).uid}catch{return null}},t=C("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((s)=>{let c=o(s);return c!==null&&c!==e.uid});if(!n.length)return;let i="";try{let s=w("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(s))i=w(`/proc/${s}/comm`,"utf8").trim()}catch{}if(/^X/.test(i))return;for(let s of n)oe(s,{force:!0})}var x="REASON_DESKTOP_KEEP",J="reason-desktop-keep",de=new RegExp(`^${J} ([1-9]\\d{0,9}) (\\d{1,20})$`),U="reason-desktop-wedged",ue=new RegExp(`^${U} (display|browser)$`),fe=32,me=5000,I=null,k=new Set,f=new Map;function Al(e){let o=(t)=>/^\/sys\/fs\/cgroup\/[A-Za-z0-9._/-]+$/.test(t)&&!t.split("/").includes("..");I=e&&o(e.join)&&o(e.keep)?e:null}function g(e,o){try{return w(`/proc/${e}/${o}`,"utf8")}catch{return null}}function m(e){let o=g(e,"stat");if(!o)return null;let t=o.slice(o.lastIndexOf(")")+2).split(" "),n=Number(t[1]);return Number.isSafeInteger(n)&&/^\d+$/.test(t[19]??"")?{ppid:n,start:t[19]}:null}function Ue(e){if(process.env[x]!=="1"||!e)return;let o=m(e)?.start;if(o)process.stderr.write(`${J} ${e} ${o}
3
+ `)}function wr(e){if(process.env[x]==="1")process.stderr.write(`${U} ${e}
4
+ `)}function br(e,o){if(process.env[x]!=="1")return;let t=process.getuid?.(),n=[];try{n=ee("/proc")}catch{return}for(let i of n){if(!/^\d+$/.test(i))continue;let s=Number(i);try{if(C(`/proc/${i}`).uid!==t||g(s,"comm")?.trim()!==e)continue;if(!(g(s,"cmdline")??"").split("\x00").includes(o))continue}catch{continue}Ue(s)}}function b(e){try{return w(D(e,"cgroup.procs"),"utf8").split(`
5
+ `).filter((o)=>/^\d+$/.test(o)).map(Number)}catch{return[]}}function M(e,o){let t=o.replace(/^\/sys\/fs\/cgroup/,"");return g(e,"cgroup")?.split(`
6
+ `).some((n)=>n===`0::${t}`)===!0}function W(e,o){let t=g(e,"status")?.split(`
7
+ `).find((n)=>n.startsWith("Uid:"))?.slice(4).trim().split(/\s+/)??[];return t.length===4&&t.every((n)=>Number(n)===o)}function ge(e){let o=e;for(let t=0;t<64&&o>1;t++){let n=m(o);if(!n)return!1;if(k.has(o))return!1;if(f.get(o)===n.start)return!0;o=n.ppid}return!1}function q(e,o){for(let[t,n]of f)if(m(t)?.start!==n)f.delete(t);if(!f.size)return;for(let t=0;t<8;t++){let n=0;for(let i of b(e.join)){let s=m(i)?.start;if(!s||!ge(i)||!W(i,o))continue;if(!M(i,e.join)||m(i)?.start!==s)continue;try{O(D(e.keep,"cgroup.procs"),String(i))}catch{continue}if(m(i)?.start!==s){e.log?.("vm_hands.desktop_kept",{cause:"pid_reused"});continue}n++}if(!n)return}}function ye(e,o,t,n){if(f.size>=fe||f.get(t)===n||k.has(t))return!1;if(m(t)?.start!==n||!W(t,o)||!M(t,e.join))return!1;let i="";try{i=te(`/proc/${t}/exe`)}catch{return!1}if(!e.programs.includes(i))return!1;return f.set(t,n),q(e,o),!0}function H(e){let o=b(e.keep),t=Number(ke(D(e.keep,"memory.current")));if(Number.isSafeInteger(t)&&t>0)return{count:o.length,bytes:t};let n=0;for(let i of o)n+=Number(/^VmRSS:\s+(\d+) kB$/m.exec(g(i,"status")??"")?.[1]??0);return{count:o.length,bytes:n*1024}}function ke(e){try{return w(e,"utf8").trim()}catch{return""}}async function be(e,o){let t=H(e);if(!t.count)return;let n=D(e.keep,"cgroup.freeze");try{O(n,"1")}catch{return}let i=Date.now()+me;try{for(let s=b(e.keep);s.length&&Date.now()<i;s=b(e.keep)){for(let c of s)if(M(c,e.keep))try{process.kill(c,"SIGKILL")}catch{}await new Promise((c)=>setTimeout(c,10))}}finally{try{O(n,"0")}catch{}}f.clear(),e.log?.("vm_hands.desktop_reset",{code:o,...t,value:b(e.keep).length})}function vr(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{pe(e)}catch{}let i=n.command??ce(),s=I&&(o.op==="display"||o.op==="automation")?I:null,c=[se,`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...i],[V,...Y]=s?["/bin/sh","-c",`echo $$ > '${D(s.join,"cgroup.procs")}' 2>/dev/null; exec "$@"`,"desktop-join",...c]:c;return new Promise((Z,R)=>{let p=(n.spawnProcess??Q)(V,Y,{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin",...s?{[x]:"1"}:{}}}),h=s&&p.pid?p.pid:null;if(h)k.add(h);let L=0,A=null,E="",K=[],B=0,u="",S=null,j=!1,v,G=(l)=>{try{process.kill(-p.pid,l)}catch{p.kill(l)}},X=(l)=>{S??=l,G("SIGTERM"),v??=setTimeout(()=>G("SIGKILL"),le)},T=()=>X(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",T,{once:!0});let F=(l)=>{if(j)return;if(j=!0,clearTimeout(v),t.removeEventListener("abort",T),s&&h){if(k.delete(h),q(s,e.uid),L)s.log?.("vm_hands.desktop_kept",{value:L,...H(s)});if(A&&k.size===0){be(s,`${A}_wedged`).catch(()=>{return}).finally(l);return}}l()};if(p.stdout.on("data",(l)=>{if(B+=l.byteLength,B>ie)X(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else K.push(l)}),p.stderr.setEncoding("utf8").on("data",(l)=>{if(!s){u=(u+l).slice(-P);return}let _=(E+l).split(`
8
+ `);E=(_.pop()??"").slice(-P);for(let a of _){let d=de.exec(a),y=d?null:ue.exec(a);if(d){if(ye(s,e.uid,Number(d[1]),d[2]))L++}else if(y)A=y[1];else u=(u+a+`
9
+ `).slice(-P)}}),p.stdin.on("error",()=>{}),p.once("error",()=>F(()=>R(S??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),p.once("close",(l,_)=>F(()=>{if(S)return R(S);if(E)u=(u+E).slice(-P);let a=ae(Buffer.concat(K).toString("utf8"));if(N(a)&&a.ok===!0&&N(a.result))return Z(a.result);let d=N(a)&&a.ok===!1&&typeof a.code==="string"&&typeof a.message==="string"?new r(a.code.slice(0,120),a.message.slice(0,2000)):null,y=`exited ${l??_}${d?"":" with no reply"}`,z=u.trim().split(`
10
+ `).at(-1)?.slice(-300)??"";if(!d||d.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${y}${u?`: ${u.trim().slice(-500)}`:""}
11
+ `);if(d)return R(d);R(new r("desktop_delegate_failed",`Reason's desktop operation failed (${y}${z?`: ${z}`:""}).`))})),t.aborted)T();p.stdin.end(JSON.stringify(o))})}async function Yo(e,o,t,n={}){let i=await vr(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(i.code)||typeof i.stdout!=="string"||typeof i.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:i.code,stdout:Buffer.from(i.stdout,"base64"),stderr:i.stderr}}
12
+ export{Al,Ue,wr,br,vr,Yo};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{t,o,_,d,n,we,A,i}from"./vm-hands-entry-lite-k5ytpgzz.js";var zn=25,e=1e5,a=/^[0-9a-f]{64}$/,to=n({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(e),received:o().int().min(0).max(e)}),s=20,r=n({name:t().min(1).max(100),address:t().min(1).max(300).optional()}),m=n({name:t().min(1).max(100),agent:t().min(1).max(100)}),h=n({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:_().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(zn).optional(),message_counts:d(to).max(14).optional().catch(void 0),endpoint:t().regex(a).optional().catch(void 0),hosted:d(r).max(50).optional().catch(void 0)}),l=A("kind",[n({id:t(),kind:i("who"),all:_().optional()}),n({id:t(),kind:i("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:_(),reply_to:t().max(100).optional(),notify:_().optional()})]),ba=n({job:l.nullable(),retry_after_seconds:o().optional(),hosted:d(m).max(s).optional().catch(void 0)}),p=n({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:_(),tier:t().max(10).optional()}),c=n({person:t(),machine:t(),online:_()}),y=n({team:t().nullable(),sessions:d(p).max(2000),machines:d(c).max(500),all:_().optional()}),x=n({address:t().max(300),state:t().max(40),note:t().max(500)}),S=we([n({who:y}),n({sent:n({ids:d(t().max(100)).max(500),recipients:d(t().max(300)).max(500),from:t().max(300),deliveries:d(x).max(500).optional()})}),n({error:t().min(1).max(2000)})]),g=n({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),f=n({messages:d(g).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:_().optional(),session:t().min(1).max(100).optional().catch(void 0),machine:t().min(1).max(200).optional().catch(void 0)});
3
- export{zn,to,ba};
2
+ import{t,o,_,d,n,we,P,i}from"./vm-hands-entry-lite-zpvr7wc6.js";var Vn=25,e=1e5,a=/^[0-9a-f]{64}$/,io=n({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(e),received:o().int().min(0).max(e)}),s=20,r=n({name:t().min(1).max(100),address:t().min(1).max(300).optional()}),m=n({name:t().min(1).max(100),agent:t().min(1).max(100)}),h=n({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:_().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(Vn).optional(),message_counts:d(io).max(14).optional().catch(void 0),endpoint:t().regex(a).optional().catch(void 0),hosted:d(r).max(50).optional().catch(void 0)}),l=P("kind",[n({id:t(),kind:i("who"),all:_().optional()}),n({id:t(),kind:i("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:_(),reply_to:t().max(100).optional(),notify:_().optional()})]),Pa=n({job:l.nullable(),retry_after_seconds:o().optional(),hosted:d(m).max(s).optional().catch(void 0)}),p=n({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:_(),tier:t().max(10).optional()}),c=n({person:t(),machine:t(),online:_()}),y=n({team:t().nullable(),sessions:d(p).max(2000),machines:d(c).max(500),all:_().optional()}),x=n({address:t().max(300),state:t().max(40),note:t().max(500)}),S=we([n({who:y}),n({sent:n({ids:d(t().max(100)).max(500),recipients:d(t().max(300)).max(500),from:t().max(300),deliveries:d(x).max(500).optional()})}),n({error:t().min(1).max(2000)})]),g=n({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),f=n({messages:d(g).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:_().optional(),session:t().min(1).max(100).optional().catch(void 0),machine:t().min(1).max(200).optional().catch(void 0)});
3
+ export{Vn,io,Pa};
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{$i,Mi,vt,Yt,as,cs}from"./vm-hands-entry-lite-6jxshhps.js";import{rc,nc}from"./vm-hands-entry-lite-tcmye5ny.js";import{Ai,Pi,mn,yr,l,ac,Ri,cc,gn,Vt,_n}from"./vm-hands-entry-lite-vdv4nm5f.js";import{s}from"./vm-hands-entry-lite-zawytz09.js";import{G}from"./vm-hands-entry-lite-8xv6c0rm.js";import{randomUUID as p}from"crypto";import{chmodSync as Z,closeSync as J,constants as C,existsSync as A,fstatSync as ke,lstatSync as h,mkdirSync as q,openSync as Ie,readFileSync as K,readdirSync as re,readlinkSync as w,realpathSync as T,renameSync as S,rmSync as I,statSync as V,symlinkSync as Q,unlinkSync as R,writeFileSync as U}from"fs";import{basename as H,dirname as E,isAbsolute as We,join as m,relative as Xe,resolve as M,sep as me}from"path";import{spawnSync as ee}from"child_process";import{createRequire as Te}from"module";var ae=1,xe=1,Ze=128,Qe=65536,Vc="https://reasonmachines.com/api/runtime-manifest-v2",et=30000,tt=600000,Ee=1e4,nt=60000,rt=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var Me=/^[a-z0-9_.-]{1,80}$/,it=64,at="so.ara.device-broker",Pe=[at,"com.reasonmachines.device-broker"],An=Mi(Pe),we=["com.apple.security.cs.allow-jit","com.apple.security.cs.allow-unsigned-executable-memory"],ot=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function W(e){if(e?.aborted)throw new l("update_cancelled","Managed runtime update request was cancelled.")}function fe(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function ge(e,t,n=[]){let r=new Set([...t,...n]);return t.every((i)=>(i in e))&&Object.keys(e).every((i)=>r.has(i))}function b(e){return typeof e==="string"&&rt.test(e)}function De(e){return typeof e==="string"&&!Number.isNaN(Date.parse(e))&&new Date(e).toISOString()===e}function st(e){return yr.includes(e)}function x(e){q(e,{recursive:!0,mode:448}),Z(e,448)}function Oe(e,t){x(E(e));let n=`${e}.${process.pid}.${p()}.tmp`;try{U(n,t,{mode:384,flag:"wx"}),Z(n,384),S(n,e)}finally{if(A(n))R(n)}}function Nt(e={}){if((e.platform??process.platform)!=="darwin")throw new l("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let n=e.environment??process.env,r=P(n,"REASON_CLI_CHANNEL")==="staging",i=r?P(n,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,o=e.root!==void 0||Boolean(i&&We(i))?null:m(e.home??s(),"Library","Application Support"),c=e.root??(o?m(o,r?"Reason Staging":"Reason","CLI"):i);return{executableName:"reason",root:c,...o?{legacyRoot:m(o,"Ara",...r?["staging","runtime"]:["runtime"])}:{},versions:m(c,"versions"),current:m(c,"current"),previous:m(c,"previous"),brokerLock:m(c,"broker.lock"),transitionLock:m(c,"transition.lock"),lifecycleEvents:m(c,"lifecycle-events")}}function hl(e){let t=e.legacyRoot;if(!t)return null;return{root:t,versions:m(t,"versions"),current:m(t,"current"),previous:m(t,"previous"),brokerLock:m(t,"broker.lock"),transitionLock:m(t,"transition.lock"),lifecycleEvents:m(t,"lifecycle-events")}}function F(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let n=m(e.versions,t,"ara");if(!e.executableName)return n;let r=m(e.versions,t,e.executableName),i=(c)=>{try{return h(c),!0}catch(d){if(d.code==="ENOENT")return!1;throw d}},a=i(n),o=i(r);if(a&&o)throw new l("installed_artifact_mismatch","Ambiguous managed runtime executable layout.");return a?n:r}function oe(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");return _e(F(e,t))}function _e(e){return m(E(e),H(e)==="reason"?Pi:Ai)}function Ce(e,t){if(!b(e)||!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let[n,r]=e.split("-",2),[i,a]=t.split("-",2),o=n.split(".").map(Number),c=i.split(".").map(Number);for(let _=0;_<3;_+=1){let g=o[_]-c[_];if(g!==0)return g<0?-1:1}if(r===void 0||a===void 0){if(r===a)return 0;return r===void 0?1:-1}let d=r.split("."),u=a.split("."),f=Math.max(d.length,u.length);for(let _=0;_<f;_+=1){let g=d[_],y=u[_];if(g===void 0||y===void 0){if(g===y)return 0;return g===void 0?-1:1}if(g===y)continue;let v=/^\d+$/.test(g),L=/^\d+$/.test(y);if(v&&L)return Number(g)<Number(y)?-1:1;if(v!==L)return v?-1:1;return g<y?-1:1}return 0}function ct(e=process.arch){let t=`darwin-${e}`;if(!st(t))throw new l("unsupported_architecture","The managed Reason runtime supports only Apple Silicon and Intel Macs.");return t}function Re(e){return[...e.matchAll(/<key>\s*([^<]+?)\s*<\/key>/g)].map((t)=>t[1].trim())}function pe(e){let t=e.match(/^CodeDirectory .*$/gm)??[];return t.length>0&&t.every((n)=>(/ flags=0x[0-9a-f]+\(([^)]*)\)(?: |$)/.exec(n)?.[1]?.split(/[ ,]+/).filter(Boolean)??[]).includes("runtime"))}function lt(e){let t=`TeamIdentifier=${$i}`,n=Pe.map((a)=>`Identifier=${a}`),r=Re(e.brokerEntitlements),i=Re(e.credentialLibraryEntitlements);if(!e.brokerDetail.split(`
2
+ import{R}from"./vm-hands-entry-lite-z65xva21.js";import{Fi,ji,St,Yt,ms,gs}from"./vm-hands-entry-lite-t86kt9jz.js";import{uc,dc}from"./vm-hands-entry-lite-q62g6sx0.js";import{Ti,Ii,bn,yr,l,mc,Di,gc,vn,Gt,Sn}from"./vm-hands-entry-lite-1b21avcs.js";import{s}from"./vm-hands-entry-lite-12ck5swp.js";import{G}from"./vm-hands-entry-lite-pg7nnyc6.js";import{randomUUID as L}from"crypto";import{chmodSync as Z,closeSync as J,constants as C,existsSync as S,fstatSync as ke,lstatSync as h,mkdirSync as q,openSync as Ie,readFileSync as K,readdirSync as re,readlinkSync as w,realpathSync as x,renameSync as k,rmSync as T,statSync as V,symlinkSync as Q,unlinkSync as p,writeFileSync as U}from"fs";import{basename as H,dirname as E,isAbsolute as je,join as m,relative as We,resolve as M,sep as me}from"path";import{spawnSync as ee}from"child_process";import{createRequire as Te}from"module";var ae=1,xe=1,Xe=128,Qe=65536,Qc="https://reasonmachines.com/api/runtime-manifest-v2",et=30000,tt=600000,Ee=1e4,nt=60000,rt=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var Me=/^[a-z0-9_.-]{1,80}$/,it=64,at="so.ara.device-broker",Pe=[at,"com.reasonmachines.device-broker"],Ln=ji(Pe),we=["com.apple.security.cs.allow-jit","com.apple.security.cs.allow-unsigned-executable-memory"],ot=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function W(e){if(e?.aborted)throw new l("update_cancelled","Managed runtime update request was cancelled.")}function fe(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function ge(e,t,n=[]){let r=new Set([...t,...n]);return t.every((i)=>(i in e))&&Object.keys(e).every((i)=>r.has(i))}function b(e){return typeof e==="string"&&rt.test(e)}function De(e){return typeof e==="string"&&!Number.isNaN(Date.parse(e))&&new Date(e).toISOString()===e}function st(e){return yr.includes(e)}function P(e){q(e,{recursive:!0,mode:448}),Z(e,448)}function Oe(e,t){P(E(e));let n=`${e}.${process.pid}.${L()}.tmp`;try{U(n,t,{mode:384,flag:"wx"}),Z(n,384),k(n,e)}finally{if(S(n))p(n)}}function Lt(e={}){if((e.platform??process.platform)!=="darwin")throw new l("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let n=e.environment??process.env,r=R(n,"REASON_CLI_CHANNEL")==="staging",i=r?R(n,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,o=e.root!==void 0||Boolean(i&&je(i))?null:m(e.home??s(),"Library","Application Support"),c=e.root??(o?m(o,r?"Reason Staging":"Reason","CLI"):i);return{executableName:"reason",root:c,...o?{legacyRoot:m(o,"Ara",...r?["staging","runtime"]:["runtime"])}:{},versions:m(c,"versions"),current:m(c,"current"),previous:m(c,"previous"),brokerLock:m(c,"broker.lock"),transitionLock:m(c,"transition.lock"),lifecycleEvents:m(c,"lifecycle-events")}}function bl(e){let t=e.legacyRoot;if(!t)return null;return{root:t,versions:m(t,"versions"),current:m(t,"current"),previous:m(t,"previous"),brokerLock:m(t,"broker.lock"),transitionLock:m(t,"transition.lock"),lifecycleEvents:m(t,"lifecycle-events")}}function F(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let n=m(e.versions,t,"ara");if(!e.executableName)return n;let r=m(e.versions,t,e.executableName),i=(c)=>{try{return h(c),!0}catch(d){if(d.code==="ENOENT")return!1;throw d}},a=i(n),o=i(r);if(a&&o)throw new l("installed_artifact_mismatch","Ambiguous managed runtime executable layout.");return a?n:r}function oe(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");return _e(F(e,t))}function _e(e){return m(E(e),H(e)==="reason"?Ii:Ti)}function Ce(e,t){if(!b(e)||!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let[n,r]=e.split("-",2),[i,a]=t.split("-",2),o=n.split(".").map(Number),c=i.split(".").map(Number);for(let _=0;_<3;_+=1){let g=o[_]-c[_];if(g!==0)return g<0?-1:1}if(r===void 0||a===void 0){if(r===a)return 0;return r===void 0?1:-1}let d=r.split("."),u=a.split("."),f=Math.max(d.length,u.length);for(let _=0;_<f;_+=1){let g=d[_],y=u[_];if(g===void 0||y===void 0){if(g===y)return 0;return g===void 0?-1:1}if(g===y)continue;let v=/^\d+$/.test(g),A=/^\d+$/.test(y);if(v&&A)return Number(g)<Number(y)?-1:1;if(v!==A)return v?-1:1;return g<y?-1:1}return 0}function ct(e=process.arch){let t=`darwin-${e}`;if(!st(t))throw new l("unsupported_architecture","The managed Reason runtime supports only Apple Silicon and Intel Macs.");return t}function Re(e){return[...e.matchAll(/<key>\s*([^<]+?)\s*<\/key>/g)].map((t)=>t[1].trim())}function pe(e){let t=e.match(/^CodeDirectory .*$/gm)??[];return t.length>0&&t.every((n)=>(/ flags=0x[0-9a-f]+\(([^)]*)\)(?: |$)/.exec(n)?.[1]?.split(/[ ,]+/).filter(Boolean)??[]).includes("runtime"))}function lt(e){let t=`TeamIdentifier=${Fi}`,n=Pe.map((a)=>`Identifier=${a}`),r=Re(e.brokerEntitlements),i=Re(e.credentialLibraryEntitlements);if(!e.brokerDetail.split(`
3
3
  `).includes(t)||!e.brokerDetail.split(`
4
4
  `).some((a)=>n.includes(a))||!pe(e.brokerDetail)||r.length!==we.length||we.some((a)=>!new RegExp(`<key>\\s*${a.replaceAll(".","\\.")}\\s*</key>\\s*<true\\s*/>`).test(e.brokerEntitlements)))throw new l("invalid_code_signature","Managed runtime broker has an invalid Reason signature, identifier, or entitlement set.");if(!e.credentialLibraryDetail.split(`
5
- `).includes(t)||!pe(e.credentialLibraryDetail)||i.length!==0)throw new l("invalid_code_signature","Managed runtime credential library has an invalid signature or entitlement.")}function D(e,t){let n=ee("/usr/bin/codesign",e,{stdio:["ignore","pipe","pipe"]});if(n.status!==0)throw new l("invalid_code_signature",t);return[new TextDecoder().decode(n.stdout??new Uint8Array),new TextDecoder().decode(n.stderr??new Uint8Array)].join("")}var ye=(e,t)=>{D(["--verify","--strict","--verbose=2",e],"Managed runtime broker code signature is invalid."),D(["--verify","--strict","--verbose=2",t],"Managed runtime credential library code signature is invalid."),lt({brokerDetail:D(["-d","--verbose=4",e],"Managed runtime broker signer could not be inspected."),brokerEntitlements:D(["-d","--entitlements",":-",e],"Managed runtime broker entitlements could not be inspected."),credentialLibraryDetail:D(["-d","--verbose=4",t],"Managed runtime credential library signer could not be inspected."),credentialLibraryEntitlements:D(["-d","--entitlements",":-",t],"Managed runtime credential library entitlements could not be inspected.")})};async function dt(e,t,n){let r=e.headers.get("content-length");if(r!==null){let f=Number(r);if(!Number.isSafeInteger(f)||f<0||f>t)throw new l("response_too_large","Managed runtime response exceeded its size limit.")}if(!e.body){let f=new Uint8Array(await e.arrayBuffer());if(f.byteLength>t)throw new l("response_too_large","Managed runtime response exceeded its size limit.");return f}let i=e.body.getReader(),a=[],o=0,c=()=>{if(!n)return i.read();return new Promise((f,_)=>{let g=()=>{n.removeEventListener("abort",g),i.cancel(n.reason).catch(()=>{}),_(n.reason??new DOMException("Aborted","AbortError"))};if(n.aborted){g();return}n.addEventListener("abort",g,{once:!0}),i.read().then((y)=>{n.removeEventListener("abort",g),f(y)},(y)=>{n.removeEventListener("abort",g),_(y)})})};try{while(!0){let f=await c();if(f.done)break;if(o+=f.value.byteLength,o>t)throw await i.cancel(),new l("response_too_large","Managed runtime response exceeded its size limit.");a.push(f.value)}}finally{try{i.releaseLock()}catch{}}let d=new Uint8Array(o),u=0;for(let f of a)d.set(f,u),u+=f.byteLength;return d}async function Wr(e){let t;try{t=new URL(e.url)}catch{throw new l("invalid_update_url","Managed runtime update URL is invalid.")}if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new l("invalid_update_url","Managed runtime update URL must use HTTPS.");let n=new AbortController,r,i=()=>{r??="caller",n.abort(e.signal?.reason)};if(e.signal?.aborted)i();else e.signal?.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>{r??="timeout",n.abort(Error("managed runtime fetch timed out"))},e.timeoutMs),o=(c,d)=>{if(c instanceof l)return c;if(r==="caller")return new l("update_cancelled","Managed runtime update request was cancelled.");if(r==="timeout")return new l("update_fetch_timeout","Managed runtime update request timed out.");return new l("update_fetch_failed",d)};try{let c;try{if(c=await e.fetchImpl(t,{headers:{accept:e.accept},signal:n.signal}),n.signal.aborted)throw o(n.signal.reason,"Managed runtime update request was cancelled.")}catch(d){throw o(d,"Managed runtime update request failed.")}if(!c.ok)throw new l("update_http_error","Managed runtime update request was rejected.");if(c.url&&new URL(c.url).protocol!=="https:")throw new l("insecure_redirect","Managed runtime update redirected to an insecure URL.");try{let d=await dt(c,e.maximumBytes,n.signal);if(n.signal.aborted)throw o(n.signal.reason,"Managed runtime update response was cancelled.");return d}catch(d){throw o(d,"Managed runtime update response failed.")}}finally{clearTimeout(a),e.signal?.removeEventListener("abort",i)}}async function Ve(e,t,n=Ee,r){let i=typeof n==="number"?n:Ee,a=typeof n==="number"?r:n;if(a?.aborted)return!1;let o=await rc([e,"--version"],{timeoutMs:i,...a?{signal:a}:{}});return o.exitCode===0&&o.stdout.trim().replace(/^v/,"")===t}async function ut(e){let t=!1,n=null,r=null,i=(a)=>{try{N(e.paths,a,{now:e.now})}catch{}};try{let a=e.home??s();if(!as(e.manifest.version,a))return{status:"current"};r=Yt(a);let o=await Wr({url:new URL(ac,e.manifest.artifacts[e.target].broker.url).toString(),maximumBytes:mn,fetchImpl:async(g,y)=>{let v=await e.fetchImpl(g,y);return t=v.status===404,v},timeoutMs:e.timeoutMs,accept:"application/json",signal:e.signal}),{manifest:c}=cc(new TextDecoder().decode(o),e.trustedKeys);if(c.version!==e.manifest.version||c.published_at!==e.manifest.published_at)throw new l("identity_manifest_mismatch","Background identity manifest names another release.");let d=c.artifacts[e.target],u=await Wr({url:d.url,maximumBytes:d.size_bytes,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,accept:"application/octet-stream",signal:e.signal});Vt(u,d),x(e.workDirectory),n=m(e.workDirectory,`.identity-${process.pid}-${p()}`),q(n,{mode:448});let f=m(n,"identity.tgz");if(U(f,u,{mode:384,flag:"wx"}),ee("/usr/bin/tar",["-xzf",f,"-C",n],{stdio:"ignore",timeout:60000}).status!==0)throw new l("identity_extract_failed","Background identity archive could not be extracted.");return cs({sourceApp:m(n,"Reason.app"),home:a,releaseSigned:!0,...e.command?{command:e.command}:{}}),i({event:"identity.refresh_completed",runtime_version:e.manifest.version,...r?{from_version:r}:{},to_version:e.manifest.version}),{status:"installed"}}catch(a){if(t)return{status:"unpublished"};let o=a instanceof l||a instanceof vt?a.code:"identity_install_failed";return process.stderr.write(`Reason background identity: identity_update_failed (${o})
6
- `),i({event:"identity.refresh_failed",runtime_version:e.manifest.version,...r?{from_version:r}:{},to_version:e.manifest.version,reason_code:o}),{status:"failed",code:o}}finally{if(n)I(n,{recursive:!0,force:!0})}}async function fl(e){if(!b(e.currentVersion))throw new l("invalid_version","Invalid current managed runtime version.");let t=e.paths??Nt(),n=e.target??ct(),r=e.fetchImpl??fetch,i=e.timeoutMs??et,a=e.timeoutMs??tt,o=e.healthCheck??((_,g,y)=>Ve(_,g,nt,y)),c=e.verifyCodeSignatures??ye,d=e.now?.()??new Date,u,f=!1;N(t,{event:"update.check_started",runtime_version:e.currentVersion,from_version:e.currentVersion},{now:()=>d});try{await pt({paths:t,verifyCodeSignatures:c,healthCheck:o});let _=await Wr({url:e.manifestUrl??Vc,maximumBytes:mn,fetchImpl:r,timeoutMs:i,accept:"application/json",signal:e.signal}),g=Ri(new TextDecoder().decode(_),e.trustedKeys);u=g.manifest.version;let y=()=>ut({paths:t,...e.now?{now:e.now}:{},manifest:g.manifest,target:n,trustedKeys:e.trustedKeys,fetchImpl:r,timeoutMs:a,workDirectory:t.versions,...e.home?{home:e.home}:{},...e.identityCommand?{command:e.identityCommand}:{},...e.signal?{signal:e.signal}:{}});if(Ce(u,e.currentVersion)<=0)return N(t,{event:"update.not_available",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u,duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),Ae(t,e.home),{status:"not_available",currentVersion:e.currentVersion,offeredVersion:u,...u===e.currentVersion?{identity:await y()}:{}};let v=g.manifest.artifacts[n];N(t,{event:"update.download_started",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u},{now:e.now});let L=await Wr({url:v.broker.url,maximumBytes:v.broker.size_bytes,fetchImpl:r,timeoutMs:a,accept:"application/octet-stream",signal:e.signal});Vt(L,v.broker),W(e.signal);let j=await Wr({url:v.credential_library.url,maximumBytes:v.credential_library.size_bytes,fetchImpl:r,timeoutMs:a,accept:"application/octet-stream",signal:e.signal});Vt(j,v.credential_library),N(t,{event:"update.downloaded",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u},{now:e.now}),N(t,{event:"update.verified",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u},{now:e.now}),W(e.signal);let he=mt({paths:t,version:u,artifact:v.broker,bytes:L,credentialLibraryArtifact:v.credential_library,credentialLibraryBytes:j,verifyCodeSignatures:c}),be;try{be=await o(he.executablePath,u,e.signal)}catch(B){throw W(e.signal),B}if(W(e.signal),!be)throw new l("pre_activation_health_failed","Managed runtime preflight failed.");let k=Et(t,u);if(!k.changed&&k.toVersion!==u)return N(t,{event:"update.not_available",runtime_version:k.toVersion,from_version:k.toVersion,to_version:u,duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),{status:"not_available",currentVersion:k.toVersion,offeredVersion:u};if(f=k.changed,!await o(t.current,u)){if(k.fromVersion){let B=Ge(t,u);N(t,{event:"update.rollback",runtime_version:B.toVersion,from_version:B.fromVersion,to_version:B.toVersion,reason_code:"post_activation_health_failed"},{now:e.now})}else Je(t,u);throw O(t),f=!1,new l("post_activation_health_failed","Managed runtime activation failed.")}return O(t),Ae(t,e.home),N(t,{event:"update.activated",runtime_version:u,from_version:e.currentVersion,to_version:u,duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),{status:"activated",fromVersion:e.currentVersion,toVersion:u,installed:he.installed,identity:await y()}}catch(_){throw N(t,{event:"update.failed",runtime_version:f?u??e.currentVersion:e.currentVersion,from_version:e.currentVersion,...u?{to_version:u}:{},reason_code:_ instanceof l?_.code:"update_failed",duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),_}}function Le(e,t,n){try{let r=h(E(e));if(!r.isDirectory()||r.isSymbolicLink())return!1;let i=h(e);if(!i.isFile()||i.isSymbolicLink()||i.size!==t.size_bytes)return!1;let a=_e(e),o=h(a);return o.isFile()&&!o.isSymbolicLink()&&o.size===n.size_bytes&&gn(K(e))===t.sha256&&gn(K(a))===n.sha256}catch{return!1}}function mt(e){let t=F(e.paths,e.version);Vt(e.bytes,e.artifact),Vt(e.credentialLibraryBytes,e.credentialLibraryArtifact);let n=e.verifyCodeSignatures??ye;if(x(e.paths.root),x(e.paths.versions),A(E(t))){if(!Le(t,e.artifact,e.credentialLibraryArtifact))throw new l("installed_artifact_mismatch","The installed runtime version does not match the verified artifact.");return n(t,oe(e.paths,e.version)),{installed:!1,executablePath:t}}let r=m(e.paths.versions,`.install-${e.version}-${process.pid}-${p()}`),i=m(r,H(t)),a=_e(i);q(r,{mode:448});try{U(i,e.bytes,{mode:448,flag:"wx"}),Z(i,448),U(a,e.credentialLibraryBytes,{mode:448,flag:"wx"}),Z(a,448),n(i,a);try{S(r,E(t))}catch(o){if(!Le(t,e.artifact,e.credentialLibraryArtifact))throw o;return{installed:!1,executablePath:t}}return{installed:!0,executablePath:t}}finally{I(r,{recursive:!0,force:!0})}}function ft(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");return`versions/${t}/${H(F(e,t))}`}function te(e,t){x(E(e));let n=`${e}.${process.pid}.${p()}.tmp`;try{Q(t,n),S(n,e)}finally{if(A(n))R(n)}}var Ue=/^\.(?:ara|reason)-worker-(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)-(darwin-(?:arm64|x64))\.([0-9A-Za-z]{6})$/,gt=new Set(["reason","ara"]);function Fe(e,t){let n=E(e),r=M(n,t),i=E(r),a=Ue.exec(H(i));if(!gt.has(H(r))||E(i)!==n||!a||!b(a[1])||!yr.includes(a[2]))return!1;try{return h(i).isDirectory()&&E(T(i))===T(n)&&h(r).isFile()&&h(_n(i)).isFile()}catch(o){if(o.code==="ENOENT")return!1;throw o}}function Be(e,t,n){try{if(w(e)!==t)return!1;R(e)}catch(r){if(r.code==="ENOENT")return!1;throw r}try{return Q(n,e),!0}catch(r){if(r.code==="EEXIST")return!1;try{Q(t,e)}catch(i){if(i.code!=="EEXIST")throw i}throw r}}function _t(e,t){if(!e.legacyRoot)return!1;let n;try{if(!h(t).isSymbolicLink())return!1;n=w(t)}catch(i){if(i.code==="ENOENT")return!1;throw i}if(M(E(t),n)!==m(e.legacyRoot,"current"))return!1;if(!Be(t,n,e.current))return!1;let r=Ye(e);if(r)N(e,{event:"service.launcher_adopted",runtime_version:r,to_version:r,reason_code:"legacy_runtime_root"});return!0}function yt(e,t){let n=m(e,".local","bin"),r=m(n,"ara"),i=m(n,"reason"),a=h(r,{throwIfNoEntry:!1});if(a?.isSymbolicLink()&&w(r)==="reason")return i;if(a||!h(i,{throwIfNoEntry:!1})?.isSymbolicLink())return r;let o=w(i);return o===t.current||Fe(i,o)?i:r}function ml(e){let t=e.launcherPath??yt(e.home??s(),e.paths);try{if(h(t).isSymbolicLink()){let r=w(t);if(r===e.paths.current)return"managed";if(Fe(t,r)&&Be(t,r,e.paths.current)){let i=se(e.paths.current,e.paths.executableName)??"unknown";return N(e.paths,{event:"service.launcher_adopted",runtime_version:i,to_version:i,reason_code:"legacy_curl_entrypoint"}),"adopted"}if(_t(e.paths,t))return"adopted"}return"conflict"}catch(n){if(n.code!=="ENOENT")throw n}q(E(t),{recursive:!0,mode:448});for(let n=0;n<4;n+=1)try{return Q(e.paths.current,t),"created"}catch(r){if(r.code!=="EEXIST")throw r;try{return h(t).isSymbolicLink()&&w(t)===e.paths.current?"managed":"conflict"}catch(i){if(i.code!=="ENOENT")throw i}}return"conflict"}function se(e,t){let n;try{if(!h(e).isSymbolicLink())return null;n=w(e)}catch{return null}let r=n.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return r&&(r[2]==="ara"||r[2]===t)?r[1]:null}function Ye(e){return se(e.current,e.executableName)}function ne(e,t,n){let i=Xe(t,e).split(me);return i.length===2&&b(i[0])&&(i[1]==="ara"||n!==void 0&&i[1]===n)?i[0]:null}function $e(e,t){try{return h(t).isSymbolicLink()&&M(E(t),w(t))===M(e.current)}catch{return!1}}function gl(e,t=process.execPath){try{return ne(T(t),T(e.versions),e.executableName)!==null}catch{let n=M(t);return n===M(e.current)||$e(e,n)||ne(n,M(e.versions),e.executableName)!==null}}function _l(e,t=process.execPath){try{return ne(T(t),T(e.versions),e.executableName)}catch{let n=M(t);if(n===M(e.current)||$e(e,n))return Ye(e);return ne(n,M(e.versions),e.executableName)}}function ht(e,t,n=!1){let r=Ye(e);if(!r)return null;if(r===t)return{changed:!1,fromVersion:r,toVersion:r};if(!n&&Ce(t,r)<=0&&!(/^\d+\.\d+\.\d+-desktop\.v1\.\d+\.\d+\.\d+$/.test(t)&&/^\d+\.\d+\.\d+-desktopdev\./.test(r)))return{changed:!1,fromVersion:r,toVersion:r};return null}function bt(e,t,n,r=!1){let i=ht(e,t,r);if(i)return i;let a=Ye(e);if(n?.(a),a)te(e.previous,w(e.current));else if(A(e.previous))R(e.previous);return te(e.current,ft(e,t)),{changed:!0,fromVersion:a,toVersion:t}}function Et(e,t){let n=F(e,t),r=oe(e,t);if(!A(n)||!V(n).isFile()||!A(r)||!V(r).isFile())throw new l("runtime_not_installed","Managed Reason runtime version is not installed.");return ce(e,t,()=>bt(e,t,(i)=>{Rt(e,{schema_version:ae,from_version:i,to_version:t})}))}function Ge(e,t){return ce(e,t,()=>{if(Ye(e)!==t)throw new l("rollback_fence_failed","Managed runtime changed before rollback could be applied.");let n=se(e.previous,e.executableName);if(!n||n===t)throw new l("rollback_unavailable","No previous managed runtime is available.");let r=F(e,n),i=oe(e,n);if(!A(r)||!V(r).isFile()||!A(i)||!V(i).isFile())throw new l("rollback_unavailable","Previous managed runtime is not installed.");let a=w(e.previous),o=w(e.current);if(M(E(e.previous),a)!==M(r))throw new l("rollback_fence_failed","Previous runtime pointer does not match its installed layout.");return te(e.current,a),te(e.previous,o),{fromVersion:t,toVersion:n}})}function ze(){let e=ee("/bin/ps",["-axww","-o","args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000,maxBuffer:16777216});if(e.status!==0||typeof e.stdout!=="string")return null;let t=ee("/usr/sbin/lsof",["-nP","-w","-d","txt","-Fn"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:20000,maxBuffer:67108864});if(t.error||t.status!==0&&t.status!==1||!t.stdout)return null;return`${e.stdout}
7
- ${t.stdout}`}function Ae(e,t){let n=[];Mt(e,t??s());try{let r=Ye(e);if(!r||de(e))return n;let i=re(e.versions).filter((o)=>b(o));if(i.length<=2)return n;let a=ze();if(a===null)return n;ce(e,r,()=>{let o=new Set([Ye(e),se(e.previous,e.executableName)]);if(de(e))return;for(let c of i){if(o.has(c))continue;let d=m(e.versions,c);if(a.includes(`${d}${me}`))continue;try{I(d,{recursive:!0,force:!0}),n.push(c)}catch{}}})}catch{}return n}function Mt(e,t){try{let n=le(m(t,".local","bin"));if(!n)return;let r=["reason","ara"].flatMap((c)=>{try{return[M(n,w(m(n,c)))]}catch{return[]}}),i=le(e.current);if(!i||!r.some((c)=>le(c)===i))return;let a=re(n).filter((c)=>Ue.test(c)).map((c)=>m(n,c)).filter((c)=>!r.some((d)=>E(d)===c)).filter((c)=>Date.now()-h(c).mtimeMs>3600000);if(a.length===0)return;let o=ze();if(o===null)return;for(let c of a){if(o.includes(`${c}${me}`))continue;try{I(c,{recursive:!0,force:!0})}catch{}}}catch{}}function le(e){try{return T(e)}catch{return null}}function Je(e,t){ce(e,t,()=>{if(Ye(e)!==t)throw new l("rollback_fence_failed","Managed runtime changed before rollback could be applied.");R(e.current)})}function ve(e){return e.activationState??m(e.root,"activation.json")}function wt(e){return fe(e)&&ge(e,["schema_version","from_version","to_version"])&&e.schema_version===ae&&(e.from_version===null||b(e.from_version))&&b(e.to_version)}function de(e){try{let t=ve(e),n=h(t);if(!n.isFile()||n.isSymbolicLink()||n.nlink!==1||(n.mode&63)!==0||n.size>4096)throw new l("invalid_activation_state","Managed runtime activation state is invalid.");let r=JSON.parse(K(t,"utf8"));if(!wt(r))throw new l("invalid_activation_state","Managed runtime activation state is invalid.");return r}catch(t){if(t instanceof l)throw t;if(t.code==="ENOENT")return null;throw new l("invalid_activation_state","Managed runtime activation state is invalid.")}}function Rt(e,t){Oe(ve(e),JSON.stringify(t)+`
8
- `)}function O(e){try{R(ve(e))}catch(t){if(t.code!=="ENOENT")throw t}}async function pt(e){let t=de(e.paths);if(!t)return"none";let n=Ye(e.paths);if(n===t.from_version)return O(e.paths),"cleared";if(n!==t.to_version)throw new l("rollback_fence_failed","Managed runtime changed before activation recovery could be applied.");let r=e.verifyCodeSignatures??ye,i=e.healthCheck??Ve,a=!1;try{let o=F(e.paths,t.to_version);r(o,oe(e.paths,t.to_version)),a=await i(o,t.to_version)}catch{a=!1}if(a)return O(e.paths),N(e.paths,{event:"update.activated",runtime_version:t.to_version,...t.from_version?{from_version:t.from_version}:{},to_version:t.to_version,reason_code:"restart_recovery"}),"committed";if(t.from_version){let o=Ge(e.paths,t.to_version);return O(e.paths),N(e.paths,{event:"update.rollback",runtime_version:o.toVersion,from_version:o.fromVersion,to_version:o.toVersion,reason_code:"restart_recovery"}),"rolled_back"}return Je(e.paths,t.to_version),O(e.paths),N(e.paths,{event:"update.rollback",runtime_version:t.to_version,from_version:t.to_version,reason_code:"restart_recovery"}),"rolled_back"}function Lt(e){return fe(e)&&ge(e,["schema_version","pid","nonce","started_at","runtime_version"])&&e.schema_version===ae&&typeof e.pid==="number"&&Number.isSafeInteger(e.pid)&&e.pid>0&&typeof e.nonce==="string"&&/^[0-9a-f-]{36}$/.test(e.nonce)&&De(e.started_at)&&b(e.runtime_version)}function Ke(e,t){try{let n=h(e);if(!n.isDirectory()||!G(n))return null;let r=Ie(m(e,t),C.O_RDONLY|C.O_NOFOLLOW|C.O_NONBLOCK);try{let i=ke(r);if(!i.isFile()||i.nlink!==1||!G(i)||i.size>4096)return null;return K(r,"utf8")}finally{J(r)}}catch{return null}}function ue(e){try{let t=JSON.parse(Ke(e,"owner.json")??"null");return Lt(t)?t:null}catch{return null}}function He(e){try{return process.kill(e,0),!0}catch(t){return!(t instanceof Error&&("code"in t)&&t.code==="ESRCH")}}var Ne="lease",At=2,St=4,Y;function kt(){if(Y!==void 0)return Y;if(Y=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let e;try{e=Te(import.meta.url)("bun:ffi")}catch{return null}let t=process.platform==="darwin"?"__error":"__errno_location",n=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let r of n)try{let i=e.dlopen(r,{flock:{args:[e.FFIType.i32,e.FFIType.i32],returns:e.FFIType.i32},[t]:{args:[],returns:e.FFIType.ptr}}),a=i.symbols[t]();if(a===null)continue;return Y={flock:(o,c)=>i.symbols.flock(o,c),errno:()=>e.read.i32(a),wouldBlock:process.platform==="darwin"?35:11},Y}catch{}return null}var z,It=3221225472,Tt=4,xt=128,Pt=32;function Dt(e){if(z===void 0){z=null;try{let a=Te(import.meta.url)("bun:ffi"),{FFIType:o}=a;z={kernel:a.dlopen("kernel32.dll",{CreateFileW:{args:[o.ptr,o.u32,o.u32,o.ptr,o.u32,o.u32,o.ptr],returns:o.i64_fast},CloseHandle:{args:[o.i64_fast],returns:o.i32},GetLastError:{args:[],returns:o.u32}}).symbols,ptr:(d)=>a.ptr(d)}}catch{return null}}if(!z)return null;let{kernel:t,ptr:n}=z,r=Buffer.from(`${e}\x00`,"utf16le"),i=t.CreateFileW(n(r),It,0,null,Tt,xt,null);if(Number(i)===-1)return t.GetLastError()===Pt?"busy":null;return{release:()=>{t.CloseHandle(i)}}}function Ot(e){if(process.platform==="win32")return Dt(`${e}.lease`);let t=kt();if(!t)return null;let n=Ie(`${e}.lease`,C.O_RDWR|C.O_CREAT|C.O_NOFOLLOW,384);try{let r=ke(n);if(!r.isFile()||r.nlink!==1||!G(r))return J(n),"busy";if(t.flock(n,At|St)===0)return{release:()=>J(n)};let i=t.errno();return J(n),i===t.wouldBlock?"busy":null}catch(r){throw J(n),r}}function ie(e){x(E(e.path));let t=Ot(e.path);if(t==="busy")return{acquired:!1,owner:ue(e.path),recoveredStaleOwner:!1};let n=t!==null;try{let r=Ct(e,t);if(r.acquired)n=!1;return r}finally{if(n)t.release()}}function Ct(e,t){let n=e.alive??He,r=!1;for(let i=0;i<4;i+=1){let a={schema_version:ae,pid:e.pid??process.pid,nonce:e.nonce?.()??p(),started_at:(e.now?.()??new Date).toISOString(),runtime_version:e.runtimeVersion},o=`${e.path}.init-${process.pid}-${p()}`,c=!1;try{if(q(o,{mode:448}),U(m(o,"owner.json"),`${JSON.stringify(a)}
5
+ `).includes(t)||!pe(e.credentialLibraryDetail)||i.length!==0)throw new l("invalid_code_signature","Managed runtime credential library has an invalid signature or entitlement.")}function D(e,t){let n=ee("/usr/bin/codesign",e,{stdio:["ignore","pipe","pipe"]});if(n.status!==0)throw new l("invalid_code_signature",t);return[new TextDecoder().decode(n.stdout??new Uint8Array),new TextDecoder().decode(n.stderr??new Uint8Array)].join("")}var ye=(e,t)=>{D(["--verify","--strict","--verbose=2",e],"Managed runtime broker code signature is invalid."),D(["--verify","--strict","--verbose=2",t],"Managed runtime credential library code signature is invalid."),lt({brokerDetail:D(["-d","--verbose=4",e],"Managed runtime broker signer could not be inspected."),brokerEntitlements:D(["-d","--entitlements",":-",e],"Managed runtime broker entitlements could not be inspected."),credentialLibraryDetail:D(["-d","--verbose=4",t],"Managed runtime credential library signer could not be inspected."),credentialLibraryEntitlements:D(["-d","--entitlements",":-",t],"Managed runtime credential library entitlements could not be inspected.")})};async function dt(e,t,n){let r=e.headers.get("content-length");if(r!==null){let f=Number(r);if(!Number.isSafeInteger(f)||f<0||f>t)throw new l("response_too_large","Managed runtime response exceeded its size limit.")}if(!e.body){let f=new Uint8Array(await e.arrayBuffer());if(f.byteLength>t)throw new l("response_too_large","Managed runtime response exceeded its size limit.");return f}let i=e.body.getReader(),a=[],o=0,c=()=>{if(!n)return i.read();return new Promise((f,_)=>{let g=()=>{n.removeEventListener("abort",g),i.cancel(n.reason).catch(()=>{}),_(n.reason??new DOMException("Aborted","AbortError"))};if(n.aborted){g();return}n.addEventListener("abort",g,{once:!0}),i.read().then((y)=>{n.removeEventListener("abort",g),f(y)},(y)=>{n.removeEventListener("abort",g),_(y)})})};try{while(!0){let f=await c();if(f.done)break;if(o+=f.value.byteLength,o>t)throw await i.cancel(),new l("response_too_large","Managed runtime response exceeded its size limit.");a.push(f.value)}}finally{try{i.releaseLock()}catch{}}let d=new Uint8Array(o),u=0;for(let f of a)d.set(f,u),u+=f.byteLength;return d}async function Yr(e){let t;try{t=new URL(e.url)}catch{throw new l("invalid_update_url","Managed runtime update URL is invalid.")}if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new l("invalid_update_url","Managed runtime update URL must use HTTPS.");let n=new AbortController,r,i=()=>{r??="caller",n.abort(e.signal?.reason)};if(e.signal?.aborted)i();else e.signal?.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>{r??="timeout",n.abort(Error("managed runtime fetch timed out"))},e.timeoutMs),o=(c,d)=>{if(c instanceof l)return c;if(r==="caller")return new l("update_cancelled","Managed runtime update request was cancelled.");if(r==="timeout")return new l("update_fetch_timeout","Managed runtime update request timed out.");return new l("update_fetch_failed",d)};try{let c;try{if(c=await e.fetchImpl(t,{headers:{accept:e.accept},signal:n.signal}),n.signal.aborted)throw o(n.signal.reason,"Managed runtime update request was cancelled.")}catch(d){throw o(d,"Managed runtime update request failed.")}if(!c.ok)throw new l("update_http_error","Managed runtime update request was rejected.");if(c.url&&new URL(c.url).protocol!=="https:")throw new l("insecure_redirect","Managed runtime update redirected to an insecure URL.");try{let d=await dt(c,e.maximumBytes,n.signal);if(n.signal.aborted)throw o(n.signal.reason,"Managed runtime update response was cancelled.");return d}catch(d){throw o(d,"Managed runtime update response failed.")}}finally{clearTimeout(a),e.signal?.removeEventListener("abort",i)}}async function Ve(e,t,n=Ee,r){let i=typeof n==="number"?n:Ee,a=typeof n==="number"?r:n;if(a?.aborted)return!1;let o=await uc([e,"--version"],{timeoutMs:i,...a?{signal:a}:{}});return o.exitCode===0&&o.stdout.trim().replace(/^v/,"")===t}async function ut(e){let t=!1,n=null,r=null,i=(a)=>{try{N(e.paths,a,{now:e.now})}catch{}};try{let a=e.home??s();if(!ms(e.manifest.version,a))return{status:"current"};r=Yt(a);let o=await Yr({url:new URL(mc,e.manifest.artifacts[e.target].broker.url).toString(),maximumBytes:bn,fetchImpl:async(g,y)=>{let v=await e.fetchImpl(g,y);return t=v.status===404,v},timeoutMs:e.timeoutMs,accept:"application/json",signal:e.signal}),{manifest:c}=gc(new TextDecoder().decode(o),e.trustedKeys);if(c.version!==e.manifest.version||c.published_at!==e.manifest.published_at)throw new l("identity_manifest_mismatch","Background identity manifest names another release.");let d=c.artifacts[e.target],u=await Yr({url:d.url,maximumBytes:d.size_bytes,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,accept:"application/octet-stream",signal:e.signal});Gt(u,d),P(e.workDirectory),n=m(e.workDirectory,`.identity-${process.pid}-${L()}`),q(n,{mode:448});let f=m(n,"identity.tgz");if(U(f,u,{mode:384,flag:"wx"}),ee("/usr/bin/tar",["-xzf",f,"-C",n],{stdio:"ignore",timeout:60000}).status!==0)throw new l("identity_extract_failed","Background identity archive could not be extracted.");return gs({sourceApp:m(n,"Reason.app"),home:a,releaseSigned:!0,...e.command?{command:e.command}:{}}),i({event:"identity.refresh_completed",runtime_version:e.manifest.version,...r?{from_version:r}:{},to_version:e.manifest.version}),{status:"installed"}}catch(a){if(t)return{status:"unpublished"};let o=a instanceof l||a instanceof St?a.code:"identity_install_failed";return process.stderr.write(`Reason background identity: identity_update_failed (${o})
6
+ `),i({event:"identity.refresh_failed",runtime_version:e.manifest.version,...r?{from_version:r}:{},to_version:e.manifest.version,reason_code:o}),{status:"failed",code:o}}finally{if(n)T(n,{recursive:!0,force:!0})}}async function vl(e){if(!b(e.currentVersion))throw new l("invalid_version","Invalid current managed runtime version.");let t=e.paths??Lt(),n=e.target??ct(),r=e.fetchImpl??fetch,i=e.timeoutMs??et,a=e.timeoutMs??tt,o=e.healthCheck??((_,g,y)=>Ve(_,g,nt,y)),c=e.verifyCodeSignatures??ye,d=e.now?.()??new Date,u,f=!1;N(t,{event:"update.check_started",runtime_version:e.currentVersion,from_version:e.currentVersion},{now:()=>d});try{await Rt({paths:t,verifyCodeSignatures:c,healthCheck:o});let _=await Yr({url:e.manifestUrl??Qc,maximumBytes:bn,fetchImpl:r,timeoutMs:i,accept:"application/json",signal:e.signal}),g=Di(new TextDecoder().decode(_),e.trustedKeys);u=g.manifest.version;let y=()=>ut({paths:t,...e.now?{now:e.now}:{},manifest:g.manifest,target:n,trustedKeys:e.trustedKeys,fetchImpl:r,timeoutMs:a,workDirectory:t.versions,...e.home?{home:e.home}:{},...e.identityCommand?{command:e.identityCommand}:{},...e.signal?{signal:e.signal}:{}});if(Ce(u,e.currentVersion)<=0)return N(t,{event:"update.not_available",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u,duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),Ae(t,e.home),{status:"not_available",currentVersion:e.currentVersion,offeredVersion:u,...u===e.currentVersion?{identity:await y()}:{}};let v=g.manifest.artifacts[n];N(t,{event:"update.download_started",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u},{now:e.now});let A=await Yr({url:v.broker.url,maximumBytes:v.broker.size_bytes,fetchImpl:r,timeoutMs:a,accept:"application/octet-stream",signal:e.signal});Gt(A,v.broker),W(e.signal);let j=await Yr({url:v.credential_library.url,maximumBytes:v.credential_library.size_bytes,fetchImpl:r,timeoutMs:a,accept:"application/octet-stream",signal:e.signal});Gt(j,v.credential_library),N(t,{event:"update.downloaded",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u},{now:e.now}),N(t,{event:"update.verified",runtime_version:e.currentVersion,from_version:e.currentVersion,to_version:u},{now:e.now}),W(e.signal);let he=mt({paths:t,version:u,artifact:v.broker,bytes:A,credentialLibraryArtifact:v.credential_library,credentialLibraryBytes:j,verifyCodeSignatures:c}),be;try{be=await o(he.executablePath,u,e.signal)}catch(B){throw W(e.signal),B}if(W(e.signal),!be)throw new l("pre_activation_health_failed","Managed runtime preflight failed.");let I=bt(t,u);if(!I.changed&&I.toVersion!==u)return N(t,{event:"update.not_available",runtime_version:I.toVersion,from_version:I.toVersion,to_version:u,duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),{status:"not_available",currentVersion:I.toVersion,offeredVersion:u};if(f=I.changed,!await o(t.current,u)){if(I.fromVersion){let B=Ge(t,u);N(t,{event:"update.rollback",runtime_version:B.toVersion,from_version:B.fromVersion,to_version:B.toVersion,reason_code:"post_activation_health_failed"},{now:e.now})}else ze(t,u);throw O(t),f=!1,new l("post_activation_health_failed","Managed runtime activation failed.")}return O(t),Ae(t,e.home),N(t,{event:"update.activated",runtime_version:u,from_version:e.currentVersion,to_version:u,duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),{status:"activated",fromVersion:e.currentVersion,toVersion:u,installed:he.installed,identity:await y()}}catch(_){throw N(t,{event:"update.failed",runtime_version:f?u??e.currentVersion:e.currentVersion,from_version:e.currentVersion,...u?{to_version:u}:{},reason_code:_ instanceof l?_.code:"update_failed",duration_ms:Math.max(0,(e.now?.()??new Date).getTime()-d.getTime())},{now:e.now}),_}}function Le(e,t,n){try{let r=h(E(e));if(!r.isDirectory()||r.isSymbolicLink())return!1;let i=h(e);if(!i.isFile()||i.isSymbolicLink()||i.size!==t.size_bytes)return!1;let a=_e(e),o=h(a);return o.isFile()&&!o.isSymbolicLink()&&o.size===n.size_bytes&&vn(K(e))===t.sha256&&vn(K(a))===n.sha256}catch{return!1}}function mt(e){let t=F(e.paths,e.version);Gt(e.bytes,e.artifact),Gt(e.credentialLibraryBytes,e.credentialLibraryArtifact);let n=e.verifyCodeSignatures??ye;if(P(e.paths.root),P(e.paths.versions),S(E(t))){if(!Le(t,e.artifact,e.credentialLibraryArtifact))throw new l("installed_artifact_mismatch","The installed runtime version does not match the verified artifact.");return n(t,oe(e.paths,e.version)),{installed:!1,executablePath:t}}let r=m(e.paths.versions,`.install-${e.version}-${process.pid}-${L()}`),i=m(r,H(t)),a=_e(i);q(r,{mode:448});try{U(i,e.bytes,{mode:448,flag:"wx"}),Z(i,448),U(a,e.credentialLibraryBytes,{mode:448,flag:"wx"}),Z(a,448),n(i,a);try{k(r,E(t))}catch(o){if(!Le(t,e.artifact,e.credentialLibraryArtifact))throw o;return{installed:!1,executablePath:t}}return{installed:!0,executablePath:t}}finally{T(r,{recursive:!0,force:!0})}}function ft(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");return`versions/${t}/${H(F(e,t))}`}function te(e,t){P(E(e));let n=`${e}.${process.pid}.${L()}.tmp`;try{Q(t,n),k(n,e)}finally{if(S(n))p(n)}}var Ue=/^\.(?:ara|reason)-worker-(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)-(darwin-(?:arm64|x64))\.([0-9A-Za-z]{6})$/,gt=new Set(["reason","ara"]);function Fe(e,t){let n=E(e),r=M(n,t),i=E(r),a=Ue.exec(H(i));if(!gt.has(H(r))||E(i)!==n||!a||!b(a[1])||!yr.includes(a[2]))return!1;try{return h(i).isDirectory()&&E(x(i))===x(n)&&h(r).isFile()&&h(Sn(i)).isFile()}catch(o){if(o.code==="ENOENT")return!1;throw o}}function Be(e,t,n){try{if(w(e)!==t)return!1;p(e)}catch(r){if(r.code==="ENOENT")return!1;throw r}try{return Q(n,e),!0}catch(r){if(r.code==="EEXIST")return!1;try{Q(t,e)}catch(i){if(i.code!=="EEXIST")throw i}throw r}}function _t(e,t){if(!e.legacyRoot)return!1;let n;try{if(!h(t).isSymbolicLink())return!1;n=w(t)}catch(i){if(i.code==="ENOENT")return!1;throw i}if(M(E(t),n)!==m(e.legacyRoot,"current"))return!1;if(!Be(t,n,e.current))return!1;let r=Ze(e);if(r)N(e,{event:"service.launcher_adopted",runtime_version:r,to_version:r,reason_code:"legacy_runtime_root"});return!0}function yt(e,t){let n=m(e,".local","bin"),r=m(n,"ara"),i=m(n,"reason"),a=h(r,{throwIfNoEntry:!1});if(a?.isSymbolicLink()&&w(r)==="reason")return i;if(a||!h(i,{throwIfNoEntry:!1})?.isSymbolicLink())return r;let o=w(i);return o===t.current||Fe(i,o)?i:r}function Sl(e){let t=e.launcherPath??yt(e.home??s(),e.paths);try{if(h(t).isSymbolicLink()){let r=w(t);if(r===e.paths.current)return"managed";if(Fe(t,r)&&Be(t,r,e.paths.current)){let i=se(e.paths.current,e.paths.executableName)??"unknown";return N(e.paths,{event:"service.launcher_adopted",runtime_version:i,to_version:i,reason_code:"legacy_curl_entrypoint"}),"adopted"}if(_t(e.paths,t))return"adopted"}return"conflict"}catch(n){if(n.code!=="ENOENT")throw n}q(E(t),{recursive:!0,mode:448});for(let n=0;n<4;n+=1)try{return Q(e.paths.current,t),"created"}catch(r){if(r.code!=="EEXIST")throw r;try{return h(t).isSymbolicLink()&&w(t)===e.paths.current?"managed":"conflict"}catch(i){if(i.code!=="ENOENT")throw i}}return"conflict"}function se(e,t){let n;try{if(!h(e).isSymbolicLink())return null;n=w(e)}catch{return null}let r=n.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return r&&(r[2]==="ara"||r[2]===t)?r[1]:null}function Ze(e){return se(e.current,e.executableName)}function ne(e,t,n){let i=We(t,e).split(me);return i.length===2&&b(i[0])&&(i[1]==="ara"||n!==void 0&&i[1]===n)?i[0]:null}function $e(e,t){try{return h(t).isSymbolicLink()&&M(E(t),w(t))===M(e.current)}catch{return!1}}function El(e,t=process.execPath){try{return ne(x(t),x(e.versions),e.executableName)!==null}catch{let n=M(t);return n===M(e.current)||$e(e,n)||ne(n,M(e.versions),e.executableName)!==null}}function kl(e,t=process.execPath){try{return ne(x(t),x(e.versions),e.executableName)}catch{let n=M(t);if(n===M(e.current)||$e(e,n))return Ze(e);return ne(n,M(e.versions),e.executableName)}}function vt(e,t,n=!1){let r=Ze(e);if(!r)return null;if(r===t)return{changed:!1,fromVersion:r,toVersion:r};if(!n&&Ce(t,r)<=0&&!(/^\d+\.\d+\.\d+-desktop\.v1\.\d+\.\d+\.\d+$/.test(t)&&/^\d+\.\d+\.\d+-desktopdev\./.test(r)))return{changed:!1,fromVersion:r,toVersion:r};return null}function ht(e,t,n,r=!1){let i=vt(e,t,r);if(i)return i;let a=Ze(e);if(n?.(a),a)te(e.previous,w(e.current));else if(S(e.previous))p(e.previous);return te(e.current,ft(e,t)),{changed:!0,fromVersion:a,toVersion:t}}function bt(e,t){let n=F(e,t),r=oe(e,t);if(!S(n)||!V(n).isFile()||!S(r)||!V(r).isFile())throw new l("runtime_not_installed","Managed Reason runtime version is not installed.");return ce(e,t,()=>ht(e,t,(i)=>{wt(e,{schema_version:ae,from_version:i,to_version:t})}))}function Ge(e,t){return ce(e,t,()=>{if(Ze(e)!==t)throw new l("rollback_fence_failed","Managed runtime changed before rollback could be applied.");let n=se(e.previous,e.executableName);if(!n||n===t)throw new l("rollback_unavailable","No previous managed runtime is available.");let r=F(e,n),i=oe(e,n);if(!S(r)||!V(r).isFile()||!S(i)||!V(i).isFile())throw new l("rollback_unavailable","Previous managed runtime is not installed.");let a=w(e.previous),o=w(e.current);if(M(E(e.previous),a)!==M(r))throw new l("rollback_fence_failed","Previous runtime pointer does not match its installed layout.");return te(e.current,a),te(e.previous,o),{fromVersion:t,toVersion:n}})}function Ye(){let e=ee("/bin/ps",["-axww","-o","args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000,maxBuffer:16777216});if(e.status!==0||typeof e.stdout!=="string")return null;let t=ee("/usr/sbin/lsof",["-nP","-w","-d","txt","-Fn"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:20000,maxBuffer:67108864});if(t.error||t.status!==0&&t.status!==1||!t.stdout)return null;return`${e.stdout}
7
+ ${t.stdout}`}function Ae(e,t){let n=[];Et(e,t??s());try{let r=Ze(e);if(!r||de(e))return n;let i=re(e.versions).filter((o)=>b(o));if(i.length<=2)return n;let a=Ye();if(a===null)return n;ce(e,r,()=>{let o=new Set([Ze(e),se(e.previous,e.executableName)]);if(de(e))return;for(let c of i){if(o.has(c))continue;let d=m(e.versions,c);if(a.includes(`${d}${me}`))continue;try{T(d,{recursive:!0,force:!0}),n.push(c)}catch{}}})}catch{}return n}function Et(e,t){try{let n=le(m(t,".local","bin"));if(!n)return;let r=["reason","ara"].flatMap((c)=>{try{return[M(n,w(m(n,c)))]}catch{return[]}}),i=le(e.current);if(!i||!r.some((c)=>le(c)===i))return;let a=re(n).filter((c)=>Ue.test(c)).map((c)=>m(n,c)).filter((c)=>!r.some((d)=>E(d)===c)).filter((c)=>Date.now()-h(c).mtimeMs>3600000);if(a.length===0)return;let o=Ye();if(o===null)return;for(let c of a){if(o.includes(`${c}${me}`))continue;try{T(c,{recursive:!0,force:!0})}catch{}}}catch{}}function le(e){try{return x(e)}catch{return null}}function ze(e,t){ce(e,t,()=>{if(Ze(e)!==t)throw new l("rollback_fence_failed","Managed runtime changed before rollback could be applied.");p(e.current)})}function ve(e){return e.activationState??m(e.root,"activation.json")}function Mt(e){return fe(e)&&ge(e,["schema_version","from_version","to_version"])&&e.schema_version===ae&&(e.from_version===null||b(e.from_version))&&b(e.to_version)}function de(e){try{let t=ve(e),n=h(t);if(!n.isFile()||n.isSymbolicLink()||n.nlink!==1||(n.mode&63)!==0||n.size>4096)throw new l("invalid_activation_state","Managed runtime activation state is invalid.");let r=JSON.parse(K(t,"utf8"));if(!Mt(r))throw new l("invalid_activation_state","Managed runtime activation state is invalid.");return r}catch(t){if(t instanceof l)throw t;if(t.code==="ENOENT")return null;throw new l("invalid_activation_state","Managed runtime activation state is invalid.")}}function wt(e,t){Oe(ve(e),JSON.stringify(t)+`
8
+ `)}function O(e){try{p(ve(e))}catch(t){if(t.code!=="ENOENT")throw t}}async function Rt(e){let t=de(e.paths);if(!t)return"none";let n=Ze(e.paths);if(n===t.from_version)return O(e.paths),"cleared";if(n!==t.to_version)throw new l("rollback_fence_failed","Managed runtime changed before activation recovery could be applied.");let r=e.verifyCodeSignatures??ye,i=e.healthCheck??Ve,a=!1;try{let o=F(e.paths,t.to_version);r(o,oe(e.paths,t.to_version)),a=await i(o,t.to_version)}catch{a=!1}if(a)return O(e.paths),N(e.paths,{event:"update.activated",runtime_version:t.to_version,...t.from_version?{from_version:t.from_version}:{},to_version:t.to_version,reason_code:"restart_recovery"}),"committed";if(t.from_version){let o=Ge(e.paths,t.to_version);return O(e.paths),N(e.paths,{event:"update.rollback",runtime_version:o.toVersion,from_version:o.fromVersion,to_version:o.toVersion,reason_code:"restart_recovery"}),"rolled_back"}return ze(e.paths,t.to_version),O(e.paths),N(e.paths,{event:"update.rollback",runtime_version:t.to_version,from_version:t.to_version,reason_code:"restart_recovery"}),"rolled_back"}function pt(e){return fe(e)&&ge(e,["schema_version","pid","nonce","started_at","runtime_version"])&&e.schema_version===ae&&typeof e.pid==="number"&&Number.isSafeInteger(e.pid)&&e.pid>0&&typeof e.nonce==="string"&&/^[0-9a-f-]{36}$/.test(e.nonce)&&De(e.started_at)&&b(e.runtime_version)}function Je(e,t){try{let n=h(e);if(!n.isDirectory()||!G(n))return null;let r=Ie(m(e,t),C.O_RDONLY|C.O_NOFOLLOW|C.O_NONBLOCK);try{let i=ke(r);if(!i.isFile()||i.nlink!==1||!G(i)||i.size>4096)return null;return K(r,"utf8")}finally{J(r)}}catch{return null}}function ue(e){try{let t=JSON.parse(Je(e,"owner.json")??"null");return pt(t)?t:null}catch{return null}}function Ke(e){try{return process.kill(e,0),!0}catch(t){return!(t instanceof Error&&("code"in t)&&t.code==="ESRCH")}}var Ne="lease",At=2,Nt=4,Y;function kt(){if(Y!==void 0)return Y;if(Y=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let e;try{e=Te(import.meta.url)("bun:ffi")}catch{return null}let t=process.platform==="darwin"?"__error":"__errno_location",n=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let r of n)try{let i=e.dlopen(r,{flock:{args:[e.FFIType.i32,e.FFIType.i32],returns:e.FFIType.i32},[t]:{args:[],returns:e.FFIType.ptr}}),a=i.symbols[t]();if(a===null)continue;return Y={flock:(o,c)=>i.symbols.flock(o,c),errno:()=>e.read.i32(a),wouldBlock:process.platform==="darwin"?35:11},Y}catch{}return null}var z,It=3221225472,Tt=4,xt=128,Pt=32;function Dt(e){if(z===void 0){z=null;try{let a=Te(import.meta.url)("bun:ffi"),{FFIType:o}=a;z={kernel:a.dlopen("kernel32.dll",{CreateFileW:{args:[o.ptr,o.u32,o.u32,o.ptr,o.u32,o.u32,o.ptr],returns:o.i64_fast},CloseHandle:{args:[o.i64_fast],returns:o.i32},GetLastError:{args:[],returns:o.u32}}).symbols,ptr:(d)=>a.ptr(d)}}catch{return null}}if(!z)return null;let{kernel:t,ptr:n}=z,r=Buffer.from(`${e}\x00`,"utf16le"),i=t.CreateFileW(n(r),It,0,null,Tt,xt,null);if(Number(i)===-1)return t.GetLastError()===Pt?"busy":null;return{release:()=>{t.CloseHandle(i)}}}function Ot(e){if(process.platform==="win32")return Dt(`${e}.lease`);let t=kt();if(!t)return null;let n=Ie(`${e}.lease`,C.O_RDWR|C.O_CREAT|C.O_NOFOLLOW,384);try{let r=ke(n);if(!r.isFile()||r.nlink!==1||!G(r))return J(n),"busy";if(t.flock(n,At|Nt)===0)return{release:()=>J(n)};let i=t.errno();return J(n),i===t.wouldBlock?"busy":null}catch(r){throw J(n),r}}function ie(e){P(E(e.path));let t=Ot(e.path);if(t==="busy")return{acquired:!1,owner:ue(e.path),recoveredStaleOwner:!1};let n=t!==null;try{let r=Ct(e,t);if(r.acquired)n=!1;return r}finally{if(n)t.release()}}function Ct(e,t){let n=e.alive??Ke,r=!1;for(let i=0;i<4;i+=1){let a={schema_version:ae,pid:e.pid??process.pid,nonce:e.nonce?.()??L(),started_at:(e.now?.()??new Date).toISOString(),runtime_version:e.runtimeVersion},o=`${e.path}.init-${process.pid}-${L()}`,c=!1;try{if(q(o,{mode:448}),U(m(o,"owner.json"),`${JSON.stringify(a)}
9
9
  `,{mode:384,flag:"wx"}),t!==null)U(m(o,Ne),`flock
10
- `,{mode:384,flag:"wx"});e.beforePublish?.();try{throw h(e.path),Object.assign(Error("Managed runtime lock exists."),{code:"EEXIST"})}catch(u){if(u.code!=="ENOENT")throw u}S(o,e.path),c=!0;let d=!1;return{acquired:!0,owner:a,recoveredStaleOwner:r,release(){if(d)return;if(d=!0,ue(e.path)?.nonce===a.nonce)I(e.path,{recursive:!0,force:!0});t?.release()}}}catch(d){let u=d.code;if(!["EEXIST","ENOTEMPTY"].includes(u??""))throw d;let f=ue(e.path),_=(e.now?.()??new Date).getTime(),g=f&&e.staleAfterMs!==void 0?_-Date.parse(f.started_at)<e.staleAfterMs:!1,y=f!==null&&!(t!==null&&Ke(e.path,Ne)!==null)&&n(f.pid);if(!f||y||g)return{acquired:!1,owner:f,recoveredStaleOwner:!1};let v=`${e.path}.stale-${process.pid}-${p()}`;try{S(e.path,v),I(v,{recursive:!0,force:!0}),r=!0}catch(L){let j=L.code;if(!["ENOENT","EEXIST"].includes(j??""))throw L}}finally{if(!c)I(o,{recursive:!0,force:!0})}}throw new l("lock_unavailable","Could not acquire the managed Reason runtime lock.")}var Ut=20000;function ce(e,t,n){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let r=Date.now()+Ut,i=ie({path:e.transitionLock,runtimeVersion:t,staleAfterMs:60000});while(!i.acquired&&Date.now()<r)nc(100),i=ie({path:e.transitionLock,runtimeVersion:t,staleAfterMs:60000});if(!i.acquired)throw new l("transition_busy","Another managed Reason runtime transition is in progress.");try{return n()}finally{i.release()}}function yl(e){if(!b(e.runtimeVersion))throw new l("invalid_version","Invalid managed Reason runtime version.");let t=e.paths??Nt();return ie({path:t.brokerLock,runtimeVersion:e.runtimeVersion,...e.pid===void 0?{}:{pid:e.pid},...e.now===void 0?{}:{now:e.now},...e.nonce===void 0?{}:{nonce:e.nonce},...e.alive===void 0?{}:{alive:e.alive},...e.beforePublish===void 0?{}:{beforePublish:e.beforePublish}})}function qe(e){return fe(e)&&ge(e,["schema_version","event_id","occurred_at","event","runtime_version"],["from_version","to_version","reason_code","duration_ms","attempt_count","retry_in_ms","capabilities"])&&e.schema_version===xe&&typeof e.event_id==="string"&&/^[0-9a-f-]{36}$/.test(e.event_id)&&De(e.occurred_at)&&typeof e.event==="string"&&ot.includes(e.event)&&b(e.runtime_version)&&(e.from_version===void 0||b(e.from_version))&&(e.to_version===void 0||b(e.to_version))&&(e.reason_code===void 0||typeof e.reason_code==="string"&&Me.test(e.reason_code))&&(e.duration_ms===void 0||typeof e.duration_ms==="number"&&Number.isSafeInteger(e.duration_ms)&&e.duration_ms>=0&&e.duration_ms<=86400000)&&(e.attempt_count===void 0||typeof e.attempt_count==="number"&&Number.isSafeInteger(e.attempt_count)&&e.attempt_count>=1&&e.attempt_count<=1e5)&&(e.retry_in_ms===void 0||typeof e.retry_in_ms==="number"&&Number.isSafeInteger(e.retry_in_ms)&&e.retry_in_ms>=0&&e.retry_in_ms<=30000)&&(e.capabilities===void 0||Array.isArray(e.capabilities)&&e.capabilities.length<=it&&e.capabilities.every((t)=>typeof t==="string"&&Me.test(t)))}var Ft=/^(\d{22}-[0-9a-f-]{36}\.json)$/,Bt=/^(\d{22}-[0-9a-f-]{36}\.json)\.sending-(\d+)-[0-9a-f-]{36}$/,$t=300000,X=0n;function Gt(e){let t=BigInt(new Date(e.occurred_at).getTime())*1000000n;return X=t>X?t:X+1n,`${String(X).padStart(22,"0")}-${e.event_id}.json`}function je(e){try{return re(e.lifecycleEvents).filter((t)=>Ft.test(t)).sort()}catch{return[]}}function Se(e){try{let t=JSON.parse(K(e,"utf8"));return qe(t)?t:null}catch{return null}}function zt(e,t=He,n=Date.now()){let r;try{r=re(e.lifecycleEvents)}catch{return}for(let i of r){let a=i.match(Bt);if(!a)continue;let o=m(e.lifecycleEvents,i),c=m(e.lifecycleEvents,a[1]),d=!t(Number(a[2]));if(!d)try{d=n-V(o).mtimeMs>=$t}catch{continue}if(!d)continue;try{S(o,c)}catch(u){let f=u.code;if(f==="EEXIST")R(o);else if(f!=="ENOENT")throw u}}}function Jt(e){let n=je(e).flatMap((i)=>{try{return[{name:i,size:V(m(e.lifecycleEvents,i)).size}]}catch{return[]}}),r=n.reduce((i,a)=>i+a.size,0);while(n.length>Ze||r>Qe){let i=n.shift();if(!i)break;try{R(m(e.lifecycleEvents,i.name)),r-=i.size}catch(a){if(a.code!=="ENOENT")throw a}}}function N(e,t,n={}){let r={schema_version:xe,event_id:n.eventId?.()??p(),occurred_at:(n.now?.()??new Date).toISOString(),...t};if(!qe(r))throw new l("invalid_lifecycle_event","Managed runtime lifecycle event is invalid.");return x(e.lifecycleEvents),Oe(m(e.lifecycleEvents,Gt(r)),`${JSON.stringify(r)}
11
- `),Jt(e),r}async function Qi(e,t,n){zt(e);let r=0;for(let i of je(e)){let a=m(e.lifecycleEvents,i);if(n){let d=Se(a);if(!d||!n(d))continue}let o=`${a}.sending-${process.pid}-${p()}`;try{S(a,o)}catch(d){if(d.code==="ENOENT")continue;throw d}let c=Se(o);if(!c){R(o);continue}try{await t(c),R(o),r+=1}catch{try{S(o,a)}catch(d){if(d.code!=="ENOENT")throw d}break}}return r}export{Vc,Nt,hl,Wr,fl,ml,Ye,gl,_l,ie,yl,N,Qi};
10
+ `,{mode:384,flag:"wx"});e.beforePublish?.();try{throw h(e.path),Object.assign(Error("Managed runtime lock exists."),{code:"EEXIST"})}catch(u){if(u.code!=="ENOENT")throw u}k(o,e.path),c=!0;let d=!1;return{acquired:!0,owner:a,recoveredStaleOwner:r,release(){if(d)return;if(d=!0,ue(e.path)?.nonce===a.nonce)T(e.path,{recursive:!0,force:!0});t?.release()}}}catch(d){let u=d.code;if(!["EEXIST","ENOTEMPTY"].includes(u??""))throw d;let f=ue(e.path),_=(e.now?.()??new Date).getTime(),g=f&&e.staleAfterMs!==void 0?_-Date.parse(f.started_at)<e.staleAfterMs:!1,y=f!==null&&!(t!==null&&Je(e.path,Ne)!==null)&&n(f.pid);if(!f||y||g)return{acquired:!1,owner:f,recoveredStaleOwner:!1};let v=`${e.path}.stale-${process.pid}-${L()}`;try{k(e.path,v),T(v,{recursive:!0,force:!0}),r=!0}catch(A){let j=A.code;if(!["ENOENT","EEXIST"].includes(j??""))throw A}}finally{if(!c)T(o,{recursive:!0,force:!0})}}throw new l("lock_unavailable","Could not acquire the managed Reason runtime lock.")}var Vt=20000;function ce(e,t,n){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let r=Date.now()+Vt,i=ie({path:e.transitionLock,runtimeVersion:t,staleAfterMs:60000});while(!i.acquired&&Date.now()<r)dc(100),i=ie({path:e.transitionLock,runtimeVersion:t,staleAfterMs:60000});if(!i.acquired)throw new l("transition_busy","Another managed Reason runtime transition is in progress.");try{return n()}finally{i.release()}}function xl(e){if(!b(e.runtimeVersion))throw new l("invalid_version","Invalid managed Reason runtime version.");let t=e.paths??Lt();return ie({path:t.brokerLock,runtimeVersion:e.runtimeVersion,...e.pid===void 0?{}:{pid:e.pid},...e.now===void 0?{}:{now:e.now},...e.nonce===void 0?{}:{nonce:e.nonce},...e.alive===void 0?{}:{alive:e.alive},...e.beforePublish===void 0?{}:{beforePublish:e.beforePublish}})}function He(e){return fe(e)&&ge(e,["schema_version","event_id","occurred_at","event","runtime_version"],["from_version","to_version","reason_code","duration_ms","attempt_count","retry_in_ms","capabilities"])&&e.schema_version===xe&&typeof e.event_id==="string"&&/^[0-9a-f-]{36}$/.test(e.event_id)&&De(e.occurred_at)&&typeof e.event==="string"&&ot.includes(e.event)&&b(e.runtime_version)&&(e.from_version===void 0||b(e.from_version))&&(e.to_version===void 0||b(e.to_version))&&(e.reason_code===void 0||typeof e.reason_code==="string"&&Me.test(e.reason_code))&&(e.duration_ms===void 0||typeof e.duration_ms==="number"&&Number.isSafeInteger(e.duration_ms)&&e.duration_ms>=0&&e.duration_ms<=86400000)&&(e.attempt_count===void 0||typeof e.attempt_count==="number"&&Number.isSafeInteger(e.attempt_count)&&e.attempt_count>=1&&e.attempt_count<=1e5)&&(e.retry_in_ms===void 0||typeof e.retry_in_ms==="number"&&Number.isSafeInteger(e.retry_in_ms)&&e.retry_in_ms>=0&&e.retry_in_ms<=30000)&&(e.capabilities===void 0||Array.isArray(e.capabilities)&&e.capabilities.length<=it&&e.capabilities.every((t)=>typeof t==="string"&&Me.test(t)))}var Ut=/^(\d{22}-[0-9a-f-]{36}\.json)$/,Ft=/^(\d{22}-[0-9a-f-]{36}\.json)\.sending-(\d+)-[0-9a-f-]{36}$/,Bt=300000,X=0n;function $t(e){let t=BigInt(new Date(e.occurred_at).getTime())*1000000n;return X=t>X?t:X+1n,`${String(X).padStart(22,"0")}-${e.event_id}.json`}function qe(e){try{return re(e.lifecycleEvents).filter((t)=>Ut.test(t)).sort()}catch{return[]}}function Se(e){try{let t=JSON.parse(K(e,"utf8"));return He(t)?t:null}catch{return null}}function zt(e,t=Ke,n=Date.now()){let r;try{r=re(e.lifecycleEvents)}catch{return}for(let i of r){let a=i.match(Ft);if(!a)continue;let o=m(e.lifecycleEvents,i),c=m(e.lifecycleEvents,a[1]),d=!t(Number(a[2]));if(!d)try{d=n-V(o).mtimeMs>=Bt}catch{continue}if(!d)continue;try{k(o,c)}catch(u){let f=u.code;if(f==="EEXIST")p(o);else if(f!=="ENOENT")throw u}}}function Jt(e){let n=qe(e).flatMap((i)=>{try{return[{name:i,size:V(m(e.lifecycleEvents,i)).size}]}catch{return[]}}),r=n.reduce((i,a)=>i+a.size,0);while(n.length>Xe||r>Qe){let i=n.shift();if(!i)break;try{p(m(e.lifecycleEvents,i.name)),r-=i.size}catch(a){if(a.code!=="ENOENT")throw a}}}function N(e,t,n={}){let r={schema_version:xe,event_id:n.eventId?.()??L(),occurred_at:(n.now?.()??new Date).toISOString(),...t};if(!He(r))throw new l("invalid_lifecycle_event","Managed runtime lifecycle event is invalid.");return P(e.lifecycleEvents),Oe(m(e.lifecycleEvents,$t(r)),`${JSON.stringify(r)}
11
+ `),Jt(e),r}async function ro(e,t,n){zt(e);let r=0;for(let i of qe(e)){let a=m(e.lifecycleEvents,i);if(n){let d=Se(a);if(!d||!n(d))continue}let o=`${a}.sending-${process.pid}-${L()}`;try{k(a,o)}catch(d){if(d.code==="ENOENT")continue;throw d}let c=Se(o);if(!c){p(o);continue}try{await t(c),p(o),r+=1}catch{try{k(o,a)}catch(d){if(d.code!=="ENOENT")throw d}break}}return r}export{Qc,Lt,bl,Yr,vl,Sl,Ze,El,kl,ie,xl,N,ro};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{resolve as s,sep as i}from"path";var bt=[[".ssh"],[".gnupg"],[".aws"],[".azure"],[".kube"],[".docker"],[".infisical"],[".password-store"],[".terraform.d"],[".config","ara"],[".config","reason"],[".config","gh"],[".config","gcloud"],[".config","infisical"],[".config","op"],[".config","1password"],[".config","pass"],[".local","share","keyrings"],["library","keychains"],["library","application support","so.ara.desktop"],["appdata","roaming","github cli"],["appdata","roaming","gcloud"],["appdata","roaming","microsoft","credentials"],["appdata","local","microsoft","credentials"],["appdata","roaming","microsoft","protect"],["appdata","roaming","1password"],["appdata","local","1password"],["appdata","roaming","microsoft","windows","start menu","programs","startup"],["documents","windowspowershell"],["documents","powershell"],["appdata","local","reason"]],Cn=[[".codex","config.toml"],[".cursor","mcp.json"],[".claude","settings.json"],[".claude","settings.local.json"],[".cargo","credentials"],[".cargo","credentials.toml"],[".gem","credentials"],[".config","git","config"],[".config","git","credentials"],[".config","pip","pip.conf"]],An=new Set([".bash_login",".bash_profile",".bashrc",".bunfig.toml",".claude.json",".env",".envrc",".git-credentials",".gitconfig",".mcp.json",".netrc",".npmrc",".profile",".pypirc",".terraformrc",".yarnrc",".yarnrc.yml",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","auth.json","credentials.json","credentials.tfrc.json","local-daemon.json","local-device.json","mcp.json"]),Pn=[".key",".p12",".pfx",".pem"];function t(n,a){if(n.length<a.length)return!1;for(let r=0;r<=n.length-a.length;r+=1)if(a.every((o,e)=>n[r+e]===o))return!0;return!1}function L(n){let a=s(n).split(i).filter(Boolean).map((o)=>o.toLowerCase());if(bt.some((o)=>t(a,o)))return!0;if(Cn.some((o)=>t(a,o)))return!0;let r=a.at(-1)??"";return An.has(r)||r.startsWith(".env.")||Pn.some((o)=>r.endsWith(o))}
3
- export{bt,Cn,An,Pn,L};
2
+ import{resolve as s,sep as i}from"path";var vt=[[".ssh"],[".gnupg"],[".aws"],[".azure"],[".kube"],[".docker"],[".infisical"],[".password-store"],[".terraform.d"],[".config","ara"],[".config","reason"],[".config","gh"],[".config","gcloud"],[".config","infisical"],[".config","op"],[".config","1password"],[".config","pass"],[".local","share","keyrings"],["library","keychains"],["library","application support","so.ara.desktop"],["appdata","roaming","github cli"],["appdata","roaming","gcloud"],["appdata","roaming","microsoft","credentials"],["appdata","local","microsoft","credentials"],["appdata","roaming","microsoft","protect"],["appdata","roaming","1password"],["appdata","local","1password"],["appdata","roaming","microsoft","windows","start menu","programs","startup"],["documents","windowspowershell"],["documents","powershell"],["appdata","local","reason"]],Rn=[[".codex","config.toml"],[".cursor","mcp.json"],[".claude","settings.json"],[".claude","settings.local.json"],[".cargo","credentials"],[".cargo","credentials.toml"],[".gem","credentials"],[".config","git","config"],[".config","git","credentials"],[".config","pip","pip.conf"]],Tn=new Set([".bash_login",".bash_profile",".bashrc",".bunfig.toml",".claude.json",".env",".envrc",".git-credentials",".gitconfig",".mcp.json",".netrc",".npmrc",".profile",".pypirc",".terraformrc",".yarnrc",".yarnrc.yml",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","auth.json","credentials.json","credentials.tfrc.json","local-daemon.json","local-device.json","mcp.json"]),In=[".key",".p12",".pfx",".pem"];function t(n,a){if(n.length<a.length)return!1;for(let r=0;r<=n.length-a.length;r+=1)if(a.every((o,e)=>n[r+e]===o))return!0;return!1}function L(n){let a=s(n).split(i).filter(Boolean).map((o)=>o.toLowerCase());if(vt.some((o)=>t(a,o)))return!0;if(Rn.some((o)=>t(a,o)))return!0;let r=a.at(-1)??"";return Tn.has(r)||r.startsWith(".env.")||In.some((o)=>r.endsWith(o))}
3
+ export{vt,Rn,Tn,In,L};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,la=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var ct=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var il=(a,b)=>{for(var c in b)h(a,c,{get:b[c],enumerable:!0,configurable:!0,set:s.bind(b,c)})};var ol=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var e=import.meta.require;
3
- export{la,ct,il,ol,e};
2
+ var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,_a=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var lt=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var dl=(a,b)=>{for(var c in b)h(a,c,{get:b[c],enumerable:!0,configurable:!0,set:s.bind(b,c)})};var pl=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var e=import.meta.require;
3
+ export{_a,lt,dl,pl,e};