@reason-machines/cli-linux-x64 0.2.416 → 0.2.418

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 (117) hide show
  1. package/bin/reason +1 -1
  2. package/bin/runtime/srt/sandbox-runtime.mjs +38 -38
  3. package/bin/vm-hands/api-18d75dfn.js +2 -0
  4. package/bin/vm-hands/api-credentials-3vhge1ap.js +2 -0
  5. package/bin/vm-hands/connect-cli-pn1h0b08.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-17t4efc4.js +2 -0
  7. package/bin/vm-hands/desktop-account-6sjrxy69.js +2 -0
  8. package/bin/vm-hands/device-workspace-s50q53sz.js +2 -0
  9. package/bin/vm-hands/{fsevents-ekt70rcc.js → fsevents-p3d8kd0p.js} +1 -1
  10. package/bin/vm-hands/hands-worker-source-kddz4y15.js +2 -0
  11. package/bin/vm-hands/{index-k8kcz8a3.js → index-wrw65904.js} +35 -35
  12. package/bin/vm-hands/install-receipt-ysa70fvh.js +2 -0
  13. package/bin/vm-hands/local-automation-7nc6cgjp.js +2 -0
  14. package/bin/vm-hands/local-capabilities-5f36fr9x.js +2 -0
  15. package/bin/vm-hands/local-desktop-users-cppjjr81.js +2 -0
  16. package/bin/vm-hands/local-display-mac-0qz3b627.js +2 -0
  17. package/bin/vm-hands/local-display-session-zg4dpnf1.js +2 -0
  18. package/bin/vm-hands/local-display-video-remg1c30.js +2 -0
  19. package/bin/vm-hands/local-managed-process-gjc8gvgb.js +2 -0
  20. package/bin/vm-hands/local-pty-session-rpk05ap5.js +2 -0
  21. package/bin/vm-hands/managed-runtime-f85h6h7f.js +2 -0
  22. package/bin/vm-hands/network-contract-trkxqc0w.js +2 -0
  23. package/bin/vm-hands/package-xqbhdf15.js +2 -0
  24. package/bin/vm-hands/permissions-bhbnb1bp.js +2 -0
  25. package/bin/vm-hands/reason-hands-protocol-xn3ddz70.js +2 -0
  26. package/bin/vm-hands/serve-service-58ea9cwx.js +2 -0
  27. package/bin/vm-hands/status-z9r8nq3y.js +10 -0
  28. package/bin/vm-hands/version-p0g28erd.js +2 -0
  29. package/bin/vm-hands/{vm-hands-entry-lite-bdhjpv7g.js → vm-hands-entry-lite-21qpxvt8.js} +2 -2
  30. package/bin/vm-hands/vm-hands-entry-lite-2nkj0dpx.js +539 -0
  31. package/bin/vm-hands/vm-hands-entry-lite-2wzsnnsp.js +3 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-8t9xssf9.js → vm-hands-entry-lite-3krzmhkk.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-k278g9kj.js → vm-hands-entry-lite-4vks5phw.js} +5 -5
  34. package/bin/vm-hands/{vm-hands-entry-lite-1cwqa4jr.js → vm-hands-entry-lite-50zbqwkv.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-1rrb66r9.js → vm-hands-entry-lite-5dtfehjv.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-6aeea05q.js → vm-hands-entry-lite-60pg3wxj.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-9ay6f56v.js → vm-hands-entry-lite-6c67a3jc.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-zybbbegw.js → vm-hands-entry-lite-6wt5ja1k.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-zg36myyf.js → vm-hands-entry-lite-8r31b0ps.js} +4 -4
  40. package/bin/vm-hands/vm-hands-entry-lite-ah6fwqxp.js +128 -0
  41. package/bin/vm-hands/{vm-hands-entry-lite-ckv17tn8.js → vm-hands-entry-lite-aj139v8j.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-907pa7f9.js → vm-hands-entry-lite-avc65bd7.js} +6 -6
  43. package/bin/vm-hands/{vm-hands-entry-lite-9c95p6n9.js → vm-hands-entry-lite-beyyy1gz.js} +37 -37
  44. package/bin/vm-hands/{vm-hands-entry-lite-ab2m9erf.js → vm-hands-entry-lite-bx5zy5bd.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-pgb514h0.js → vm-hands-entry-lite-dk79tnax.js} +2 -2
  46. package/bin/vm-hands/vm-hands-entry-lite-ec9jemny.js +5 -0
  47. package/bin/vm-hands/{vm-hands-entry-lite-gvwdy3rf.js → vm-hands-entry-lite-fbhqfzbq.js} +3 -3
  48. package/bin/vm-hands/{vm-hands-entry-lite-t7an5zg2.js → vm-hands-entry-lite-fcvf8md1.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-qysyf65v.js → vm-hands-entry-lite-g4zd2d5n.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-0xrsph3r.js → vm-hands-entry-lite-hbs3tpdg.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-f5e3dbgk.js → vm-hands-entry-lite-hk6trmwa.js} +3 -3
  52. package/bin/vm-hands/{vm-hands-entry-lite-qk4kexta.js → vm-hands-entry-lite-hn76pcgk.js} +5 -5
  53. package/bin/vm-hands/vm-hands-entry-lite-j43nqe8y.js +452 -0
  54. package/bin/vm-hands/{vm-hands-entry-lite-89z488gz.js → vm-hands-entry-lite-jev771b3.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-eqgj4acy.js → vm-hands-entry-lite-jzz73e3f.js} +10 -10
  56. package/bin/vm-hands/vm-hands-entry-lite-m8nqnd9j.js +126 -0
  57. package/bin/vm-hands/vm-hands-entry-lite-mmdwr0mf.js +2 -0
  58. package/bin/vm-hands/{vm-hands-entry-lite-enah5gv4.js → vm-hands-entry-lite-nefcet81.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-hj8n59y9.js → vm-hands-entry-lite-np07qyeq.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-1rtkf2xm.js → vm-hands-entry-lite-nzmkyezg.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-q0k6kx6d.js → vm-hands-entry-lite-pf5qtbj5.js} +4 -4
  62. package/bin/vm-hands/{vm-hands-entry-lite-cs5t8eyd.js → vm-hands-entry-lite-ppmvge7n.js} +5 -5
  63. package/bin/vm-hands/{vm-hands-entry-lite-m11j0f9q.js → vm-hands-entry-lite-rfz60hb3.js} +2 -2
  64. package/bin/vm-hands/vm-hands-entry-lite-s3cg1dsk.js +52 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-s4bharcb.js +9 -0
  66. package/bin/vm-hands/{vm-hands-entry-lite-88swf2qr.js → vm-hands-entry-lite-s5qkb1fk.js} +3 -3
  67. package/bin/vm-hands/{vm-hands-entry-lite-dqd4p5kw.js → vm-hands-entry-lite-stmbekq0.js} +16 -16
  68. package/bin/vm-hands/{vm-hands-entry-lite-6sgfhegd.js → vm-hands-entry-lite-svvysppj.js} +4 -4
  69. package/bin/vm-hands/{vm-hands-entry-lite-22kfyvnk.js → vm-hands-entry-lite-tdgtpx8e.js} +1 -1
  70. package/bin/vm-hands/{vm-hands-entry-lite-b885gwfh.js → vm-hands-entry-lite-vpz54vwj.js} +6 -6
  71. package/bin/vm-hands/vm-hands-entry-lite-w8w451gj.js +4 -0
  72. package/bin/vm-hands/{vm-hands-entry-lite-09m2cdkw.js → vm-hands-entry-lite-wx4ax7wg.js} +3 -3
  73. package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +3 -0
  74. package/bin/vm-hands/vm-hands-entry-lite-z76nfb19.js +3 -0
  75. package/bin/vm-hands/vm-hands-entry-lite-zp6naptr.js +3 -0
  76. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  77. package/bin/vm-hands/vm-hands-executor-73b49jkg.js +11 -0
  78. package/bin/vm-hands/vm-hands-op-runner-ef9ts9c6.js +2 -0
  79. package/bin/vm-hands/vm-hands-runtime-8z6rx1fj.js +4 -0
  80. package/bin/vm-hands/worker-preview-readiness-w62n91kr.js +2 -0
  81. package/bin/vm-hands/worker-sandbox-2r5nseff.js +2 -0
  82. package/package.json +1 -1
  83. package/bin/vm-hands/api-cjv8m2zy.js +0 -2
  84. package/bin/vm-hands/api-credentials-m5akr9fv.js +0 -2
  85. package/bin/vm-hands/connect-cli-pcfvh00f.js +0 -2
  86. package/bin/vm-hands/custom-endpoint-device-dkqb4rqy.js +0 -2
  87. package/bin/vm-hands/desktop-account-5v7x0ajx.js +0 -2
  88. package/bin/vm-hands/device-workspace-p9q9dckg.js +0 -2
  89. package/bin/vm-hands/hands-worker-source-cgrpm21b.js +0 -2
  90. package/bin/vm-hands/install-receipt-7vt2y2vh.js +0 -2
  91. package/bin/vm-hands/local-automation-zj5h05b9.js +0 -2
  92. package/bin/vm-hands/local-capabilities-gkdh1z5z.js +0 -2
  93. package/bin/vm-hands/local-desktop-users-q886k0mm.js +0 -2
  94. package/bin/vm-hands/local-display-mac-w85956f1.js +0 -2
  95. package/bin/vm-hands/local-display-session-m6an1hqp.js +0 -2
  96. package/bin/vm-hands/local-pty-session-5f50sqq0.js +0 -2
  97. package/bin/vm-hands/managed-runtime-esfmzn6z.js +0 -2
  98. package/bin/vm-hands/network-contract-9x9kc5vv.js +0 -2
  99. package/bin/vm-hands/package-78fkast4.js +0 -2
  100. package/bin/vm-hands/permissions-bvfecyb8.js +0 -2
  101. package/bin/vm-hands/reason-hands-protocol-2tnghj3b.js +0 -2
  102. package/bin/vm-hands/serve-service-mr4mkymv.js +0 -2
  103. package/bin/vm-hands/status-7m9d0yek.js +0 -10
  104. package/bin/vm-hands/version-4bsjs55h.js +0 -2
  105. package/bin/vm-hands/vm-hands-entry-lite-7n60veqy.js +0 -458
  106. package/bin/vm-hands/vm-hands-entry-lite-8ns59paz.js +0 -3
  107. package/bin/vm-hands/vm-hands-entry-lite-8vfd0kez.js +0 -250
  108. package/bin/vm-hands/vm-hands-entry-lite-pmcz7j7t.js +0 -3
  109. package/bin/vm-hands/vm-hands-entry-lite-sm5nkxpw.js +0 -540
  110. package/bin/vm-hands/vm-hands-entry-lite-t7n6t3j9.js +0 -2
  111. package/bin/vm-hands/vm-hands-entry-lite-vq14wv7h.js +0 -52
  112. package/bin/vm-hands/vm-hands-entry-lite-vrqzr15t.js +0 -3
  113. package/bin/vm-hands/vm-hands-entry-lite-zjn2nsth.js +0 -3
  114. package/bin/vm-hands/vm-hands-executor-a7aqej5n.js +0 -11
  115. package/bin/vm-hands/vm-hands-op-runner-k4n3zrqb.js +0 -2
  116. package/bin/vm-hands/vm-hands-runtime-z6ydmvqc.js +0 -4
  117. package/bin/vm-hands/worker-sandbox-smqj3mbe.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$e,Fi,F,Qe,Ct,yr,P,V,Be}from"./vm-hands-entry-lite-8vfd0kez.js";import{G}from"./vm-hands-entry-lite-f5e3dbgk.js";import{st}from"./vm-hands-entry-lite-eqgj4acy.js";import{at}from"./vm-hands-entry-lite-qk4kexta.js";import{Br}from"./vm-hands-entry-lite-enah5gv4.js";import{gt,_i}from"./vm-hands-entry-lite-gvwdy3rf.js";import{be,Cn}from"./vm-hands-entry-lite-dqd4p5kw.js";import{ht}from"./vm-hands-entry-lite-k278g9kj.js";import{a}from"./vm-hands-entry-lite-89z488gz.js";import{x}from"./vm-hands-entry-lite-9ay6f56v.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{spawn as R,spawnSync as tt}from"child_process";import{createHash as ot,randomUUID as me}from"crypto";import{closeSync as rt,copyFileSync as se,existsSync as M,fstatSync as nt,mkdirSync as ie,openSync as it,readdirSync as U,readFileSync as K,readlinkSync as ct,renameSync as fe,rmSync as lt,statSync as ut,writeFileSync as dt}from"fs";import{connect as pt}from"net";import{tmpdir as L,userInfo as ge}from"os";import{basename as ae,delimiter as mt,dirname as B,join as f}from"path";var Y=`import { spawn, execFileSync } from "node:child_process";
2
+ import{We,so,F,Ve,Ft,Tr,x}from"./vm-hands-entry-lite-m8nqnd9j.js";import{K}from"./vm-hands-entry-lite-hk6trmwa.js";import{mt}from"./vm-hands-entry-lite-jzz73e3f.js";import{gt}from"./vm-hands-entry-lite-hn76pcgk.js";import{Jr}from"./vm-hands-entry-lite-nefcet81.js";import{kt,Di}from"./vm-hands-entry-lite-fbhqfzbq.js";import{G,qe}from"./vm-hands-entry-lite-ah6fwqxp.js";import{Ee,Hn}from"./vm-hands-entry-lite-stmbekq0.js";import{St}from"./vm-hands-entry-lite-4vks5phw.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{C}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{spawn as R,spawnSync as tt}from"child_process";import{createHash as ot,randomUUID as me}from"crypto";import{closeSync as rt,copyFileSync as se,existsSync as M,fstatSync as nt,mkdirSync as ie,openSync as st,readdirSync as U,readFileSync as X,readlinkSync as it,renameSync as fe,rmSync as at,statSync as ct,writeFileSync as lt}from"fs";import{connect as ut}from"net";import{tmpdir as L,userInfo as ge}from"os";import{basename as ae,delimiter as dt,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
@@ -849,7 +849,7 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
849
849
  process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
850
850
  }
851
851
  }
