@reason-machines/cli-linux-x64 0.2.560 → 0.2.563

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-3stvmqsj.js +2 -0
  3. package/bin/vm-hands/api-9xm5e4g9.js +2 -0
  4. package/bin/vm-hands/api-credentials-3wwkpts2.js +2 -0
  5. package/bin/vm-hands/{ask-relay-2vf6fa2t.js → ask-relay-5f92e4c5.js} +2 -2
  6. package/bin/vm-hands/connect-cli-d3dp0r1t.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-p0zx6qxg.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-0a7enct8.js +2 -0
  18. package/bin/vm-hands/local-capabilities-d3ycjdyg.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-pc85z6mg.js +2 -0
  22. package/bin/vm-hands/local-display-video-40avbg94.js +2 -0
  23. package/bin/vm-hands/local-managed-process-ka331rcr.js +2 -0
  24. package/bin/vm-hands/local-pty-session-tqn2xmph.js +2 -0
  25. package/bin/vm-hands/managed-runtime-nwj7cn7c.js +2 -0
  26. package/bin/vm-hands/network-auto-update-tk104maa.js +3 -0
  27. package/bin/vm-hands/network-contract-nkwcf4r9.js +2 -0
  28. package/bin/vm-hands/{network-sign-in-8yvdx5rm.js → network-sign-in-t9ng36rs.js} +2 -2
  29. package/bin/vm-hands/package-9w0mmxb5.js +2 -0
  30. package/bin/vm-hands/permissions-ywh8x4dq.js +2 -0
  31. package/bin/vm-hands/reason-hands-protocol-pck5har9.js +2 -0
  32. package/bin/vm-hands/serve-service-43kmwskj.js +2 -0
  33. package/bin/vm-hands/{status-fr7192eh.js → status-ec366bs8.js} +7 -7
  34. package/bin/vm-hands/version-6ys9zwbj.js +2 -0
  35. package/bin/vm-hands/{vm-hands-entry-lite-0as6nsks.js → vm-hands-entry-lite-0jy8mv4a.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-zawytz09.js → vm-hands-entry-lite-12ck5swp.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-j10cw3d9.js → vm-hands-entry-lite-13nx02p7.js} +7 -7
  38. package/bin/vm-hands/{vm-hands-entry-lite-vdv4nm5f.js → vm-hands-entry-lite-1b21avcs.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-qegwyvyz.js → vm-hands-entry-lite-1w39j6vz.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-8w0ah5j9.js → vm-hands-entry-lite-1wxwsb3f.js} +7 -7
  41. package/bin/vm-hands/{vm-hands-entry-lite-ms99mzp0.js → vm-hands-entry-lite-284z7ct8.js} +3 -3
  42. package/bin/vm-hands/{vm-hands-entry-lite-a7bf7xr7.js → vm-hands-entry-lite-2qfmabqn.js} +3 -3
  43. package/bin/vm-hands/{vm-hands-entry-lite-q9s1e2y1.js → vm-hands-entry-lite-33at6g06.js} +2 -2
  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-41nn0vbf.js +150 -0
  47. package/bin/vm-hands/{vm-hands-entry-lite-0ex2twm5.js → vm-hands-entry-lite-43bv9hf0.js} +3 -3
  48. package/bin/vm-hands/{vm-hands-entry-lite-f8p11q6h.js → vm-hands-entry-lite-61p78r72.js} +19 -19
  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-0wb1n769.js → vm-hands-entry-lite-b1vanmtv.js} +5 -5
  53. package/bin/vm-hands/{vm-hands-entry-lite-q9djb28r.js → vm-hands-entry-lite-cc8hwgxc.js} +3 -3
  54. package/bin/vm-hands/vm-hands-entry-lite-chq0qx9f.js +12 -0
  55. package/bin/vm-hands/{vm-hands-entry-lite-84mc1f7h.js → vm-hands-entry-lite-cmmb9k3g.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-fhx46jny.js → vm-hands-entry-lite-d12hx1dk.js} +6 -6
  57. package/bin/vm-hands/{vm-hands-entry-lite-4jgykvd3.js → vm-hands-entry-lite-d431ffz0.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-ptycjmkc.js → vm-hands-entry-lite-fccn6s4j.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-qf990rxw.js → vm-hands-entry-lite-fn2805g8.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-y4df9n3f.js → vm-hands-entry-lite-frg1b1rg.js} +105 -105
  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-57ajjwmh.js → vm-hands-entry-lite-gxf2r5en.js} +1 -1
  63. package/bin/vm-hands/{vm-hands-entry-lite-cspd38hc.js → vm-hands-entry-lite-j8s2vqpf.js} +42 -42
  64. package/bin/vm-hands/{vm-hands-entry-lite-fk2s50nc.js → vm-hands-entry-lite-jgwjt10t.js} +3 -5
  65. package/bin/vm-hands/{vm-hands-entry-lite-hjjbjpd7.js → vm-hands-entry-lite-jj7873n8.js} +3 -3
  66. package/bin/vm-hands/{vm-hands-entry-lite-f95mg81d.js → vm-hands-entry-lite-k4d5rhpw.js} +2 -2
  67. package/bin/vm-hands/{vm-hands-entry-lite-9g52kxyj.js → vm-hands-entry-lite-kbnxk71q.js} +2 -2
  68. package/bin/vm-hands/{vm-hands-entry-lite-8pcs85ak.js → vm-hands-entry-lite-mn8rjpxq.js} +10 -10
  69. package/bin/vm-hands/{vm-hands-entry-lite-52qz0n30.js → vm-hands-entry-lite-ngry8nkq.js} +4 -4
  70. package/bin/vm-hands/vm-hands-entry-lite-pe374cn6.js +81 -0
  71. package/bin/vm-hands/{vm-hands-entry-lite-8xv6c0rm.js → vm-hands-entry-lite-pg7nnyc6.js} +2 -2
  72. package/bin/vm-hands/{vm-hands-entry-lite-tcmye5ny.js → vm-hands-entry-lite-q62g6sx0.js} +2 -2
  73. package/bin/vm-hands/{vm-hands-entry-lite-v4hr9x9h.js → vm-hands-entry-lite-qjrgvdbj.js} +34 -34
  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-srtqjjqb.js +48 -0
  78. package/bin/vm-hands/{vm-hands-entry-lite-q3er9m6y.js → vm-hands-entry-lite-thstg177.js} +6 -6
  79. package/bin/vm-hands/vm-hands-entry-lite-vbqfmsd3.js +4 -0
  80. package/bin/vm-hands/vm-hands-entry-lite-wnqqjsew.js +3 -0
  81. package/bin/vm-hands/{vm-hands-entry-lite-pxtycfdv.js → vm-hands-entry-lite-xfak34av.js} +4 -4
  82. package/bin/vm-hands/{vm-hands-entry-lite-sy7dcccg.js → vm-hands-entry-lite-y0jtj8zz.js} +1 -1
  83. package/bin/vm-hands/{vm-hands-entry-lite-yvws5zpx.js → vm-hands-entry-lite-yg4dk99m.js} +1 -1
  84. package/bin/vm-hands/{vm-hands-entry-lite-2rgf8866.js → vm-hands-entry-lite-z65xva21.js} +2 -2
  85. package/bin/vm-hands/{vm-hands-entry-lite-rhx6adbr.js → vm-hands-entry-lite-zj9esd2g.js} +7 -7
  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-2ngwj96m.js +12 -0
  90. package/bin/vm-hands/vm-hands-op-runner-te2ze1e7.js +2 -0
  91. package/bin/vm-hands/{vm-hands-runtime-gjjm5fzd.js → vm-hands-runtime-09ehkm3c.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-j5f603sy.js +0 -2
  96. package/bin/vm-hands/api-credentials-7rhpwe7n.js +0 -2
  97. package/bin/vm-hands/api-vkgf7wma.js +0 -2
  98. package/bin/vm-hands/connect-cli-06x1wfgv.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-8b1znx0p.js +0 -2
  106. package/bin/vm-hands/local-capabilities-m6pzcc94.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-zyd8s6n6.js +0 -2
  110. package/bin/vm-hands/local-display-video-rk680vwg.js +0 -2
  111. package/bin/vm-hands/local-managed-process-w26jhyfg.js +0 -2
  112. package/bin/vm-hands/local-pty-session-edd8ttf9.js +0 -2
  113. package/bin/vm-hands/managed-runtime-ykv5nyva.js +0 -2
  114. package/bin/vm-hands/network-auto-update-mrjz964a.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-nmxr8238.js +0 -2
  118. package/bin/vm-hands/reason-hands-protocol-1nkpw1v3.js +0 -2
  119. package/bin/vm-hands/serve-service-det934tz.js +0 -2
  120. package/bin/vm-hands/version-5d6gbmrd.js +0 -2
  121. package/bin/vm-hands/vm-hands-entry-lite-ab1pq3xg.js +0 -3
  122. package/bin/vm-hands/vm-hands-entry-lite-bnpdn6fw.js +0 -127
  123. package/bin/vm-hands/vm-hands-entry-lite-jhsa4av7.js +0 -3
  124. package/bin/vm-hands/vm-hands-entry-lite-nn6zcvmp.js +0 -3
  125. package/bin/vm-hands/vm-hands-entry-lite-tvnfm4xg.js +0 -150
  126. package/bin/vm-hands/vm-hands-executor-qny3mx8f.js +0 -12
  127. package/bin/vm-hands/vm-hands-op-runner-5q01rhkc.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,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-q3er9m6y.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-thstg177.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,5 +1,5 @@
1
1
  // @bun
2
- import{pt,et,ht}from"./vm-hands-entry-lite-0wb1n769.js";import{Tt,Me,It}from"./vm-hands-entry-lite-8xv6c0rm.js";import{spawn as A}from"child_process";import{randomUUID as s}from"crypto";import{basename as C}from"path";import{fileURLToPath as E}from"url";function S(){let p=C(process.execPath).startsWith("bun");return{command:process.execPath,args:[...p?["--no-env-file",E(new URL("./worker-candidate-entry.ts",import.meta.url))]:[],"worker","__preview-probe"]}}async function Zi(p,a,m=S()){if(a.aborted||!["darwin","linux","win32"].includes(process.platform)||process.platform==="win32"&&!et())return!1;let n=new AbortController,o=()=>n.abort();a.addEventListener("abort",o,{once:!0});let y=setTimeout(o,5000),t=A(m.command,m.args,{cwd:p,...Me(),stdio:["pipe","pipe","ignore"],env:Tt()});It(t);let l=!1,b=new Promise((e)=>t.once("close",()=>{l=!0,e()}));t.on("error",o);let f,w,k=new Promise((e)=>{f=e}),I=new Promise((e)=>{w=e}),v=new Promise((e)=>n.signal.addEventListener("abort",()=>e(null),{once:!0})),i="",g=0,P=!1;t.stdout.setEncoding("utf8"),t.stdout.on("data",(e)=>{if(g+=Buffer.byteLength(e),i+=e,g>512){o();return}while(i.includes(`
2
+ import{ht,tt,ft}from"./vm-hands-entry-lite-b1vanmtv.js";import{It,Me,Dt}from"./vm-hands-entry-lite-pg7nnyc6.js";import{spawn as A}from"child_process";import{randomUUID as s}from"crypto";import{basename as C}from"path";import{fileURLToPath as E}from"url";function S(){let p=C(process.execPath).startsWith("bun");return{command:process.execPath,args:[...p?["--no-env-file",E(new URL("./worker-candidate-entry.ts",import.meta.url))]:[],"worker","__preview-probe"]}}async function to(p,a,m=S()){if(a.aborted||!["darwin","linux","win32"].includes(process.platform)||process.platform==="win32"&&!tt())return!1;let n=new AbortController,o=()=>n.abort();a.addEventListener("abort",o,{once:!0});let y=setTimeout(o,5000),t=A(m.command,m.args,{cwd:p,...Me(),stdio:["pipe","pipe","ignore"],env:It()});Dt(t);let l=!1,b=new Promise((e)=>t.once("close",()=>{l=!0,e()}));t.on("error",o);let f,w,k=new Promise((e)=>{f=e}),I=new Promise((e)=>{w=e}),v=new Promise((e)=>n.signal.addEventListener("abort",()=>e(null),{once:!0})),i="",g=0,P=!1;t.stdout.setEncoding("utf8"),t.stdout.on("data",(e)=>{if(g+=Buffer.byteLength(e),i+=e,g>512){o();return}while(i.includes(`
3
3
  `)){let c=i.indexOf(`
4
- `),d=i.slice(0,c);i=i.slice(c+1);try{if(!P){let r=JSON.parse(d);if(!r||Object.keys(r).length!==2||!Number.isInteger(r.port)||r.port<1024||r.port>65535||typeof r.token!=="string"||!/^[a-zA-Z0-9_-]{43}$/.test(r.token))throw Error("probe_receipt_invalid");P=!0,f({port:r.port,token:r.token})}else if(d==="ready")w(!0);else o()}catch{o()}}}),b.then(o);let h,u=!1;try{let e=await Promise.race([k,v]);if(!e||!t.pid||n.signal.aborted||a.aborted)return!1;let c=Date.now()+4500,d=s(),r={organizationId:s(),userId:s(),runId:s(),deviceId:s(),rootId:s(),attachmentRevision:0,grantRevision:1,jobId:"readiness",generation:1,fenceId:s(),port:e.port,expiresAtMs:c},L={binding:r,executorLaunchId:d,job:{jobId:r.jobId,state:"running",startedAtMs:Date.now(),finishedAtMs:null,leaseExpiresAtMs:c,exitCode:null,inputSequence:0,output:[],firstCursor:1,nextCursor:0,truncated:!1,process:{pid:t.pid,processGroupId:t.pid,executorLaunchId:d}}},x=ht({binding:r,deniedPorts:new Set,readCurrentJob:async()=>!l&&!n.signal.aborted?L:null});h=await pt({binding:r,deviceRelayUrl:`ws://127.0.0.1:${e.port}/device/readiness/${e.token}`,port:x,signal:n.signal}),u=await Promise.race([I,v])===!0&&!n.signal.aborted&&!a.aborted}catch{u=!1}finally{if(clearTimeout(y),a.removeEventListener("abort",o),h?.close(),n.abort(),t.stdin.destroy(),!l)t.kill("SIGKILL");await b}return u&&l}
5
- export{Zi};
4
+ `),d=i.slice(0,c);i=i.slice(c+1);try{if(!P){let r=JSON.parse(d);if(!r||Object.keys(r).length!==2||!Number.isInteger(r.port)||r.port<1024||r.port>65535||typeof r.token!=="string"||!/^[a-zA-Z0-9_-]{43}$/.test(r.token))throw Error("probe_receipt_invalid");P=!0,f({port:r.port,token:r.token})}else if(d==="ready")w(!0);else o()}catch{o()}}}),b.then(o);let h,u=!1;try{let e=await Promise.race([k,v]);if(!e||!t.pid||n.signal.aborted||a.aborted)return!1;let c=Date.now()+4500,d=s(),r={organizationId:s(),userId:s(),runId:s(),deviceId:s(),rootId:s(),attachmentRevision:0,grantRevision:1,jobId:"readiness",generation:1,fenceId:s(),port:e.port,expiresAtMs:c},L={binding:r,executorLaunchId:d,job:{jobId:r.jobId,state:"running",startedAtMs:Date.now(),finishedAtMs:null,leaseExpiresAtMs:c,exitCode:null,inputSequence:0,output:[],firstCursor:1,nextCursor:0,truncated:!1,process:{pid:t.pid,processGroupId:t.pid,executorLaunchId:d}}},x=ft({binding:r,deniedPorts:new Set,readCurrentJob:async()=>!l&&!n.signal.aborted?L:null});h=await ht({binding:r,deviceRelayUrl:`ws://127.0.0.1:${e.port}/device/readiness/${e.token}`,port:x,signal:n.signal}),u=await Promise.race([I,v])===!0&&!n.signal.aborted&&!a.aborted}catch{u=!1}finally{if(clearTimeout(y),a.removeEventListener("abort",o),h?.close(),n.abort(),t.stdin.destroy(),!l)t.kill("SIGKILL");await b}return u&&l}
5
+ export{to};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{w,ye}from"./vm-hands-entry-lite-q9s1e2y1.js";import{yt}from"./vm-hands-entry-lite-hs6sdn60.js";import{randomBytes as f}from"crypto";import{chmodSync as c,existsSync as a,lstatSync as p,mkdirSync as u,readFileSync as g,renameSync as m,unlinkSync as l,writeFileSync as d}from"fs";import{homedir as y}from"os";import{dirname as S,join as o}from"path";function Q(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=w({env:r})==="staging"?["staging"]:[];return o(yt(e,...t),"credentials.json")}function ro(r,n=Q()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
2
+ import{w,ye}from"./vm-hands-entry-lite-33at6g06.js";import{wt}from"./vm-hands-entry-lite-88dxn9b5.js";import{randomBytes as f}from"crypto";import{chmodSync as c,existsSync as a,lstatSync as p,mkdirSync as u,readFileSync as g,renameSync as m,unlinkSync as l,writeFileSync as d}from"fs";import{homedir as y}from"os";import{dirname as S,join as o}from"path";function Q(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=w({env:r})==="staging"?["staging"]:[];return o(wt(e,...t),"credentials.json")}function oo(r,n=Q()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
3
3
  `,{mode:384}),c(n,384),n}function ve(r=Q()){if(!a(r))return null;try{let n=g(r,"utf8"),e=JSON.parse(n);if(typeof e.apiOrigin!=="string"||typeof e.clientId!=="string"||typeof e.accessToken!=="string"||typeof e.refreshToken!=="string"||typeof e.expiresAt!=="string"||typeof e.orgId!=="string"||!Array.isArray(e.scopes))return null;let i=new URL(e.apiOrigin).origin,t=ye(i);if(t!==i)k(r,n,t);return{apiOrigin:t,clientId:e.clientId,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,scopes:e.scopes.filter((s)=>typeof s==="string"),orgId:e.orgId}}catch{return null}}function k(r,n,e){let i=`${r}.${process.pid}.${f(6).toString("hex")}.tmp`;try{let t=p(r);if(!t.isFile()||process.platform!=="win32"&&t.uid!==process.geteuid?.())return;let s=JSON.parse(n);if(d(i,`${JSON.stringify({...s,apiOrigin:e},null,2)}
4
- `,{mode:384,flag:"wx"}),c(i,384),g(r,"utf8")!==n)throw Error("credentials_changed");m(i,r)}catch{try{l(i)}catch{}}}function no(r=Q()){if(!a(r))return!1;return l(r),!0}
5
- export{Q,ro,ve,no};
4
+ `,{mode:384,flag:"wx"}),c(i,384),g(r,"utf8")!==n)throw Error("credentials_changed");m(i,r)}catch{try{l(i)}catch{}}}function so(r=Q()){if(!a(r))return!1;return l(r),!0}
5
+ export{Q,oo,ve,so};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{basename as o}from"path";var br=["production","staging"],s="https://api.reasonmachines.com",l="https://staging-api.reasonmachines.com";var r={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},p=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function w(n={}){let t=P(n.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(t){if(br.includes(t))return t;throw Error(`Unknown Reason CLI channel: ${t}`)}let e=o(n.executablePath??process.execPath).toLowerCase();return p.has(e)?"staging":"production"}function We(n){return n==="staging"?l:s}function _c(n){return`${We(n)}/mcp/ara`}var i={production:["https://api.ara.so",r.production.api],staging:["https://api-staging.ara.so",r.staging.api]};function ye(n){let t;try{t=new URL(n).origin}catch{return n}let e=br.find((a)=>i[a].includes(t));return e?We(e):t}function W(n,t){return n===t||ye(n)===ye(t)}function En(n,t){return br.some((e)=>i[e].includes(n)&&t===We(e))}function kn(n,t){try{let e=new URL(t);return!e.username&&!e.password&&(e.origin===We(n)||e.origin===r[n].api)}catch{return!1}}function vr(n){try{let t=new URL(n).hostname.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}
3
- export{br,w,We,_c,ye,W,En,kn,vr};
2
+ import{R}from"./vm-hands-entry-lite-z65xva21.js";import{basename as o}from"path";var xr=["production","staging"],s="https://api.reasonmachines.com",l="https://staging-api.reasonmachines.com";var r={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},p=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function w(n={}){let t=R(n.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(t){if(xr.includes(t))return t;throw Error(`Unknown Reason CLI channel: ${t}`)}let e=o(n.executablePath??process.execPath).toLowerCase();return p.has(e)?"staging":"production"}function Ve(n){return n==="staging"?l:s}function kc(n){return`${Ve(n)}/mcp/ara`}var i={production:["https://api.ara.so",r.production.api],staging:["https://api-staging.ara.so",r.staging.api]};function ye(n){let t;try{t=new URL(n).origin}catch{return n}let e=xr.find((a)=>i[a].includes(t));return e?Ve(e):t}function W(n,t){return n===t||ye(n)===ye(t)}function Cn(n,t){return xr.some((e)=>i[e].includes(n)&&t===Ve(e))}function An(n,t){try{let e=new URL(t);return!e.username&&!e.password&&(e.origin===Ve(n)||e.origin===r[n].api)}catch{return!1}}function Cr(n){try{let t=new URL(n).hostname.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}
3
+ export{xr,w,Ve,kc,ye,W,Cn,An,Cr};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{ct}from"./vm-hands-entry-lite-qf990rxw.js";var oo=ct(function(t,e){e.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
- export{oo};
2
+ import{lt}from"./vm-hands-entry-lite-fn2805g8.js";var co=lt(function(t,e){e.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
+ export{co};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{te}from"./vm-hands-entry-lite-9g52kxyj.js";import{_r}from"./vm-hands-entry-lite-jpvmkce5.js";import{dn}from"./vm-hands-entry-lite-zh6ncdjn.js";import{Se}from"./vm-hands-entry-lite-pxtycfdv.js";import{Ve}from"./vm-hands-entry-lite-zawytz09.js";import{Dt}from"./vm-hands-entry-lite-ab1pq3xg.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as W,statSync as J}from"fs";import{platform as h}from"os";import{isAbsolute as q,sep as X}from"path";import{existsSync as F}from"fs";import{createRequire as H}from"module";var k=Dt(dn)(()=>H(import.meta.url)("bun:ffi"),F);function fi(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function E(e=process.env){return k.defaultShell(e)}function C(e){return k.shellArgs(e)}function M(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var mi=43200000,an=_r,gi=4,Y=/^[A-Za-z0-9._:-]{1,160}$/,K=1000;function z(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(K,Math.max(1,Math.floor(e)))}function G(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!z(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Y.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:te(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+mi)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function Q(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+X)}function N(e,n){if(n===void 0)return e;if(!q(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=W(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!Q(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!J(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function Yc(e=process.env){if(h()==="win32")return E(e);let n=e.SHELL;if(n&&q(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function V(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Lo(){if(h()==="win32")return fi();return typeof globalThis.Bun<"u"}var Z=(e)=>{if(h()==="win32")try{return M({...e,file:e.shell,args:C(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=V()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},_i=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function ee(e){if(v.size>=gi||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function $o(e,n={}){let o=n.now??Date.now,t=G(e.payload,o()),c=ee(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?Ve(e.root,t.workspace):void 0;g=a?N(D(a.boundary)?W(a.boundary):a.boundary,a.path):N(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??Yc(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let I=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>an)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>an)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??Z)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)I(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let j=(n.loadProxy??Se)()?.url;try{i=(n.connect??_i)(t.relay_url,j)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!z(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
- export{fi,mi,an,gi,Yc,Lo,_i,$o};
2
+ import{te}from"./vm-hands-entry-lite-kbnxk71q.js";import{_r}from"./vm-hands-entry-lite-zp7chzcc.js";import{gn}from"./vm-hands-entry-lite-a3gq377t.js";import{Se}from"./vm-hands-entry-lite-xfak34av.js";import{Ge}from"./vm-hands-entry-lite-12ck5swp.js";import{Ot}from"./vm-hands-entry-lite-wnqqjsew.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as W,statSync as J}from"fs";import{platform as h}from"os";import{isAbsolute as q,sep as X}from"path";import{existsSync as F}from"fs";import{createRequire as H}from"module";var k=Ot(gn)(()=>H(import.meta.url)("bun:ffi"),F);function _i(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function E(e=process.env){return k.defaultShell(e)}function C(e){return k.shellArgs(e)}function M(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var yi=43200000,pn=_r,wi=4,Y=/^[A-Za-z0-9._:-]{1,160}$/,K=1000;function z(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(K,Math.max(1,Math.floor(e)))}function G(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!z(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Y.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:te(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+yi)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function Q(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+X)}function N(e,n){if(n===void 0)return e;if(!q(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=W(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!Q(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!J(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function il(e=process.env){if(h()==="win32")return E(e);let n=e.SHELL;if(n&&q(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function V(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Bo(){if(h()==="win32")return _i();return typeof globalThis.Bun<"u"}var Z=(e)=>{if(h()==="win32")try{return M({...e,file:e.shell,args:C(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=V()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},bi=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function ee(e){if(v.size>=wi||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function Fo(e,n={}){let o=n.now??Date.now,t=G(e.payload,o()),c=ee(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?Ge(e.root,t.workspace):void 0;g=a?N(D(a.boundary)?W(a.boundary):a.boundary,a.path):N(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??il(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let I=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>pn)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>pn)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??Z)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)I(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let j=(n.loadProxy??Se)()?.url;try{i=(n.connect??bi)(t.relay_url,j)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!z(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
+ export{_i,yi,pn,wi,il,Bo,bi,Fo};
@@ -0,0 +1,150 @@
1
+ // @bun
2
+ import{ls,us,Mc,Dn}from"./vm-hands-entry-lite-13nx02p7.js";import{A}from"./vm-hands-entry-lite-pe374cn6.js";import{Ue,wr,br}from"./vm-hands-entry-lite-chq0qx9f.js";import{qr}from"./vm-hands-entry-lite-sh4mqy93.js";import{Vo,Kt,_c,Go,Ko,Jo,Jt}from"./vm-hands-entry-lite-srtqjjqb.js";import{bi}from"./vm-hands-entry-lite-3q2ng4e9.js";import{Se}from"./vm-hands-entry-lite-xfak34av.js";import{s}from"./vm-hands-entry-lite-12ck5swp.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as ce}from"child_process";import{randomBytes as qe}from"crypto";import{chmodSync as Ce,existsSync as ne,lstatSync as Ge,mkdirSync as Oe,readFileSync as S,rmSync as ae,writeFileSync as R}from"fs";import{connect as he}from"net";import{join as p}from"path";var B=32,N=76;var M="./desktop-wallpaper-fd8f2wb2.jpg";var v="./dock-browser-y53t41cx.png";var Z="./dock-files-cp52htdw.png";var V="./dock-terminal-1es514yq.png";var z="./grok-wallpaper-71zwn2pj.jpg";var W="./grok-dock-browser-pzw59wnd.png";var j="./grok-dock-files-eckq444x.png";var U="./grok-dock-terminal-hcpz3e43.png";var ee=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
+ # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
+ # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
+ # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
6
+ import ctypes, sys
7
+ import gi
8
+ gi.require_version("GdkPixbuf", "2.0")
9
+ from gi.repository import GdkPixbuf
10
+ x = ctypes.cdll.LoadLibrary("libX11.so.6")
11
+ x.XOpenDisplay.restype = ctypes.c_void_p
12
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
13
+ d = x.XOpenDisplay(None)
14
+ if not d: sys.exit("no display")
15
+ for name, res, args in [
16
+ ("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
17
+ ("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
18
+ ("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
19
+ ("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
20
+ ("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
21
+ ("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
22
+ ("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
23
+ ("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
24
+ ("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
25
+ ("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
26
+ ("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
27
+ ("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
28
+ ("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
29
+ ("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
30
+ ("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
31
+ ("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
32
+ ]:
33
+ f = getattr(x, name); f.restype = res; f.argtypes = args
34
+ s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
35
+ w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
36
+ if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
37
+ # Scale to cover the screen, then crop the centre.
38
+ src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
39
+ k = max(w / src.get_width(), h / src.get_height())
40
+ sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
41
+ pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
42
+ if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
43
+ rgb, stride = pb.get_pixels(), pb.get_rowstride()
44
+ bgrx = bytearray(w * h * 4)
45
+ for y in range(h):
46
+ row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
47
+ bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
48
+ buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
49
+ pix = x.XCreatePixmap(d, root, w, h, 24)
50
+ img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
51
+ x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
52
+ ref = ctypes.c_ulong(pix)
53
+ for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
54
+ x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
55
+ x.XSetWindowBackgroundPixmap(d, root, pix)
56
+ x.XClearWindow(d, root)
57
+ x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
58
+ x.XCloseDisplay(d)
59
+ `;function Ae(e){return`<?xml version="1.0" encoding="UTF-8"?>
60
+ <openbox_config xmlns="http://openbox.org/3.4/rc">
61
+ <theme><keepBorder>no</keepBorder></theme>
62
+ <applications>
63
+ <!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
64
+ <application class="Chromium*">
65
+ <decor>no</decor>
66
+ <position force="yes"><x>${B}</x><y>${B}</y></position>
67
+ <size><width>${e.width-B*2}</width><height>${e.height-B-N}</height></size>
68
+ </application>
69
+ </applications>
70
+ </openbox_config>`}var Pe=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
71
+ panel_items = L
72
+ panel_size = 100% 46
73
+ panel_margin = 0 10
74
+ panel_padding = 0 0 10
75
+ panel_position = bottom center horizontal
76
+ panel_shrink = 1
77
+ panel_background_id = 0
78
+ panel_layer = top
79
+ mouse_effects = 1
80
+ mouse_hover_icon_asb = 100 0 12
81
+ mouse_pressed_icon_asb = 100 0 -12
82
+
83
+ launcher_icon_size = 46
84
+ launcher_padding = 0 0 10
85
+ launcher_background_id = 0
86
+ launcher_tooltip = 1
87
+
88
+ launcher_item_app = /tmp/ara-chromium.desktop
89
+ launcher_item_app = /tmp/ara-files.desktop
90
+ launcher_item_app = /tmp/ara-terminal.desktop
91
+ `,re=32,Ye=`# Remote sandbox dock (grok look) \u2014 small launcher icons only, centred, no panel fill
92
+ panel_items = L
93
+ panel_size = 100% ${re+16}
94
+ panel_margin = 0 0
95
+ panel_padding = 0 0 8
96
+ panel_position = bottom center horizontal
97
+ panel_shrink = 1
98
+ panel_background_id = 0
99
+ panel_layer = top
100
+ mouse_effects = 1
101
+ mouse_hover_icon_asb = 100 0 10
102
+ mouse_pressed_icon_asb = 100 0 -10
103
+
104
+ launcher_icon_size = ${re}
105
+ launcher_padding = 0 0 8
106
+ launcher_background_id = 0
107
+ launcher_tooltip = 1
108
+
109
+ launcher_item_app = /tmp/ara-chromium.desktop
110
+ launcher_item_app = /tmp/ara-files.desktop
111
+ launcher_item_app = /tmp/ara-terminal.desktop
112
+ `,Ne=`corner-radius = 12;
113
+ rounded-corners-exclude = [
114
+ "class_g = 'tint2'",
115
+ "window_type = 'dock'",
116
+ "window_type = 'desktop'"
117
+ ];
118
+ backend = "xrender";
119
+ shadow = false;
120
+ fading = false;
121
+ vsync = false;
122
+ inactive-opacity = 1.0;
123
+ active-opacity = 1.0;
124
+ `,ue="/tmp/ara-dock-browser.png",Re=`[Desktop Entry]
125
+ Name=Chrome
126
+ Exec=chromium --no-sandbox %U
127
+ Icon=${ue}
128
+ Type=Application
129
+ Categories=Network;WebBrowser;
130
+ `,ge=`[Desktop Entry]
131
+ Name=Terminal
132
+ Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
133
+ Icon=/tmp/ara-dock-terminal.png
134
+ Type=Application
135
+ Categories=System;TerminalEmulator;
136
+ `,De=`[Desktop Entry]
137
+ Name=Files
138
+ Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
139
+ Icon=/tmp/ara-dock-files.png
140
+ Type=Application
141
+ Categories=System;FileManager;
142
+ `;var te={"wallpaper.jpg":M,"dock-browser.png":v,"dock-terminal.png":V,"dock-files.png":Z,"grok-wallpaper.jpg":z,"grok-dock-browser.png":W,"grok-dock-terminal.png":U,"grok-dock-files.png":j},Ke=ee,Fe='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function $e(e){let D=(I)=>I.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),n=e.look==="grok",d=new Set(e.absent??[]),t=d.has("files")&&e.filesViewerExec?e.filesViewerExec:null;if(t)d.delete("files");let c=(n?Ye:Pe).split(`
143
+ `).filter((I)=>!(d.has("terminal")&&I.endsWith("/ara-terminal.desktop"))&&!(d.has("files")&&I.endsWith("/ara-files.desktop"))).join(`
144
+ `),a=(I)=>n?I.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):I,o=t?De.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):De,f=n?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":Ae(e.screen),"tint2/tint2rc":D(c),"picom/picom.conf":Ne,...d.has("terminal")?{}:{"ara-terminal.desktop":D(a(ge))},...d.has("files")?{}:{"ara-files.desktop":D(a(o))},"ara-chromium.desktop":D(a(Re)).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Ke},X=[...u.slice(0,3),Fe,`[ ! -f "$ROOT/${f}" ] || set_wallpaper "$ROOT/${f}" "$ROOT/ara-set-root-wallpaper.py" || true`,'if alive tint2 && ! cmp -s "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied"; then read -r pid _ <"$ROOT/tint2.pid"; kill -USR1 "$pid" 2>/dev/null || true; fi','cp "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied" 2>/dev/null || true',...u.slice(3)];return{files:i,start:X}}var u=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Je=43200000,y=":99",Qe=60000,Y=15000,g={width:1280,height:800},ke=/^[A-Za-z0-9._:-]{1,160}$/;function _e(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var we=["video","viewer","viewer_same_network","viewer_network","look"];function me(e,D=Date.now()){let n=["relay_url","session_id","expires_at"];if(!_e(e)||n.some((f)=>!(f in e))||Object.keys(e).some((f)=>!n.includes(f)&&!we.includes(f)))throw new r("invalid_display_request","Reason desktop request is malformed.");let d="video"in e?Mc(e.video):void 0,t="viewer"in e?ls(e.viewer):null,c="look"in e?us(e.look):null;if(d===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let a=null;try{a=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!a||a.protocol!=="wss:"&&a.protocol!=="ws:"||a.username||a.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!ke.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let o=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(o)||o<=D)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(o,D+Je)).toISOString(),...d?{video:d}:{},...t?{viewer:t}:{},...d&&e.viewer_same_network===!0?{viewer_same_network:!0}:{},...c?{look:c}:{}}}function un(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&A()?.features.display===!0}async function Mo(){if(process.platform==="win32")return un()&&await Jt();if(process.platform!=="darwin")return un();return await Jt()}function Te(e){Oe(e,{recursive:!0,mode:448});let D=Ge(e);if(!D.isDirectory()||D.isSymbolicLink()||process.getuid&&D.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");Ce(e,448)}function Me(e,D){let n=(t)=>{let c=Buffer.alloc(2);return c.writeUInt16BE(t.length),Buffer.concat([c,t])},d=Buffer.from([255,255]);return Buffer.concat([d,n(Buffer.alloc(0)),n(Buffer.from(e)),n(Buffer.from("MIT-MAGIC-COOKIE-1")),n(D)])}function x(e,D,n=2000){return new Promise((d)=>{let t=he(e),c="",a=(o)=>{t.destroy(),d(o)};t.setTimeout(n,()=>a(!1)),t.once("error",()=>a(!1)),t.once("close",()=>a(!1)),t.once("connect",()=>{if(!D)a(!0)}),t.on("data",(o)=>{if(c+=o.toString("latin1"),c.length>=4)a(c.startsWith("RFB "))})})}async function Q(e,D){let n=Date.now()+D;while(Date.now()<n){if(await e())return!0;await new Promise((d)=>setTimeout(d,100))}return!1}function K(e,D,n,d=!1){return new Promise((t)=>{let c=ce(e,D,{detached:!0,stdio:"ignore",env:n});if(d)Ue(c.pid);c.once("error",()=>t(-1)),c.once("exit",(a)=>t(a)),c.unref(),setTimeout(()=>t(null),Y).unref()})}var J=null;function jt(e=s()){return J??=ve(e).finally(()=>{J=null}),J}async function ve(e){let D=A({home:e});if(!D?.xvfb||!D.x11vnc||!D.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");qr({root:D.root,automation:D.automation,extensionDir:D.extensionDir});let n=p(D.root,"display");Te(n);let d=await ze(e,n,D.x11vnc);if(d)return d;let t={display:y,xauthority:p(n,"Xauthority"),rfbSocket:p(n,"rfb.sock")},c=p(n,"pulse"),a=(async()=>{try{Te(c)}catch{return null}return await _c(c,D.pulseaudio)})();Te(p(n,"home"));let o=k(n,t,D.pulseaudio),f=async()=>({...t,sound:await a});if(await x({path:t.rfbSocket},!0))return pe(p(n,"theme"),u,o),await f();if(!ne(t.xauthority))R(t.xauthority,Me(y.slice(1),qe(16)),{mode:384,flag:"wx"});let i=T(p(n,"theme"),t.display,g,e),X={path:`/tmp/.X11-unix/X${y.slice(1)}`};if(!await x(X,!1)){let I=`${g.width}x${g.height}`,L;if(D.xvnc)ae(t.rfbSocket,{force:!0}),L=K(D.xvnc,[t.display,"-geometry",I,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-UseBlacklist=0","-AlwaysShared","-desktop","Reason"],o,!0);else L=K(D.xvfb,[t.display,"-screen","0",`${I}x24`,"-nolisten","tcp","-auth",t.xauthority],o,!0);if(!await Q(()=>x(X,!1),Y)||D.xvnc&&!await Q(()=>x({path:t.rfbSocket},!0),Y)){if(await L!==null&&Ze())wr("display");throw new r("display_unavailable","Reason could not start the virtual display.")}K(D.openbox,["--config-file",i.openboxConfig],o,!0)}if(await _(i,o),!await oe(D.x11vnc,t,n,"x11vnc.log",o))throw new r("display_unavailable","Reason could not start the desktop server.");return await f()}function Ze(){let e=0;try{e=Number(S(`/tmp/.X${y.slice(1)}-lock`,"utf8").trim())}catch{return!1}if(!Number.isSafeInteger(e)||e<=1)return!1;try{return process.kill(e,0),!0}catch(D){return D.code==="EPERM"}}function k(e,D,n){let d={HOME:p(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:D.display,XAUTHORITY:D.xauthority};if(n)d.PULSE_SERVER=Kt(Vo(p(e,"pulse")));return d}async function oe(e,D,n,d,t){if(await x({path:D.rfbSocket},!0))return!0;ae(D.rfbSocket,{force:!0});let c=await K(e,["-display",D.display,"-auth",D.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",D.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",p(n,d)],t);if(c!==null&&c!==0)return!1;if(!await Q(()=>x({path:D.rfbSocket},!0),Y))return!1;return br("x11vnc",D.rfbSocket),!0}async function Ve(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],D=(n)=>Object.fromEntries(e.flatMap((d)=>n[d]?[[d,n[d]]]:[]));if(process.env.DISPLAY)return D(process.env);try{let n=await new Promise((d,t)=>se("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(c,a)=>c?t(c):d(a)));return D(Object.fromEntries(n.split(`
145
+ `).flatMap((d)=>{let t=d.indexOf("=");return t>0?[[d.slice(0,t),d.slice(t+1)]]:[]})))}catch{return{}}}var de=new Set;async function ze(e,D,n){let d=await Ve(),t=/^:(\d+)(?:\.\d+)?$/.exec(d.DISPLAY??"")?.[1];if(!t||`:${t}`===y||d.WAYLAND_DISPLAY||d.XDG_SESSION_TYPE==="wayland")return null;let c={display:`:${t}`,xauthority:d.XAUTHORITY??p(e,".Xauthority"),rfbSocket:p(D,`rfb-${t}.sock`)},a=`${c.display} ${c.xauthority}`;if(de.has(a)||!await x({path:`/tmp/.X11-unix/X${t}`},!1))return null;let o={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:c.display,XAUTHORITY:c.xauthority};if(await oe(n,c,D,`x11vnc-${t}.log`,o))return{...c,sound:null};return de.add(a),process.stderr.write(`Reason worker: your screen ${c.display} could not be served; using the virtual desktop
146
+ `),null}var ie="look";function fe(e){try{return us(S(p(e,ie),"utf8").trim())??"reason"}catch{return"reason"}}function T(e,D,n,d,t=fe(e)){let c=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,a=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!ne(`/usr/bin/${i}`)).map(([i])=>i),o=`${c.replace(/ %U$/,"")} --app=file://${p(d,".reason","workspace")}/`,f=$e({root:e,display:D,screen:n,browserExec:c,absent:a,look:t,filesViewerExec:o});for(let i of["","openbox","tint2","picom"])Te(p(e,i));R(p(e,ie),`${t}
147
+ `,{mode:384});for(let[i,X]of Object.entries(f.files))R(p(e,i),X,{mode:384});for(let[i,X]of Object.entries(te))R(p(e,`ara-${i}`),S(X),{mode:384});return{root:e,openboxConfig:p(e,"openbox","rc.xml"),start:f.start}}function _(e,D){return pe(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],D)}function pe(e,D,n){let d=[`ROOT=${JSON.stringify(e)}`,...D].join(`
148
+ `);return new Promise((t)=>{let c=ce("/bin/sh",["-c",d],{stdio:"ignore",env:{...n,PATH:"/usr/bin:/bin"}}),a=setTimeout(()=>{c.kill(),t()},Y);c.once("error",()=>{clearTimeout(a),t()}),c.once("exit",()=>{clearTimeout(a),t()})})}var We=2073600,je=320;function er(e,D){let n=Math.min(1,Math.sqrt(We/(e.width*e.height))),d=(t,c)=>Math.min(Math.floor(c/8)*8,Math.max(je,Math.round(t*n/8)*8));return{width:d(e.width,D.width),height:d(e.height,D.height)}}function w(e,D,n){return new Promise((d)=>se(e,D,{env:n,encoding:"utf8",timeout:5000},(t,c)=>d(t?null:c)))}function Ie(e){let D=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),n=e.split(`
149
+ `),d=n.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of n.slice(d+1)){let a=/^\s+(\d+x\d+)\s/.exec(c);if(!a)break;t.push(a[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:n[d].split(" ")[0],modes:t}}async function rr(e,D,n){if(e.display!==y)return null;let d={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(f)=>w("xrandr",f,d),c=Ie(await t(["--query"])??"");if(!c||c.maximum.width<=c.current.width&&c.maximum.height<=c.current.height)return null;let a=er(D,c.maximum);if(a.width===c.current.width&&a.height===c.current.height)return{size:a,changed:!1};let o=`${a.width}x${a.height}`;if(!c.modes.includes(o)){if(await t(["--newmode",o,"60",...[a.width,a.width,a.width,a.width,a.height,a.height,a.height,a.height].map(String)]),await t(["--addmode",c.output,o])===null)return null}return n(),await t(["--output",c.output,"--mode",o])===null?null:{size:a,changed:!0}}async function Dr(e,D){let n=s(),d=A({home:n});if(!d)return;let t=p(d.root,"display"),c=k(t,e,d.pulseaudio);await _(T(p(t,"theme"),e.display,D,n),c);let a=D.width-B*2,o=D.height-B-N;await w("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(a),String(o),"windowmove","%@",String(B),String(B)],{...c,PATH:"/usr/bin:/bin"})}var F=Promise.resolve();function tr(e,D,n=()=>{}){let d=F.then(()=>rr(e,D,n));return F=d.then((t)=>t?.changed?Dr(e,t.size):void 0).catch(()=>{}),d.then((t)=>t?.size??null,()=>null)}function $r(e,D){if(e.display!==y)return Promise.resolve();let n=F.then(async()=>{let d=s(),t=A({home:d});if(!t)return;let c=p(t.root,"display"),a=p(c,"theme");if(fe(a)===D)return;let o=k(c,e,t.pulseaudio),f=Ie(await w("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await _(T(a,e.display,f?.current??g,d,D),o)});return F=n.catch(()=>{}),n.catch(()=>{})}async function dn(e,D={}){let n=D.now??Date.now,d=me(e.payload,n());if(e.signal.throwIfAborted(),!d.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=D.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let{video:c,look:a}=d,o=(D.video?.desktop??(t==="darwin"?async()=>Go:t==="win32"?async()=>Ko:async()=>{let f=await jt();if(a)await $r(f,a);return f}))();return await dr(e.signal,d,D,n,(f)=>Jo(f,{request:c,desktop:o,...d.viewer?{viewer:d.viewer}:{},viewerSameNetwork:d.viewer_same_network===!0},{resizeDesktop:tr,...D.video}),(f)=>Dn({type:"error",code:f}))}function dr(e,D,n,d,t,c){let a=d();return new Promise((o,f)=>{let i=null,X=!1,I=!1,L,q,P,C=!1,l=null,E=(b)=>{if(I)return;if(l)b=l.outcome;I=!0,clearTimeout(L),clearTimeout(q),e.removeEventListener("abort",O),P?.close();try{i?.close(1000,"display_session_over")}catch{}if("error"in b){f(b.error);return}o({reason:b.reason,...P?.summary(),duration_ms:Math.max(0,d()-a)})},G=()=>E({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),O=()=>{let b=e.reason;E({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},m=()=>{if(!l||!i)return;let{outcome:b}=l,H=!("error"in b)?b.reason:b.error instanceof r?b.error.code:"display_unavailable";if(!l.told)try{i.send(c(H))}catch{}E(b)};if(P=t({get done(){return I||l!==null},get open(){return X&&!I&&l===null},get bufferedAmount(){return i?.bufferedAmount??0},send(b){if(I||l||!X||!i)return;try{i.send(b)}catch{E({reason:"relay_closed"})}},end:(b)=>{if(I||l)return;if(!("error"in b)&&C&&X){E(b);return}if(l={outcome:b,told:!("error"in b)&&X},C&&X)m()}}),I){P.close();return}if(e.aborted){O();return}e.addEventListener("abort",O,{once:!0}),L=setTimeout(()=>E({reason:"session_expired"}),Math.max(1,Date.parse(D.expires_at)-d())),q=setTimeout(()=>E({reason:"viewer_absent"}),n.viewerWaitMs??Qe);try{i=(n.connect??bi)(D.relay_url,(n.loadProxy??Se)()?.url)}catch{G();return}i.binaryType="arraybuffer",i.onopen=()=>{if(I||!i)return;X=!0,P?.opened()},i.onmessage=(b)=>{if(I)return;let H=b.data,h=H instanceof ArrayBuffer?new Uint8Array(H):ArrayBuffer.isView(H)?new Uint8Array(H.buffer,H.byteOffset,H.byteLength):null;if(!h||h.byteLength===0)return;if(clearTimeout(q),C=!0,l){m();return}P?.received(h)},i.onclose=()=>{if(I)return;if(!X){G();return}E({reason:"relay_closed"})},i.onerror=()=>{if(I||X)return;G()}})}
150
+ export{un,Mo,Te,jt,dn};
@@ -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-f8p11q6h.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-61p78r72.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};