@reason-machines/cli-linux-arm64-musl 0.2.281 → 0.2.283
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.
- package/bin/ara +1 -1
- package/bin/vm-hands/connect-cli-55e1yksk.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-92914wyp.js → custom-endpoint-device-7kd3qh6r.js} +1 -1
- package/bin/vm-hands/desktop-account-5kmddfvt.js +2 -0
- package/bin/vm-hands/{device-workspace-zk5xwd10.js → device-workspace-te28d7t5.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-da93x0qx.js → hands-worker-source-6ts5hhas.js} +1 -1
- package/bin/vm-hands/{index-w9nq2f0p.js → index-9aw1gjs5.js} +1 -1
- package/bin/vm-hands/local-automation-04rec2qb.js +2 -0
- package/bin/vm-hands/local-capabilities-2bd5ev5m.js +2 -0
- package/bin/vm-hands/local-desktop-users-nxyv3mk1.js +2 -0
- package/bin/vm-hands/local-display-mac-rp51a8w7.js +2 -0
- package/bin/vm-hands/local-display-session-zvj3ntsc.js +2 -0
- package/bin/vm-hands/{network-contract-41qanjhp.js → network-contract-wkc0ycet.js} +1 -1
- package/bin/vm-hands/package-56yg8k4a.js +2 -0
- package/bin/vm-hands/permissions-qnq69hfd.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-51gs8j7v.js → reason-hands-protocol-2gkb9qeb.js} +1 -1
- package/bin/vm-hands/{status-ycqjx7at.js → status-mbjv1h54.js} +2 -2
- package/bin/vm-hands/version-vs0sn7wr.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-zjnq10yb.js → vm-hands-entry-lite-0etm5tzc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-t678ape1.js → vm-hands-entry-lite-2yne3ped.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fraghb8k.js → vm-hands-entry-lite-4fnbmmp6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ptmqg51y.js → vm-hands-entry-lite-53jm8bj7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-s2xydt0n.js → vm-hands-entry-lite-5vrdj7jm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rs7g2egs.js → vm-hands-entry-lite-7s23wnph.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-c2nrar90.js → vm-hands-entry-lite-8kqg77ym.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-n0v0srqp.js → vm-hands-entry-lite-9jdxjw46.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-bjhw87nc.js +343 -0
- package/bin/vm-hands/{vm-hands-entry-lite-bm9x8vng.js → vm-hands-entry-lite-d2wgjdc5.js} +24 -23
- package/bin/vm-hands/{vm-hands-entry-lite-65pbrs1x.js → vm-hands-entry-lite-h2xpqaxn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bfwf82rw.js → vm-hands-entry-lite-k1wbh9dq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-84aq8d12.js → vm-hands-entry-lite-kxbpf40y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sv6xwe0h.js → vm-hands-entry-lite-m5pmd2cz.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-s5qn1k80.js → vm-hands-entry-lite-qbk0wxrz.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-d2xzrjx2.js → vm-hands-entry-lite-rnykqcys.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-7gh1rbn7.js → vm-hands-entry-lite-ss2w3h3d.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-9pmag2qk.js → vm-hands-entry-lite-vvmq0mtv.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ffg7rf02.js → vm-hands-entry-lite-wffqkcjq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1hwdab4e.js → vm-hands-entry-lite-whcnpjdx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rwdevjb0.js → vm-hands-entry-lite-y3k1pyx7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-anaydk9m.js → vm-hands-entry-lite-y9k070mt.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-bwt3y6wz.js → vm-hands-entry-lite-yf8h8gmh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-gqncr2j0.js → vm-hands-entry-lite-yh7n4svm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-k4c504n7.js → vm-hands-entry-lite-yvmzze06.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-samg5ahn.js → vm-hands-executor-h8hm44fp.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-v941qg9f.js → vm-hands-op-runner-e2p1qwmv.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-emtd6z5q.js → vm-hands-runtime-pdvbqbpj.js} +3 -3
- package/bin/vm-hands/worker-sandbox-4c9302zr.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-sfr2y6mq.js +0 -2
- package/bin/vm-hands/desktop-account-vsrtgkk9.js +0 -2
- package/bin/vm-hands/local-automation-99wn9bh2.js +0 -2
- package/bin/vm-hands/local-capabilities-7thv11wy.js +0 -2
- package/bin/vm-hands/local-desktop-users-3j79jbyp.js +0 -2
- package/bin/vm-hands/local-display-mac-j1v3mcgx.js +0 -2
- package/bin/vm-hands/local-display-session-mrf9pm28.js +0 -2
- package/bin/vm-hands/package-rx9y4bwe.js +0 -2
- package/bin/vm-hands/permissions-p9p6z62j.js +0 -2
- package/bin/vm-hands/version-xjrgafqj.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-c0whrdtr.js +0 -343
- package/bin/vm-hands/worker-sandbox-nnce49w0.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Zg as J}from"./vm-hands-entry-lite-vvmq0mtv.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
|
|
3
3
|
`)){let j=I.split(":");if(j.length<7||Number(j[2])!==q||!/^\d+$/.test(j[2])||!/^\d+$/.test(j[3]))continue;let x=j[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(j[0])||!M(x)||Q(x)!==x||x==="/")return null;return{username:j[0],uid:q,gid:Number(j[3]),home:x}}return null}function b(q={}){let B="value"in q?q.value:process.env[W];if(G=null,B===void 0||B==="")return null;let I=q.platform??process.platform,j="euid"in q?q.euid:process.geteuid?.(),x=/^[1-9]\d{0,9}$/.test(B)?Number(B):NaN,C=I==="linux"&&j===0&&Number.isSafeInteger(x)?X(x,(q.passwd??(()=>L("/etc/passwd","utf8")))()):null;if(!C||C.gid===0)throw Error("worker_desktop_user_invalid");return G=C,C}function k(){return G}function y(){return G?.home??J()}
|
|
4
|
-
export{W as
|
|
4
|
+
export{W as Ug,X as Vg,b as Wg,k as Xg,y as Yg};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Og as wz,Pg as Nz}from"./vm-hands-entry-lite-5vrdj7jm.js";import{Zg as N}from"./vm-hands-entry-lite-vvmq0mtv.js";import{wh as A}from"./vm-hands-entry-lite-0etm5tzc.js";import{Mh as Fz}from"./vm-hands-entry-lite-ss2w3h3d.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-
|
|
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-mbjv1h54.js")).connectionMacState(),open:(z)=>{iz("/usr/bin/open",z,{stdio:"ignore",timeout:1e4})},tile:Xz,restartConnection:async()=>(await import("./connect-cli-55e1yksk.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}
|
|
@@ -40,4 +40,4 @@ ${Dz}`),1;if($.command==="help")return Z.stdout.write(Dz),0;let j=J.platform??pr
|
|
|
40
40
|
`:`Reason permissions: macOS privacy permissions do not apply on this computer.
|
|
41
41
|
`),0;let q=J.host??Pz();if($.command==="allow")return JJ($.ids,{io:Z,wait:!0,host:q});let Q=await vz(q);return Z.stdout.write($.json?`${JSON.stringify({platform:j,applicable:!0,...Q},null,2)}
|
|
42
42
|
`:zJ(Q)),0}
|
|
43
|
-
export{a as
|
|
43
|
+
export{a as gg,k as hg,hz as ig,b as jg,Kz as kg,dz as lg,mz as mg,VJ as ng,XJ as og,Xz as pg,Dz as qg,h as rg,Bz as sg,ez as tg,vz as ug,MJ as vg,zJ as wg,JJ as xg,ZJ as yg,OJ as zg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=import.meta.require;
|
|
3
|
-
export{s as
|
|
3
|
+
export{s as Jh,t as Kh,u as Lh,v as Mh};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{Q as
|
|
2
|
+
import{gh as X,ih as Y,kh as Z}from"./vm-hands-entry-lite-kxbpf40y.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
|
|
3
|
+
export{Q as Zg,O as _g,_ as $g,b as ah,g as bh};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ae as j}from"./vm-hands-entry-lite-m5pmd2cz.js";var p="inference.custom.v1",R=32768,$=67108864,x=16384,A=204800,z=600000,P=["content-type","anthropic-version","user-agent"],W=j.enum(["openai-completions","openai-responses","anthropic-messages"]),U=new Set(P),V=j.record(j.string(),j.string().max(2048)).refine((w)=>Object.keys(w).every((F)=>U.has(F))&&Object.values(w).every((F)=>!/[\r\n\0]/.test(F)),"Only non-secret custom endpoint request headers are permitted");function J(w){try{let F=new URL(w);return["http:","https:"].includes(F.protocol)&&!F.username&&!F.password&&!F.search&&!F.hash?F:null}catch{return null}}function X(w,F){let G=J(w.baseUrl),K=J(F.baseUrl),H=J(w.url);if(!G||!K||!H||w.method!=="POST"||F.execution!=="device")return!1;let L=(Q)=>Q.origin+Q.pathname.replace(/\/+$/,"");if(L(G)!==L(K)||H.origin!==G.origin)return!1;let Z=F.api==="openai-completions"?"/chat/completions":F.api==="openai-responses"?"/responses":"/v1/messages";return H.pathname===G.pathname.replace(/\/+$/,"")+Z}var B=j.object({baseUrl:j.string().max(2048),url:j.string().max(4096),method:j.literal("POST"),body:j.string().refine((w)=>new TextEncoder().encode(w).byteLength<=A).optional(),headers:V,credentialOrganizationId:j.string().uuid(),accountKey:j.string().min(1).max(256).optional()}).strict().refine((w)=>W.options.some((F)=>X(w,{baseUrl:w.baseUrl,api:F,execution:"device"})),"Invalid custom endpoint inference URL"),C=j.object({status:j.number().int().min(200).max(599),statusText:j.string().max(256).refine((w)=>!/[\r\n\0]/.test(w)),headers:j.record(j.string(),j.string().max(4096)).refine((w)=>Object.keys(w).every((F)=>["content-type","retry-after","x-request-id","request-id"].includes(F))&&Object.values(w).every((F)=>!/[\r\n\0]/.test(F)))}).strict(),I=j.union([j.object({eof:j.literal(!0)}).strict(),j.object({eof:j.literal(!1),data:j.string().max(Math.ceil(R/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((w)=>w.length>0&&w.length*3/4-(w.endsWith("==")?2:w.endsWith("=")?1:0)<=R)}).strict()]),M=j.object({bytes:j.number().int().min(0).max($),chunks:j.number().int().min(0).max(x)}).strict(),N=j.object({apiKey:j.string().min(1).max(16384).refine((w)=>!/[\r\n\0]/.test(w)),api:W}).strict();
|
|
3
3
|
export{p as _b,R as $b,$ as ac,x as bc,A as cc,z as dc,P as ec,X as fc,B as gc,C as hc,I as ic,M as jc,N as kc};
|
|
@@ -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-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(`
|
|
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-2yne3ped.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-8kqg77ym.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-h2xpqaxn.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-whcnpjdx.js";import{Bc as r1,Ec as H7,Nc as D7}from"./vm-hands-entry-lite-d2wgjdc5.js";import{$c as u,$d as g8,Ad as L6,Cd as O6,Dd as j6,Ed as I6,Fd as A6,Gd as T6,Ld as D8,Md as M8,Nd as w8,Oc as w1,Od as L8,Pc as Q2,Pd as O8,Qc as e5,Qd as j8,Rc as I3,Sc as r3,Sd as I8,Tc as a3,Td as A8,Uc as M0,Ud as T8,Vd as _8,Wd as R8,Xd as P8,Yc as N0,Yd as z8,Zd as q8,_d as E8,ad as E1,dd as H8,fd as g1,hd as $6,id as J6,jd as Z6,kd as Q6,ld as K6,md as B6,nd as V6,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as w6}from"./vm-hands-entry-lite-yh7n4svm.js";import{ae as V}from"./vm-hands-entry-lite-m5pmd2cz.js";import{Ae as l1,be as W7,ce as Y7,de as F7,ee as N7,fe as C7,le as p5,pe as Q5,qe as T5,we as M7,ze as K5}from"./vm-hands-entry-lite-7s23wnph.js";import{Ze as j4,ef as c6}from"./vm-hands-entry-lite-k1wbh9dq.js";import{jf as M3,wf as g6}from"./vm-hands-entry-lite-53jm8bj7.js";import{Ag as Z7,Bg as Q7,Cg as K7,Dg as B7,Fg as V7,Gg as G7,Ig as U7,Jg as X7}from"./vm-hands-entry-lite-5vrdj7jm.js";import{Xg as n1}from"./vm-hands-entry-lite-qbk0wxrz.js";import{$g as H4,Zg as j1,_g as k6,ah as D4}from"./vm-hands-entry-lite-vvmq0mtv.js";import{ch as D3,eh as $1,kh as K8,lh as J4}from"./vm-hands-entry-lite-kxbpf40y.js";import{Ih as H}from"./vm-hands-entry-lite-wffqkcjq.js";import{Mh as a4}from"./vm-hands-entry-lite-ss2w3h3d.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)}))
|
|
@@ -23,7 +23,7 @@ Content-Length: 0\r
|
|
|
23
23
|
\r
|
|
24
24
|
`),E4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{B.once("error",W),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as O2,randomUUID as f9}from"crypto";import{closeSync as t0,constants as s,fchownSync as b9,fstatSync as z0,fsyncSync as x9,linkSync as y9,mkdirSync as h9,openSync as i4,readSync as o4,unlinkSync as m9,writeSync as v9}from"fs";import{platform as n4}from"os";import{getSystemErrorName as p9}from"util";var x4={type:"string",format:"uuid"},v4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,A1={type:"string",minLength:1,maxLength:4096,pattern:v4},H2=V.string().min(1).max(4096).regex(new RegExp(v4)),T1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},_1={device_id:x4,root_id:x4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},fK={read:{schema:V.object({...T1,path:H2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{..._1,path:A1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...T1,path:H2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{..._1,path:A1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...T1,command:V.string().min(1).max(16000),cwd:H2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{..._1,command:{type:"string",minLength:1,maxLength:16000},cwd:A1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},W0=1073741824,i0=600000,y4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,p4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${y4}(?:/${y4})*(?![\s\S])`,u4=new RegExp(p4);function d4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&u4.test($)}var D2=V.string().min(1).max(4096).regex(u4),M2={...A1,pattern:p4},l4=V.string().regex(/^[a-f0-9]{64}$/),s4=V.object({kind:V.literal("workspace"),path:D2}).strict(),g9=V.discriminatedUnion("kind",[s4,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:l4}).strict()]),R1=1,o0="cloud_workspace_id",w2="cloud_workspace",L2=1,S9=V.discriminatedUnion("kind",[s4,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(W0),sha256:l4}).strict()]),c4=V.object({source_version:V.literal(R1),source:S9,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[o0]:V.string().min(1).max(160).optional()}).strict(),bK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(R1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var h4=V.object({...T1,timeout_ms:V.number().int().min(1000).max(i0).optional(),source_path:D2,destination_path:D2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),m4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{..._1,timeout_ms:{type:"integer",minimum:1000,maximum:i0},source_path:M2,destination_path:M2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},k9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:M2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},xK=V.union([h4,h4.omit({source_path:!0}).extend({source:g9}).strict()]),yK={...m4,required:["device_id","root_id","destination_path"],properties:{...m4.properties,source:k9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var j2=65536;function p($){throw new H($,$)}function z1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function P1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return p(Z)}function u9($,J,Z){let Q;switch(z1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return P1($,J,Q)}function d9($){if(typeof $!=="string"||$.length>16384)return p("transfer_url_invalid");let J;try{J=new URL($)}catch{return p("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return p("transfer_url_invalid");return J.href}async function l9(){if(n4()==="linux")return{open:(U,W,Y,X=384)=>i4(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>h9(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>y9(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>m9(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(n4()!=="darwin")return p("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),K=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),B=K.symbols.__error();if(B===null)return K.close(),p("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=p9(-Q.i32(B));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(K.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(K.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(K.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(K.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>K.close()}}function t4($,J){let Z=z0($),Q=z0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)b9(J,Z.uid,Z.gid)}function s9($,J,Z,Q){if(!d4(Z))return p("transfer_path_invalid");let K=Z.split("/"),B=i4(J,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW);try{for(let G of K.slice(0,-1)){let U;try{U=$.open(B,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW)}catch(W){if(!Q||z1(W)!=="ENOENT")throw W;try{$.mkdir(B,G)}catch(Y){if(z1(Y)!=="EEXIST")throw Y}U=$.open(B,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW),t4(B,U)}t0(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw t0(B),G}}function r4($,J){let Z=z0($,{bigint:!0});if(!Z.isFile()||Z.size>W0)return p("transfer_file_invalid");let Q=O2("sha256"),K=Buffer.alloc(j2),B=0;while(!0){J.throwIfAborted();let U=o4($,K,0,K.length,B);if(!U)break;if(B+=U,B>W0)return p("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=z0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return p("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=d9($.payload.url),Z=await l9(),Q,K,B;try{if(Q=s9(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);let C=z0(K,{bigint:!0});if(!C.isFile()||C.size>W0)return p("transfer_file_invalid");let N=O2("sha256"),D=0,L=K,M,I=new ReadableStream({pull(j){try{$.signal.throwIfAborted();let R=Buffer.alloc(j2),A=o4(L,R,0,R.length,D);if(!A){j.close();return}if(D+=A,D>C.size)return p("transfer_source_changed");N.update(R.subarray(0,A)),j.enqueue(R.subarray(0,A))}catch(R){throw M=R,R}}});try{let j=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:I,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(C.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!j.ok)return p("transfer_upload_failed");await j.body?.cancel()}catch(j){if(M!==void 0)throw M;return P1(j,$.signal,"transfer_upload_failed")}let O=z0(K,{bigint:!0});if(BigInt(D)!==C.size||O.size!==C.size||O.mtimeNs!==C.mtimeNs||O.ctimeNs!==C.ctimeNs)return p("transfer_source_changed");let k=N.digest("hex"),E=r4(K,$.signal);if(E.size_bytes!==D||E.sha256!==k)return p("transfer_source_changed");return{size_bytes:D,sha256:k,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>W0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return p("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK)}catch(C){if(z1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=r4(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{t0(W)}return p("transfer_destination_exists")}B=`.reason-copy-${f9()}`,K=Z.open(Q.fd,B,s.O_CREAT|s.O_EXCL|s.O_WRONLY|s.O_NOFOLLOW,384),t4(Q.fd,K);let Y;try{let C=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!C.ok||!C.body)return p("transfer_download_failed");Y=C.body.getReader()}catch(C){return P1(C,$.signal,"transfer_download_failed")}let X=O2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((N)=>P1(N,$.signal,"transfer_download_failed"));if(C.done)break;if(F+=C.value.length,F>G)return p("transfer_size_mismatch");X.update(C.value);for(let N=0;N<C.value.length;)$.signal.throwIfAborted(),N+=v9(K,C.value,N,Math.min(j2,C.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return p("transfer_hash_mismatch");return x9(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)t0(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}t0(Q.fd)}}finally{Z.close()}}}}catch(J){return u9(J,$.signal,$.direction)}}import{spawn as n9}from"child_process";import{mkdtempSync as r9,rmSync as a9,writeFileSync as i9}from"fs";import{constants as o9,platform as t9,tmpdir as e9}from"os";import{join as Z8}from"path";import{gunzipSync as c9,gzipSync as nK}from"zlib";var $8=900000,aK=$8+60000,e0=49152,e4=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),J8=V.object({version:V.literal(1),script_gzip:e4(163840),stdin_gzip:e4(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max($8)}).strict(),I2=V.string().max(e0+256),iK=V.object({exit_code:V.number().int().min(0).max(255),stdout:I2,stderr:I2,combined:I2.optional()}).strict();function A2($){return c9(Buffer.from($,"base64")).toString("utf8")}var $$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",J$=["RUSTUP_HOME","TZ","LC_ALL"],Z$=2000,Q$=100;function _2(){return t9()==="linux"&&process.geteuid?.()===0}function T2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
25
25
|
[reason: ${G} bytes of output omitted]
|
|
26
|
-
`:"")+K.toString("utf8")}}}async function Q8($,J){if(!_2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=J8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=A2(Q.script_gzip),B=A2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r9(Z8(e9(),"reason-workspace-setup-"));try{let U=Z8(G,"setup.sh");i9(U,K,{mode:384});let W={PATH:$$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let E of J$)if(process.env[E])W[E]=process.env[E];Object.assign(W,Q.env);let Y=n9("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=T2(e0),F=T2(e0),C=T2(e0);Y.stdout.on("data",(E)=>{X.push(E),C.push(E)}),Y.stderr.on("data",(E)=>{F.push(E),C.push(E)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let N=(E)=>{try{if(Y.pid)process.kill(-Y.pid,E)}catch{}},D=!1,L,M=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),Z$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((E,j)=>{Y.once("error",()=>j(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(R,A)=>E({code:R,signal:A}))}).finally(()=>{clearTimeout(I),clearTimeout(L),J.removeEventListener("abort",M)});await new Promise((E)=>{let j=setTimeout(E,Q$);Y.once("close",()=>{clearTimeout(j),E()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let k=D?124:O.signal?128+(o9.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,k),stdout:X.text(),stderr:F.text(),...k!==0?{combined:C.text()}:{}}}finally{a9(G,{recursive:!0,force:!0})}}import{chmodSync as K$,mkdtempSync as B$,realpathSync as G8,rmSync as V$}from"fs";import{tmpdir as G$}from"os";import{dirname as U$,join as R2,sep as X$}from"path";function P2($){return V8($,B8($)!==null).repoPath}function U8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[$1,void 0].map((K)=>U$(K8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=G8(R2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${X$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function X8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=P2($.runtimeRoot);if(w0(Q)||w0(R2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=B$(R2(G$(),`reason-cloud-copy-${process.pid}-`));try{K$(Z,448);let Q=G8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{V$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as w7,existsSync as G0,fstatSync as L7,lstatSync as O7,mkdirSync as mZ,mkdtempSync as j7,openSync as I7,readSync as vZ,realpathSync as J0,rmSync as A7,statSync as N1,writeSync as pZ}from"fs";import{homedir as W1,platform as d,tmpdir as T7}from"os";import{dirname as Y1,isAbsolute as uZ,join as T3,relative as w3,resolve as dZ,sep as lZ}from"path";import{spawn as sZ}from"child_process";import{createHash as C$,randomBytes as H$}from"crypto";var z2=30000,W$=1800000,Y$=5000,q1=30000,F$=g1+15000,W8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,N$=[/^\/app\/local-runtime\/operations\/claim$/,W8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(N$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},F$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(Y$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(W$,z2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(E1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+z2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!W8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(z2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var g2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function IB($,J={}){let Z=D$($),Q=J.rootPathsSupported===!0?D1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function D$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}function M$($){return $===408||$===429||$===500||$===502||$===503||$===504}function w$($){if($ instanceof Y0)return!1;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function L$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function O$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function AB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function Y8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function F8($){return C$("sha256").update($??"").digest("hex")}function j$($){return D8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function N8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var I$=20000,A$=1e4,C8=[2000,4000];class E2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class T${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=M8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J){let Z=this.proofOptions.challengeAttemptTimeoutsMs??C8;for(let Q of Z)try{return await this.challengeAttempt($,J,Q)}catch(K){if(J?.aborted||!(K instanceof E2))throw K}return await this.challengeAttempt($,J,null)}async challengeAttempt($,J,Z){let Q=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,B=K&&Z!==null?setTimeout(()=>K.abort(new E2(Z)),Z):null;try{let G=await this.fetchImpl(`${this.apiOrigin}${u.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:Q,signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return w8(await this.parseResponse(G))}catch(G){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw G}finally{if(B)clearTimeout(B)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=I$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,C8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B){let G=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=A$?B:null,U=!G&&K?await this.takeSpareChallenge(Z.deviceId):null,W=G??U??await this.challenge(Z.deviceId,Q);if(K)this.refillSpareChallenge(Z.deviceId);let Y=F8(J),X=this.signProof("POST",$,W.challenge,Y);return{"x-device-id":Z.deviceId,"x-device-timestamp":X.timestamp,"x-device-nonce":X.nonce,"x-device-challenge":W.challenge,"x-device-body-sha256":Y,"x-device-signature":X.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>H$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(j$({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!H8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",E1,Q,F8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&Y8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??O$,W=this.sessionFor($,J.device),Y;for(let X=0;X<G;X+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let C=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,J.signal,J.useSpareChallenge===!0&&X===0,X===0?J.issuedChallenge:void 0),N=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...C,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,signal:J.signal});return await this.parseResponse(N)}catch(F){if(Y=F,J.signal?.aborted)throw F;let C=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),N=F instanceof Y0&&M$(F.status),D=w$(F),L=J.transientRetryOwner!=="caller"&&(N||D);if((C||L)&&X+1<G){let M=C?0:L$(X,F,this.proofOptions.retryBaseDelayMs??500);if(M>0)await U(M,J.signal);continue}if(C&&X+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw Y??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(u.register,{authorization:$,body:J,signal:Z});return L8(Q)}async enroll($,J,Z,Q){let K=await this.request(u.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return O8(K)}async heartbeat($,J,Z,Q){let K=await this.request(u.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return j8(K)}async syncRoots($,J,Z){let Q=await this.request(u.rootsSync,{device:$,body:{roots:J},signal:Z});return I8(Q)}async identity($,J){let Z=await this.request(u.identity,{device:$,signal:J});return A8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(u.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return T8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(u.lifecycle,{device:$,body:J,signal:Z});R8(Q)}async localSubscription($,J,Z){return _8(await this.request(u.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(u.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(u.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(u.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!N8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(u.operationClaim,{device:$,body:Q(30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,g1))},signal:J.signal});if(B===null)return null;return P8(B,g2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(u.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return z8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!N8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(u.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return q8(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(Y8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(u.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return g8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-92914wyp.js");return Q.parse(await this.request(u.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(u.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return E8(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(u.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var _$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),J1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function S1($,J){if(_$.has($))return!1;if(J1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||J1.has($)))return!1;return!0}import{accessSync as R$,constants as P$,existsSync as z$,statSync as q$}from"fs";import{basename as E$,isAbsolute as g$}from"path";var Z1=["-lic"],S$="/bin/zsh",k$=new Set(["zsh","bash"]),S8=20000,S2=60000,f$=65536,b$=64,x$=8192,y$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),h$=["DYLD_","LD_"];function m$($){let J=$.toUpperCase();return y$.has(J)||h$.some((Z)=>J.startsWith(Z))}function k8($=process.env){return!0}function v$($){if(!g$($)||$.includes("\x00"))return!1;if(!k$.has(E$($)))return!1;try{if(!q$($).isFile())return!1;return R$($,P$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&v$(J))return J;return S$}function k2($=process.env){return k8($)&&z$(E0($))}function f2($=process.env){if(!k8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function b2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>f$)throw new H("invalid_payload","command is missing or too large.");return $}function x2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>b$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>x$)throw new H("invalid_payload","env entry is invalid or too large.");if(m$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function f8($){let J=$.processEnv??process.env;if(f2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=b2($.command),Q=E0(J),{forwarded:K,ignored:B}=x2($.requestEnv),G=await $.spawn(Q,[...Z1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...Z1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function b8($=process.env){return{transport:"shell",shell:`${E0($)} ${Z1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:S2}}import{readFile as p$,readdir as u$,readlink as d$,realpath as l$}from"fs/promises";import{basename as s$,relative as c$,sep as n$}from"path";var L0="/proc",r$=250,x8=500,a$=50,i$=250,o$=1024,y8=4096,t$=1,e$=3,h8=9,$J="0A",JJ=/^socket:\[(\d+)\]$/,y2={readDirectory:($)=>u$($),readLink:($)=>d$($),readTextFile:($)=>p$($,"utf8"),realPath:($)=>l$($)};function v8($,J){return J===$||J.startsWith(`${$}${n$}`)}function ZJ($,J){return c$($,J)||"."}async function p8($){let J;try{J=await $.readDirectory(L0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function u8($,J){try{let Q=(await J.readTextFile(`${L0}/${$}/comm`)).slice(0,y8).split(`
|
|
26
|
+
`:"")+K.toString("utf8")}}}async function Q8($,J){if(!_2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=J8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=A2(Q.script_gzip),B=A2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r9(Z8(e9(),"reason-workspace-setup-"));try{let U=Z8(G,"setup.sh");i9(U,K,{mode:384});let W={PATH:$$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let E of J$)if(process.env[E])W[E]=process.env[E];Object.assign(W,Q.env);let Y=n9("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=T2(e0),F=T2(e0),C=T2(e0);Y.stdout.on("data",(E)=>{X.push(E),C.push(E)}),Y.stderr.on("data",(E)=>{F.push(E),C.push(E)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let N=(E)=>{try{if(Y.pid)process.kill(-Y.pid,E)}catch{}},D=!1,L,M=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),Z$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((E,j)=>{Y.once("error",()=>j(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(R,A)=>E({code:R,signal:A}))}).finally(()=>{clearTimeout(I),clearTimeout(L),J.removeEventListener("abort",M)});await new Promise((E)=>{let j=setTimeout(E,Q$);Y.once("close",()=>{clearTimeout(j),E()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let k=D?124:O.signal?128+(o9.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,k),stdout:X.text(),stderr:F.text(),...k!==0?{combined:C.text()}:{}}}finally{a9(G,{recursive:!0,force:!0})}}import{chmodSync as K$,mkdtempSync as B$,realpathSync as G8,rmSync as V$}from"fs";import{tmpdir as G$}from"os";import{dirname as U$,join as R2,sep as X$}from"path";function P2($){return V8($,B8($)!==null).repoPath}function U8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[$1,void 0].map((K)=>U$(K8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=G8(R2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${X$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function X8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=P2($.runtimeRoot);if(w0(Q)||w0(R2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=B$(R2(G$(),`reason-cloud-copy-${process.pid}-`));try{K$(Z,448);let Q=G8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{V$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as w7,existsSync as G0,fstatSync as L7,lstatSync as O7,mkdirSync as mZ,mkdtempSync as j7,openSync as I7,readSync as vZ,realpathSync as J0,rmSync as A7,statSync as N1,writeSync as pZ}from"fs";import{homedir as W1,platform as d,tmpdir as T7}from"os";import{dirname as Y1,isAbsolute as uZ,join as T3,relative as w3,resolve as dZ,sep as lZ}from"path";import{spawn as sZ}from"child_process";import{createHash as C$,randomBytes as H$}from"crypto";var z2=30000,W$=1800000,Y$=5000,q1=30000,F$=g1+15000,W8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,N$=[/^\/app\/local-runtime\/operations\/claim$/,W8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(N$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},F$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(Y$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(W$,z2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(E1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+z2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!W8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(z2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var g2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function IB($,J={}){let Z=D$($),Q=J.rootPathsSupported===!0?D1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function D$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}function M$($){return $===408||$===429||$===500||$===502||$===503||$===504}function w$($){if($ instanceof Y0)return!1;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function L$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function O$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function AB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function Y8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function F8($){return C$("sha256").update($??"").digest("hex")}function j$($){return D8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function N8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var I$=20000,A$=1e4,C8=[2000,4000];class E2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class T${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=M8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J){let Z=this.proofOptions.challengeAttemptTimeoutsMs??C8;for(let Q of Z)try{return await this.challengeAttempt($,J,Q)}catch(K){if(J?.aborted||!(K instanceof E2))throw K}return await this.challengeAttempt($,J,null)}async challengeAttempt($,J,Z){let Q=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,B=K&&Z!==null?setTimeout(()=>K.abort(new E2(Z)),Z):null;try{let G=await this.fetchImpl(`${this.apiOrigin}${u.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:Q,signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return w8(await this.parseResponse(G))}catch(G){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw G}finally{if(B)clearTimeout(B)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=I$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,C8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B){let G=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=A$?B:null,U=!G&&K?await this.takeSpareChallenge(Z.deviceId):null,W=G??U??await this.challenge(Z.deviceId,Q);if(K)this.refillSpareChallenge(Z.deviceId);let Y=F8(J),X=this.signProof("POST",$,W.challenge,Y);return{"x-device-id":Z.deviceId,"x-device-timestamp":X.timestamp,"x-device-nonce":X.nonce,"x-device-challenge":W.challenge,"x-device-body-sha256":Y,"x-device-signature":X.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>H$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(j$({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!H8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",E1,Q,F8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&Y8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??O$,W=this.sessionFor($,J.device),Y;for(let X=0;X<G;X+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let C=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,J.signal,J.useSpareChallenge===!0&&X===0,X===0?J.issuedChallenge:void 0),N=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...C,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,signal:J.signal});return await this.parseResponse(N)}catch(F){if(Y=F,J.signal?.aborted)throw F;let C=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),N=F instanceof Y0&&M$(F.status),D=w$(F),L=J.transientRetryOwner!=="caller"&&(N||D);if((C||L)&&X+1<G){let M=C?0:L$(X,F,this.proofOptions.retryBaseDelayMs??500);if(M>0)await U(M,J.signal);continue}if(C&&X+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw Y??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(u.register,{authorization:$,body:J,signal:Z});return L8(Q)}async enroll($,J,Z,Q){let K=await this.request(u.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return O8(K)}async heartbeat($,J,Z,Q){let K=await this.request(u.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return j8(K)}async syncRoots($,J,Z){let Q=await this.request(u.rootsSync,{device:$,body:{roots:J},signal:Z});return I8(Q)}async identity($,J){let Z=await this.request(u.identity,{device:$,signal:J});return A8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(u.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return T8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(u.lifecycle,{device:$,body:J,signal:Z});R8(Q)}async localSubscription($,J,Z){return _8(await this.request(u.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(u.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(u.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(u.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!N8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(u.operationClaim,{device:$,body:Q(30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,g1))},signal:J.signal});if(B===null)return null;return P8(B,g2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(u.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return z8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!N8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(u.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return q8(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(Y8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(u.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return g8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-7kd3qh6r.js");return Q.parse(await this.request(u.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(u.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return E8(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(u.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var _$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),J1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function S1($,J){if(_$.has($))return!1;if(J1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||J1.has($)))return!1;return!0}import{accessSync as R$,constants as P$,existsSync as z$,statSync as q$}from"fs";import{basename as E$,isAbsolute as g$}from"path";var Z1=["-lic"],S$="/bin/zsh",k$=new Set(["zsh","bash"]),S8=20000,S2=60000,f$=65536,b$=64,x$=8192,y$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),h$=["DYLD_","LD_"];function m$($){let J=$.toUpperCase();return y$.has(J)||h$.some((Z)=>J.startsWith(Z))}function k8($=process.env){return!0}function v$($){if(!g$($)||$.includes("\x00"))return!1;if(!k$.has(E$($)))return!1;try{if(!q$($).isFile())return!1;return R$($,P$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&v$(J))return J;return S$}function k2($=process.env){return k8($)&&z$(E0($))}function f2($=process.env){if(!k8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function b2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>f$)throw new H("invalid_payload","command is missing or too large.");return $}function x2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>b$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>x$)throw new H("invalid_payload","env entry is invalid or too large.");if(m$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function f8($){let J=$.processEnv??process.env;if(f2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=b2($.command),Q=E0(J),{forwarded:K,ignored:B}=x2($.requestEnv),G=await $.spawn(Q,[...Z1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...Z1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function b8($=process.env){return{transport:"shell",shell:`${E0($)} ${Z1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:S2}}import{readFile as p$,readdir as u$,readlink as d$,realpath as l$}from"fs/promises";import{basename as s$,relative as c$,sep as n$}from"path";var L0="/proc",r$=250,x8=500,a$=50,i$=250,o$=1024,y8=4096,t$=1,e$=3,h8=9,$J="0A",JJ=/^socket:\[(\d+)\]$/,y2={readDirectory:($)=>u$($),readLink:($)=>d$($),readTextFile:($)=>p$($,"utf8"),realPath:($)=>l$($)};function v8($,J){return J===$||J.startsWith(`${$}${n$}`)}function ZJ($,J){return c$($,J)||"."}async function p8($){let J;try{J=await $.readDirectory(L0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function u8($,J){try{let Q=(await J.readTextFile(`${L0}/${$}/comm`)).slice(0,y8).split(`
|
|
27
27
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${L0}/${$}/cmdline`)).slice(0,y8).split("\x00",1)[0]?.trim();return Q?s$(Q):null}catch{return null}}async function d8($,J=y2){let Z;try{Z=await J.readLink(`${L0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function l8($,J=y2){let Z=[];for(let Q of await p8(J)){if(Z.length>=r$)break;let K=await d8(Q,J);if(!K||!v8($,K))continue;Z.push({pid:Q,command:await u8(Q,J),cwd:ZJ($,K)})}return{processes:Z}}function m8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function QJ($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(K<0)K=W;continue}if(K>=0){let Y=W-K;if(Y>Q)Z=K,Q=Y;K=-1}}let B=J.map((W)=>W.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function KJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=m8($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...m8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${QJ(Z)}]:${J}`}return null}function BJ($,J){let Z=[];for(let Q of $.split(`
|
|
28
28
|
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=h8)continue;if(K[e$]?.toUpperCase()!==$J)continue;let B=K[t$]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=KJ(B.slice(0,G),U),Y=K[h8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function VJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=x8)break;let Q;try{Q=await $.readTextFile(`${L0}/net/${Z}`)}catch{continue}J.push(...BJ(Q,x8-J.length))}return J}async function GJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await p8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${L0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,o$)){let G;try{G=await J.readLink(`${L0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(JJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function s8($,J=y2){let Z=await VJ(J),Q=await GJ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;K.push({pid:F,port:X.port,address:X.address})}K.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,a$),G=await Promise.all(B.map(async(X)=>[X,await d8(X,J)])),U=new Map(G),W=K.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&v8($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await u8(X,J)])));return{ports:W.slice(0,i$).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as m2}from"path";var k1=200,UJ=250,XJ=250;async function f1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function h2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var c8="/System/Volumes/Data",WJ=["/tmp","/var","/etc"];function v2($){let J=m2.normalize($);if(J.startsWith(`${c8}/`))J=J.slice(c8.length);return WJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function n8($){return $&&m2.isAbsolute($)?v2($):null}async function r8($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=k1){let K=J.slice(Q,Q+k1).join(",");for(let B of await f1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:n8(B.names[0])})}return Z}async function a8($,J){let Z=v2($),Q=(await f1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=n8(B.names[0]);return G!==null&&h2(Z,G)}).map((B)=>B.pid).slice(0,UJ),K=await r8(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&h2(Z,G.cwd)?[{pid:B,command:G.command,cwd:m2.relative(Z,G.cwd)||"."}]:[]})}}async function i8($,J){let Z=v2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await f1(J,Q),B=await r8(J,K.map((Y)=>Y.pid)),G=K.map((Y)=>Y.pid).filter((Y)=>{let X=B.get(Y)?.cwd;return Boolean(X&&h2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=k1){let X=G.slice(Y,Y+k1).join(",");for(let F of await f1(J,["-a","-p",X,...Q]))for(let C of F.names)if(U.has(`${F.pid} ${C}`))W.push({pid:F.pid,command:F.command,address:C})}return{ports:W.slice(0,XJ)}}import{join as AJ}from"path";import{spawn as MJ}from"child_process";import{randomUUID as wJ}from"crypto";import{chmodSync as e8,lstatSync as $5,mkdirSync as LJ,readdirSync as OJ,statSync as jJ,unlinkSync as IJ}from"fs";import{join as u2}from"path";function Q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var p2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var b1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var O0=()=>{throw Error("proof_visual_contract_invalid")};class o8 extends Error{constructor(){super("proof_visual_contract_invalid")}}function FJ($){if(!Q1($)||$.version!==1)return O0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new o8;if(!Q1($.viewport)||!b1($.viewport.width,1,4096)||!b1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>p2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return O0();let J=$.targets.map((Q)=>{if(!Q1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return O0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return O0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return O0();Z=$.additionalViewports.map((K)=>{if(!Q1(K)||!b1(K.width,1,4096)||!Number.isInteger(K.width)||!b1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return O0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return O0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var CJ=["organizationId","userId","sessionId","runId"],HJ=[...CJ,"prUrl","headSha","skillDigest","evidenceKind"],dB=[...HJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DJ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function t8($){return DJ[$].directory}var J5=10485760;function Z5($={}){let J=$.directory??t8("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");LJ(J,{recursive:!0,mode:457});let B=$5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");e8(J,457);let G=OJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:jJ(u2(J,M)).mtimeMs})).sort((M,I)=>I.time-M.time);for(let M of G.slice(9))IJ(u2(J,M.name));let U=u2(J,`${wJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??MJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(J5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,C=!1,N=new Promise((M,I)=>{X=M,F=I});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,I)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),I(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(O)=>{try{if(O!==0&&O!==255)throw Error();let k=$5(U);if(!C||!k.isFile()||k.isSymbolicLink()||k.uid!==process.getuid?.()||k.size<128||k.size>J5+65536)throw Error();e8(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),I(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let L=setTimeout(()=>Y.kill("SIGKILL"),(Number(K)+5)*1000);D.finally(()=>clearTimeout(L)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await N}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function B5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??Q5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AJ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??K5)();return B??=Z5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:j1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as G3}from"child_process";import{createHash as mJ,randomUUID as vJ}from"crypto";import{existsSync as Q0,mkdirSync as Z3,mkdtempSync as U3,readdirSync as d1,readFileSync as X3,renameSync as pJ,rmSync as V1,statSync as m1,writeFileSync as uJ}from"fs";import{homedir as W3,tmpdir as _5}from"os";import{basename as R5,dirname as Q3,join as q,relative as P5,resolve as K3,sep as z5}from"path";var i=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),x1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),V5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),l2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),s2=["home","lock","side_button","siri","apple_pay"],TJ=V.enum(["tree","screenshot","both","none"]),_J=V.object({...l2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:TJ.optional(),wait_for:_J.optional(),timeout:V.number().min(0).max(20).optional()},d2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...l2.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(s2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),c2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:i}).strict(),V.object({action:V.literal("shutdown"),device:i}).strict(),V.object({action:V.literal("build"),path:x1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:x1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),steps:V.array(V.lazy(()=>d2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:i.optional(),app_path:x1.optional(),bundle_id:V5.optional(),steps:V.array(V.lazy(()=>d2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:i.optional(),bundle_id:V5}).strict(),V.object({action:V.literal("logs"),device:i.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:i.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:x1.optional()}).strict(),V.object({action:V.literal("chrome"),device:i.optional()}).strict(),V.object({action:V.literal("inspect"),device:i.optional()}).strict(),V.object({action:V.literal("tap"),device:i.optional(),x:Z0.optional(),y:Z0.optional(),...l2.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:i.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:i.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:i.optional(),name:V.enum(s2),...C0}).strict(),V.object({action:V.literal("open_url"),device:i.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:i.optional(),steps:V.array(d2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),G5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),UV=V.object({text:V.string(),error:V.string().optional(),device:G5.optional(),devices:V.array(G5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var XV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),WV={type:"object",properties:{action:{type:"string",enum:c2.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...s2]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as i2}from"child_process";import{createHash as PJ}from"crypto";import{existsSync as r2,mkdirSync as y1,mkdtempSync as zJ,readdirSync as U5,readFileSync as X5,renameSync as qJ,rmSync as W5,symlinkSync as a2,writeFileSync as K1}from"fs";import{homedir as EJ}from"os";import{dirname as C5,join as f}from"path";import{createInterface as gJ}from"readline";var n2=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
29
29
|
//
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Ih as C}from"./vm-hands-entry-lite-wffqkcjq.js";import{execFileSync as W}from"child_process";import{mkdirSync as b,readdirSync as R,readFileSync as F,rmSync as B,statSync as K,writeFileSync as f}from"fs";import{join as $}from"path";import{setTimeout as k}from"timers/promises";var A=3000,X=null;function G(z){return $(z,"users")}function m(z){if(X?.root===z.root)return;let H=G(z.root);b(H,{recursive:!0,mode:448}),f($(H,String(process.pid)),"",{mode:384}),X=z}function S(){if(!X)return;B($(G(X.root),String(process.pid)),{force:!0}),X=null}function x(z){try{return process.kill(z,0),!0}catch(H){return H instanceof Error&&"code"in H&&H.code==="EPERM"}}function L(){let z=process.getuid?.();if(process.platform==="linux")return R("/proc").flatMap((N)=>{if(!/^\d+$/.test(N))return[];try{if(K(`/proc/${N}`).uid!==z)return[];let Q=F(`/proc/${N}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return Q?[{pid:Number(N),command:Q}]:[]}catch{return[]}});return W("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
|
|
3
3
|
`).flatMap((N)=>{let Q=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(N);return Q&&Number(Q[2])===z?[{pid:Number(Q[1]),command:Q[3]}]:[]})}async function p(){let z=X;if(!z)return{released:"unused",stopped:0};let H=G(z.root);B($(H,String(process.pid)),{force:!0}),X=null;let N=!1;for(let J of R(H)){let U=Number(J);if(Number.isSafeInteger(U)&&U>0&&x(U))N=!0;else B($(H,J),{force:!0})}if(N)return{released:"shared",stopped:0};let Q=L().filter((J)=>J.pid!==process.pid&&(J.command.includes(`${z.root}/`)||J.command.includes(`${z.automation}/`)||J.command.includes(z.extensionDir))),Y=(J,U)=>{try{process.kill(J,U)}catch{}};for(let J of Q)Y(J.pid,"SIGTERM");for(let J=Date.now()+A;Date.now()<J&&Q.some((U)=>x(U.pid));)await new Promise((U)=>setTimeout(U,100));for(let J of Q)if(x(J.pid))Y(J.pid,"SIGKILL");return{released:"stopped",stopped:Q.length}}var O=20000,j=30000,v=100,Z=new Map,V=null,q=[];function h(z){Z.set(z,(Z.get(z)??0)+1);let H=!1;return()=>{if(H)return;H=!0;let N=(Z.get(z)??1)-1;if(N>0){Z.set(z,N);return}if(Z.delete(z),V?.run===z)V.idleUntil=0}}function M(){return new C("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function P(z,H){return V!==null&&V.run!==z&&(V.calls>0||H<V.idleUntil)}async function I(z,H,N=Date.now){let Q=Symbol(z);q.push(Q);try{let U=N()+j;for(;;){if(!P(z,N())&&(V?.run===z||q[0]===Q))break;if(N()>=U)throw M();await k(v,void 0,{signal:H}).catch(()=>H.throwIfAborted())}}finally{q.splice(q.indexOf(Q),1)}if(V?.run!==z)V={run:z,calls:0,idleUntil:0};let Y=V;Y.calls+=1;let J=!1;return()=>{if(J)return;J=!0,Y.calls-=1,Y.idleUntil=N()+O}}
|
|
4
|
-
export{m as
|
|
4
|
+
export{m as Bh,S as Ch,p as Dh,O as Eh,j as Fh,h as Gh,I as Hh};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Kh as e}from"./vm-hands-entry-lite-ss2w3h3d.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
|
|
3
3
|
export{i as x};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ae as W}from"./vm-hands-entry-lite-m5pmd2cz.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),g=W.string().regex(/^[a-f0-9]{40}$/),N=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),q={version:W.literal(1),repoFullName:T},c=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),l=W.discriminatedUnion("kind",[W.strictObject({...q,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...q,kind:W.literal("pr_review_context"),number:N,after:W.string().min(1).max(1024).optional()}),W.strictObject({...q,kind:W.literal("prepare"),branch:G,baseSha:g,defaultBranch:G}),W.strictObject({...q,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:g,remoteHeadSha:g.nullable()}),W.strictObject({...q,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...q,kind:W.literal("pr_mutation"),number:N,mutation:c}),W.strictObject({...q,kind:W.literal("pr_merge"),number:N,expectedHeadSha:g,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"])})]),I=245760,u=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(I)}),W.strictObject({kind:W.literal("prepare"),headSha:g}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(I)}),W.strictObject({kind:W.literal("publish"),headSha:g,scannedObjectCount:W.number().int().min(0).max(5000)}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:N,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:N,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=I,"local_device_gh_result_too_large"),y=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),j=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:y.optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function a(Q,Z,$={},H="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return d(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((K)=>K==="."||K===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((K)=>K.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((K,B)=>{if(B==="per_page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(B==="page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(Y==="/pulls"&&B==="state"&&["open","closed","all"].includes(K))return;if(Y==="/pulls"&&B==="sort"&&K==="updated")return;if(Y==="/pulls"&&B==="direction"&&K==="desc")return;if(Y==="/pulls"&&["head","base"].includes(B)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(K))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((B,b)=>{if(b!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(B))throw Error("local_device_gh_header_denied")})}function d(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let H=new URL(Z,"https://api.github.com");if(H.pathname!=="/search/issues"||H.username||H.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;H.searchParams.forEach((X,K)=>{if(K==="q"&&V===null){V=X;return}if(K==="per_page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;if(K==="page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,U=V?.toLowerCase()??"";if(U.length>512||!(U+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(U.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((X,K)=>{if(K!=="accept"||X!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var e=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
|
|
3
3
|
repository(owner: $owner, name: $repo) {
|
|
4
4
|
nameWithOwner
|
|
5
5
|
pullRequest(number: $number) {
|
|
@@ -39,4 +39,4 @@ import{_d as W}from"./vm-hands-entry-lite-sv6xwe0h.js";var T=W.string().max(201)
|
|
|
39
39
|
`)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
|
|
40
40
|
`),"utf8")}function D(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function p(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function L(Q){return D(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function r(Q){return D(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&D(Q.payload)}function w(Q){throw Error(Q)}function sQ(Q,Z){let $=D(Q)?Q:{},H=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:H,message:V}}function n(Q){if(!D(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
|
|
41
41
|
`)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function _(Q,Z){if(!D(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==x||!Array.isArray(Q.roots)||!Q.roots.every(L)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:x,roots:Q.roots},auth_scheme:"p256"}}function oQ(Q){return _(Q,!1)}function iQ(Q){let Z=_(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function tQ(Q){if(!D(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...o(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var s=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(s.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function vQ(Q){if(!D(Q))return;try{return{...n(Q),...f(Q)}}catch{return}}function o(Q){if(!D(Q))return{};let Z={};for(let $ of R){let H=Q[$];if(typeof H==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(H))Z[$]=H}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function lQ(Q){if(!D(Q)||!Array.isArray(Q.roots)||!Q.roots.every(L))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function uQ(Q){if(!D(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function aQ(Q){if(!D(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function eQ(Q){if(D(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(D(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function QW(Q){if(!D(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function i(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function WW(Q,Z=E){if(!D(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!k(Q.owner)||!p(Q.capability,Z)||!D(Q.payload)||Q.protocol_version!==x||i(Q.payload)>O||Q.authority!==void 0&&!J(Q.authority)||Q.local_github_authority!==void 0&&!j.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!j.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!k(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...J(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:j.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&D(Q.environment)&&D(Q.environment.payload)&&J(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:x};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function ZW(Q){if(!D(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(r)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function $W(Q){if(!D(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function DW(Q){if(!D(Q)||!D(Q.payload)||!J(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function t(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function KW(Q){if(!D(Q)||!t(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
|
|
42
|
-
export{l as
|
|
42
|
+
export{l as Oc,I as Pc,u as Qc,j as Rc,a as Sc,e as Tc,QQ as Uc,E as Vc,x as Wc,m as Xc,O as Yc,KQ as Zc,FQ as _c,wQ as $c,HQ as ad,VQ as bd,YQ as cd,XQ as dd,BQ as ed,GQ as fd,qQ as gd,gQ as hd,MQ as id,NQ as jd,UQ as kd,jQ as ld,JQ as md,xQ as nd,IQ as od,SQ as pd,mQ as qd,PQ as rd,TQ as sd,CQ as td,AQ as ud,EQ as vd,kQ as wd,LQ as xd,_Q as yd,fQ as zd,bQ as Ad,cQ as Bd,yQ as Cd,dQ as Dd,OQ as Ed,zQ as Fd,RQ as Gd,hQ as Hd,pQ as Id,h as Jd,rQ as Kd,nQ as Ld,sQ as Md,n as Nd,oQ as Od,iQ as Pd,tQ as Qd,vQ as Rd,lQ as Sd,uQ as Td,aQ as Ud,eQ as Vd,QW as Wd,WW as Xd,ZW as Yd,$W as Zd,DW as _d,KW as $d};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Kb as j,Lb as q}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Kb as j,Lb as q}from"./vm-hands-entry-lite-h2xpqaxn.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
|
|
3
3
|
export{y as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-
|
|
2
|
+
import"./vm-hands-entry-lite-4fnbmmp6.js";import"./vm-hands-entry-lite-yh7n4svm.js";import"./vm-hands-entry-lite-m5pmd2cz.js";import{Mh as A}from"./vm-hands-entry-lite-ss2w3h3d.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-e2p1qwmv.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-pdvbqbpj.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();
|