@reason-machines/cli-linux-arm64-musl 0.2.278 → 0.2.281

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 (23) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/{connect-cli-qphdm1f1.js → connect-cli-sfr2y6mq.js} +1 -1
  3. package/bin/vm-hands/{local-automation-tvf2dbfq.js → local-automation-99wn9bh2.js} +1 -1
  4. package/bin/vm-hands/{local-capabilities-p579j21r.js → local-capabilities-7thv11wy.js} +1 -1
  5. package/bin/vm-hands/{local-display-session-jwdq3jb4.js → local-display-session-mrf9pm28.js} +1 -1
  6. package/bin/vm-hands/{permissions-2s0qyrg0.js → permissions-p9p6z62j.js} +1 -1
  7. package/bin/vm-hands/status-ycqjx7at.js +96 -0
  8. package/bin/vm-hands/{version-1qgvgegp.js → version-xjrgafqj.js} +1 -1
  9. package/bin/vm-hands/{vm-hands-entry-lite-jwqqfjba.js → vm-hands-entry-lite-bm9x8vng.js} +1 -1
  10. package/bin/vm-hands/{vm-hands-entry-lite-8wyfep1z.js → vm-hands-entry-lite-c0whrdtr.js} +83 -83
  11. package/bin/vm-hands/{vm-hands-entry-lite-2xas56hm.js → vm-hands-entry-lite-d2xzrjx2.js} +2 -2
  12. package/bin/vm-hands/{vm-hands-entry-lite-1bvbhwbb.js → vm-hands-entry-lite-n0v0srqp.js} +1 -1
  13. package/bin/vm-hands/vm-hands-entry-lite-rs7g2egs.js +181 -0
  14. package/bin/vm-hands/{vm-hands-entry-lite-51hcyapr.js → vm-hands-entry-lite-rwdevjb0.js} +1 -1
  15. package/bin/vm-hands/{vm-hands-entry-lite-htn1genx.js → vm-hands-entry-lite-t678ape1.js} +1 -1
  16. package/bin/vm-hands/{vm-hands-entry-lite-y4sjgfqz.js → vm-hands-entry-lite-zjnq10yb.js} +1 -1
  17. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  18. package/bin/vm-hands/{vm-hands-executor-v2qjnrb5.js → vm-hands-executor-samg5ahn.js} +1 -1
  19. package/bin/vm-hands/{vm-hands-op-runner-ej1c20a6.js → vm-hands-op-runner-v941qg9f.js} +1 -1
  20. package/bin/vm-hands/{vm-hands-runtime-yyy4ad4z.js → vm-hands-runtime-emtd6z5q.js} +2 -2
  21. package/package.json +1 -1
  22. package/bin/vm-hands/status-2d21kwsn.js +0 -96
  23. package/bin/vm-hands/vm-hands-entry-lite-5pxbx31d.js +0 -179
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Mg as wz,Ng as Nz}from"./vm-hands-entry-lite-s2xydt0n.js";import{Xg as N}from"./vm-hands-entry-lite-9pmag2qk.js";import{uh as A}from"./vm-hands-entry-lite-y4sjgfqz.js";import{Kh as Fz}from"./vm-hands-entry-lite-7gh1rbn7.js";import{spawnSync as iz}from"child_process";import{dirname as g}from"path";import{spawn as cz}from"child_process";import{accessSync as lz,constants as sz}from"fs";import{basename as nz,join as pz}from"path";import{randomUUID as p}from"crypto";import{spawnSync as M}from"child_process";import{chmodSync as Hz,cpSync as Rz,existsSync as U,lstatSync as O,mkdirSync as i,readdirSync as Cz,readFileSync as E,readlinkSync as Lz,realpathSync as T,renameSync as R,rmdirSync as Mz,rmSync as P,symlinkSync as c,writeFileSync as Oz}from"fs";import{dirname as C,join as D,relative as Uz,resolve as Tz}from"path";var a="so.ara.cli",_z="5LJFSBRY2F";var o="ReasonBackgroundIdentity",r="Contents/Helpers/ReasonPermissionTile";var x="AraBackgroundIdentity",Az="Reason",Iz=`anchor apple generic and identifier "${a}" and certificate leaf[subject.OU] = "${_z}"`;class L extends Error{code;constructor(z,J){super(J);this.code=z;this.name="MacOSBackgroundIdentityError"}}var k="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function v(z=N()){return D(z,"Library","Application Support","Reason","Background","Reason.app")}function _(z=N()){return D(z,"Library","Application Support","Ara","Background","Ara.app")}function kz(z){try{return O(z).isFile()}catch{return!1}}function y(z){return[o,x].map((J)=>D(z,"Contents","MacOS",J)).find(kz)??null}function w(z){try{if(!O(z).isDirectory())return!1;let J=E(D(z,"Contents","Info.plist"),"utf8");return J.includes(`<string>${a}</string>`)&&(J.includes(`<string>${Az}</string>`)||J.includes("<string>Ara</string>"))&&y(z)!==null}catch{return!1}}function I(z=N()){let J=v(z);if(!w(J))return null;try{let Z=E(D(J,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(Z)?.[1]??null}catch{return null}}function Sz(z,J=N()){let Z=I(J);return Z===null||$z(S(Z.split(".")),S(z.split(/[.-]/).slice(0,3)))}var fz=1e4;function t(z,J){return M(z,[...J],{stdio:"ignore",timeout:fz}).status??1}var e=new Set;function zz(z){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let J=(Z)=>{try{return T(Z)}catch{return Tz(Z)}};if(z!==void 0&&J(z)!==J(N()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var Jz=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.ara(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,Zz=new Set(["ara","ara.exe","reason","reason.exe"]);function S(z){return z.map((J)=>Number(J))}function $z(z,J){for(let Z=0;Z<3;Z+=1)if(z[Z]!==J[Z])return z[Z]<J[Z];return!1}var Ez=[0,2,161];function xz(z){if(z===null)return!0;let J=Ez,Z=null;try{Z=T(process.execPath)}catch{}return z.some(($)=>{let j=Jz.exec($);if(j){let Q=j[1]===void 0?j.slice(4,7):j.slice(1,4);return $z(S(Q),J)}let q=$.slice($.lastIndexOf("/")+1);return Zz.has(q)&&$!==Z&&$!==process.execPath})}function yz(){let z=M("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(z.status!==0)return null;let J=[];for(let Z of z.stdout.split(`
2
+ import{Mg as wz,Ng as Nz}from"./vm-hands-entry-lite-s2xydt0n.js";import{Xg as N}from"./vm-hands-entry-lite-9pmag2qk.js";import{uh as A}from"./vm-hands-entry-lite-zjnq10yb.js";import{Kh as Fz}from"./vm-hands-entry-lite-7gh1rbn7.js";import{spawnSync as iz}from"child_process";import{dirname as g}from"path";import{spawn as cz}from"child_process";import{accessSync as lz,constants as sz}from"fs";import{basename as nz,join as pz}from"path";import{randomUUID as p}from"crypto";import{spawnSync as M}from"child_process";import{chmodSync as Hz,cpSync as Rz,existsSync as U,lstatSync as O,mkdirSync as i,readdirSync as Cz,readFileSync as E,readlinkSync as Lz,realpathSync as T,renameSync as R,rmdirSync as Mz,rmSync as P,symlinkSync as c,writeFileSync as Oz}from"fs";import{dirname as C,join as D,relative as Uz,resolve as Tz}from"path";var a="so.ara.cli",_z="5LJFSBRY2F";var o="ReasonBackgroundIdentity",r="Contents/Helpers/ReasonPermissionTile";var x="AraBackgroundIdentity",Az="Reason",Iz=`anchor apple generic and identifier "${a}" and certificate leaf[subject.OU] = "${_z}"`;class L extends Error{code;constructor(z,J){super(J);this.code=z;this.name="MacOSBackgroundIdentityError"}}var k="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function v(z=N()){return D(z,"Library","Application Support","Reason","Background","Reason.app")}function _(z=N()){return D(z,"Library","Application Support","Ara","Background","Ara.app")}function kz(z){try{return O(z).isFile()}catch{return!1}}function y(z){return[o,x].map((J)=>D(z,"Contents","MacOS",J)).find(kz)??null}function w(z){try{if(!O(z).isDirectory())return!1;let J=E(D(z,"Contents","Info.plist"),"utf8");return J.includes(`<string>${a}</string>`)&&(J.includes(`<string>${Az}</string>`)||J.includes("<string>Ara</string>"))&&y(z)!==null}catch{return!1}}function I(z=N()){let J=v(z);if(!w(J))return null;try{let Z=E(D(J,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(Z)?.[1]??null}catch{return null}}function Sz(z,J=N()){let Z=I(J);return Z===null||$z(S(Z.split(".")),S(z.split(/[.-]/).slice(0,3)))}var fz=1e4;function t(z,J){return M(z,[...J],{stdio:"ignore",timeout:fz}).status??1}var e=new Set;function zz(z){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let J=(Z)=>{try{return T(Z)}catch{return Tz(Z)}};if(z!==void 0&&J(z)!==J(N()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var Jz=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.ara(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,Zz=new Set(["ara","ara.exe","reason","reason.exe"]);function S(z){return z.map((J)=>Number(J))}function $z(z,J){for(let Z=0;Z<3;Z+=1)if(z[Z]!==J[Z])return z[Z]<J[Z];return!1}var Ez=[0,2,161];function xz(z){if(z===null)return!0;let J=Ez,Z=null;try{Z=T(process.execPath)}catch{}return z.some(($)=>{let j=Jz.exec($);if(j){let Q=j[1]===void 0?j.slice(4,7):j.slice(1,4);return $z(S(Q),J)}let q=$.slice($.lastIndexOf("/")+1);return Zz.has(q)&&$!==Z&&$!==process.execPath})}function yz(){let z=M("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(z.status!==0)return null;let J=[];for(let Z of z.stdout.split(`
3
3
  `)){let $=/^\s*(\d+)\s+(\S.*)$/.exec(Z);if(!$||Number($[1])===process.pid)continue;let j=$[2].trimEnd(),q=j.slice(j.lastIndexOf("/")+1);if(!Jz.test(j)&&Zz.has(q)){let V=M("/usr/sbin/lsof",["-a","-p",$[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
4
4
  `).find((X)=>X.startsWith("n/"));if(V)j=V.slice(1)}J.push(j)}return J}function bz(z){if(zz(z.home),!w(z.sourceApp))throw new L("identity_invalid","The packaged Reason background identity is missing or invalid.");let J=z.command??t,Z=v(z.home),$=C(Z);i($,{recursive:!0,mode:448}),Hz($,448);let j=T(z.sourceApp),q=null;try{q=T(Z)}catch{}if(j!==q){let Q=`${process.pid}.${p()}`,V=D($,`.Reason.app.${Q}.tmp`),X=D($,`.Reason.app.${Q}.old`),W=!1;try{if(Rz(j,V,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!w(V))throw new L("identity_invalid","The copied Reason background identity is invalid.");let Y=z.releaseSigned?["--test-requirement",`=${Iz}`]:[];if(J("/usr/bin/codesign",["--verify","--strict",...Y,V])!==0)throw new L("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let B=!1;for(let F=0;F<4;F+=1){let G=!1;try{R(Z,X),G=!0,W=!0}catch(K){if(K.code!=="ENOENT")throw K}if(F===0)z.beforePublish?.();try{R(V,Z),B=!0}catch(K){let m=K.code;if(!["EEXIST","ENOTEMPTY"].includes(m??""))throw K;if(G)P(X,{recursive:!0,force:!0}),W=!1;if(F===3)throw K;continue}if(G)P(X,{recursive:!0,force:!0}),W=!1;break}if(!B)throw Error("Could not publish Reason's background identity.")}catch(Y){if(W&&!U(Z)&&U(X))R(X,Z);throw Y}finally{P(V,{recursive:!0,force:!0}),P(X,{recursive:!0,force:!0})}}return Wz(Z,z,{verified:j!==q}),Z}function jz(z){return D(C(z),".Reason.app.registered")}function qz(z){try{let J=O(z);return J.isDirectory()?`${J.ino}:${J.birthtimeMs}`:null}catch{return null}}function f(z){let J=qz(z);try{return J!==null&&E(jz(z),"utf8")===J}catch{return!1}}function Qz(z){if(w(z))return"bundle";try{if(O(D(z,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return O(D(z,"Contents","MacOS",x)).isSymbolicLink()?"retired":null}catch{return null}}function Wz(z,J,Z={}){let $=J.command??t;if(!Z.verified&&$("/usr/bin/codesign",["--verify","--strict",z])!==0)throw new L("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if($(k,["-f",z])!==0)throw new L("identity_register_failed","Could not register Reason's macOS background identity.");let j=qz(z);try{if(j)Oz(jz(z),j,{mode:384})}catch{}try{gz(z,J.home,$,J.runningExecutables??yz)}catch(q){let Q=q.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${Q})
5
5
  `)}}function gz(z,J,Z,$){let j=y(z);if(!j)return;let q=_(J),Q=C(q),V=(K)=>D(K,"Contents","MacOS",x),X=Uz(C(V(q)),j),W=`${process.pid}.${p()}`,Y=Qz(q);if(Y===null)return;let B=Y==="bundle";if(B)Z(k,["-u",q]);let F=D(Q,`.Ara.app.${W}.old`);if(!e.has(q)&&!xz($())){if(!B)Z(k,["-u",q]);try{R(q,F)}catch(K){if(K.code==="ENOENT")return;throw K}P(F,{recursive:!0,force:!0}),uz(Q);return}if(!B){if(Lz(V(q))===X)return;let K=`${V(q)}.${W}`;c(X,K);try{R(K,V(q))}finally{P(K,{force:!0})}return}let G=D(Q,`.Ara.app.${W}.shim`);i(C(V(G)),{recursive:!0}),c(X,V(G));try{try{R(q,F)}catch(K){if(K.code==="ENOENT")return;throw K}try{R(G,q)}catch(K){if(U(q))return;throw R(F,q),K}}finally{P(G,{recursive:!0,force:!0}),P(F,{recursive:!0,force:!0})}}function uz(z){try{if(Cz(z).some((Z)=>Z!==".DS_Store"))return;P(D(z,".DS_Store"),{force:!0}),Mz(z)}catch{}}var l=new Map;function hz(z=N()){let J=l.get(z);if(J)return J;if(process.platform!=="darwin")return[];let Z=s(z);if(Z===null&&U(C(v(z))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),Z=s(z);if(Z===null)return[];return l.set(z,Z),Z}function s(z){let J=v(z),Z=_(z);if(!w(J)||!f(J))try{dz({home:z,skipWhenSettled:!0})}catch{}let $=w(J)&&(f(J)||!w(Z))?J:w(Z)?Z:null,j=$?y($):null;if(!j)return null;if($===Z)e.add(Z);let q=M(j,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return q.status===0&&q.stdout===`spawn
@@ -20,7 +20,7 @@ The macOS privacy permissions of this computer's Reason worker:
20
20
  allow asks for each missing one, or the one named. macOS cannot ask for Full
21
21
  Disk Access: allow disk opens its pane, shows the file to add in Finder and
22
22
  waits until the worker has it.
23
- `,u="x-apple.systempreferences:com.apple.preference.security",az="curl -fsSL https://reasonmachines.com/install.sh | bash",oz=180000,rz=2000,h=["screen","accessibility","disk"],d={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${u}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${u}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${u}?Privacy_AllFiles`}};function Bz(z){return z.executable}function tz(z,J){if(z==="computer_use_identity_missing")return`Reason's background identity is not installed (${z}); reinstall Reason: ${az}`;if(z==="computer_use_identity_outdated")return`Reason's background identity is outdated (${I(J)??"unknown"}; this CLI is ${A}) (${z}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${z}); run the installed \`reason\``}function ez(z=N()){let J=b(z);if(J.length>0)return{state:"ready",path:g(g(g(J[0]))),prefix:J};let Z=Kz(J,z)??"computer_use_identity_unavailable";return{state:Z,path:v(z),detail:tz(Z,z)}}function Pz(){return{identity:()=>ez(),grants:(z)=>wz(z),request:(z,J)=>Nz(z,J),worker:async()=>(await import("./status-2d21kwsn.js")).connectionMacState(),open:(z)=>{iz("/usr/bin/open",z,{stdio:"ignore",timeout:1e4})},tile:Xz,restartConnection:async()=>(await import("./connect-cli-qphdm1f1.js")).restartConnection(),sleep:(z)=>new Promise((J)=>setTimeout(J,z)),now:()=>Date.now()}}function Yz(z,J,Z){if(z.state!=="ready"||!J)return"unknown";return J[Z]?"granted":"missing"}async function vz(z){let J=z.identity(),Z=J.state==="ready"?await z.grants(J.prefix):null,$=await z.worker(),j=$?Bz($):null,q=!j||$?.full_disk_access==="unknown"?"unknown":$?.full_disk_access==="granted"?"granted":"missing",Q=(V,X,W)=>{let{label:Y,purpose:B,level:F}=d[V];return{id:V,label:Y,purpose:B,level:F,state:X,holder:W}};return{identity:{state:J.state,path:J.path,detail:J.state==="ready"?null:J.detail},worker_detail:j?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[Q("screen",Yz(J,Z,"screen"),J.path),Q("accessibility",Yz(J,Z,"accessibility"),J.path),Q("disk",q,j)]}}function MJ(z){let J=z.identity.state==="ready"?null:z.identity.state,Z=z.permissions.filter((q)=>q.state==="granted").length,$=[...J?[J]:[],...z.permissions.filter((q)=>q.state!=="granted"&&!(J&&q.id!=="disk")).map((q)=>`${q.label} ${q.state}`)],j=!J&&z.permissions.some((q)=>q.state==="missing");return`Permissions: ${Z} of ${z.permissions.length}${$.length>0?` (${$.join(", ")})`:""}`+(j?" \u2014 reason permissions allow":$.length>0?" \u2014 reason permissions":"")}function zJ(z){let J=[];if(z.identity.detail)J.push(z.identity.detail);J.push(`Reason: ${z.identity.path}`);let Z=z.permissions.find(($)=>$.id==="disk");J.push(Z?.holder?`Worker: ${Z.holder}`:`Worker: ${z.worker_detail}`),J.push("");for(let $ of z.permissions){let j=`${$.label}${$.level==="recommended"?" (recommended)":""}`;J.push(` ${$.id.padEnd(13)} ${$.state.padEnd(7)} ${j}: ${$.purpose}`)}if(z.permissions.some(($)=>$.state==="missing"))J.push("","Allow the missing ones: reason permissions allow");return`${J.join(`
23
+ `,u="x-apple.systempreferences:com.apple.preference.security",az="curl -fsSL https://reasonmachines.com/install.sh | bash",oz=180000,rz=2000,h=["screen","accessibility","disk"],d={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${u}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${u}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${u}?Privacy_AllFiles`}};function Bz(z){return z.executable}function tz(z,J){if(z==="computer_use_identity_missing")return`Reason's background identity is not installed (${z}); reinstall Reason: ${az}`;if(z==="computer_use_identity_outdated")return`Reason's background identity is outdated (${I(J)??"unknown"}; this CLI is ${A}) (${z}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${z}); run the installed \`reason\``}function ez(z=N()){let J=b(z);if(J.length>0)return{state:"ready",path:g(g(g(J[0]))),prefix:J};let Z=Kz(J,z)??"computer_use_identity_unavailable";return{state:Z,path:v(z),detail:tz(Z,z)}}function Pz(){return{identity:()=>ez(),grants:(z)=>wz(z),request:(z,J)=>Nz(z,J),worker:async()=>(await import("./status-ycqjx7at.js")).connectionMacState(),open:(z)=>{iz("/usr/bin/open",z,{stdio:"ignore",timeout:1e4})},tile:Xz,restartConnection:async()=>(await import("./connect-cli-sfr2y6mq.js")).restartConnection(),sleep:(z)=>new Promise((J)=>setTimeout(J,z)),now:()=>Date.now()}}function Yz(z,J,Z){if(z.state!=="ready"||!J)return"unknown";return J[Z]?"granted":"missing"}async function vz(z){let J=z.identity(),Z=J.state==="ready"?await z.grants(J.prefix):null,$=await z.worker(),j=$?Bz($):null,q=!j||$?.full_disk_access==="unknown"?"unknown":$?.full_disk_access==="granted"?"granted":"missing",Q=(V,X,W)=>{let{label:Y,purpose:B,level:F}=d[V];return{id:V,label:Y,purpose:B,level:F,state:X,holder:W}};return{identity:{state:J.state,path:J.path,detail:J.state==="ready"?null:J.detail},worker_detail:j?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[Q("screen",Yz(J,Z,"screen"),J.path),Q("accessibility",Yz(J,Z,"accessibility"),J.path),Q("disk",q,j)]}}function MJ(z){let J=z.identity.state==="ready"?null:z.identity.state,Z=z.permissions.filter((q)=>q.state==="granted").length,$=[...J?[J]:[],...z.permissions.filter((q)=>q.state!=="granted"&&!(J&&q.id!=="disk")).map((q)=>`${q.label} ${q.state}`)],j=!J&&z.permissions.some((q)=>q.state==="missing");return`Permissions: ${Z} of ${z.permissions.length}${$.length>0?` (${$.join(", ")})`:""}`+(j?" \u2014 reason permissions allow":$.length>0?" \u2014 reason permissions":"")}function zJ(z){let J=[];if(z.identity.detail)J.push(z.identity.detail);J.push(`Reason: ${z.identity.path}`);let Z=z.permissions.find(($)=>$.id==="disk");J.push(Z?.holder?`Worker: ${Z.holder}`:`Worker: ${z.worker_detail}`),J.push("");for(let $ of z.permissions){let j=`${$.label}${$.level==="recommended"?" (recommended)":""}`;J.push(` ${$.id.padEnd(13)} ${$.state.padEnd(7)} ${j}: ${$.purpose}`)}if(z.permissions.some(($)=>$.state==="missing"))J.push("","Allow the missing ones: reason permissions allow");return`${J.join(`
24
24
  `)}
25
25
  `}async function Gz(z,J){let Z=J.now()+oz;for(;;){if(await z())return!0;if(J.now()>=Z)return!1;await J.sleep(rz)}}async function JJ(z,J){let Z=J.host??Pz(),{io:$}=J,j=await vz(Z),q=j.permissions.filter((W)=>z.includes(W.id)&&W.state!=="granted");if(q.length===0)return $.stdout.write(`Reason permissions: ${z.map((W)=>d[W].label).join(", ")} already allowed.
26
26
  `),0;let Q=!1,V=!1,X=Z.identity();for(let W of q){let{label:Y,pane:B}=d[W.id];if(W.id!=="disk"){if(X.state!=="ready"){if(!Q)$.stderr.write(`Reason permissions: ${X.detail}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var r={name:"github-native-engineer-device-worker-production",version:"0.2.278",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
2
+ var r={name:"github-native-engineer-device-worker-production",version:"0.2.281",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
3
3
  export{r as yh};
@@ -0,0 +1,181 @@
1
+ // @bun
2
+ import{cf as Z8}from"./vm-hands-entry-lite-bfwf82rw.js";import{lf as R0}from"./vm-hands-entry-lite-ptmqg51y.js";import{gg as Kq}from"./vm-hands-entry-lite-d2xzrjx2.js";import{Cg as p,Fg as V0,Ig as F0,Jg as C8,Kg as eq,Mg as g8,Pg as q0,Rg as x0}from"./vm-hands-entry-lite-s2xydt0n.js";import{Wg as wq}from"./vm-hands-entry-lite-s5qn1k80.js";import{Xg as o,Yg as C0}from"./vm-hands-entry-lite-9pmag2qk.js";import{jh as B0}from"./vm-hands-entry-lite-84aq8d12.js";import{zh as A0}from"./vm-hands-entry-lite-anaydk9m.js";import{Gh as Z}from"./vm-hands-entry-lite-ffg7rf02.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
+ # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
+ # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
+ # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
6
+ import ctypes, sys
7
+ import gi
8
+ gi.require_version("GdkPixbuf", "2.0")
9
+ from gi.repository import GdkPixbuf
10
+ x = ctypes.cdll.LoadLibrary("libX11.so.6")
11
+ x.XOpenDisplay.restype = ctypes.c_void_p
12
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
13
+ d = x.XOpenDisplay(None)
14
+ if not d: sys.exit("no display")
15
+ for name, res, args in [
16
+ ("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
17
+ ("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
18
+ ("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
19
+ ("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
20
+ ("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
21
+ ("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
22
+ ("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
23
+ ("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
24
+ ("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
25
+ ("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
26
+ ("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
27
+ ("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
28
+ ("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
29
+ ("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
30
+ ("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
31
+ ("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
32
+ ]:
33
+ f = getattr(x, name); f.restype = res; f.argtypes = args
34
+ s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
35
+ w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
36
+ if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
37
+ # Scale to cover the screen, then crop the centre.
38
+ src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
39
+ k = max(w / src.get_width(), h / src.get_height())
40
+ sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
41
+ pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
42
+ if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
43
+ rgb, stride = pb.get_pixels(), pb.get_rowstride()
44
+ bgrx = bytearray(w * h * 4)
45
+ for y in range(h):
46
+ row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
47
+ bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
48
+ buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
49
+ pix = x.XCreatePixmap(d, root, w, h, 24)
50
+ img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
51
+ x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
52
+ ref = ctypes.c_ulong(pix)
53
+ for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
54
+ x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
55
+ x.XSetWindowBackgroundPixmap(d, root, pix)
56
+ x.XClearWindow(d, root)
57
+ x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
58
+ x.XCloseDisplay(d)
59
+ `;var X8=32,Zq=76;function v0(q){return`<?xml version="1.0" encoding="UTF-8"?>
60
+ <openbox_config xmlns="http://openbox.org/3.4/rc">
61
+ <theme><keepBorder>no</keepBorder></theme>
62
+ <applications>
63
+ <!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
64
+ <application class="Chromium*">
65
+ <decor>no</decor>
66
+ <position force="yes"><x>${X8}</x><y>${X8}</y></position>
67
+ <size><width>${q.width-X8*2}</width><height>${q.height-X8-Zq}</height></size>
68
+ </application>
69
+ </applications>
70
+ </openbox_config>`}var u0=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
71
+ panel_items = L
72
+ panel_size = 100% 46
73
+ panel_margin = 0 10
74
+ panel_padding = 0 0 10
75
+ panel_position = bottom center horizontal
76
+ panel_shrink = 1
77
+ panel_background_id = 0
78
+ panel_layer = top
79
+ mouse_effects = 1
80
+ mouse_hover_icon_asb = 100 0 12
81
+ mouse_pressed_icon_asb = 100 0 -12
82
+
83
+ launcher_icon_size = 46
84
+ launcher_padding = 0 0 10
85
+ launcher_background_id = 0
86
+ launcher_tooltip = 1
87
+
88
+ launcher_item_app = /tmp/ara-chromium.desktop
89
+ launcher_item_app = /tmp/ara-terminal.desktop
90
+ launcher_item_app = /tmp/ara-files.desktop
91
+ `,c0=`corner-radius = 12;
92
+ rounded-corners-exclude = [
93
+ "class_g = 'tint2'",
94
+ "window_type = 'dock'",
95
+ "window_type = 'desktop'"
96
+ ];
97
+ backend = "xrender";
98
+ shadow = false;
99
+ fading = false;
100
+ vsync = false;
101
+ inactive-opacity = 1.0;
102
+ active-opacity = 1.0;
103
+ `,m0="/tmp/ara-dock-browser.png",r0=`[Desktop Entry]
104
+ Name=Chrome
105
+ Exec=chromium --no-sandbox %U
106
+ Icon=${m0}
107
+ Type=Application
108
+ Categories=Network;WebBrowser;
109
+ `,l0=`[Desktop Entry]
110
+ Name=Terminal
111
+ Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
112
+ Icon=/tmp/ara-dock-terminal.png
113
+ Type=Application
114
+ Categories=System;TerminalEmulator;
115
+ `,d0=`[Desktop Entry]
116
+ Name=Files
117
+ Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
118
+ Icon=/tmp/ara-dock-files.png
119
+ Type=Application
120
+ Categories=System;FileManager;
121
+ `;var Gq={"wallpaper.jpg":Bq,"dock-browser.png":Rq,"dock-terminal.png":yq,"dock-files.png":Cq},s0=Sq,a0='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function Aq(q){let x=(J)=>J.replaceAll("DISPLAY=:99",`DISPLAY=${q.display}`).replaceAll("/tmp/ara-",`${q.root}/ara-`),X=new Set(q.absent??[]),Q=u0.split(`
122
+ `).filter((J)=>!(X.has("terminal")&&J.endsWith("/ara-terminal.desktop"))&&!(X.has("files")&&J.endsWith("/ara-files.desktop"))).join(`
123
+ `);return{files:{"openbox/rc.xml":v0(q.screen),"tint2/tint2rc":x(Q),"picom/picom.conf":c0,...X.has("terminal")?{}:{"ara-terminal.desktop":x(l0)},...X.has("files")?{}:{"ara-files.desktop":x(d0)},"ara-chromium.desktop":x(r0).replace("chromium --no-sandbox %U",q.browserExec),"ara-set-root-wallpaper.py":s0},start:['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; [ "$(ticks "$pid")" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }',a0,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true','if ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi']}}import{createHash as Mq}from"crypto";import{once as i0}from"events";import{createWriteStream as n0,existsSync as o0,mkdirSync as t0,mkdtempSync as GX,readFileSync as T8,readdirSync as AX,renameSync as e0,realpathSync as qx,rmSync as xx,statSync as h8,writeFileSync as Xx}from"fs";import{dirname as k8,join as G}from"path";import{finished as Qx}from"stream/promises";var O8="omljlfpmafedpplnpkkahegadhkimdje",PX="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";function NX(q){if(!q||typeof q!=="object"||Array.isArray(q)||!("version"in q)||q.version!==1||!("status"in q))return null;if(q.status==="unavailable")return Object.keys(q).length===2?{version:1,status:"unavailable"}:null;if(q.status!=="connected"||Object.keys(q).length!==5||!("deviceId"in q)||typeof q.deviceId!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(q.deviceId)||!("apiOrigin"in q)||typeof q.apiOrigin!=="string"||q.apiOrigin.length>2048||!("managedRootIds"in q)||!Array.isArray(q.managedRootIds)||q.managedRootIds.length>32)return null;let x=[];for(let X of q.managedRootIds){if(typeof X!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(X))return null;x.push(X)}try{let X=new URL(q.apiOrigin);if(X.origin!==q.apiOrigin||X.username||X.password||!(X.protocol==="https:"||X.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(X.hostname)))return null}catch{return null}return{version:1,status:"connected",deviceId:q.deviceId,apiOrigin:q.apiOrigin,managedRootIds:x}}var c={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},j8={version:"154.0.8037.57",macArm64Sha256:"0e6b3439469c1b8b95b2e89c72ea29f7af00fb2c28a8878358a0b6002b6d3a64",linux64Sha256:"ceee2972074d441ea7c4ba8bcc0eaab77e7e87680f6653d73d3065851fe10302"};var Q8={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${c.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${c.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${c.obu.version}/open-browser-use-chrome-extension-${c.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},i="pnbmoicbkopffjjgfgfglopechaiemkp";var Px=["none","standard","all"],H8="22.23.3",bx={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53"},f8={"linux-x64":{ocu:"dist/linux/amd64/open-computer-use",obu:"native/linux-amd64/open-browser-use"},"linux-arm64":{ocu:"dist/linux/arm64/open-computer-use",obu:"native/linux-arm64/open-browser-use"},"darwin-arm64":{ocu:"dist/Open Computer Use.app/Contents/MacOS/OpenComputerUse",obu:"native/darwin-arm64/open-browser-use"}},zq="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",I8={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},Jx={version:I8.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},n="com.ifuryst.open_browser_use.extension",Yq="com.reasonmachines.browser_use.extension",Vq="/tmp/reason-browser-use",p8=["tint2","picom","xterm","pcmanfm"],_q=["fonts-droid-fallback"],Eq=["pulseaudio"],Nx=["xvfb","openbox","x11vnc","x11-utils","x11-xserver-utils","xdotool","dbus-x11","at-spi2-core","python3","python3-gi","gir1.2-atspi-2.0","gir1.2-gtk-3.0","fonts-dejavu-core",..._q,"galculator","chromium","ffmpeg","tmux",...Eq,...p8],Wx=new Set([...p8,..._q,...Eq]),Fq=Nx.filter((q)=>q!=="chromium"&&!Wx.has(q)),Lx=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],U8="/usr/bin/chromium",jx=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function $q(q=process.platform,x=process.arch){let X=`${q}-${x}`;return X==="linux-x64"||X==="linux-arm64"||X==="darwin-arm64"?X:null}function D8(q){return{node:{version:H8,url:`https://nodejs.org/dist/v${H8}/node-v${H8}-${q}.tar.gz`,sha256:bx[q]},open_computer_use:{version:c.ocu.version,url:Q8.ocu.url,sha256:Q8.ocu.sha256},open_browser_use:{version:c.obu.version,url:Q8.obu.url,sha256:Q8.obu.sha256},...q==="darwin-arm64"?{chrome_for_testing:{version:j8.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${j8.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:j8.macArm64Sha256}}:{}}}function Ux(q){let x={extension:i};for(let[X,Q]of Object.entries(D8(q)))x[X]=`${Q.version}@${Q.sha256}`;return x}function Oq(q){return G(q,".local","share","reason","desktop")}function Hq(q,x=wq()){let X=Oq(x),Q=(W)=>G(X,W,D8(q)[W]?.version??""),P=Q("open_computer_use"),b=Q("open_browser_use"),J=q==="darwin-arm64",L=G(x,"Library","Application Support"),y=J?G(L,"Google","Chrome","NativeMessagingHosts",`${n}.json`):G(x,".config","google-chrome","NativeMessagingHosts",`${n}.json`);return{root:X,automation:G(k8(X),"automation"),receipt:G(X,"receipt.json"),minimal:u8(x),node:G(Q("node"),"bin","node"),ocuDir:P,ocu:G(P,f8[q].ocu),ocuApp:J?G(P,"dist","Open Computer Use.app"):null,obuDir:b,obu:G(b,"cli","open-browser-use.js"),nativeHost:G(b,f8[q].obu),extensionDir:J?G(L,"OpenBrowserUse","chrome-extension","release"):G(x,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:y,nativeHostManifests:J?[y,G(L,"Google","ChromeForTesting","NativeMessagingHosts",`${n}.json`)]:[G(x,".config","chromium","NativeMessagingHosts",`${n}.json`),G(x,".config","google-chrome-for-testing","NativeMessagingHosts",`${n}.json`)],browser:J?G(Q("chrome_for_testing"),zq):U8,userChromeHost:J?G(X,"user-chrome","reason-browser-use"):null,userChromeRegistration:J?G(L,"Google","Chrome","NativeMessagingHosts",`${Yq}.json`):null,ffmpegDir:G(X,"ffmpeg"),ffmpeg:J?G(X,"ffmpeg",I8.version,"ffmpeg"):null,ffprobe:J?G(X,"ffprobe",Jx.version,"ffprobe"):null}}function fq(q){try{let x=JSON.parse(T8(q,"utf8"));if(typeof x!=="object"||x===null)return null;let X=x,Q=X.pins;if(X.schema_version!==1||typeof X.platform!=="string"||typeof Q!=="object"||Q===null||!Object.values(Q).every((P)=>typeof P==="string")||!Px.includes(X.permissions)||!Array.isArray(X.missing_system_packages)||!X.missing_system_packages.every((P)=>typeof P==="string")||typeof X.updated_at!=="string")return null;return{schema_version:1,platform:X.platform,pins:Q,permissions:X.permissions,missing_system_packages:X.missing_system_packages,updated_at:X.updated_at}}catch{return null}}function Tx(q,x,X=384){t0(k8(q),{recursive:!0,mode:448});let Q=`${q}.pending.${process.pid}`;Xx(Q,x,{mode:X}),e0(Q,q)}function m(q){try{return h8(q).isFile()}catch{return!1}}function gq(q){try{let x=h8(q);return x.isFile()&&(x.mode&73)!==0}catch{return!1}}function Dx(q){try{return T8(q,"utf8")}catch{return null}}function l(q){for(let x of jx){let X=G(x,q);try{let Q=h8(X);if(Q.isFile()&&(Q.mode&73)!==0)return X}catch{}}return null}function Bx(q){try{let x=JSON.parse(T8(G(q,"package.json"),"utf8"));return typeof x==="object"&&x!==null&&typeof x.version==="string"?x.version:null}catch{return null}}function Rx(q,x,X){let Q=D8(X)[q];if(!Q)return!1;if(q==="node")return m(G(x,"bin","node"));if(q==="chrome_for_testing")return m(G(x,zq));let P=f8[X][q==="open_computer_use"?"ocu":"obu"];return Bx(x)===Q.version&&m(G(x,P))&&(q==="open_computer_use"||m(G(x,"cli","open-browser-use.js")))}function Cx(q){return Mq("sha256").update(Buffer.from(q,"base64")).digest("hex").slice(0,32).replace(/./g,(x)=>String.fromCharCode(97+Number.parseInt(x,16)))}function v8(q){try{let x=JSON.parse(T8(q,"utf8"));return typeof x==="object"&&x!==null&&!Array.isArray(x)?x:null}catch{return null}}function yx(q){let x=v8(G(q.extensionDir,"manifest.json"));return x!==null&&x.version===c.obu.version&&typeof x.key==="string"&&Cx(x.key)===i}function Sx(q,x){let X=q?.allowed_origins;return q!==null&&q.name===n&&Array.isArray(X)&&X.length===1&&X[0]===`chrome-extension://${i}/`&&(x===void 0||q.path===x)}function Zx(q){return yx(q)&&m(q.nativeHost)&&q.nativeHostManifests.every((x)=>Sx(v8(x),q.nativeHost))}function Gx(q){return`#!/bin/sh
124
+ # Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
125
+ obu=${`'${q.replaceAll("'","'\\''")}'`}
126
+ case "$1" in
127
+ chrome-extension://*) exec "$obu" host --socket-dir ${Vq} ;;
128
+ mcp) shift; exec "$obu" mcp --socket-dir ${Vq} "$@" ;;
129
+ esac
130
+ exec "$obu" "$@"
131
+ `}function Ax(q){let x=v8(q),X=x?.allowed_origins;return x!==null&&x.name===Yq&&x.type==="stdio"&&Array.isArray(X)&&X.includes(`chrome-extension://${O8}/`)&&typeof x.path==="string"&&gq(x.path)}function Vx(q,x){if(!q.userChromeHost||!q.userChromeRegistration)return null;if(!x||Dx(q.userChromeHost)!==Gx(q.nativeHost)||!gq(q.userChromeHost))return{code:"user_chrome_browser_use_missing"};return Ax(q.userChromeRegistration)?{host:q.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var Fx={display:["display"],computer:["display","system_packages","node","open_computer_use"],browser:["display","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function r(q={}){let x=q.platform===void 0?$q():q.platform;if(!x)return null;let X=Hq(x,q.home),Q=fq(X.receipt),P=Ux(x),b=Q!==null&&Q.platform===x&&JSON.stringify(Object.entries(Q.pins).sort())===JSON.stringify(Object.entries(P).sort()),J=[],L=D8(x);for(let N of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let S=L[N];if(!S)continue;let F=Rx(N,G(X.root,N,S.version),x),K=Q?.pins[N],$=F&&K===P[N]?"ready":K!==void 0&&K!==P[N]?"outdated":"missing";J.push({name:N,state:$,detail:S.version})}let y=Q?.pins.extension===i&&Zx(X);J.push({name:"browser_extension",state:y?"ready":"missing",detail:i});let W=l("Xvfb"),U=l("x11vnc"),C=l("openbox");if(x!=="darwin-arm64"){J.push(m(U8)?{name:"browser",state:"ready",detail:U8}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${U8}`});let N=W!==null&&U!==null&&C!==null;J.push({name:"display",state:N?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let S=Lx.filter((_)=>l(_)===null),F=(Q?.missing_system_packages??Fq).filter((_)=>Fq.includes(_)),K=S.length===0&&F.length===0;J.push(K?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...F,...S])].join(" ")});let $=p8.filter((_)=>l(_)===null);J.push($.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:$.join(" ")})}let R=X.ffmpeg&&m(X.ffmpeg)?X.ffmpeg:l("ffmpeg"),D=!R?null:R===X.ffmpeg?X.ffprobe:G(k8(qx(R)),"ffprobe"),Y=b&&J.every((N)=>N.state==="ready"),A=(N)=>b&&J.every((S)=>!Fx[N].includes(S.name)||S.state==="ready");return{platform:x,root:X.root,automation:X.automation,ready:Y,features:{display:A("display"),computer:A("computer"),browser:A("browser")},node:X.node,ocu:X.ocu,obu:X.obu,nativeHost:X.nativeHost,extensionDir:X.extensionDir,browser:X.browser,ffmpeg:R,ffprobe:D&&m(D)?D:null,userChrome:Vx(X,b&&["node","open_browser_use"].every((N)=>J.find((S)=>S.name===N)?.state==="ready")),pulseaudio:l("pulseaudio"),xvfb:W,x11vnc:U,openbox:C,components:J}}function hq(q){return wx(q)?Kq():[]}function wx(q){return q?.platform==="darwin-arm64"&&q.ffmpeg===G(q.root,"ffmpeg",I8.version,"ffmpeg")}async function HX(q,x,X,Q=fetch){try{let P=await Q(q,{redirect:"follow"});if(!P.ok||!P.body)throw Error(`download failed (HTTP ${P.status}): ${q}`);let b=Mq("sha256"),J=n0(X,{mode:384});try{let y=P.body.getReader();for(let W=await y.read();!W.done;W=await y.read())if(b.update(W.value),!J.write(W.value))await i0(J,"drain")}finally{J.end(),await Qx(J)}let L=b.digest("hex");if(L!==x)throw Error(`digest mismatch for ${q}: expected ${x}, got ${L}`)}catch(P){throw xx(X,{force:!0}),P}}function u8(q){return G(Oq(q),"minimal.json")}function Kx(q=o()){return o0(u8(q))}function fX(q={}){Tx(u8(q.home??o()),`${JSON.stringify({version:1,minimal_at:(q.now?.()??new Date).toISOString()})}
132
+ `)}function gX(q={}){let x=q.platform===void 0?$q():q.platform;if(x===null)return null;let X=q.home??o();if(fq(Hq(x,X).receipt)!==null)return"refresh";return Kx(X)?null:"install"}import{execFile as Ix,spawn as i8}from"child_process";import{existsSync as px}from"fs";import{connect as vx}from"net";function Mx(){let q=new Set,x=null,X=(P)=>({holder:x?.viewer??null,you:x===P,same_user:Boolean(x?.viewer&&P.viewer&&x.viewer.user_id===P.viewer.user_id)}),Q=()=>{for(let P of q)P.notify(X(P))};return{join(P){return q.add(P),P.notify(X(P)),()=>{if(!q.delete(P))return;if(x!==P)return;x=null,Q()}},claim(P){if(x===P||!q.has(P))return;x=P,Q()}}}var kq=Mx();import{spawn as zx}from"child_process";import{existsSync as Yx}from"fs";import{connect as _x}from"net";import{join as B8}from"path";var pq="reason_desktop",P8={sampleRate:48000,channels:2,codec:"opus"},Ex=5000,$x=107,Ox=262144,r8=(q)=>B8(q,"native"),R8=(q)=>`unix:${q}`;function c8(q,x=1000){if(!Yx(q))return Promise.resolve(!1);return new Promise((X)=>{let Q=_x({path:q}),P=(b)=>{Q.destroy(),X(b)};Q.setTimeout(x,()=>P(!1)),Q.once("error",()=>P(!1)),Q.once("close",()=>P(!1)),Q.once("connect",()=>P(!0))})}async function vq(q,x){if(!x)return null;let X=r8(q);if(Buffer.byteLength(X)>$x||/["'\\\s]/.test(X))return null;try{if(await c8(X))return X;let Q=zx(x,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${B8(q,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${X}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${pq} rate=${P8.sampleRate} channels=${P8.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:q,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:q,PULSE_RUNTIME_PATH:B8(q,"runtime"),PULSE_STATE_PATH:B8(q,"state")}}),P=!1;Q.once("error",()=>{P=!0}),Q.once("exit",()=>{P=!0}),Q.unref();let b=Date.now()+Ex;while(Date.now()<b){if(await c8(X))return X;if(P)return await c8(X)?X:null;await new Promise((J)=>setTimeout(J,50))}if(!P)Q.kill("SIGKILL");return null}catch{return null}}function uq(){let{sampleRate:q,channels:x}=P8;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(q),"-channels",String(x),"-fragment_size",String(q*x*2/50),"-i",`${pq}.monitor`,"-vn","-ac",String(x),"-ar",String(q),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var Hx=[79,103,103,83],fx=Buffer.from("OpusHead"),gx=Buffer.from("OpusTags"),Iq=(q,x)=>q.byteLength>=x.byteLength&&x.every((X,Q)=>q[Q]===X);class m8 extends Error{constructor(q){super(q);this.name="OggProtocolError"}}class l8{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(q){let x=new Uint8Array(this.buffer.byteLength+q.byteLength);x.set(this.buffer),x.set(q,this.buffer.byteLength);let X=[],Q=0;while(x.byteLength-Q>=27){if(Hx.some((R,D)=>x[Q+D]!==R)||x[Q+4]!==0)throw new m8("invalid_page");let P=(x[Q+5]&1)!==0,b=x[Q+26];if(x.byteLength-Q<27+b)break;let J=x.subarray(Q+27,Q+27+b),L=J.reduce((R,D)=>R+D,0),y=27+b+L;if(x.byteLength-Q<y)break;if(!P&&this.partialBytes>0)this.resetPartial();let W=P&&this.partialBytes===0,U=Q+27+b,C=U;for(let R of J){if(U+=R,R===255)continue;if(this.appendPartial(x.subarray(C,U),W),C=U,!W){let D=this.takePartial();if(D.byteLength>0&&!Iq(D,fx)&&!Iq(D,gx))X.push(D)}W=!1,this.resetPartial()}if(C<U)this.appendPartial(x.subarray(C,U),W);Q+=y}return this.buffer=x.slice(Q),X}appendPartial(q,x){if(x||q.byteLength===0)return;if(this.partialBytes+=q.byteLength,this.partialBytes>Ox)throw new m8("packet_too_large");this.partial.push(q.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let q=new Uint8Array(this.partialBytes),x=0;for(let X of this.partial)q.set(X,x),x+=X.byteLength;return q}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as hx}from"child_process";var cq=1048576,kx=String.raw`
133
+ import gi, json, os, sys
134
+ gi.require_version("Gtk", "3.0")
135
+ from gi.repository import Gtk, Gdk, GLib
136
+ if not Gtk.init_check()[0]:
137
+ sys.exit(1)
138
+ clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
139
+ pending = b""
140
+ generation = 0
141
+ def send(value):
142
+ print(json.dumps(value, ensure_ascii=True), flush=True)
143
+ def changed(clipboard, event):
144
+ global generation
145
+ generation += 1
146
+ current = generation
147
+ def received(clipboard, text, unused):
148
+ if current == generation and text is not None and len(text.encode("utf-8")) <= ${p}:
149
+ send({"text": text})
150
+ clipboard.request_text(received, None)
151
+ # No request_text on startup: never share the pre-existing clipboard.
152
+ clipboard.connect("owner-change", changed)
153
+ def input_ready(fd, condition):
154
+ global pending
155
+ chunk = os.read(fd, 65536)
156
+ if not chunk:
157
+ Gtk.main_quit()
158
+ return False
159
+ pending += chunk
160
+ while b"\n" in pending:
161
+ line, pending = pending.split(b"\n", 1)
162
+ text = json.loads(line)
163
+ if not isinstance(text, str) or len(text.encode("utf-8")) > ${p} or "\x00" in text:
164
+ sys.exit(1)
165
+ clipboard.set_text(text, -1)
166
+ send("ack")
167
+ if len(pending) > ${p*6+2}:
168
+ sys.exit(1)
169
+ return True
170
+ GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
171
+ send("ready")
172
+ Gtk.main()
173
+ `;function mq(q,x){let X=hx("/usr/bin/python3",["-I","-u","-c",kx],{env:{DISPLAY:q.display,XAUTHORITY:q.xauthority},stdio:["pipe","pipe","ignore"]}),Q=!1,P=!0,b="",J=0,L=[],y=setTimeout(()=>U(),5000),W=()=>{Q=!0,clearTimeout(y),L.length=0,X.kill("SIGKILL")},U=()=>{if(Q)return;W(),x.end({error:new Z("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},C=(R,D=32)=>{if(Q)return;if(!P){R();return}if(J+=D,J>cq)W(),x.end({reason:"input_backpressure"});else L.push({apply:R,bytes:D})};return X.stdout.on("data",(R)=>{if(Q)return;b+=R.toString("ascii");for(let D=b.indexOf(`
174
+ `);D>=0;D=b.indexOf(`
175
+ `)){let Y=b.slice(0,D);b=b.slice(D+1);let A;try{A=JSON.parse(Y)}catch{U();return}if(A==="ready"||A==="ack"){clearTimeout(y),P=!1;while(!P&&!Q&&L.length){let N=L.shift();J-=N.bytes,N.apply()}}else if(A&&typeof A==="object"&&"text"in A&&typeof A.text==="string"&&Buffer.byteLength(A.text)<=p)x.clipboard(A.text);else{U();return}if(Q)return}if(b.length>p*6+32)U()}),X.stdin.on("error",U),X.once("error",U),X.once("exit",U),{apply:C,write(R){if(Buffer.byteLength(R)>p||R.includes("\x00")){U();return}let D=`${JSON.stringify(R)}
176
+ `;C(()=>{if(P=!0,y=setTimeout(()=>U(),5000),X.stdin.write(D),X.stdin.writableLength>cq)W(),x.end({reason:"input_backpressure"})},Buffer.byteLength(D))},close:W}}var t={smooth:{fps:60,crf:23,kbps:8000,x264Preset:"ultrafast",threads:2,scale:1},sharp:{fps:30,crf:19,kbps:1e4,x264Preset:"superfast",scale:1},data_saver:{fps:20,crf:28,kbps:2000,x264Preset:"ultrafast",scale:0.75},balanced:{fps:30,crf:23,kbps:4000,x264Preset:"ultrafast",threads:2,scale:1}},ux="avc1.4D002A",rq={width:1920,height:1080},cx=262144,mx=0.2,rx=250,lx=1e4,dx=1024,d8=1e4,sx=500,ax=60,ix=1e4,nx=1000,lq=1048576,X0={kind:"mac_screen",sound:null},ox,dq=()=>ox??=r()?.ffmpeg??null,n8=(q,x,X)=>i8(q,x,{env:X,stdio:["ignore","pipe","ignore"]}),tx,o8=()=>tx??=hq(r()),sq=(q,x,X)=>{let[Q,...P]=[...o8(),q];return n8(Q,[...P,...x],X)},aq=()=>L0?.videotoolbox?"h264_videotoolbox":"libx264",ex=()=>Math.round(performance.now()*1000),s8=new Set,iq=!1;function Q0(q){if(s8.add(q),q.once("exit",()=>s8.delete(q)),iq)return;iq=!0,process.once("exit",()=>{for(let x of s8)try{x.kill("SIGKILL")}catch{}})}function P0(q){try{q.stdout?.destroy()}catch{}if(q.exitCode!==null||q.signalCode!==null)return;try{q.kill("SIGTERM")}catch{return}let x=setTimeout(()=>{if(q.exitCode===null&&q.signalCode===null)try{q.kill("SIGKILL")}catch{}},sx);q.once("exit",()=>clearTimeout(x))}function q1(q,x,X){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(q),"-video_size",`${x.width}x${x.height}`,"-i",X],size:x}}function x1(q){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(q),"-i","Capture screen 0:none"],size:null}}function X1(q){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(q),"-i","pipe:0"],size:null}}var b0=1700000;function J0(q){return Math.min(1,Math.round(Math.sqrt(b0/(q.width*q.height))*100)/100)}function Q1(q,x,X){let Q=i8(X.axe,["stream-video","--udid",X.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,J0(X.size)))],{stdio:["ignore","pipe","ignore"]}),P=i8(q,x,{env:{},stdio:["pipe","pipe","ignore"]});Q.stdout.pipe(P.stdin),P.stdin.on("error",()=>{});let b=()=>{if(Q.exitCode===null&&Q.signalCode===null)Q.kill("SIGTERM")};return P.once("exit",b),P.once("error",b),Q.once("exit",()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")}),Q.once("error",()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")}),P}function P1(q){let x=Math.min(1,rq.width/q.width,rq.height/q.height);return{width:Math.round(q.width*x),height:Math.round(q.height*x)}}function a8(q,x,X,Q="libx264"){let P=t[q],b=(C)=>Math.max(2,Math.floor(C/2)*2),J={width:b(X.width*P.scale),height:b(X.height*P.scale)},L=J.width!==x.size?.width||J.height!==x.size.height,y=Math.max(1,Math.round(P.kbps*2/P.fps)),W=["-g",String(P.fps*ax)],U=Q==="h264_videotoolbox"?["-c:v","h264_videotoolbox","-realtime","1","-prio_speed","1","-allow_sw","1","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","nv12",...W,"-b:v",`${P.kbps}k`,"-maxrate",`${P.kbps}k`,"-bufsize",`${y}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",P.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...P.threads?["-threads",String(P.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...W,"-crf",String(P.crf),"-maxrate",`${P.kbps}k`,"-bufsize",`${y}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...x.args,"-an",...L?["-vf",`scale=${J.width}:${J.height}:flags=fast_bilinear`]:[],...U,"-flush_packets","1","-f","h264","pipe:1"]}class N0{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(q,x){if(this.buffer.byteLength===0)this.micros=x;let X=new Uint8Array(this.buffer.byteLength+q.byteLength);X.set(this.buffer),X.set(q,this.buffer.byteLength),this.buffer=X;let Q=[],P=this.scanned;while(P+3<this.buffer.byteLength){if(this.buffer[P]!==0||this.buffer[P+1]!==0||this.buffer[P+2]!==1){P++;continue}let b=this.buffer[P+3]&31,J=P>0&&this.buffer[P-1]===0?P-1:P;if(b===9&&J>0)Q.push({data:this.buffer.slice(0,J),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(J),this.key=!1,this.micros=x,P-=J;if(b===5)this.key=!0;P+=3}return this.scanned=P,Q}}function b1(q,x){let X=vx({path:q}),Q=Buffer.alloc(0),P="version",b=0,J=!1,L=[],y=0,W=!1,U=(N)=>{if(W)return;W=!0,X.destroy(),x.end(N)},C=()=>U({reason:"display_protocol"}),R=(N)=>{if(W)return;if(!J){if(y+=N.byteLength,y>lq)U({reason:"input_backpressure"});else L.push(N);return}if(X.write(N),X.writableLength>lq)U({reason:"input_backpressure"})},D=(N)=>{Q=Q.subarray(N)},Y=()=>{switch(P){case"version":{if(Q.byteLength<12)return!1;let N=/^RFB (\d{3})\.(\d{3})\n$/.exec(Q.subarray(0,12).toString("latin1"));if(!N||Number(N[1])*1000+Number(N[2])<3007)return C(),!1;return D(12),X.write(`RFB 003.007
177
+ `),P="security",!0}case"security":{if(Q.byteLength<1)return!1;let N=Q[0];if(N===0)return C(),!1;if(Q.byteLength<1+N)return!1;if(!Q.subarray(1,1+N).includes(1))return C(),!1;return D(1+N),X.write(Buffer.from([1,1])),P="init",!0}case"init":{if(Q.byteLength<24)return!1;let N=Q.readUInt32BE(20);if(N>65536)return C(),!1;if(Q.byteLength<24+N)return!1;let S={width:Q.readUInt16BE(0),height:Q.readUInt16BE(2)};if(D(24+N),S.width===0||S.height===0)return C(),!1;P="messages",J=!0;for(let F of L)X.write(F);return L=[],y=0,x.ready(S),!W}case"skip":{let N=Math.min(b,Q.byteLength);if(D(N),b-=N,b>0)return!1;return P="messages",!0}case"messages":{if(Q.byteLength<1)return!1;switch(Q[0]){case 1:{if(Q.byteLength<6)return!1;let N=6+Q.readUInt16BE(4)*6;if(Q.byteLength<N)return!1;return D(N),!0}case 2:return D(1),!0;case 3:{if(Q.byteLength<8)return!1;let N=Q.readUInt32BE(4);if(N>p/2)return D(8),P="skip",b=N,!0;if(Q.byteLength<8+N)return!1;let S=Q.subarray(8,8+N).toString("latin1");return D(8+N),x.clipboard(S),!W}default:return C(),!1}}}},A=!1;return X.once("connect",()=>{A=!0}),X.on("data",(N)=>{if(W)return;Q=Q.byteLength?Buffer.concat([Q,N]):N;while(!W&&Y());}),X.once("error",()=>{if(!A)U({error:new Z("display_unavailable","Reason could not reach this machine's desktop server.")})}),X.once("close",()=>U({reason:"display_closed"})),{pointer(N,S,F){let K=Buffer.alloc(6);K.writeUInt8(5,0),K.writeUInt8(F&255,1),K.writeUInt16BE(N,2),K.writeUInt16BE(S,4),R(K)},key(N,S){let F=Buffer.alloc(8);F.writeUInt8(4,0),F.writeUInt8(N?1:0,1),F.writeUInt32BE(S>>>0,4),R(F)},clipboard(N){if(Array.from(N).some((K)=>K.codePointAt(0)>255)){U({reason:"clipboard_unicode_unsupported"});return}let S=Buffer.from(N,"latin1"),F=Buffer.alloc(8);F.writeUInt8(6,0),F.writeUInt32BE(S.byteLength,4),R(Buffer.concat([F,S]))},close(){W=!0,X.destroy()}}}class t8{run=null;viewers=new Set;get running(){return this.run!==null}start(q,x,X,Q){this.viewers.add(q),this.stop();let P;try{P=X()}catch{this.fail();return}Q0(P);let b={child:P,splitter:new N0};this.run=b;for(let L of[...this.viewers])L.started(x);P.stdout?.on("data",(L)=>{if(this.run!==b)return;for(let y of b.splitter.push(L,Q()))for(let W of[...this.viewers])W.unit(y)});let J=()=>{if(this.run!==b)return;this.run=null,this.fail()};P.once("exit",J),P.once("error",J)}leave(q){if(!this.viewers.delete(q))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;P0(this.run.child),this.run=null}fail(){for(let q of[...this.viewers])q.failed()}}var nq=new WeakMap;function J1(q){let x=nq.get(q);if(!x)nq.set(q,x=new t8);return x}function W0(q,x,X={}){let Q=X.micros??ex,P=new eq,b=x.request.preset,J=null,L=null,y=null,W=!1,U=null,C=!1,R=!1,D=null,Y=0,A=0,N=!1,S=null,F=null,K=0,$=null,_=[],E=0,V=[],g=new Uint32Array(d8+1),v=0,w=null,O=0,k=0,I=0,bq=0,Jq=0,b8=null,F8=0,d={frames:0,bytes:0,since:Q()},s=[],q8=0,w8,K8=!1,Y0=Q(),f={},a=()=>Math.round((Q()-Y0)/1000),Nq=X.control??kq,M8=null,z8=null,h=(T)=>{let j=C8(T);return q.send(j),bq+=j.byteLength,j.byteLength},J8=(T)=>{if(q.done)return;if(q.open)h({type:"error",code:T});q.end({reason:T})},N8=()=>Math.max(cx,t[b].kbps*1000/8*mx),W8=()=>Q()/1000,_0=()=>{while(V.length>1&&V[0].atMs<W8()-lx)V.shift();return V[0]?.rttMs??null},Wq=(T)=>{let j=_0();if(j===null||_.length===0)return!1;let B=(j+rx)*T;return W8()-_[0].sentMs>B||E>B/1000*t[b].kbps*1000/8},E0=(T)=>{if(K===0)return;let j=Math.min(T,K-1);if($!==null&&j<=$)return;$=j;let B=W8();while(_.length&&_[0].seq<=j){let M=_.shift();if(E-=M.bytes,M.seq!==j)continue;let z=Math.max(0,B-M.sentMs);while(V.length&&V.at(-1).rttMs>=z)V.pop();V.push({atMs:B,rttMs:z}),g[Math.min(d8,Math.round(z))]++,v++,w=Math.min(w??z,z)}},$0=()=>{let T=0;for(let j=0;j<=d8;j++)if(T+=g[j],T*2>=v)return j;return 0},O0=()=>q.bufferedAmount<=N8()/2&&!Wq(0.5),Lq=()=>{K8=!0,s=[],q8=0,U?.leave(Y8),U=null},jq=(T)=>{if(q.done)return;if(T.key)f.first_key_ms??=a();if(!W){if(!U||s.length===0&&!T.key)return;if(s.push(T),q8+=T.data.byteLength,q8>N8())Lq();return}if(N){k++;return}if(q.bufferedAmount>N8()||Wq(1)){N=!0,k++,S=setInterval(()=>{if(q.done||!O0())return;if(S)clearInterval(S);S=null,N=!1,E8()},X.drainPollMs??25);return}if(!C){if(!T.key){k++;return}if(h({type:"hello",width:L.width,height:L.height,fps:t[b].fps,preset:b,codec:ux}),C=!0,f.first_frame_ms??=a(),!R&&J?.sound)h({type:"audioHello",...P8}),R=!0}let j=h({type:"frame",key:T.key,seq:K,captureMicros:T.micros,data:T.data});if(_.push({seq:K,sentMs:W8(),bytes:j}),E+=j,_.length>dx)E-=_.shift().bytes;K++,O++,b8??=T.micros,F8=T.micros,d.frames++,d.bytes+=j},Y8={started(T){b=T,C=!1,s=[],q8=0},unit:jq,failed:()=>J8("encoder_failed")},_8=()=>{let T=(X.ffmpeg??dq)();if(!J||!L){J8("encoder_failed");return}let[j,B]=[J,L],M="kind"in j&&j.kind==="simulator"?j.stream:null;if(!T&&!M){J8("encoder_failed");return}if(U??="kind"in j&&j.kind==="mac_screen"?J1(X.spawn??sq):new t8,f.encoder_ms===void 0)f.encoder_ms=a(),f.encoder_shared=U.running;U.start(Y8,b,()=>{let z=t[b].fps;if(M)return M(z,t[b].kbps,b0);if("kind"in j&&j.kind==="simulator"){let u=Math.min(0.99,J0(j.size)),x8={width:j.size.width*u,height:j.size.height*u};return Q1(T,a8(b,X1(Math.min(z,30)),x8,(X.macEncoder??aq)()),j)}return"kind"in j?(X.spawn??sq)(T,a8(b,x1(z),P1(B),(X.macEncoder??aq)()),{}):(X.spawn??n8)(T,a8(b,q1(z,B,j.display),B),{DISPLAY:j.display,XAUTHORITY:j.xauthority})},Q)},L8=()=>{if(!D)return;P0(D.child),D=null},H0=()=>{let T=(X.ffmpeg??dq)();if(D||q.done||!R||!J?.sound||!T)return;let j;try{j=(X.spawn??n8)(T,uq(),{PULSE_SERVER:R8(J.sound)})}catch{return}Q0(j);let B={child:j,reader:new l8};D=B,j.stdout?.on("data",(z)=>{if(D!==B||q.done)return;let u;try{u=B.reader.push(z)}catch{L8();return}let x8=Q();for(let f0 of u){if(q.bufferedAmount>N8()){A++;continue}h({type:"audio",captureMicros:x8,data:f0}),Y++}});let M=()=>{if(D===B)L8()};j.once("exit",M),j.once("error",M)},E8=()=>{if(!U||q.done)return;I++,_8()},Uq=()=>{if(q.done||!L)return;if(!W){if(U||K8)return;_8(),w8=setTimeout(()=>{if(!W)Lq()},ix);return}if(clearTimeout(w8),f.encoder_early===void 0){if(f.encoder_early=U!==null,K8)f.hold_lapsed=!0}if(!U)_8();let T=s;s=[],q8=0;for(let j of T)jq(j);F??=setInterval(()=>{let j=Q(),B=Math.max(0.001,(j-d.since)/1e6);h({type:"stats",stats:{fps:Math.round(d.frames/B*10)/10,kbps:Math.round(d.bytes*8/1000/B),dropped:k,restarts:I,queued_bytes:q.bufferedAmount}}),d={frames:0,bytes:0,since:j}},nx)};x.desktop.then((T)=>{if(q.done)return;J=T;let j={ready(B){L=B,f.desktop_ms??=a(),Uq()},clipboard(B){if(q.open&&Buffer.byteLength(B)<=p)h({type:"serverClipboard",text:B})},end(B){if("reason"in B&&q.open)h({type:"error",code:B.reason});q.end(B)}};if("kind"in T&&T.kind==="simulator")y=T.input,j.ready(T.points);else if("kind"in T)y=(X.macInput??((B)=>x0(B,o8())))(j);else{let B=(X.linuxClipboard??mq)(T,j),M=b1(T.rfbSocket,{...j,clipboard:(z)=>{if(!B)j.clipboard(z)}});y=B?{pointer:(z,u,x8)=>B.apply(()=>M.pointer(z,u,x8)),key:(z,u)=>B.apply(()=>M.key(z,u)),clipboard:(z)=>B.write(z),close(){B.close(),M.close()}}:M}Tq()},(T)=>q.end({error:T}));function Tq(){if(z8||!x.viewerSameNetwork||!W||q.done||!J||!("kind"in J)||J.kind!=="mac_screen")return;z8=(X.macWindows??q0)((T)=>{if(q.open)h({type:"windows",bounds:T})})}let Dq={viewer:x.viewer??null,notify(T){if(q.open)h({type:"control",control:T})}},$8=(T)=>{if(!y)return;if(!J||!("kind"in J)||J.kind!=="simulator")Nq.claim(Dq);T(y)};return{opened(){f.relay_ms??=a()},received(T){Jq+=T.byteLength;let j;try{j=P.push(T)}catch{J8("viewer_protocol");return}for(let B of j){if(q.done)return;switch(B.type){case"ping":h({type:"pong",token:B.token});break;case"pointer":$8((M)=>M.pointer(B.x,B.y,B.buttons));break;case"key":$8((M)=>M.key(B.down,B.keysym));break;case"clientClipboard":$8((M)=>M.clipboard(B.text));break;case"config":if(B.preset!==b)b=B.preset,E8();break;case"keyframeRequest":if(C&&!N)E8();break;case"ack":E0(B.seq);break;case"audioEnable":if(B.on)H0();else L8();break;default:break}}if(!W&&!q.done){if(W=!0,f.viewer_ms=a(),x.viewer)M8=Nq.join(Dq);Uq(),Tq()}},close(){if(M8?.(),M8=null,z8?.close(),S)clearInterval(S);if(F)clearInterval(F);clearTimeout(w8),U?.leave(Y8),L8(),y?.close()},summary:()=>({output_bytes:bq,input_bytes:Jq,video:{preset:b,frames:O,dropped:k,restarts:I,avg_fps:b8!==null&&F8>b8?Math.round((O-1)/((F8-b8)/1e6)*10)/10:0,min_rtt_ms:Math.round(w??0),p50_rtt_ms:v?$0():0,audio_packets:Y,audio_dropped:A,connect:f}})}}var oq=null,L0=null,N1=null;function W1(){let q=r();return q?.features.display?q.ffmpeg:null}function j0(q){return oq??=new Promise((x)=>{Ix(q,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(X,Q)=>{let P=(b)=>!X&&new RegExp(`^\\s*V\\S*\\s+${b}\\s`,"m").test(Q);x(L0={x264:P("libx264"),videotoolbox:P("h264_videotoolbox")})})}),oq}var tq=null;function Q9(){return tq??=(async()=>{let q=[r()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((X)=>Boolean(X&&px(X)));if(!q)return null;let x=await j0(q);return x.videotoolbox||x.x264?q:null})(),tq}function U0(q=process.platform,x={}){if(q!=="linux"&&q!=="darwin")return Promise.resolve(!1);let X=(x.ffmpeg??W1)();if(!X)return Promise.resolve(!1);let Q=(x.encoders??j0)(X);if(q==="linux")return Q.then((b)=>b.x264);let P=x.macScreen?x.macScreen():N1??=g8(o8());return Promise.all([Q,P]).then(([b,J])=>(b.x264||b.videotoolbox)&&J?.screen===!0&&J.accessibility)}import{existsSync as e8,realpathSync as y0,statSync as L1}from"fs";import{platform as j1}from"os";import{isAbsolute as S0,sep as U1}from"path";var T1=43200000,T0=R0,D1=4,B1=/^[A-Za-z0-9._:-]{1,160}$/,R1=1000;function Z0(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}function S8(q,x){if(typeof q!=="number"||!Number.isFinite(q)||q<=0)return x;return Math.min(R1,Math.max(1,Math.floor(q)))}function C1(q,x=Date.now()){let X=["relay_url","session_id","expires_at"],Q=new Set([...X,"cols","rows","cwd","workspace"]);if(!Z0(q)||X.some((U)=>!(U in q))||Object.keys(q).some((U)=>!Q.has(U)))throw new Z("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:P,session_id:b,expires_at:J}=q;if(typeof P!=="string")throw new Z("invalid_pty_request","Reason terminal relay URL is missing.");let L;try{L=new URL(P)}catch{throw new Z("invalid_pty_request","Reason terminal relay URL is invalid.")}if(L.protocol!=="wss:"&&L.protocol!=="ws:"||L.username||L.password)throw new Z("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof b!=="string"||!B1.test(b))throw new Z("invalid_pty_request","Reason terminal session identity is invalid.");let y=typeof J==="string"?Date.parse(J):Number.NaN;if(!Number.isFinite(y)||y<=x)throw new Z("invalid_pty_request","Reason terminal session has already expired.");if(q.cwd!==void 0&&typeof q.cwd!=="string")throw new Z("invalid_pty_request","Reason terminal working directory is invalid.");let W=q.workspace===void 0?void 0:B0(q.workspace);if(W===null||W&&q.cwd!==void 0)throw new Z("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:P,session_id:b,expires_at:new Date(Math.min(y,x+T1)).toISOString(),cols:S8(q.cols,80),rows:S8(q.rows,24),...q.cwd===void 0?{}:{cwd:q.cwd},...W?{workspace:W}:{}}}function y1(q,x){return x===q||x.startsWith(q+U1)}function D0(q,x){if(x===void 0)return q;if(!S0(x))throw new Z("pty_cwd_invalid","Reason terminal working directory must be absolute.");let X;try{X=y0(x)}catch{throw new Z("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!y1(q,X))throw new Z("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!L1(X).isDirectory())throw new Z("pty_cwd_invalid","Reason terminal working directory is not a directory.");return X}function S1(q=process.env){let x=q.SHELL;if(x&&S0(x)&&e8(x))return x;for(let X of j1()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(e8(X))return X;return"/bin/sh"}function Z1(){let q=globalThis.Bun;if(!q)throw new Z("pty_unavailable","Reason terminals require the Bun runtime.");return q.spawn}function D9(){return typeof globalThis.Bun<"u"}var G1=(q)=>{let x=Z1()({cmd:[q.shell,"-i","-l"],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(Q,P)=>{q.onData(P)}}}),X=x.terminal;if(!X){try{x.kill()}catch{}throw new Z("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(Q)=>X.write(Q),resize:(Q,P)=>X.resize(Q,P),kill:()=>{try{x.kill()}catch{}},exited:x.exited.then((Q)=>typeof Q==="number"?Q:null,()=>null)}},qq=(q,x)=>{return x===void 0?new WebSocket(q):new WebSocket(q,{proxy:x})},y8=new Set;function A1(q){if(y8.size>=D1||y8.has(q))return null;y8.add(q);let x=!1;return()=>{if(x)return;x=!0,y8.delete(q)}}async function B9(q,x={}){let X=x.now??Date.now,Q=C1(q.payload,X()),P=A1(q.operationId);if(!P)throw new Z("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let b=X(),J,L,y;try{let W=Q.workspace?C0(q.root,Q.workspace):void 0;J=W?D0(e8(W.boundary)?y0(W.boundary):W.boundary,W.path):D0(q.root,Q.cwd),L=x.environment??process.env,y=x.shellPath??S1(L)}catch(W){throw P(),W}return await new Promise((W,U)=>{let C=null,R=null,D=!1,Y=!1,A=!1,N=null,S=0,F=0,K=[],$=0,_=null,E=(w)=>{if(A)return;if(A=!0,_)clearTimeout(_);q.signal.removeEventListener("abort",V);try{C?.kill()}catch{}try{R?.close(1000,"pty_session_over")}catch{}if(P(),w.kind==="rejected"){U(w.error);return}let O={reason:w.reason,exit_code:N,output_bytes:S,input_bytes:F,duration_ms:Math.max(0,X()-b)};q.emitEvent("pty.stopped",{...O}).catch(()=>{return}),W({...O})},V=()=>{let w=q.signal.reason;E({kind:"rejected",error:w instanceof Z?w:new Z("cancelled","Reason closed the terminal session.")})};if(q.signal.aborted){V();return}q.signal.addEventListener("abort",V,{once:!0}),_=setTimeout(()=>E({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(Q.expires_at)-X()));let g=(w)=>{if(S+=w.byteLength,!D||!R){if(K.push(w),$+=w.byteLength,$>T0)E({kind:"resolved",reason:"output_backpressure"});return}try{R.send(w)}catch{E({kind:"resolved",reason:"relay_closed"});return}if(R.bufferedAmount>T0)E({kind:"resolved",reason:"output_backpressure"})};try{C=(x.spawnPty??G1)({shell:y,args:["-i","-l"],cwd:J,cols:Q.cols,rows:Q.rows,environment:L,onData:(w)=>{if(!A)g(w)}})}catch(w){E({kind:"rejected",error:w instanceof Z?w:new Z("pty_spawn_failed","Reason could not start the terminal shell.")});return}C.exited.then((w)=>{if(A)return;if(N=w,D&&R)try{R.send(JSON.stringify({t:"exit",code:w}))}catch{}E({kind:"resolved",reason:"shell_exited"})});let v=(x.loadProxy??Z8)()?.url;try{R=(x.connect??qq)(Q.relay_url,v)}catch{E({kind:"rejected",error:new Z("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}R.binaryType="arraybuffer",R.onopen=()=>{if(A||!R)return;D=!0;try{R.send(JSON.stringify({t:"open",cols:Q.cols,rows:Q.rows}));for(let w of K.splice(0))R.send(w);$=0}catch{E({kind:"resolved",reason:"relay_closed"});return}Y=!0,q.emitEvent("pty.ready",{session_id:Q.session_id,cols:Q.cols,rows:Q.rows}).catch(()=>{return})},R.onmessage=(w)=>{if(A||!C)return;let O=w.data;if(typeof O==="string"){let I;try{I=JSON.parse(O)}catch{return}if(!Z0(I))return;if(I.t==="resize"){try{C.resize(S8(I.cols,Q.cols),S8(I.rows,Q.rows))}catch{}return}if(I.t==="close")E({kind:"resolved",reason:"client_closed"});return}let k=O instanceof ArrayBuffer?new Uint8Array(O):ArrayBuffer.isView(O)?new Uint8Array(O.buffer,O.byteOffset,O.byteLength):null;if(!k||k.byteLength===0)return;F+=k.byteLength;try{C.write(k)}catch{}},R.onclose=()=>{if(A)return;if(!Y){E({kind:"rejected",error:new Z("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}E({kind:"resolved",reason:"relay_closed"})},R.onerror=()=>{if(A||Y)return;E({kind:"rejected",error:new Z("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}var E1=43200000,G8=":99",$1=60000,V8=15000,Qq={width:1280,height:800},O1=/^[A-Za-z0-9._:-]{1,160}$/;function H1(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}var f1=["video","viewer","viewer_same_network","viewer_network"];function g1(q,x=Date.now()){let X=["relay_url","session_id","expires_at"];if(!H1(q)||X.some((L)=>!(L in q))||Object.keys(q).some((L)=>!X.includes(L)&&!f1.includes(L)))throw new Z("invalid_display_request","Reason desktop request is malformed.");let Q="video"in q?F0(q.video):void 0,P="viewer"in q?V0(q.viewer):null;if(Q===null)throw new Z("invalid_display_request","Reason desktop video request is invalid.");let b=null;try{b=typeof q.relay_url==="string"?new URL(q.relay_url):null}catch{}if(!b||b.protocol!=="wss:"&&b.protocol!=="ws:"||b.username||b.password)throw new Z("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof q.session_id!=="string"||!O1.test(q.session_id))throw new Z("invalid_display_request","Reason desktop session identity is invalid.");let J=typeof q.expires_at==="string"?Date.parse(q.expires_at):Number.NaN;if(!Number.isFinite(J)||J<=x)throw new Z("invalid_display_request","Reason desktop session has already expired.");return{relay_url:q.relay_url,session_id:q.session_id,expires_at:new Date(Math.min(J,x+E1)).toISOString(),...Q?{video:Q}:{},...P?{viewer:P}:{},...Q&&q.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function h1(q=process.platform){return(q==="linux"||q==="darwin")&&r()?.features.display===!0}async function $9(){if(process.platform!=="darwin")return h1();return await U0()}function A8(q){M1(q,{recursive:!0,mode:448});let x=K1(q);if(!x.isDirectory()||x.isSymbolicLink()||process.getuid&&x.uid!==process.getuid())throw new Z("display_unavailable","Reason desktop state directory is not private.");w1(q,448)}function k1(q,x){let X=(P)=>{let b=Buffer.alloc(2);return b.writeUInt16BE(P.length),Buffer.concat([b,P])},Q=Buffer.from([255,255]);return Buffer.concat([Q,X(Buffer.alloc(0)),X(Buffer.from(q)),X(Buffer.from("MIT-MAGIC-COOKIE-1")),X(x)])}function e(q,x,X=2000){return new Promise((Q)=>{let P=_1(q),b="",J=(L)=>{P.destroy(),Q(L)};P.setTimeout(X,()=>J(!1)),P.once("error",()=>J(!1)),P.once("close",()=>J(!1)),P.once("connect",()=>{if(!x)J(!0)}),P.on("data",(L)=>{if(b+=L.toString("latin1"),b.length>=4)J(b.startsWith("RFB "))})})}async function M0(q,x){let X=Date.now()+x;while(Date.now()<X){if(await q())return!0;await new Promise((Q)=>setTimeout(Q,100))}return!1}function Pq(q,x,X){return new Promise((Q)=>{let P=w0(q,x,{detached:!0,stdio:"ignore",env:X});P.once("error",()=>Q(-1)),P.once("exit",(b)=>Q(b)),P.unref(),setTimeout(()=>Q(null),V8).unref()})}var xq=null;function I1(q=o()){return xq??=p1(q).finally(()=>{xq=null}),xq}async function p1(q){let x=r({home:q});if(!x?.xvfb||!x.x11vnc||!x.openbox)throw new Z("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");A0({root:x.root,automation:x.automation,extensionDir:x.extensionDir});let X=H(x.root,"display");A8(X);let Q=await u1(q,X,x.x11vnc);if(Q)return Q;let P={display:G8,xauthority:H(X,"Xauthority"),rfbSocket:H(X,"rfb.sock")},b=H(X,"pulse"),J=(async()=>{try{A8(b)}catch{return null}return await vq(b,x.pulseaudio)})(),L=H(X,"home");A8(L);let y={HOME:L,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:P.display,XAUTHORITY:P.xauthority};if(x.pulseaudio)y.PULSE_SERVER=R8(r8(b));let W=async()=>({...P,sound:await J});if(await e({path:P.rfbSocket},!0))return await W();if(!K0(P.xauthority))Xq(P.xauthority,k1(G8.slice(1),F1(16)),{mode:384,flag:"wx"});let U=c1(H(X,"theme"),P.display),C={path:`/tmp/.X11-unix/X${G8.slice(1)}`};if(!await e(C,!1)){if(Pq(x.xvfb,[P.display,"-screen","0",`${Qq.width}x${Qq.height}x24`,"-nolisten","tcp","-auth",P.xauthority],y),!await M0(()=>e(C,!1),V8))throw new Z("display_unavailable","Reason could not start the virtual display.");Pq(x.openbox,["--config-file",U.openboxConfig],y)}if(await m1(U,y),!await z0(x.x11vnc,P,X,"x11vnc.log",y))throw new Z("display_unavailable","Reason could not start the desktop server.");return await W()}async function z0(q,x,X,Q,P){if(await e({path:x.rfbSocket},!0))return!0;Y1(x.rfbSocket,{force:!0});let b=await Pq(q,["-display",x.display,"-auth",x.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",x.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",H(X,Q)],P);if(b!==null&&b!==0)return!1;return await M0(()=>e({path:x.rfbSocket},!0),V8)}async function v1(){let q=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],x=(X)=>Object.fromEntries(q.flatMap((Q)=>X[Q]?[[Q,X[Q]]]:[]));if(process.env.DISPLAY)return x(process.env);try{let X=await new Promise((Q,P)=>V1("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(b,J)=>b?P(b):Q(J)));return x(Object.fromEntries(X.split(`
178
+ `).flatMap((Q)=>{let P=Q.indexOf("=");return P>0?[[Q.slice(0,P),Q.slice(P+1)]]:[]})))}catch{return{}}}var G0=new Set;async function u1(q,x,X){let Q=await v1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===G8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??H(q,".Xauthority"),rfbSocket:H(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(G0.has(J)||!await e({path:`/tmp/.X11-unix/X${P}`},!1))return null;let L={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await z0(X,b,x,`x11vnc-${P}.log`,L))return{...b,sound:null};return G0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
179
+ `),null}function c1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!K0(`/usr/bin/${b}`)).map(([b])=>b),P=Aq({root:q,display:x,screen:Qq,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])A8(H(q,b));for(let[b,J]of Object.entries(P.files))Xq(H(q,b),J,{mode:384});for(let[b,J]of Object.entries(Gq))Xq(H(q,`ara-${b}`),z1(J),{mode:384});return{root:q,openboxConfig:H(q,"openbox","rc.xml"),start:P.start}}async function m1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
180
+ `);await new Promise((Q)=>{let P=w0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},V8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function O9(q,x={}){let X=x.now??Date.now,Q=g1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new Z("display_video_required","Reason desktops stream as video now; this request came without it.");let P=x.platform??process.platform;if(P!=="linux"&&P!=="darwin")throw new Z("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>X0:I1))();return await r1(q.signal,Q,x,X,(L)=>W0(L,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(L)=>C8({type:"error",code:L}))}function r1(q,x,X,Q,P,b){let J=Q();return new Promise((L,y)=>{let W=null,U=!1,C=!1,R,D,Y,A=!1,N=null,S=(V)=>{if(C)return;if(N)V=N;C=!0,clearTimeout(R),clearTimeout(D),q.removeEventListener("abort",K),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in V){y(V.error);return}L({reason:V.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},F=()=>S({error:new Z("display_relay_unavailable","Reason could not reach the desktop relay.")}),K=()=>{let V=q.reason;S({error:V instanceof Z?V:new Z("cancelled","Reason closed the desktop session.")})},$=()=>{if(!N||!W)return;let V=N.error;try{W.send(b(V instanceof Z?V.code:"display_unavailable"))}catch{}S(N)};if(Y=P({get done(){return C||N!==null},get open(){return U&&!C&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(V){if(C||N||!U||!W)return;try{W.send(V)}catch{S({reason:"relay_closed"})}},end:(V)=>{if(C||N)return;if(!("error"in V)){S(V);return}if(N=V,A&&U)$()}}),C){Y.close();return}if(q.aborted){K();return}q.addEventListener("abort",K,{once:!0}),R=setTimeout(()=>S({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),D=setTimeout(()=>S({reason:"viewer_absent"}),X.viewerWaitMs??$1);try{W=(X.connect??qq)(x.relay_url,(X.loadProxy??Z8)()?.url)}catch{F();return}W.binaryType="arraybuffer",W.onopen=()=>{if(C||!W)return;U=!0,Y?.opened()},W.onmessage=(V)=>{if(C)return;let g=V.data,v=g instanceof ArrayBuffer?new Uint8Array(g):ArrayBuffer.isView(g)?new Uint8Array(g.buffer,g.byteOffset,g.byteLength):null;if(!v||v.byteLength===0)return;if(clearTimeout(D),A=!0,N){$();return}Y?.received(v)},W.onclose=()=>{if(C)return;if(!U){F();return}S({reason:"relay_closed"})},W.onerror=()=>{if(C||U)return;F()}})}
181
+ export{T1 as $d,T0 as ae,D1 as be,D9 as ce,B9 as de,O8 as ee,PX as fe,NX as ge,i as he,R8 as ie,Q9 as je,U0 as ke,Vq as le,Hq as me,r as ne,HX as oe,fX as pe,gX as qe,E1 as re,G8 as se,g1 as te,h1 as ue,$9 as ve,A8 as we,I1 as xe,O9 as ye};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$a as n6,Ea as u6,Ga as L4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as w4,wa as v6,xa as p6}from"./vm-hands-entry-lite-htn1genx.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-c2nrar90.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-65pbrs1x.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as w0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-1hwdab4e.js";import{Cc as H7,Lc as D7,zc as r1}from"./vm-hands-entry-lite-jwqqfjba.js";import{Ad as O6,Bd as j6,Cd as I6,Dd as A6,Ed as T6,Jd as D8,Kd as M8,Ld as w8,Mc as w1,Md as L8,Nc as Q2,Nd as O8,Oc as e5,Od as j8,Pc as I3,Qc as r3,Qd as I8,Rc as a3,Rd as A8,Sc as M0,Sd as T8,Td as _8,Ud as R8,Vd as P8,Wc as N0,Wd as z8,Xd as q8,Yd as E8,Zc as u,Zd as g8,_c as E1,bd as H8,dd as g1,fd as $6,gd as J6,hd as Z6,id as Q6,jd as K6,kd as B6,ld as V6,md as G6,nd as U6,od as X6,pd as W6,qd as Y6,rd as F6,sd as N6,td as C6,ud as H6,vd as D6,wd as M6,xd as w6,yd as L6}from"./vm-hands-entry-lite-gqncr2j0.js";import{_d as V}from"./vm-hands-entry-lite-sv6xwe0h.js";import{$d as W7,ae as Y7,be as F7,ce as N7,de as C7,je as p5,ne as Q5,oe as T5,ue as M7,xe as K5,ye as l1}from"./vm-hands-entry-lite-5pxbx31d.js";import{Xe as j4,cf as c6}from"./vm-hands-entry-lite-bfwf82rw.js";import{hf as M3,uf as g6}from"./vm-hands-entry-lite-ptmqg51y.js";import{Ag as K7,Bg as B7,Dg as V7,Eg as G7,Gg as U7,Hg as X7,yg as Z7,zg as Q7}from"./vm-hands-entry-lite-s2xydt0n.js";import{Vg as n1}from"./vm-hands-entry-lite-s5qn1k80.js";import{Xg as j1,Yg as k6,Zg as H4,_g as D4}from"./vm-hands-entry-lite-9pmag2qk.js";import{ah as D3,ch as $1,ih as K8,jh as J4}from"./vm-hands-entry-lite-84aq8d12.js";import{Gh as H}from"./vm-hands-entry-lite-ffg7rf02.js";import{Kh as a4}from"./vm-hands-entry-lite-7gh1rbn7.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((L,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),L()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let L={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=K.headers[M];if(typeof I==="string")L[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:L});for await(let M of K){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as l from"path";import{homedir as a7}from"os";function $2($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function J2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=r7($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,l,$,J),home:a7};function T($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");T(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function o3($,J,Z=o7){let Q=w1.parse($);if(!["darwin","linux"].includes(process.platform))T("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.realpathSync(J.root);if(K==="/")T("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)T("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)T("local_device_gh_read_only");if(!M0(Q)){let w=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!w.clean)n3(w.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=$2(z,l,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+l.sep)))T("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:l.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((w)=>process.env[w]?[[w,process.env[w]]]:[])):{}},X=async(w,_,P=W,g,b=T0)=>{J.assertCurrent();let x=await Z.command(w,_,{cwd:P,env:Y,input:g,maxBuffer:b,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),x.error||x.status!==0)T("local_device_gh_command_failed");return x.stdout},F=async(w)=>(await X(B,w)).toString("utf8").trim(),C=async(w,_="application/vnd.github+json")=>{r3(Q.repoFullName,w,{headers:{accept:_}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${_}`,w],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)T("local_device_gh_response_unavailable");let g=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!g)T("local_device_gh_response_invalid");let b=Number(g[1]);if(b>=200&&b<300&&P.status!==0)T("local_device_gh_response_unavailable");if(Buffer.byteLength(g[3])>Q2)T("local_device_gh_response_too_large");let x={};for(let n of g[2].split(/\r?\n/)){let r=n.indexOf(":"),D0=n.slice(0,r).toLowerCase();if(["link","content-type"].includes(D0))x[D0]=n.slice(r+1).trim().slice(0,8192)}return{kind:"read",status:b,headers:x,body:b>=200&&b<300?g[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[w,_]=Q.repoFullName.split("/"),P=await F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${w}`,"-f",`repo=${_}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)T("local_device_gh_response_too_large");let g=JSON.parse(P);if(g.errors||g.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||g.data.repository.pullRequest?.number!==Q.number)T("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let w=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),_=JSON.parse(w.body),P=(x)=>x.number===Q.number&&x.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&x.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&x.base?.ref===Q.expectedBaseRef&&x.head?.sha===Q.expectedHeadSha;if(w.status!==200||!P(_)||_.state!=="open"||_.draft!==!1||_.head?.sha!==Q.expectedHeadSha||_.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())T("local_device_gh_merge_target_changed");await F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);let g=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),b=JSON.parse(g.body);if(g.status!==200||!P(b)||b.merged!==!0)T("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)T("local_device_gh_default_branch");let w=await F(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(w))T("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:w}}if(Q.kind==="pr_mutation"){let w=Q.mutation,_=w.action==="edit"?["edit",...w.title!==void 0?[`--title=${w.title}`]:[],...w.body!==void 0?[`--body=${w.body}`]:[],...w.base?[`--base=${w.base}`]:[]]:w.action==="metadata"?["edit",`--${w.change}-${w.field}=${w.value}`]:w.action==="ready"?["ready"]:w.action==="draft"?["ready","--undo"]:["close"];return await F(["pr",..._,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)T("local_device_gh_workspace_unavailable");let N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+l.sep))T("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,L="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+i3+")")(),I=(w,_,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",w,_,...P]]:[_,P],O=async(w,_,P,g=T0)=>{let b=w===W||w.startsWith(W+l.sep),x=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...b?["-c",`credential.https://github.com.helper=${L}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",..._];if(b)return X(U,x,w,P,g);let n=l.join(N,".ara-local-gh-tmp");if(z.mkdirSync(n,{recursive:!0,mode:448}),z.lstatSync(n).isSymbolicLink()||z.realpathSync(n)!==n)T("local_device_gh_workspace_unavailable");J.assertCurrent();let r=await Z.command(...I(M(N,n),U,x),{cwd:w,input:P,maxBuffer:g,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:N,TMPDIR:n,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),r.error||r.status!==0)T("local_device_gh_collection_failed");return r.stdout},k=async(w,_)=>(await O(w,_)).toString("utf8").trim(),E=async(w,_)=>{let P=l.join(w,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)T("local_device_gh_workspace_unavailable");J.assertCurrent();let g=await Z.command(...I(M(w,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",_]),{cwd:w,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:w,TMPDIR:P}});if(J.assertCurrent(),g.error||g.status!==0)T("local_device_gh_materialization_failed")},j=async(w)=>{let _=new Map;if(w.length===0)return _;let P=await O(m,["cat-file","--batch"],[...new Set(w)].join(`
2
+ import{$a as n6,Ea as u6,Ga as L4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as w4,wa as v6,xa as p6}from"./vm-hands-entry-lite-t678ape1.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-c2nrar90.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-65pbrs1x.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as w0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-1hwdab4e.js";import{Cc as H7,Lc as D7,zc as r1}from"./vm-hands-entry-lite-bm9x8vng.js";import{Ad as O6,Bd as j6,Cd as I6,Dd as A6,Ed as T6,Jd as D8,Kd as M8,Ld as w8,Mc as w1,Md as L8,Nc as Q2,Nd as O8,Oc as e5,Od as j8,Pc as I3,Qc as r3,Qd as I8,Rc as a3,Rd as A8,Sc as M0,Sd as T8,Td as _8,Ud as R8,Vd as P8,Wc as N0,Wd as z8,Xd as q8,Yd as E8,Zc as u,Zd as g8,_c as E1,bd as H8,dd as g1,fd as $6,gd as J6,hd as Z6,id as Q6,jd as K6,kd as B6,ld as V6,md as G6,nd as U6,od as X6,pd as W6,qd as Y6,rd as F6,sd as N6,td as C6,ud as H6,vd as D6,wd as M6,xd as w6,yd as L6}from"./vm-hands-entry-lite-gqncr2j0.js";import{_d as V}from"./vm-hands-entry-lite-sv6xwe0h.js";import{$d as W7,ae as Y7,be as F7,ce as N7,de as C7,je as p5,ne as Q5,oe as T5,ue as M7,xe as K5,ye as l1}from"./vm-hands-entry-lite-rs7g2egs.js";import{Xe as j4,cf as c6}from"./vm-hands-entry-lite-bfwf82rw.js";import{hf as M3,uf as g6}from"./vm-hands-entry-lite-ptmqg51y.js";import{Ag as K7,Bg as B7,Dg as V7,Eg as G7,Gg as U7,Hg as X7,yg as Z7,zg as Q7}from"./vm-hands-entry-lite-s2xydt0n.js";import{Vg as n1}from"./vm-hands-entry-lite-s5qn1k80.js";import{Xg as j1,Yg as k6,Zg as H4,_g as D4}from"./vm-hands-entry-lite-9pmag2qk.js";import{ah as D3,ch as $1,ih as K8,jh as J4}from"./vm-hands-entry-lite-84aq8d12.js";import{Gh as H}from"./vm-hands-entry-lite-ffg7rf02.js";import{Kh as a4}from"./vm-hands-entry-lite-7gh1rbn7.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((L,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),L()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let L={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=K.headers[M];if(typeof I==="string")L[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:L});for await(let M of K){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as l from"path";import{homedir as a7}from"os";function $2($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function J2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=r7($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,l,$,J),home:a7};function T($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");T(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function o3($,J,Z=o7){let Q=w1.parse($);if(!["darwin","linux"].includes(process.platform))T("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.realpathSync(J.root);if(K==="/")T("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)T("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)T("local_device_gh_read_only");if(!M0(Q)){let w=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!w.clean)n3(w.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=$2(z,l,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+l.sep)))T("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:l.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((w)=>process.env[w]?[[w,process.env[w]]]:[])):{}},X=async(w,_,P=W,g,b=T0)=>{J.assertCurrent();let x=await Z.command(w,_,{cwd:P,env:Y,input:g,maxBuffer:b,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),x.error||x.status!==0)T("local_device_gh_command_failed");return x.stdout},F=async(w)=>(await X(B,w)).toString("utf8").trim(),C=async(w,_="application/vnd.github+json")=>{r3(Q.repoFullName,w,{headers:{accept:_}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${_}`,w],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)T("local_device_gh_response_unavailable");let g=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!g)T("local_device_gh_response_invalid");let b=Number(g[1]);if(b>=200&&b<300&&P.status!==0)T("local_device_gh_response_unavailable");if(Buffer.byteLength(g[3])>Q2)T("local_device_gh_response_too_large");let x={};for(let n of g[2].split(/\r?\n/)){let r=n.indexOf(":"),D0=n.slice(0,r).toLowerCase();if(["link","content-type"].includes(D0))x[D0]=n.slice(r+1).trim().slice(0,8192)}return{kind:"read",status:b,headers:x,body:b>=200&&b<300?g[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[w,_]=Q.repoFullName.split("/"),P=await F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${w}`,"-f",`repo=${_}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)T("local_device_gh_response_too_large");let g=JSON.parse(P);if(g.errors||g.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||g.data.repository.pullRequest?.number!==Q.number)T("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let w=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),_=JSON.parse(w.body),P=(x)=>x.number===Q.number&&x.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&x.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&x.base?.ref===Q.expectedBaseRef&&x.head?.sha===Q.expectedHeadSha;if(w.status!==200||!P(_)||_.state!=="open"||_.draft!==!1||_.head?.sha!==Q.expectedHeadSha||_.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())T("local_device_gh_merge_target_changed");await F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);let g=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),b=JSON.parse(g.body);if(g.status!==200||!P(b)||b.merged!==!0)T("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)T("local_device_gh_default_branch");let w=await F(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(w))T("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:w}}if(Q.kind==="pr_mutation"){let w=Q.mutation,_=w.action==="edit"?["edit",...w.title!==void 0?[`--title=${w.title}`]:[],...w.body!==void 0?[`--body=${w.body}`]:[],...w.base?[`--base=${w.base}`]:[]]:w.action==="metadata"?["edit",`--${w.change}-${w.field}=${w.value}`]:w.action==="ready"?["ready"]:w.action==="draft"?["ready","--undo"]:["close"];return await F(["pr",..._,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)T("local_device_gh_workspace_unavailable");let N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+l.sep))T("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,L="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+i3+")")(),I=(w,_,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",w,_,...P]]:[_,P],O=async(w,_,P,g=T0)=>{let b=w===W||w.startsWith(W+l.sep),x=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...b?["-c",`credential.https://github.com.helper=${L}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",..._];if(b)return X(U,x,w,P,g);let n=l.join(N,".ara-local-gh-tmp");if(z.mkdirSync(n,{recursive:!0,mode:448}),z.lstatSync(n).isSymbolicLink()||z.realpathSync(n)!==n)T("local_device_gh_workspace_unavailable");J.assertCurrent();let r=await Z.command(...I(M(N,n),U,x),{cwd:w,input:P,maxBuffer:g,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:N,TMPDIR:n,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),r.error||r.status!==0)T("local_device_gh_collection_failed");return r.stdout},k=async(w,_)=>(await O(w,_)).toString("utf8").trim(),E=async(w,_)=>{let P=l.join(w,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)T("local_device_gh_workspace_unavailable");J.assertCurrent();let g=await Z.command(...I(M(w,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",_]),{cwd:w,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:w,TMPDIR:P}});if(J.assertCurrent(),g.error||g.status!==0)T("local_device_gh_materialization_failed")},j=async(w)=>{let _=new Map;if(w.length===0)return _;let P=await O(m,["cat-file","--batch"],[...new Set(w)].join(`
3
3
  `)+`
4
4
  `,T0*8);for(let g=0;g<P.length;){let b=P.indexOf(10,g),[x,n,r]=P.subarray(g,b).toString("utf8").split(" ");if(b<0||!x||n!=="blob"||!/^[0-9]+$/.test(r??""))T("local_device_gh_object_invalid");_.set(x,P.subarray(b+1,b+1+Number(r)).toString("utf8")),g=b+1+Number(r)+1}return _},R=async(w,_,P)=>{let g=l.join(N,".ara-local-gh-tmp"),b=M(N,g)+`
5
5
  (allow file-read* file-write* (subpath ${JSON.stringify(N)}))
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ab as W9,Bb as u0,Ib as z0,wb as WQ,xb as Z8,yb as u9,zb as q0}from"./vm-hands-entry-lite-c2nrar90.js";import{Qb as PQ,Rb as IQ,Sb as rZ,Tb as tZ,Ub as G8}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as R0}from"./vm-hands-entry-lite-n07kxrd1.js";import{Mc as a$,Pc as o$,sd as R9,td as n0,ud as H8,vd as w0,zd as N0}from"./vm-hands-entry-lite-gqncr2j0.js";import{_d as I}from"./vm-hands-entry-lite-sv6xwe0h.js";import{Ie as kQ,Je as f8,Xe as wQ,bf as s9,cf as w8}from"./vm-hands-entry-lite-bfwf82rw.js";import{Bf as c9,Jf as A8,Kf as P0,Lf as j0,Mf as d9,Tf as R8,Uf as $Q,Vf as l$,ef as WZ,hf as F9,qf as r$,rf as t$,tf as e$,vf as v9,wf as p$,xf as u$,yf as x8}from"./vm-hands-entry-lite-ptmqg51y.js";import{Vg as aZ}from"./vm-hands-entry-lite-s5qn1k80.js";import{$g as iZ,Xg as U8,Yg as p9}from"./vm-hands-entry-lite-9pmag2qk.js";import{ah as F8,bh as l0,ch as W8,dh as s0,eh as K9,fh as Q8,gh as r8,hh as p0,ih as v0,jh as d$,th as F$}from"./vm-hands-entry-lite-84aq8d12.js";import{yh as JZ}from"./vm-hands-entry-lite-1bvbhwbb.js";import{Eh as oZ}from"./vm-hands-entry-lite-anaydk9m.js";import{Gh as C}from"./vm-hands-entry-lite-ffg7rf02.js";import{Hh as L1,Kh as ZZ}from"./vm-hands-entry-lite-7gh1rbn7.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000};function g9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function g0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function I$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function _0($){if(!g9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(I$)||!g0($.attachmentRevision,0)||!g0($.grantRevision,1)||!g0($.generation,1)||!g0($.port,1024,65535)||!g0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function y0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function M9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function P$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function N9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function R$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function E$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!g9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello"){let Z=_0(Q.binding);return g0(Q.messages,v.chunk,v.upload)?{type:"hello",binding:Z,messages:Q.messages}:{type:"hello",binding:Z}}if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:_0(Q.binding),reason:Q.reason};if(!I$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return N9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&g0(Q.status,200,599)&&P$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&P$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return N9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:M9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function T8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((G)=>G.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function O8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function j9($){return await O8($)===!0}function y9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function S$($){if(!g9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:_0($.binding),deviceRelayUrl:y9($.deviceRelayUrl,"device")}}function w$($){if(!g9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:_0($.binding)}}import{request as B4}from"http";import{WebSocket as C9}from"ws";import{randomBytes as F4,timingSafeEqual as W4}from"crypto";import{createServer as U4}from"net";var b$="x-preview-connection";async function k$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=F4(32).toString("base64url"),X=new Set,J=!1,G=U4((Y)=>{if(J||Q.aborted||X.size>=v.streams*2)return Y.destroy();X.add(Y);let H=new AbortController;Y.once("close",()=>{X.delete(Y),H.abort()}),Y.on("error",()=>Y.destroy()),Y.setTimeout(2000,()=>Y.destroy());let W=Buffer.alloc(0),F=(L)=>{W=Buffer.concat([W,L]);let B=W.indexOf(`\r
2
+ import{Ab as W9,Bb as u0,Ib as z0,wb as WQ,xb as Z8,yb as u9,zb as q0}from"./vm-hands-entry-lite-c2nrar90.js";import{Qb as PQ,Rb as IQ,Sb as rZ,Tb as tZ,Ub as G8}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as R0}from"./vm-hands-entry-lite-n07kxrd1.js";import{Mc as a$,Pc as o$,sd as R9,td as n0,ud as H8,vd as w0,zd as N0}from"./vm-hands-entry-lite-gqncr2j0.js";import{_d as I}from"./vm-hands-entry-lite-sv6xwe0h.js";import{Ie as kQ,Je as f8,Xe as wQ,bf as s9,cf as w8}from"./vm-hands-entry-lite-bfwf82rw.js";import{Bf as c9,Jf as A8,Kf as P0,Lf as j0,Mf as d9,Tf as R8,Uf as $Q,Vf as l$,ef as WZ,hf as F9,qf as r$,rf as t$,tf as e$,vf as v9,wf as p$,xf as u$,yf as x8}from"./vm-hands-entry-lite-ptmqg51y.js";import{Vg as aZ}from"./vm-hands-entry-lite-s5qn1k80.js";import{$g as iZ,Xg as U8,Yg as p9}from"./vm-hands-entry-lite-9pmag2qk.js";import{ah as F8,bh as l0,ch as W8,dh as s0,eh as K9,fh as Q8,gh as r8,hh as p0,ih as v0,jh as d$,th as F$}from"./vm-hands-entry-lite-84aq8d12.js";import{yh as JZ}from"./vm-hands-entry-lite-n0v0srqp.js";import{Eh as oZ}from"./vm-hands-entry-lite-anaydk9m.js";import{Gh as C}from"./vm-hands-entry-lite-ffg7rf02.js";import{Hh as L1,Kh as ZZ}from"./vm-hands-entry-lite-7gh1rbn7.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000};function g9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function g0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function I$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function _0($){if(!g9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(I$)||!g0($.attachmentRevision,0)||!g0($.grantRevision,1)||!g0($.generation,1)||!g0($.port,1024,65535)||!g0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function y0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function M9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function P$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function N9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function R$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function E$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!g9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello"){let Z=_0(Q.binding);return g0(Q.messages,v.chunk,v.upload)?{type:"hello",binding:Z,messages:Q.messages}:{type:"hello",binding:Z}}if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:_0(Q.binding),reason:Q.reason};if(!I$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return N9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&g0(Q.status,200,599)&&P$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&P$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return N9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:M9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function T8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((G)=>G.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function O8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function j9($){return await O8($)===!0}function y9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function S$($){if(!g9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:_0($.binding),deviceRelayUrl:y9($.deviceRelayUrl,"device")}}function w$($){if(!g9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:_0($.binding)}}import{request as B4}from"http";import{WebSocket as C9}from"ws";import{randomBytes as F4,timingSafeEqual as W4}from"crypto";import{createServer as U4}from"net";var b$="x-preview-connection";async function k$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=F4(32).toString("base64url"),X=new Set,J=!1,G=U4((Y)=>{if(J||Q.aborted||X.size>=v.streams*2)return Y.destroy();X.add(Y);let H=new AbortController;Y.once("close",()=>{X.delete(Y),H.abort()}),Y.on("error",()=>Y.destroy()),Y.setTimeout(2000,()=>Y.destroy());let W=Buffer.alloc(0),F=(L)=>{W=Buffer.concat([W,L]);let B=W.indexOf(`\r
3
3
  \r
4
4
  `);if(B<0){if(W.length>16384)Y.destroy();return}if(Y.pause(),Y.off("data",F),B>16384||W.length>v.upload+16384)return Y.destroy();K(W,B).catch(()=>Y.destroy())};Y.on("data",F);async function K(L,B){let U=L.subarray(0,B).toString("latin1").split(`\r
5
5
  `),M=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(U.shift()??"");if(!M)throw Error("preview_request_invalid");M9(M[2]);let _=!1,q=0,D=[];for(let T of U){let k=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!k)throw Error("preview_header_invalid");if(k[1].toLowerCase()===b$){q++;let g=Buffer.from(k[2].trim());_=g.length===Z.length&&W4(g,Buffer.from(Z))}else if(k[1].toLowerCase()!=="host")D.push(T)}if(!_||q!==1||J||H.signal.aborted)throw Error("preview_connection_denied");let x=await $.connect(H.signal);if(J||H.signal.aborted)throw x.destroy(),Error("preview_closed");X.add(x),x.on("error",()=>Y.destroy()),x.once("close",()=>{X.delete(x),Y.destroy()}),Y.once("close",()=>x.destroy()),Y.setTimeout(0);let b=[`${M[1]} ${M[2]} HTTP/1.1`,`Host: 127.0.0.1:${x.remotePort}`,...D,"",""].join(`\r
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{yh as $}from"./vm-hands-entry-lite-1bvbhwbb.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
2
+ import{yh as $}from"./vm-hands-entry-lite-n0v0srqp.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
3
  export{O as uh,Z as vh,S as wh,k as xh};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./vm-hands-entry-lite-fraghb8k.js";import"./vm-hands-entry-lite-gqncr2j0.js";import"./vm-hands-entry-lite-sv6xwe0h.js";import{Kh as A}from"./vm-hands-entry-lite-7gh1rbn7.js";import{readFileSync as J}from"fs";var G=performance.now();delete process.env.BUN_BE_BUN;var q=(j,b={})=>console.log(JSON.stringify({stage:j,ms:Math.round(performance.now()),...b}));async function K(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:D}=await import("./vm-hands-op-runner-ej1c20a6.js");await D();return}q("parsed",{t0:Math.round(G)});let j="";try{j=J(3,"utf8")}catch{}q("fd3_read",{bytes:j.length});let b=null;if(j.trim())try{b=JSON.parse(j)}catch{b=null}if(!b||typeof b!=="object"||Array.isArray(b))q(j.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:B,runVmHands:C}=await import("./vm-hands-runtime-yyy4ad4z.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();
2
+ import"./vm-hands-entry-lite-fraghb8k.js";import"./vm-hands-entry-lite-gqncr2j0.js";import"./vm-hands-entry-lite-sv6xwe0h.js";import{Kh as A}from"./vm-hands-entry-lite-7gh1rbn7.js";import{readFileSync as J}from"fs";var G=performance.now();delete process.env.BUN_BE_BUN;var q=(j,b={})=>console.log(JSON.stringify({stage:j,ms:Math.round(performance.now()),...b}));async function K(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:D}=await import("./vm-hands-op-runner-v941qg9f.js");await D();return}q("parsed",{t0:Math.round(G)});let j="";try{j=J(3,"utf8")}catch{}q("fd3_read",{bytes:j.length});let b=null;if(j.trim())try{b=JSON.parse(j)}catch{b=null}if(!b||typeof b!=="object"||Array.isArray(b))q(j.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:B,runVmHands:C}=await import("./vm-hands-runtime-emtd6z5q.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ka as s,ob as i,qa as t,sb as n}from"./vm-hands-entry-lite-htn1genx.js";import"./vm-hands-entry-lite-c2nrar90.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-gqncr2j0.js";import"./vm-hands-entry-lite-sv6xwe0h.js";import"./vm-hands-entry-lite-bfwf82rw.js";import"./vm-hands-entry-lite-ptmqg51y.js";import"./vm-hands-entry-lite-s5qn1k80.js";import"./vm-hands-entry-lite-9pmag2qk.js";import"./vm-hands-entry-lite-84aq8d12.js";import"./vm-hands-entry-lite-1bvbhwbb.js";import"./vm-hands-entry-lite-anaydk9m.js";import"./vm-hands-entry-lite-ffg7rf02.js";import"./vm-hands-entry-lite-7gh1rbn7.js";import{spawn as Zq}from"child_process";import{chmodSync as $q,chownSync as zq,existsSync as Qq,lstatSync as S,mkdirSync as Wq,mkdtempSync as Gq,readdirSync as m,readFileSync as F,realpathSync as Jq,rmSync as Yq,writeFileSync as u}from"fs";import{join as U}from"path";var o="/sys/fs/cgroup/reason-payload",k="vm-hands",Kq="/run/ara-srt/fallbacks.jsonl",E="/reason-person",Bq=5000,bq=1e4,c="__VM_HANDS_PROOF_DIR__",Tq="__VM_HANDS_PROBE_NONCE__";class L extends Error{code;constructor(q,W){super(W);this.code=q}}var Lq=30000,e=(q)=>`'${q.replaceAll("'","'\\''")}'`;function xq(q){let W=q.cgroup??o,J=q.init.layout.payload_uid,X=q.log??(()=>{}),Q=null,Z=0,T=()=>{try{let z=F("/run/ara-srt/starts.jsonl","utf8"),$=z.slice(Z>z.length?0:Z).split(`
2
+ import{Ka as s,ob as i,qa as t,sb as n}from"./vm-hands-entry-lite-t678ape1.js";import"./vm-hands-entry-lite-c2nrar90.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-gqncr2j0.js";import"./vm-hands-entry-lite-sv6xwe0h.js";import"./vm-hands-entry-lite-bfwf82rw.js";import"./vm-hands-entry-lite-ptmqg51y.js";import"./vm-hands-entry-lite-s5qn1k80.js";import"./vm-hands-entry-lite-9pmag2qk.js";import"./vm-hands-entry-lite-84aq8d12.js";import"./vm-hands-entry-lite-n0v0srqp.js";import"./vm-hands-entry-lite-anaydk9m.js";import"./vm-hands-entry-lite-ffg7rf02.js";import"./vm-hands-entry-lite-7gh1rbn7.js";import{spawn as Zq}from"child_process";import{chmodSync as $q,chownSync as zq,existsSync as Qq,lstatSync as S,mkdirSync as Wq,mkdtempSync as Gq,readdirSync as m,readFileSync as F,realpathSync as Jq,rmSync as Yq,writeFileSync as u}from"fs";import{join as U}from"path";var o="/sys/fs/cgroup/reason-payload",k="vm-hands",Kq="/run/ara-srt/fallbacks.jsonl",E="/reason-person",Bq=5000,bq=1e4,c="__VM_HANDS_PROOF_DIR__",Tq="__VM_HANDS_PROBE_NONCE__";class L extends Error{code;constructor(q,W){super(W);this.code=q}}var Lq=30000,e=(q)=>`'${q.replaceAll("'","'\\''")}'`;function xq(q){let W=q.cgroup??o,J=q.init.layout.payload_uid,X=q.log??(()=>{}),Q=null,Z=0,T=()=>{try{let z=F("/run/ara-srt/starts.jsonl","utf8"),$=z.slice(Z>z.length?0:Z).split(`
3
3
  `).filter(Boolean);Z=z.length;let G=$.map((Y)=>{try{return Number(JSON.parse(Y).elapsed_ms)||0}catch{return 0}});if(G.length)X("vm_hands.srt_server_starts",{count:G.length,elapsed_ms:G.slice(0,8)})}catch{}},j=null,D=!1,C=q.srtCgroup??"/sys/fs/cgroup/reason-srt",R=()=>{j??=Iq()},N=0,A=()=>{try{let z=F(Kq,"utf8"),$=z.slice(N>z.length?0:N);N=z.length;let G=$.split(`
4
4
  `).filter(Boolean).slice(0,1000);if(!G.length)return null;let Y={},K=0;for(let b of G)try{let M=JSON.parse(b),I=typeof M.code==="string"&&/^[a-z_]{1,40}$/.test(M.code)?M.code:"other";if(Y[I]=(Y[I]??0)+1,typeof M.elapsed_ms==="number")K=Math.max(K,M.elapsed_ms)}catch{Y.unparsed=(Y.unparsed??0)+1}return X("vm_hands.srt_fallbacks",{count:G.length,codes:Y,max_elapsed_ms:K}),{count:G.length,codes:Y,max_elapsed_ms:K}}catch{return null}},v=!1,qq=(z,$,G)=>{if(v)throw Error("vm_hands_pool_held");return H(z,$,G)},H=(z,$,G)=>Zq("/bin/sh",["-c",`echo $$ > ${e(U(W,k,"cgroup.procs"))} || exit 125; exec "$@"`,"vm-hands-join",z,...$],G),Xq=(z)=>H(z.command,z.args,z.options),P=q.prespawn?s({spawnProcess:qq,...q.relayDependencies?.sourceEntrypoint?{sourceEntrypoint:q.relayDependencies.sourceEntrypoint}:{},log:(z,$)=>X(z,$??{})}):null;P?.arm();let h=P?setInterval(()=>{if(!Q)P.arm()},Lq):null;h?.unref?.();async function y(){let z=Q;if(Q=null,!z)return;z.abort.abort(),await z.done}return{async startExecutor(z){if(R(),D=!0,!z.claim)throw new L("vm_hands_bind_invalid","an executor needs the claim it serves");await y();let $=z.claim,G=$.owner;if(!G||typeof G.device_id!=="string"||typeof $.root_id!=="string")throw new L("vm_hands_bind_invalid","claim without its owner Device or root");let Y=new AbortController,K,b,M=new Promise((B,O)=>{K=B,b=O}),I,w=new Promise((B)=>{I=B}),g=n({headless:!0,hostExecution:!0,runtimeDirectory:q.runtimeDirectory,deviceIdentity:{deviceId:G.device_id,rootId:$.root_id,apiOrigin:q.apiOrigin},claimOwner:$.owner,root:q.root,runId:$.run_id,operationId:$.operation_id,attemptId:$.attempt_id,payload:Object.fromEntries(Object.entries($.payload).filter(([B])=>!B.startsWith("vm_hands_"))),signal:Y.signal,emitEvent:async(B,O)=>{if(B==="hands.ready"){K(O);return}if(B==="hands.started"||B==="hands.stopped"||B==="hands.failed")return;await q.forward(B,O)}},{...q.relayDependencies,spawnWorker:Xq,...P?{takePrespawnedWorker:P.take,adoptSpawnedWorker:P.adopt}:{}}).then(()=>{I("executor_stopped")},(B)=>{let O=B&&typeof B==="object"&&"code"in B?String(B.code):"executor_failed";b(new L(O,B instanceof Error?B.message:String(B))),I(O)}).finally(()=>b(new L("vm_hands_executor_exited","executor ended before it was ready")));Q={abort:Y,done:g,exited:w,operationId:$.operation_id,runId:$.run_id,expiresAtMs:Date.parse(String($.payload.expires_at??""))||0};let V=await M,x=V.executor_launch_id;if(typeof x!=="string")throw new L("vm_hands_bind_failed","executor ready without a launch id");return{launchId:x,readyData:V,applied:{hands_confinement:typeof $.payload.hands_confinement==="string"?$.payload.hands_confinement:null,browser_egress:$.payload.browser_egress??null}}},takeSrtFallbacks:A,executorExited(){return Q?Q.exited:new Promise(()=>{})},async killAndVerifyPayload(){v=!0;let z=Aq();try{await Dq(),await y().catch(()=>{return}),T();let $=Date.now()+Bq;await p(W,$,"payload");let G=(D||q.srtWarmLate?.()===!0)&&Qq(U(C,"cgroup.events"));if(G)await p(C,$,"srt");let Y=Cq(J).filter((K)=>!l(K,E));if(j!==null){let K=Mq(j).filter((b)=>b!==process.pid&&!l(b,E));if(K.length)throw X("vm_hands.kill_strays",{strays:K.slice(0,16).map((b)=>{let M="?",I="?";try{M=F(`/proc/${b}/comm`,"utf8").trim().slice(0,32)}catch{}try{I=(F(`/proc/${b}/cgroup`,"utf8").split(`
5
5
  `).find((w)=>w.startsWith("0::"))??"").slice(3,80)}catch{}return{pid:b,comm:M,cgroup:I}})}),new L("vm_hands_kill_unverified",`${K.length} process(es) the run started survived it`);j=null}if(D=!1,G)q.onSrtReset?.();if(Y.length)throw X("vm_hands.kill_survivors",{pids:Y.slice(0,16)}),new L("vm_hands_kill_unverified",`${Y.length} payload-uid process(es) outside the payload cgroup`)}finally{v=!1,z()}if(P)setTimeout(()=>{if(!Q)P.arm()},100).unref?.()},async runProbe({nonce:z,script:$}){if(R(),!$.includes(c))throw new L("vm_hands_probe_failed","probe names no proof directory");let G=q.proofParent??"/tmp/reason-vm-hands-proof";Wq(G,{mode:457,recursive:!0});let Y=S(G);if(Y.isSymbolicLink()||!Y.isDirectory()||Y.uid!==(process.getuid?.()??-1)||(Y.mode&4095)!==457)throw new L("vm_hands_probe_failed","proof parent is not root's 0711 directory");let K=Gq(U(G,"p-")),b=!1;try{if(!/^[A-Za-z0-9/._-]+$/.test(K)||!/^[A-Za-z0-9_-]{1,128}$/.test(z))throw new L("vm_hands_probe_failed","proof directory path or nonce");zq(K,J,J),$q(K,448);let M=S(K).ino,I=H("/bin/bash",["-c",$.replaceAll(c,K).replaceAll(Tq,z)],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:["ignore","pipe","ignore"]}),w="";I.stdout?.on("data",(V)=>{if(w.length<16384)w+=V.toString("utf8").slice(0,16384-w.length)});let g=await new Promise((V)=>{let x=setTimeout(()=>{b=!0,I.kill("SIGKILL"),V(124)},bq);I.once("error",()=>{clearTimeout(x),V(127)}),I.once("close",(B)=>{clearTimeout(x),V(B??1)})});return X("vm_hands.probe",{nonce_len:z.length,exit_code:g}),{exitCode:g,markers:w,proofDirInode:M}}finally{if(!b)Yq(K,{recursive:!0,force:!0})}},restatLayout(){let{session_root:z,alias:$}=q.init.layout,G="invalid";try{i(z),G="0:0:755"}catch{}let Y=!1,K=-1;try{let b=S($);K=b.uid,Y=G==="0:0:755"&&$===U(z,"repo")&&!b.isSymbolicLink()&&b.isDirectory()&&Jq($)===$&&b.uid===J}catch{}return{root_mode:G,alias_ok:Y,owner_uid:K}},installEnvironment(z){let $=Q;if(!$)throw new L("environment_unavailable","no executor owns an environment");return t({root:q.root,operationId:$.operationId,payload:z}).installed_revision},async stop(){if(h)clearInterval(h);P?.close(),await y()}}}function l(q,W,J="/proc"){try{let Q=F(U(J,String(q),"cgroup"),"utf8").split(`