@reason-machines/cli-linux-x64 0.2.396 → 0.2.398

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 (93) hide show
  1. package/bin/reason +1 -1
  2. package/bin/runtime/srt/sandbox-runtime.mjs +38 -38
  3. package/bin/vm-hands/api-5fk9zhcg.js +2 -0
  4. package/bin/vm-hands/api-credentials-y4f0h1hq.js +2 -0
  5. package/bin/vm-hands/{ask-relay-gzds2969.js → ask-relay-t4m6n3zq.js} +3 -3
  6. package/bin/vm-hands/connect-cli-vq039qgz.js +2 -0
  7. package/bin/vm-hands/{custom-endpoint-device-qd3zcysz.js → custom-endpoint-device-2hzektq4.js} +1 -1
  8. package/bin/vm-hands/desktop-account-skdwydhn.js +2 -0
  9. package/bin/vm-hands/{device-workspace-ntckpym4.js → device-workspace-1n8aaz1j.js} +1 -1
  10. package/bin/vm-hands/{hands-worker-source-p6530nj7.js → hands-worker-source-2x76smhs.js} +1 -1
  11. package/bin/vm-hands/{index-z6q2j1e0.js → index-58750fwy.js} +1 -1
  12. package/bin/vm-hands/{install-receipt-kqayxfsn.js → install-receipt-jddye4b2.js} +1 -1
  13. package/bin/vm-hands/local-automation-azdzmmhp.js +2 -0
  14. package/bin/vm-hands/local-capabilities-vvpsze8k.js +2 -0
  15. package/bin/vm-hands/local-desktop-users-aqjt40m2.js +2 -0
  16. package/bin/vm-hands/local-display-mac-r6nm1tb1.js +2 -0
  17. package/bin/vm-hands/local-display-session-061jhxjw.js +2 -0
  18. package/bin/vm-hands/local-pty-session-ysfq0rq1.js +2 -0
  19. package/bin/vm-hands/{managed-runtime-5dv9fvs8.js → managed-runtime-4rg0bkrp.js} +1 -1
  20. package/bin/vm-hands/network-contract-h7dq97gc.js +2 -0
  21. package/bin/vm-hands/package-9c803cqw.js +2 -0
  22. package/bin/vm-hands/permissions-y7petg2m.js +2 -0
  23. package/bin/vm-hands/{reason-hands-protocol-90kpyg4s.js → reason-hands-protocol-bexqzhq5.js} +1 -1
  24. package/bin/vm-hands/{serve-service-p7j53hva.js → serve-service-bxyvbaf8.js} +1 -1
  25. package/bin/vm-hands/{status-ss83z3ah.js → status-1md7695q.js} +2 -2
  26. package/bin/vm-hands/version-r3x5z0dj.js +2 -0
  27. package/bin/vm-hands/{vm-hands-entry-lite-bgs4zjkf.js → vm-hands-entry-lite-04y4b7c6.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-qvj5560v.js → vm-hands-entry-lite-09yt840b.js} +5 -5
  29. package/bin/vm-hands/{vm-hands-entry-lite-e1cbqqqw.js → vm-hands-entry-lite-0a1ch6wx.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-q5h859gg.js → vm-hands-entry-lite-0kzefw0a.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-f9akybcm.js → vm-hands-entry-lite-18kfytsa.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-0nd56w02.js → vm-hands-entry-lite-39wk67c3.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-29f3m7x2.js → vm-hands-entry-lite-3pecyp8y.js} +1 -1
  34. package/bin/vm-hands/{vm-hands-entry-lite-f50vcbjg.js → vm-hands-entry-lite-4yw77epm.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-5d31qv44.js → vm-hands-entry-lite-4yw8vx5h.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-sbn9bmf7.js → vm-hands-entry-lite-6ffdqdyw.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-gk3y60ap.js → vm-hands-entry-lite-923jmcs3.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-kbjh8x26.js → vm-hands-entry-lite-ajmxhzs9.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-xhbjkkk5.js → vm-hands-entry-lite-bw28d85m.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-gc7prfyz.js → vm-hands-entry-lite-ce3vtmdk.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-2sx1a43v.js → vm-hands-entry-lite-ecgyzbdp.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-hx4w3r63.js → vm-hands-entry-lite-ew7amfaf.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-t839nkd2.js → vm-hands-entry-lite-fgdtrsf4.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-e99ftdr6.js → vm-hands-entry-lite-fkkmhfjc.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-6nj2ejfh.js → vm-hands-entry-lite-h3vmfk68.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-69n9q5f1.js → vm-hands-entry-lite-hkvkfq0z.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-ps9gjbs5.js → vm-hands-entry-lite-ht482g94.js} +2 -2
  48. package/bin/vm-hands/vm-hands-entry-lite-jkcbweew.js +458 -0
  49. package/bin/vm-hands/{vm-hands-entry-lite-1cs1jy20.js → vm-hands-entry-lite-k90ysszf.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-09426bhf.js → vm-hands-entry-lite-mkrwdts5.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-ek5r435m.js → vm-hands-entry-lite-mkynexaq.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-sjn5yjvx.js → vm-hands-entry-lite-mrw8bv5s.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-cfwke54v.js → vm-hands-entry-lite-n71rv7kv.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-entry-lite-6zrz9pkm.js → vm-hands-entry-lite-nsbsmrva.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-eztjchde.js → vm-hands-entry-lite-qv9j0tb5.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-v0kpksbf.js → vm-hands-entry-lite-qwxmr70t.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-j2w231k5.js → vm-hands-entry-lite-qxx37a43.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-tys29eyh.js → vm-hands-entry-lite-r67d5w6h.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-vqfpryez.js → vm-hands-entry-lite-rmaawtgm.js} +1 -1
  60. package/bin/vm-hands/{vm-hands-entry-lite-smrymax6.js → vm-hands-entry-lite-saemagkr.js} +1 -1
  61. package/bin/vm-hands/{vm-hands-entry-lite-eatqxe5y.js → vm-hands-entry-lite-shm5nhjk.js} +1 -1
  62. package/bin/vm-hands/{vm-hands-entry-lite-34h6rv5c.js → vm-hands-entry-lite-sqyf9q9z.js} +1 -1
  63. package/bin/vm-hands/{vm-hands-entry-lite-dq1459rx.js → vm-hands-entry-lite-vz6nt5sc.js} +1 -1
  64. package/bin/vm-hands/{vm-hands-entry-lite-t67cjjan.js → vm-hands-entry-lite-wdpx0750.js} +1 -1
  65. package/bin/vm-hands/{vm-hands-entry-lite-k4erfh5k.js → vm-hands-entry-lite-x64d3bdx.js} +1 -1
  66. package/bin/vm-hands/{vm-hands-entry-lite-tbn5dn91.js → vm-hands-entry-lite-xdfghcd0.js} +32 -32
  67. package/bin/vm-hands/{vm-hands-entry-lite-e4kdpq0t.js → vm-hands-entry-lite-xz9w76j7.js} +1 -1
  68. package/bin/vm-hands/{vm-hands-entry-lite-q62fwa20.js → vm-hands-entry-lite-z9y1sb0f.js} +1 -1
  69. package/bin/vm-hands/{vm-hands-entry-lite-sg0c4khn.js → vm-hands-entry-lite-zd4xbqsv.js} +2 -2
  70. package/bin/vm-hands/{vm-hands-entry-lite-w0hb7fnf.js → vm-hands-entry-lite-zxpa53zd.js} +3 -3
  71. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  72. package/bin/vm-hands/{vm-hands-executor-4z8mfd2d.js → vm-hands-executor-652ckfnw.js} +1 -1
  73. package/bin/vm-hands/vm-hands-op-runner-z3fqtf7t.js +2 -0
  74. package/bin/vm-hands/{vm-hands-runtime-tzy4hep5.js → vm-hands-runtime-79x8rs7b.js} +3 -3
  75. package/bin/vm-hands/worker-sandbox-0bwwxmxz.js +2 -0
  76. package/package.json +1 -1
  77. package/bin/vm-hands/api-credentials-200ret9z.js +0 -2
  78. package/bin/vm-hands/api-jcccjxss.js +0 -2
  79. package/bin/vm-hands/connect-cli-2v6pb882.js +0 -2
  80. package/bin/vm-hands/desktop-account-r5fsgx43.js +0 -2
  81. package/bin/vm-hands/local-automation-gg7cav41.js +0 -2
  82. package/bin/vm-hands/local-capabilities-6em6gns3.js +0 -2
  83. package/bin/vm-hands/local-desktop-users-7kbrnvba.js +0 -2
  84. package/bin/vm-hands/local-display-mac-0k5twcjj.js +0 -2
  85. package/bin/vm-hands/local-display-session-whzvcvse.js +0 -2
  86. package/bin/vm-hands/local-pty-session-a0fz1f9t.js +0 -2
  87. package/bin/vm-hands/network-contract-xgbrevt2.js +0 -2
  88. package/bin/vm-hands/package-x8ct3epg.js +0 -2
  89. package/bin/vm-hands/permissions-xxtp2y29.js +0 -2
  90. package/bin/vm-hands/version-9c07f7wf.js +0 -2
  91. package/bin/vm-hands/vm-hands-entry-lite-ygbggn2q.js +0 -458
  92. package/bin/vm-hands/vm-hands-op-runner-0kwhtm4z.js +0 -2
  93. package/bin/vm-hands/worker-sandbox-ecjj14h5.js +0 -2
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Gk as N}from"./vm-hands-entry-lite-ek5r435m.js";import{randomUUID as K}from"crypto";import{closeSync as L,constants as V,fstatSync as M,lstatSync as Z,mkdirSync as $,openSync as O,readFileSync as T,realpathSync as b,renameSync as U,unlinkSync as X,writeFileSync as Y}from"fs";import{dirname as g,resolve as z}from"path";var A=65536;function J(j){try{return Z(j),!0}catch(q){if(q instanceof Error&&"code"in q&&q.code==="ENOENT")return!1;throw q}}function I(j,q=!1){if(!J(j)){if(!q)throw Error("worker_state_missing");D(j),$(j,{mode:448})}let C=Z(j);if(!C.isDirectory()||C.isSymbolicLink()||!N(C)||b(j)!==z(j))throw Error("worker_state_directory_not_private_or_canonical")}function D(j){let q=g(j);if(!J(q))D(q),$(q,{mode:448});if(b(q)!==z(q))throw Error("worker_parent_not_canonical")}function u(j,q=A){let C=O(j,V.O_RDONLY|V.O_NOFOLLOW);try{let G=M(C);if(!G.isFile()||G.nlink!==1||!N(G)||G.size>q)throw Error("worker_file_not_private");return T(C,"utf8")}finally{L(C)}}function f(j,q,C=A){let G=JSON.stringify(q);if(G===void 0)throw Error("worker_file_invalid");let Q=G+`
2
+ import{Ik as N}from"./vm-hands-entry-lite-mkynexaq.js";import{randomUUID as K}from"crypto";import{closeSync as L,constants as V,fstatSync as M,lstatSync as Z,mkdirSync as $,openSync as O,readFileSync as T,realpathSync as b,renameSync as U,unlinkSync as X,writeFileSync as Y}from"fs";import{dirname as g,resolve as z}from"path";var A=65536;function J(j){try{return Z(j),!0}catch(q){if(q instanceof Error&&"code"in q&&q.code==="ENOENT")return!1;throw q}}function I(j,q=!1){if(!J(j)){if(!q)throw Error("worker_state_missing");D(j),$(j,{mode:448})}let C=Z(j);if(!C.isDirectory()||C.isSymbolicLink()||!N(C)||b(j)!==z(j))throw Error("worker_state_directory_not_private_or_canonical")}function D(j){let q=g(j);if(!J(q))D(q),$(q,{mode:448});if(b(q)!==z(q))throw Error("worker_parent_not_canonical")}function u(j,q=A){let C=O(j,V.O_RDONLY|V.O_NOFOLLOW);try{let G=M(C);if(!G.isFile()||G.nlink!==1||!N(G)||G.size>q)throw Error("worker_file_not_private");return T(C,"utf8")}finally{L(C)}}function f(j,q,C=A){let G=JSON.stringify(q);if(G===void 0)throw Error("worker_file_invalid");let Q=G+`
3
3
  `;if(Buffer.byteLength(Q,"utf8")>C)throw Error("worker_file_too_large");if(I(g(j)),J(j))u(j,C);let H=`${j}.${K()}`;try{Y(H,Q,{mode:384,flag:"wx"}),U(H,j)}finally{if(J(H))X(H)}}
4
4
  export{J as $c,I as ad,u as bd,f as cd};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var U=".reason/workspace",T="workspace_base",y="sessions",W="workspace_layout",g=".reason/workspace/sessions",B=/^[0-9a-f]{8}$/;function C(j){if(!J(j))return!1;let q=".reason/workspace/sessions/";if(!j.startsWith(q))return!1;let z=j.slice(q.length).split("/");return z.length===2&&B.test(z[0])}var G=4096,X="workspaces/pi";function J(j){if(typeof j!=="string"||!j||j.length>G)return!1;if(j.startsWith("/")||j.includes("\x00")||j.includes("\\"))return!1;return j.split("/").every((q)=>q!==""&&q!=="."&&q!=="..")}function Z(j){if(j.kind==="root"){if(j.path===void 0)return".";if(!J(j.path))throw Error("invalid_device_workspace_identity");return j.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(j.workspaceId)||j.workspaceId==="."||j.workspaceId==="..")throw Error("invalid_device_workspace_identity");let q=j.layout==="sessions"?"sessions":X;return`${j.base?`${j.base}/`:""}${q}/${j.workspaceId}/repo`}function L(j){if(!j||typeof j!=="object"||Array.isArray(j))return null;let q=j;if(q.kind==="root"&&Object.keys(q).length===1)return{kind:"root"};if(q.kind==="root"&&Object.keys(q).length===2&&J(q.path))return{kind:"root",path:q.path};if(q.kind!=="managed"||typeof q.workspaceId!=="string"||Object.keys(q).length!==2+(q.base===void 0?0:1)+(q.layout===void 0?0:1)||q.base!==void 0&&q.base!==".reason/workspace"||q.layout!==void 0&&q.layout!=="sessions")return null;let z={kind:"managed",workspaceId:q.workspaceId,...q.base===".reason/workspace"?{base:".reason/workspace"}:{},...q.layout==="sessions"?{layout:"sessions"}:{}};try{return Z(z),z}catch{return null}}var b="/home/runner",P=10001,x="/run/reason/sessions",f=/^(?:\/[A-Za-z0-9._-]+)+$/,M=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,H=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function K(j){return M.exec(j)?.[1]??H.exec(j)?.[1]??j}var $=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/,A="*/.reason/workspace/workspaces/pi/*|*/.reason/workspace/sessions/*";function N(j,q=b,z="sessions"){if(!f.test(q)||q.split("/").some((V)=>V==="."||V===".."))throw Error("invalid_cloud_payload_home");let Q=`${q}/${Z({kind:"managed",workspaceId:j,base:".reason/workspace",...z?{layout:z}:{}})}`,F=`${x}/${K(j)}`;return{home:q,root:Q.slice(0,-5),checkout:Q,control:F,jobEnv:`${F}/job.env`,cloudAccess:`${F}/cloud-access`,logs:`${F}/logs`,pin:`${F}/ws`}}function Y(j){return $.exec(j.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function D(j){return{kind:"managed",workspaceId:j,layout:"sessions"}}function R(j){let q=$.exec(j.replace(/\/+$/,""));if(!q)return null;try{let z=N(q[3],q[1],Y(j));return z.root===j.replace(/\/+$/,"")?z:null}catch{return null}}
3
- export{U as vj,T as wj,y as xj,W as yj,g as zj,B as Aj,C as Bj,J as Cj,Z as Dj,L as Ej,b as Fj,P as Gj,x as Hj,M as Ij,H as Jj,$ as Kj,A as Lj,N as Mj,Y as Nj,D as Oj,R as Pj};
3
+ export{U as xj,T as yj,y as zj,W as Aj,g as Bj,B as Cj,C as Dj,J as Ej,Z as Fj,L as Gj,b as Hj,P as Ij,x as Jj,M as Kj,H as Lj,$ as Mj,A as Nj,N as Oj,Y as Pj,D as Qj,R as Rj};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{D as T,F as U}from"./vm-hands-entry-lite-cfwke54v.js";import{_c as V}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ri as M,ti as Q}from"./vm-hands-entry-lite-gk3y60ap.js";import{Hi as G}from"./vm-hands-entry-lite-eatqxe5y.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
2
+ import{D as T,F as U}from"./vm-hands-entry-lite-n71rv7kv.js";import{_c as V}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ti as M,vi as Q}from"./vm-hands-entry-lite-923jmcs3.js";import{Ji as G}from"./vm-hands-entry-lite-shm5nhjk.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
3
3
  export{W as v,X as w,$ as x,N as y,P as z};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var n=Object.create;var{getPrototypeOf:o,defineProperty:e,getOwnPropertyNames:k,getOwnPropertyDescriptor:p}=Object,l=Object.prototype.hasOwnProperty;function m(a){return this[a]}var q,r,u=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?q??=new WeakMap:r??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?n(o(a)):{};let f=b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c;for(let g of k(a))if(!l.call(f,g))e(f,g,{get:m.bind(a,g),enumerable:!0});if(d)h.set(a,f);return f},v=(a)=>{var b=(j??=new WeakMap).get(a),c;if(b)return b;if(b=e({},"__esModule",{value:!0}),a&&typeof a==="object"||typeof a==="function"){for(var d of k(a))if(!l.call(b,d))e(b,d,{get:m.bind(a,d),enumerable:!(c=p(a,d))||c.enumerable})}return j.set(a,b),b},j,w=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=(a)=>a;function t(a,b){this[a]=s.bind(null,b)}var x=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0,configurable:!0,set:t.bind(b,c)})};var y=(a,b)=>()=>(a&&(b=a(a=0)),b);var z=import.meta.require;
3
- export{u as Lk,v as Mk,w as Nk,x as Ok,y as Pk,z as Qk};
3
+ export{u as Nk,v as Ok,w as Pk,x as Qk,y as Rk,z as Sk};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import{resolve as H,sep as J}from"path";var K=[[".ssh"],[".gnupg"],[".aws"],[".azure"],[".kube"],[".docker"],[".infisical"],[".password-store"],[".terraform.d"],[".config","ara"],[".config","reason"],[".config","gh"],[".config","gcloud"],[".config","infisical"],[".config","op"],[".config","1password"],[".config","pass"],[".local","share","keyrings"],["library","keychains"],["library","application support","so.ara.desktop"],["appdata","roaming","github cli"],["appdata","roaming","gcloud"],["appdata","roaming","microsoft","credentials"],["appdata","local","microsoft","credentials"],["appdata","roaming","microsoft","protect"],["appdata","roaming","1password"],["appdata","local","1password"],["appdata","roaming","microsoft","windows","start menu","programs","startup"],["documents","windowspowershell"],["documents","powershell"],["appdata","local","reason"]],V=[[".codex","config.toml"],[".cursor","mcp.json"],[".claude","settings.json"],[".claude","settings.local.json"],[".cargo","credentials"],[".cargo","credentials.toml"],[".gem","credentials"],[".config","git","config"],[".config","git","credentials"],[".config","pip","pip.conf"]],Z=new Set([".bash_login",".bash_profile",".bashrc",".bunfig.toml",".claude.json",".env",".envrc",".git-credentials",".gitconfig",".mcp.json",".netrc",".npmrc",".profile",".pypirc",".terraformrc",".yarnrc",".yarnrc.yml",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","auth.json","credentials.json","credentials.tfrc.json","local-daemon.json","local-device.json","mcp.json"]),$=[".key",".p12",".pfx",".pem"];function B(z,j){if(z.length<j.length)return!1;for(let k=0;k<=z.length-j.length;k+=1)if(j.every((b,G)=>z[k+G]===b))return!0;return!1}function A(z){let j=H(z).split(J).filter(Boolean).map((b)=>b.toLowerCase());if(K.some((b)=>B(j,b)))return!0;if(V.some((b)=>B(j,b)))return!0;let k=j.at(-1)??"";return Z.has(k)||k.startsWith(".env.")||$.some((b)=>k.endsWith(b))}
3
- export{K as Wi,V as Xi,Z as Yi,$ as Zi,A as _i};
3
+ export{K as Yi,V as Zi,Z as _i,$ as $i,A as aj};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Hi as m,Ii as y}from"./vm-hands-entry-lite-eatqxe5y.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){if(Q==="win32")return K(J,"AppData","Local","Reason","Logs");let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
- export{f as qi,mJ as ri,yJ as si,j as ti,sJ as ui,p as vi,cJ as wi,lJ as xi,iJ as yi,rJ as zi,r as Ai,jJ as Bi,qQ as Ci,BQ as Di,YQ as Ei,WQ as Fi,LJ as Gi};
2
+ import{Ji as m,Ki as y}from"./vm-hands-entry-lite-shm5nhjk.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){if(Q==="win32")return K(J,"AppData","Local","Reason","Logs");let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
+ export{f as si,mJ as ti,yJ as ui,j as vi,sJ as wi,p as xi,cJ as yi,lJ as zi,iJ as Ai,rJ as Bi,r as Ci,jJ as Di,qQ as Ei,BQ as Fi,YQ as Gi,WQ as Hi,LJ as Ii};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Bi as m,qi as A,ri as y,si as p}from"./vm-hands-entry-lite-gk3y60ap.js";import{Hi as u}from"./vm-hands-entry-lite-eatqxe5y.js";import{randomUUID as d}from"crypto";import{chmodSync as c,existsSync as n,mkdirSync as YJ,readlinkSync as GJ,readFileSync as OJ,renameSync as VJ,unlinkSync as FJ,writeFileSync as HJ}from"fs";import{homedir as v}from"os";import{basename as C,dirname as H,isAbsolute as g,join as N,normalize as a,relative as TJ,resolve as zJ}from"path";import{unlinkSync as XJ}from"fs";import{dirname as ZJ,join as $J}from"path";function jJ(J){return $J(ZJ(J),"future-device-grant.json")}function l(J){try{XJ(jJ(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var z=3,BJ=1,SJ=2,D=1,i=1,r="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",E="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",_J=[E,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function t(J){return typeof J==="string"&&_J.includes(J)}var IJ=["future_device","updates_only","cli_only"];function h(J){return typeof J==="string"&&IJ.some((Q)=>Q===J)}function LJ(J=process.env,Q=v()){return J.XDG_CONFIG_HOME?.trim()||N(Q,".config")}function K(J=process.env,Q=v()){let U=y({env:J}),W=LJ(J,Q);return N(W,m(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function G(J){return typeof J==="string"&&J.trim().length>0}var NJ=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function AJ(J){return typeof J==="string"&&NJ.test(J)}function M(J){return G(J)&&g(J)&&a(J)===J}function e(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return M(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&M(Q.target))}function JJ(J){return J==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}var gJ=/^\.(?:reason|ara)(?:-staging)?-worker-/,hJ=["reason","ara"];function oJ(J){let Q=J.owned_paths.filter((W)=>W.role==="launcher").map((W)=>W.path),[U]=JJ(J.channel);return Q.find((W)=>C(W)===U)??Q[0]??null}function o(J){let[Q,U]=JJ(J.channel==="staging"?"staging":"production"),W=[[Q,U],[U,Q]];return J.owned_paths?.every((X)=>X.role!=="alias"||J.installer==="shell"&&W.some(([$,j])=>X.path===N(J.install_dir,$)&&X.target===N(J.install_dir,j))&&J.owned_paths?.some(($)=>$.role==="launcher"&&$.path===X.target))??!1}function w(J,Q){try{return zJ(H(J),GJ(J))===Q}catch{return!1}}function sJ(J){let Q=C(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=N(H(J),U);return w(W,J)||w(J,W)?W:J}function f(J,Q){let U=TJ(J,Q);return U.length>0&&!U.startsWith("..")&&!g(U)}function QJ(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return(Q.kind==="shell_profile"||Q.kind==="windows_user_path")&&G(Q.location)&&G(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function UJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==D||!G(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&t(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function DJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==BJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"&&Q.installer!=="powershell"||!G(Q.installed_at)||!G(Q.version)||!G(Q.target)||!M(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(e)||!Q.owned_paths.every((U)=>f(Q.install_dir,U.path))||!o(Q)||!QJ(Q.path_entry))return null;return{...Q,schema_version:z,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==SJ||!WJ(Q)||!h(Q.background_mode)||!UJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:z,installation_id:null}}function WJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&(J.installer==="shell"||J.installer==="powershell")||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&G(J.installed_at)&&G(J.version)&&G(J.target)&&M(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(e)&&J.owned_paths.every((Q)=>f(J.install_dir,Q.path))&&o(J)&&QJ(J.path_entry)}function RJ(J){let Q=DJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==z||!AJ(W.installation_id)||!WJ(W)||!h(W.background_mode)||!UJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==i||W.desktop_account_access.scope!==r||!G(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function k(J=K()){if(!n(J))return null;try{return RJ(JSON.parse(OJ(J,"utf8")))}catch{return null}}function b(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===D&&J.device_consent.decision==="authorized"&&t(J.device_consent.scope))}function s(J,Q){let U=k(Q);if(!(b(U)&&b(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))l(Q);YJ(H(Q),{recursive:!0,mode:448}),c(H(Q),448);let X=`${Q}.${process.pid}.${d()}.tmp`;try{HJ(X,`${JSON.stringify(J,null,2)}
2
+ import{Di as m,si as A,ti as y,ui as p}from"./vm-hands-entry-lite-923jmcs3.js";import{Ji as u}from"./vm-hands-entry-lite-shm5nhjk.js";import{randomUUID as d}from"crypto";import{chmodSync as c,existsSync as n,mkdirSync as YJ,readlinkSync as GJ,readFileSync as OJ,renameSync as VJ,unlinkSync as FJ,writeFileSync as HJ}from"fs";import{homedir as v}from"os";import{basename as C,dirname as H,isAbsolute as g,join as N,normalize as a,relative as TJ,resolve as zJ}from"path";import{unlinkSync as XJ}from"fs";import{dirname as ZJ,join as $J}from"path";function jJ(J){return $J(ZJ(J),"future-device-grant.json")}function l(J){try{XJ(jJ(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var z=3,BJ=1,SJ=2,D=1,i=1,r="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",E="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",_J=[E,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function t(J){return typeof J==="string"&&_J.includes(J)}var IJ=["future_device","updates_only","cli_only"];function h(J){return typeof J==="string"&&IJ.some((Q)=>Q===J)}function LJ(J=process.env,Q=v()){return J.XDG_CONFIG_HOME?.trim()||N(Q,".config")}function K(J=process.env,Q=v()){let U=y({env:J}),W=LJ(J,Q);return N(W,m(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function G(J){return typeof J==="string"&&J.trim().length>0}var NJ=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function AJ(J){return typeof J==="string"&&NJ.test(J)}function M(J){return G(J)&&g(J)&&a(J)===J}function e(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return M(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&M(Q.target))}function JJ(J){return J==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}var gJ=/^\.(?:reason|ara)(?:-staging)?-worker-/,hJ=["reason","ara"];function oJ(J){let Q=J.owned_paths.filter((W)=>W.role==="launcher").map((W)=>W.path),[U]=JJ(J.channel);return Q.find((W)=>C(W)===U)??Q[0]??null}function o(J){let[Q,U]=JJ(J.channel==="staging"?"staging":"production"),W=[[Q,U],[U,Q]];return J.owned_paths?.every((X)=>X.role!=="alias"||J.installer==="shell"&&W.some(([$,j])=>X.path===N(J.install_dir,$)&&X.target===N(J.install_dir,j))&&J.owned_paths?.some(($)=>$.role==="launcher"&&$.path===X.target))??!1}function w(J,Q){try{return zJ(H(J),GJ(J))===Q}catch{return!1}}function sJ(J){let Q=C(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=N(H(J),U);return w(W,J)||w(J,W)?W:J}function f(J,Q){let U=TJ(J,Q);return U.length>0&&!U.startsWith("..")&&!g(U)}function QJ(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return(Q.kind==="shell_profile"||Q.kind==="windows_user_path")&&G(Q.location)&&G(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function UJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==D||!G(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&t(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function DJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==BJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"&&Q.installer!=="powershell"||!G(Q.installed_at)||!G(Q.version)||!G(Q.target)||!M(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(e)||!Q.owned_paths.every((U)=>f(Q.install_dir,U.path))||!o(Q)||!QJ(Q.path_entry))return null;return{...Q,schema_version:z,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==SJ||!WJ(Q)||!h(Q.background_mode)||!UJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:z,installation_id:null}}function WJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&(J.installer==="shell"||J.installer==="powershell")||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&G(J.installed_at)&&G(J.version)&&G(J.target)&&M(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(e)&&J.owned_paths.every((Q)=>f(J.install_dir,Q.path))&&o(J)&&QJ(J.path_entry)}function RJ(J){let Q=DJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==z||!AJ(W.installation_id)||!WJ(W)||!h(W.background_mode)||!UJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==i||W.desktop_account_access.scope!==r||!G(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function k(J=K()){if(!n(J))return null;try{return RJ(JSON.parse(OJ(J,"utf8")))}catch{return null}}function b(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===D&&J.device_consent.decision==="authorized"&&t(J.device_consent.scope))}function s(J,Q){let U=k(Q);if(!(b(U)&&b(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))l(Q);YJ(H(Q),{recursive:!0,mode:448}),c(H(Q),448);let X=`${Q}.${process.pid}.${d()}.tmp`;try{HJ(X,`${JSON.stringify(J,null,2)}
3
3
  `,{mode:384,flag:"wx"}),c(X,384),VJ(X,Q)}finally{if(n(X))FJ(X)}let $=H(Q),j=C($)==="staging"?H($):$;if(C(j)==="reason")m(H(j));return J}function qJ(J=K(),Q=new Date){let U=k(J);if(!U?.installation_id)throw Error("Reason installation ownership is missing; reinstall the current CLI before enabling Device execution");if(b(U))return U;let W={...U,background_mode:"future_device",device_consent:{version:D,decision:"authorized",scope:E,recorded_at:Q.toISOString()}};return delete W.desktop_account_access,s(W,J)}function lJ(J,Q=K(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=L(J.installDir,"install directory"),X=k(Q);if(X?.installation_id&&!J.accountAccess)return qJ(Q,U);return s({...X??{schema_version:z,channel:J.channel,install_method:"desktop",installer:"desktop",installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:[],path_entry:null},schema_version:z,installation_id:X?.installation_id??d(),background_mode:"future_device",...J.accountAccess?{desktop_account_access:{version:i,scope:r,recorded_at:U.toISOString()}}:{},device_consent:{version:D,decision:"authorized",scope:E,recorded_at:U.toISOString()}},Q)}function CJ(J,Q){return J.kind===Q.kind&&J.location===Q.location&&J.value===Q.value}function L(J,Q){let U=a(J);if(!g(U))throw Error(`${Q} must be an absolute path`);return U}function MJ(J,Q=K(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=L(J.install_dir,"install directory"),X=k(Q),$=J.backgroundMode??"preserve",j=$==="preserve"?X?.background_mode??"cli_only":$,T=X?.channel===J.channel&&b(X)&&j==="future_device",B=$==="preserve"&&!X||X?.channel===J.channel&&($==="preserve"||T),O={path:L(J.launcherPath,"launcher path"),kind:J.launcherKind,role:"launcher"};if(!f(W,O.path))throw Error("launcher path must be inside the install directory");let S=(J.workerRoots??[]).map((Y)=>L(Y,"worker root"));if(S.some((Y)=>!f(W,Y)))throw Error("worker root must be inside the install directory");let _=[];if(J.aliasPath){let Y={path:L(J.aliasPath,"alias path"),kind:"symlink",role:"alias",target:O.path};if(!o({installer:J.installer,channel:J.channel,install_dir:W,owned_paths:[O,Y]})||!w(Y.path,Y.target))throw Error("alias must be the channel's symlink to its canonical launcher");_.push(Y)}let R=[...X?.channel===J.channel&&X.install_dir===W?X.owned_paths:[],O,..._,...S.map((Y)=>({path:Y,kind:"directory",role:"worker_root"}))],P=Array.from(new Map(R.map((Y)=>[Y.path,Y])).values()),Z=J.pathEntry??null,F=Z?X?.path_entry&&CJ(Z,X.path_entry)?{...Z,added_by_installer:q(Z)||q(X.path_entry),added_by_ara:q(Z)||q(X.path_entry)}:Z:X?.path_entry??null,I={schema_version:z,installation_id:X?.installation_id??d(),channel:J.channel,install_method:"curl",installer:J.installer,installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:P,path_entry:F,background_mode:j,device_consent:B?X?.device_consent??null:{version:D,decision:j==="future_device"?"authorized":j==="updates_only"?"ask":"disabled",scope:j==="future_device"?E:null,recorded_at:U.toISOString()},...T&&X.desktop_account_access?{desktop_account_access:X.desktop_account_access}:{}};return s(I,Q)}function x(J,Q){let U=J.indexOf(Q);if(U===-1)return;let W=J[U+1];if(!W||W.startsWith("--"))throw Error(`${Q} needs a value`);return W}function V(J,Q){let U=x(J,Q);if(!U)throw Error(`${Q} is required`);return U}function cJ(J,Q={}){let U=Q.io??{stdout:process.stdout,stderr:process.stderr};try{let W=new Set(["--channel","--installer","--version","--target","--install-dir","--launcher-path","--launcher-kind","--worker-root","--path-kind","--path-location","--path-value","--background-mode"]);for(let Z=0;Z<J.length;Z+=1){let F=J[Z];if(F==="--path-added")continue;if(!W.has(F))throw Error(`unknown option: ${F}`);if(Z+=1,Z>=J.length)throw Error(`${F} needs a value`)}let X=Q.env??process.env,$=V(J,"--channel"),j=y({env:X,executablePath:Q.executablePath});if($!==j)throw Error(`installer channel ${$} does not match running ${j} CLI`);let T=V(J,"--installer");if(T!=="shell"&&T!=="powershell")throw Error("--installer must be shell or powershell");let B=V(J,"--launcher-kind");if(B!=="file"&&B!=="symlink")throw Error("--launcher-kind must be file or symlink");let O=x(J,"--path-kind"),S=null;if(O){if(O!=="shell_profile"&&O!=="windows_user_path")throw Error("--path-kind must be shell_profile or windows_user_path");S={kind:O,location:V(J,"--path-location"),value:V(J,"--path-value"),added_by_installer:J.includes("--path-added"),added_by_ara:J.includes("--path-added")}}else if(J.includes("--path-location")||J.includes("--path-value")||J.includes("--path-added"))throw Error("path entry flags require --path-kind");let _={channel:j,install_method:"curl",installer:T,version:V(J,"--version"),target:V(J,"--target"),install_dir:V(J,"--install-dir"),launcherPath:V(J,"--launcher-path"),launcherKind:B,workerRoots:J.flatMap((Z,F)=>{if(Z!=="--worker-root")return[];let I=J[F+1];if(!I||I.startsWith("--"))throw Error("--worker-root needs a value");return[I]}),pathEntry:S,backgroundMode:(()=>{let Z=x(J,"--background-mode")??"preserve";if(Z!=="preserve"&&!h(Z))throw Error("--background-mode must be future_device, updates_only, cli_only, or preserve");return Z})()},R=u(X,"REASON_INSTALL_ALIAS_PATH");if(R)_.aliasPath=R;let P=K(p(X,j),Q.home??v());return(Q.writeReceipt??MJ)(_,P,Q.now?.()??new Date),0}catch(W){return U.stderr.write(`Reason installer receipt: ${W instanceof Error?W.message:String(W)}
4
4
  `),1}}
5
5
  export{z as ge,D as he,i as ie,r as je,E as ke,IJ as le,LJ as me,K as ne,JJ as oe,gJ as pe,hJ as qe,oJ as re,w as se,sJ as te,q as ue,RJ as ve,k as we,b as xe,qJ as ye,lJ as ze,MJ as Ae,cJ as Be};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Cc as v,xc as q}from"./vm-hands-entry-lite-v0kpksbf.js";function A(j=process.platform){if(q(),j==="linux"||j==="win32")v("strict")}
2
+ import{Cc as v,xc as q}from"./vm-hands-entry-lite-qwxmr70t.js";function A(j=process.platform){if(q(),j==="linux"||j==="win32")v("strict")}
3
3
  export{A as r};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ag as k0}from"./vm-hands-entry-lite-t839nkd2.js";import{Rg as f0}from"./vm-hands-entry-lite-ps9gjbs5.js";import{Xg as uq}from"./vm-hands-entry-lite-q5h859gg.js";import{jj as cq}from"./vm-hands-entry-lite-sg0c4khn.js";import{qj as i}from"./vm-hands-entry-lite-2sx1a43v.js";import{Zj as _,ak as g0,dk as h0,ek as G8,fk as y0,hk as l8,kk as G0,mk as A0}from"./vm-hands-entry-lite-hx4w3r63.js";import{ok as H0}from"./vm-hands-entry-lite-sjn5yjvx.js";import{Kk as K}from"./vm-hands-entry-lite-69n9q5f1.js";import{execFile as f1,spawn as I0}from"child_process";import{randomBytes as g1}from"crypto";import{chmodSync as h1,existsSync as p0,lstatSync as k1,mkdirSync as I1,readFileSync as p1,rmSync as v1,writeFileSync as Wq}from"fs";import{connect as u1}from"net";import{join as $}from"path";var Gq="./desktop-wallpaper-0pjhgyfk.jpg";var Aq="./dock-browser-afp005mt.png";var Sq="./dock-files-rywdm96b.png";var Vq="./dock-terminal-s41cj1jp.png";var Fq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
2
+ import{Cg as k0}from"./vm-hands-entry-lite-fgdtrsf4.js";import{Tg as f0}from"./vm-hands-entry-lite-ht482g94.js";import{Zg as uq}from"./vm-hands-entry-lite-0kzefw0a.js";import{lj as cq}from"./vm-hands-entry-lite-zd4xbqsv.js";import{sj as i}from"./vm-hands-entry-lite-ecgyzbdp.js";import{$j as _,ck as g0,fk as h0,gk as G8,hk as y0,jk as l8,mk as G0,ok as A0}from"./vm-hands-entry-lite-ew7amfaf.js";import{qk as H0}from"./vm-hands-entry-lite-mrw8bv5s.js";import{Mk as K}from"./vm-hands-entry-lite-hkvkfq0z.js";import{execFile as f1,spawn as I0}from"child_process";import{randomBytes as g1}from"crypto";import{chmodSync as h1,existsSync as p0,lstatSync as k1,mkdirSync as I1,readFileSync as p1,rmSync as v1,writeFileSync as Wq}from"fs";import{connect as u1}from"net";import{join as $}from"path";var Gq="./desktop-wallpaper-0pjhgyfk.jpg";var Aq="./dock-browser-afp005mt.png";var Sq="./dock-files-rywdm96b.png";var Vq="./dock-terminal-s41cj1jp.png";var Fq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
3
  # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
4
  # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
5
  # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
@@ -248,4 +248,4 @@ Gtk.main()
248
248
  `).flatMap((P)=>{let X=P.indexOf("=");return X>0?[[P.slice(0,X),P.slice(X+1)]]:[]})))}catch{return{}}}var E0=new Set;async function t1(q,x,Q){let P=await o1(),X=/^:(\d+)(?:\.\d+)?$/.exec(P.DISPLAY??"")?.[1];if(!X||`:${X}`===A8||P.WAYLAND_DISPLAY||P.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${X}`,xauthority:P.XAUTHORITY??$(q,".Xauthority"),rfbSocket:$(x,`rfb-${X}.sock`)},J=`${b.display} ${b.xauthority}`;if(E0.has(J)||!await o({path:`/tmp/.X11-unix/X${X}`},!1))return null;let N={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await u0(Q,b,x,`x11vnc-${X}.log`,N))return{...b,sound:null};return E0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
249
249
  `),null}function e1(q,x){let Q=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,P=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!p0(`/usr/bin/${b}`)).map(([b])=>b),X=Mq({root:q,display:x,screen:Nq,browserExec:Q,absent:P});for(let b of["","openbox","tint2","picom"])S8($(q,b));for(let[b,J]of Object.entries(X.files))Wq($(q,b),J,{mode:384});for(let[b,J]of Object.entries(zq))Wq($(q,`ara-${b}`),p1(J),{mode:384});return{root:q,openboxConfig:$(q,"openbox","rc.xml"),start:X.start}}async function q9(q,x){let Q=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
250
250
  `);await new Promise((P)=>{let X=I0("/bin/sh",["-c",Q],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{X.kill(),P()},V8);X.once("error",()=>{clearTimeout(b),P()}),X.once("exit",()=>{clearTimeout(b),P()})})}async function uQ(q,x={}){let Q=x.now??Date.now,P=a1(q.payload,Q());if(q.signal.throwIfAborted(),!P.video)throw new K("display_video_required","Reason desktops stream as video now; this request came without it.");let X=x.platform??process.platform;if(X!=="linux"&&X!=="darwin"&&X!=="win32")throw new K("display_video_unsupported","This machine does not serve desktop video.");let b=P.video,J=(x.video?.desktop??(X==="darwin"?async()=>S0:X==="win32"?async()=>V0:i1))();return await x9(q.signal,P,x,Q,(N)=>w0(N,{request:b,desktop:J,...P.viewer?{viewer:P.viewer}:{},viewerSameNetwork:P.viewer_same_network===!0},x.video),(N)=>G8({type:"error",code:N}))}function x9(q,x,Q,P,X,b){let J=P();return new Promise((N,T)=>{let L=null,C=!1,U=!1,y,R,Y,S=!1,W=null,G=(A)=>{if(U)return;if(W)A=W;U=!0,clearTimeout(y),clearTimeout(R),q.removeEventListener("abort",F),Y?.close();try{L?.close(1000,"display_session_over")}catch{}if("error"in A){T(A.error);return}N({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,P()-J)})},V=()=>G({error:new K("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;G({error:A instanceof K?A:new K("cancelled","Reason closed the desktop session.")})},E=()=>{if(!W||!L)return;let A=W.error;try{L.send(b(A instanceof K?A.code:"display_unavailable"))}catch{}G(W)};if(Y=X({get done(){return U||W!==null},get open(){return C&&!U&&W===null},get bufferedAmount(){return L?.bufferedAmount??0},send(A){if(U||W||!C||!L)return;try{L.send(A)}catch{G({reason:"relay_closed"})}},end:(A)=>{if(U||W)return;if(!("error"in A)){G(A);return}if(W=A,S&&C)E()}}),U){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),y=setTimeout(()=>G({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-P())),R=setTimeout(()=>G({reason:"viewer_absent"}),Q.viewerWaitMs??l1);try{L=(Q.connect??k0)(x.relay_url,(Q.loadProxy??f0)()?.url)}catch{V();return}L.binaryType="arraybuffer",L.onopen=()=>{if(U||!L)return;C=!0,Y?.opened()},L.onmessage=(A)=>{if(U)return;let f=A.data,p=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!p||p.byteLength===0)return;if(clearTimeout(R),S=!0,W){E();return}Y?.received(p)},L.onclose=()=>{if(U)return;if(!C){V();return}G({reason:"relay_closed"})},L.onerror=()=>{if(U||C)return;V()}})}
251
- export{g8 as Yf,D9 as Zf,y9 as _f,d as $f,T8 as ag,FQ as bg,bq as cg,pq as dg,oq as eg,I as fg,t9 as gg,e9 as hg,qQ as ig,c1 as jg,A8 as kg,a1 as lg,O0 as mg,vQ as ng,S8 as og,i1 as pg,uQ as qg};
251
+ export{g8 as _f,D9 as $f,y9 as ag,d as bg,T8 as cg,FQ as dg,bq as eg,pq as fg,oq as gg,I as hg,t9 as ig,e9 as jg,qQ as kg,c1 as lg,A8 as mg,a1 as ng,O0 as og,vQ as pg,S8 as qg,i1 as rg,uQ as sg};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Bj as Y,Dj as Z,zj as X}from"./vm-hands-entry-lite-29f3m7x2.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
- export{Q as qj,O as rj,_ as sj,b as tj,g as uj};
2
+ import{Bj as X,Dj as Y,Fj as Z}from"./vm-hands-entry-lite-3pecyp8y.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
+ export{Q as sj,O as tj,_ as uj,b as vj,g as wj};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Kk as l}from"./vm-hands-entry-lite-69n9q5f1.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
2
+ import{Mk as l}from"./vm-hands-entry-lite-hkvkfq0z.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);X>=0;X=B.indexOf(`
110
110
  `)){let S=B.slice(0,X);if(B=B.slice(X+1),!S.startsWith("c "))continue;let O=S.slice(2);if(O.length>Math.ceil(Y/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(O)){K({reason:"display_protocol"});return}let _=Buffer.from(O,"base64");if(_.byteLength<=Y)q.clipboard(_.toString("utf8"));if(z)return}if(B.length>Math.ceil(Y/3)*4+2)K({reason:"display_protocol"})}),G.once("error",()=>W("Reason could not watch this Mac's desktop clipboard.")),G.once("exit",()=>{if(!z)W("Reason could not watch this Mac's desktop clipboard.")})};return J.stdout.on("data",(B)=>{if(z||Z===null)return;Z+=B.toString("utf8");let N=Z.indexOf(`
111
111
  `);if(N<0){if(Z.length>4096)K({reason:"display_protocol"});return}let X=y(Z.slice(0,N));if(Z=null,!X)K({reason:"display_protocol"});else if(!X.screen||!X.accessibility)W(j.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else i(),q.ready({width:X.width,height:X.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>W("Reason could not start this Mac's desktop input.")),J.once("exit",()=>{if(Z!==null)W("Reason could not start this Mac's desktop input.");else K({reason:"display_closed"})}),{pointer:(B,N,X)=>L(Q.pointer(B,N,X)),key:(B,N)=>L(Q.key(B,N)),clipboard:(B)=>L([`c ${Buffer.from(B,"utf8").toString("base64")}`]),close(){z=!0,F()}}}
112
- export{Cj as Vj,kj as Wj,h as Xj,Yj,Y as Zj,Lj as _j,Aj as $j,s as ak,xj as bk,Mj as ck,fj as dk,hj as ek,$j as fk,y as gk,Sj as hk,_j as ik,Hj as jk,Tj as kk,a as lk,Vj as mk};
112
+ export{Cj as Xj,kj as Yj,h as Zj,Yj as _j,Y as $j,Lj as ak,Aj as bk,s as ck,xj as dk,Mj as ek,fj as fk,hj as gk,$j as hk,y as ik,Sj as jk,_j as kk,Hj as lk,Tj as mk,a as nk,Vj as ok};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Rg as p}from"./vm-hands-entry-lite-ps9gjbs5.js";import{Yg as h}from"./vm-hands-entry-lite-vqfpryez.js";import{eh as s}from"./vm-hands-entry-lite-1cs1jy20.js";import{rj as d}from"./vm-hands-entry-lite-2sx1a43v.js";import{Ej as i}from"./vm-hands-entry-lite-29f3m7x2.js";import{Ik as P}from"./vm-hands-entry-lite-bgs4zjkf.js";import{Kk as V}from"./vm-hands-entry-lite-69n9q5f1.js";import{existsSync as U,realpathSync as l,statSync as e}from"fs";import{platform as f}from"os";import{isAbsolute as r,sep as zz}from"path";import{existsSync as n}from"fs";import{createRequire as t}from"module";var E=P(h)(()=>t(import.meta.url)("bun:ffi"),n);function m(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&E.available()}function w(z=process.env){return E.defaultShell(z)}function k(z){return E.shellArgs(z)}function v(z){let H=E.spawn({...z,env:z.environment});return H.exited.then(()=>H.close()),{write:(Q)=>H.write(Q),resize:(Q,J)=>H.resize(Q,J),kill:()=>H.close(),exited:H.exited}}var Hz=43200000,y=s,Jz=4,Qz=/^[A-Za-z0-9._:-]{1,160}$/,Vz=1000;function u(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function g(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(Vz,Math.max(1,Math.floor(z)))}function Zz(z,H=Date.now()){let Q=["relay_url","session_id","expires_at"],J=new Set([...Q,"cols","rows","cwd","workspace"]);if(!u(z)||Q.some((C)=>!(C in z))||Object.keys(z).some((C)=>!J.has(C)))throw new V("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:N,session_id:Y,expires_at:R}=z;if(typeof N!=="string")throw new V("invalid_pty_request","Reason terminal relay URL is missing.");let K;try{K=new URL(N)}catch{throw new V("invalid_pty_request","Reason terminal relay URL is invalid.")}if(K.protocol!=="wss:"&&K.protocol!=="ws:"||K.username||K.password)throw new V("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!Qz.test(Y))throw new V("invalid_pty_request","Reason terminal session identity is invalid.");let D=typeof R==="string"?Date.parse(R):Number.NaN;if(!Number.isFinite(D)||D<=H)throw new V("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new V("invalid_pty_request","Reason terminal working directory is invalid.");let j=z.workspace===void 0?void 0:i(z.workspace);if(j===null||j&&z.cwd!==void 0)throw new V("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:N,session_id:Y,expires_at:new Date(Math.min(D,H+Hz)).toISOString(),cols:g(z.cols,80),rows:g(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...j?{workspace:j}:{}}}function $z(z,H){if(f()==="win32")[z,H]=[z.toLowerCase(),H.toLowerCase()];return H===z||H.startsWith(z+zz)}function c(z,H){if(H===void 0)return z;if(!r(H))throw new V("pty_cwd_invalid","Reason terminal working directory must be absolute.");let Q;try{Q=l(H)}catch{throw new V("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!$z(z,Q))throw new V("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!e(Q).isDirectory())throw new V("pty_cwd_invalid","Reason terminal working directory is not a directory.");return Q}function jz(z=process.env){if(f()==="win32")return w(z);let H=z.SHELL;if(H&&r(H)&&U(H))return H;for(let Q of f()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(U(Q))return Q;return"/bin/sh"}function Gz(){let z=globalThis.Bun;if(!z)throw new V("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Sz(){if(f()==="win32")return m();return typeof globalThis.Bun<"u"}var Nz=(z)=>{if(f()==="win32")try{return v({...z,file:z.shell,args:k(z.shell),environment:{...z.environment,TERM:"xterm-256color"}})}catch{throw new V("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let H=Gz()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,N)=>{z.onData(N)}}}),Q=H.terminal;if(!Q){try{H.kill()}catch{}throw new V("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>Q.write(J),resize:(J,N)=>Q.resize(J,N),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Wz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},M=new Set;function Kz(z){if(M.size>=Jz||M.has(z))return null;M.add(z);let H=!1;return()=>{if(H)return;H=!0,M.delete(z)}}async function Tz(z,H={}){let Q=H.now??Date.now,J=Zz(z.payload,Q()),N=Kz(z.operationId);if(!N)throw new V("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=Q(),R,K,D;try{let j=J.workspace?d(z.root,J.workspace):void 0;R=j?c(U(j.boundary)?l(j.boundary):j.boundary,j.path):c(z.root,J.cwd),K=H.environment??process.env,D=H.shellPath??jz(K)}catch(j){throw N(),j}return await new Promise((j,C)=>{let F=null,$=null,I=!1,B=!1,X=!1,_=null,b=0,x=0,O=[],S=0,T=null,G=(Z)=>{if(X)return;if(X=!0,T)clearTimeout(T);z.signal.removeEventListener("abort",A);try{F?.kill()}catch{}try{$?.close(1000,"pty_session_over")}catch{}if(N(),Z.kind==="rejected"){C(Z.error);return}let W={reason:Z.reason,exit_code:_,output_bytes:b,input_bytes:x,duration_ms:Math.max(0,Q()-Y)};z.emitEvent("pty.stopped",{...W}).catch(()=>{return}),j({...W})},A=()=>{let Z=z.signal.reason;G({kind:"rejected",error:Z instanceof V?Z:new V("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){A();return}z.signal.addEventListener("abort",A,{once:!0}),T=setTimeout(()=>G({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-Q()));let a=(Z)=>{if(b+=Z.byteLength,!I||!$){if(O.push(Z),S+=Z.byteLength,S>y)G({kind:"resolved",reason:"output_backpressure"});return}try{$.send(Z)}catch{G({kind:"resolved",reason:"relay_closed"});return}if($.bufferedAmount>y)G({kind:"resolved",reason:"output_backpressure"})};try{F=(H.spawnPty??Nz)({shell:D,args:["-i","-l"],cwd:R,cols:J.cols,rows:J.rows,environment:K,onData:(Z)=>{if(!X)a(Z)}})}catch(Z){G({kind:"rejected",error:Z instanceof V?Z:new V("pty_spawn_failed","Reason could not start the terminal shell.")});return}F.exited.then((Z)=>{if(X)return;if(_=Z,I&&$)try{$.send(JSON.stringify({t:"exit",code:Z}))}catch{}G({kind:"resolved",reason:"shell_exited"})});let o=(H.loadProxy??p)()?.url;try{$=(H.connect??Wz)(J.relay_url,o)}catch{G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$.binaryType="arraybuffer",$.onopen=()=>{if(X||!$)return;I=!0;try{$.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let Z of O.splice(0))$.send(Z);S=0}catch{G({kind:"resolved",reason:"relay_closed"});return}B=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},$.onmessage=(Z)=>{if(X||!F)return;let W=Z.data;if(typeof W==="string"){let L;try{L=JSON.parse(W)}catch{return}if(!u(L))return;if(L.t==="resize"){try{F.resize(g(L.cols,J.cols),g(L.rows,J.rows))}catch{}return}if(L.t==="close")G({kind:"resolved",reason:"client_closed"});return}let q=W instanceof ArrayBuffer?new Uint8Array(W):ArrayBuffer.isView(W)?new Uint8Array(W.buffer,W.byteOffset,W.byteLength):null;if(!q||q.byteLength===0)return;x+=q.byteLength;try{F.write(q)}catch{}},$.onclose=()=>{if(X)return;if(!B){G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}G({kind:"resolved",reason:"relay_closed"})},$.onerror=()=>{if(X||B)return;G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
- export{m as rg,Hz as sg,y as tg,Jz as ug,Zz as vg,c as wg,jz as xg,Sz as yg,Nz as zg,Wz as Ag,Tz as Bg};
2
+ import{Tg as p}from"./vm-hands-entry-lite-ht482g94.js";import{_g as h}from"./vm-hands-entry-lite-rmaawtgm.js";import{gh as s}from"./vm-hands-entry-lite-k90ysszf.js";import{tj as d}from"./vm-hands-entry-lite-ecgyzbdp.js";import{Gj as i}from"./vm-hands-entry-lite-3pecyp8y.js";import{Kk as P}from"./vm-hands-entry-lite-04y4b7c6.js";import{Mk as V}from"./vm-hands-entry-lite-hkvkfq0z.js";import{existsSync as U,realpathSync as l,statSync as e}from"fs";import{platform as f}from"os";import{isAbsolute as r,sep as zz}from"path";import{existsSync as n}from"fs";import{createRequire as t}from"module";var E=P(h)(()=>t(import.meta.url)("bun:ffi"),n);function m(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&E.available()}function w(z=process.env){return E.defaultShell(z)}function k(z){return E.shellArgs(z)}function v(z){let H=E.spawn({...z,env:z.environment});return H.exited.then(()=>H.close()),{write:(Q)=>H.write(Q),resize:(Q,J)=>H.resize(Q,J),kill:()=>H.close(),exited:H.exited}}var Hz=43200000,y=s,Jz=4,Qz=/^[A-Za-z0-9._:-]{1,160}$/,Vz=1000;function u(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function g(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(Vz,Math.max(1,Math.floor(z)))}function Zz(z,H=Date.now()){let Q=["relay_url","session_id","expires_at"],J=new Set([...Q,"cols","rows","cwd","workspace"]);if(!u(z)||Q.some((C)=>!(C in z))||Object.keys(z).some((C)=>!J.has(C)))throw new V("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:N,session_id:Y,expires_at:R}=z;if(typeof N!=="string")throw new V("invalid_pty_request","Reason terminal relay URL is missing.");let K;try{K=new URL(N)}catch{throw new V("invalid_pty_request","Reason terminal relay URL is invalid.")}if(K.protocol!=="wss:"&&K.protocol!=="ws:"||K.username||K.password)throw new V("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!Qz.test(Y))throw new V("invalid_pty_request","Reason terminal session identity is invalid.");let D=typeof R==="string"?Date.parse(R):Number.NaN;if(!Number.isFinite(D)||D<=H)throw new V("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new V("invalid_pty_request","Reason terminal working directory is invalid.");let j=z.workspace===void 0?void 0:i(z.workspace);if(j===null||j&&z.cwd!==void 0)throw new V("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:N,session_id:Y,expires_at:new Date(Math.min(D,H+Hz)).toISOString(),cols:g(z.cols,80),rows:g(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...j?{workspace:j}:{}}}function $z(z,H){if(f()==="win32")[z,H]=[z.toLowerCase(),H.toLowerCase()];return H===z||H.startsWith(z+zz)}function c(z,H){if(H===void 0)return z;if(!r(H))throw new V("pty_cwd_invalid","Reason terminal working directory must be absolute.");let Q;try{Q=l(H)}catch{throw new V("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!$z(z,Q))throw new V("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!e(Q).isDirectory())throw new V("pty_cwd_invalid","Reason terminal working directory is not a directory.");return Q}function jz(z=process.env){if(f()==="win32")return w(z);let H=z.SHELL;if(H&&r(H)&&U(H))return H;for(let Q of f()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(U(Q))return Q;return"/bin/sh"}function Gz(){let z=globalThis.Bun;if(!z)throw new V("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Sz(){if(f()==="win32")return m();return typeof globalThis.Bun<"u"}var Nz=(z)=>{if(f()==="win32")try{return v({...z,file:z.shell,args:k(z.shell),environment:{...z.environment,TERM:"xterm-256color"}})}catch{throw new V("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let H=Gz()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,N)=>{z.onData(N)}}}),Q=H.terminal;if(!Q){try{H.kill()}catch{}throw new V("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>Q.write(J),resize:(J,N)=>Q.resize(J,N),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Wz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},M=new Set;function Kz(z){if(M.size>=Jz||M.has(z))return null;M.add(z);let H=!1;return()=>{if(H)return;H=!0,M.delete(z)}}async function Tz(z,H={}){let Q=H.now??Date.now,J=Zz(z.payload,Q()),N=Kz(z.operationId);if(!N)throw new V("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=Q(),R,K,D;try{let j=J.workspace?d(z.root,J.workspace):void 0;R=j?c(U(j.boundary)?l(j.boundary):j.boundary,j.path):c(z.root,J.cwd),K=H.environment??process.env,D=H.shellPath??jz(K)}catch(j){throw N(),j}return await new Promise((j,C)=>{let F=null,$=null,I=!1,B=!1,X=!1,_=null,b=0,x=0,O=[],S=0,T=null,G=(Z)=>{if(X)return;if(X=!0,T)clearTimeout(T);z.signal.removeEventListener("abort",A);try{F?.kill()}catch{}try{$?.close(1000,"pty_session_over")}catch{}if(N(),Z.kind==="rejected"){C(Z.error);return}let W={reason:Z.reason,exit_code:_,output_bytes:b,input_bytes:x,duration_ms:Math.max(0,Q()-Y)};z.emitEvent("pty.stopped",{...W}).catch(()=>{return}),j({...W})},A=()=>{let Z=z.signal.reason;G({kind:"rejected",error:Z instanceof V?Z:new V("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){A();return}z.signal.addEventListener("abort",A,{once:!0}),T=setTimeout(()=>G({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-Q()));let a=(Z)=>{if(b+=Z.byteLength,!I||!$){if(O.push(Z),S+=Z.byteLength,S>y)G({kind:"resolved",reason:"output_backpressure"});return}try{$.send(Z)}catch{G({kind:"resolved",reason:"relay_closed"});return}if($.bufferedAmount>y)G({kind:"resolved",reason:"output_backpressure"})};try{F=(H.spawnPty??Nz)({shell:D,args:["-i","-l"],cwd:R,cols:J.cols,rows:J.rows,environment:K,onData:(Z)=>{if(!X)a(Z)}})}catch(Z){G({kind:"rejected",error:Z instanceof V?Z:new V("pty_spawn_failed","Reason could not start the terminal shell.")});return}F.exited.then((Z)=>{if(X)return;if(_=Z,I&&$)try{$.send(JSON.stringify({t:"exit",code:Z}))}catch{}G({kind:"resolved",reason:"shell_exited"})});let o=(H.loadProxy??p)()?.url;try{$=(H.connect??Wz)(J.relay_url,o)}catch{G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$.binaryType="arraybuffer",$.onopen=()=>{if(X||!$)return;I=!0;try{$.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let Z of O.splice(0))$.send(Z);S=0}catch{G({kind:"resolved",reason:"relay_closed"});return}B=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},$.onmessage=(Z)=>{if(X||!F)return;let W=Z.data;if(typeof W==="string"){let L;try{L=JSON.parse(W)}catch{return}if(!u(L))return;if(L.t==="resize"){try{F.resize(g(L.cols,J.cols),g(L.rows,J.rows))}catch{}return}if(L.t==="close")G({kind:"resolved",reason:"client_closed"});return}let q=W instanceof ArrayBuffer?new Uint8Array(W):ArrayBuffer.isView(W)?new Uint8Array(W.buffer,W.byteOffset,W.byteLength):null;if(!q||q.byteLength===0)return;x+=q.byteLength;try{F.write(q)}catch{}},$.onclose=()=>{if(X)return;if(!B){G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}G({kind:"resolved",reason:"relay_closed"})},$.onerror=()=>{if(X||B)return;G({kind:"rejected",error:new V("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
+ export{m as tg,Hz as ug,y as vg,Jz as wg,Zz as xg,c as yg,jz as zg,Sz as Ag,Nz as Bg,Wz as Cg,Tz as Dg};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_i as I}from"./vm-hands-entry-lite-sbn9bmf7.js";import{Ak as U,Dk as C,Ek as O,Fk as g,xk as R}from"./vm-hands-entry-lite-ek5r435m.js";import{spawn as S}from"child_process";import{existsSync as x,mkdirSync as T,readFileSync as w,writeFileSync as E}from"fs";import{homedir as H}from"os";import{basename as L,delimiter as D,join as G,win32 as $}from"path";var N=process.platform==="win32"?U("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",b=N.split(D),_=5000,j=65536,k=new Set(["zsh","bash"]),f=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],P=(z,J)=>new Promise((B,Q)=>{let K;try{K=S(z,[...J],{...C(),stdio:["ignore","pipe","ignore"]}),O(K)}catch(X){Q(X);return}let W=[],V=0,Z=null,q=(X)=>{Z??=Error(X);try{if(K.pid!==void 0)g(K.pid,"SIGKILL")}catch{}},F=setTimeout(()=>q("login_shell_timeout"),_);K.stdout?.on("data",(X)=>{if(V+=X.length,V>j)q("login_shell_output_too_large");else W.push(X)}),K.once("error",(X)=>{clearTimeout(F),Q(X)}),K.once("close",(X)=>{if(clearTimeout(F),Z)Q(Z);else if(X!==0)Q(Error("login_shell_exit_nonzero"));else B(Buffer.concat(W).toString("utf8"))})});function v(z){return typeof z==="string"&&z.startsWith("/")&&!z.includes("\x00")&&k.has(L(z))}function M(z){let J=new Set,B=[];for(let Q of z){if(J.has(Q))continue;J.add(Q),B.push(Q)}return B}function A(z,J=process.platform){let B=J==="win32",Q=z.split(`
2
+ import{aj as I}from"./vm-hands-entry-lite-6ffdqdyw.js";import{Ck as U,Fk as C,Gk as O,Hk as g,zk as R}from"./vm-hands-entry-lite-mkynexaq.js";import{spawn as S}from"child_process";import{existsSync as x,mkdirSync as T,readFileSync as w,writeFileSync as E}from"fs";import{homedir as H}from"os";import{basename as L,delimiter as D,join as G,win32 as $}from"path";var N=process.platform==="win32"?U("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",b=N.split(D),_=5000,j=65536,k=new Set(["zsh","bash"]),f=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],P=(z,J)=>new Promise((B,Q)=>{let K;try{K=S(z,[...J],{...C(),stdio:["ignore","pipe","ignore"]}),O(K)}catch(X){Q(X);return}let W=[],V=0,Z=null,q=(X)=>{Z??=Error(X);try{if(K.pid!==void 0)g(K.pid,"SIGKILL")}catch{}},F=setTimeout(()=>q("login_shell_timeout"),_);K.stdout?.on("data",(X)=>{if(V+=X.length,V>j)q("login_shell_output_too_large");else W.push(X)}),K.once("error",(X)=>{clearTimeout(F),Q(X)}),K.once("close",(X)=>{if(clearTimeout(F),Z)Q(Z);else if(X!==0)Q(Error("login_shell_exit_nonzero"));else B(Buffer.concat(W).toString("utf8"))})});function v(z){return typeof z==="string"&&z.startsWith("/")&&!z.includes("\x00")&&k.has(L(z))}function M(z){let J=new Set,B=[];for(let Q of z){if(J.has(Q))continue;J.add(Q),B.push(Q)}return B}function A(z,J=process.platform){let B=J==="win32",Q=z.split(`
3
3
  `).at(-1)??"",K=[];for(let W of Q.split(B?";":":")){let V=W.trim();if(B?!$.isAbsolute(V):!V.startsWith("/"))continue;if(V.includes("\x00"))continue;if(I(V))continue;K.push(V)}return M(K)}function y(z){let J=z?.home??H(),B=z?.directoryExists??x,Q=f.map((K)=>G(J,...K)).filter((K)=>{try{return B(K)}catch{return!1}});return M([...Q,...process.platform==="win32"?A(process.env.PATH??process.env.Path??""):[],...b]).join(D)}async function d(z){let J=z?.shell??process.env.SHELL,B=()=>({path:y({home:z?.home,directoryExists:z?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!v(J))return B();let Q;try{Q=await(z?.runLoginShell??P)(J,["-lic",'printf %s "$PATH"'])}catch{return B()}if(Buffer.byteLength(Q,"utf8")>j)return B();let K=A(Q);if(K.length===0)return B();return{path:M([...K,...b]).join(":"),source:"login_shell"}}function n(z){let J=null;return()=>{return J??=d(z),J}}function Y(z){if(z===void 0||z.includes("\x00")||Buffer.byteLength(z,"utf8")>32768)return;return z}function r(z){let J=z.source??process.env,B={HOME:z.home,PATH:z.path??N,TMPDIR:z.temporaryDirectory,SHELL:Y(J.SHELL)??"/bin/zsh",LANG:Y(J.LANG)??"C.UTF-8",LC_ALL:Y(J.LC_ALL)??Y(J.LANG)??"C.UTF-8"},Q=Y(J.LC_CTYPE),K=Y(J.TERM),W=Y(J.COLORTERM);if(Q)B.LC_CTYPE=Q;if(K)B.TERM=K;if(W)B.COLORTERM=W;if(process.platform==="win32"){for(let V of h){let Z=Y(J[V]);if(Z)B[V]=Z}B.TEMP=B.TMP=z.temporaryDirectory,B.SHELL=R()??B.SHELL,B.PATH=m(B.PATH)}return B}function m(z,J=G(H(),".reason","python3")){let B=(W)=>z.split($.delimiter).filter((V)=>V&&!/[\\/]WindowsApps[\\/]?$/i.test(V)).map((V)=>$.join(V,W)).find((V)=>x(V)),Q=B("python.exe");if(B("python3.exe")||!Q)return z;let K=`#!/bin/sh
4
4
  exec "${Q.replaceAll("\\","/")}" "$@"
5
5
  `;try{let W=G(J,"python3");if(!x(W)||w(W,"utf8")!==K)T(J,{recursive:!0}),E(W,K)}catch{return z}return[J,z].join($.delimiter)}var h=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$e as OJ,Hf as jJ,Se as _J,_e as gJ,af as RJ,bf as IJ}from"./vm-hands-entry-lite-qvj5560v.js";import{createHash as m,randomBytes as WJ}from"crypto";import{closeSync as MJ,fsyncSync as TJ,mkdirSync as aJ,openSync as DJ,renameSync as nJ,rmSync as tJ,statSync as qJ,writeSync as xJ,constants as y}from"fs";import{join as t}from"path";var eJ=1;var e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function FJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new F("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function AJ(J,Q){let{payload:$,authority:z}=J;if(!$||typeof $!=="object"||Array.isArray($)||!z||typeof z!=="object"||Array.isArray(z)||!Q.deviceId||!Q.rootId||$.run_id!==Q.runId||$.device_id!==Q.deviceId||z.device_id!==Q.deviceId||$.root_id!==Q.rootId||Q.snapshotId!==void 0&&$.snapshot_id!==Q.snapshotId)throw new F("vm_hands_env_invalid","environment does not match this Hands");return $}function SJ(J){if(J.capability!=="hands.connect")throw new F("vm_hands_bind_invalid","not a hands.connect claim");let Q=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Q.workspace_id==="string"&&e.test(Q.workspace_id)?Q.workspace_id:J.run_id,brain_generation:Q.target_generation,fence_id:Q.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Q.hands_confinement??""),browser_egress:Q.browser_egress??null,policy_digest:Q.vm_hands_policy_digest},cwd:typeof Q.cwd==="string"?Q.cwd:"",claim:J,env:FJ(J)?J.environment_sealed:null,workspace_deferred:JQ(J)}}function JQ(J){let Q=J.payload[OJ];if(Q===void 0)return!1;if(Q!==!0||J.payload.vm_hands_env_deferred!==!0||J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class F extends Error{code;constructor(J,Q){super(Q);this.code=J}}var I=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),b=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function c(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(c).join(",")}]`;return`{${Object.keys(J).sort().map((Q)=>`${JSON.stringify(Q)}:${c(J[Q])}`).join(",")}}`}async function SQ(J){let Q=await crypto.subtle.importKey("pkcs8",b(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),$=b(J.device_key.spki),z=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),L=new Uint8Array(await crypto.subtle.exportKey("spki",z.publicKey)),U=m("sha256").update($).digest("base64url");return{signing:{privateKey:Q},agreement:z,signingSpki:$,agreementSpki:L,fingerprint:U}}var QQ=4;class ZQ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;commandsSinceVerified=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(J){let Q=this.structural.then(J,J);return this.structural=Q.catch(()=>{return}),Q}constructor(J,Q,$,z){this.init=J;this.keys=Q;this.hooks=$;this.options=z;if(!e.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new F("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new F("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Q of this.bound.values())if(Q.runId===J)return!0;return!1}bindIdForRun(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Q,$){for(let z=Date.now()+Q;;){let L=this.bound.get(J);if(!L)return!1;if(L.envInstalled)return!0;if(Date.now()>=z||$?.aborted)return!1;await new Promise((U)=>setTimeout(U,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new F("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new F("vm_hands_challenge_invalid","bad register challenge");let Q={challenge:J,t:"register",v:eJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:I(this.keys.signingSpki),env_public_key:I(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:I(WJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},$=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(c(Q)));return{...Q,device_signature:I($)}}async helloFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","hello before register");let $=String((this.options.now??Date.now)()),z=I(WJ(32)),L=jJ({method:"GET",pathAndQuery:_J,timestamp:$,nonce:z,challenge:J,bodySha256:m("sha256").update("").digest("hex")}),U=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(L)));return{t:"hello",timestamp:$,nonce:z,signature:I($Q(U)),...Q?{vm_hands_previous_connection:Q}:{}}}registered(){if(this.identity!=="identity_free")throw new F("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new F("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new F("vm_hands_bind_invalid","bad bind");for(let $ of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!e.test($))throw new F("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new F("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new F("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new F("vm_hands_bind_invalid","bad policy or nonce");if(m("sha256").update(c({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new F("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some(($)=>$.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new F("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=QQ)throw new F("vm_hands_busy","every bind slot is held");if(this.grants.size)throw new F("vm_hands_busy","a bind waits for its workspace beside the setup");if(J.workspace_deferred&&(this.liveBindIds.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),J.workspace_deferred){let $,z,L=new Promise((U,N)=>{$=U,z=N});L.catch(()=>{return}),this.grants.set(J.bind_id,{promise:L,resolve:$,reject:z})}return this.exclusive(()=>this.setUp(J))}async setUp(J){let Q=[...this.bound.keys()],$=null,z=!1,L=this.grants.get(J.bind_id);try{if(L&&(Q.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(Q.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new F("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.commandsSinceVerified)await this.hooks.killAndVerifyPayload(),this.unverified.clear(),this.commandsSinceVerified=!1;else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({own:!0}),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Q}),this.unverified.clear();this.servedRun=!0,z=!0;let{launchId:U,applied:N,readyData:O}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim,...L?{workspaceGrant:L.promise}:{}}),T=this.hooks.restatLayout();this.hooks.verifyMounts?.();let D=null,A=null;if(J.env){let w=J.claim?.owner??{},v=AJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,D=this.hooks.installEnvironment(J.bind_id,v),A=typeof v.snapshot_id==="string"&&v.snapshot_id?v.snapshot_id:null,$=this.writeJobEnvRootOnly(J.bind_id,v)}if(this.unbinding.has(J.bind_id))throw new F("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:D!==null,rootId:J.claim?.root_id??"",envDirectory:$}),this.binding.delete(J.bind_id),this.grants.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:D,snapshot_id:A,layout:T,...O?{ready_data:O}:{},policy_digest:m("sha256").update(c({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(U){if($)KJ($);if(z){let O=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:O,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id),this.grants.delete(J.bind_id);let N=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof F?U:new F(N,"executor refused the bind")}}grantWorkspace(J){let Q=this.grants.get(J);if(!Q)throw new F("vm_hands_not_binding","no pre-bind waits for a workspace grant");Q.resolve()}abandonWorkspaceGrant(J){this.grants.get(J)?.reject(new F("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(J){let Q=this.bound.get(J.attemptId);if(!Q||this.unbinding.has(J.attemptId))throw new F("vm_hands_not_bound","environment delivered while not bound");if(!e.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new F("vm_hands_env_invalid","bad snapshot id");let $=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==$)throw new F("vm_hands_env_invalid","bad env envelope");let z=AJ(await this.openSealed(J.sealed,$),{runId:Q.runId,deviceId:J.deviceId,rootId:Q.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let L=this.hooks.installEnvironment(Q.bindId,z);if(Q.envInstalled=!0,Q.envDirectory)KJ(Q.envDirectory);return Q.envDirectory=null,Q.envDirectory=this.writeJobEnvRootOnly(`${Q.bindId}-r${L}`,z),{snapshot_id:J.snapshotId,installed_revision:L,installed:!0}}async attestFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new F("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new F("vm_hands_attest_invalid","attest beside a bind");let $=await this.hooks.runProbe({nonce:Q,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Q,exit_code:$.exitCode,markers:$.markers,proof_dir_inode:$.proofDirInode,script_sha256:m("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Q=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),this.abandonWorkspaceGrant(J),Q)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Q))}async retryUnbind(J){if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(J,this.unverifiedTeardowns.get(J)??null,!0)})}async tearDown(J,Q,$=!1){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((U)=>U!==J),L=!z.length&&($||!this.commandsSinceVerified);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:L?{bindId:J,own:!0}:void 0)}catch(U){if(this.unverified.add(J),!this.unverifiedTeardowns.has(J))this.unverifiedTeardowns.set(J,Q);throw U}if(this.unverified.delete(J),!z.length&&!$)this.unverified.clear(),this.commandsSinceVerified=!1;if(Q?.envDirectory)KJ(Q.envDirectory);return this.unverifiedTeardowns.delete(J),{bind_id:Q?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length||$?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Q){let $=()=>{throw new F("vm_hands_env_invalid","env did not decrypt")},z=await crypto.subtle.importKey("spki",b(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch($),L=await crypto.subtle.deriveKey({name:"ECDH",public:z},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),U=await crypto.subtle.decrypt({name:"AES-GCM",iv:b(J.iv),additionalData:new TextEncoder().encode(Q)},L,b(J.ct)).catch($),N=JSON.parse(new TextDecoder().decode(U));if(!N||typeof N!=="object"||Array.isArray(N))throw new F("vm_hands_env_invalid","env not an object");return N}writeJobEnvRootOnly(J,Q){let $=t(this.options.envRoot,`bind-${J}`);aJ($,{mode:448});let z=qJ($);if(!z.isDirectory()||(z.mode&63)!==0||z.uid!==(process.getuid?.()??-1))throw new F("vm_hands_env_dir_unsafe","env directory is not root's 0700");let L=Q.variables&&typeof Q.variables==="object"?Q.variables:{},U=Object.entries(L).filter(([T,D])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(T)&&typeof D==="string").map(([T,D])=>`export ${T}='${String(D).replaceAll("'","'\\''")}'`).join(`
2
+ import{$e as OJ,Jf as jJ,Se as _J,_e as gJ,af as RJ,bf as IJ}from"./vm-hands-entry-lite-09yt840b.js";import{createHash as m,randomBytes as WJ}from"crypto";import{closeSync as MJ,fsyncSync as TJ,mkdirSync as aJ,openSync as DJ,renameSync as nJ,rmSync as tJ,statSync as qJ,writeSync as xJ,constants as y}from"fs";import{join as t}from"path";var eJ=1;var e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function FJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new F("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function AJ(J,Q){let{payload:$,authority:z}=J;if(!$||typeof $!=="object"||Array.isArray($)||!z||typeof z!=="object"||Array.isArray(z)||!Q.deviceId||!Q.rootId||$.run_id!==Q.runId||$.device_id!==Q.deviceId||z.device_id!==Q.deviceId||$.root_id!==Q.rootId||Q.snapshotId!==void 0&&$.snapshot_id!==Q.snapshotId)throw new F("vm_hands_env_invalid","environment does not match this Hands");return $}function SJ(J){if(J.capability!=="hands.connect")throw new F("vm_hands_bind_invalid","not a hands.connect claim");let Q=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Q.workspace_id==="string"&&e.test(Q.workspace_id)?Q.workspace_id:J.run_id,brain_generation:Q.target_generation,fence_id:Q.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Q.hands_confinement??""),browser_egress:Q.browser_egress??null,policy_digest:Q.vm_hands_policy_digest},cwd:typeof Q.cwd==="string"?Q.cwd:"",claim:J,env:FJ(J)?J.environment_sealed:null,workspace_deferred:JQ(J)}}function JQ(J){let Q=J.payload[OJ];if(Q===void 0)return!1;if(Q!==!0||J.payload.vm_hands_env_deferred!==!0||J.environment_sealed!==void 0)throw new F("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class F extends Error{code;constructor(J,Q){super(Q);this.code=J}}var I=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),b=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function c(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(c).join(",")}]`;return`{${Object.keys(J).sort().map((Q)=>`${JSON.stringify(Q)}:${c(J[Q])}`).join(",")}}`}async function SQ(J){let Q=await crypto.subtle.importKey("pkcs8",b(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),$=b(J.device_key.spki),z=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),L=new Uint8Array(await crypto.subtle.exportKey("spki",z.publicKey)),U=m("sha256").update($).digest("base64url");return{signing:{privateKey:Q},agreement:z,signingSpki:$,agreementSpki:L,fingerprint:U}}var QQ=4;class ZQ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;commandsSinceVerified=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(J){let Q=this.structural.then(J,J);return this.structural=Q.catch(()=>{return}),Q}constructor(J,Q,$,z){this.init=J;this.keys=Q;this.hooks=$;this.options=z;if(!e.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new F("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new F("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Q of this.bound.values())if(Q.runId===J)return!0;return!1}bindIdForRun(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Q,$){for(let z=Date.now()+Q;;){let L=this.bound.get(J);if(!L)return!1;if(L.envInstalled)return!0;if(Date.now()>=z||$?.aborted)return!1;await new Promise((U)=>setTimeout(U,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Q of this.bound.values())if(Q.runId===J)return Q.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new F("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new F("vm_hands_challenge_invalid","bad register challenge");let Q={challenge:J,t:"register",v:eJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:I(this.keys.signingSpki),env_public_key:I(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:I(WJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},$=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(c(Q)));return{...Q,device_signature:I($)}}async helloFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","hello before register");let $=String((this.options.now??Date.now)()),z=I(WJ(32)),L=jJ({method:"GET",pathAndQuery:_J,timestamp:$,nonce:z,challenge:J,bodySha256:m("sha256").update("").digest("hex")}),U=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(L)));return{t:"hello",timestamp:$,nonce:z,signature:I($Q(U)),...Q?{vm_hands_previous_connection:Q}:{}}}registered(){if(this.identity!=="identity_free")throw new F("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new F("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new F("vm_hands_bind_invalid","bad bind");for(let $ of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!e.test($))throw new F("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new F("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new F("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new F("vm_hands_bind_invalid","bad policy or nonce");if(m("sha256").update(c({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new F("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some(($)=>$.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new F("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=QQ)throw new F("vm_hands_busy","every bind slot is held");if(this.grants.size)throw new F("vm_hands_busy","a bind waits for its workspace beside the setup");if(J.workspace_deferred&&(this.liveBindIds.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),J.workspace_deferred){let $,z,L=new Promise((U,N)=>{$=U,z=N});L.catch(()=>{return}),this.grants.set(J.bind_id,{promise:L,resolve:$,reject:z})}return this.exclusive(()=>this.setUp(J))}async setUp(J){let Q=[...this.bound.keys()],$=null,z=!1,L=this.grants.get(J.bind_id);try{if(L&&(Q.length||this.commandsSinceVerified))throw new F("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(Q.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new F("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.commandsSinceVerified)await this.hooks.killAndVerifyPayload(),this.unverified.clear(),this.commandsSinceVerified=!1;else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({own:!0}),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Q}),this.unverified.clear();this.servedRun=!0,z=!0;let{launchId:U,applied:N,readyData:O}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim,...L?{workspaceGrant:L.promise}:{}}),T=this.hooks.restatLayout();this.hooks.verifyMounts?.();let D=null,A=null;if(J.env){let w=J.claim?.owner??{},v=AJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,D=this.hooks.installEnvironment(J.bind_id,v),A=typeof v.snapshot_id==="string"&&v.snapshot_id?v.snapshot_id:null,$=this.writeJobEnvRootOnly(J.bind_id,v)}if(this.unbinding.has(J.bind_id))throw new F("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:D!==null,rootId:J.claim?.root_id??"",envDirectory:$}),this.binding.delete(J.bind_id),this.grants.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:D,snapshot_id:A,layout:T,...O?{ready_data:O}:{},policy_digest:m("sha256").update(c({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(U){if($)KJ($);if(z){let O=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:O,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id),this.grants.delete(J.bind_id);let N=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof F?U:new F(N,"executor refused the bind")}}grantWorkspace(J){let Q=this.grants.get(J);if(!Q)throw new F("vm_hands_not_binding","no pre-bind waits for a workspace grant");Q.resolve()}abandonWorkspaceGrant(J){this.grants.get(J)?.reject(new F("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(J){let Q=this.bound.get(J.attemptId);if(!Q||this.unbinding.has(J.attemptId))throw new F("vm_hands_not_bound","environment delivered while not bound");if(!e.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new F("vm_hands_env_invalid","bad snapshot id");let $=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==$)throw new F("vm_hands_env_invalid","bad env envelope");let z=AJ(await this.openSealed(J.sealed,$),{runId:Q.runId,deviceId:J.deviceId,rootId:Q.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let L=this.hooks.installEnvironment(Q.bindId,z);if(Q.envInstalled=!0,Q.envDirectory)KJ(Q.envDirectory);return Q.envDirectory=null,Q.envDirectory=this.writeJobEnvRootOnly(`${Q.bindId}-r${L}`,z),{snapshot_id:J.snapshotId,installed_revision:L,installed:!0}}async attestFrame(J,Q){if(this.identity==="identity_free")throw new F("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new F("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new F("vm_hands_attest_invalid","attest beside a bind");let $=await this.hooks.runProbe({nonce:Q,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Q,exit_code:$.exitCode,markers:$.markers,proof_dir_inode:$.proofDirInode,script_sha256:m("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Q=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),this.abandonWorkspaceGrant(J),Q)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Q))}async retryUnbind(J){if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(J))throw new F("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(J,this.unverifiedTeardowns.get(J)??null,!0)})}async tearDown(J,Q,$=!1){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((U)=>U!==J),L=!z.length&&($||!this.commandsSinceVerified);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:L?{bindId:J,own:!0}:void 0)}catch(U){if(this.unverified.add(J),!this.unverifiedTeardowns.has(J))this.unverifiedTeardowns.set(J,Q);throw U}if(this.unverified.delete(J),!z.length&&!$)this.unverified.clear(),this.commandsSinceVerified=!1;if(Q?.envDirectory)KJ(Q.envDirectory);return this.unverifiedTeardowns.delete(J),{bind_id:Q?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length||$?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Q){let $=()=>{throw new F("vm_hands_env_invalid","env did not decrypt")},z=await crypto.subtle.importKey("spki",b(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch($),L=await crypto.subtle.deriveKey({name:"ECDH",public:z},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),U=await crypto.subtle.decrypt({name:"AES-GCM",iv:b(J.iv),additionalData:new TextEncoder().encode(Q)},L,b(J.ct)).catch($),N=JSON.parse(new TextDecoder().decode(U));if(!N||typeof N!=="object"||Array.isArray(N))throw new F("vm_hands_env_invalid","env not an object");return N}writeJobEnvRootOnly(J,Q){let $=t(this.options.envRoot,`bind-${J}`);aJ($,{mode:448});let z=qJ($);if(!z.isDirectory()||(z.mode&63)!==0||z.uid!==(process.getuid?.()??-1))throw new F("vm_hands_env_dir_unsafe","env directory is not root's 0700");let L=Q.variables&&typeof Q.variables==="object"?Q.variables:{},U=Object.entries(L).filter(([T,D])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(T)&&typeof D==="string").map(([T,D])=>`export ${T}='${String(D).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,N=t($,`.job.env.${WJ(8).toString("hex")}`),O=DJ(N,y.O_WRONLY|y.O_CREAT|y.O_EXCL|y.O_NOFOLLOW,384);try{xJ(O,U),TJ(O)}finally{MJ(O)}return nJ(N,t($,"job.env")),$}}function KJ(J){try{let Q=t(J,"job.env"),$=qJ(Q).size,z=DJ(Q,y.O_WRONLY|y.O_NOFOLLOW);try{xJ(z,Buffer.alloc($)),TJ(z)}finally{MJ(z)}}catch{}tJ(J,{recursive:!0,force:!0})}function $Q(J){if(J.length!==64)throw new F("vm_hands_signature_invalid","unexpected ECDSA signature length");let Q=(L)=>{let U=0;while(U<L.length-1&&L[U]===0)U++;let N=L.subarray(U),O=N[0]&128?Uint8Array.of(0,...N):N;return Uint8Array.of(2,O.length,...O)},$=Q(J.subarray(0,32)),z=Q(J.subarray(32));return Uint8Array.of(48,$.length+z.length,...$,...z)}import{randomUUID as zQ}from"crypto";var XQ="/app/local-runtime/session?register=vm_hands_v1",YQ="/app/local-runtime",wJ=25000,hJ=20000,GQ=1e4,yJ=5000,kJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),PJ=75000,WQ=2000,KQ=1e4,FQ=new Set(["vm_hands_no_register","vm_hands_register_failed"]),PQ=3,CQ=20000,NQ=250,UQ=2000;function fJ(J){let Q=Math.min(NQ*2**(J-1),UQ);return Math.round(Q/2+Math.random()*Q/2)}var EQ=5000;function BQ(J){return J>=500||J===408||J===429}var JJ=20000;function HJ(J,Q){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Q}class V extends Error{}var LQ=64,VJ=[1000,2000,4000,8000,15000,30000,60000,120000];function mJ(J){let Q=J&&typeof J==="object"&&"code"in J?J.code:null;return typeof Q==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(Q)?Q:"vm_hands_unbind_failed"}function AQ(J,Q,$,z,L){let U=$.turn.claim.attempt_id,N=J.healing??=new Set;if(N.has(U))return;N.add(U);let O=$.turn.claim.operation_id;(async()=>{for(let[T,D]of VJ.entries()){if(z.aborted)return;if(await new Promise((A)=>{let w=setTimeout(A,D);w.unref?.(),z.addEventListener("abort",()=>{clearTimeout(w),A()},{once:!0})}),z.aborted)return;try{let A=await Q.retryUnbind(U);L("vm_hands.unbind_healed",{operation_id:O,attempt:T+1}),J.receipts.push({...$,unbound:A}),J.flushReceipts?.();return}catch(A){let w=mJ(A);if(L("vm_hands.unbind_unverified",{operation_id:O,code:w,attempt:T+1}),w==="vm_hands_unbind_unknown")return}}L("vm_hands.unbind_heal_exhausted",{operation_id:O,attempts:VJ.length})})().finally(()=>N.delete(U))}async function bJ(J,Q){let $=[...J.modelOps.get(Q)??[]];for(let z of $)z.abort.abort();await Promise.race([Promise.all($.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,yJ))])}async function _Q(J){let Q=[...J.personTerminals];for(let $ of Q)$.abort.abort();if(Q.length)await Promise.race([Promise.all(Q.map(($)=>$.settled)),new Promise(($)=>setTimeout($,yJ))]);return Q.length}async function p(J,Q,$){return await bJ(J,$),Q.unbind($)}function QJ(J){for(let Q of J.outbox?.splice(0)??[])Q.reject(Error("vm_hands_attempt_ended"))}var vJ=15000,OQ=1e4,jQ=1000;async function vQ(J){let Q=Date.now(),$={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:0},z=J.log??(()=>{}),L=async(O)=>{for(let[T,D]of[...$.turns]){$.turns.delete(T),J.onTurn?.(T,null),QJ(D);let A=await p($,J.agent,T).catch(()=>null);if(A)$.receipts.push({turn:D,failure:"vm_hands_bind_lost",unbound:A});z("vm_hands.bound_dropped",{reason:O})}},U=0,N=0;try{for(let O=0;!J.signal.aborted;O++){let T=await MQ(J,$).catch((A)=>{if(A instanceof F&&$.deviceId===null&&A.code==="vm_hands_no_session"&&Date.now()-Q<KQ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(A instanceof F&&$.deviceId===null&&FQ.has(A.code)&&U<PQ&&Date.now()-Q<CQ)return U++,N=fJ(U),z("vm_hands.register_retry",{attempt:U,code:A.code,delay_ms:N}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(A instanceof F&&$.deviceId===null)throw A;return{closeCode:0,closeReason:A instanceof Error?A.message:String(A)}});if(z("vm_hands.session_closed",{close_code:T.closeCode,reason:T.closeReason.slice(0,120),registered:$.deviceId!==null}),T.closeCode===4401||$.attest==="refused")return;if(J.signal.aborted)return;if($.turns.size&&Date.now()-$.lostAt>=PJ)await L("reconnect_deadline");if($.served)$.served=!1,O=0;let D=T.closeReason==="drain_reconnect"?0:T.closeReason==="vm_hands_register_retry"?N:T.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(O,5),2000):$.turns.size?Math.min(250*2**Math.min(O,5),5000,Math.max(0,$.lostAt+PJ-Date.now())):Math.min(500*2**O,30000);if(await new Promise((A)=>setTimeout(A,D)),$.turns.size&&Date.now()-$.lostAt>=PJ)await L("reconnect_deadline")}}finally{await L("session_ended")}}async function MQ(J,Q){let $=Q.deviceId,z=J.log??(()=>{}),L=$?`/app/local-runtime/session?device_id=${encodeURIComponent($)}`:XQ,U=`${J.apiOrigin.replace(/^http/,"ws")}${L}`,N=new WebSocket(U),O=0,T="",D=new Map,A=[],w=null,v=new Promise((Z)=>{N.onclose=(Y)=>{O=Y.code,T=Y.reason;for(let X of D.values())X.reject(new V(`session closed ${Y.code}`));for(let X of Q.attestWaiters.splice(0))X(!1);D.clear(),Z()}});N.onmessage=(Z)=>{let Y;try{Y=JSON.parse(String(Z.data))}catch{N.close(4400);return}if(Y.t==="res"){let X=Y;D.get(X.id)?.resolve({status:X.status,body:X.body}),D.delete(X.id);return}if(Y.t==="reconnect"){let X=Math.max(0,Math.min(Number(Y.after_ms)||0,jQ));z("vm_hands.drain_reconnect",{after_ms:X}),setTimeout(()=>{try{N.close(4001,"drain_reconnect")}catch{}},X).unref?.();return}if(!w?.(Y))A.push(Y)};let l=(Z,Y)=>new Promise((X,K)=>{let C=A.findIndex((B)=>Z.includes(B.t));if(C>=0){X(A.splice(C,1)[0]);return}let E=setTimeout(()=>{w=null,K(new F("vm_hands_no_register",`no ${Z.join("/")} in ${Y} ms`))},Y);w=(B)=>{if(!Z.includes(B.t))return!1;return clearTimeout(E),w=null,X(B),!0}}),u=(Z)=>N.send(JSON.stringify(Z)),k=(Z,Y)=>new Promise((X,K)=>{if(N.readyState!==WebSocket.OPEN){K(new V("session closed"));return}let C=zQ(),E=typeof Y.wait_ms==="number"?Y.wait_ms:0,B=setTimeout(()=>{if(!D.delete(C))return;K(new V(`no answer to ${Z.split("/").pop()} in ${E+vJ} ms`)),N.close(4000,"request_timeout")},E+vJ);D.set(C,{reject:(G)=>{clearTimeout(B),K(G)},resolve:({status:G,body:W})=>{clearTimeout(B);let P=null;try{P=W?JSON.parse(W):null}catch{}X({status:G,json:P})}}),u({t:"req",id:C,path:`${YQ}${Z}`,body:JSON.stringify(Y)})}),CJ=()=>N.close(1001,"stopping");J.signal.addEventListener("abort",CJ,{once:!0});let ZJ,o=new Map,d=new Map,$J=!1,zJ=new Set,XJ=new Set,YJ=Promise.resolve(),NJ=()=>{r().catch(()=>{return})},i=!1;try{await new Promise((G,W)=>{let P=setTimeout(()=>W(Error("session open timeout")),OQ);N.onopen=()=>{clearTimeout(P),z("vm_hands.ws_open",{}),G()},N.onerror=()=>{clearTimeout(P),W(Error("session socket error"))}});let Z=await l(["challenge"],5000);z("vm_hands.challenge",{});let Y=[],X=null,K;if($){u(await J.agent.helloFrame(Z.challenge,Q.connection));let G=await l(["ready"],1e4);if(typeof G.vm_hands_connection==="string")Q.connection=G.vm_hands_connection;if(K={device_id:$,...G.cadence?{cadence:G.cadence}:{}},typeof G.vm_hands_probe_script==="string"){if(X=G.vm_hands_probe_script,i=!0,J.agent.phase==="registered"&&!Q.turns.size)Q.attest="pending"}Q.served=!0,z("vm_hands.reconnected",{device_id:$});let W=Array.isArray(G.vm_hands_binds)?G.vm_hands_binds:G.vm_hands_bind?[G.vm_hands_bind]:[];for(let[P,M]of[...Q.turns]){if(W.some((x)=>x&&x.operation_id===M.claim.operation_id&&x.attempt_id===M.claim.attempt_id)){Y.push(M),z("vm_hands.bound_resumed",{operation_id:M.claim.operation_id});continue}Q.turns.delete(P),J.onTurn?.(P,null),QJ(M);let q=await p(Q,J.agent,P).catch((x)=>s(x,M,"vm_hands_bind_lost"));if(q)Q.receipts.push({turn:M,failure:"vm_hands_bind_lost",unbound:q});z("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{u(await J.agent.registerFrame(Z.challenge)),z("vm_hands.register_sent",{});let G=await Promise.race([l(["registered","register_refused"],1e4),v.then(()=>{throw new F(T==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(G.t==="register_refused")throw new F(G.code,"register refused");J.agent.registered();let W=G;if(K=W,Q.deviceId=W.device_id,typeof W.vm_hands_connection==="string")Q.connection=W.vm_hands_connection;if(typeof W.vm_hands_probe_script==="string"){if(X=W.vm_hands_probe_script,i=!0,J.agent.phase==="registered"&&!Q.turns.size)Q.attest="pending"}Q.served=!0,z("vm_hands.registered",{device_id:K.device_id})}let C=async()=>{let G=await k("/heartbeat",await J.heartbeat());if(G.status>=300)throw Error(`heartbeat ${G.status}`)};await C();let E=K.cadence?.presence_interval_ms??30000;if(ZJ=setInterval(()=>{C().catch(()=>N.close())},E),X&&Q.attest!=="accepted"&&J.agent.phase==="registered"&&!Q.turns.size)pJ(X,Z.challenge);let B=(G,W)=>{d.set(G,W().catch(async(P)=>{if(await UJ(P,G),P instanceof V)N.close();else await r().catch(()=>{return})}).finally(()=>{d.delete(G)}))};Q.flushReceipts=NJ;try{await r();for(let G of Y)G.flush=()=>EJ(G),G.flush(),B(G.claim.attempt_id,()=>BJ(G));while(!J.signal.aborted&&N.readyState===WebSocket.OPEN){let G=await k("/operations/claim",{wait_ms:Math.min(K.cadence?.claim_wait_ms??wJ,wJ)});if(G.status===204||!G.json)continue;if(G.status>=300)throw Error(`claim ${G.status}`);let W=G.json;if(W.capability==="hands.connect"){if(d.has(W.attempt_id)){h({claim:W,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}B(W.attempt_id,()=>lJ(W))}else oJ(W).catch(()=>{return})}}catch(G){await UJ(G,null)}}finally{if(ZJ)clearInterval(ZJ);J.signal.removeEventListener("abort",CJ);for(let Z of Q.turns.values())Z.flush=null;if(Q.flushReceipts===NJ)Q.flushReceipts=null;N.close(),await v,await Promise.all([...d.values()]);for(let Z of J.agent.liveBindIds){if(Q.turns.has(Z))continue;let Y=o.get(Z),X=Y?{...Y,eventSeq:Y.eventSeq+1}:null,K=await p(Q,J.agent,Z).catch((C)=>X?s(C,X,"vm_hands_bind_lost"):null);if(K&&X)Q.receipts.push({turn:X,failure:"vm_hands_bind_lost",unbound:K});z("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let Z of zJ)Z.abort()}return{closeCode:O,closeReason:T};async function UJ(Z,Y){if(Z instanceof V){if(!$J&&Q.turns.size)Q.lostAt=Date.now();$J=!0}else{let X=Y!==null?[Y]:[...new Set([...Q.turns.keys(),...J.agent.liveBindIds])];if(Y===null)$J=!0;for(let K of X){let C=Q.turns.get(K);if(Q.turns.delete(K),C)QJ(C),J.onTurn?.(K,null);if(J.agent.liveBindIds.includes(K)){let E=o.get(K)??C,B=E?{...E,eventSeq:E.eventSeq+1}:null,G=await p(Q,J.agent,K).catch((W)=>B?s(W,B,"vm_hands_bind_lost"):null);if(G&&B)Q.receipts.push({turn:B,failure:"vm_hands_bind_lost",unbound:G})}}}z("vm_hands.session_lost",{error:Z instanceof Error?Z.message:String(Z),bound_kept:Q.turns.size})}function h(Z){let Y=Z.claim,X={attempt_id:Y.attempt_id,attempt_token:Y.attempt_token},K=encodeURIComponent(Y.operation_id);return{fence:X,op:K,complete:(E,B={})=>k(`/operations/${K}/complete`,{...X,status:E,...B}),emit:(E,B)=>{let G=(Z.chain??Promise.resolve()).catch(()=>{return}).then(()=>C(E,B));return Z.chain=G,G}};async function C(E,B){let G=Z.eventSeq,W=(x)=>k(`/operations/${K}/events`,{...X,event_seq_start:x,events:[{kind:E,payload:{sequence:x,capability:String(Y.capability??"hands.connect"),data:B}}]}),P=G,M=await W(P),q=M.status===409?M.json?.expected_event_seq:void 0;if(typeof q==="number"&&q===G+1)M={status:200,json:{duplicate:!0}};else if(typeof q==="number"&&q>=0&&q!==G)P=q,M=await W(P);if(M.status<300)Z.eventSeq=P+1;return M}}function cJ(Z){return(Y,X)=>new Promise((K,C)=>{if(Q.turns.get(Z.claim.attempt_id)!==Z){C(Error("vm_hands_attempt_ended"));return}if(Z.outbox??=[],Z.outbox.length>=LQ){C(Error("vm_hands_outbox_full"));return}Z.outbox.push({kind:Y,data:X,resolve:K,reject:C}),Z.flush?.()})}function EJ(Z){if(XJ.has(Z))return;XJ.add(Z),(async()=>{try{while(Z.outbox?.length&&Q.turns.get(Z.claim.attempt_id)===Z&&N.readyState===WebSocket.OPEN){let Y=Z.outbox[0],X;try{X=await h(Z).emit(Y.kind,Y.data)}catch(K){if(K instanceof V)return;X={status:500}}if(Z.outbox.shift(),X.status<300)Y.resolve();else Y.reject(Error(`${Y.kind} refused ${X.status}`))}}finally{XJ.delete(Z)}})()}async function pJ(Z,Y){try{let X=await J.agent.attestFrame(Z,Y);if(N.readyState!==WebSocket.OPEN)return;u(X);let K=await l(["attested","attest_refused"],15000);Q.attest=K.t==="attested"?"accepted":"refused";for(let C of Q.attestWaiters.splice(0))C(Q.attest==="accepted");if(z("vm_hands.attest",{result:Q.attest,exit_code:X.exit_code,...K.t==="attest_refused"?{code:String(K.code??"")}:{}}),Q.attest==="refused")N.close(4401,"attest_refused")}catch(X){z("vm_hands.attest_failed",{code:X instanceof F?X.code:"probe_error"});for(let K of Q.attestWaiters.splice(0))K(!1);if(Q.attest!=="accepted")N.close(4000,"attest_unanswered")}}async function lJ(Z){let Y=i&&Q.attest==="pending",X=Z.vm_hands_attest,K=X;if(Q.attest==="refused"){z("vm_hands.claim_attest_refused",{said:typeof X==="string"?X.slice(0,16):typeof X,local:Q.attest}),await h({claim:Z,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(K==="accepted"){if(!Y&&Q.attest!=="accepted"){Q.attest="accepted";for(let _ of Q.attestWaiters.splice(0))_(!0)}}else if(K!=="pending"||!Y&&Q.attest!=="accepted"){z("vm_hands.claim_attest_refused",{said:typeof X==="string"?X.slice(0,16):typeof X,local:Q.attest}),await h({claim:Z,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Q.attest!=="accepted"){let _=Date.parse(Z.lease_until)-Date.now()-5000,H=Math.max(0,Math.min(JJ,Number.isFinite(_)?_:JJ));if(!await new Promise((n)=>{let sJ=setTimeout(()=>n(!1),H);Q.attestWaiters.push((rJ)=>{clearTimeout(sJ),n(rJ)})})){await h({claim:Z,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let C={claim:Z,eventSeq:0},{complete:E,emit:B}=h(C),G;try{if(Z.capability!=="hands.connect")throw new F("vm_hands_bind_invalid","not hands.connect");G=!FJ(Z)}catch(_){z("vm_hands.bind_refused",{code:_ instanceof F?_.code:"unexpected"}),await E("failed",{error_code:_ instanceof F?_.code:"vm_hands_bind_invalid"});return}let W,P=null,M=!1;Q.bindsStarting++;try{let _=await _Q(Q);if(_)z("vm_hands.person_terminals_closed",{count:_});let H=SJ(Z),a=J.agent.bind(H);if(H.workspace_deferred)M=!0,P=uJ(C,()=>M);W=await a}catch(_){z("vm_hands.bind_refused",{code:_ instanceof F?_.code:"unexpected"}),await E("failed",{error_code:_ instanceof F?_.code:"vm_hands_bind_failed"});return}finally{M=!1,Q.bindsStarting--}let q=P?await P:-1,x={...W.ready_data??J.readyData({launchId:W.launch_id,claim:Z})};if(G)delete x.environment_installed;let GJ=!G&&W.snapshot_revision!==null&&W.snapshot_id!==null?{environment_installed:{snapshot_id:W.snapshot_id,installed_revision:W.snapshot_revision}}:{};o.set(Z.attempt_id,{claim:Z,launchId:W.launch_id,readyData:x,eventSeq:C.eventSeq,ackSeq:-1});let g={...x,...GJ,vm_hands:{layout:W.layout,policy_digest:W.policy_digest,launch_id:W.launch_id}},f=Date.now()+EQ,R=1,j=await B("hands.ready",g);while(BQ(j.status)&&!J.signal.aborted){let _=fJ(R);if(Date.now()+_>=f)break;await new Promise((H)=>setTimeout(H,_)),R++,j=await B("hands.ready",g)}if(R>1)z("vm_hands.ready_retried",{attempts:R,status_class:`${Math.floor(j.status/100)}xx`});if(o.delete(Z.attempt_id),j.status>=300){await bJ(Q,Z.attempt_id),await J.agent.boundRefused(Z.attempt_id),await E("failed",{error_code:HJ(j.json?.error,"vm_hands_probe_failed")});return}let S={claim:Z,launchId:W.launch_id,readyData:x,eventSeq:C.eventSeq,ackSeq:q};Q.turns.set(Z.attempt_id,S),S.flush=()=>EJ(S),J.onTurn?.(Z.attempt_id,cJ(S)),await BJ(S)}async function uJ(Z,Y){let{fence:X,op:K}=h(Z),C=Z.claim.attempt_id,E=-1;try{for(;;){let B=await k(`/operations/${K}/heartbeat`,{...X,control_ack_seq:E,wait_ms:hJ});if(!Y())return E;if(B.status>=300)return J.agent.abandonWorkspaceGrant(C),E;let G=(B.json?.controls??[]).slice().sort((W,P)=>W.seq-P.seq);for(let W of G){if(W.seq<=E)continue;if(E=W.seq,W.kind===RJ)return z("vm_hands.workspace_granted",{}),J.agent.grantWorkspace(C),E;return z("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(W.kind)?W.kind:"other"}),J.agent.abandonWorkspaceGrant(C),E}}}catch{return J.agent.abandonWorkspaceGrant(C),E}}async function BJ(Z){let{fence:Y,op:X}=h(Z),K=null,C=null,E=J.agent.executorExited(Z.claim.attempt_id).then((B)=>{return C=B,null});J:for(;;){let B=await Promise.race([E,k(`/operations/${X}/heartbeat`,{...Y,control_ack_seq:Z.ackSeq,wait_ms:hJ})]);if(!B){K="vm_hands_executor_exited",z("vm_hands.executor_exited",{reason:C});break}if(B.status>=300)break;let G=(B.json?.controls??[]).slice().sort((W,P)=>W.seq-P.seq);for(let W of G){if(W.seq<=Z.ackSeq)continue;if(W.kind==="operation.cancel"||W.kind==="cancel"){Z.ackSeq=W.seq;break J}if(W.kind===gJ)try{await iJ(Z,W.payload??{})}catch(P){if(P instanceof V)throw P;K=P instanceof F?P.code:"environment_unavailable";let M=P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(P.code)?P.code:null;z("vm_hands.environment_refused",{code:K,cause:M});break J}Z.ackSeq=W.seq}}await dJ(Z,K)}async function oJ(Z){let Y=Z,X={claim:Y,eventSeq:0},{complete:K,emit:C,fence:E,op:B}={...h(X)},G=Z.vm_hands_origin==="person"?"person":"model",W=String(Z.capability??"");if(!J.executeOp){await K("failed",{error_code:"vm_hands_op_unsupported"});return}if(Z.vm_hands_attest==="accepted"&&Q.attest==="pending"&&!(i&&Q.attest==="pending")){Q.attest="accepted";for(let j of Q.attestWaiters.splice(0))j(!0)}if(Q.attest!=="accepted"){let j=Date.parse(String(Z.lease_until??""))-Date.now()-5000,S=Q.attest==="refused"?0:Math.max(0,Math.min(JJ,Number.isFinite(j)?j:JJ));if(!(S>0&&await new Promise((H)=>{let a=setTimeout(()=>H(!1),S);Q.attestWaiters.push((n)=>{clearTimeout(a),H(n)})}))){await K("failed",{error_code:"vm_hands_unattested"});return}}let P=J.agent.bindIdForRun(Y.run_id);if(G==="model"&&P===null){await K("failed",{error_code:"vm_hands_not_bound"});return}let M=W==="pty.start"&&G==="person"&&!Z.authority;if(M&&(J.agent.liveBindIds.length>0||Q.bindsStarting>0)){await K("failed",{error_code:"vm_hands_bound"});return}if(kJ.has(W)&&!M&&J.agent.liveBindIds.length===0){await K("failed",{error_code:"vm_hands_not_bound"});return}if(G==="model"&&P||kJ.has(W)&&!M)J.agent.opServed();let q=new AbortController;zJ.add(q);let x,GJ=new Promise((j)=>{x=j}),g={abort:q,settled:GJ};if(M)Q.personTerminals.add(g);if(G==="model"&&P){let j=Q.modelOps.get(P)??new Set;j.add(g),Q.modelOps.set(P,j),await J.agent.environmentInstalled(P,WQ,q.signal)}let f=-1,R=setInterval(()=>{k(`/operations/${B}/heartbeat`,{...E,control_ack_seq:f,wait_ms:0}).then((j)=>{if(j.status>=300){q.abort();return}let S=j.json?.controls??[];for(let _ of S)if(f=Math.max(f,_.seq),_.kind==="operation.cancel"||_.kind==="cancel")q.abort()},()=>q.abort())},GQ);try{let j=await J.executeOp({kind:G,claim:Z,...G==="model"&&P?{bindId:P}:{},signal:q.signal,emit:async(_)=>{await C(_.kind,_.data??{})}}),S=await K(j.status,{...j.result?{result:j.result}:{},...j.error_code?{error_code:HJ(j.error_code,"vm_hands_op_failed")}:{}});z("vm_hands.op",{capability:W,kind:G,status:j.status,code:j.error_code??null,...S.status>=300?{complete_status:S.status,complete_error:String(S.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(R),zJ.delete(q),P)Q.modelOps.get(P)?.delete(g);Q.personTerminals.delete(g),x()}}async function dJ(Z,Y){let X=Z.claim.attempt_id;if(Q.turns.get(X)===Z)Q.turns.delete(X);J.onTurn?.(X,null),QJ(Z);let K=await p(Q,J.agent,X).catch((C)=>s(C,Z,Y));if(!K)return;Q.receipts.push({turn:Z,failure:Y,unbound:K}),await r()}function s(Z,Y,X){let K=mJ(Z);return z("vm_hands.unbind_unverified",{operation_id:Y.claim.operation_id,code:K,attempt:0}),h(Y).emit(IJ,{code:K}).catch(()=>{return}),AQ(Q,J.agent,{turn:Y,failure:X},J.signal,z),null}function r(){return YJ=YJ.then(LJ,LJ),YJ}async function LJ(){while(Q.receipts.length){let{turn:Z,failure:Y,unbound:X}=Q.receipts[0],{complete:K,emit:C}=h(Z);try{if(await C("hands.stopped",{...Z.readyData,reason_code:Y?"failed":"cancelled",killed_verified:X.killed_verified,shredded:X.shredded,...X.srt_fallbacks?{vm_hands_srt_fallbacks:X.srt_fallbacks}:{}}),Y)await K("failed",{error_code:Y});else await K("cancelled",{error_code:"driver_stopped"})}catch(E){if(E instanceof V)return}Q.receipts.shift()}}async function iJ(Z,Y){let{fence:X,op:K}=h(Z),C=Y.snapshot_id;if(Y.version!==1||typeof C!=="string"||Object.keys(Y).length!==2)throw new F("vm_hands_env_invalid","invalid environment delivery");let E=await k(`/operations/${K}/environment`,{...X,snapshot_id:C}),B=E.json?.environment_sealed;if(E.status!==200||!B||E.json?.payload!==void 0)throw new F("vm_hands_env_invalid","environment not delivered sealed");let G=await J.agent.deliverEnvironment({attemptId:Z.claim.attempt_id,snapshotId:C,deviceId:Q.deviceId??"",sealed:B});if((await k(`/operations/${K}/environment-ack`,{...X,...G})).status>=300)throw new F("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{SQ as xa,ZQ as ya,vQ as za};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  class o extends Error{code;constructor(a,r){super(r);this.code=a;this.name="LocalCapabilityError"}}
3
- export{o as Kk};
3
+ export{o as Mk};