852
- `;import{spawn as Ee}from"child_process";import{basename as Ce}from"path";var Te="__desktop-call",Ne="/usr/bin/setpriv",Pe=27262976,De=8192,Me=2000;function q(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Ue(e){try{return JSON.parse(e)}catch{return null}}function Le(){return[process.execPath,...Ce(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Te]}function kt(e,o,t,n={}){t.throwIfAborted();let s=n.command??Le();return new Promise((i,u)=>{let c=(n.spawnProcess??Ee)(Ne,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,h,y=(_)=>{try{process.kill(-c.pid,_)}catch{c.kill(_)}},I=(_)=>{p??=_,y("SIGTERM"),h??=setTimeout(()=>y("SIGKILL"),Me)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(_)=>{if(g)return;g=!0,clearTimeout(h),t.removeEventListener("abort",S),_()};if(c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>Pe)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-De)}),c.stdin.on("error",()=>{}),c.once("error",()=>w(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(_,Oe)=>w(()=>{if(p)return u(p);let b=Ue(Buffer.concat(d).toString("utf8"));if(q(b)&&b.ok===!0&&q(b.result))return i(b.result);let O=q(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,X=`exited ${_??Oe}${O?"":" with no reply"}`,J=l.trim().split(`
853
- `).at(-1)?.slice(-300)??"";if(!O||O.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${X}${l?`: ${l.trim().slice(-500)}`:""}
854
- `);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${X}${J?`: ${J}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function z(e,o,t,n={}){let s=await kt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as qe,spawn as We}from"child_process";import{closeSync as Fe,mkdirSync as Ge,openSync as He}from"fs";import{dirname as E,join as je}from"path";import{promisify as Ke}from"util";var Xe=Ke(qe),Z="x-apple.systempreferences:com.apple.preference.security",Je={accessibility:`${Z}?Privacy_Accessibility`,screen:`${Z}?Privacy_ScreenCapture`},Ye=64,A=new Map;function C(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=Ye)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function ze(){let e=a(),o=Cn(be(e),process.env),t=je(e,".local","share","reason","desktop-install.log");Ge(E(t),{recursive:!0,mode:448});let n=He(t,"a",384);try{let s=We(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Fe(n)}}var T={open:async(e,o)=>{await Xe("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>st(e,o),tile:Br,installDesktop:ze},Q=!1;async function ee(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function oe(e,o,t,n){if(await t.open([Je[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function Ve(e,o,t,n,s){for(let i of t){if(!C(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await oe(o,i,n,s)}}var Ze={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function te(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function et(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function re(e,o=T){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return te({result:{tools:[Ze]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!Q){Q=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&C(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)C(n,`grant:${m}`);for(let m of d)await oe(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(C(n,"page:chrome-extension"))await ee(Fi,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?et(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await ee(u,o,s),te({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ne(e,o=T){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await Ve(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,ft=18874368,wt=8192,_t=65536,yt=55000,bt=60000,St=4,xt=40000,Rt=/^[0-9a-f-]{36}$/,ce=Y,It=me();function N(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function he(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!N(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==ht||t.kind!=="browser")||JSON.stringify(t).length>_t)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function mn(e=process.platform,o=P){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var vt="__computer-use";function ss(e=P){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function we(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Ot(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function At(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Et=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Tt=33554432;function Nt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=N(t)&&N(t.result)?t.result.metadata:null;if(!N(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Et.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function _e(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Nt(await Ot(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(ut(m).size>Tt)continue;let l=K(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Pt(e,o,t){return(await _e(e,o,t))[0]?.instance??null}function ye(e,o,t){return Pt(e.nativeHost,o,{socketDir:At(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var le=/^(Default|Profile ([0-9]+))$/;async function Dt(e,o,t=a(),n=Ct){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(le.exec(l)?.[2]??-1),c=i.filter((l)=>le.test(l)&&M(f(s,l,"Extensions",$e))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",$e);return(await _e(e,o,{socketDir:n,extensionId:$e,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((h)=>d(h)===l),instance:p,socket:g}))}async function Mt(e,o,t=a(),n=Ct){let s=(await Dt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function ue(e){return new Promise((o)=>{let t=pt({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function Se(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var W=new Map;function H(e,o){let t=W.get(e);if(!t)t=o().finally(()=>W.delete(e)),W.set(e,t);return t}async function Ut(e,o){if(await ue(e))return;if(lt(e,{force:!0}),await we("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await Se(()=>ue(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function de(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await ye(e,o,t)!==null:async()=>await we(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");V(l);let p=f(l,"NativeMessagingHosts");ie(p,{recursive:!0,mode:448});let g=yr(e.platform).nativeHostManifests[0];se(g,f(p,ae(g)));let h=e.browser.slice(0,e.browser.indexOf(".app/")+4),y=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",h,"--args",`--user-data-dir=${l}`,...y],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");V(l),tt(x("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ie(p,{recursive:!0,mode:448});let g=yr(e.platform).nativeHostManifests[0];se(g,f(p,ae(g)));let h=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let y=it(u,"a",384);c=nt(y).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...h,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",y,y],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),rt(y)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await Se(async()=>d||(m=await n()),xt),!m){if(u&&K(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function as(e){await Re(e,!0)}function cs(e){return xe(e,ke(e))}function xe(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function ke(e){let o=f(e.root,"automation");if(!M(o)||!Lt(e.automation))return e.automation;if(!$t(xe(e,o)))try{fe(o,e.automation)}catch{}return M(o)?o:e.automation}function Lt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function $t(e){let o;try{o=ct(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function Re(e,o){gt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=ke(e);V(t);let n=ge().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...Bt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:vt};if(!o)return l;await H("browser",()=>de(e,l,t));let p=await ye(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await Be(),u=f(t,"home"),c=f(t,"runtime");V(u),V(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Qe(i.sound)}:{}};if(await H("bus",()=>Ut(d,m)),o)await H("browser",()=>de(e,m,t));return m}function Bt(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(mt)}}async function qt(e,o,t){let n=ge().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Mt(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function Wt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${ot("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||K(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;dt(t,e,{mode:384}),fe(t,o)}return[o]}function Ie(e,o,t,n){if(typeof ce!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ce;return new Promise((i,u)=>{let c=R(e,Wt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,h=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){R(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},y=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>h(new r("automation_timed_out","Reason automation did not finish in time.")),yt),S=()=>h(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(w)=>{if(m+=w.byteLength,m>ft)h(new r("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),c.stderr.setEncoding("utf8").on("data",(w)=>{l=(l+w).slice(-wt)}),c.stdin.on("error",()=>{}),c.once("error",()=>y(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>y(()=>{if(p)u(p);else i({code:w??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Ft(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=St)k.delete(k.keys().next().value);let n=me();return k.set(n,{runId:e,bytes:o,expiresAt:t+bt}),n}async function ve(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ie)(e.node,s,JSON.stringify(o),t)}async function ls(e,o){let t=he({call:e});if(!("call"in t))D();let n=P();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await ve(n,t.call,o)}function pe(e,o,t){let n=e.stdout.byteLength>j?Ft(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:It,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function gn(e,o={}){let t=he(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??P)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??at)():[],c=o.macSetup??T,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return pe(await re({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=await _i(e.runId,e.signal,o.now),p="account"in o?o.account??null:G(),g;try{if(m){let h=await(o.userChromeEnvironment??qt)(s,m,e.signal);e.signal.throwIfAborted(),g=await(o.runtime??Ie)(s.node,h,JSON.stringify(t.call),e.signal)}else if(p)g=await(o.delegate??z)(p,t.call,e.signal);else g=await ve(s,t.call,e.signal,o)}finally{l()}if(i)g=await ne({runId:e.runId,call:t.call,identity:u,output:g,signal:e.signal},c);return pe(g,e.runId,n)}
855
- export{kt,mn,ss,as,cs,ls,gn};
852
+ `;import{spawn as Ae}from"child_process";import{basename as Ce}from"path";var Te="__desktop-call",Ne="/usr/bin/setpriv",Pe=27262976,De=8192,Me=2000;function q(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Ue(e){try{return JSON.parse(e)}catch{return null}}function Le(){return[process.execPath,...Ce(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Te]}function Mt(e,o,t,n={}){t.throwIfAborted();let s=n.command??Le();return new Promise((i,u)=>{let c=(n.spawnProcess??Ae)(Ne,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,h,y=(_)=>{try{process.kill(-c.pid,_)}catch{c.kill(_)}},I=(_)=>{p??=_,y("SIGTERM"),h??=setTimeout(()=>y("SIGKILL"),Me)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(_)=>{if(g)return;g=!0,clearTimeout(h),t.removeEventListener("abort",S),_()};if(c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>Pe)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-De)}),c.stdin.on("error",()=>{}),c.once("error",()=>w(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(_,ve)=>w(()=>{if(p)return u(p);let b=Ue(Buffer.concat(d).toString("utf8"));if(q(b)&&b.ok===!0&&q(b.result))return i(b.result);let O=q(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${_??ve}${O?"":" with no reply"}`,Y=l.trim().split(`
853
+ `).at(-1)?.slice(-300)??"";if(!O||O.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
854
+ `);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function V(e,o,t,n={}){let s=await Mt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as $e,spawn as Be}from"child_process";import{closeSync as Fe,mkdirSync as Ge,openSync as He}from"fs";import{dirname as E,join as je}from"path";import{promisify as Ke}from"util";var Xe=Ke($e),Z="x-apple.systempreferences:com.apple.preference.security",Je={accessibility:`${Z}?Privacy_Accessibility`,screen:`${Z}?Privacy_ScreenCapture`},Ye=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=Ye)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function ze(){let e=a(),o=Hn(Ee(e),process.env),t=je(e,".local","share","reason","desktop-install.log");Ge(E(t),{recursive:!0,mode:448});let n=He(t,"a",384);try{let s=Be(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Fe(n)}}var N={open:async(e,o)=>{await Xe("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>mt(e,o),tile:Jr,installDesktop:ze},Q=!1;async function ee(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function oe(e,o,t,n){if(await t.open([Je[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function Ze(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await oe(o,i,n,s)}}var Qe={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function te(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function et(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function re(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return te({result:{tools:[Qe]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!Q){Q=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await oe(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await ee(so,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?et(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await ee(u,o,s),te({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ne(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await Ze(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,pt=18874368,ft=8192,ht=65536,wt=55000,_t=60000,yt=4,bt=40000,xt=/^[0-9a-f-]{36}$/,ce=z,Rt=me();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function he(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==St||t.kind!=="browser")||JSON.stringify(t).length>ht)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!xt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Cn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var It="__computer-use";function Os(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function we(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function vt(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Ot(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var At=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Et=33554432;function Ct(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&At.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function _e(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Ct(await vt(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(ct(m).size>Et)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Tt(e,o,t){return(await _e(e,o,t))[0]?.instance??null}function ye(e,o,t){return Tt(e.nativeHost,o,{socketDir:Ot(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var le=/^(Default|Profile ([0-9]+))$/;async function Nt(e,o,t=a(),n=Ft){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(le.exec(l)?.[2]??-1),c=i.filter((l)=>le.test(l)&&M(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await _e(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((h)=>d(h)===l),instance:p,socket:g}))}async function Pt(e,o,t=a(),n=Ft){let s=(await Nt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function ue(e){return new Promise((o)=>{let t=ut({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function be(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var W=new Map;function H(e,o){let t=W.get(e);if(!t)t=o().finally(()=>W.delete(e)),W.set(e,t);return t}async function Dt(e,o){if(await ue(e))return;if(at(e,{force:!0}),await we("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await be(()=>ue(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function de(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await ye(e,o,t)!==null:async()=>await we(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ie(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];se(g,f(p,ae(g)));let h=e.browser.slice(0,e.browser.indexOf(".app/")+4),y=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",h,"--args",`--user-data-dir=${l}`,...y],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");G(l),tt(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ie(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];se(g,f(p,ae(g)));let h=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let y=st(u,"a",384);c=nt(y).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...h,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",y,y],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),rt(y)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await be(async()=>d||(m=await n()),bt),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Is(e){await ke(e,!0)}function Ds(e){return Se(e,xe(e))}function Se(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function xe(e){let o=f(e.root,"automation");if(!M(o)||!Ut(e.automation))return e.automation;if(!Lt(Se(e,o)))try{fe(o,e.automation)}catch{}return M(o)?o:e.automation}function Ut(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function Lt(e){let o;try{o=it(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function ke(e,o){kt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=xe(e);G(t);let n=ge().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...$t(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:It};if(!o)return l;await H("browser",()=>de(e,l,t));let p=await ye(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await H("bus",()=>Dt(d,m)),o)await H("browser",()=>de(e,m,t));return m}function $t(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(dt)}}async function Bt(e,o,t){let n=ge().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Pt(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function qt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${ot("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;lt(t,e,{mode:384}),fe(t,o)}return[o]}function Re(e,o,t,n){if(typeof ce!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ce;return new Promise((i,u)=>{let c=R(e,qt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,h=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){R(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},y=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>h(new r("automation_timed_out","Reason automation did not finish in time.")),wt),S=()=>h(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(w)=>{if(m+=w.byteLength,m>pt)h(new r("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),c.stderr.setEncoding("utf8").on("data",(w)=>{l=(l+w).slice(-ft)}),c.stdin.on("error",()=>{}),c.once("error",()=>y(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>y(()=>{if(p)u(p);else i({code:w??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Wt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=yt)k.delete(k.keys().next().value);let n=me();return k.set(n,{runId:e,bytes:o,expiresAt:t+_t}),n}async function Ie(e,o,t,n={}){let s=await(n.environment??ke)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Re)(e.node,s,JSON.stringify(o),t)}async function Ns(e,o){let t=he({call:e});if(!("call"in t))D();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Ie(n,t.call,o)}function pe(e,o,t){let n=e.stdout.byteLength>j?Wt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:Rt,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function An(e,o={}){let t=he(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return pe(await re({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=await Di(e.runId,e.signal,o.now),p="account"in o?o.account??null:K(),g;try{if(m){let h=await(o.userChromeEnvironment??Bt)(s,m,e.signal);e.signal.throwIfAborted(),g=await(o.runtime??Re)(s.node,h,JSON.stringify(t.call),e.signal)}else if(p)g=await(o.delegate??V)(p,t.call,e.signal);else g=await Ie(s,t.call,e.signal,o)}finally{l()}if(i)g=await ne({runId:e.runId,call:t.call,identity:u,output:g,signal:e.signal},c);return pe(g,e.runId,n)}
855
+ export{Mt,Cn,Os,Is,Ds,Ns,An};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var Zt=String.raw`(function(require) {
2
+ var sr=String.raw`(function(require) {
3
3
  if (process.platform !== "win32") return null;
4
4
  let ffi, kernel32;
5
5
  try {
@@ -64,4 +64,4 @@ var Zt=String.raw`(function(require) {
64
64
  },
65
65
  };
66
66
  })`;
67
- export{Zt};
67
+ export{sr};
@@ -0,0 +1,52 @@
1
+ // @bun
2
+ import{g,go,xe}from"./vm-hands-entry-lite-aj139v8j.js";import{l,Ut,Ge,Dr,Ht,Lr,lt}from"./vm-hands-entry-lite-pf5qtbj5.js";import{wt,or}from"./vm-hands-entry-lite-4vks5phw.js";import{ln}from"./vm-hands-entry-lite-2nkj0dpx.js";import{B,m,te,Ue}from"./vm-hands-entry-lite-j43nqe8y.js";import{F}from"./vm-hands-entry-lite-m8nqnd9j.js";import{Ro}from"./vm-hands-entry-lite-hn76pcgk.js";import{Ee,Xe,zn,qr}from"./vm-hands-entry-lite-stmbekq0.js";import{f,v,h}from"./vm-hands-entry-lite-wx4ax7wg.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{$o,nn,y,t,k,xt,o,d,Ie,u,i,c,_,is,s,n,on}from"./vm-hands-entry-lite-avc65bd7.js";import{closeSync as Dh,existsSync as Th,mkdirSync as Wh,openSync as Nh,readdirSync as Hh,realpathSync as pe,rmSync as $h}from"fs";import{dirname as Uh,join as J,resolve as Fh}from"path";import{createHash as Pt}from"crypto";import{platform as Ct}from"os";import{join as At}from"path";var It=_("store",[c({version:n(1),store:n("keychain")}),c({version:n(1),store:n("file"),api_key:t().min(1).max(4096)})]),We=(e)=>At(e,"api-key.json");function Ne(e){let r=Pt("sha256").update(`reason-connect-api-key
3
+ ${e}`).digest("hex");return new Ge(Ut(),Ct(),r)}function we(e,r=Ne(e)){if(!f(We(e)))return null;let p=It.parse(JSON.parse(h(We(e))));if(p.store==="file")return p.api_key;try{let b=r.loadBinding();return b?new TextDecoder().decode(b):null}catch(b){if(!(b instanceof l))throw b;throw Error("worker_api_key_unreadable")}}import{readdirSync as Gt,renameSync as Fn,rmSync as jn}from"fs";import{join as ee}from"path";import{createHash as Mt}from"crypto";import{platform as Dt}from"os";import{join as N}from"path";function w(e){return{state:N(m(e),"device.json"),control:N(m(e),"control.json"),lock:N(m(e),"lifecycle.lock"),socket:N(m(e),"control.sock"),daemon:N(m(e),"daemon.json"),releaseCheck:N(m(e),"release-check.json"),updateDeferral:N(m(e),"update-deferral.json"),firstHeartbeat:N(m(e),"first-heartbeat.json")}}var rn=i({version:n(1),device_id:t().min(1).max(160),offer:Ie().optional(),enrollment_ms:o().int().nonnegative().max(or).optional()});function z(e,r=!1){v(m(e),r);let p=["local-device.key","local-device.binding","device.json"].filter((b)=>{let R=N(m(e),b);if(!f(R))return!1;return h(R),!0});return e.lifetime==="persistent"&&p.join()==="device.json"?Tt(e):new Dr(m(e))}function Tt(e){return new Ge(Ut(),Dt(),Wt(e))}function Wt(e){let r=Bt(e);return Mt("sha256").update(`reason-worker
4
+ ${r?.directory??m(e)}`).digest("hex")}var Nt="keychain-scope.json";var $t=c({version:n(1),directory:t().min(1),devicePublicKey:t().min(1)});function Bt(e){let r=N(m(e),Nt);if(!f(r))return null;let p=$t.safeParse(JSON.parse(h(r))),b=w(e).state;if(!p.success||!f(b))return null;return JSON.parse(h(b))?.devicePublicKey===p.data.devicePublicKey?p.data:null}function M(e){if(!f(m(e)))return null;let r=Lr(w(e).state,{proofStore:z(e),repair:!1}),p=r!==null&&go(e.apiOrigin,r.apiOrigin),b=p?[te(e),te({...e,apiOrigin:r.apiOrigin})]:[te(e)];if(r&&(!b.includes(r.worker?.configDigest??"")||r.worker.lifetime!==e.lifetime||r.apiOrigin!==e.apiOrigin&&!p||r.roots.length>32||r.roots[0]?.path!==e.workspaceRoot||r.handsSlots!==e.slots))throw Error("worker_config_binding_mismatch");return r}var Ft=c({version:n(1),drained:d(),revoked:d()});function H(e){let r=w(e).control;return f(r)?Ft.parse(JSON.parse(h(r))):{version:1,drained:!1,revoked:!1}}var qt=c({read:d(),write:d(),execute:d(),discover_environment:d(),expose_mcp:n(!1)}),zt=c({version:n(1),organization_id:t().min(1).max(160),enrollment_ticket:t().min(1).max(4096),code_verifier:t().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:t().regex(/^[a-f0-9]{64}$/),root:c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/),permissions:qt,execution_mode:s(["confined","host"]).default("confined")}),folders:u(c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),_n=i({device_id:t().min(1).max(160),organization_id:t().min(1).max(160),auth_scheme:n("p256"),protocol_version:n(2),roots:u(i({id:t().min(1),label:t(),path_fingerprint:t()})).min(1).max(32),headless:i({lifecycle:s(["persistent","ephemeral"]),expires_at:y.datetime({offset:!0})}),first_heartbeat:Ie().optional()});var Nn=c({version:n(1),install_id:k(),fingerprint_key:t().regex(/^[a-f0-9]{64}$/)}),Hn=i({enrollment_ticket:t().min(1).max(4096),expires_at:y.datetime({offset:!0}),device_kind:n("headless"),lifecycle:s(["persistent","ephemeral"]),device_expires_at:y.datetime({offset:!0})});var $n=i({credentialKind:s(["oauth","api_key"]).optional(),apiOrigin:xt(),clientId:t(),accessToken:t().min(1).max(32768),refreshToken:t().max(32768),expiresAt:y.datetime({offset:!0}),scopes:u(t().max(128)).max(128),orgId:t().min(1).max(160)});var je=8;var Yt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_e=(e)=>ee(m(e),"workspaces"),Xt="account.json",Zt=(e)=>f(ee(e,Xt));function ve(e){let r;try{r=Gt(_e(e))}catch{return[]}return r.filter((p)=>Yt.test(p)).sort().map((p)=>{let b=ee(_e(e),p),R=ee(b,"worker.json"),S=null;try{let P=B.safeParse(JSON.parse(h(R)));if(P.success&&P.data.stateDirectory===b)S=P.data}catch{}return{organizationId:p,directory:b,configPath:R,config:S,account:Zt(b)}})}var Qt=(e)=>ee(_e(e),"listed.json");function er(e){try{let r=JSON.parse(h(Qt(e))),p=r.names&&typeof r.names==="object"&&!Array.isArray(r.names)?Object.fromEntries(Object.entries(r.names).filter((b)=>typeof b[1]==="string")):{};return{listed:r.listed===!0,reason:r.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(r.blocked)?r.blocked.filter((b)=>typeof b==="string"):[],names:p}}catch{return null}}function qe(e,r){let p=ve(e),b=p.filter((C)=>C.account),R=p.filter((C)=>!C.account),S=er(e),P=S&&!S.listed?S.reason:null,E=P||R.length===0&&S&&!S.listed?[]:R;if(b.length===0&&E.length===0&&(P||S&&!S.listed))return{workspaces:null,off:P};return{off:P,workspaces:[...b,...E].map(({organizationId:C,config:L,account:x})=>{let A=!1,D=null,T=!1,he=null;try{A=L?H(L).revoked:!1,D=L&&!A?M(L):null;let Te=L?lt(w(L).daemon):null;T=r&&!!D&&Te?.state==="connected",he=T?Ht(Te,D):null}catch{}return{...he?{permission_recovery:he}:{},organization_id:C,device_id:D?.deviceId??null,name:S?.names?.[C]??null,root:D?.roots[0]?{id:D.roots[0].id,permissions:D.roots[0].permissions}:null,state:A?"removed":T?"connected":"not_running",blocked:!x&&!A&&!T&&(S?.blocked.includes(C)??!1),...x?{account:!0}:{}}})}}import{readFileSync as rr}from"fs";function lr(e){try{let r=JSON.parse(rr(`${e}.keep-awake.json`,"utf8"));return r!==null&&typeof r==="object"&&"version"in r&&r.version===1&&"enabled"in r&&r.enabled===!0?"battery_and_ac":void 0}catch(r){return r.code==="ENOENT"?"battery_and_ac":void 0}}import{chmodSync as Ni,lstatSync as Ze,mkdtempSync as Hi,realpathSync as nr,rmdirSync as $i,rmSync as Bi,unlinkSync as Ui}from"fs";import{createConnection as ir,createServer as ji}from"net";import{basename as Ve,dirname as Je,join as oe}from"path";var ar=s(["status","drain","resume","stop","reload_roots"]),sr=c({version:n(1),instanceId:t(),deviceId:t(),phase:s(["starting","running","reconnecting","stopping"]),drained:d(),activeClaims:o().int().nonnegative(),activeSessions:o().int().nonnegative().optional(),executionEligible:d(),supportedOperations:u(s(wt)).max(wt.length).optional(),capabilityReadiness:is(s(wt),d()).optional(),lastHeartbeat:t().nullable(),expiresAt:t()}),Gi=c({nonce:t(),action:ar}),cr=i({nonce:k()}),dr=c({version:n(1),nonce:k(),socketPath:t().max(100)});function ur(e){return oe(w(e).lock,"control.json")}function Qe(e){return v(w(e).lock),cr.parse(JSON.parse(h(oe(w(e).lock,"owner.json"))))}function Ye(e){if(!f(e))return!1;let r=Ze(e);if(!r.isSocket()||r.uid!==process.getuid?.()||(r.mode&63)!==0)throw Error("worker_control_socket_not_private");return!0}function et(e,r){let p=ur(e);if(!f(p)){let S=w(e).socket;if(!f(S)||!Ze(S).isSocket())return null;return Ye(S)?S:null}let b=dr.parse(JSON.parse(h(p)));if(b.nonce!==r)throw Error("worker_instance_changed");if(process.platform==="win32"){if(!fr.test(b.socketPath))throw Error("worker_control_endpoint_invalid");return b.socketPath}let R=Je(b.socketPath);if(Je(R)!==nr("/tmp")||!/^(?:reason|ara)-worker-[A-Za-z0-9]{6}$/.test(Ve(R))||Ve(b.socketPath)!=="control.sock"||Buffer.byteLength(b.socketPath)>100)throw Error("worker_control_endpoint_invalid");if(!f(R))return null;return v(R),Ye(b.socketPath)?b.socketPath:null}var fr=/^\\\\\.\\pipe\\reason-worker-[0-9a-f-]{36}$/;function mr(e,r){try{let p=JSON.parse(h(oe(w(e).lock,"owner.json"))),b=p&&typeof p==="object"?p[r]:void 0;return typeof b==="string"?b:null}catch{return null}}function tt(e){return mr(e,"runtime_version")}function ot(e,r){if(r)return r.message==="worker_control_timeout"?"socket_timeout":"bad_reply";try{if(!f(oe(w(e).lock,"owner.json")))return"no_lock";return et(e,Qe(e).nonce)?"socket_refused":"no_socket"}catch{return"bad_reply"}}var Yi=c({instance:t().nullable(),since:o().int().nonnegative()});async function G(e,r){let p=w(e);if(!f(oe(p.lock,"owner.json")))return null;let b=Qe(e),R=et(e,b.nonce);if(!R)return null;return new Promise((S,P)=>{let E=ir(R),C="",L=!1,x=(A,D)=>{if(L)return;if(L=!0,E.destroy(),D)P(D);else S(A)};E.setTimeout(2000,()=>E.destroy(Error("worker_control_timeout"))),E.on("connect",()=>E.write(JSON.stringify({nonce:b.nonce,action:r})+`
5
+ `)),E.on("data",(A)=>{if(C+=A.toString(),Buffer.byteLength(C)>16384)E.destroy(Error("worker_control_oversize"))}),E.on("error",(A)=>{if("code"in A&&["ECONNREFUSED","ENOENT"].includes(String(A.code)))x(null);else x(null,A.message==="worker_control_timeout"?A:Error("worker_control_unavailable"))}),E.on("end",()=>{try{let A=sr.parse(JSON.parse(C));if(A.instanceId!==b.nonce)throw Error("worker_instance_changed");x(A)}catch{x(null,Error("worker_control_invalid_response"))}}),E.once("close",()=>x(null,Error("worker_control_unavailable")))})}import{realpathSync as wr}from"fs";import{constants as Se}from"fs";import{open as pr}from"fs/promises";var oa={platform:process.platform,home:a,async openFile(e){let r=await pr(e,Se.O_RDONLY|Se.O_NOFOLLOW|Se.O_NONBLOCK);return{isFile:async()=>(await r.stat()).isFile(),close:()=>r.close()}}};var Ha=Ro(wr(process.execPath));var ms=Buffer.from([0,255,3,4]);import{execFile as Zr}from"child_process";import{promisify as Qr}from"util";var vr=new RegExp("^/media/pr-screenshots/([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/([a-z0-9][a-z0-9._-]*)\\.(png|jpe?g|gif|webp|webm|mp4)$","i");var Sr=new Set(["png","jpg","jpeg","gif","webp"]),Rr=new Set(["webm","mp4"]);function Er(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function at(e,r){let p;try{p=new URL(e)}catch{return null}let b=Er(r),R=p.hostname==="ara.so"||p.hostname.endsWith(".ara.so")||p.hostname==="reasonmachines.ai"||p.hostname.endsWith(".reasonmachines.ai")||p.hostname==="reasonmachines.com"||p.hostname.endsWith(".reasonmachines.com");if(p.protocol!=="https:"||!R&&p.origin!==b||p.username||p.password||p.port||p.search||p.hash)return null;let S=vr.exec(p.pathname);if(!S)return null;let P=S[1]?.toLowerCase(),E=S[2]?.toLowerCase(),C=S[3]?.toLowerCase(),L=S[4]?.toLowerCase();if(!P||!E||!C||!L)return null;let x=Sr.has(L)?"image":Rr.has(L)?"video":null;if(!x)return null;let A=/^(before|after)[\s:_-]+/.exec(C),D=p.pathname.replace(/^\/media\//,"");return{url:p.toString(),storagePath:D,runId:P,artifactId:E,fileName:`${C}.${L}`,kind:x,phase:A?.[1]==="before"||A?.[1]==="after"?A[1]:null}}var Pr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,st=(e)=>Boolean(e&&typeof e==="object"&&!Array.isArray(e)),K=()=>{throw Error("cloud_browser_media_request_invalid")};function Pe(e){if(!st(e)||Object.keys(e).some((S)=>!["runId","configuredMediaOrigin","media"].includes(S))||typeof e.runId!=="string"||!Pr.test(e.runId)||typeof e.configuredMediaOrigin!=="string"||e.configuredMediaOrigin.length>2048||!Array.isArray(e.media)||e.media.length<1||e.media.length>8)return K();let r;try{r=new URL(e.configuredMediaOrigin)}catch{return K()}if(r.protocol!=="https:"||r.username||r.password||r.port||!Ue(r.origin,{mode:"public_web"}).allowed)return K();let p=e.runId.toLowerCase(),b=new Set,R=e.media.map((S)=>{if(!st(S)||Object.keys(S).some((E)=>!["url","sourceUrl","kind"].includes(E))||typeof S.url!=="string"||S.url.length>2048||typeof S.sourceUrl!=="string"||S.sourceUrl.length>8192||!["image","video"].includes(String(S.kind)))return K();let P=at(S.url,r.origin);if(!P||new URL(P.url).origin!==r.origin||P.runId!==p||P.kind!==S.kind||P.url!==S.url||b.has(S.url))return K();if(b.add(S.url),S.sourceUrl!==S.url){let E;try{E=new URL(S.sourceUrl)}catch{return K()}let C=/^\/(?:[a-f0-9]{40}|[a-f0-9]{64})\/([a-f0-9]+)$/.exec(E.pathname)?.[1];if(S.kind!=="image"||E.origin!=="https://camo.githubusercontent.com"||E.username||E.password||E.search||E.hash||!C||C.length%2!==0||Buffer.from(C,"hex").toString("utf8")!==S.url)return K()}return{url:S.url,sourceUrl:S.sourceUrl,kind:S.kind}});return{runId:e.runId,configuredMediaOrigin:r.origin,media:R}}var I=t().uuid(),X=t().regex(/^[a-f0-9]{64}$/),V=y.datetime({precision:3}),Ce=t().regex(/^[a-zA-Z0-9_-]{1,160}$/),ut=t().max(2048).regex(/^https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/).refine((e)=>![".",".."].includes(e.split("/")[4])),U=i({kind:n("primary_mac"),version:n(1),organizationId:Ce,userId:Ce,sessionId:Ce,runId:I,deviceId:I,rootId:I,rootRevision:t().min(1).max(64),binding:s(["workspace_source","mcp_control"]),targetRevision:o().int().nonnegative(),generation:I,profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:t().min(1).max(1024)}).strict().refine((e)=>e.binding!=="workspace_source"||e.targetRevision===0),Cr=on().transform((e,r)=>{try{return ln(e)}catch{return r.addIssue({code:"custom",message:"proof_visual_contract_invalid"}),$o}}),ue=i({version:n(1),owner:U,contextId:I,preparedAt:V,expiresAt:V,prUrl:ut,headSha:t().regex(/^[a-f0-9]{40}$/),skillDigest:X,evidenceKind:s(["image","video"]),visualPlan:Cr.optional(),uploadOrigin:t().url().refine((e)=>{let r=new URL(e);return r.protocol==="https:"&&r.origin===e&&!r.username&&!r.password}).optional()}).strict().refine((e)=>Date.parse(e.expiresAt)>Date.parse(e.preparedAt)&&Date.parse(e.expiresAt)-Date.parse(e.preparedAt)<=300000),Ar=i({version:n(1),producer:n("primary_mac"),context:ue,captureId:I,operationId:I,attemptId:I,tabId:o().int().positive(),startedAt:V,finishedAt:V,sha256:X,media:_("contentType",[i({contentType:n("image/png"),sizeBytes:o().int().min(24).max(8388608),width:o().int().min(1).max(4096),height:o().int().min(1).max(4096)}).strict(),i({contentType:n("video/webm"),sizeBytes:o().int().min(128).max(10485760),durationSeconds:o().min(0.05).max(15),frameCount:o().int().min(1).max(450),receivedFrameCount:o().int().min(1).max(2000)}).strict()])}).strict().superRefine((e,r)=>{let p=Date.parse(e.startedAt),b=Date.parse(e.finishedAt);if(p<Date.parse(e.context.preparedAt)||b<p||b>Date.parse(e.context.expiresAt)||b-p>30000||e.media.contentType==="video/webm"&&(e.media.receivedFrameCount<e.media.frameCount||Math.abs((b-p)/1000-e.media.durationSeconds)>0.1))r.addIssue({code:"custom",message:"mac_pr_proof_capture_chronology_invalid"})}),dc=_("action",[i({action:n("screenshot"),context_id:I,tab_id:o().int().positive()}).strict(),i({action:n("start_video"),context_id:I,tab_id:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),i({action:n("stop_video"),recording_operation_id:I}).strict()]),fe=i({login:t().regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/),id:t().regex(/^[1-9][0-9]{0,19}$/).nullable()}).strict(),ce=t().regex(/^[1-9][0-9]{0,19}$/),le=i({version:n(1),owner:U,expectedActorId:ce.nullable(),repositoryId:ce,repositoryFullName:t().max(200).regex(/^[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+$/).refine((e)=>![".",".."].includes(e.split("/")[1]))}).strict(),Ir=["browser_unavailable","github_page_unavailable","identity_check_failed","operation_incomplete","attachment_unavailable"],xr=_("status",[le.extend({status:n("ready"),observedActor:fe,checkedAt:V}),le.extend({status:n("not_ready"),reason:s(["authentication_required","identity_mismatch","authority_lost","unavailable"]),cause:s(Ir).optional()})]).refine((e)=>e.status!=="ready"||e.expectedActorId===null||e.observedActor.id===e.expectedActorId),Y=i({version:n(1),owner:U,expectedActorId:ce.nullable(),authenticatedActor:fe,attemptId:I,captureId:I,prUrl:ut,repositoryId:ce,headSha:t().regex(/^[a-f0-9]{40}$/),sha256:X,sizeBytes:o().int().min(128).max(10485760),contentType:n("video/webm")}).strict(),ft=t().regex(/^https:\/\/github\.com\/user-attachments\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),Or=_("status",[Y.extend({status:n("not_attempted"),reason:s(["authentication_required","attachment_unavailable","identity_mismatch","capture_invalid","authority_lost"])}),Y.extend({status:n("uncertain"),reason:n("upload_outcome_unknown")}),Y.extend({status:n("uploaded"),observedActor:fe,nativeUrl:ft,uploadedAt:V})]).refine((e)=>(e.expectedActorId===null||e.authenticatedActor.id===e.expectedActorId)&&(e.status!=="uploaded"||e.observedActor.id===e.authenticatedActor.id&&e.observedActor.login===e.authenticatedActor.login)),de=Y.extend({nativeUrl:ft,observedActor:fe,bodySha256:X}),Mr=_("status",[de.extend({status:n("incomplete"),reason:s(["authentication_required","identity_mismatch","playback_unverified","authority_lost"])}),de.extend({status:n("verified"),sourceSha256:X,width:o().int().min(1).max(4096),height:o().int().min(1).max(4096),durationSeconds:o().positive().max(30),advancedSeconds:o().min(0.05).max(10),advancedFrames:o().int().positive(),playbackRestored:n(!0),verifiedAt:V})]).refine((e)=>(e.expectedActorId===null||e.authenticatedActor.id===e.expectedActorId)&&e.observedActor.id===e.authenticatedActor.id&&e.observedActor.login===e.authenticatedActor.login&&(e.status!=="verified"||e.sourceSha256===e.sha256)),Tr=on().transform((e,r)=>{try{let p=Pe(e);if(p.media.some((b)=>b.kind!=="image"))throw Error();return p}catch{return r.addIssue({code:"custom",message:"proof_media_request_invalid"}),$o}}),Wr=_("action",[i({action:n("auth_check"),input:le}).strict(),i({action:n("prepare"),context:ue}).strict(),i({action:n("capture_png"),owner:U,contextId:I,tabId:o().int().positive()}).strict(),i({action:n("start_video"),owner:U,contextId:I,tabId:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),i({action:n("inspect_capture"),owner:U,captureId:I}).strict(),i({action:n("publish_video"),input:Y}).strict(),i({action:n("verify_png_media"),owner:U,media:Tr}).strict().refine((e)=>e.media.runId===e.owner.runId),i({action:n("verify_saved_media"),input:de}).strict(),i({action:n("publish_png"),owner:U,attemptId:I,captureId:I,sha256:X,sizeBytes:o().int().min(24).max(8388608),storagePath:t().max(512),uploadUrl:t().url().max(8192)}).strict()]);var Nr=i({requestId:I,command:Wr}).strict();var Hr={type:"object",required:["action"],properties:{action:{type:"string",enum:["screenshot","start_video","stop_video"]},context_id:{type:"string",format:"uuid"},tab_id:{type:"integer",minimum:1},seconds:{type:"integer",minimum:1,maximum:15},recording_operation_id:{type:"string",format:"uuid"}},additionalProperties:!1},ct={type:"string",format:"uuid",description:"capture_context_id from tools.pr.prepareProof."},dt={type:"integer",minimum:1,description:"An already-owned tab's id."},uc={...Hr,oneOf:[{type:"object",required:["action","context_id","tab_id"],additionalProperties:!1,properties:{action:{type:"string",const:"screenshot"},context_id:ct,tab_id:dt}},{type:"object",required:["action","context_id","tab_id","seconds"],additionalProperties:!1,properties:{action:{type:"string",const:"start_video"},context_id:ct,tab_id:dt,seconds:{type:"integer",minimum:1,maximum:15}}},{type:"object",required:["action","recording_operation_id"],additionalProperties:!1,properties:{action:{type:"string",const:"stop_video"},recording_operation_id:{type:"string",format:"uuid",description:"The recording_operation_id start_video returned."}}}]};var gc=i({operationId:t().uuid(),attemptId:t().uuid(),contextId:t().uuid(),tabId:o().int().positive()}).strict();var $r=String.raw`async (media) => {
6
+ const deadline = (promise) => {
7
+ let timer;
8
+ return Promise.race([promise, new Promise((_, reject) => {
9
+ timer = setTimeout(() => reject(new Error("media_decode_timeout")), 12000);
10
+ })]).finally(() => clearTimeout(timer));
11
+ };
12
+ const items = await Promise.all(media.map(async (item) => {
13
+ const element = document.createElement(item.kind === "image" ? "img" : "video");
14
+ document.body.append(element);
15
+ try {
16
+ if (item.kind === "image") {
17
+ element.src = item.sourceUrl;
18
+ await deadline(element.decode());
19
+ if (!element.complete || !element.naturalWidth || !element.naturalHeight) throw new Error("media_image_not_decoded");
20
+ return { ...item, width: element.naturalWidth, height: element.naturalHeight };
21
+ }
22
+ element.muted = true;
23
+ element.playsInline = true;
24
+ element.preload = "auto";
25
+ const loaded = new Promise((resolve, reject) => {
26
+ element.addEventListener("loadeddata", resolve, { once: true });
27
+ element.addEventListener("error", () => reject(new Error("media_video_not_decoded")), { once: true });
28
+ });
29
+ element.src = item.sourceUrl;
30
+ await deadline(loaded);
31
+ if (!element.videoWidth || !element.videoHeight || !Number.isFinite(element.duration) || element.duration <= 0) throw new Error("media_video_not_decoded");
32
+ const initial = element.currentTime;
33
+ await deadline(element.play());
34
+ await deadline(new Promise((resolve, reject) => {
35
+ let timer;
36
+ const check = () => {
37
+ if (element.error) { clearTimeout(timer); reject(new Error("media_video_not_decoded")); return; }
38
+ if (element.currentTime - initial >= 0.05) { clearTimeout(timer); resolve(); return; }
39
+ timer = setTimeout(check, 25);
40
+ };
41
+ element.addEventListener("pause", () => { clearTimeout(timer); reject(new Error("media_video_not_advancing")); }, { once: true });
42
+ check();
43
+ }));
44
+ return { ...item, width: element.videoWidth, height: element.videoHeight, advancedSeconds: element.currentTime - initial };
45
+ } finally {
46
+ if (item.kind === "video") element.pause();
47
+ element.removeAttribute("src");
48
+ element.remove();
49
+ }
50
+ }));
51
+ return { verified: true, items };
52
+ }`;import{execFile as Br}from"child_process";import{promisify as Ur}from"util";var vc=Ur(Br);var $c=_("ok",[i({ok:n(!0),actor:i({login:t(),id:t().nullable()}).strict()}).strict(),i({ok:n(!1),reason:s(["authentication_required","identity_mismatch","attachment_unavailable"])}).strict()]),Bc=i({version:n("0.1.42"),metadata:i({extensionId:t(),extensionInstanceId:t(),nativeHostName:t()})});var jc=i({version:n(1),recording_operation_id:t().uuid(),proof_ready:n(!1),acknowledged_at:y.datetime()}).strict(),me=i({action:n("start"),request_id:t().uuid(),profile:t().regex(/^(Default|Profile [0-9]+)$/),tab_id:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),mt=i({action:n("inspect"),recording_operation_id:t().uuid()}).strict(),qc=_("action",[me,mt]),pt=i({recording_operation_id:t().uuid()}).strict(),Oe={device_id:t().uuid(),root_id:t().uuid()},jr=_("action",[me.extend(Oe),mt.extend(Oe),pt.extend({...Oe,action:n("stop")})]),zc=nn(jr),Kc=i({version:n(1),recordingId:t().uuid(),proofReady:n(!1),capture:i({captureId:t().uuid(),contentType:n("video/webm"),sha256:t().regex(/^[a-f0-9]{64}$/),sizeBytes:o().int().min(128).max(10485760),startedAt:y.datetime(),finishedAt:y.datetime(),durationSeconds:o().min(0.05).max(15),frameCount:o().int().min(1).max(450),receivedFrameCount:o().int().min(1).max(2000),owner:i({runId:t().uuid(),deviceId:t().uuid(),rootId:t().uuid(),rootRevision:t().max(64),profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:t().min(1).max(1024),generation:t().uuid(),browserScope:t().max(128),tabId:o().int().positive()}).strict()}).strict().refine((e)=>e.receivedFrameCount>=e.frameCount&&Math.abs((Date.parse(e.finishedAt)-Date.parse(e.startedAt))/1000-e.durationSeconds)<=0.1)}).strict();var rl=me.extend({action:s(["start","inspect"]),recording_boot_generation:t().uuid(),recording_operation_id:t().uuid().optional(),recording_attempt_id:t().uuid().optional()}).strict();import{execFile as zr}from"child_process";import{promisify as Kr}from"util";var al=Kr(zr);var Vr=s(["recording_failed","authority_lost","browser_timeout","cleanup_failed","no_frames","encoding_invalid","frame_invalid","timestamp_invalid","capture_bound","ack_failed","cancelled","detached","browser_changed","tab_not_owned","encoding_frames_failed","encoding_encode_failed","encoding_output_failed","encoding_probe_failed","encoding_probe_streams_failed","encoding_probe_dimensions_failed","encoding_probe_duration_failed","encoding_probe_frames_failed","encoding_probe_format_failed","encoding_decode_failed","encoding_pin_failed"]);var j=t().min(1).max(1024),ht=i({path:j,sha256:t().regex(/^[a-f0-9]{64}$/)}).strict(),Jr=i({owner:i({runId:j,deviceId:j,rootId:j,rootRevision:j,profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:j,generation:j,browserScope:j,tabId:o().int().positive()}).strict(),socketPath:j,extensionId:t().regex(/^[a-p]{32}$/),nativeHostName:j,seconds:o().int().min(1).max(15),encoder:i({ffmpeg:ht,ffprobe:ht}).strict()}).strict();var Cl=i({version:n("0.1.42"),metadata:i({extensionId:t(),extensionInstanceId:t(),nativeHostName:t()})});var $l=i({operationId:t().uuid()}).strict();var nd=Qr(Zr);var id=i({version:n("0.1.42"),metadata:i({extensionId:n(F),extensionInstanceId:t().min(1).max(1024)})});var Le=1;var If=c({type:n("configure"),protocol:n(Le),version:t(),config:B}),xf=c({type:n("ticket"),organizationId:t().min(1).max(160),receipt:Ie()}),Of=c({type:s(["ping","stop"])});var Vf=c({type:n("hello"),protocol:n(Le),version:t(),platform:s(["linux","darwin"]),architecture:s(["arm64","x64"]),enrolled:d()}),Jf=c({type:n("ticket-request"),request:c({install_id:k(),code_challenge:t().regex(/^[A-Za-z0-9_-]{43}$/),lifecycle:s(["persistent","ephemeral"]),roots:u(c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/),execution_mode:s(["confined","host"]),permissions:c({read:n(!0),write:n(!0),execute:n(!0),discover_environment:n(!0),expose_mcp:n(!1)})})).length(1)})}),Gf=_("type",[c({type:n("running"),deviceId:t().min(1).max(160),expiresAt:y.datetime({offset:!0}),lifetime:s(["persistent","ephemeral"]),supervision:n("ssh-foreground")}),c({type:n("pong")}),c({type:n("stopped")})]);var wo=1;var Z=k(),yo=c({kind:n("install_only"),authorityId:Z,organizationId:Z,userId:Z,connectionId:Z,attemptId:Z,purpose:n("install"),generation:o().int().positive(),transport:n("reverse_ssh"),expiresAt:y.datetime({offset:!0}),maxDurationMs:n(300000),maxChannels:n(1),allowTcpForwarding:n(!1),allowPty:n(!1)}),_o=t().max(2048).superRefine((e,r)=>{let p;try{p=new URL(e)}catch{r.addIssue({code:"custom",message:"invalid relay url"});return}if(p.protocol!=="ws:"&&p.protocol!=="wss:"){r.addIssue({code:"custom",message:"invalid relay protocol"});return}if(p.username||p.password||p.search||p.hash){r.addIssue({code:"custom",message:"relay credentials or modifiers are not allowed"});return}let b=p.pathname.split("/");if(b.length!==4||b[1]!=="device"||!Z.safeParse(b[2]).success||!/^[a-f0-9]{64}$/.test(b[3]??""))r.addIssue({code:"custom",message:"invalid device relay path"});if(p.protocol==="ws:"&&!["127.0.0.1","[::1]"].includes(p.hostname))r.addIssue({code:"custom",message:"plaintext relay must be loopback"})});var Zf=c({protocol:n(wo),type:n("ssh_install_relay"),authorityToken:t().regex(/^(?:reason|ara)_ssh_install_[A-Za-z0-9_-]{43}$/),authority:yo,relayUrl:_o,endpoint:c({host:n("127.0.0.1"),port:n(22)})});class Rt extends Error{}function Fe(e){if(!f(e))return null;let r=new Rt(`${e} is not a valid worker config. Remove it to start over.`),p;try{p=JSON.parse(h(e))}catch(R){if(R instanceof SyntaxError)throw r;throw R}let b=B.safeParse(p);if(!b.success)throw r;return b.data}var Io=200;var Kp=c({version:n(1),session_ids:u(t().min(1).max(200)).max(Io)});function rt(e,r,p=!1){let b=xo(e,r,p);return b.length===1?b[0]:J(xe(J(e,".config")),...Et(r,p))}var Et=(e,r)=>[...e==="production"?[]:[e],r?"connect-once":"connect"];function xo(e,r,p=!1){let b=e;try{b=pe(e)}catch{}return["ara","reason"].map((R)=>J(b,".config",R,...Et(r,p))).filter(Oo)}function Oo(e){try{if(pe(e)!==e)return!1;return Fe(J(e,"worker.json"))?.stateDirectory===e}catch{return!1}}var Lo="disconnected.json";function cs(e,r){return f(J(rt(e,r),Lo))}function Mo(e,r){return r==="darwin"&&e.userChrome!==!1}var kg=i({root:i({id:t().min(1).max(160),label:t().max(160),path_fingerprint:t()})});var vg=Symbol("serve here");async function ls(e={}){let r=pe(e.home??a()),p=Fe(J(rt(r,e.channel??g()),"worker.json"));if(!p)return null;let b,R=await(e.controlWorker??G)(p,"status").catch((T)=>(b=T instanceof Error?T:Error(String(T)),null)),S=R?tt(p):null,P=e.serviceHost??Ee(r),E=Xe(p,P,"connect"),C=H(p).revoked,L=!C&&!R,x=(()=>{try{return M(p)}catch{return null}})(),{workspaces:A,off:D}=C||we(p.stateDirectory)!==null?{workspaces:null,off:null}:qe(p,R?.phase==="running");return{workspaces:A,workspaces_off:D,workspaces_max:je+(A?.filter((T)=>T.account).length??0),name:p.name,device_id:x?.deviceId??null,organization_id:x?.orgId??null,folder:p.workspaceRoot,mode:p.executionMode,sessions_max:null,user_chrome:Mo(p,P.platform),cloud_sessions:p.cloudSessions===!0,root:x?.roots[0]?{id:x.roots[0].id,permissions:x.roots[0].permissions}:null,roots:x?.roots.map((T)=>({id:T.id,folder:T.path,permissions:T.permissions}))??[],state:C?"removed":R?R.phase==="running"?"connected":R.phase:"not_running",not_running_reason:L?ot(p,b):null,worker_alive:L&&E?zn(E,P):null,sessions_running:R?.activeSessions??null,version:S,service:E?{label:E.label,logs:E.logs}:null}}function us(e={}){let r=pe(e.home??a()),p=Fe(J(rt(r,e.channel??g()),"worker.json"));if(!p)return null;return qr(p,e.serviceHost??Ee(r),"connect")?.label??null}export{w,M,lr,Fe,rt,cs,ls,us};
@@ -0,0 +1,9 @@
1
+ // @bun
2
+ import{De,Ne}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{request as Le}from"http";import{pipeline as Ce}from"stream";import{constants as te,createBrotliCompress as $e,createGzip as Me}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as We,timingSafeEqual as Re}from"crypto";import{createServer as Be}from"net";var p={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function Z(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function pe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function fe(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!Z(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(pe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function He(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function ue(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=p.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function ge(e){if(Buffer.byteLength(e)>p.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!Z(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,p.chunk,p.upload)?{messages:t.messages}:{},...L(t.window,1,p.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!pe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,p.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&ue(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&ue(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,p.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function ee(e){let t=[...e],n=new Set(t.filter(([s])=>s.toLowerCase()==="connection").flatMap(([,s])=>s.toLowerCase().split(",").map((i)=>i.trim()))),o=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return t.filter(([s])=>!o.has(s.toLowerCase())&&!n.has(s.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(s))}async function re(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),p.authorizationMs)})])}finally{clearTimeout(t)}}async function Dt(e){return await re(e)===!0}function J(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function at(e){if(!Z(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:J(e.deviceRelayUrl,"device")}}function Yi(e){if(!Z(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var be="x-preview-connection";async function he(e,t){if(t.aborted)throw Error("preview_closed");let n=We(32).toString("base64url"),o=new Set,s=!1,i=Be((c)=>{if(s||t.aborted||o.size>=p.streams*2)return c.destroy();o.add(c);let d=new AbortController;c.once("close",()=>{o.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let b=Buffer.alloc(0),m=(g)=>{b=Buffer.concat([b,g]);let w=b.indexOf(`\r
3
+ \r
4
+ `);if(w<0){if(b.length>16384)c.destroy();return}if(c.pause(),c.off("data",m),w>16384||b.length>p.upload+16384)return c.destroy();l(b,w).catch(()=>c.destroy())};c.on("data",m);async function l(g,w){let y=g.subarray(0,w).toString("latin1").split(`\r
5
+ `),_=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(y.shift()??"");if(!_)throw Error("preview_request_invalid");H(_[2]);let k=!1,O=0,T=[];for(let B of y){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(B);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===be){O++;let N=Buffer.from(S[2].trim());k=N.length===n.length&&Re(N,Buffer.from(n))}else if(S[1].toLowerCase()!=="host")T.push(B)}if(!k||O!==1||s||d.signal.aborted)throw Error("preview_connection_denied");let v=await e.connect(d.signal);if(s||d.signal.aborted)throw v.destroy(),Error("preview_closed");o.add(v),v.on("error",()=>c.destroy()),v.once("close",()=>{o.delete(v),c.destroy()}),c.once("close",()=>v.destroy()),c.setTimeout(0);let P=[`${_[1]} ${_[2]} HTTP/1.1`,`Host: 127.0.0.1:${v.remotePort}`,...T,"",""].join(`\r
6
+ `);v.write(Buffer.concat([Buffer.from(P,"latin1"),g.subarray(w+4)])),v.pipe(c),c.pipe(v),c.resume()}});await new Promise((c,d)=>{i.once("error",d),i.listen(0,"127.0.0.1",c)});let a=i.address();if(!a||typeof a==="string")throw i.close(),Error("preview_bind_failed");function u(){if(s)return;s=!0,t.removeEventListener("abort",u);for(let c of o)c.destroy();o.clear(),i.close()}if(t.addEventListener("abort",u,{once:!0}),t.aborted)u();return{port:a.port,headers:{[be]:n},close:u}}var Oe=60000,Fe=1e4,ze=5000,Ue=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function je(e,t,n,o){let s=(c)=>t.find(([d])=>d.toLowerCase()===c)?.[1],i=(c)=>o.find(([d])=>d.toLowerCase()===c)?.[1],a=Number(i("content-length")??Number.NaN);if(e!=="GET"||n!==200||s("range")!==void 0||i("content-encoding")!==void 0||!Ue.test(i("content-type")??"")||/\bno-transform\b/i.test(i("cache-control")??"")||a<1024)return null;let u=(c)=>new RegExp(`(?:^|,)\\s*${c}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test(s("accept-encoding")??"");return u("br")?"br":u("gzip")?"gzip":null}function qe(e,t){let n=e.filter(([o])=>o.toLowerCase()==="vary").map(([,o])=>o).join(", ");return[...e.filter(([o])=>!["vary","etag","content-md5"].includes(o.toLowerCase())),...e.filter(([o])=>o.toLowerCase()==="etag").map(([o,s])=>[o,s.startsWith("W/")?s:`W/${s}`]),["Content-Encoding",t],["Vary",n.split(",").some((o)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(o))?n:n?`${n}, Accept-Encoding`:"Accept-Encoding"]]}async function yn(e){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:e.jobId,port:e.port,reason_code:e.reason})}
7
+ `);let t=e.binding,n;try{n=J(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((o)=>{let s=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{s.terminate(),o()},p.authorizationMs*2);s.addEventListener("open",()=>{s.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),s.close(1000,`worker_refused_${e.reason}`)}),s.addEventListener("error",()=>{clearTimeout(i),o()}),s.addEventListener("close",()=>{clearTimeout(i),o()})})}async function Ke(e,t){let n=Date.now()+Fe,o;for(;;){if(!t())return"closed";let s=o??=e.refusal().finally(()=>{o=void 0}),i,a=await Promise.race([s.catch(()=>"port_unproved"),new Promise((u)=>{i=setTimeout(()=>u("port_check_timeout"),p.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((u)=>setTimeout(u,500))}}async function _e(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,o=t.expiresAtMs>Date.now()+p.lifetimeMs+ze?"binding_mismatch":await Ke(e.port,n);if(o)throw await yn({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:o}),Error("preview_not_authorized",{cause:o});let s=J(e.deviceRelayUrl,"device"),i=await he(e.port,e.signal),a;try{a=new U(s,{followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload*1.4+300000})}catch(f){throw i.close(),f}let u=new Map,c=!1,d=!1,b=0,m=!1,l,g,w,y=new Promise((f)=>{w=f}),_,k,O=new Promise((f,h)=>{_=f,k=h}),T=!1,v=(f)=>{let h=Buffer.isBuffer(f)?f:JSON.stringify(f);if(b+=Buffer.byteLength(h),!n()||d||a.readyState!==U.OPEN)return P(n()?"relay_closed":"expired");if(a.bufferedAmount>p.relayBuffered)return P("relay_backlog");if(b>p.total)return P("quota");a.send(h)};function P(f="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let h of u.values())h.stop();u.clear(),i.close(),a.close(1000,`worker_${f}`),k(Error("preview_closed")),w()}let B=()=>P("aborted"),S=setTimeout(()=>P("pair_timeout"),p.requestMs),N=setInterval(async()=>{if(!n())return P(e.signal.aborted?"aborted":"expired");if(m)return;m=!0;try{let f=l??=Promise.resolve().then(()=>e.port.check()).finally(()=>{l=void 0}),h=await re(()=>f);if(h===!1)return P("port_refused");if(h){g=void 0;return}if(Date.now()-(g??=Date.now())>Oe)return P("port_unknown");for(let E of u.values())E.stop()}finally{m=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())P(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>v({type:"hello",binding:t,messages:p.upload,window:p.window})),a.addEventListener("close",()=>P("relay_closed")),a.addEventListener("error",()=>P("relay_error")),a.addEventListener("message",(f)=>{try{if(!n()||d)return P(e.signal.aborted?"aborted":"expired");if(typeof f.data!=="string")throw Error("preview_frame_invalid");if(b+=Buffer.byteLength(f.data),b>p.total)return P("quota");let h=ge(f.data);if(!c){if(h.type!=="hello"||!He(t,h.binding))return P("binding_mismatch");c=!0,T=h.bytes===!0,clearTimeout(S),_();return}if(h.type==="hello"||h.type==="refused")return P("invalid_frame");if(h.type==="request"){D(h).catch(()=>P("invalid_request"));return}let E=u.get(h.id);if(!E)return;if(h.type==="cancel"||h.type==="end")E.stop();else if(h.type==="credit"&&E.credit)E.credit();else if(h.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>p.buffered)return E.stop();let I=z(h.data,p.upload);E.ws.send(h.binary?I:I.toString("utf8"))}else P("invalid_frame")}catch{P("invalid_frame")}});async function D(f){if(u.has(f.id)||u.size>=p.streams)return P("stream_limit");if(!n())return P(e.signal.aborted?"aborted":"expired");let h=new AbortController,E,I,q,Y=0,R=(W=!1)=>{if(!u.delete(f.id))return;clearTimeout(E),h.abort(),I?.close(1000,"preview_closed"),q?.(),v({type:W?"end":"cancel",id:f.id})},ie={stop:()=>R(),credit:()=>{Y++,q?.()}};if(u.set(f.id,ie),E=setTimeout(R,p.requestMs),!await Dt(()=>e.port.check())||!n()||h.signal.aborted)return R();let ae=H(f.path);if(f.upgrade){if(f.method!=="GET"||f.body)return R();let W=f.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${ae}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload}),ie.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),v({type:"ws",id:f.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let K=typeof A.data!=="string",M=me(A.data);if(M.length>p.upload)return R();v({type:"data",id:f.id,data:M.toString("base64"),binary:K})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let Te=z(f.body,p.upload),de=Le({hostname:"127.0.0.1",port:i.port,path:ae,method:f.method,headers:{...Object.fromEntries(ee(f.headers)),...i.headers,connection:"close"},signal:h.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let K=W.statusCode??502,M=je(f.method,f.headers,K,A),Q=M==="br"?$e({flush:te.BROTLI_OPERATION_FLUSH,params:{[te.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Me({level:6,flush:te.Z_SYNC_FLUSH}):void 0;if(v({type:"head",id:f.id,status:K,headers:ee(M?qe(A,M):A)}),clearTimeout(E),Q)Ce(W,Q,()=>{});for await(let F of Q??W){let ce=Buffer.from(F);for(let G=0;G<ce.length;G+=p.chunk){if(Y===0&&!h.signal.aborted)await new Promise((Ie)=>{q=Ie});if(q=void 0,h.signal.aborted)return;Y--;let le=ce.subarray(G,G+p.chunk);v(T?fe(f.id,le):{type:"data",id:f.id,data:le.toString("base64"),binary:!0})}}R(!0)}catch{R()}});de.on("error",()=>R()),de.end(Te)}return await O,{close:P,closed:y}}import{execFile as Ge}from"child_process";import{createRequire as Ze}from"module";import{win32 as V}from"path";var Je=250,Ve=50,Xe=250,Ye=4194304;function Pe(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Qe(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim().split(/\s+/);if(o[0]!=="TCP"||o.length<5)continue;let s=Pe(o[1]),i=Pe(o[2]),a=Number(o.at(-1));if(!s||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:s.address,localPort:s.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function er(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var ke=(e)=>new Promise((t,n)=>Ge(V.join(De("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:Ye,encoding:"utf8",windowsHide:!0,env:Ne()},(o,s)=>o?n(o):t(s)));function ne(e){let t=V.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function rr(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return o===n||o.startsWith(n.endsWith("\\")?n:`${n}\\`)}function xe(e,t,n){let o=e.cwd(n),s=o?ne(o):null;return s&&V.isAbsolute(s)&&rr(t,s)?s:null}var j;function ye(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=Ze(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,o,s;try{o=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,s=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,u=1040,c=568,d=(b,m,l)=>{let g=Buffer.alloc(l);return o.ReadProcessMemory(b,m,n(g),l,null)?g:null};return j={processes(){let b=BigInt(o.CreateToolhelp32Snapshot(a,0));if(b===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let m=Buffer.alloc(c);m.writeUInt32LE(c,0);let l=n(m),g=[];for(let w=o.Process32FirstW(b,l);w;w=o.Process32NextW(b,l)){let y=m.toString("utf16le",44,c),_=y.slice(0,y.includes("\x00")?y.indexOf("\x00"):void 0),k=m.readUInt32LE(8);if(k>0)g.push({pid:k,parentPid:m.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return g}finally{o.CloseHandle(b)}},cwd(b){let m=BigInt(o.OpenProcess(u,0,b));if(m===0n)return null;try{let l=Buffer.alloc(48);if(s.NtQueryInformationProcess(m,0,n(l),l.length,null)!==0)return null;let g=d(m,l.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),w=g?d(m,g+0x38n,16):null,y=w?.readUInt16LE(0)??0;if(!w||y===0||y%2!==0)return null;return d(m,w.readBigUInt64LE(8),y)?.toString("utf16le")??null}finally{o.CloseHandle(m)}}},j}function oe(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function Se(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Qe(n)}async function Qi(e,t=ye()){let n=oe(t),o=ne(e),s=[];for(let i of n.processes()){if(s.length>=Je)break;let a=xe(n,o,i.pid);if(a)s.push({pid:i.pid,command:i.command,cwd:V.relative(o,a)||"."})}return{processes:s}}async function eo(e,t=ye(),n=ke){let o=oe(t),s=ne(e),i=(await Se(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:er(d)})).sort((d,b)=>d.pid-b.pid||d.port-b.port||(d.address<b.address?-1:d.address>b.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,Ve),u=new Set(a.filter((d)=>xe(o,s,d)!==null));if(u.size===0)return{ports:[]};let c=new Map(o.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>u.has(d.pid)).slice(0,Xe).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function ve(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let s of e)if(!n.has(s.pid)&&n.has(s.parentPid)&&s.pid!==s.parentPid)n.add(s.pid),o=!0}return n}function tr(e,t,n,o){let s=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==o)return[];let a=i.listening&&(s(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),u=!i.listening&&s(i.localAddress)&&s(i.remoteAddress);if(!a&&!u)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:o,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function Ee(e,t,n=ye(),o=ke){let s=oe(n),i=ve(s.processes(),e),a=await Se(o,1000),u=ve(s.processes(),e);return tr(a,new Set([...i].filter((c)=>u.has(c))),e,t)}import{execFile as nr}from"child_process";import{readFile as or,readdir as sr,readlink as ir}from"fs/promises";import{connect as ar}from"net";import{setTimeout as dr}from"timers/promises";var cr={directory:sr,text:(e)=>or(e,"utf8"),link:ir};class se extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new se(e),X="preview_listener_unproved",Ae="00000000000000000000000001000000";async function lr(e,t,n=cr){let o=new Map;for(let a of["tcp","tcp6"]){let u=await n.text(`/proc/net/${a}`);if(u.length>4194304)throw x();for(let c of u.split(`
8
+ `).slice(1)){let d=c.trim().split(/\s+/);if(d.length<10||!["0A","01"].includes(d[3]))continue;let[b,m]=d[1].split(":"),[l,g]=d[2].split(":");if(Number.parseInt(m,16)!==t)continue;let w=(k)=>k==="0100007F"||k==="0000000000000000FFFF00000100007F"||k===Ae,y=d[3]==="0A";if(!(w(b)||y&&/^0+$/.test(b??"")))continue;if(!y&&!w(l))continue;let _=d[9];if(!/^[1-9][0-9]*$/.test(_))continue;o.set(_,{kernelId:_,port:t,peerPort:y?null:Number.parseInt(g,16),state:y?"listen":"established",host:b===Ae?"::1":"127.0.0.1"})}}let s=await n.directory("/proc");if(s.length>8192)throw x();let i=[];for(let a of s){if(!/^[1-9][0-9]*$/.test(a))continue;try{let u=await n.text(`/proc/${a}/stat`),c=u.slice(u.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(c[2])!==e)continue;let d=await n.directory(`/proc/${a}/fd`);if(d.length>1024)throw x();let b=[];for(let g of d){if(!/^[0-9]+$/.test(g))continue;let w=await n.link(`/proc/${a}/fd/${g}`).catch(()=>""),y=/^socket:\[([0-9]+)\]$/.exec(w)?.[1],_=y?o.get(y):void 0;if(_)b.push({..._,pid:Number(a),processGroupId:e,descriptor:g})}let m=await n.text(`/proc/${a}/stat`),l=m.slice(m.lastIndexOf(")")+2).trim().split(/\s+/);if(c[19]===l[19]&&c[2]===l[2])i.push(...b)}catch(u){if(u instanceof Error&&u.message==="preview_port_ownership_unproved")throw u}}return i}function ur(e,t,n){if(e.length>2097152)throw x();let o=0,s=0,i="",a="",u="",c="",d=[],b=()=>{if(o<1||s!==t||!/^\d+$/.test(i)||!/^0x[0-9a-f]+$/i.test(a))return;let m=c==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((g)=>u===`${g}:${n}`),l=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${n}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(u);if(m||c==="ESTABLISHED"&&l)d.push({pid:o,processGroupId:s,descriptor:i,kernelId:a,state:m?"listen":"established",port:n,peerPort:m?null:Number(l[1]),host:u.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let m of e.split(/[\0\n]/)){let l=m.slice(1);if(m[0]==="p")b(),o=Number(l),s=0,i=a=u=c="";else if(m[0]==="g")s=Number(l);else if(m[0]==="f")b(),i=l,a=u=c="";else if(m[0]==="d")a=l;else if(m[0]==="n")u=l;else if(m.startsWith("TST="))c=m.slice(4)}return b(),d}async function pr(e,t){if(process.platform==="linux")return lr(e,t);if(process.platform==="win32")return Ee(e,t);if(process.platform!=="darwin")throw x();let n=await new Promise((o,s)=>nr("/usr/sbin/lsof",["-nP","-a","-g",String(e),`-iTCP:${t}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(i,a)=>i?s(x()):o(a)));return ur(n,e,t)}function we(e,t={}){let n=C(e.binding),o=t.inspectSockets??pr,s=t.monotonicNow??(()=>performance.now());async function i(){let l=()=>{if(Date.now()>=n.expiresAtMs)throw x("binding_expired");if(e.deniedPorts.has(n.port))throw x("port_denied")};l();let g=await e.readCurrentJob(),w=g?.job,y=w?.process;if(l(),!g)throw x("server_stopped");if(!He(n,g.binding)||w?.jobId!==n.jobId)throw x("binding_changed");if(w.state!=="running"||w.finishedAtMs!==null||w.leaseExpiresAtMs<n.expiresAtMs)throw x("job_not_running");if(!y||y.pid<1||y.pid!==y.processGroupId||y.executorLaunchId!==g.executorLaunchId)throw x("process_unproved");return{pid:y.pid,launch:y.executorLaunchId,started:w.startedAtMs}}let a,u;async function c(){let l=await i(),g=await o(l.pid,n.port).catch(()=>{throw Error(X)}),w=await i();if(l.pid!==w.pid||l.launch!==w.launch||l.started!==w.started)throw x("job_restarted");return g}async function d(l){for(;;){if(u&&u.startedAt>=l)return u.sockets;if(a&&a.startedAt>=l)return await a.sockets;if(a){await a.sockets.catch(()=>{});continue}let g={startedAt:s(),sockets:c()};a=g;try{let w=await g.sockets;if(!u||u.startedAt<=g.startedAt)u={startedAt:g.startedAt,sockets:w};return w}finally{if(a===g)a=void 0}}}async function b(l=()=>{},g=s()){l();let w=await d(g);if(l(),Date.now()>=n.expiresAtMs)throw x("binding_expired");if(!w.some((y)=>y.state==="listen"))throw Error(X);return w}async function m(){try{return await b(()=>{},s()-1000),null}catch(l){if(l instanceof Error&&l.message===X)return"listener_unproved";return l instanceof se?l.code:"port_unproved"}}return{refusal:m,async check(){let l=await m();if(l==="listener_unproved")throw Error(X);return l===null},async connect(l){if(l.aborted)throw x();let g=s()+2000,w=new AbortController,y=new Promise((P)=>w.signal.addEventListener("abort",()=>P(null),{once:!0})),_,k=()=>{w.abort(),_?.destroy()},O=setTimeout(k,2000);l.addEventListener("abort",k,{once:!0});let T=()=>{if(w.signal.aborted||l.aborted||s()>=g||_?.destroyed)throw k(),x()};async function v(P){T();let B=await Promise.race([P().then((S)=>({value:S})),y]);if(T(),!B)throw x();return B.value}try{let P=await v(()=>b(T,s()-1000));T();let B=P.some((f)=>f.state==="listen"&&f.host==="127.0.0.1")?"127.0.0.1":"::1",S=ar({host:B,port:n.port,signal:l});_=S,S.once("close",k),await v(()=>new Promise((f,h)=>{S.once("connect",f),S.once("error",h)}));let N=S.localPort;if(!N)throw x();let D=s();while(!(await v(()=>b(T,D))).some((f)=>f.state==="established"&&f.peerPort===N))await v(()=>dr(Math.min(20,Math.max(1,g-s())),void 0,{signal:w.signal})),D=s();return T(),S}catch(P){throw k(),P}finally{clearTimeout(O),l.removeEventListener("abort",k),_?.off("close",k),w.abort()}}}}
9
+ export{p,He,Dt,at,Yi,yn,_e,ye,Qi,eo,we};
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{E}from"./vm-hands-entry-lite-pgb514h0.js";import{fe,Re,Kt,Jt,Oe}from"./vm-hands-entry-lite-9ay6f56v.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var fr=process.platform==="win32"?Re("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=fr.split(g),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Kt(),stdio:["ignore","pipe","ignore"]}),Jt(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)Oe(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function mr(t,e=process.platform){let n=e==="win32",r=t.split(`
3
- `).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(E(s))continue;o.push(s)}return h(o)}function ln(t){let e=t?.home??m(),n=t?.directoryExists??p,r=b.map((o)=>f(e,...o)).filter((o)=>{try{return n(o)}catch{return!1}});return h([...r,...process.platform==="win32"?mr(process.env.PATH??process.env.Path??""):[],...P]).join(g)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:ln({home:t?.home,directoryExists:t?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!w(e))return n();let r;try{r=await(t?.runLoginShell??x)(e,["-lic",'printf %s "$PATH"'])}catch{return n()}if(Buffer.byteLength(r,"utf8")>S)return n();let o=mr(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function $i(t){let e=null;return()=>(e??=C(t),e)}function l(t){if(t===void 0||t.includes("\x00")||Buffer.byteLength(t,"utf8")>32768)return;return t}function Me(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??fr,TMPDIR:t.temporaryDirectory,SHELL:l(e.SHELL)??"/bin/zsh",LANG:l(e.LANG)??"C.UTF-8",LC_ALL:l(e.LC_ALL)??l(e.LANG)??"C.UTF-8"},r=l(e.LC_CTYPE),o=l(e.TERM),i=l(e.COLORTERM);if(r)n.LC_CTYPE=r;if(o)n.TERM=o;if(i)n.COLORTERM=i;if(process.platform==="win32"){for(let s of I){let a=l(e[s]);if(a)n[s]=a}n.TEMP=n.TMP=t.temporaryDirectory,n.SHELL=fe()??n.SHELL,n.PATH=un(n.PATH)}return n}function un(t,e=f(m(),".reason","python3")){let n=(i)=>t.split(u.delimiter).filter((s)=>s&&!/[\\/]WindowsApps[\\/]?$/i.test(s)).map((s)=>u.join(s,i)).find((s)=>p(s)),r=n("python.exe");if(n("python3.exe")||!r)return t;let o=`#!/bin/sh
2
+ import{E}from"./vm-hands-entry-lite-dk79tnax.js";import{fe,De,Le,Me,$e}from"./vm-hands-entry-lite-6c67a3jc.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var xr=process.platform==="win32"?De("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=xr.split(g),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Le(),stdio:["ignore","pipe","ignore"]}),Me(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)$e(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function kr(t,e=process.platform){let n=e==="win32",r=t.split(`
3
+ `).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(E(s))continue;o.push(s)}return h(o)}function bn(t){let e=t?.home??m(),n=t?.directoryExists??p,r=b.map((o)=>f(e,...o)).filter((o)=>{try{return n(o)}catch{return!1}});return h([...r,...process.platform==="win32"?kr(process.env.PATH??process.env.Path??""):[],...P]).join(g)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:bn({home:t?.home,directoryExists:t?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!w(e))return n();let r;try{r=await(t?.runLoginShell??x)(e,["-lic",'printf %s "$PATH"'])}catch{return n()}if(Buffer.byteLength(r,"utf8")>S)return n();let o=kr(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function io(t){let e=null;return()=>(e??=C(t),e)}function l(t){if(t===void 0||t.includes("\x00")||Buffer.byteLength(t,"utf8")>32768)return;return t}function ze(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??xr,TMPDIR:t.temporaryDirectory,SHELL:l(e.SHELL)??"/bin/zsh",LANG:l(e.LANG)??"C.UTF-8",LC_ALL:l(e.LC_ALL)??l(e.LANG)??"C.UTF-8"},r=l(e.LC_CTYPE),o=l(e.TERM),i=l(e.COLORTERM);if(r)n.LC_CTYPE=r;if(o)n.TERM=o;if(i)n.COLORTERM=i;if(process.platform==="win32"){for(let s of I){let a=l(e[s]);if(a)n[s]=a}n.TEMP=n.TMP=t.temporaryDirectory,n.SHELL=fe()??n.SHELL,n.PATH=vn(n.PATH)}return n}function vn(t,e=f(m(),".reason","python3")){let n=(i)=>t.split(u.delimiter).filter((s)=>s&&!/[\\/]WindowsApps[\\/]?$/i.test(s)).map((s)=>u.join(s,i)).find((s)=>p(s)),r=n("python.exe");if(n("python3.exe")||!r)return t;let o=`#!/bin/sh
4
4
  exec "${r.replaceAll("\\","/")}" "$@"
5
5
  `;try{let i=f(e,"python3");if(!p(i)||_(i,"utf8")!==o)T(e,{recursive:!0}),A(i,o)}catch{return t}return[e,t].join(u.delimiter)}var I=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
6
- export{fr,mr,ln,$i,Me,un};
6
+ export{xr,kr,bn,io,ze,vn};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{C}from"./vm-hands-entry-lite-t7an5zg2.js";import{g}from"./vm-hands-entry-lite-ckv17tn8.js";import{Nr,Pn,Lr,Tn}from"./vm-hands-entry-lite-qysyf65v.js";import{Ln,Ut,lo}from"./vm-hands-entry-lite-qk4kexta.js";import{x}from"./vm-hands-entry-lite-9ay6f56v.js";import{spawnSync as v}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as P,mkdirSync as $e,readdirSync as Ve,readFileSync as k,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as We}from"fs";import{dirname as Ae,isAbsolute as Y,join as p}from"path";import{spawnSync as de}from"child_process";import{readFileSync as me}from"fs";import{userInfo as D}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function H(r){return fe(r,"AppData","Local","Reason","Tasks")}function w(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function M(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${w(r)};`}function U(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${w(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(w).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${w(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[M(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${D().username}`:D().username}function B(r){let e=I(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
2
+ import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{g}from"./vm-hands-entry-lite-aj139v8j.js";import{Wr,qn,Vr,Wn}from"./vm-hands-entry-lite-g4zd2d5n.js";import{Xn,Qt,Oo}from"./vm-hands-entry-lite-hn76pcgk.js";import{C}from"./vm-hands-entry-lite-6c67a3jc.js";import{spawnSync as v}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as P,mkdirSync as $e,readdirSync as Ve,readFileSync as k,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as be}from"fs";import{dirname as We,isAbsolute as q,join as p}from"path";import{spawnSync as de}from"child_process";import{readFileSync as me}from"fs";import{userInfo as D}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function H(r){return fe(r,"AppData","Local","Reason","Tasks")}function w(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function M(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${w(r)};`}function K(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${w(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(w).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${w(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[M(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${D().username}`:D().username}function U(r){let e=I(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
3
3
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
4
4
  <RegistrationInfo>
5
5
  <Description>${I(r.description)}</Description>
@@ -33,21 +33,21 @@ import{C}from"./vm-hands-entry-lite-t7an5zg2.js";import{g}from"./vm-hands-entry-
33
33
  </Exec>
34
34
  </Actions>
35
35
  </Task>
36
- `}function V(r){return Buffer.concat([Buffer.from([255,254]),Buffer.from(r.replaceAll(`\r
36
+ `}function B(r){return Buffer.concat([Buffer.from([255,254]),Buffer.from(r.replaceAll(`\r
37
37
  `,`
38
38
  `).replaceAll(`
39
39
  `,`\r
40
- `),"utf16le")])}function j(r){let e=me(r);return(e[0]===255&&e[1]===254?e.subarray(2).toString("utf16le"):e.toString("utf8")).replaceAll(`\r
40
+ `),"utf16le")])}function V(r){let e=me(r);return(e[0]===255&&e[1]===254?e.subarray(2).toString("utf16le"):e.toString("utf8")).replaceAll(`\r
41
41
  `,`
42
- `)}function F(r,e){return["/Create","/TN",r,"/XML",e,"/F"]}function E(r){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}function _(r){return`'*${M(r).replaceAll("'","''")}*'`}function T(r,e){return E(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${_(r)} })`,...e.keepWrapper?[]:["foreach ($w in $wrappers) { Stop-Process -Id $w.ProcessId -Force -ErrorAction SilentlyContinue }"],`foreach ($w in $wrappers) { $all | ? { $_.ParentProcessId -eq $w.ProcessId } | % { taskkill.exe /F ${e.tree?"/T ":""}/PID $_.ProcessId | Out-Null } }`].join(`
43
- `))}function X(r){return E(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${_(r)} })`,"foreach ($w in $wrappers) { if ($all | ? { $_.ParentProcessId -eq $w.ProcessId -and $_.Name -ne 'conhost.exe' }) { 'running'; exit 0 } }","exit 1"].join(`
44
- `))}function G(r,e=process.pid){let n=de(x("powershell.exe"),E(["$all = @{}; Get-CimInstance Win32_Process | % { $all[[int]$_.ProcessId] = $_ }",`$p = $all[${Math.trunc(e)}]`,"for ($i = 0; $p -and $i -lt 64; $i++) {",` if ($p.CommandLine -like ${_(r)}) { exit 10 }`," $n = $all[[int]$p.ParentProcessId]"," if (-not $n -or $n.ProcessId -eq $p.ProcessId -or $n.CreationDate -gt $p.CreationDate) { exit 11 }"," $p = $n","}","exit 11"].join(`
45
- `)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var Ir="REASON_WORKER_SERVICE",Ie="worker_identity_unavailable";function be(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>v(x(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=v(x(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>lo(r,e),insideService:(e,n)=>xe(e,process.platform,process.getuid?.(),n)}}function xe(r,e,n,t=!0){if(process.env[Ir]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return k("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return G(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=v("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Ee)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=v("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var Ee=113;class K extends Error{code;constructor(r,e){super(r);this.code=e}}function Cn(r,e){if(!re(r.home,r.platform))throw new K(ee);if(r.platform==="darwin")S(r);let n=Tn(Nr(e,r.home)),t=g({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?Pn(n):null,C(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?p(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):p(r.home,".local","bin",i)];for(let a of s)try{if(a&&Y(a)&&ve(a).isFile())return Lr(a)}catch{}throw new K(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var R=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,y=new RegExp(`(\\n\\s*<key>${Ut}</key>\\s*<string>)[^<]*(</string>)`),_e=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Te(r){return r.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function J(r){let e=[...(R.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Te(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function z(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function h(r){return r.map((e)=>` <string>${d(e)}</string>`).join(`
46
- `)}function Z(r,e){let n;try{n=k(r,"utf8")}catch{return null}let t=J(n);if(!t)return null;let i=Y(t.launcher)?Lr(t.launcher):t.launcher,{program:s,identity:a}=z(i,t.args,e),o=n.replace(R,(l,c,m,O)=>`${c}${h(s)}
42
+ `)}function j(r,e){return["/Create","/TN",r,"/XML",e,"/F"]}function x(r){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}function E(r){return`'*${M(r).replaceAll("'","''")}*'`}function _(r,e){return x(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${E(r)} })`,...e.keepWrapper?[]:["foreach ($w in $wrappers) { Stop-Process -Id $w.ProcessId -Force -ErrorAction SilentlyContinue }"],`foreach ($w in $wrappers) { $all | ? { $_.ParentProcessId -eq $w.ProcessId } | % { taskkill.exe /F ${e.tree?"/T ":""}/PID $_.ProcessId | Out-Null } }`].join(`
43
+ `))}function F(r){return x(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${E(r)} })`,"foreach ($w in $wrappers) { if ($all | ? { $_.ParentProcessId -eq $w.ProcessId -and $_.Name -ne 'conhost.exe' }) { 'running'; exit 0 } }","exit 1"].join(`
44
+ `))}function X(r,e=process.pid){let n=de(C("powershell.exe"),x(["$all = @{}; Get-CimInstance Win32_Process | % { $all[[int]$_.ProcessId] = $_ }",`$p = $all[${Math.trunc(e)}]`,"for ($i = 0; $p -and $i -lt 64; $i++) {",` if ($p.CommandLine -like ${E(r)}) { exit 10 }`," $n = $all[[int]$p.ParentProcessId]"," if (-not $n -or $n.ProcessId -eq $p.ProcessId -or $n.CreationDate -gt $p.CreationDate) { exit 11 }"," $p = $n","}","exit 11"].join(`
45
+ `)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var zr="REASON_WORKER_SERVICE",Ae="worker_identity_unavailable";function Ee(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>v(C(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=v(C(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>Oo(r,e),insideService:(e,n)=>Ie(e,process.platform,process.getuid?.(),n)}}function Ie(r,e,n,t=!0){if(process.env[zr]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return k("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return X(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=v("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===xe)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=v("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var xe=113;class J extends Error{code;constructor(r,e){super(r);this.code=e}}function Hn(r,e){if(!re(r.home,r.platform))throw new J(ee);if(r.platform==="darwin")S(r);let n=Wn(Wr(e,r.home)),t=g({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?qn(n):null,T(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?p(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):p(r.home,".local","bin",i)];for(let a of s)try{if(a&&q(a)&&ve(a).isFile())return Vr(a)}catch{}throw new J(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var R=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,y=new RegExp(`(\\n\\s*<key>${Qt}</key>\\s*<string>)[^<]*(</string>)`),_e=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Te(r){return r.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function Y(r){let e=[...(R.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Te(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function z(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function h(r){return r.map((e)=>` <string>${d(e)}</string>`).join(`
46
+ `)}function Z(r,e){let n;try{n=k(r,"utf8")}catch{return null}let t=Y(n);if(!t)return null;let i=q(t.launcher)?Vr(t.launcher):t.launcher,{program:s,identity:a}=z(i,t.args,e),o=n.replace(R,(l,c,m,O)=>`${c}${h(s)}
47
47
  ${O}`);if(!a)o=o.replace(y,"");else if(y.test(o))o=o.replace(y,(l,c,m)=>`${c}${d(a.app)}${m}`);else o=o.replace(_e,(l,c,m)=>`${c}
48
- <key>${Ut}</key>
49
- <string>${d(a.app)}</string>${m}`);return o===n?null:o}function Pe(r,e){let n=Z(r,e);if(n!==null)A(r,n)}function ps(r,e,n){if(e.platform!=="darwin")return!1;let t=qe(r,e,n);return t!==null&&Z(t.definition,e)!==null}var W="com.reasonmachines.worker.",N="so.reason.worker.",Q=[W,N];function Wi(r,e=W){return`${e}connect${r==="production"?"":`.${r}`}`}function hs(r,e){return Q.some((n)=>r===Wi(e,n))}function Re(r,e,n){if(e==="connect")return Wi(r.channel,n);let t=ke("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var ee="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function re(r,e){if(e==="darwin")return{directory:p(r,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:p(r,".config","systemd","user"),suffix:".service"};if(e==="win32")return{directory:H(r),suffix:".xml"};return null}function f(r,e,n,t=W){let i=Re(r,n,t),s=re(e.home,e.platform);if(!s)return null;return{label:i,definition:p(s.directory,`${i}${s.suffix}`),logs:e.platform==="linux"?`journalctl --user -u ${i}.service`:p(r.stateDirectory,"service.log")}}function qe(r,e,n="serve"){return ne(r,e,n)[0]??null}function ne(r,e,n){return Q.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&P(t.definition))}function te(r,e,n){let t=f(r,e,n,N);return t&&P(t.definition)?t:null}function Oo(r,e,n){let t=f(r,e,n),i=te(r,e,n);if(!t||!i||!P(t.definition)||e.insideService?.(i.label))return null;if(!Ce(t,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);return u(i.definition,{force:!0}),"retired"}if(e.platform==="win32")return b(i,e,!0),"retired";return e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Ce(r,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`])===0;if(e.platform==="win32")return e.command("schtasks",["/Query","/TN",r.label])===0;let n=`${r.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",n])===0&&he.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var he=new Set(["active","activating","reloading"]);function An(r,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let n=e.read("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(n??"")?.[1]??0)>0}if(e.platform==="win32")return e.read("powershell.exe",X(r.label))?.trim()==="running";return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${r.label}.service`])?.trim()??0)>0}function fs(r){let{config:e,launcher:n,host:t,kind:i}=r,s=f(e,t,i);if(!s)return!1;let a;try{a=t.platform==="win32"?j(s.definition):k(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===se(e,i,s,n);if(t.platform!=="darwin")return a===oe(e,i,s,n,t.home,r.path);let o=J(a);return a.replace(y,"").replace(R,(c,m,O,ue)=>`${m}${o?`${h([o.launcher,...o.args])}
50
- `:""}${ue}`)===ie(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function L(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function q(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new K("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function ie(r,e,n,t,i,s){let a=L(r,e),o=z(t,a.args,i),l={HOME:i.home,PATH:s,[Ir]:n.label,...a.environment,...o.identity?{[Ut]:o.identity.app}:{}};return{identity:o.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
48
+ <key>${Qt}</key>
49
+ <string>${d(a.app)}</string>${m}`);return o===n?null:o}function Pe(r,e){let n=Z(r,e);if(n!==null)A(r,n)}function $s(r,e,n){if(e.platform!=="darwin")return!1;let t=Xe(r,e,n);return t!==null&&Z(t.definition,e)!==null}var W="com.reasonmachines.worker.",N="so.reason.worker.",Q=[W,N];function ho(r,e=W){return`${e}connect${r==="production"?"":`.${r}`}`}function Bs(r,e){return Q.some((n)=>r===ho(e,n))}function Re(r,e,n){if(e==="connect")return ho(r.channel,n);let t=ke("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var ee="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function re(r,e){if(e==="darwin")return{directory:p(r,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:p(r,".config","systemd","user"),suffix:".service"};if(e==="win32")return{directory:H(r),suffix:".xml"};return null}function f(r,e,n,t=W){let i=Re(r,n,t),s=re(e.home,e.platform);if(!s)return null;return{label:i,definition:p(s.directory,`${i}${s.suffix}`),logs:e.platform==="linux"?`journalctl --user -u ${i}.service`:p(r.stateDirectory,"service.log")}}function Xe(r,e,n="serve"){return ne(r,e,n)[0]??null}function ne(r,e,n){return Q.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&P(t.definition))}function te(r,e,n){let t=f(r,e,n,N);return t&&P(t.definition)?t:null}function Yo(r,e,n){let t=f(r,e,n),i=te(r,e,n);if(!t||!i||!P(t.definition)||e.insideService?.(i.label))return null;if(!Ce(t,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);return u(i.definition,{force:!0}),"retired"}if(e.platform==="win32")return b(i,e,!0),"retired";return e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Ce(r,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`])===0;if(e.platform==="win32")return e.command("schtasks",["/Query","/TN",r.label])===0;let n=`${r.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",n])===0&&he.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var he=new Set(["active","activating","reloading"]);function zn(r,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let n=e.read("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(n??"")?.[1]??0)>0}if(e.platform==="win32")return e.read("powershell.exe",F(r.label))?.trim()==="running";return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${r.label}.service`])?.trim()??0)>0}function Fs(r){let{config:e,launcher:n,host:t,kind:i}=r,s=f(e,t,i);if(!s)return!1;let a;try{a=t.platform==="win32"?V(s.definition):k(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===se(e,i,s,n);if(t.platform!=="darwin")return a===oe(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(y,"").replace(R,(c,m,O,ue)=>`${m}${o?`${h([o.launcher,...o.args])}
50
+ `:""}${ue}`)===ie(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function L(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function G(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new J("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function ie(r,e,n,t,i,s){let a=L(r,e),o=z(t,a.args,i),l={HOME:i.home,PATH:s,[zr]:n.label,...a.environment,...o.identity?{[Qt]:o.identity.app}:{}};return{identity:o.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
51
51
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
52
52
  <plist version="1.0">
53
53
  <dict>
@@ -55,7 +55,7 @@ ${O}`);if(!a)o=o.replace(y,"");else if(y.test(o))o=o.replace(y,(l,c,m)=>`${c}${d
55
55
  <string>${d(n.label)}</string>
56
56
  <key>AssociatedBundleIdentifiers</key>
57
57
  <array>
58
- <string>${Ln}</string>
58
+ <string>${Xn}</string>
59
59
  </array>
60
60
  <key>ProgramArguments</key>
61
61
  <array>
@@ -92,8 +92,8 @@ ${Object.entries(l).map(([c,m])=>` <key>${c}</key>
92
92
  Description=${a.description}
93
93
 
94
94
  [Service]
95
- ExecStart=${[t,...a.args].map((o)=>q(o,!0)).join(" ")}
96
- Environment=${[`HOME=${i}`,`PATH=${s}`,`${Ir}=${n.label}`,...Object.entries(a.environment).map(([o,l])=>`${o}=${l}`)].map((o)=>q(o)).join(" ")}
95
+ ExecStart=${[t,...a.args].map((o)=>G(o,!0)).join(" ")}
96
+ Environment=${[`HOME=${i}`,`PATH=${s}`,`${zr}=${n.label}`,...Object.entries(a.environment).map(([o,l])=>`${o}=${l}`)].map((o)=>G(o)).join(" ")}
97
97
  Restart=on-failure
98
98
  RestartSec=10
99
99
  TimeoutStopSec=${Math.ceil(r.shutdownGraceMs/1000)+10}
@@ -101,5 +101,5 @@ UMask=0077
101
101
 
102
102
  [Install]
103
103
  WantedBy=default.target
104
- `}function se(r,e,n,t){let i=L(r,e);return B({description:i.description,schedule:"logon",script:U({name:n.label,program:t,args:i.args,environment:{[Ir]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function ae(r,e,n){e.command("powershell.exe",T(r.label,{tree:n,keepWrapper:!n}))}function b(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",T(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function A(r,e){$e(Ae(r),{recursive:!0,mode:448});let n=`${r}.${Se()}.tmp`;try{We(n,e,{mode:384,flag:"wx"}),we(n,384),ye(n,r)}finally{u(n,{force:!0})}}function S(r){if(typeof r.uid!=="number"||!Number.isSafeInteger(r.uid)||r.uid<=0)throw new K("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${r.uid}`}function ms(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=te(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?N:W);if(!o)throw new K(ee);if(t.platform==="darwin")S(t);if(t.platform==="linux"&&t.command("systemctl",["--user","show-environment"])!==0)throw new K("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let l=t.platform==="darwin"?ie(e,i,o,n,t,r.path):null;if(A(o.definition,l?l.plist:t.platform==="win32"?V(se(e,i,o,n)):oe(e,i,o,n,t.home,r.path)),le(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ie};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function le(r,e,n,t){if(e.platform==="darwin"){let a=S(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(ce(r,n,e)){if(t)u(t.definition,{force:!0});return}if(u(n.definition,{force:!0}),t)e.command("/bin/launchctl",["bootstrap",a,t.definition]);throw new K("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}if(e.platform==="win32"){if(t)b(t,e,!0);if(e.command("schtasks",F(n.label,n.definition))===0){if(ae(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw b(n,e,!0),new K("Could not start the background service (schtasks failed).")}let i=`${n.label}.service`,s=t?`${t.label}.service`:null;if(e.command("systemctl",["--user","daemon-reload"])!==0||s!==null&&e.command("systemctl",["--user","disable","--now",s])!==0||e.command("systemctl",["--user","enable",i])!==0||e.command("systemctl",["--user","restart",i])!==0){if(e.command("systemctl",["--user","disable",i]),u(n.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),s)e.command("systemctl",["--user","enable","--now",s]);throw new K("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(t)u(t.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}function ce(r,e,n){let t=S(n);n.command("/bin/launchctl",["bootout",`${t}/${e.label}`]);let i=(Math.ceil(r.shutdownGraceMs/1000)+10)*1000;for(let s=0,a=100;;a=Math.min(a*2,2000)){if(n.command("/bin/launchctl",["bootstrap",t,e.definition])===0)return!0;if(s>=i)return!1;n.sleep(a),s+=a}}function Dr(r,e,n){let t=qe(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Pe(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return A(s.definition,k(t.definition,"utf8").replaceAll(t.label,s.label)),le(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")ae(t,e,!i),o=e.command("schtasks",["/Run","/TN",t.label])===0;else if(a)o=e.command("/bin/launchctl",["kickstart","-k",`${S(e)}/${t.label}`])===0;else if(e.platform==="darwin")o=ce(r,t,e);else e.command("systemctl",["--user","enable",`${t.label}.service`]),o=e.command("systemctl",["--user","restart",`${t.label}.service`])===0;if(!o)throw new K(`Could not restart the background service ${t.label}.`,"worker_service_restart_failed");if(s&&t.label===s.label)Oo(r,e,n);return t}function gs(r,e,n,t){let i=qe(r,n,t),s=f(e,n,t);if(n.platform!=="darwin"||!i||!s)return;let a=`<string>${d(i.logs)}</string>`,o=k(i.definition,"utf8");if(o.includes(a))A(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function _s(r,e,n="serve"){let t=ne(r,e,n);for(let i of t){if(e.platform==="win32"){b(i,e,e.insideService?.(i.label,!1)!==!0);continue}if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);u(i.definition,{force:!0});continue}e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}return t[0]??null}
105
- export{Ir,be,K,Cn,ps,Wi,hs,qe,Oo,An,fs,ms,Dr,gs,_s};
104
+ `}function se(r,e,n,t){let i=L(r,e);return U({description:i.description,schedule:"logon",script:K({name:n.label,program:t,args:i.args,environment:{[zr]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function ae(r,e,n){e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!n}))}function b(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function A(r,e){$e(We(r),{recursive:!0,mode:448});let n=`${r}.${Se()}.tmp`;try{be(n,e,{mode:384,flag:"wx"}),we(n,384),ye(n,r)}finally{u(n,{force:!0})}}function S(r){if(typeof r.uid!=="number"||!Number.isSafeInteger(r.uid)||r.uid<=0)throw new J("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${r.uid}`}function js(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=te(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?N:W);if(!o)throw new J(ee);if(t.platform==="darwin")S(t);if(t.platform==="linux"&&t.command("systemctl",["--user","show-environment"])!==0)throw new J("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let l=t.platform==="darwin"?ie(e,i,o,n,t,r.path):null;if(A(o.definition,l?l.plist:t.platform==="win32"?B(se(e,i,o,n)):oe(e,i,o,n,t.home,r.path)),le(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ae};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function le(r,e,n,t){if(e.platform==="darwin"){let a=S(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(ce(r,n,e)){if(t)u(t.definition,{force:!0});return}if(u(n.definition,{force:!0}),t)e.command("/bin/launchctl",["bootstrap",a,t.definition]);throw new J("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}if(e.platform==="win32"){if(t)b(t,e,!0);if(e.command("schtasks",j(n.label,n.definition))===0){if(ae(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw b(n,e,!0),new J("Could not start the background service (schtasks failed).")}let i=`${n.label}.service`,s=t?`${t.label}.service`:null;if(e.command("systemctl",["--user","daemon-reload"])!==0||s!==null&&e.command("systemctl",["--user","disable","--now",s])!==0||e.command("systemctl",["--user","enable",i])!==0||e.command("systemctl",["--user","restart",i])!==0){if(e.command("systemctl",["--user","disable",i]),u(n.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),s)e.command("systemctl",["--user","enable","--now",s]);throw new J("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(t)u(t.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}function ce(r,e,n){let t=S(n);n.command("/bin/launchctl",["bootout",`${t}/${e.label}`]);let i=(Math.ceil(r.shutdownGraceMs/1000)+10)*1000;for(let s=0,a=100;;a=Math.min(a*2,2000)){if(n.command("/bin/launchctl",["bootstrap",t,e.definition])===0)return!0;if(s>=i)return!1;n.sleep(a),s+=a}}function qr(r,e,n){let t=Xe(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Pe(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return A(s.definition,k(t.definition,"utf8").replaceAll(t.label,s.label)),le(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")ae(t,e,!i),o=e.command("schtasks",["/Run","/TN",t.label])===0;else if(a)o=e.command("/bin/launchctl",["kickstart","-k",`${S(e)}/${t.label}`])===0;else if(e.platform==="darwin")o=ce(r,t,e);else e.command("systemctl",["--user","enable",`${t.label}.service`]),o=e.command("systemctl",["--user","restart",`${t.label}.service`])===0;if(!o)throw new J(`Could not restart the background service ${t.label}.`,"worker_service_restart_failed");if(s&&t.label===s.label)Yo(r,e,n);return t}function Us(r,e,n,t){let i=Xe(r,n,t),s=f(e,n,t);if(n.platform!=="darwin"||!i||!s)return;let a=`<string>${d(i.logs)}</string>`,o=k(i.definition,"utf8");if(o.includes(a))A(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function Hs(r,e,n="serve"){let t=ne(r,e,n);for(let i of t){if(e.platform==="win32"){b(i,e,e.insideService?.(i.label,!1)!==!0);continue}if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);u(i.definition,{force:!0});continue}e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}return t[0]??null}
105
+ export{zr,Ee,J,Hn,$s,ho,Bs,Xe,Yo,zn,Fs,js,qr,Us,Hs};