@reason-machines/cli-linux-x64 0.2.521 → 0.2.523

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 (106) hide show
  1. package/bin/reason +2 -2
  2. package/bin/vm-hands/api-credentials-e57krknv.js +2 -0
  3. package/bin/vm-hands/api-jec93cnj.js +2 -0
  4. package/bin/vm-hands/connect-cli-yzezydnr.js +2 -0
  5. package/bin/vm-hands/credentials-md79hkqh.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-hzgdnyx2.js +2 -0
  7. package/bin/vm-hands/desktop-account-gm7m5bwr.js +2 -0
  8. package/bin/vm-hands/{fsevents-sw63c1nr.js → fsevents-fev1pxw2.js} +1 -1
  9. package/bin/vm-hands/grok-dock-browser-pzw59wnd.png +0 -0
  10. package/bin/vm-hands/grok-dock-files-eckq444x.png +0 -0
  11. package/bin/vm-hands/grok-dock-terminal-hcpz3e43.png +0 -0
  12. package/bin/vm-hands/grok-wallpaper-71zwn2pj.jpg +0 -0
  13. package/bin/vm-hands/{hands-worker-source-h0qmr1jt.js → hands-worker-source-hzkacxxz.js} +1 -1
  14. package/bin/vm-hands/{index-j4gb3cze.js → index-gmsadq51.js} +4 -4
  15. package/bin/vm-hands/install-receipt-qtwtzafq.js +2 -0
  16. package/bin/vm-hands/local-automation-rmedb06z.js +2 -0
  17. package/bin/vm-hands/local-capabilities-mvnm7kc8.js +2 -0
  18. package/bin/vm-hands/local-desktop-users-qdpbfh6s.js +2 -0
  19. package/bin/vm-hands/local-display-mac-4654wqzs.js +2 -0
  20. package/bin/vm-hands/local-display-session-e662q50r.js +2 -0
  21. package/bin/vm-hands/local-display-video-0pb76z1k.js +2 -0
  22. package/bin/vm-hands/local-managed-process-s90s65vr.js +2 -0
  23. package/bin/vm-hands/local-pty-session-s60ca00y.js +2 -0
  24. package/bin/vm-hands/managed-runtime-cc93epas.js +2 -0
  25. package/bin/vm-hands/network-contract-5wc6wbn2.js +2 -0
  26. package/bin/vm-hands/package-way7qesn.js +2 -0
  27. package/bin/vm-hands/permissions-tjhfq2b6.js +2 -0
  28. package/bin/vm-hands/{reason-hands-protocol-6fxcbhzd.js → reason-hands-protocol-zffy7kc8.js} +1 -1
  29. package/bin/vm-hands/serve-service-qhsnbxmy.js +2 -0
  30. package/bin/vm-hands/{status-qvgxpr8f.js → status-h7fq0xa9.js} +1 -1
  31. package/bin/vm-hands/version-whw9wgya.js +2 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-4wgq9vfr.js → vm-hands-entry-lite-06mdg33e.js} +5 -5
  33. package/bin/vm-hands/{vm-hands-entry-lite-d7kdqz8w.js → vm-hands-entry-lite-06mges91.js} +4 -4
  34. package/bin/vm-hands/{vm-hands-entry-lite-gj1ce9nc.js → vm-hands-entry-lite-0bp8kbe3.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-wzq3qsh1.js → vm-hands-entry-lite-0tavq3p4.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-qz74j563.js → vm-hands-entry-lite-1kt82jes.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-spb0z2m4.js → vm-hands-entry-lite-3a8ra8ah.js} +4 -4
  38. package/bin/vm-hands/{vm-hands-entry-lite-70x16hkx.js → vm-hands-entry-lite-4cdn822w.js} +3 -3
  39. package/bin/vm-hands/{vm-hands-entry-lite-qxeegp2n.js → vm-hands-entry-lite-5wsygx6n.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-ydgedg8n.js → vm-hands-entry-lite-88yjxxvf.js} +5 -5
  41. package/bin/vm-hands/{vm-hands-entry-lite-148nz8be.js → vm-hands-entry-lite-9x81cr3a.js} +3 -3
  42. package/bin/vm-hands/{vm-hands-entry-lite-fcvf8md1.js → vm-hands-entry-lite-a3p6xz53.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-dcrz19xf.js → vm-hands-entry-lite-a6w60nv9.js} +3 -3
  44. package/bin/vm-hands/{vm-hands-entry-lite-25yzr6m8.js → vm-hands-entry-lite-baxqey3h.js} +42 -42
  45. package/bin/vm-hands/{vm-hands-entry-lite-wx1fmrbs.js → vm-hands-entry-lite-bvqwsd3b.js} +3 -3
  46. package/bin/vm-hands/{vm-hands-entry-lite-fgppp6x9.js → vm-hands-entry-lite-c0t5xpzh.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-ymqb2927.js → vm-hands-entry-lite-c4959xva.js} +2 -2
  48. package/bin/vm-hands/vm-hands-entry-lite-f8ts9y2q.js +3 -0
  49. package/bin/vm-hands/vm-hands-entry-lite-ghva8qrf.js +2 -0
  50. package/bin/vm-hands/{vm-hands-entry-lite-x9qp374y.js → vm-hands-entry-lite-h33trj58.js} +7 -7
  51. package/bin/vm-hands/{vm-hands-entry-lite-0sh835na.js → vm-hands-entry-lite-haws181e.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-gh0yjzye.js → vm-hands-entry-lite-hc11hecd.js} +1 -1
  53. package/bin/vm-hands/{vm-hands-entry-lite-cwsjrxqj.js → vm-hands-entry-lite-j1qppwnx.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-v0zva5nj.js → vm-hands-entry-lite-krnvgf71.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-90y6pf98.js → vm-hands-entry-lite-kwmjn9y3.js} +3 -3
  56. package/bin/vm-hands/{vm-hands-entry-lite-mma9qt5r.js → vm-hands-entry-lite-mfvtp7py.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-3f6bayc8.js → vm-hands-entry-lite-mxyry9da.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-19dpjtpb.js → vm-hands-entry-lite-n3274tws.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-gtnpk3sc.js → vm-hands-entry-lite-nb0n1vy1.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-423rvptb.js → vm-hands-entry-lite-nercg1yz.js} +19 -19
  61. package/bin/vm-hands/{vm-hands-entry-lite-zc8fsn2e.js → vm-hands-entry-lite-pzj5s203.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-svd5v9dr.js → vm-hands-entry-lite-q1yvw4xz.js} +1 -1
  63. package/bin/vm-hands/{vm-hands-entry-lite-1nrxnm0y.js → vm-hands-entry-lite-sfmeafdm.js} +9 -9
  64. package/bin/vm-hands/{vm-hands-entry-lite-5eg3tgdq.js → vm-hands-entry-lite-t82dzcxb.js} +2 -2
  65. package/bin/vm-hands/{vm-hands-entry-lite-q80xmhrx.js → vm-hands-entry-lite-tash5m18.js} +14 -14
  66. package/bin/vm-hands/{vm-hands-entry-lite-ndhspax6.js → vm-hands-entry-lite-tns12zqc.js} +2 -2
  67. package/bin/vm-hands/{vm-hands-entry-lite-wh0xwp85.js → vm-hands-entry-lite-wc730qz7.js} +3 -3
  68. package/bin/vm-hands/{vm-hands-entry-lite-5np5k3wb.js → vm-hands-entry-lite-wfc0agnt.js} +3 -3
  69. package/bin/vm-hands/{vm-hands-entry-lite-zk6hbpa3.js → vm-hands-entry-lite-xjpb3g9t.js} +3 -3
  70. package/bin/vm-hands/vm-hands-entry-lite-z35nbedn.js +150 -0
  71. package/bin/vm-hands/{vm-hands-entry-lite-1jdt74g0.js → vm-hands-entry-lite-z4jrseer.js} +1 -1
  72. package/bin/vm-hands/{vm-hands-entry-lite-g6fr9e30.js → vm-hands-entry-lite-zrs8h4rf.js} +5 -5
  73. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  74. package/bin/vm-hands/{vm-hands-executor-v24y415a.js → vm-hands-executor-5n4k8t53.js} +3 -3
  75. package/bin/vm-hands/vm-hands-op-runner-mzyesbyf.js +2 -0
  76. package/bin/vm-hands/{vm-hands-runtime-gsjba3vg.js → vm-hands-runtime-zhsw99cm.js} +3 -3
  77. package/bin/vm-hands/worker-preview-readiness-8ftb3nbw.js +2 -0
  78. package/bin/vm-hands/worker-sandbox-k0vx97tx.js +2 -0
  79. package/package.json +1 -1
  80. package/bin/vm-hands/api-693jj5gc.js +0 -2
  81. package/bin/vm-hands/api-credentials-jed7tp30.js +0 -2
  82. package/bin/vm-hands/connect-cli-wstfzzds.js +0 -2
  83. package/bin/vm-hands/credentials-yf556ykn.js +0 -2
  84. package/bin/vm-hands/custom-endpoint-device-vbct7bj9.js +0 -2
  85. package/bin/vm-hands/desktop-account-j6fjngt1.js +0 -2
  86. package/bin/vm-hands/install-receipt-gwv1qv2m.js +0 -2
  87. package/bin/vm-hands/local-automation-06wtwxjp.js +0 -2
  88. package/bin/vm-hands/local-capabilities-wj42bc6s.js +0 -2
  89. package/bin/vm-hands/local-desktop-users-4hc6jysa.js +0 -2
  90. package/bin/vm-hands/local-display-mac-fjeyb4h9.js +0 -2
  91. package/bin/vm-hands/local-display-session-n5pv37tf.js +0 -2
  92. package/bin/vm-hands/local-display-video-kdybca06.js +0 -2
  93. package/bin/vm-hands/local-managed-process-c890ref6.js +0 -2
  94. package/bin/vm-hands/local-pty-session-4h4ekakp.js +0 -2
  95. package/bin/vm-hands/managed-runtime-ar9pn1mp.js +0 -2
  96. package/bin/vm-hands/network-contract-4wew8f21.js +0 -2
  97. package/bin/vm-hands/package-sng72tm1.js +0 -2
  98. package/bin/vm-hands/permissions-t03k97w0.js +0 -2
  99. package/bin/vm-hands/serve-service-nrb9h8af.js +0 -2
  100. package/bin/vm-hands/version-0r7g0x44.js +0 -2
  101. package/bin/vm-hands/vm-hands-entry-lite-60pnam39.js +0 -3
  102. package/bin/vm-hands/vm-hands-entry-lite-etg5ft0x.js +0 -2
  103. package/bin/vm-hands/vm-hands-entry-lite-y5b73xe5.js +0 -128
  104. package/bin/vm-hands/vm-hands-op-runner-7derp3tq.js +0 -2
  105. package/bin/vm-hands/worker-preview-readiness-ye6cvg3k.js +0 -2
  106. package/bin/vm-hands/worker-sandbox-j6cmex8e.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{We,fo,F,Ve,Ut,Rr,x}from"./vm-hands-entry-lite-4wgq9vfr.js";import{K}from"./vm-hands-entry-lite-wx1fmrbs.js";import{pt}from"./vm-hands-entry-lite-1nrxnm0y.js";import{gt}from"./vm-hands-entry-lite-g6fr9e30.js";import{Or}from"./vm-hands-entry-lite-3f6bayc8.js";import{Pt,ji}from"./vm-hands-entry-lite-148nz8be.js";import{G,qe}from"./vm-hands-entry-lite-y5b73xe5.js";import{xe,Kn}from"./vm-hands-entry-lite-x9qp374y.js";import{St}from"./vm-hands-entry-lite-ydgedg8n.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-qz74j563.js";import{spawn as R,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as M,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as U,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as dt,statSync as mt,writeFileSync as ft}from"fs";import{connect as ht}from"net";import{tmpdir as L,userInfo as we}from"os";import{basename as le,delimiter as wt,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
2
+ import{We,mo,F,Ve,Ut,Tr,x}from"./vm-hands-entry-lite-06mdg33e.js";import{K}from"./vm-hands-entry-lite-bvqwsd3b.js";import{pt}from"./vm-hands-entry-lite-sfmeafdm.js";import{gt}from"./vm-hands-entry-lite-zrs8h4rf.js";import{Or}from"./vm-hands-entry-lite-mxyry9da.js";import{Pt,Ui}from"./vm-hands-entry-lite-9x81cr3a.js";import{G,qe}from"./vm-hands-entry-lite-z35nbedn.js";import{xe,Jn}from"./vm-hands-entry-lite-h33trj58.js";import{St}from"./vm-hands-entry-lite-88yjxxvf.js";import{a}from"./vm-hands-entry-lite-haws181e.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-1kt82jes.js";import{spawn as R,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as M,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as U,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as dt,statSync as mt,writeFileSync as ft}from"fs";import{connect as ht}from"net";import{tmpdir as L,userInfo as we}from"os";import{basename as le,delimiter as wt,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";
@@ -856,5 +856,5 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
856
856
  }
857
857
  `;import{spawn as Te}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var De="__desktop-call",Me="/usr/bin/setpriv",Ue=27262976,Le=8192,$e=2000;function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],De]}function Ge(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Bt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{Ge(e)}catch{}let s=n.command??Fe();return new Promise((i,u)=>{let c=(n.spawnProcess??Te)(Me,[`--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,w,h=(y)=>{try{process.kill(-c.pid,y)}catch{c.kill(y)}},I=(y)=>{p??=y,h("SIGTERM"),w??=setTimeout(()=>h("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let _=(y)=>{if(g)return;g=!0,clearTimeout(w),t.removeEventListener("abort",S),y()};if(c.stdout.on("data",(y)=>{if(m+=y.byteLength,m>Ue)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(y)}),c.stderr.setEncoding("utf8").on("data",(y)=>{l=(l+y).slice(-Le)}),c.stdin.on("error",()=>{}),c.once("error",()=>_(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(y,Ee)=>_(()=>{if(p)return u(p);let b=Be(Buffer.concat(d).toString("utf8"));if(W(b)&&b.ok===!0&&W(b.result))return i(b.result);let O=W(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 ${y??Ee}${O?"":" with no reply"}`,Y=l.trim().split(`
858
858
  `).at(-1)?.slice(-300)??"";if(!O||O.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
859
- `);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 Q(e,o,t,n={}){let s=await Bt(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 He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Kn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>pt(e,o),tile:Or,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(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 ne(o,i,n,s)}}var rt={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 re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(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 se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});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&&!te){te=!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 ne(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 oe(fo,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(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 oe(u,o,s),re({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 ie(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 ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,_t=18874368,yt=8192,bt=65536,xt=55000,kt=60000,Rt=4,It=40000,vt=/^[0-9a-f-]{36}$/,ue=z,Ot=ge();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 _e(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>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!vt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var At="__computer-use";function Fs(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(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 Et(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 Ct(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 Tt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Dt(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"&&Tt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(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=Dt(await Et(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(mt(m).size>Nt)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 Mt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Mt(e.nativeHost,o,{socketDir:Ct(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ut){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(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.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 be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((w)=>d(w)===l),instance:p,socket:g}))}async function $t(e,o,t=a(),n=Ut){let s=(await Lt(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 pe(e){return new Promise((o)=>{let t=ht({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 ke(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 q=new Map;function H(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function Wt(e,o){if(await pe(e))return;if(dt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(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");ce(p,{recursive:!0,mode:448});let g=Rr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",w,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");G(l),st(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");ce(p,{recursive:!0,mode:448});let g=Rr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...w,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!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 js(e){await ve(e,!0)}function Us(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!qt(e.automation))return e.automation;if(!Ft(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function qt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function Ft(e){let o;try{o=ut(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 ve(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().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,...Gt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:At};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(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",()=>Wt(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Gt(){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(wt)}}async function Ht(e,o,t){let n=we().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 $t(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;ft(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(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,w=(_)=>{if(p??=_,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")}},h=(_)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),_()},I=setTimeout(()=>w(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>w(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>_t)w(new r("automation_output_too_large","Reason automation output is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(_)=>h(()=>{if(p)u(p);else i({code:_??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=Rt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Hs(e,o){let t=_e({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 Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:Ot,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Tn(e,o={}){let t=_e(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 fe(await se({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=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await ji(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),w;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),w=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)w=await(o.delegate??Q)(g,t.call,e.signal);else w=await Ae(s,t.call,e.signal,o)}finally{p()}if(i)w=await ie({runId:e.runId,call:t.call,identity:u,output:w,signal:e.signal},c);return fe(w,e.runId,n)}
860
- export{Bt,Pn,Fs,js,Us,Hs,Tn};
859
+ `);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 Q(e,o,t,n={}){let s=await Bt(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 He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>pt(e,o),tile:Or,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(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 ne(o,i,n,s)}}var rt={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 re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(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 se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});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&&!te){te=!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 ne(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 oe(mo,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(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 oe(u,o,s),re({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 ie(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 ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,_t=18874368,yt=8192,bt=65536,xt=55000,kt=60000,Rt=4,It=40000,vt=/^[0-9a-f-]{36}$/,ue=z,Ot=ge();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 _e(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>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!vt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var At="__computer-use";function Hs(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(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 Et(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 Ct(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 Tt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Dt(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"&&Tt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(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=Dt(await Et(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(mt(m).size>Nt)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 Mt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Mt(e.nativeHost,o,{socketDir:Ct(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ut){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(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.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 be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((w)=>d(w)===l),instance:p,socket:g}))}async function $t(e,o,t=a(),n=Ut){let s=(await Lt(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 pe(e){return new Promise((o)=>{let t=ht({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 ke(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 q=new Map;function H(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function Wt(e,o){if(await pe(e))return;if(dt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(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");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",w,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");G(l),st(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");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...w,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!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 zs(e){await ve(e,!0)}function qs(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!qt(e.automation))return e.automation;if(!Ft(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function qt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function Ft(e){let o;try{o=ut(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 ve(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().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,...Gt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:At};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(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",()=>Wt(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Gt(){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(wt)}}async function Ht(e,o,t){let n=we().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 $t(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;ft(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(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,w=(_)=>{if(p??=_,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")}},h=(_)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),_()},I=setTimeout(()=>w(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>w(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>_t)w(new r("automation_output_too_large","Reason automation output is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(_)=>h(()=>{if(p)u(p);else i({code:_??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=Rt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=_e({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 Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:Ot,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=_e(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 fe(await se({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=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Ui(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),w;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),w=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)w=await(o.delegate??Q)(g,t.call,e.signal);else w=await Ae(s,t.call,e.signal,o)}finally{p()}if(i)w=await ie({runId:e.runId,call:t.call,identity:u,output:w,signal:e.signal},c);return fe(w,e.runId,n)}
860
+ export{Bt,Pn,Hs,zs,qs,Ws,Rn};
@@ -0,0 +1,150 @@
1
+ // @bun
2
+ import{Mn,$n,Ro,Wt}from"./vm-hands-entry-lite-sfmeafdm.js";import{Tn,Ve,go,On,In,Dn,Rr,x}from"./vm-hands-entry-lite-06mdg33e.js";import{Pt}from"./vm-hands-entry-lite-9x81cr3a.js";import{Nr}from"./vm-hands-entry-lite-5wsygx6n.js";import{j}from"./vm-hands-entry-lite-hc11hecd.js";import{a}from"./vm-hands-entry-lite-haws181e.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as oe,spawn as ae}from"child_process";import{randomBytes as ge}from"crypto";import{chmodSync as Me,existsSync as ce,lstatSync as Ce,mkdirSync as Ke,readFileSync as be,rmSync as xe,writeFileSync as T}from"fs";import{connect as Ie}from"net";import{join as P}from"path";var u=32,R=76;var W="./desktop-wallpaper-0pjhgyfk.jpg";var Y="./dock-browser-afp005mt.png";var v="./dock-files-rywdm96b.png";var Z="./dock-terminal-s41cj1jp.png";var H="./grok-wallpaper-71zwn2pj.jpg";var z="./grok-dock-browser-pzw59wnd.png";var V="./grok-dock-files-eckq444x.png";var ee="./grok-dock-terminal-hcpz3e43.png";var re=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
+ # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
+ # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
+ # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
6
+ import ctypes, sys
7
+ import gi
8
+ gi.require_version("GdkPixbuf", "2.0")
9
+ from gi.repository import GdkPixbuf
10
+ x = ctypes.cdll.LoadLibrary("libX11.so.6")
11
+ x.XOpenDisplay.restype = ctypes.c_void_p
12
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
13
+ d = x.XOpenDisplay(None)
14
+ if not d: sys.exit("no display")
15
+ for name, res, args in [
16
+ ("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
17
+ ("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
18
+ ("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
19
+ ("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
20
+ ("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
21
+ ("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
22
+ ("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
23
+ ("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
24
+ ("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
25
+ ("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
26
+ ("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
27
+ ("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
28
+ ("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
29
+ ("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
30
+ ("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
31
+ ("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
32
+ ]:
33
+ f = getattr(x, name); f.restype = res; f.argtypes = args
34
+ s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
35
+ w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
36
+ if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
37
+ # Scale to cover the screen, then crop the centre.
38
+ src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
39
+ k = max(w / src.get_width(), h / src.get_height())
40
+ sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
41
+ pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
42
+ if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
43
+ rgb, stride = pb.get_pixels(), pb.get_rowstride()
44
+ bgrx = bytearray(w * h * 4)
45
+ for y in range(h):
46
+ row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
47
+ bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
48
+ buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
49
+ pix = x.XCreatePixmap(d, root, w, h, 24)
50
+ img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
51
+ x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
52
+ ref = ctypes.c_ulong(pix)
53
+ for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
54
+ x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
55
+ x.XSetWindowBackgroundPixmap(d, root, pix)
56
+ x.XClearWindow(d, root)
57
+ x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
58
+ x.XCloseDisplay(d)
59
+ `;function Ne(e){return`<?xml version="1.0" encoding="UTF-8"?>
60
+ <openbox_config xmlns="http://openbox.org/3.4/rc">
61
+ <theme><keepBorder>no</keepBorder></theme>
62
+ <applications>
63
+ <!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
64
+ <application class="Chromium*">
65
+ <decor>no</decor>
66
+ <position force="yes"><x>${u}</x><y>${u}</y></position>
67
+ <size><width>${e.width-u*2}</width><height>${e.height-u-R}</height></size>
68
+ </application>
69
+ </applications>
70
+ </openbox_config>`}var Te=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
71
+ panel_items = L
72
+ panel_size = 100% 46
73
+ panel_margin = 0 10
74
+ panel_padding = 0 0 10
75
+ panel_position = bottom center horizontal
76
+ panel_shrink = 1
77
+ panel_background_id = 0
78
+ panel_layer = top
79
+ mouse_effects = 1
80
+ mouse_hover_icon_asb = 100 0 12
81
+ mouse_pressed_icon_asb = 100 0 -12
82
+
83
+ launcher_icon_size = 46
84
+ launcher_padding = 0 0 10
85
+ launcher_background_id = 0
86
+ launcher_tooltip = 1
87
+
88
+ launcher_item_app = /tmp/ara-chromium.desktop
89
+ launcher_item_app = /tmp/ara-terminal.desktop
90
+ launcher_item_app = /tmp/ara-files.desktop
91
+ `,te=32,Ae=`# Remote sandbox dock (grok look) \u2014 small launcher icons only, centred, no panel fill
92
+ panel_items = L
93
+ panel_size = 100% ${te+16}
94
+ panel_margin = 0 0
95
+ panel_padding = 0 0 8
96
+ panel_position = bottom center horizontal
97
+ panel_shrink = 1
98
+ panel_background_id = 0
99
+ panel_layer = top
100
+ mouse_effects = 1
101
+ mouse_hover_icon_asb = 100 0 10
102
+ mouse_pressed_icon_asb = 100 0 -10
103
+
104
+ launcher_icon_size = ${te}
105
+ launcher_padding = 0 0 8
106
+ launcher_background_id = 0
107
+ launcher_tooltip = 1
108
+
109
+ launcher_item_app = /tmp/ara-chromium.desktop
110
+ launcher_item_app = /tmp/ara-files.desktop
111
+ launcher_item_app = /tmp/ara-terminal.desktop
112
+ `,Le=`corner-radius = 12;
113
+ rounded-corners-exclude = [
114
+ "class_g = 'tint2'",
115
+ "window_type = 'dock'",
116
+ "window_type = 'desktop'"
117
+ ];
118
+ backend = "xrender";
119
+ shadow = false;
120
+ fading = false;
121
+ vsync = false;
122
+ inactive-opacity = 1.0;
123
+ active-opacity = 1.0;
124
+ `,_e="/tmp/ara-dock-browser.png",Oe=`[Desktop Entry]
125
+ Name=Chrome
126
+ Exec=chromium --no-sandbox %U
127
+ Icon=${_e}
128
+ Type=Application
129
+ Categories=Network;WebBrowser;
130
+ `,Be=`[Desktop Entry]
131
+ Name=Terminal
132
+ Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
133
+ Icon=/tmp/ara-dock-terminal.png
134
+ Type=Application
135
+ Categories=System;TerminalEmulator;
136
+ `,se=`[Desktop Entry]
137
+ Name=Files
138
+ Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
139
+ Icon=/tmp/ara-dock-files.png
140
+ Type=Application
141
+ Categories=System;FileManager;
142
+ `;var ne={"wallpaper.jpg":W,"dock-browser.png":Y,"dock-terminal.png":Z,"dock-files.png":v,"grok-wallpaper.jpg":H,"grok-dock-browser.png":z,"grok-dock-terminal.png":ee,"grok-dock-files.png":V},Je=re,we='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function pe(e){let t=(y)=>y.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),p=e.look==="grok",n=new Set(e.absent??[]),s=p&&n.has("files")&&e.filesViewerExec?e.filesViewerExec:null;if(s)n.delete("files");let i=(p?Ae:Te).split(`
143
+ `).filter((y)=>!(n.has("terminal")&&y.endsWith("/ara-terminal.desktop"))&&!(n.has("files")&&y.endsWith("/ara-files.desktop"))).join(`
144
+ `),o=(y)=>p?y.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):y,c=s?se.replace(/^Exec=.*$/m,`Exec=${s}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):se,l=p?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",b={"openbox/rc.xml":Ne(e.screen),"tint2/tint2rc":t(i),"picom/picom.conf":Le,...n.has("terminal")?{}:{"ara-terminal.desktop":t(o(Be))},...n.has("files")?{}:{"ara-files.desktop":t(o(c))},"ara-chromium.desktop":t(o(Oe)).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Je},q=[...N.slice(0,3),we,`[ ! -f "$ROOT/${l}" ] || set_wallpaper "$ROOT/${l}" "$ROOT/ara-set-root-wallpaper.py" || true`,'if alive tint2 && ! cmp -s "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied"; then read -r pid _ <"$ROOT/tint2.pid"; kill -USR1 "$pid" 2>/dev/null || true; fi','cp "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied" 2>/dev/null || true',...N.slice(3)];return{files:b,start:q}}var N=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var me=43200000,h=":99",Fe=60000,Q=15000,A={width:1280,height:800},Ge=/^[A-Za-z0-9._:-]{1,160}$/;function ke(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var je=["video","viewer","viewer_same_network","viewer_network","look"];function Ue(e,t=Date.now()){let p=["relay_url","session_id","expires_at"];if(!ke(e)||p.some((l)=>!(l in e))||Object.keys(e).some((l)=>!p.includes(l)&&!je.includes(l)))throw new r("invalid_display_request","Reason desktop request is malformed.");let n="video"in e?Ro(e.video):void 0,s="viewer"in e?Mn(e.viewer):null,i="look"in e?$n(e.look):null;if(n===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let o=null;try{o=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!o||o.protocol!=="wss:"&&o.protocol!=="ws:"||o.username||o.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!Ge.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let c=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(c)||c<=t)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(c,t+me)).toISOString(),...n?{video:n}:{},...s?{viewer:s}:{},...n&&e.viewer_same_network===!0?{viewer_same_network:!0}:{},...i?{look:i}:{}}}function Ft(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function Vs(){if(process.platform==="win32")return Ft()&&await Rr();if(process.platform!=="darwin")return Ft();return await Rr()}function G(e){Ke(e,{recursive:!0,mode:448});let t=Ce(e);if(!t.isDirectory()||t.isSymbolicLink()||process.getuid&&t.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");Me(e,448)}function We(e,t){let p=(s)=>{let i=Buffer.alloc(2);return i.writeUInt16BE(s.length),Buffer.concat([i,s])},n=Buffer.from([255,255]);return Buffer.concat([n,p(Buffer.alloc(0)),p(Buffer.from(e)),p(Buffer.from("MIT-MAGIC-COOKIE-1")),p(t)])}function d(e,t,p=2000){return new Promise((n)=>{let s=Ie(e),i="",o=(c)=>{s.destroy(),n(c)};s.setTimeout(p,()=>o(!1)),s.once("error",()=>o(!1)),s.once("close",()=>o(!1)),s.once("connect",()=>{if(!t)o(!0)}),s.on("data",(c)=>{if(i+=c.toString("latin1"),i.length>=4)o(i.startsWith("RFB "))})})}async function C(e,t){let p=Date.now()+t;while(Date.now()<p){if(await e())return!0;await new Promise((n)=>setTimeout(n,100))}return!1}function L(e,t,p){return new Promise((n)=>{let s=ae(e,t,{detached:!0,stdio:"ignore",env:p});s.once("error",()=>n(-1)),s.once("exit",(i)=>n(i)),s.unref(),setTimeout(()=>n(null),Q).unref()})}var M=null;function qe(e=a()){return M??=Ye(e).finally(()=>{M=null}),M}async function Ye(e){let t=x({home:e});if(!t?.xvfb||!t.x11vnc||!t.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");Pt({root:t.root,automation:t.automation,extensionDir:t.extensionDir});let p=P(t.root,"display");G(p);let n=await Ze(e,p,t.x11vnc);if(n)return n;let s={display:h,xauthority:P(p,"Xauthority"),rfbSocket:P(p,"rfb.sock")},i=P(p,"pulse"),o=(async()=>{try{G(i)}catch{return null}return await go(i,t.pulseaudio)})();G(P(p,"home"));let c=K(p,s,t.pulseaudio),l=async()=>({...s,sound:await o});if(await d({path:s.rfbSocket},!0))return De(P(p,"theme"),N,c),await l();if(!ce(s.xauthority))T(s.xauthority,We(h.slice(1),ge(16)),{mode:384,flag:"wx"});let b=I(P(p,"theme"),s.display,A,e),q={path:`/tmp/.X11-unix/X${h.slice(1)}`};if(!await d(q,!1)){let y=`${A.width}x${A.height}`;if(t.xvnc)xe(s.rfbSocket,{force:!0}),L(t.xvnc,[s.display,"-geometry",y,"-depth","24","-nolisten","tcp","-auth",s.xauthority,"-rfbport","-1","-rfbunixpath",s.rfbSocket,"-SecurityTypes","None","-UseBlacklist=0","-AlwaysShared","-desktop","Reason"],c);else L(t.xvfb,[s.display,"-screen","0",`${y}x24`,"-nolisten","tcp","-auth",s.xauthority],c);if(!await C(()=>d(q,!1),Q)||t.xvnc&&!await C(()=>d({path:s.rfbSocket},!0),Q))throw new r("display_unavailable","Reason could not start the virtual display.");L(t.openbox,["--config-file",b.openboxConfig],c)}if(await m(b,c),!await le(t.x11vnc,s,p,"x11vnc.log",c))throw new r("display_unavailable","Reason could not start the desktop server.");return await l()}function K(e,t,p){let n={HOME:P(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:t.display,XAUTHORITY:t.xauthority};if(p)n.PULSE_SERVER=Ve(Tn(P(e,"pulse")));return n}async function le(e,t,p,n,s){if(await d({path:t.rfbSocket},!0))return!0;xe(t.rfbSocket,{force:!0});let i=await L(e,["-display",t.display,"-auth",t.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",t.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",P(p,n)],s);if(i!==null&&i!==0)return!1;return await C(()=>d({path:t.rfbSocket},!0),Q)}async function ve(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],t=(p)=>Object.fromEntries(e.flatMap((n)=>p[n]?[[n,p[n]]]:[]));if(process.env.DISPLAY)return t(process.env);try{let p=await new Promise((n,s)=>oe("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(i,o)=>i?s(i):n(o)));return t(Object.fromEntries(p.split(`
145
+ `).flatMap((n)=>{let s=n.indexOf("=");return s>0?[[n.slice(0,s),n.slice(s+1)]]:[]})))}catch{return{}}}var ie=new Set;async function Ze(e,t,p){let n=await ve(),s=/^:(\d+)(?:\.\d+)?$/.exec(n.DISPLAY??"")?.[1];if(!s||`:${s}`===h||n.WAYLAND_DISPLAY||n.XDG_SESSION_TYPE==="wayland")return null;let i={display:`:${s}`,xauthority:n.XAUTHORITY??P(e,".Xauthority"),rfbSocket:P(t,`rfb-${s}.sock`)},o=`${i.display} ${i.xauthority}`;if(ie.has(o)||!await d({path:`/tmp/.X11-unix/X${s}`},!1))return null;let c={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:i.display,XAUTHORITY:i.xauthority};if(await le(p,i,t,`x11vnc-${s}.log`,c))return{...i,sound:null};return ie.add(o),process.stderr.write(`Reason worker: your screen ${i.display} could not be served; using the virtual desktop
146
+ `),null}var Pe="look";function ye(e){try{return $n(be(P(e,Pe),"utf8").trim())??"reason"}catch{return"reason"}}function I(e,t,p,n,s=ye(e)){let i=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,o=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!ce(`/usr/bin/${b}`)).map(([b])=>b),c=`${i.replace(/ %U$/,"")} --app=file://${P(n,".reason","workspace")}/`,l=pe({root:e,display:t,screen:p,browserExec:i,absent:o,look:s,filesViewerExec:c});for(let b of["","openbox","tint2","picom"])G(P(e,b));T(P(e,Pe),`${s}
147
+ `,{mode:384});for(let[b,q]of Object.entries(l.files))T(P(e,b),q,{mode:384});for(let[b,q]of Object.entries(ne))T(P(e,`ara-${b}`),be(q),{mode:384});return{root:e,openboxConfig:P(e,"openbox","rc.xml"),start:l.start}}function m(e,t){return De(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],t)}function De(e,t,p){let n=[`ROOT=${JSON.stringify(e)}`,...t].join(`
148
+ `);return new Promise((s)=>{let i=ae("/bin/sh",["-c",n],{stdio:"ignore",env:{...p,PATH:"/usr/bin:/bin"}}),o=setTimeout(()=>{i.kill(),s()},Q);i.once("error",()=>{clearTimeout(o),s()}),i.once("exit",()=>{clearTimeout(o),s()})})}var He=2073600,ze=320;function er(e,t){let p=Math.min(1,Math.sqrt(He/(e.width*e.height))),n=(s,i)=>Math.min(Math.floor(i/8)*8,Math.max(ze,Math.round(s*p/8)*8));return{width:n(e.width,t.width),height:n(e.height,t.height)}}function F(e,t,p){return new Promise((n)=>oe(e,t,{env:p,encoding:"utf8",timeout:5000},(s,i)=>n(s?null:i)))}function fe(e){let t=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),p=e.split(`
149
+ `),n=p.findIndex((i)=>/^\S+ connected/.test(i));if(!t||n<0)return null;let s=[];for(let i of p.slice(n+1)){let o=/^\s+(\d+x\d+)\s/.exec(i);if(!o)break;s.push(o[1])}return{current:{width:Number(t[1]),height:Number(t[2])},maximum:{width:Number(t[3]),height:Number(t[4])},output:p[n].split(" ")[0],modes:s}}async function rr(e,t,p){if(e.display!==h)return null;let n={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},s=(l)=>F("xrandr",l,n),i=fe(await s(["--query"])??"");if(!i||i.maximum.width<=i.current.width&&i.maximum.height<=i.current.height)return null;let o=er(t,i.maximum);if(o.width===i.current.width&&o.height===i.current.height)return{size:o,changed:!1};let c=`${o.width}x${o.height}`;if(!i.modes.includes(c)){if(await s(["--newmode",c,"60",...[o.width,o.width,o.width,o.width,o.height,o.height,o.height,o.height].map(String)]),await s(["--addmode",i.output,c])===null)return null}return p(),await s(["--output",i.output,"--mode",c])===null?null:{size:o,changed:!0}}async function tr(e,t){let p=a(),n=x({home:p});if(!n)return;let s=P(n.root,"display"),i=K(s,e,n.pulseaudio);await m(I(P(s,"theme"),e.display,t,p),i);let o=t.width-u*2,c=t.height-u-R;await F("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(o),String(c),"windowmove","%@",String(u),String(u)],{...i,PATH:"/usr/bin:/bin"})}var _=Promise.resolve();function sr(e,t,p=()=>{}){let n=_.then(()=>rr(e,t,p));return _=n.then((s)=>s?.changed?tr(e,s.size):void 0).catch(()=>{}),n.then((s)=>s?.size??null,()=>null)}function nr(e,t){if(e.display!==h)return Promise.resolve();let p=_.then(async()=>{let n=a(),s=x({home:n});if(!s)return;let i=P(s.root,"display"),o=P(i,"theme");if(ye(o)===t)return;let c=K(i,e,s.pulseaudio),l=fe(await F("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await m(I(o,e.display,l?.current??A,n,t),c)});return _=p.catch(()=>{}),p.catch(()=>{})}async function jt(e,t={}){let p=t.now??Date.now,n=Ue(e.payload,p());if(e.signal.throwIfAborted(),!n.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let s=t.platform??process.platform;if(s!=="linux"&&s!=="darwin"&&s!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let{video:i,look:o}=n,c=(t.video?.desktop??(s==="darwin"?async()=>On:s==="win32"?async()=>In:async()=>{let l=await qe();if(o)await nr(l,o);return l}))();return await pr(e.signal,n,t,p,(l)=>Dn(l,{request:i,desktop:c,...n.viewer?{viewer:n.viewer}:{},viewerSameNetwork:n.viewer_same_network===!0},{resizeDesktop:sr,...t.video}),(l)=>Wt({type:"error",code:l}))}function pr(e,t,p,n,s,i){let o=n();return new Promise((c,l)=>{let b=null,q=!1,y=!1,k,O,S,B=!1,f=null,X=(D)=>{if(y)return;if(f)D=f.outcome;y=!0,clearTimeout(k),clearTimeout(O),e.removeEventListener("abort",w),S?.close();try{b?.close(1000,"display_session_over")}catch{}if("error"in D){l(D.error);return}c({reason:D.reason,...S?.summary(),duration_ms:Math.max(0,n()-o)})},J=()=>X({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),w=()=>{let D=e.reason;X({error:D instanceof r?D:new r("cancelled","Reason closed the desktop session.")})},U=()=>{if(!f||!b)return;let{outcome:D}=f,E=!("error"in D)?D.reason:D.error instanceof r?D.error.code:"display_unavailable";if(!f.told)try{b.send(i(E))}catch{}X(D)};if(S=s({get done(){return y||f!==null},get open(){return q&&!y&&f===null},get bufferedAmount(){return b?.bufferedAmount??0},send(D){if(y||f||!q||!b)return;try{b.send(D)}catch{X({reason:"relay_closed"})}},end:(D)=>{if(y||f)return;if(!("error"in D)&&B&&q){X(D);return}if(f={outcome:D,told:!("error"in D)&&q},B&&q)U()}}),y){S.close();return}if(e.aborted){w();return}e.addEventListener("abort",w,{once:!0}),k=setTimeout(()=>X({reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-n())),O=setTimeout(()=>X({reason:"viewer_absent"}),p.viewerWaitMs??Fe);try{b=(p.connect??Nr)(t.relay_url,(p.loadProxy??j)()?.url)}catch{J();return}b.binaryType="arraybuffer",b.onopen=()=>{if(y||!b)return;q=!0,S?.opened()},b.onmessage=(D)=>{if(y)return;let E=D.data,g=E instanceof ArrayBuffer?new Uint8Array(E):ArrayBuffer.isView(E)?new Uint8Array(E.buffer,E.byteOffset,E.byteLength):null;if(!g||g.byteLength===0)return;if(clearTimeout(O),B=!0,f){U();return}S?.received(g)},b.onclose=()=>{if(y)return;if(!q){J();return}X({reason:"relay_closed"})},b.onerror=()=>{if(y||q)return;J()}})}
150
+ export{Ft,Vs,G,qe,jt};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var tr={name:"github-native-engineer-device-worker-production",version:"0.2.521",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
2
+ var tr={name:"github-native-engineer-device-worker-production",version:"0.2.523",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
3
3
  export{tr};
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Qe}from"./vm-hands-entry-lite-etg5ft0x.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Zn="so.ara.cli",k=[Zn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",Io="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
2
+ import{Qe}from"./vm-hands-entry-lite-ghva8qrf.js";import{a}from"./vm-hands-entry-lite-haws181e.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Xn="so.ara.cli",k=[Xn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",Lo="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
3
3
  `)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
4
4
  `).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
5
- `)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Xn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
6
- `?[i,"--spawn"]:[]}var P=new Map;function gt(e=a()){let t=Xn(e),n=t[0];if(!n)return[];let r=P.get(n);if(r===void 0){let i=b(n,["--can-spawn-computer-use"],{env:{},timeout:2000,encoding:"utf8"});r=i.status===0&&i.stdout===`spawn
7
- `,P.set(n,r)}return r?t:[]}function Do(e=gt(),t=a()){if(e.length>0)return null;if(Kr(t)===null)return"computer_use_identity_missing";return pe(Qe,t)?"computer_use_identity_outdated":"computer_use_identity_unavailable"}function he(e={}){H(e.home);let t=le(e.home);if(e.skipWhenSettled&&d(t)&&C(t)&&Q(O(e.home))===null)return!0;if(!d(t)){let n=O(e.home);if(!d(n))return!1;try{return _e({...e,sourceApp:n}),!0}catch(r){if(!d(t))throw r}}return z(t,e),!0}var er="REASON_WORKER_IDENTITY_APP";function No(e,t=process.env,n=a()){let r=t[er];return r&&r===le(n)?r:e}function Lo(e,t){if(process.platform!=="darwin")return null;let n=le(e),r=u(n,"Contents","MacOS",G),i=b(r,["--can-run-worker",t],{env:{},timeout:2000,encoding:"utf8"});return i.status===0&&i.stdout===`run-worker
5
+ `)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Yn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
6
+ `?[i,"--spawn"]:[]}var P=new Map;function gt(e=a()){let t=Yn(e),n=t[0];if(!n)return[];let r=P.get(n);if(r===void 0){let i=b(n,["--can-spawn-computer-use"],{env:{},timeout:2000,encoding:"utf8"});r=i.status===0&&i.stdout===`spawn
7
+ `,P.set(n,r)}return r?t:[]}function Mo(e=gt(),t=a()){if(e.length>0)return null;if(Kr(t)===null)return"computer_use_identity_missing";return pe(Qe,t)?"computer_use_identity_outdated":"computer_use_identity_unavailable"}function he(e={}){H(e.home);let t=le(e.home);if(e.skipWhenSettled&&d(t)&&C(t)&&Q(O(e.home))===null)return!0;if(!d(t)){let n=O(e.home);if(!d(n))return!1;try{return _e({...e,sourceApp:n}),!0}catch(r){if(!d(t))throw r}}return z(t,e),!0}var er="REASON_WORKER_IDENTITY_APP";function $o(e,t=process.env,n=a()){let r=t[er];return r&&r===le(n)?r:e}function Bo(e,t){if(process.platform!=="darwin")return null;let n=le(e),r=u(n,"Contents","MacOS",G),i=b(r,["--can-run-worker",t],{env:{},timeout:2000,encoding:"utf8"});return i.status===0&&i.stdout===`run-worker
8
8
  `?{app:n,executable:r}:null}
9
- export{Zn,Gr,Io,le,Kr,Xn,gt,Do,er,No,Lo};
9
+ export{Xn,Gr,Lo,le,Kr,Yn,gt,Mo,er,$o,Bo};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ni,vt,oi,si,ai,Ri}from"./vm-hands-entry-lite-ydgedg8n.js";import"./vm-hands-entry-lite-mma9qt5r.js";import{createHash as H,randomBytes as he}from"crypto";import{closeSync as Ae,fsyncSync as xe,mkdirSync as Xe,openSync as Oe,renameSync as Qe,rmSync as Ze,statSync as De,writeSync as Me,constants as W}from"fs";import{join as se}from"path";var en=1;var oe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pe(e){if(e.environment!==void 0||e.payload.environment!==void 0)throw new l("vm_hands_bind_invalid","bind carries a plaintext environment");if(e.payload.vm_hands_env_deferred===!0&&e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","split bind carries an environment");return e.environment_sealed!==void 0}function Te(e,n){let{payload:i,authority:r}=e;if(!i||typeof i!=="object"||Array.isArray(i)||!r||typeof r!=="object"||Array.isArray(r)||!n.deviceId||!n.rootId||i.run_id!==n.runId||i.device_id!==n.deviceId||r.device_id!==n.deviceId||i.root_id!==n.rootId||n.snapshotId!==void 0&&i.snapshot_id!==n.snapshotId)throw new l("vm_hands_env_invalid","environment does not match this Hands");return i}function ve(e){if(e.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not a hands.connect claim");let n=e.payload;return{kind:"vm_hands.bind",v:1,bind_id:e.attempt_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,run_id:e.run_id,session_id:typeof n.workspace_id==="string"&&oe.test(n.workspace_id)?n.workspace_id:e.run_id,brain_generation:n.target_generation,fence_id:n.target_fence_id,lease_until:e.lease_until,policy:{agent_profile:"",confinement_key:String(n.hands_confinement??""),browser_egress:n.browser_egress??null,policy_digest:n.vm_hands_policy_digest},cwd:typeof n.cwd==="string"?n.cwd:"",claim:e,env:pe(e)?e.environment_sealed:null,workspace_deferred:nn(e)}}function nn(e){let n=e.payload[oi];if(n===void 0)return!1;if(n!==!0||e.payload.vm_hands_env_deferred!==!0||e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class l extends Error{code;constructor(e,n){super(n);this.code=e}}function Re(e,n){if(e instanceof l)return e;let i=e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(e.code)?e.code:"vm_hands_bind_failed";return new l(i,n)}var G=(e)=>Buffer.from(e instanceof Uint8Array?e:new Uint8Array(e)).toString("base64url"),K=(e)=>new Uint8Array(Buffer.from(e,"base64url"));function V(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${V(e[n])}`).join(",")}}`}async function Hi(e){let n=await crypto.subtle.importKey("pkcs8",K(e.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),i=K(e.device_key.spki),r=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),h=new Uint8Array(await crypto.subtle.exportKey("spki",r.publicKey)),m=H("sha256").update(i).digest("base64url");return{signing:{privateKey:n},agreement:r,signingSpki:i,agreementSpki:h,fingerprint:m}}var tn=16;class pn{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;rebindableGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(e){let n=this.structural.then(e,e);return this.structural=n.catch(()=>{return}),n}constructor(e,n,i,r){this.init=e;this.keys=n;this.hooks=i;this.options=r;if(!oe.test(e.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(e.workspace_id))throw new l("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(e.instance_generation)||e.instance_generation<1)throw new l("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(e){for(let n of this.bound.values())if(n.runId===e)return!0;return!1}bindIdForRun(e){for(let n of this.bound.values())if(n.runId===e)return n.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}get liveSessionIds(){return[...new Set([...this.bound.values()].map((e)=>e.sessionId.toLowerCase()))]}get settingUp(){return this.binding.size>0}async environmentInstalled(e,n,i){for(let r=Date.now()+n;;){let h=this.bound.get(e);if(!h)return!1;if(h.envInstalled)return!0;if(Date.now()>=r||i?.aborted)return!1;await new Promise((m)=>setTimeout(m,25))}}canSpawn(e){for(let n of this.bound.values())if(n.runId===e)return n.envInstalled;return!1}async registerFrame(e){if(this.identity!=="identity_free")throw new l("vm_hands_register_twice","already registered");if(typeof e!=="string"||e.length<16||e.length>256)throw new l("vm_hands_challenge_invalid","bad register challenge");let n={challenge:e,t:"register",v:en,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:G(this.keys.signingSpki),env_public_key:G(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:G(he(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},i=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(V(n)));return{...n,device_signature:G(i)}}async helloFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","hello before register");let i=String((this.options.now??Date.now)()),r=G(he(32)),h=Ri({method:"GET",pathAndQuery:ni,timestamp:i,nonce:r,challenge:e,bodySha256:H("sha256").update("").digest("hex")}),m=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(h)));return{t:"hello",timestamp:i,nonce:r,signature:G(rn(m)),...n?{vm_hands_previous_connection:n}:{}}}registered(){if(this.identity!=="identity_free")throw new l("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(e){if(this.identity!=="registered")throw new l("vm_hands_not_registered","bind before register");if(e.kind!=="vm_hands.bind"||e.v!==1)throw new l("vm_hands_bind_invalid","bad bind");for(let r of[e.bind_id,e.attempt_id,e.run_id,e.session_id,e.fence_id])if(!oe.test(r))throw new l("vm_hands_bind_invalid","bad id");let n=this.lastBrainGeneration.get(e.run_id)??0;if(!Number.isSafeInteger(e.brain_generation)||e.brain_generation<n||e.brain_generation===n&&this.rebindableGeneration.get(e.run_id)!==n)throw new l("vm_hands_generation_stale","brain generation not strictly higher");if(e.env&&(e.env.aad!==e.bind_id||e.env.alg!=="ECDH-P256+A256GCM"))throw new l("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(e.policy.policy_digest))throw new l("vm_hands_bind_invalid","bad policy or nonce");if(H("sha256").update(V({hands_confinement:e.policy.confinement_key||null,browser_egress:e.policy.browser_egress??null})).digest("hex")!==e.policy.policy_digest)throw new l("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(e.bind_id)||[...this.bound.values()].some((r)=>r.runId===e.run_id)||[...this.binding.values()].includes(e.run_id))throw new l("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=tn)throw new l("vm_hands_busy","every bind slot is held");if([...this.grants.values()].some((r)=>r.sessionId===e.session_id))throw new l("vm_hands_busy","a bind of this Session waits for its workspace beside the setup");if(this.lastBrainGeneration.set(e.run_id,e.brain_generation),this.rebindableGeneration.delete(e.run_id),this.binding.set(e.bind_id,e.run_id),e.workspace_deferred){let r,h,m=new Promise((_,k)=>{r=_,h=k});return m.catch(()=>{return}),this.grants.set(e.bind_id,{sessionId:e.session_id,promise:m,resolve:r,reject:h}),this.setUpDeferred(e)}return this.exclusive(()=>this.setUp(e))}liveCgroupBindsBut(e){return[...new Set([...this.bound.keys(),...this.binding.keys()])].filter((n)=>n!==e)}async setUpDeferred(e){let n=this.grants.get(e.bind_id);try{await this.exclusive(()=>this.prepareBind(e))}catch(v){throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(v,"the bind's kill-verify failed")}let i,r=new Promise((v)=>{i=v}),h=!1,m=!1,_=()=>{m=!0,i()},k=n.promise.then(()=>new Promise((v,I)=>{this.exclusive(async()=>{if(m){I(new l("vm_hands_bind_lost","the pre-bind ended before its turn"));return}h=!0;try{if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:[...this.liveCgroupBindsBut(e.bind_id),e.bind_id]}),this.unverified.clear();v()}catch(w){I(w)}await r})}));k.catch(()=>{return});try{return await this.setUp(e,{workspaceGrant:k,inTurn:()=>h,leave:_})}finally{_()}}async prepareBind(e){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new l("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}let n=this.liveCgroupBindsBut(e.bind_id);if(this.unverified.size>0)await this.hooks.killAndVerifyPayload(n.length?{keep:n}:void 0),this.unverified.clear();this.servedRun=!0}async setUp(e,n){let i=null,r=!1;try{if(!n)await this.prepareBind(e);r=!0;let{launchId:h,applied:m,readyData:_}=await this.hooks.startExecutor({bindId:e.bind_id,sessionId:e.session_id,policyDigest:e.policy.policy_digest,confinementKey:e.policy.confinement_key,browserEgress:e.policy.browser_egress,cwd:e.cwd,claim:e.claim,...n?{workspaceGrant:n.workspaceGrant}:{}}),k=this.hooks.restatLayout(e.session_id);this.hooks.verifyMounts?.(e.session_id);let v=null,I=null;if(e.env){let w=e.claim?.owner??{},E=Te(await this.openSealed(e.env,e.bind_id),{runId:e.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:e.claim?.root_id??""});v=this.hooks.installEnvironment(e.bind_id,E),I=typeof E.snapshot_id==="string"&&E.snapshot_id?E.snapshot_id:null,i=this.writeJobEnvRootOnly(e.bind_id,E)}if(this.unbinding.has(e.bind_id))throw new l("vm_hands_bind_lost","unbound while binding");return this.bound.set(e.bind_id,{bindId:e.bind_id,runId:e.run_id,sessionId:e.session_id,brainGeneration:e.brain_generation,policyDigest:e.policy.policy_digest,launchId:h,envInstalled:v!==null,rootId:e.claim?.root_id??"",envDirectory:i}),this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),{bind_id:e.bind_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,launch_id:h,snapshot_revision:v,snapshot_id:I,layout:k,..._?{ready_data:_}:{},policy_digest:H("sha256").update(V({hands_confinement:m.hands_confinement??null,browser_egress:m.browser_egress??null})).digest("hex")}}catch(h){if(i)fe(i);if(r){let m=()=>this.hooks.killAndVerifyPayload({bindId:e.bind_id,keep:this.liveCgroupBindsBut(e.bind_id),own:!0}).catch(()=>{this.unverified.add(e.bind_id)});if(n&&!n.inTurn())n.leave(),await this.exclusive(m);else await m()}throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(h,"executor refused the bind")}}grantWorkspace(e){let n=this.grants.get(e);if(!n)throw new l("vm_hands_not_binding","no pre-bind waits for a workspace grant");n.resolve()}abandonWorkspaceGrant(e){this.grants.get(e)?.reject(new l("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(e){let n=this.bound.get(e.attemptId);if(!n||this.unbinding.has(e.attemptId))throw new l("vm_hands_not_bound","environment delivered while not bound");if(!oe.test(e.attemptId)||typeof e.snapshotId!=="string"||!e.snapshotId||e.snapshotId.length>128||e.snapshotId.includes("/"))throw new l("vm_hands_env_invalid","bad snapshot id");let i=`${e.attemptId}/${e.snapshotId}`;if(e.sealed?.alg!=="ECDH-P256+A256GCM"||e.sealed.aad!==i)throw new l("vm_hands_env_invalid","bad env envelope");let r=Te(await this.openSealed(e.sealed,i),{runId:n.runId,deviceId:e.deviceId,rootId:n.rootId,snapshotId:e.snapshotId}),h=this.hooks.installEnvironment(n.bindId,r);if(n.envInstalled=!0,n.envDirectory)fe(n.envDirectory);return n.envDirectory=null,n.envDirectory=this.writeJobEnvRootOnly(`${n.bindId}-r${h}`,r),{snapshot_id:e.snapshotId,installed_revision:h,installed:!0}}async attestFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","attest before register");if(!e||e.length>65536)throw new l("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new l("vm_hands_attest_invalid","attest beside a bind");let i=await this.hooks.runProbe({nonce:n,script:e});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:n,exit_code:i.exitCode,markers:i.markers,proof_dir_inode:i.proofDirInode,script_sha256:H("sha256").update(e).digest("hex")}})}executorExited(e){return this.hooks.executorExited?.(e)??new Promise(()=>{})}async boundRefused(e){await this.unbind(e)}async unbind(e){let n=this.bound.get(e)??null;if(this.unbinding.add(e),this.bound.delete(e),this.abandonWorkspaceGrant(e),n)try{this.hooks.freezeBind?.(e)}catch{}return this.exclusive(()=>this.tearDown(e,n))}async retryUnbind(e){if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(e,this.unverifiedTeardowns.get(e)??null,!0)})}async tearDown(e,n,i=!1){try{this.bound.delete(e);let r=this.liveCgroupBindsBut(e);try{await this.hooks.killAndVerifyPayload({bindId:e,keep:r})}catch(h){if(this.unverified.add(e),!this.unverifiedTeardowns.has(e))this.unverifiedTeardowns.set(e,n);throw h}if(this.unverified.delete(e),!r.length&&!i)this.unverified.clear();if(n?.envDirectory)fe(n.envDirectory);if(this.unverifiedTeardowns.delete(e),n&&this.lastBrainGeneration.get(n.runId)===n.brainGeneration)this.rebindableGeneration.set(n.runId,n.brainGeneration);return{bind_id:n?e:null,killed_verified:!0,shredded:!0,srt_fallbacks:r.length||i?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(e)}}async openSealed(e,n){let i=()=>{throw new l("vm_hands_env_invalid","env did not decrypt")},r=await crypto.subtle.importKey("spki",K(e.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(i),h=await crypto.subtle.deriveKey({name:"ECDH",public:r},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),m=await crypto.subtle.decrypt({name:"AES-GCM",iv:K(e.iv),additionalData:new TextEncoder().encode(n)},h,K(e.ct)).catch(i),_=JSON.parse(new TextDecoder().decode(m));if(!_||typeof _!=="object"||Array.isArray(_))throw new l("vm_hands_env_invalid","env not an object");return _}writeJobEnvRootOnly(e,n){let i=se(this.options.envRoot,`bind-${e}`);Xe(i,{mode:448});let r=De(i);if(!r.isDirectory()||(r.mode&63)!==0||r.uid!==(process.getuid?.()??-1))throw new l("vm_hands_env_dir_unsafe","env directory is not root's 0700");let h=n.variables&&typeof n.variables==="object"?n.variables:{},m=Object.entries(h).filter(([v,I])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(v)&&typeof I==="string").map(([v,I])=>`export ${v}='${String(I).replaceAll("'","'\\''")}'`).join(`
2
+ import{ii,vt,si,ai,ci,Oi}from"./vm-hands-entry-lite-88yjxxvf.js";import"./vm-hands-entry-lite-mfvtp7py.js";import{createHash as H,randomBytes as he}from"crypto";import{closeSync as Ae,fsyncSync as xe,mkdirSync as Xe,openSync as Oe,renameSync as Qe,rmSync as Ze,statSync as De,writeSync as Me,constants as W}from"fs";import{join as se}from"path";var en=1;var oe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pe(e){if(e.environment!==void 0||e.payload.environment!==void 0)throw new l("vm_hands_bind_invalid","bind carries a plaintext environment");if(e.payload.vm_hands_env_deferred===!0&&e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","split bind carries an environment");return e.environment_sealed!==void 0}function Te(e,n){let{payload:i,authority:r}=e;if(!i||typeof i!=="object"||Array.isArray(i)||!r||typeof r!=="object"||Array.isArray(r)||!n.deviceId||!n.rootId||i.run_id!==n.runId||i.device_id!==n.deviceId||r.device_id!==n.deviceId||i.root_id!==n.rootId||n.snapshotId!==void 0&&i.snapshot_id!==n.snapshotId)throw new l("vm_hands_env_invalid","environment does not match this Hands");return i}function ve(e){if(e.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not a hands.connect claim");let n=e.payload;return{kind:"vm_hands.bind",v:1,bind_id:e.attempt_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,run_id:e.run_id,session_id:typeof n.workspace_id==="string"&&oe.test(n.workspace_id)?n.workspace_id:e.run_id,brain_generation:n.target_generation,fence_id:n.target_fence_id,lease_until:e.lease_until,policy:{agent_profile:"",confinement_key:String(n.hands_confinement??""),browser_egress:n.browser_egress??null,policy_digest:n.vm_hands_policy_digest},cwd:typeof n.cwd==="string"?n.cwd:"",claim:e,env:pe(e)?e.environment_sealed:null,workspace_deferred:nn(e)}}function nn(e){let n=e.payload[si];if(n===void 0)return!1;if(n!==!0||e.payload.vm_hands_env_deferred!==!0||e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class l extends Error{code;constructor(e,n){super(n);this.code=e}}function Re(e,n){if(e instanceof l)return e;let i=e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(e.code)?e.code:"vm_hands_bind_failed";return new l(i,n)}var G=(e)=>Buffer.from(e instanceof Uint8Array?e:new Uint8Array(e)).toString("base64url"),K=(e)=>new Uint8Array(Buffer.from(e,"base64url"));function V(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${V(e[n])}`).join(",")}}`}async function zi(e){let n=await crypto.subtle.importKey("pkcs8",K(e.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),i=K(e.device_key.spki),r=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),h=new Uint8Array(await crypto.subtle.exportKey("spki",r.publicKey)),m=H("sha256").update(i).digest("base64url");return{signing:{privateKey:n},agreement:r,signingSpki:i,agreementSpki:h,fingerprint:m}}var tn=16;class pn{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;rebindableGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(e){let n=this.structural.then(e,e);return this.structural=n.catch(()=>{return}),n}constructor(e,n,i,r){this.init=e;this.keys=n;this.hooks=i;this.options=r;if(!oe.test(e.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(e.workspace_id))throw new l("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(e.instance_generation)||e.instance_generation<1)throw new l("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(e){for(let n of this.bound.values())if(n.runId===e)return!0;return!1}bindIdForRun(e){for(let n of this.bound.values())if(n.runId===e)return n.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}get liveSessionIds(){return[...new Set([...this.bound.values()].map((e)=>e.sessionId.toLowerCase()))]}get settingUp(){return this.binding.size>0}async environmentInstalled(e,n,i){for(let r=Date.now()+n;;){let h=this.bound.get(e);if(!h)return!1;if(h.envInstalled)return!0;if(Date.now()>=r||i?.aborted)return!1;await new Promise((m)=>setTimeout(m,25))}}canSpawn(e){for(let n of this.bound.values())if(n.runId===e)return n.envInstalled;return!1}async registerFrame(e){if(this.identity!=="identity_free")throw new l("vm_hands_register_twice","already registered");if(typeof e!=="string"||e.length<16||e.length>256)throw new l("vm_hands_challenge_invalid","bad register challenge");let n={challenge:e,t:"register",v:en,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:G(this.keys.signingSpki),env_public_key:G(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:G(he(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},i=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(V(n)));return{...n,device_signature:G(i)}}async helloFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","hello before register");let i=String((this.options.now??Date.now)()),r=G(he(32)),h=Oi({method:"GET",pathAndQuery:ii,timestamp:i,nonce:r,challenge:e,bodySha256:H("sha256").update("").digest("hex")}),m=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(h)));return{t:"hello",timestamp:i,nonce:r,signature:G(rn(m)),...n?{vm_hands_previous_connection:n}:{}}}registered(){if(this.identity!=="identity_free")throw new l("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(e){if(this.identity!=="registered")throw new l("vm_hands_not_registered","bind before register");if(e.kind!=="vm_hands.bind"||e.v!==1)throw new l("vm_hands_bind_invalid","bad bind");for(let r of[e.bind_id,e.attempt_id,e.run_id,e.session_id,e.fence_id])if(!oe.test(r))throw new l("vm_hands_bind_invalid","bad id");let n=this.lastBrainGeneration.get(e.run_id)??0;if(!Number.isSafeInteger(e.brain_generation)||e.brain_generation<n||e.brain_generation===n&&this.rebindableGeneration.get(e.run_id)!==n)throw new l("vm_hands_generation_stale","brain generation not strictly higher");if(e.env&&(e.env.aad!==e.bind_id||e.env.alg!=="ECDH-P256+A256GCM"))throw new l("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(e.policy.policy_digest))throw new l("vm_hands_bind_invalid","bad policy or nonce");if(H("sha256").update(V({hands_confinement:e.policy.confinement_key||null,browser_egress:e.policy.browser_egress??null})).digest("hex")!==e.policy.policy_digest)throw new l("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(e.bind_id)||[...this.bound.values()].some((r)=>r.runId===e.run_id)||[...this.binding.values()].includes(e.run_id))throw new l("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=tn)throw new l("vm_hands_busy","every bind slot is held");if([...this.grants.values()].some((r)=>r.sessionId===e.session_id))throw new l("vm_hands_busy","a bind of this Session waits for its workspace beside the setup");if(this.lastBrainGeneration.set(e.run_id,e.brain_generation),this.rebindableGeneration.delete(e.run_id),this.binding.set(e.bind_id,e.run_id),e.workspace_deferred){let r,h,m=new Promise((_,k)=>{r=_,h=k});return m.catch(()=>{return}),this.grants.set(e.bind_id,{sessionId:e.session_id,promise:m,resolve:r,reject:h}),this.setUpDeferred(e)}return this.exclusive(()=>this.setUp(e))}liveCgroupBindsBut(e){return[...new Set([...this.bound.keys(),...this.binding.keys()])].filter((n)=>n!==e)}async setUpDeferred(e){let n=this.grants.get(e.bind_id);try{await this.exclusive(()=>this.prepareBind(e))}catch(v){throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(v,"the bind's kill-verify failed")}let i,r=new Promise((v)=>{i=v}),h=!1,m=!1,_=()=>{m=!0,i()},k=n.promise.then(()=>new Promise((v,I)=>{this.exclusive(async()=>{if(m){I(new l("vm_hands_bind_lost","the pre-bind ended before its turn"));return}h=!0;try{if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:[...this.liveCgroupBindsBut(e.bind_id),e.bind_id]}),this.unverified.clear();v()}catch(w){I(w)}await r})}));k.catch(()=>{return});try{return await this.setUp(e,{workspaceGrant:k,inTurn:()=>h,leave:_})}finally{_()}}async prepareBind(e){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new l("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}let n=this.liveCgroupBindsBut(e.bind_id);if(this.unverified.size>0)await this.hooks.killAndVerifyPayload(n.length?{keep:n}:void 0),this.unverified.clear();this.servedRun=!0}async setUp(e,n){let i=null,r=!1;try{if(!n)await this.prepareBind(e);r=!0;let{launchId:h,applied:m,readyData:_}=await this.hooks.startExecutor({bindId:e.bind_id,sessionId:e.session_id,policyDigest:e.policy.policy_digest,confinementKey:e.policy.confinement_key,browserEgress:e.policy.browser_egress,cwd:e.cwd,claim:e.claim,...n?{workspaceGrant:n.workspaceGrant}:{}}),k=this.hooks.restatLayout(e.session_id);this.hooks.verifyMounts?.(e.session_id);let v=null,I=null;if(e.env){let w=e.claim?.owner??{},E=Te(await this.openSealed(e.env,e.bind_id),{runId:e.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:e.claim?.root_id??""});v=this.hooks.installEnvironment(e.bind_id,E),I=typeof E.snapshot_id==="string"&&E.snapshot_id?E.snapshot_id:null,i=this.writeJobEnvRootOnly(e.bind_id,E)}if(this.unbinding.has(e.bind_id))throw new l("vm_hands_bind_lost","unbound while binding");return this.bound.set(e.bind_id,{bindId:e.bind_id,runId:e.run_id,sessionId:e.session_id,brainGeneration:e.brain_generation,policyDigest:e.policy.policy_digest,launchId:h,envInstalled:v!==null,rootId:e.claim?.root_id??"",envDirectory:i}),this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),{bind_id:e.bind_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,launch_id:h,snapshot_revision:v,snapshot_id:I,layout:k,..._?{ready_data:_}:{},policy_digest:H("sha256").update(V({hands_confinement:m.hands_confinement??null,browser_egress:m.browser_egress??null})).digest("hex")}}catch(h){if(i)fe(i);if(r){let m=()=>this.hooks.killAndVerifyPayload({bindId:e.bind_id,keep:this.liveCgroupBindsBut(e.bind_id),own:!0}).catch(()=>{this.unverified.add(e.bind_id)});if(n&&!n.inTurn())n.leave(),await this.exclusive(m);else await m()}throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(h,"executor refused the bind")}}grantWorkspace(e){let n=this.grants.get(e);if(!n)throw new l("vm_hands_not_binding","no pre-bind waits for a workspace grant");n.resolve()}abandonWorkspaceGrant(e){this.grants.get(e)?.reject(new l("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(e){let n=this.bound.get(e.attemptId);if(!n||this.unbinding.has(e.attemptId))throw new l("vm_hands_not_bound","environment delivered while not bound");if(!oe.test(e.attemptId)||typeof e.snapshotId!=="string"||!e.snapshotId||e.snapshotId.length>128||e.snapshotId.includes("/"))throw new l("vm_hands_env_invalid","bad snapshot id");let i=`${e.attemptId}/${e.snapshotId}`;if(e.sealed?.alg!=="ECDH-P256+A256GCM"||e.sealed.aad!==i)throw new l("vm_hands_env_invalid","bad env envelope");let r=Te(await this.openSealed(e.sealed,i),{runId:n.runId,deviceId:e.deviceId,rootId:n.rootId,snapshotId:e.snapshotId}),h=this.hooks.installEnvironment(n.bindId,r);if(n.envInstalled=!0,n.envDirectory)fe(n.envDirectory);return n.envDirectory=null,n.envDirectory=this.writeJobEnvRootOnly(`${n.bindId}-r${h}`,r),{snapshot_id:e.snapshotId,installed_revision:h,installed:!0}}async attestFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","attest before register");if(!e||e.length>65536)throw new l("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new l("vm_hands_attest_invalid","attest beside a bind");let i=await this.hooks.runProbe({nonce:n,script:e});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:n,exit_code:i.exitCode,markers:i.markers,proof_dir_inode:i.proofDirInode,script_sha256:H("sha256").update(e).digest("hex")}})}executorExited(e){return this.hooks.executorExited?.(e)??new Promise(()=>{})}async boundRefused(e){await this.unbind(e)}async unbind(e){let n=this.bound.get(e)??null;if(this.unbinding.add(e),this.bound.delete(e),this.abandonWorkspaceGrant(e),n)try{this.hooks.freezeBind?.(e)}catch{}return this.exclusive(()=>this.tearDown(e,n))}async retryUnbind(e){if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(e,this.unverifiedTeardowns.get(e)??null,!0)})}async tearDown(e,n,i=!1){try{this.bound.delete(e);let r=this.liveCgroupBindsBut(e);try{await this.hooks.killAndVerifyPayload({bindId:e,keep:r})}catch(h){if(this.unverified.add(e),!this.unverifiedTeardowns.has(e))this.unverifiedTeardowns.set(e,n);throw h}if(this.unverified.delete(e),!r.length&&!i)this.unverified.clear();if(n?.envDirectory)fe(n.envDirectory);if(this.unverifiedTeardowns.delete(e),n&&this.lastBrainGeneration.get(n.runId)===n.brainGeneration)this.rebindableGeneration.set(n.runId,n.brainGeneration);return{bind_id:n?e:null,killed_verified:!0,shredded:!0,srt_fallbacks:r.length||i?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(e)}}async openSealed(e,n){let i=()=>{throw new l("vm_hands_env_invalid","env did not decrypt")},r=await crypto.subtle.importKey("spki",K(e.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(i),h=await crypto.subtle.deriveKey({name:"ECDH",public:r},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),m=await crypto.subtle.decrypt({name:"AES-GCM",iv:K(e.iv),additionalData:new TextEncoder().encode(n)},h,K(e.ct)).catch(i),_=JSON.parse(new TextDecoder().decode(m));if(!_||typeof _!=="object"||Array.isArray(_))throw new l("vm_hands_env_invalid","env not an object");return _}writeJobEnvRootOnly(e,n){let i=se(this.options.envRoot,`bind-${e}`);Xe(i,{mode:448});let r=De(i);if(!r.isDirectory()||(r.mode&63)!==0||r.uid!==(process.getuid?.()??-1))throw new l("vm_hands_env_dir_unsafe","env directory is not root's 0700");let h=n.variables&&typeof n.variables==="object"?n.variables:{},m=Object.entries(h).filter(([v,I])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(v)&&typeof I==="string").map(([v,I])=>`export ${v}='${String(I).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
- `,_=se(i,`.job.env.${he(8).toString("hex")}`),k=Oe(_,W.O_WRONLY|W.O_CREAT|W.O_EXCL|W.O_NOFOLLOW,384);try{Me(k,m),xe(k)}finally{Ae(k)}return Qe(_,se(i,"job.env")),i}}function fe(e){try{let n=se(e,"job.env"),i=De(n).size,r=Oe(n,W.O_WRONLY|W.O_NOFOLLOW);try{Me(r,Buffer.alloc(i)),xe(r)}finally{Ae(r)}}catch{}Ze(e,{recursive:!0,force:!0})}function rn(e){if(e.length!==64)throw new l("vm_hands_signature_invalid","unexpected ECDSA signature length");let n=(h)=>{let m=0;while(m<h.length-1&&h[m]===0)m++;let _=h.subarray(m),k=_[0]&128?Uint8Array.of(0,..._):_;return Uint8Array.of(2,k.length,...k)},i=n(e.subarray(0,32)),r=n(e.subarray(32));return Uint8Array.of(48,i.length+r.length,...i,...r)}import{randomUUID as sn}from"crypto";var on="/app/local-runtime/session?register=vm_hands_v1",an="/app/local-runtime",Ce=25000,we=20000,dn=1e4,Ue=5000,cn=new Set(["pty.start","jobs.control","tunnel.open","tunnel.close"]),ln="preview.serve.v1",un=60000,ye=75000,_n=2000,mn=1e4,gn=new Set(["vm_hands_no_register","vm_hands_register_failed"]),hn=3,fn=20000,vn=250,wn=2000;function $e(e){let n=Math.min(vn*2**(e-1),wn);return Math.round(n/2+Math.random()*n/2)}var yn=5000;function bn(e){return e>=500||e===408||e===429}var ae=20000;function Be(e,n){return typeof e==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:n}class D extends Error{}var kn=64,qe=[1000,2000,4000,8000,15000,30000,60000,120000];function je(e){let n=e&&typeof e==="object"&&"code"in e?e.code:null;return typeof n==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(n)?n:"vm_hands_unbind_failed"}function Sn(e,n,i,r,h){let m=i.turn.claim.attempt_id,_=e.healing??=new Set;if(_.has(m))return;_.add(m);let k=i.turn.claim.operation_id;(async()=>{for(let[v,I]of qe.entries()){if(r.aborted)return;if(await new Promise((w)=>{let E=setTimeout(w,I);E.unref?.(),r.addEventListener("abort",()=>{clearTimeout(E),w()},{once:!0})}),r.aborted)return;try{let w=await n.retryUnbind(m);h("vm_hands.unbind_healed",{operation_id:k,attempt:v+1}),e.receipts.push({...i,unbound:w}),e.flushReceipts?.();return}catch(w){let E=je(w);if(h("vm_hands.unbind_unverified",{operation_id:k,code:E,attempt:v+1}),E==="vm_hands_unbind_unknown")return}}h("vm_hands.unbind_heal_exhausted",{operation_id:k,attempts:qe.length})})().finally(()=>_.delete(m))}async function Ge(e,n){let i=[...e.modelOps.get(n)??[]];for(let r of i)r.abort.abort();await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))])}async function In(e,n){let i=[...e.personTerminals].filter((r)=>r.session===null||r.session===n);for(let r of i)r.abort.abort();if(i.length)await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))]);return i.length}function Pn(e){let n=e.payload,i=n?.workspace?.kind==="managed"?n.workspace.workspaceId:void 0;return typeof i==="string"&&/^[0-9a-f-]{36}$/i.test(i)?i.toLowerCase():null}async function L(e,n,i){return await Ge(e,i),n.unbind(i)}function de(e){for(let n of e.outbox?.splice(0)??[])n.reject(Error("vm_hands_attempt_ended"))}var Ne=15000,En=1e4,Tn=1000;async function zi(e){let n=Date.now(),i={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:new Map},r=e.log??(()=>{}),h=async(k)=>{for(let[v,I]of[...i.turns]){i.turns.delete(v),e.onTurn?.(v,null),de(I);let w=await L(i,e.agent,v).catch(()=>null);if(w)i.receipts.push({turn:I,failure:"vm_hands_bind_lost",unbound:w});r("vm_hands.bound_dropped",{reason:k})}},m=0,_=0;try{for(let k=0;!e.signal.aborted;k++){let v=await Rn(e,i).catch((w)=>{if(w instanceof l&&i.deviceId===null&&w.code==="vm_hands_no_session"&&Date.now()-n<mn)return{closeCode:0,closeReason:"vm_hands_no_session"};if(w instanceof l&&i.deviceId===null&&gn.has(w.code)&&m<hn&&Date.now()-n<fn)return m++,_=$e(m),r("vm_hands.register_retry",{attempt:m,code:w.code,delay_ms:_}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(w instanceof l&&i.deviceId===null)throw w;return{closeCode:0,closeReason:w instanceof Error?w.message:String(w)}});if(r("vm_hands.session_closed",{close_code:v.closeCode,reason:v.closeReason.slice(0,120),registered:i.deviceId!==null}),v.closeCode===4401||i.attest==="refused")return;if(e.signal.aborted)return;if(i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline");if(i.served)i.served=!1,k=0;let I=v.closeReason==="drain_reconnect"?0:v.closeReason==="vm_hands_register_retry"?_:v.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(k,5),2000):i.turns.size?Math.min(250*2**Math.min(k,5),5000,Math.max(0,i.lostAt+ye-Date.now())):Math.min(500*2**k,30000);if(await new Promise((w)=>setTimeout(w,I)),i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline")}}finally{await h("session_ended")}}async function Rn(e,n){let i=n.deviceId,r=e.log??(()=>{}),h=i?`/app/local-runtime/session?device_id=${encodeURIComponent(i)}`:on,m=`${e.apiOrigin.replace(/^http/,"ws")}${h}`,_=new WebSocket(m),k=0,v="",I=new Map,w=[],E=null,ce=new Promise((t)=>{_.onclose=(o)=>{k=o.code,v=o.reason;for(let s of I.values())s.reject(new D(`session closed ${o.code}`));for(let s of n.attestWaiters.splice(0))s(!1);I.clear(),t()}});_.onmessage=(t)=>{let o;try{o=JSON.parse(String(t.data))}catch{_.close(4400);return}if(o.t==="res"){let s=o;I.get(s.id)?.resolve({status:s.status,body:s.body}),I.delete(s.id);return}if(o.t==="reconnect"){let s=Math.max(0,Math.min(Number(o.after_ms)||0,Tn));r("vm_hands.drain_reconnect",{after_ms:s}),setTimeout(()=>{try{_.close(4001,"drain_reconnect")}catch{}},s).unref?.();return}if(!E?.(o))w.push(o)};let J=(t,o)=>new Promise((s,a)=>{let u=w.findIndex((p)=>t.includes(p.t));if(u>=0){s(w.splice(u,1)[0]);return}let f=setTimeout(()=>{E=null,a(new l("vm_hands_no_register",`no ${t.join("/")} in ${o} ms`))},o);E=(p)=>{if(!t.includes(p.t))return!1;return clearTimeout(f),E=null,s(p),!0}}),Y=(t)=>_.send(JSON.stringify(t)),q=(t,o)=>new Promise((s,a)=>{if(_.readyState!==WebSocket.OPEN){a(new D("session closed"));return}let u=sn(),f=typeof o.wait_ms==="number"?o.wait_ms:0,p=setTimeout(()=>{if(!I.delete(u))return;a(new D(`no answer to ${t.split("/").pop()} in ${f+Ne} ms`)),_.close(4000,"request_timeout")},f+Ne);I.set(u,{reject:(c)=>{clearTimeout(p),a(c)},resolve:({status:c,body:d})=>{clearTimeout(p);let g=null;try{g=d?JSON.parse(d):null}catch{}s({status:c,json:g})}}),Y({t:"req",id:u,path:`${an}${t}`,body:JSON.stringify(o)})}),be=()=>_.close(1001,"stopping");e.signal.addEventListener("abort",be,{once:!0});let le,X=new Map,Q=new Map,ue=!1,_e=new Set,me=Promise.resolve(),ke=()=>{ne().catch(()=>{return})},Z=!1;try{await new Promise((c,d)=>{let g=setTimeout(()=>d(Error("session open timeout")),En);_.onopen=()=>{clearTimeout(g),r("vm_hands.ws_open",{}),c()},_.onerror=()=>{clearTimeout(g),d(Error("session socket error"))}});let t=await J(["challenge"],5000);r("vm_hands.challenge",{});let o=[],s=null,a;if(i){Y(await e.agent.helloFrame(t.challenge,n.connection));let c=await J(["ready"],1e4);if(typeof c.vm_hands_connection==="string")n.connection=c.vm_hands_connection;if(a={device_id:i,...c.cadence?{cadence:c.cadence}:{}},typeof c.vm_hands_probe_script==="string"){if(s=c.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.reconnected",{device_id:i});let d=Array.isArray(c.vm_hands_binds)?c.vm_hands_binds:c.vm_hands_bind?[c.vm_hands_bind]:[];for(let[g,S]of[...n.turns]){if(d.some((T)=>T&&T.operation_id===S.claim.operation_id&&T.attempt_id===S.claim.attempt_id)){o.push(S),r("vm_hands.bound_resumed",{operation_id:S.claim.operation_id});continue}n.turns.delete(g),e.onTurn?.(g,null),de(S);let P=await L(n,e.agent,g).catch((T)=>ee(T,S,"vm_hands_bind_lost"));if(P)n.receipts.push({turn:S,failure:"vm_hands_bind_lost",unbound:P});r("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{Y(await e.agent.registerFrame(t.challenge)),r("vm_hands.register_sent",{});let c=await Promise.race([J(["registered","register_refused"],1e4),ce.then(()=>{throw new l(v==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(c.t==="register_refused")throw new l(c.code,"register refused");e.agent.registered();let d=c;if(a=d,n.deviceId=d.device_id,typeof d.vm_hands_connection==="string")n.connection=d.vm_hands_connection;if(typeof d.vm_hands_probe_script==="string"){if(s=d.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.registered",{device_id:a.device_id})}let u=async()=>{let c=await q("/heartbeat",await e.heartbeat());if(c.status>=300)throw Error(`heartbeat ${c.status}`)};await u();let f=a.cadence?.presence_interval_ms??30000;if(le=setInterval(()=>{u().catch(()=>_.close())},f),e.onHeartbeatNow?.(()=>{u().catch(()=>_.close())}),n.request=q,ce.then(()=>{if(n.request===q)n.request=null}),s&&n.attest!=="accepted"&&e.agent.phase==="registered"&&!n.turns.size)ze(s,t.challenge);let p=(c,d)=>{Q.set(c,d().catch(async(g)=>{if(await Se(g,c),g instanceof D)_.close();else await ne().catch(()=>{return})}).finally(()=>{Q.delete(c)}))};n.flushReceipts=ke;try{await ne();for(let c of o)c.flush=()=>Ie(c),c.flush(),p(c.claim.attempt_id,()=>Pe(c));while(!e.signal.aborted&&_.readyState===WebSocket.OPEN){let c=await q("/operations/claim",{wait_ms:Math.min(a.cadence?.claim_wait_ms??Ce,Ce)});if(c.status===204||!c.json)continue;if(c.status>=300)throw Error(`claim ${c.status}`);let d=c.json;if(d.capability==="hands.connect"){if(Q.has(d.attempt_id)){O({claim:d,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}p(d.attempt_id,()=>Fe(d))}else Ke(d).catch(()=>{return})}}catch(c){await Se(c,null)}}finally{if(le)clearInterval(le);e.signal.removeEventListener("abort",be);for(let t of n.turns.values())t.flush=null;if(n.flushReceipts===ke)n.flushReceipts=null;_.close(),await ce,await Promise.all([...Q.values()]);for(let t of e.agent.liveBindIds){if(n.turns.has(t))continue;let o=X.get(t),s=o?{...o,eventSeq:o.eventSeq+1}:null,a=await L(n,e.agent,t).catch((u)=>s?ee(u,s,"vm_hands_bind_lost"):null);if(a&&s)n.receipts.push({turn:s,failure:"vm_hands_bind_lost",unbound:a});r("vm_hands.bound_dropped",{reason:"bound_after_loss"})}}return{closeCode:k,closeReason:v};async function Se(t,o){if(t instanceof D){if(!ue&&n.turns.size)n.lostAt=Date.now();ue=!0}else{let s=o!==null?[o]:[...new Set([...n.turns.keys(),...e.agent.liveBindIds])];if(o===null)ue=!0;for(let a of s){let u=n.turns.get(a);if(n.turns.delete(a),u)de(u),e.onTurn?.(a,null);if(e.agent.liveBindIds.includes(a)){let f=X.get(a)??u,p=f?{...f,eventSeq:f.eventSeq+1}:null,c=await L(n,e.agent,a).catch((d)=>p?ee(d,p,"vm_hands_bind_lost"):null);if(c&&p)n.receipts.push({turn:p,failure:"vm_hands_bind_lost",unbound:c})}}}r("vm_hands.session_lost",{error:t instanceof Error?t.message:String(t),bound_kept:n.turns.size})}function O(t,o=q){let s=o,a=t.claim,u={attempt_id:a.attempt_id,attempt_token:a.attempt_token},f=encodeURIComponent(a.operation_id);return{fence:u,op:f,complete:(c,d={})=>s(`/operations/${f}/complete`,{...u,status:c,...d}),emit:(c,d)=>{let g=(t.chain??Promise.resolve()).catch(()=>{return}).then(()=>p(c,d));return t.chain=g,g}};async function p(c,d){let g=t.eventSeq,S=(R)=>s(`/operations/${f}/events`,{...u,event_seq_start:R,events:[{kind:c,payload:{sequence:R,capability:String(a.capability??"hands.connect"),data:d}}]}),P=g,T=await S(P),M=T.status===409?T.json?.expected_event_seq:void 0;if(typeof M==="number"&&M>=0&&M!==g)P=M,T=await S(P);if(T.status<300)t.eventSeq=P+1;return T}}function We(t){return(o,s)=>new Promise((a,u)=>{if(n.turns.get(t.claim.attempt_id)!==t){u(Error("vm_hands_attempt_ended"));return}if(t.outbox??=[],t.outbox.length>=kn){u(Error("vm_hands_outbox_full"));return}t.outbox.push({kind:o,data:s,resolve:a,reject:u}),t.flush?.()})}function Ie(t){if(_e.has(t))return;_e.add(t),(async()=>{try{while(t.outbox?.length&&n.turns.get(t.claim.attempt_id)===t&&_.readyState===WebSocket.OPEN){let o=t.outbox[0],s;try{s=await O(t).emit(o.kind,o.data)}catch(a){if(a instanceof D)return;s={status:500}}if(t.outbox.shift(),s.status<300)o.resolve();else o.reject(Error(`${o.kind} refused ${s.status}`))}}finally{_e.delete(t)}})()}async function ze(t,o){try{let s=await e.agent.attestFrame(t,o);if(_.readyState!==WebSocket.OPEN)return;Y(s);let a=await J(["attested","attest_refused"],15000);n.attest=a.t==="attested"?"accepted":"refused";for(let u of n.attestWaiters.splice(0))u(n.attest==="accepted");if(r("vm_hands.attest",{result:n.attest,exit_code:s.exit_code,...a.t==="attest_refused"?{code:String(a.code??"")}:{}}),n.attest==="refused")_.close(4401,"attest_refused")}catch(s){r("vm_hands.attest_failed",{code:s instanceof l?s.code:"probe_error"});for(let a of n.attestWaiters.splice(0))a(!1);if(n.attest!=="accepted")_.close(4000,"attest_unanswered")}}async function Fe(t){let o=Z&&n.attest==="pending",s=t.vm_hands_attest,a=s;if(n.attest==="refused"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(a==="accepted"){if(!o&&n.attest!=="accepted"){n.attest="accepted";for(let b of n.attestWaiters.splice(0))b(!0)}}else if(a!=="pending"||!o&&n.attest!=="accepted"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(n.attest!=="accepted"){let b=Date.parse(t.lease_until)-Date.now()-5000,B=Math.max(0,Math.min(ae,Number.isFinite(b)?b:ae));if(!await new Promise((ie)=>{let y=setTimeout(()=>ie(!1),B);n.attestWaiters.push((x)=>{clearTimeout(y),ie(x)})})){await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let u={claim:t,eventSeq:0},{complete:f,emit:p}=O(u),c;try{if(t.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not hands.connect");c=!pe(t)}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_invalid"});return}let d,g=null,S=!1,P=(()=>{try{return ve(t).session_id.toLowerCase()}catch{return String(t.run_id)}})();n.bindsStarting.set(P,(n.bindsStarting.get(P)??0)+1);try{let b=await In(n,P);if(b)r("vm_hands.person_terminals_closed",{count:b});let B=ve(t),j=e.agent.bind(B);if(B.workspace_deferred)S=!0,g=He(u,()=>S);d=await j}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_failed"});return}finally{S=!1;let b=(n.bindsStarting.get(P)??1)-1;if(b>0)n.bindsStarting.set(P,b);else n.bindsStarting.delete(P)}let T=g?await g:-1,M={...d.ready_data??e.readyData({launchId:d.launch_id,claim:t})};if(c)delete M.environment_installed;let R=!c&&d.snapshot_revision!==null&&d.snapshot_id!==null?{environment_installed:{snapshot_id:d.snapshot_id,installed_revision:d.snapshot_revision}}:{};X.set(t.attempt_id,{claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:-1});let F={...M,...R,vm_hands:{layout:d.layout,policy_digest:d.policy_digest,launch_id:d.launch_id}},te=Date.now()+yn,U=1,N=await p("hands.ready",F);while(bn(N.status)&&!e.signal.aborted){let b=$e(U);if(Date.now()+b>=te)break;await new Promise((B)=>setTimeout(B,b)),U++,N=await p("hands.ready",F)}if(U>1)r("vm_hands.ready_retried",{attempts:U,status_class:`${Math.floor(N.status/100)}xx`});if(X.delete(t.attempt_id),N.status>=300){await Ge(n,t.attempt_id),await e.agent.boundRefused(t.attempt_id),await f("failed",{error_code:Be(N.json?.error,"vm_hands_probe_failed")});return}let C={claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:T};n.turns.set(t.attempt_id,C),C.flush=()=>Ie(C),e.onTurn?.(t.attempt_id,We(C)),await Pe(C)}async function He(t,o){let{fence:s,op:a}=O(t),u=t.claim.attempt_id,f=-1;try{for(;;){let p=await q(`/operations/${a}/heartbeat`,{...s,control_ack_seq:f,wait_ms:we});if(!o())return f;if(p.status>=300)return e.agent.abandonWorkspaceGrant(u),f;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=f)continue;if(f=d.seq,d.kind===si)return r("vm_hands.workspace_granted",{}),e.agent.grantWorkspace(u),f;return r("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(d.kind)?d.kind:"other"}),e.agent.abandonWorkspaceGrant(u),f}}}catch{return e.agent.abandonWorkspaceGrant(u),f}}async function Pe(t){let{fence:o,op:s}=O(t),a=null,u=null,f=e.agent.executorExited(t.claim.attempt_id).then((p)=>(u=p,null));e:for(;;){let p=await Promise.race([f,q(`/operations/${s}/heartbeat`,{...o,control_ack_seq:t.ackSeq,wait_ms:we})]);if(!p){a="vm_hands_executor_exited",r("vm_hands.executor_exited",{reason:u});break}if(p.status>=300)break;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=t.ackSeq)continue;if(d.kind==="operation.cancel"||d.kind==="cancel"){t.ackSeq=d.seq;break e}if(d.kind===vt)try{await Le(t,d.payload??{})}catch(g){if(g instanceof D)throw g;a=g instanceof l?g.code:"environment_unavailable";let S=g&&typeof g==="object"&&"code"in g&&typeof g.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(g.code)?g.code:null;r("vm_hands.environment_refused",{code:a,cause:S});break e}t.ackSeq=d.seq}}await Ve(t,a)}async function ge(t,o){let s=Date.now()+un;for(;;){let a=n.request;if(a)try{return await a(t,o)}catch(u){if(!(u instanceof D))throw u}if(Date.now()>=s||e.signal.aborted)throw new D("kept operation has no live session");await new Promise((u)=>setTimeout(u,500))}}async function Ke(t){let o=t,s={claim:o,eventSeq:0},a=String(t.capability??""),u=a===ln,{complete:f,emit:p,fence:c,op:d}={...O(s,ge)},g=t.vm_hands_origin==="person"?"person":"model";if(!e.executeOp){await f("failed",{error_code:"vm_hands_op_unsupported"});return}if(t.vm_hands_attest==="accepted"&&n.attest==="pending"&&!(Z&&n.attest==="pending")){n.attest="accepted";for(let y of n.attestWaiters.splice(0))y(!0)}if(n.attest!=="accepted"){let y=Date.parse(String(t.lease_until??""))-Date.now()-5000,x=n.attest==="refused"?0:Math.max(0,Math.min(ae,Number.isFinite(y)?y:ae));if(!(x>0&&await new Promise((re)=>{let Je=setTimeout(()=>re(!1),x);n.attestWaiters.push((Ye)=>{clearTimeout(Je),re(Ye)})}))){await f("failed",{error_code:"vm_hands_unattested"});return}}let S=e.agent.bindIdForRun(o.run_id);if(g==="model"&&S===null){await f("failed",{error_code:"vm_hands_not_bound"});return}let P=a==="pty.start"&&g==="person"&&!t.authority,T=P?Pn(t):null;if(P&&((y)=>y===null?e.agent.liveBindIds.length>0||n.bindsStarting.size>0:e.agent.liveSessionIds.includes(y)||n.bindsStarting.has(y))(T)){await f("failed",{error_code:"vm_hands_bound"});return}if(cn.has(a)&&!P&&e.agent.liveBindIds.length===0){await f("failed",{error_code:"vm_hands_not_bound"});return}let R=new AbortController,F=()=>R.abort();e.signal.addEventListener("abort",F,{once:!0});let te,U=new Promise((y)=>{te=y}),N={abort:R,settled:U},C=P?{...N,session:T}:null;if(C)n.personTerminals.add(C);if(g==="model"&&S&&a!=="preview.serve.v1"){let y=n.modelOps.get(S)??new Set;y.add(N),n.modelOps.set(S,y),await e.agent.environmentInstalled(S,_n,R.signal)}let b=-1,B=!1,j=!1,ie=u?void 0:setInterval(()=>{if(j)return;j=!0,ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:0}).then((y)=>{if(y.status>=300){R.abort();return}let x=y.json?.controls??[];for(let A of x)if(b=Math.max(b,A.seq),A.kind==="operation.cancel"||A.kind==="cancel")R.abort()},()=>R.abort()).finally(()=>{j=!1})},dn);if(u)(async()=>{while(!B&&!R.signal.aborted){let y;try{y=await ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:we})}catch{R.abort();return}if(B)return;if(y.status>=300){R.abort();return}let x=(y.json?.controls??[]).slice().sort((A,re)=>A.seq-re.seq);for(let A of x){if(A.seq<=b)continue;if(A.kind==="operation.cancel"||A.kind==="cancel")R.abort();else await e.controlOp?.({claim:t,control:A}).catch(()=>!1);b=A.seq}}})();try{let y=await e.executeOp({kind:g,claim:t,...g==="model"&&S?{bindId:S}:{},signal:R.signal,emit:async(A)=>{await p(A.kind,A.data??{})}}),x=await f(y.status,{...y.result?{result:y.result}:{},...y.error_code?{error_code:Be(y.error_code,"vm_hands_op_failed")}:{}});e.opCompleted?.({claim:t,status:y.status,acknowledged:x.status<300}),r("vm_hands.op",{capability:a,kind:g,status:y.status,code:y.error_code??null,...x.status>=300?{complete_status:x.status,complete_error:String(x.json?.error??"").slice(0,64)}:{}})}finally{if(B=!0,clearInterval(ie),e.signal.removeEventListener("abort",F),S)n.modelOps.get(S)?.delete(N);if(C)n.personTerminals.delete(C);te()}}async function Ve(t,o){let s=t.claim.attempt_id;if(n.turns.get(s)===t)n.turns.delete(s);e.onTurn?.(s,null),de(t);let a=await L(n,e.agent,s).catch((u)=>ee(u,t,o));if(!a)return;n.receipts.push({turn:t,failure:o,unbound:a}),await ne()}function ee(t,o,s){let a=je(t);return r("vm_hands.unbind_unverified",{operation_id:o.claim.operation_id,code:a,attempt:0}),O(o).emit(ai,{code:a}).catch(()=>{return}),Sn(n,e.agent,{turn:o,failure:s},e.signal,r),null}function ne(){return me=me.then(Ee,Ee),me}async function Ee(){while(n.receipts.length){let{turn:t,failure:o,unbound:s}=n.receipts[0],{complete:a,emit:u}=O(t);try{if(await u("hands.stopped",{...t.readyData,reason_code:o?"failed":"cancelled",killed_verified:s.killed_verified,shredded:s.shredded,...s.srt_fallbacks?{vm_hands_srt_fallbacks:s.srt_fallbacks}:{}}),o)await a("failed",{error_code:o});else await a("cancelled",{error_code:"driver_stopped"})}catch(f){if(f instanceof D)return}n.receipts.shift()}}async function Le(t,o){let{fence:s,op:a}=O(t),u=o.snapshot_id;if(o.version!==1||typeof u!=="string"||Object.keys(o).length!==2)throw new l("vm_hands_env_invalid","invalid environment delivery");let f=await q(`/operations/${a}/environment`,{...s,snapshot_id:u}),p=f.json?.environment_sealed;if(f.status!==200||!p||f.json?.payload!==void 0)throw new l("vm_hands_env_invalid","environment not delivered sealed");let c=await e.agent.deliverEnvironment({attemptId:t.claim.attempt_id,snapshotId:u,deviceId:n.deviceId??"",sealed:p});if((await q(`/operations/${a}/environment-ack`,{...s,...c})).status>=300)throw new l("vm_hands_env_ack_refused","environment ack refused")}}import{readFileSync as xn}from"fs";var An=performance.now();delete process.env.BUN_BE_BUN;var z=(e,n={})=>console.log(JSON.stringify({stage:e,ms:Math.round(performance.now()),...n}));async function On(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:m}=await import("./vm-hands-op-runner-7derp3tq.js");await m();return}z("parsed",{t0:Math.round(An)});let e="";try{e=xn(3,"utf8")}catch{}z("fd3_read",{bytes:e.length});let n=null;if(e.trim())try{n=JSON.parse(e)}catch{n=null}if(!n||typeof n!=="object"||Array.isArray(n))z(e.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:i,runVmHands:r}=await import("./vm-hands-runtime-gsjba3vg.js"),h=i(n);if(!h)z("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});try{await r(h,z)}catch(m){let _=m&&typeof m==="object"&&"code"in m&&typeof m.code==="string"?m.code:"error";throw z("failed",{code:_}),m}process.exit(0)}On();export{Hi,pn,zi};
4
+ `,_=se(i,`.job.env.${he(8).toString("hex")}`),k=Oe(_,W.O_WRONLY|W.O_CREAT|W.O_EXCL|W.O_NOFOLLOW,384);try{Me(k,m),xe(k)}finally{Ae(k)}return Qe(_,se(i,"job.env")),i}}function fe(e){try{let n=se(e,"job.env"),i=De(n).size,r=Oe(n,W.O_WRONLY|W.O_NOFOLLOW);try{Me(r,Buffer.alloc(i)),xe(r)}finally{Ae(r)}}catch{}Ze(e,{recursive:!0,force:!0})}function rn(e){if(e.length!==64)throw new l("vm_hands_signature_invalid","unexpected ECDSA signature length");let n=(h)=>{let m=0;while(m<h.length-1&&h[m]===0)m++;let _=h.subarray(m),k=_[0]&128?Uint8Array.of(0,..._):_;return Uint8Array.of(2,k.length,...k)},i=n(e.subarray(0,32)),r=n(e.subarray(32));return Uint8Array.of(48,i.length+r.length,...i,...r)}import{randomUUID as sn}from"crypto";var on="/app/local-runtime/session?register=vm_hands_v1",an="/app/local-runtime",Ce=25000,we=20000,dn=1e4,Ue=5000,cn=new Set(["pty.start","jobs.control","tunnel.open","tunnel.close"]),ln="preview.serve.v1",un=60000,ye=75000,_n=2000,mn=1e4,gn=new Set(["vm_hands_no_register","vm_hands_register_failed"]),hn=3,fn=20000,vn=250,wn=2000;function $e(e){let n=Math.min(vn*2**(e-1),wn);return Math.round(n/2+Math.random()*n/2)}var yn=5000;function bn(e){return e>=500||e===408||e===429}var ae=20000;function Be(e,n){return typeof e==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:n}class D extends Error{}var kn=64,qe=[1000,2000,4000,8000,15000,30000,60000,120000];function je(e){let n=e&&typeof e==="object"&&"code"in e?e.code:null;return typeof n==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(n)?n:"vm_hands_unbind_failed"}function Sn(e,n,i,r,h){let m=i.turn.claim.attempt_id,_=e.healing??=new Set;if(_.has(m))return;_.add(m);let k=i.turn.claim.operation_id;(async()=>{for(let[v,I]of qe.entries()){if(r.aborted)return;if(await new Promise((w)=>{let E=setTimeout(w,I);E.unref?.(),r.addEventListener("abort",()=>{clearTimeout(E),w()},{once:!0})}),r.aborted)return;try{let w=await n.retryUnbind(m);h("vm_hands.unbind_healed",{operation_id:k,attempt:v+1}),e.receipts.push({...i,unbound:w}),e.flushReceipts?.();return}catch(w){let E=je(w);if(h("vm_hands.unbind_unverified",{operation_id:k,code:E,attempt:v+1}),E==="vm_hands_unbind_unknown")return}}h("vm_hands.unbind_heal_exhausted",{operation_id:k,attempts:qe.length})})().finally(()=>_.delete(m))}async function Ge(e,n){let i=[...e.modelOps.get(n)??[]];for(let r of i)r.abort.abort();await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))])}async function In(e,n){let i=[...e.personTerminals].filter((r)=>r.session===null||r.session===n);for(let r of i)r.abort.abort();if(i.length)await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))]);return i.length}function Pn(e){let n=e.payload,i=n?.workspace?.kind==="managed"?n.workspace.workspaceId:void 0;return typeof i==="string"&&/^[0-9a-f-]{36}$/i.test(i)?i.toLowerCase():null}async function L(e,n,i){return await Ge(e,i),n.unbind(i)}function de(e){for(let n of e.outbox?.splice(0)??[])n.reject(Error("vm_hands_attempt_ended"))}var Ne=15000,En=1e4,Tn=1000;async function qi(e){let n=Date.now(),i={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:new Map},r=e.log??(()=>{}),h=async(k)=>{for(let[v,I]of[...i.turns]){i.turns.delete(v),e.onTurn?.(v,null),de(I);let w=await L(i,e.agent,v).catch(()=>null);if(w)i.receipts.push({turn:I,failure:"vm_hands_bind_lost",unbound:w});r("vm_hands.bound_dropped",{reason:k})}},m=0,_=0;try{for(let k=0;!e.signal.aborted;k++){let v=await Rn(e,i).catch((w)=>{if(w instanceof l&&i.deviceId===null&&w.code==="vm_hands_no_session"&&Date.now()-n<mn)return{closeCode:0,closeReason:"vm_hands_no_session"};if(w instanceof l&&i.deviceId===null&&gn.has(w.code)&&m<hn&&Date.now()-n<fn)return m++,_=$e(m),r("vm_hands.register_retry",{attempt:m,code:w.code,delay_ms:_}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(w instanceof l&&i.deviceId===null)throw w;return{closeCode:0,closeReason:w instanceof Error?w.message:String(w)}});if(r("vm_hands.session_closed",{close_code:v.closeCode,reason:v.closeReason.slice(0,120),registered:i.deviceId!==null}),v.closeCode===4401||i.attest==="refused")return;if(e.signal.aborted)return;if(i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline");if(i.served)i.served=!1,k=0;let I=v.closeReason==="drain_reconnect"?0:v.closeReason==="vm_hands_register_retry"?_:v.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(k,5),2000):i.turns.size?Math.min(250*2**Math.min(k,5),5000,Math.max(0,i.lostAt+ye-Date.now())):Math.min(500*2**k,30000);if(await new Promise((w)=>setTimeout(w,I)),i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline")}}finally{await h("session_ended")}}async function Rn(e,n){let i=n.deviceId,r=e.log??(()=>{}),h=i?`/app/local-runtime/session?device_id=${encodeURIComponent(i)}`:on,m=`${e.apiOrigin.replace(/^http/,"ws")}${h}`,_=new WebSocket(m),k=0,v="",I=new Map,w=[],E=null,ce=new Promise((t)=>{_.onclose=(o)=>{k=o.code,v=o.reason;for(let s of I.values())s.reject(new D(`session closed ${o.code}`));for(let s of n.attestWaiters.splice(0))s(!1);I.clear(),t()}});_.onmessage=(t)=>{let o;try{o=JSON.parse(String(t.data))}catch{_.close(4400);return}if(o.t==="res"){let s=o;I.get(s.id)?.resolve({status:s.status,body:s.body}),I.delete(s.id);return}if(o.t==="reconnect"){let s=Math.max(0,Math.min(Number(o.after_ms)||0,Tn));r("vm_hands.drain_reconnect",{after_ms:s}),setTimeout(()=>{try{_.close(4001,"drain_reconnect")}catch{}},s).unref?.();return}if(!E?.(o))w.push(o)};let J=(t,o)=>new Promise((s,a)=>{let u=w.findIndex((p)=>t.includes(p.t));if(u>=0){s(w.splice(u,1)[0]);return}let f=setTimeout(()=>{E=null,a(new l("vm_hands_no_register",`no ${t.join("/")} in ${o} ms`))},o);E=(p)=>{if(!t.includes(p.t))return!1;return clearTimeout(f),E=null,s(p),!0}}),Y=(t)=>_.send(JSON.stringify(t)),q=(t,o)=>new Promise((s,a)=>{if(_.readyState!==WebSocket.OPEN){a(new D("session closed"));return}let u=sn(),f=typeof o.wait_ms==="number"?o.wait_ms:0,p=setTimeout(()=>{if(!I.delete(u))return;a(new D(`no answer to ${t.split("/").pop()} in ${f+Ne} ms`)),_.close(4000,"request_timeout")},f+Ne);I.set(u,{reject:(c)=>{clearTimeout(p),a(c)},resolve:({status:c,body:d})=>{clearTimeout(p);let g=null;try{g=d?JSON.parse(d):null}catch{}s({status:c,json:g})}}),Y({t:"req",id:u,path:`${an}${t}`,body:JSON.stringify(o)})}),be=()=>_.close(1001,"stopping");e.signal.addEventListener("abort",be,{once:!0});let le,X=new Map,Q=new Map,ue=!1,_e=new Set,me=Promise.resolve(),ke=()=>{ne().catch(()=>{return})},Z=!1;try{await new Promise((c,d)=>{let g=setTimeout(()=>d(Error("session open timeout")),En);_.onopen=()=>{clearTimeout(g),r("vm_hands.ws_open",{}),c()},_.onerror=()=>{clearTimeout(g),d(Error("session socket error"))}});let t=await J(["challenge"],5000);r("vm_hands.challenge",{});let o=[],s=null,a;if(i){Y(await e.agent.helloFrame(t.challenge,n.connection));let c=await J(["ready"],1e4);if(typeof c.vm_hands_connection==="string")n.connection=c.vm_hands_connection;if(a={device_id:i,...c.cadence?{cadence:c.cadence}:{}},typeof c.vm_hands_probe_script==="string"){if(s=c.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.reconnected",{device_id:i});let d=Array.isArray(c.vm_hands_binds)?c.vm_hands_binds:c.vm_hands_bind?[c.vm_hands_bind]:[];for(let[g,S]of[...n.turns]){if(d.some((T)=>T&&T.operation_id===S.claim.operation_id&&T.attempt_id===S.claim.attempt_id)){o.push(S),r("vm_hands.bound_resumed",{operation_id:S.claim.operation_id});continue}n.turns.delete(g),e.onTurn?.(g,null),de(S);let P=await L(n,e.agent,g).catch((T)=>ee(T,S,"vm_hands_bind_lost"));if(P)n.receipts.push({turn:S,failure:"vm_hands_bind_lost",unbound:P});r("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{Y(await e.agent.registerFrame(t.challenge)),r("vm_hands.register_sent",{});let c=await Promise.race([J(["registered","register_refused"],1e4),ce.then(()=>{throw new l(v==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(c.t==="register_refused")throw new l(c.code,"register refused");e.agent.registered();let d=c;if(a=d,n.deviceId=d.device_id,typeof d.vm_hands_connection==="string")n.connection=d.vm_hands_connection;if(typeof d.vm_hands_probe_script==="string"){if(s=d.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.registered",{device_id:a.device_id})}let u=async()=>{let c=await q("/heartbeat",await e.heartbeat());if(c.status>=300)throw Error(`heartbeat ${c.status}`)};await u();let f=a.cadence?.presence_interval_ms??30000;if(le=setInterval(()=>{u().catch(()=>_.close())},f),e.onHeartbeatNow?.(()=>{u().catch(()=>_.close())}),n.request=q,ce.then(()=>{if(n.request===q)n.request=null}),s&&n.attest!=="accepted"&&e.agent.phase==="registered"&&!n.turns.size)ze(s,t.challenge);let p=(c,d)=>{Q.set(c,d().catch(async(g)=>{if(await Se(g,c),g instanceof D)_.close();else await ne().catch(()=>{return})}).finally(()=>{Q.delete(c)}))};n.flushReceipts=ke;try{await ne();for(let c of o)c.flush=()=>Ie(c),c.flush(),p(c.claim.attempt_id,()=>Pe(c));while(!e.signal.aborted&&_.readyState===WebSocket.OPEN){let c=await q("/operations/claim",{wait_ms:Math.min(a.cadence?.claim_wait_ms??Ce,Ce)});if(c.status===204||!c.json)continue;if(c.status>=300)throw Error(`claim ${c.status}`);let d=c.json;if(d.capability==="hands.connect"){if(Q.has(d.attempt_id)){O({claim:d,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}p(d.attempt_id,()=>Fe(d))}else Ke(d).catch(()=>{return})}}catch(c){await Se(c,null)}}finally{if(le)clearInterval(le);e.signal.removeEventListener("abort",be);for(let t of n.turns.values())t.flush=null;if(n.flushReceipts===ke)n.flushReceipts=null;_.close(),await ce,await Promise.all([...Q.values()]);for(let t of e.agent.liveBindIds){if(n.turns.has(t))continue;let o=X.get(t),s=o?{...o,eventSeq:o.eventSeq+1}:null,a=await L(n,e.agent,t).catch((u)=>s?ee(u,s,"vm_hands_bind_lost"):null);if(a&&s)n.receipts.push({turn:s,failure:"vm_hands_bind_lost",unbound:a});r("vm_hands.bound_dropped",{reason:"bound_after_loss"})}}return{closeCode:k,closeReason:v};async function Se(t,o){if(t instanceof D){if(!ue&&n.turns.size)n.lostAt=Date.now();ue=!0}else{let s=o!==null?[o]:[...new Set([...n.turns.keys(),...e.agent.liveBindIds])];if(o===null)ue=!0;for(let a of s){let u=n.turns.get(a);if(n.turns.delete(a),u)de(u),e.onTurn?.(a,null);if(e.agent.liveBindIds.includes(a)){let f=X.get(a)??u,p=f?{...f,eventSeq:f.eventSeq+1}:null,c=await L(n,e.agent,a).catch((d)=>p?ee(d,p,"vm_hands_bind_lost"):null);if(c&&p)n.receipts.push({turn:p,failure:"vm_hands_bind_lost",unbound:c})}}}r("vm_hands.session_lost",{error:t instanceof Error?t.message:String(t),bound_kept:n.turns.size})}function O(t,o=q){let s=o,a=t.claim,u={attempt_id:a.attempt_id,attempt_token:a.attempt_token},f=encodeURIComponent(a.operation_id);return{fence:u,op:f,complete:(c,d={})=>s(`/operations/${f}/complete`,{...u,status:c,...d}),emit:(c,d)=>{let g=(t.chain??Promise.resolve()).catch(()=>{return}).then(()=>p(c,d));return t.chain=g,g}};async function p(c,d){let g=t.eventSeq,S=(R)=>s(`/operations/${f}/events`,{...u,event_seq_start:R,events:[{kind:c,payload:{sequence:R,capability:String(a.capability??"hands.connect"),data:d}}]}),P=g,T=await S(P),M=T.status===409?T.json?.expected_event_seq:void 0;if(typeof M==="number"&&M>=0&&M!==g)P=M,T=await S(P);if(T.status<300)t.eventSeq=P+1;return T}}function We(t){return(o,s)=>new Promise((a,u)=>{if(n.turns.get(t.claim.attempt_id)!==t){u(Error("vm_hands_attempt_ended"));return}if(t.outbox??=[],t.outbox.length>=kn){u(Error("vm_hands_outbox_full"));return}t.outbox.push({kind:o,data:s,resolve:a,reject:u}),t.flush?.()})}function Ie(t){if(_e.has(t))return;_e.add(t),(async()=>{try{while(t.outbox?.length&&n.turns.get(t.claim.attempt_id)===t&&_.readyState===WebSocket.OPEN){let o=t.outbox[0],s;try{s=await O(t).emit(o.kind,o.data)}catch(a){if(a instanceof D)return;s={status:500}}if(t.outbox.shift(),s.status<300)o.resolve();else o.reject(Error(`${o.kind} refused ${s.status}`))}}finally{_e.delete(t)}})()}async function ze(t,o){try{let s=await e.agent.attestFrame(t,o);if(_.readyState!==WebSocket.OPEN)return;Y(s);let a=await J(["attested","attest_refused"],15000);n.attest=a.t==="attested"?"accepted":"refused";for(let u of n.attestWaiters.splice(0))u(n.attest==="accepted");if(r("vm_hands.attest",{result:n.attest,exit_code:s.exit_code,...a.t==="attest_refused"?{code:String(a.code??"")}:{}}),n.attest==="refused")_.close(4401,"attest_refused")}catch(s){r("vm_hands.attest_failed",{code:s instanceof l?s.code:"probe_error"});for(let a of n.attestWaiters.splice(0))a(!1);if(n.attest!=="accepted")_.close(4000,"attest_unanswered")}}async function Fe(t){let o=Z&&n.attest==="pending",s=t.vm_hands_attest,a=s;if(n.attest==="refused"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(a==="accepted"){if(!o&&n.attest!=="accepted"){n.attest="accepted";for(let b of n.attestWaiters.splice(0))b(!0)}}else if(a!=="pending"||!o&&n.attest!=="accepted"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(n.attest!=="accepted"){let b=Date.parse(t.lease_until)-Date.now()-5000,B=Math.max(0,Math.min(ae,Number.isFinite(b)?b:ae));if(!await new Promise((ie)=>{let y=setTimeout(()=>ie(!1),B);n.attestWaiters.push((x)=>{clearTimeout(y),ie(x)})})){await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let u={claim:t,eventSeq:0},{complete:f,emit:p}=O(u),c;try{if(t.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not hands.connect");c=!pe(t)}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_invalid"});return}let d,g=null,S=!1,P=(()=>{try{return ve(t).session_id.toLowerCase()}catch{return String(t.run_id)}})();n.bindsStarting.set(P,(n.bindsStarting.get(P)??0)+1);try{let b=await In(n,P);if(b)r("vm_hands.person_terminals_closed",{count:b});let B=ve(t),j=e.agent.bind(B);if(B.workspace_deferred)S=!0,g=He(u,()=>S);d=await j}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_failed"});return}finally{S=!1;let b=(n.bindsStarting.get(P)??1)-1;if(b>0)n.bindsStarting.set(P,b);else n.bindsStarting.delete(P)}let T=g?await g:-1,M={...d.ready_data??e.readyData({launchId:d.launch_id,claim:t})};if(c)delete M.environment_installed;let R=!c&&d.snapshot_revision!==null&&d.snapshot_id!==null?{environment_installed:{snapshot_id:d.snapshot_id,installed_revision:d.snapshot_revision}}:{};X.set(t.attempt_id,{claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:-1});let F={...M,...R,vm_hands:{layout:d.layout,policy_digest:d.policy_digest,launch_id:d.launch_id}},te=Date.now()+yn,U=1,N=await p("hands.ready",F);while(bn(N.status)&&!e.signal.aborted){let b=$e(U);if(Date.now()+b>=te)break;await new Promise((B)=>setTimeout(B,b)),U++,N=await p("hands.ready",F)}if(U>1)r("vm_hands.ready_retried",{attempts:U,status_class:`${Math.floor(N.status/100)}xx`});if(X.delete(t.attempt_id),N.status>=300){await Ge(n,t.attempt_id),await e.agent.boundRefused(t.attempt_id),await f("failed",{error_code:Be(N.json?.error,"vm_hands_probe_failed")});return}let C={claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:T};n.turns.set(t.attempt_id,C),C.flush=()=>Ie(C),e.onTurn?.(t.attempt_id,We(C)),await Pe(C)}async function He(t,o){let{fence:s,op:a}=O(t),u=t.claim.attempt_id,f=-1;try{for(;;){let p=await q(`/operations/${a}/heartbeat`,{...s,control_ack_seq:f,wait_ms:we});if(!o())return f;if(p.status>=300)return e.agent.abandonWorkspaceGrant(u),f;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=f)continue;if(f=d.seq,d.kind===ai)return r("vm_hands.workspace_granted",{}),e.agent.grantWorkspace(u),f;return r("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(d.kind)?d.kind:"other"}),e.agent.abandonWorkspaceGrant(u),f}}}catch{return e.agent.abandonWorkspaceGrant(u),f}}async function Pe(t){let{fence:o,op:s}=O(t),a=null,u=null,f=e.agent.executorExited(t.claim.attempt_id).then((p)=>(u=p,null));e:for(;;){let p=await Promise.race([f,q(`/operations/${s}/heartbeat`,{...o,control_ack_seq:t.ackSeq,wait_ms:we})]);if(!p){a="vm_hands_executor_exited",r("vm_hands.executor_exited",{reason:u});break}if(p.status>=300)break;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=t.ackSeq)continue;if(d.kind==="operation.cancel"||d.kind==="cancel"){t.ackSeq=d.seq;break e}if(d.kind===vt)try{await Le(t,d.payload??{})}catch(g){if(g instanceof D)throw g;a=g instanceof l?g.code:"environment_unavailable";let S=g&&typeof g==="object"&&"code"in g&&typeof g.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(g.code)?g.code:null;r("vm_hands.environment_refused",{code:a,cause:S});break e}t.ackSeq=d.seq}}await Ve(t,a)}async function ge(t,o){let s=Date.now()+un;for(;;){let a=n.request;if(a)try{return await a(t,o)}catch(u){if(!(u instanceof D))throw u}if(Date.now()>=s||e.signal.aborted)throw new D("kept operation has no live session");await new Promise((u)=>setTimeout(u,500))}}async function Ke(t){let o=t,s={claim:o,eventSeq:0},a=String(t.capability??""),u=a===ln,{complete:f,emit:p,fence:c,op:d}={...O(s,ge)},g=t.vm_hands_origin==="person"?"person":"model";if(!e.executeOp){await f("failed",{error_code:"vm_hands_op_unsupported"});return}if(t.vm_hands_attest==="accepted"&&n.attest==="pending"&&!(Z&&n.attest==="pending")){n.attest="accepted";for(let y of n.attestWaiters.splice(0))y(!0)}if(n.attest!=="accepted"){let y=Date.parse(String(t.lease_until??""))-Date.now()-5000,x=n.attest==="refused"?0:Math.max(0,Math.min(ae,Number.isFinite(y)?y:ae));if(!(x>0&&await new Promise((re)=>{let Je=setTimeout(()=>re(!1),x);n.attestWaiters.push((Ye)=>{clearTimeout(Je),re(Ye)})}))){await f("failed",{error_code:"vm_hands_unattested"});return}}let S=e.agent.bindIdForRun(o.run_id);if(g==="model"&&S===null){await f("failed",{error_code:"vm_hands_not_bound"});return}let P=a==="pty.start"&&g==="person"&&!t.authority,T=P?Pn(t):null;if(P&&((y)=>y===null?e.agent.liveBindIds.length>0||n.bindsStarting.size>0:e.agent.liveSessionIds.includes(y)||n.bindsStarting.has(y))(T)){await f("failed",{error_code:"vm_hands_bound"});return}if(cn.has(a)&&!P&&e.agent.liveBindIds.length===0){await f("failed",{error_code:"vm_hands_not_bound"});return}let R=new AbortController,F=()=>R.abort();e.signal.addEventListener("abort",F,{once:!0});let te,U=new Promise((y)=>{te=y}),N={abort:R,settled:U},C=P?{...N,session:T}:null;if(C)n.personTerminals.add(C);if(g==="model"&&S&&a!=="preview.serve.v1"){let y=n.modelOps.get(S)??new Set;y.add(N),n.modelOps.set(S,y),await e.agent.environmentInstalled(S,_n,R.signal)}let b=-1,B=!1,j=!1,ie=u?void 0:setInterval(()=>{if(j)return;j=!0,ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:0}).then((y)=>{if(y.status>=300){R.abort();return}let x=y.json?.controls??[];for(let A of x)if(b=Math.max(b,A.seq),A.kind==="operation.cancel"||A.kind==="cancel")R.abort()},()=>R.abort()).finally(()=>{j=!1})},dn);if(u)(async()=>{while(!B&&!R.signal.aborted){let y;try{y=await ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:we})}catch{R.abort();return}if(B)return;if(y.status>=300){R.abort();return}let x=(y.json?.controls??[]).slice().sort((A,re)=>A.seq-re.seq);for(let A of x){if(A.seq<=b)continue;if(A.kind==="operation.cancel"||A.kind==="cancel")R.abort();else await e.controlOp?.({claim:t,control:A}).catch(()=>!1);b=A.seq}}})();try{let y=await e.executeOp({kind:g,claim:t,...g==="model"&&S?{bindId:S}:{},signal:R.signal,emit:async(A)=>{await p(A.kind,A.data??{})}}),x=await f(y.status,{...y.result?{result:y.result}:{},...y.error_code?{error_code:Be(y.error_code,"vm_hands_op_failed")}:{}});e.opCompleted?.({claim:t,status:y.status,acknowledged:x.status<300}),r("vm_hands.op",{capability:a,kind:g,status:y.status,code:y.error_code??null,...x.status>=300?{complete_status:x.status,complete_error:String(x.json?.error??"").slice(0,64)}:{}})}finally{if(B=!0,clearInterval(ie),e.signal.removeEventListener("abort",F),S)n.modelOps.get(S)?.delete(N);if(C)n.personTerminals.delete(C);te()}}async function Ve(t,o){let s=t.claim.attempt_id;if(n.turns.get(s)===t)n.turns.delete(s);e.onTurn?.(s,null),de(t);let a=await L(n,e.agent,s).catch((u)=>ee(u,t,o));if(!a)return;n.receipts.push({turn:t,failure:o,unbound:a}),await ne()}function ee(t,o,s){let a=je(t);return r("vm_hands.unbind_unverified",{operation_id:o.claim.operation_id,code:a,attempt:0}),O(o).emit(ci,{code:a}).catch(()=>{return}),Sn(n,e.agent,{turn:o,failure:s},e.signal,r),null}function ne(){return me=me.then(Ee,Ee),me}async function Ee(){while(n.receipts.length){let{turn:t,failure:o,unbound:s}=n.receipts[0],{complete:a,emit:u}=O(t);try{if(await u("hands.stopped",{...t.readyData,reason_code:o?"failed":"cancelled",killed_verified:s.killed_verified,shredded:s.shredded,...s.srt_fallbacks?{vm_hands_srt_fallbacks:s.srt_fallbacks}:{}}),o)await a("failed",{error_code:o});else await a("cancelled",{error_code:"driver_stopped"})}catch(f){if(f instanceof D)return}n.receipts.shift()}}async function Le(t,o){let{fence:s,op:a}=O(t),u=o.snapshot_id;if(o.version!==1||typeof u!=="string"||Object.keys(o).length!==2)throw new l("vm_hands_env_invalid","invalid environment delivery");let f=await q(`/operations/${a}/environment`,{...s,snapshot_id:u}),p=f.json?.environment_sealed;if(f.status!==200||!p||f.json?.payload!==void 0)throw new l("vm_hands_env_invalid","environment not delivered sealed");let c=await e.agent.deliverEnvironment({attemptId:t.claim.attempt_id,snapshotId:u,deviceId:n.deviceId??"",sealed:p});if((await q(`/operations/${a}/environment-ack`,{...s,...c})).status>=300)throw new l("vm_hands_env_ack_refused","environment ack refused")}}import{readFileSync as xn}from"fs";var An=performance.now();delete process.env.BUN_BE_BUN;var z=(e,n={})=>console.log(JSON.stringify({stage:e,ms:Math.round(performance.now()),...n}));async function On(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:m}=await import("./vm-hands-op-runner-mzyesbyf.js");await m();return}z("parsed",{t0:Math.round(An)});let e="";try{e=xn(3,"utf8")}catch{}z("fd3_read",{bytes:e.length});let n=null;if(e.trim())try{n=JSON.parse(e)}catch{n=null}if(!n||typeof n!=="object"||Array.isArray(n))z(e.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:i,runVmHands:r}=await import("./vm-hands-runtime-zhsw99cm.js"),h=i(n);if(!h)z("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});try{await r(h,z)}catch(m){let _=m&&typeof m==="object"&&"code"in m&&typeof m.code==="string"?m.code:"error";throw z("failed",{code:_}),m}process.exit(0)}On();export{zi,pn,qi};