@reason-machines/cli-linux-arm64-musl 0.2.358 → 0.2.359
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/api-credentials-axffq0pk.js +2 -0
- package/bin/vm-hands/api-texm6ayv.js +2 -0
- package/bin/vm-hands/ask-relay-fkb3bj30.js +8 -0
- package/bin/vm-hands/connect-cli-ev4xex04.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-j3e3zjd5.js → custom-endpoint-device-bsanzqj2.js} +1 -1
- package/bin/vm-hands/desktop-account-jxfva4m1.js +2 -0
- package/bin/vm-hands/{device-workspace-7yg5x68n.js → device-workspace-fhbpenda.js} +1 -1
- package/bin/vm-hands/hands-worker-source-ze6q6h8b.js +2 -0
- package/bin/vm-hands/{index-swa20ch8.js → index-tv4kcb2a.js} +1 -1
- package/bin/vm-hands/install-receipt-3s9amwp3.js +2 -0
- package/bin/vm-hands/local-automation-f8f33qpp.js +2 -0
- package/bin/vm-hands/local-capabilities-ya6yzxh5.js +2 -0
- package/bin/vm-hands/local-desktop-users-3th2aaac.js +2 -0
- package/bin/vm-hands/local-display-mac-neweyjpa.js +2 -0
- package/bin/vm-hands/local-display-session-v00nv1fm.js +2 -0
- package/bin/vm-hands/local-pty-session-2crsy5td.js +2 -0
- package/bin/vm-hands/managed-runtime-mg7kmckn.js +2 -0
- package/bin/vm-hands/{network-contract-rm9x646s.js → network-contract-gq8x3ehk.js} +1 -1
- package/bin/vm-hands/package-s3eg9zrd.js +2 -0
- package/bin/vm-hands/permissions-3kjdp3ge.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-3z7bas06.js → reason-hands-protocol-67d4b6fm.js} +1 -1
- package/bin/vm-hands/serve-service-nqshfese.js +2 -0
- package/bin/vm-hands/{status-psxtsknj.js → status-f146chye.js} +2 -2
- package/bin/vm-hands/version-ss25ccvh.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-he2z2137.js → vm-hands-entry-lite-07er2w8q.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-5b29hq7h.js → vm-hands-entry-lite-1j9r1fca.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-22we2jrv.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-xhjbc3e4.js → vm-hands-entry-lite-3ew5ftk0.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-463aheya.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-5kgvss4p.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-5xtkyx25.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jfwz0br7.js → vm-hands-entry-lite-9z6k7898.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-bybpy28m.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-c0m2jewa.js +11 -0
- package/bin/vm-hands/{vm-hands-entry-lite-3zxjyj62.js → vm-hands-entry-lite-c7krpmd8.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-dys7am1h.js → vm-hands-entry-lite-d2hbz0r4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-nvhzj5b0.js → vm-hands-entry-lite-f4gvypnx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-wpx6sg6d.js → vm-hands-entry-lite-gxjxx1r2.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-gzxxsjmr.js +62 -0
- package/bin/vm-hands/{vm-hands-entry-lite-nd1k2jz9.js → vm-hands-entry-lite-h2xemq1f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-c9wp99nr.js → vm-hands-entry-lite-ha1ej910.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-nbtpm59m.js → vm-hands-entry-lite-j05685sg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-6f5eypjm.js → vm-hands-entry-lite-jn95s3j4.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-kt4831mq.js +340 -0
- package/bin/vm-hands/{vm-hands-entry-lite-k17ntg9v.js → vm-hands-entry-lite-kv0qat0x.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-kxdw4myj.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-0hv9ek0t.js → vm-hands-entry-lite-n867d88m.js} +9 -68
- package/bin/vm-hands/{vm-hands-entry-lite-c8hfat7y.js → vm-hands-entry-lite-p8662x7z.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-pf1gagky.js +37 -0
- package/bin/vm-hands/{vm-hands-entry-lite-rr0hhz7g.js → vm-hands-entry-lite-qbnz4h30.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-8jmwhybq.js → vm-hands-entry-lite-qhgfnhjt.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-trcg4jv7.js → vm-hands-entry-lite-qm18wqgz.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-beannz0s.js → vm-hands-entry-lite-r5y08n0q.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-r6pap1kh.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-s98hjhz3.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-zrvaqawr.js → vm-hands-entry-lite-sx2gpbap.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-qf01e5f1.js → vm-hands-entry-lite-szfy3kx7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-95k4g3jj.js → vm-hands-entry-lite-taw01cp4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0tdpjsxc.js → vm-hands-entry-lite-tg2bkah3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mybm2kyz.js → vm-hands-entry-lite-v08mjs3f.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-84d59wrf.js → vm-hands-entry-lite-w88zkzhr.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-wej1p1ry.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-gcn3rmz6.js → vm-hands-entry-lite-wry37am5.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-x4j4058x.js +9 -0
- package/bin/vm-hands/{vm-hands-entry-lite-tj1y61bg.js → vm-hands-entry-lite-ygx9kj92.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-dqqdgtqq.js → vm-hands-executor-5nqmf61x.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-zedtdcmk.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-y89fmev1.js → vm-hands-runtime-hnpk8xmf.js} +3 -3
- package/bin/vm-hands/worker-sandbox-vmp22sk6.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-emdf5nm5.js +0 -2
- package/bin/vm-hands/api-js29ghm5.js +0 -2
- package/bin/vm-hands/ask-relay-qv9ddzr1.js +0 -8
- package/bin/vm-hands/connect-cli-8nxph9td.js +0 -2
- package/bin/vm-hands/desktop-account-gcysz0m3.js +0 -2
- package/bin/vm-hands/hands-worker-source-hbp5n31r.js +0 -2
- package/bin/vm-hands/local-automation-nw3bj9b5.js +0 -2
- package/bin/vm-hands/local-capabilities-7m54wthn.js +0 -2
- package/bin/vm-hands/local-desktop-users-pccz3sz9.js +0 -2
- package/bin/vm-hands/local-display-mac-gj72gkfb.js +0 -2
- package/bin/vm-hands/local-display-session-5ajajxtg.js +0 -2
- package/bin/vm-hands/local-pty-session-zen80k1k.js +0 -2
- package/bin/vm-hands/package-1e3w44ve.js +0 -2
- package/bin/vm-hands/permissions-0ej6xgrj.js +0 -2
- package/bin/vm-hands/version-fw3dwa12.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-33ttamma.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-3ms5bb0b.js +0 -43
- package/bin/vm-hands/vm-hands-entry-lite-6qfax5p2.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-d9k3dzaq.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-dyy62gt3.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-pm0j47qj.js +0 -343
- package/bin/vm-hands/vm-hands-entry-lite-tdgbgcer.js +0 -3
- package/bin/vm-hands/vm-hands-op-runner-msdteb31.js +0 -2
- package/bin/vm-hands/worker-sandbox-yw24sxyp.js +0 -2
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Zc as dq,_c as cq}from"./vm-hands-entry-lite-wej1p1ry.js";import{Gh as zq,Hh as fq,Lh as Rq,Mh as Uq,Nh as X,Qh as mq,Sh as Fq,Th as vq,Vh as h,Wh as P,Xh as Mq}from"./vm-hands-entry-lite-kxdw4myj.js";import{ni as _q}from"./vm-hands-entry-lite-r6pap1kh.js";import{Bi as hq,Di as lq,Gi as oq,Hi as sq,Ii as uq,Ji as Nq}from"./vm-hands-entry-lite-x4j4058x.js";import{Ri as c}from"./vm-hands-entry-lite-1j9r1fca.js";import{randomUUID as O}from"crypto";import{chmodSync as qq,closeSync as m,constants as v,existsSync as B,fstatSync as pq,lstatSync as T,mkdirSync as r,openSync as rq,readFileSync as g,readdirSync as Iq,readlinkSync as E,realpathSync as C,renameSync as k,rmSync as d,statSync as x,symlinkSync as Gq,unlinkSync as D,writeFileSync as l}from"fs";import{basename as p,dirname as I,isAbsolute as jG,join as K,relative as HG,resolve as A,sep as nq}from"path";import{spawnSync as Tq}from"child_process";import{createRequire as zG}from"module";var Wq=1,iq=1,aq=128,FG=65536,MG="https://reasonmachines.com/api/runtime-manifest-v2",NG=30000,IG=600000,kq=1e4,TG=60000,AG=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var xq=/^[a-z0-9_.-]{1,80}$/,BG=64,DG="so.ara.device-broker",Vq=["com.apple.security.cs.allow-jit","com.apple.security.cs.allow-unsigned-executable-memory"],OG=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function e(q){if(q?.aborted)throw new X("update_cancelled","Managed runtime update request was cancelled.")}function Aq(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}function Bq(q,G,J=[]){let Q=new Set([...G,...J]);return G.every((R)=>(R in q))&&Object.keys(q).every((R)=>Q.has(R))}function N(q){return typeof q==="string"&&AG.test(q)}function eq(q){return typeof q==="string"&&!Number.isNaN(Date.parse(q))&&new Date(q).toISOString()===q}function EG(q){return Uq.includes(q)}function y(q){r(q,{recursive:!0,mode:448}),qq(q,448)}function tq(q,G){y(I(q));let J=`${q}.${process.pid}.${O()}.tmp`;try{l(J,G,{mode:384,flag:"wx"}),qq(J,384),k(J,q)}finally{if(B(J))D(J)}}function Dq(q={}){if((q.platform??process.platform)!=="darwin")throw new X("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let J=q.environment??process.env,Q=_q(J,"REASON_CLI_CHANNEL")==="staging",R=Q?_q(J,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,W=q.root!==void 0||Boolean(R&&jG(R))?null:K(q.home??c(),"Library","Application Support"),Z=q.root??(W?K(W,Q?"Reason Staging":"Reason","CLI"):R);return{executableName:"reason",root:Z,...W?{legacyRoot:K(W,"Ara",...Q?["staging","runtime"]:["runtime"])}:{},versions:K(Z,"versions"),current:K(Z,"current"),previous:K(Z,"previous"),brokerLock:K(Z,"broker.lock"),transitionLock:K(Z,"transition.lock"),lifecycleEvents:K(Z,"lifecycle-events")}}function CJ(q){let G=q.legacyRoot;if(!G)return null;return{root:G,versions:K(G,"versions"),current:K(G,"current"),previous:K(G,"previous"),brokerLock:K(G,"broker.lock"),transitionLock:K(G,"transition.lock"),lifecycleEvents:K(G,"lifecycle-events")}}function S(q,G){if(!N(G))throw new X("invalid_version","Invalid managed Reason runtime version.");let J=K(q.versions,G,"ara");if(!q.executableName)return J;let Q=K(q.versions,G,q.executableName),R=(Z)=>{try{return T(Z),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}},U=R(J),W=R(Q);if(U&&W)throw new X("installed_artifact_mismatch","Ambiguous managed runtime executable layout.");return U?J:Q}function n(q,G){if(!N(G))throw new X("invalid_version","Invalid managed Reason runtime version.");return Oq(S(q,G))}function Oq(q){return K(I(q),p(q)==="reason"?fq:zq)}function qG(q,G){if(!N(q)||!N(G))throw new X("invalid_version","Invalid managed Reason runtime version.");let[J,Q]=q.split("-",2),[R,U]=G.split("-",2),W=J.split(".").map(Number),Z=R.split(".").map(Number);for(let H=0;H<3;H+=1){let j=W[H]-Z[H];if(j!==0)return j<0?-1:1}if(Q===void 0||U===void 0){if(Q===U)return 0;return Q===void 0?1:-1}let _=Q.split("."),$=U.split("."),Y=Math.max(_.length,$.length);for(let H=0;H<Y;H+=1){let j=_[H],z=$[H];if(j===void 0||z===void 0){if(j===z)return 0;return j===void 0?-1:1}if(j===z)continue;let F=/^\d+$/.test(j),w=/^\d+$/.test(z);if(F&&w)return Number(j)<Number(z)?-1:1;if(F!==w)return F?-1:1;return j<z?-1:1}return 0}function CG(q=process.arch){let G=`darwin-${q}`;if(!EG(G))throw new X("unsupported_architecture","The managed Reason runtime supports only Apple Silicon and Intel Macs.");return G}function Pq(q){return[...q.matchAll(/<key>\s*([^<]+?)\s*<\/key>/g)].map((G)=>G[1].trim())}function gq(q){let G=q.match(/^CodeDirectory .*$/gm)??[];return G.length>0&&G.every((J)=>{return(/ flags=0x[0-9a-f]+\(([^)]*)\)(?: |$)/.exec(J)?.[1]?.split(/[ ,]+/).filter(Boolean)??[]).includes("runtime")})}function SG(q){let G=`TeamIdentifier=${hq}`,J=`Identifier=${DG}`,Q=Pq(q.brokerEntitlements),R=Pq(q.credentialLibraryEntitlements);if(!q.brokerDetail.split(`
|
|
3
|
+
`).includes(G)||!q.brokerDetail.split(`
|
|
4
|
+
`).includes(J)||!gq(q.brokerDetail)||Q.length!==Vq.length||Vq.some((U)=>!new RegExp(`<key>\\s*${U.replaceAll(".","\\.")}\\s*</key>\\s*<true\\s*/>`).test(q.brokerEntitlements)))throw new X("invalid_code_signature","Managed runtime broker has an invalid Reason signature, identifier, or entitlement set.");if(!q.credentialLibraryDetail.split(`
|
|
5
|
+
`).includes(G)||!gq(q.credentialLibraryDetail)||R.length!==0)throw new X("invalid_code_signature","Managed runtime credential library has an invalid signature or entitlement.")}function b(q,G){let J=Tq("/usr/bin/codesign",q,{stdio:["ignore","pipe","pipe"]});if(J.status!==0)throw new X("invalid_code_signature",G);return[new TextDecoder().decode(J.stdout??new Uint8Array),new TextDecoder().decode(J.stderr??new Uint8Array)].join("")}var Eq=(q,G)=>{b(["--verify","--strict","--verbose=2",q],"Managed runtime broker code signature is invalid."),b(["--verify","--strict","--verbose=2",G],"Managed runtime credential library code signature is invalid."),SG({brokerDetail:b(["-d","--verbose=4",q],"Managed runtime broker signer could not be inspected."),brokerEntitlements:b(["-d","--entitlements",":-",q],"Managed runtime broker entitlements could not be inspected."),credentialLibraryDetail:b(["-d","--verbose=4",G],"Managed runtime credential library signer could not be inspected."),credentialLibraryEntitlements:b(["-d","--entitlements",":-",G],"Managed runtime credential library entitlements could not be inspected.")})};async function LG(q,G,J){let Q=q.headers.get("content-length");if(Q!==null){let Y=Number(Q);if(!Number.isSafeInteger(Y)||Y<0||Y>G)throw new X("response_too_large","Managed runtime response exceeded its size limit.")}if(!q.body){let Y=new Uint8Array(await q.arrayBuffer());if(Y.byteLength>G)throw new X("response_too_large","Managed runtime response exceeded its size limit.");return Y}let R=q.body.getReader(),U=[],W=0,Z=()=>{if(!J)return R.read();return new Promise((Y,H)=>{let j=()=>{J.removeEventListener("abort",j),R.cancel(J.reason).catch(()=>{}),H(J.reason??new DOMException("Aborted","AbortError"))};if(J.aborted){j();return}J.addEventListener("abort",j,{once:!0}),R.read().then((z)=>{J.removeEventListener("abort",j),Y(z)},(z)=>{J.removeEventListener("abort",j),H(z)})})};try{while(!0){let Y=await Z();if(Y.done)break;if(W+=Y.value.byteLength,W>G)throw await R.cancel(),new X("response_too_large","Managed runtime response exceeded its size limit.");U.push(Y.value)}}finally{try{R.releaseLock()}catch{}}let _=new Uint8Array(W),$=0;for(let Y of U)_.set(Y,$),$+=Y.byteLength;return _}async function u(q){let G;try{G=new URL(q.url)}catch{throw new X("invalid_update_url","Managed runtime update URL is invalid.")}if(G.protocol!=="https:"||G.username||G.password||G.hash)throw new X("invalid_update_url","Managed runtime update URL must use HTTPS.");let J=new AbortController,Q,R=()=>{Q??="caller",J.abort(q.signal?.reason)};if(q.signal?.aborted)R();else q.signal?.addEventListener("abort",R,{once:!0});let U=setTimeout(()=>{Q??="timeout",J.abort(Error("managed runtime fetch timed out"))},q.timeoutMs),W=(Z,_)=>{if(Z instanceof X)return Z;if(Q==="caller")return new X("update_cancelled","Managed runtime update request was cancelled.");if(Q==="timeout")return new X("update_fetch_timeout","Managed runtime update request timed out.");return new X("update_fetch_failed",_)};try{let Z;try{if(Z=await q.fetchImpl(G,{headers:{accept:q.accept},signal:J.signal}),J.signal.aborted)throw W(J.signal.reason,"Managed runtime update request was cancelled.")}catch(_){throw W(_,"Managed runtime update request failed.")}if(!Z.ok)throw new X("update_http_error","Managed runtime update request was rejected.");if(Z.url&&new URL(Z.url).protocol!=="https:")throw new X("insecure_redirect","Managed runtime update redirected to an insecure URL.");try{let _=await LG(Z,q.maximumBytes,J.signal);if(J.signal.aborted)throw W(J.signal.reason,"Managed runtime update response was cancelled.");return _}catch(_){throw W(_,"Managed runtime update response failed.")}}finally{clearTimeout(U),q.signal?.removeEventListener("abort",R)}}async function GG(q,G,J=kq,Q){let R=typeof J==="number"?J:kq,U=typeof J==="number"?Q:J;if(U?.aborted)return!1;let W=await dq([q,"--version"],{timeoutMs:R,...U?{signal:U}:{}});return W.exitCode===0&&W.stdout.trim().replace(/^v/,"")===G}async function wG(q){let G=!1,J=null,Q=null,R=(U)=>{try{M(q.paths,U,{now:q.now})}catch{}};try{let U=q.home??c();if(!uq(q.manifest.version,U))return{status:"current"};Q=sq(U);let W=await u({url:new URL(mq,q.manifest.artifacts[q.target].broker.url).toString(),maximumBytes:Rq,fetchImpl:async(j,z)=>{let F=await q.fetchImpl(j,z);return G=F.status===404,F},timeoutMs:q.timeoutMs,accept:"application/json",signal:q.signal}),{manifest:Z}=vq(new TextDecoder().decode(W),q.trustedKeys);if(Z.version!==q.manifest.version||Z.published_at!==q.manifest.published_at)throw new X("identity_manifest_mismatch","Background identity manifest names another release.");let _=Z.artifacts[q.target],$=await u({url:_.url,maximumBytes:_.size_bytes,fetchImpl:q.fetchImpl,timeoutMs:q.timeoutMs,accept:"application/octet-stream",signal:q.signal});P($,_),y(q.workDirectory),J=K(q.workDirectory,`.identity-${process.pid}-${O()}`),r(J,{mode:448});let Y=K(J,"identity.tgz");if(l(Y,$,{mode:384,flag:"wx"}),Tq("/usr/bin/tar",["-xzf",Y,"-C",J],{stdio:"ignore",timeout:60000}).status!==0)throw new X("identity_extract_failed","Background identity archive could not be extracted.");return Nq({sourceApp:K(J,"Reason.app"),home:U,releaseSigned:!0,...q.command?{command:q.command}:{}}),R({event:"identity.refresh_completed",runtime_version:q.manifest.version,...Q?{from_version:Q}:{},to_version:q.manifest.version}),{status:"installed"}}catch(U){if(G)return{status:"unpublished"};let W=U instanceof X||U instanceof lq?U.code:"identity_install_failed";return process.stderr.write(`Reason background identity: identity_update_failed (${W})
|
|
6
|
+
`),R({event:"identity.refresh_failed",runtime_version:q.manifest.version,...Q?{from_version:Q}:{},to_version:q.manifest.version,reason_code:W}),{status:"failed",code:W}}finally{if(J)d(J,{recursive:!0,force:!0})}}async function SJ(q){if(!N(q.currentVersion))throw new X("invalid_version","Invalid current managed runtime version.");let G=q.paths??Dq(),J=q.target??CG(),Q=q.fetchImpl??fetch,R=q.timeoutMs??NG,U=q.timeoutMs??IG,W=q.healthCheck??((H,j,z)=>GG(H,j,TG,z)),Z=q.verifyCodeSignatures??Eq,_=q.now?.()??new Date,$,Y=!1;M(G,{event:"update.check_started",runtime_version:q.currentVersion,from_version:q.currentVersion},{now:()=>_});try{await vG({paths:G,verifyCodeSignatures:Z,healthCheck:W});let H=await u({url:q.manifestUrl??MG,maximumBytes:Rq,fetchImpl:Q,timeoutMs:R,accept:"application/json",signal:q.signal}),j=Fq(new TextDecoder().decode(H),q.trustedKeys);$=j.manifest.version;let z=()=>wG({paths:G,...q.now?{now:q.now}:{},manifest:j.manifest,target:J,trustedKeys:q.trustedKeys,fetchImpl:Q,timeoutMs:U,workDirectory:G.versions,...q.home?{home:q.home}:{},...q.identityCommand?{command:q.identityCommand}:{},...q.signal?{signal:q.signal}:{}});if(qG($,q.currentVersion)<=0)return M(G,{event:"update.not_available",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-_.getTime())},{now:q.now}),$q(G),{status:"not_available",currentVersion:q.currentVersion,offeredVersion:$,...$===q.currentVersion?{identity:await z()}:{}};let F=j.manifest.artifacts[J];M(G,{event:"update.download_started",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$},{now:q.now});let w=await u({url:F.broker.url,maximumBytes:F.broker.size_bytes,fetchImpl:Q,timeoutMs:U,accept:"application/octet-stream",signal:q.signal});P(w,F.broker),e(q.signal);let a=await u({url:F.credential_library.url,maximumBytes:F.credential_library.size_bytes,fetchImpl:Q,timeoutMs:U,accept:"application/octet-stream",signal:q.signal});P(a,F.credential_library),M(G,{event:"update.downloaded",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$},{now:q.now}),M(G,{event:"update.verified",runtime_version:q.currentVersion,from_version:q.currentVersion,to_version:$},{now:q.now}),e(q.signal);let Lq=JG({paths:G,version:$,artifact:F.broker,bytes:w,credentialLibraryArtifact:F.credential_library,credentialLibraryBytes:a,verifyCodeSignatures:Z}),wq;try{wq=await W(Lq.executablePath,$,q.signal)}catch(o){throw e(q.signal),o}if(e(q.signal),!wq)throw new X("pre_activation_health_failed","Managed runtime preflight failed.");let V=yG(G,$);if(!V.changed&&V.toVersion!==$)return M(G,{event:"update.not_available",runtime_version:V.toVersion,from_version:V.toVersion,to_version:$,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-_.getTime())},{now:q.now}),{status:"not_available",currentVersion:V.toVersion,offeredVersion:$};if(Y=V.changed,!await W(G.current,$)){if(V.fromVersion){let o=XG(G,$);M(G,{event:"update.rollback",runtime_version:o.toVersion,from_version:o.fromVersion,to_version:o.toVersion,reason_code:"post_activation_health_failed"},{now:q.now})}else ZG(G,$);throw f(G),Y=!1,new X("post_activation_health_failed","Managed runtime activation failed.")}return f(G),$q(G),M(G,{event:"update.activated",runtime_version:$,from_version:q.currentVersion,to_version:$,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-_.getTime())},{now:q.now}),{status:"activated",fromVersion:q.currentVersion,toVersion:$,installed:Lq.installed,identity:await z()}}catch(H){throw M(G,{event:"update.failed",runtime_version:Y?$??q.currentVersion:q.currentVersion,from_version:q.currentVersion,...$?{to_version:$}:{},reason_code:H instanceof X?H.code:"update_failed",duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-_.getTime())},{now:q.now}),H}}function yq(q,G,J){try{let Q=T(I(q));if(!Q.isDirectory()||Q.isSymbolicLink())return!1;let R=T(q);if(!R.isFile()||R.isSymbolicLink()||R.size!==G.size_bytes)return!1;let U=Oq(q),W=T(U);return W.isFile()&&!W.isSymbolicLink()&&W.size===J.size_bytes&&h(g(q))===G.sha256&&h(g(U))===J.sha256}catch{return!1}}function JG(q){let G=S(q.paths,q.version);P(q.bytes,q.artifact),P(q.credentialLibraryBytes,q.credentialLibraryArtifact);let J=q.verifyCodeSignatures??Eq;if(y(q.paths.root),y(q.paths.versions),B(I(G))){if(!yq(G,q.artifact,q.credentialLibraryArtifact))throw new X("installed_artifact_mismatch","The installed runtime version does not match the verified artifact.");return J(G,n(q.paths,q.version)),{installed:!1,executablePath:G}}let Q=K(q.paths.versions,`.install-${q.version}-${process.pid}-${O()}`),R=K(Q,p(G)),U=Oq(R);r(Q,{mode:448});try{l(R,q.bytes,{mode:448,flag:"wx"}),qq(R,448),l(U,q.credentialLibraryBytes,{mode:448,flag:"wx"}),qq(U,448),J(R,U);try{k(Q,I(G))}catch(W){if(!yq(G,q.artifact,q.credentialLibraryArtifact))throw W;return{installed:!1,executablePath:G}}return{installed:!0,executablePath:G}}finally{d(Q,{recursive:!0,force:!0})}}function kG(q,G){if(!N(G))throw new X("invalid_version","Invalid managed Reason runtime version.");return`versions/${G}/${p(S(q,G))}`}function Jq(q,G){y(I(q));let J=`${q}.${process.pid}.${O()}.tmp`;try{Gq(G,J),k(J,q)}finally{if(B(J))D(J)}}var xG=/^\.ara-worker-(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)-(darwin-(?:arm64|x64))\.([0-9A-Za-z]{6})$/;function VG(q,G){let J=I(q),Q=A(J,G),R=I(Q),U=xG.exec(p(R));if(p(Q)!=="ara"||I(R)!==J||!U||!N(U[1])||!Uq.includes(U[2]))return!1;try{return T(R).isDirectory()&&I(C(R))===C(J)&&T(Q).isFile()&&T(Mq(R)).isFile()}catch(W){if(W.code==="ENOENT")return!1;throw W}}function QG(q,G,J){try{if(E(q)!==G)return!1;D(q)}catch(Q){if(Q.code==="ENOENT")return!1;throw Q}try{return Gq(J,q),!0}catch(Q){if(Q.code==="EEXIST")return!1;try{Gq(G,q)}catch(R){if(R.code!=="EEXIST")throw R}throw Q}}function RG(q,G){if(!q.legacyRoot)return!1;let J;try{if(!T(G).isSymbolicLink())return!1;J=E(G)}catch(R){if(R.code==="ENOENT")return!1;throw R}if(A(I(G),J)!==K(q.legacyRoot,"current"))return!1;if(!QG(G,J,q.current))return!1;let Q=L(q);if(Q)M(q,{event:"service.launcher_adopted",runtime_version:Q,to_version:Q,reason_code:"legacy_runtime_root"});return!0}function PG(q){let G=q.launcherPath??K(q.home??c(),".local","bin","ara");try{if(T(G).isSymbolicLink()){let Q=E(G);if(Q===q.paths.current)return"managed";if(VG(G,Q)&&QG(G,Q,q.paths.current)){let R=Xq(q.paths.current,q.paths.executableName)??"unknown";return M(q.paths,{event:"service.launcher_adopted",runtime_version:R,to_version:R,reason_code:"legacy_curl_entrypoint"}),"adopted"}if(RG(q.paths,G))return"adopted"}return"conflict"}catch(J){if(J.code!=="ENOENT")throw J}r(I(G),{recursive:!0,mode:448});for(let J=0;J<4;J+=1)try{return Gq(q.paths.current,G),"created"}catch(Q){if(Q.code!=="EEXIST")throw Q;try{return T(G).isSymbolicLink()&&E(G)===q.paths.current?"managed":"conflict"}catch(R){if(R.code!=="ENOENT")throw R}}return"conflict"}function Xq(q,G){let J;try{if(!T(q).isSymbolicLink())return null;J=E(q)}catch{return null}let Q=J.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return Q&&(Q[2]==="ara"||Q[2]===G)?Q[1]:null}function L(q){return Xq(q.current,q.executableName)}function LJ(q,G=process.execPath){try{return C(q.current)===C(G)}catch{return!1}}function Qq(q,G,J){let R=HG(G,q).split(nq);return R.length===2&&N(R[0])&&(R[1]==="ara"||J!==void 0&&R[1]===J)?R[0]:null}function UG(q,G){try{return T(G).isSymbolicLink()&&A(I(G),E(G))===A(q.current)}catch{return!1}}function wJ(q,G=process.execPath){try{return Qq(C(G),C(q.versions),q.executableName)!==null}catch{let J=A(G);return J===A(q.current)||UG(q,J)||Qq(J,A(q.versions),q.executableName)!==null}}function kJ(q,G=process.execPath){try{return Qq(C(G),C(q.versions),q.executableName)}catch{let J=A(G);if(J===A(q.current)||UG(q,J))return L(q);return Qq(J,A(q.versions),q.executableName)}}function gG(q,G,J={}){let Q=S(q,G),R=n(q,G);if(!B(Q)||!x(Q).isFile()||!B(R)||!x(R).isFile())throw new X("runtime_not_installed","Managed Reason runtime version is not installed.");let U=Cq(q,G,J.allowDowngrade);if(U)return U;return i(q,G,()=>{return WG(q,G,void 0,J.allowDowngrade)})}function Cq(q,G,J=!1){let Q=L(q);if(!Q)return null;if(Q===G)return{changed:!1,fromVersion:Q,toVersion:Q};if(!J&&qG(G,Q)<=0&&!(/^\d+\.\d+\.\d+-desktop\.v1\.\d+\.\d+\.\d+$/.test(G)&&/^\d+\.\d+\.\d+-desktopdev\./.test(Q)))return{changed:!1,fromVersion:Q,toVersion:Q};return null}function WG(q,G,J,Q=!1){let R=Cq(q,G,Q);if(R)return R;let U=L(q);if(J?.(U),U)Jq(q.previous,E(q.current));else if(B(q.previous))D(q.previous);return Jq(q.current,kG(q,G)),{changed:!0,fromVersion:U,toVersion:G}}function yG(q,G){let J=S(q,G),Q=n(q,G);if(!B(J)||!x(J).isFile()||!B(Q)||!x(Q).isFile())throw new X("runtime_not_installed","Managed Reason runtime version is not installed.");return i(q,G,()=>WG(q,G,(R)=>{mG(q,{schema_version:Wq,from_version:R,to_version:G})}))}function XG(q,G){return i(q,G,()=>{if(L(q)!==G)throw new X("rollback_fence_failed","Managed runtime changed before rollback could be applied.");let J=Xq(q.previous,q.executableName);if(!J||J===G)throw new X("rollback_unavailable","No previous managed runtime is available.");let Q=S(q,J),R=n(q,J);if(!B(Q)||!x(Q).isFile()||!B(R)||!x(R).isFile())throw new X("rollback_unavailable","Previous managed runtime is not installed.");let U=E(q.previous),W=E(q.current);if(A(I(q.previous),U)!==A(Q))throw new X("rollback_fence_failed","Previous runtime pointer does not match its installed layout.");return Jq(q.current,U),Jq(q.previous,W),{fromVersion:G,toVersion:J}})}function bG(){let q=Tq("/bin/ps",["-axww","-o","args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000,maxBuffer:16777216});return q.status===0&&typeof q.stdout==="string"?q.stdout:null}function $q(q){let G=[];try{let J=L(q);if(!J||Kq(q))return G;let Q=Iq(q.versions).filter((U)=>N(U));if(Q.length<=2)return G;let R=bG();if(R===null)return G;i(q,J,()=>{let U=new Set([L(q),Xq(q.previous,q.executableName)]);if(Kq(q))return;for(let W of Q){if(U.has(W))continue;let Z=K(q.versions,W);if(R.includes(`${Z}${nq}`))continue;try{d(Z,{recursive:!0,force:!0}),G.push(W)}catch{}}})}catch{}return G}function ZG(q,G){i(q,G,()=>{if(L(q)!==G)throw new X("rollback_fence_failed","Managed runtime changed before rollback could be applied.");D(q.current)})}function Sq(q){return q.activationState??K(q.root,"activation.json")}function fG(q){return Aq(q)&&Bq(q,["schema_version","from_version","to_version"])&&q.schema_version===Wq&&(q.from_version===null||N(q.from_version))&&N(q.to_version)}function Kq(q){try{let G=Sq(q),J=T(G);if(!J.isFile()||J.isSymbolicLink()||J.nlink!==1||(J.mode&63)!==0||J.size>4096)throw new X("invalid_activation_state","Managed runtime activation state is invalid.");let Q=JSON.parse(g(G,"utf8"));if(!fG(Q))throw new X("invalid_activation_state","Managed runtime activation state is invalid.");return Q}catch(G){if(G instanceof X)throw G;if(G.code==="ENOENT")return null;throw new X("invalid_activation_state","Managed runtime activation state is invalid.")}}function mG(q,G){tq(Sq(q),JSON.stringify(G)+`
|
|
7
|
+
`)}function f(q){try{D(Sq(q))}catch(G){if(G.code!=="ENOENT")throw G}}async function vG(q){let G=Kq(q.paths);if(!G)return"none";let J=L(q.paths);if(J===G.from_version)return f(q.paths),"cleared";if(J!==G.to_version)throw new X("rollback_fence_failed","Managed runtime changed before activation recovery could be applied.");let Q=q.verifyCodeSignatures??Eq,R=q.healthCheck??GG,U=!1;try{let W=S(q.paths,G.to_version);Q(W,n(q.paths,G.to_version)),U=await R(W,G.to_version)}catch{U=!1}if(U)return f(q.paths),M(q.paths,{event:"update.activated",runtime_version:G.to_version,...G.from_version?{from_version:G.from_version}:{},to_version:G.to_version,reason_code:"restart_recovery"}),"committed";if(G.from_version){let W=XG(q.paths,G.to_version);return f(q.paths),M(q.paths,{event:"update.rollback",runtime_version:W.toVersion,from_version:W.fromVersion,to_version:W.toVersion,reason_code:"restart_recovery"}),"rolled_back"}return ZG(q.paths,G.to_version),f(q.paths),M(q.paths,{event:"update.rollback",runtime_version:G.to_version,from_version:G.to_version,reason_code:"restart_recovery"}),"rolled_back"}function dG(q){return Aq(q)&&Bq(q,["schema_version","pid","nonce","started_at","runtime_version"])&&q.schema_version===Wq&&typeof q.pid==="number"&&Number.isSafeInteger(q.pid)&&q.pid>0&&typeof q.nonce==="string"&&/^[0-9a-f-]{36}$/.test(q.nonce)&&eq(q.started_at)&&N(q.runtime_version)}function _G(q,G){try{let J=T(q);if(!J.isDirectory()||J.uid!==process.getuid?.()||(J.mode&63)!==0)return null;let Q=rq(K(q,G),v.O_RDONLY|v.O_NOFOLLOW|v.O_NONBLOCK);try{let R=pq(Q);if(!R.isFile()||R.nlink!==1||R.uid!==process.getuid?.()||(R.mode&63)!==0||R.size>4096)return null;return g(Q,"utf8")}finally{m(Q)}}catch{return null}}function Yq(q){try{let G=JSON.parse(_G(q,"owner.json")??"null");return dG(G)?G:null}catch{return null}}function $G(q){try{return process.kill(q,0),!0}catch(G){return!(G instanceof Error&&("code"in G)&&G.code==="ESRCH")}}var bq="lease",cG=2,hG=4,s;function lG(){if(s!==void 0)return s;if(s=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let q;try{q=zG(import.meta.url)("bun:ffi")}catch{return null}let G=process.platform==="darwin"?"__error":"__errno_location",J=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let Q of J)try{let R=q.dlopen(Q,{flock:{args:[q.FFIType.i32,q.FFIType.i32],returns:q.FFIType.i32},[G]:{args:[],returns:q.FFIType.ptr}}),U=R.symbols[G]();if(U===null)continue;return s={flock:(W,Z)=>R.symbols.flock(W,Z),errno:()=>q.read.i32(U),wouldBlock:process.platform==="darwin"?35:11},s}catch{}return null}function oG(q){let G=lG();if(!G)return null;let J=rq(`${q}.lease`,v.O_RDWR|v.O_CREAT|v.O_NOFOLLOW,384);try{let Q=pq(J);if(!Q.isFile()||Q.nlink!==1||Q.uid!==process.getuid?.()||(Q.mode&63)!==0)return m(J),"busy";if(G.flock(J,cG|hG)===0)return J;let R=G.errno();return m(J),R===G.wouldBlock?"busy":null}catch(Q){throw m(J),Q}}function jq(q){y(I(q.path));let G=oG(q.path);if(G==="busy")return{acquired:!1,owner:Yq(q.path),recoveredStaleOwner:!1};let J=G!==null;try{let Q=sG(q,G);if(Q.acquired)J=!1;return Q}finally{if(J)m(G)}}function sG(q,G){let J=q.alive??$G,Q=!1;for(let R=0;R<4;R+=1){let U={schema_version:Wq,pid:q.pid??process.pid,nonce:q.nonce?.()??O(),started_at:(q.now?.()??new Date).toISOString(),runtime_version:q.runtimeVersion},W=`${q.path}.init-${process.pid}-${O()}`,Z=!1;try{if(r(W,{mode:448}),l(K(W,"owner.json"),`${JSON.stringify(U)}
|
|
8
|
+
`,{mode:384,flag:"wx"}),G!==null)l(K(W,bq),`flock
|
|
9
|
+
`,{mode:384,flag:"wx"});q.beforePublish?.();try{throw T(q.path),Object.assign(Error("Managed runtime lock exists."),{code:"EEXIST"})}catch($){if($.code!=="ENOENT")throw $}k(W,q.path),Z=!0;let _=!1;return{acquired:!0,owner:U,recoveredStaleOwner:Q,release(){if(_)return;if(_=!0,Yq(q.path)?.nonce===U.nonce)d(q.path,{recursive:!0,force:!0});if(G!==null)m(G)}}}catch(_){let $=_.code;if(!["EEXIST","ENOTEMPTY"].includes($??""))throw _;let Y=Yq(q.path),H=(q.now?.()??new Date).getTime(),j=Y&&q.staleAfterMs!==void 0?H-Date.parse(Y.started_at)<q.staleAfterMs:!1,z=Y!==null&&!(G!==null&&_G(q.path,bq)!==null)&&J(Y.pid);if(!Y||z||j)return{acquired:!1,owner:Y,recoveredStaleOwner:!1};let F=`${q.path}.stale-${process.pid}-${O()}`;try{k(q.path,F),d(F,{recursive:!0,force:!0}),Q=!0}catch(w){let a=w.code;if(!["ENOENT","EEXIST"].includes(a??""))throw w}}finally{if(!Z)d(W,{recursive:!0,force:!0})}}throw new X("lock_unavailable","Could not acquire the managed Reason runtime lock.")}var uG=20000;function i(q,G,J){if(!N(G))throw new X("invalid_version","Invalid managed Reason runtime version.");let Q=Date.now()+uG,R=jq({path:q.transitionLock,runtimeVersion:G,staleAfterMs:60000});while(!R.acquired&&Date.now()<Q)cq(100),R=jq({path:q.transitionLock,runtimeVersion:G,staleAfterMs:60000});if(!R.acquired)throw new X("transition_busy","Another managed Reason runtime transition is in progress.");try{return J()}finally{R.release()}}function xJ(q){if(!N(q.runtimeVersion))throw new X("invalid_version","Invalid managed Reason runtime version.");let G=q.paths??Dq();return jq({path:G.brokerLock,runtimeVersion:q.runtimeVersion,...q.pid===void 0?{}:{pid:q.pid},...q.now===void 0?{}:{now:q.now},...q.nonce===void 0?{}:{nonce:q.nonce},...q.alive===void 0?{}:{alive:q.alive},...q.beforePublish===void 0?{}:{beforePublish:q.beforePublish}})}function KG(q){return Aq(q)&&Bq(q,["schema_version","event_id","occurred_at","event","runtime_version"],["from_version","to_version","reason_code","duration_ms","attempt_count","retry_in_ms","capabilities"])&&q.schema_version===iq&&typeof q.event_id==="string"&&/^[0-9a-f-]{36}$/.test(q.event_id)&&eq(q.occurred_at)&&typeof q.event==="string"&&OG.includes(q.event)&&N(q.runtime_version)&&(q.from_version===void 0||N(q.from_version))&&(q.to_version===void 0||N(q.to_version))&&(q.reason_code===void 0||typeof q.reason_code==="string"&&xq.test(q.reason_code))&&(q.duration_ms===void 0||typeof q.duration_ms==="number"&&Number.isSafeInteger(q.duration_ms)&&q.duration_ms>=0&&q.duration_ms<=86400000)&&(q.attempt_count===void 0||typeof q.attempt_count==="number"&&Number.isSafeInteger(q.attempt_count)&&q.attempt_count>=1&&q.attempt_count<=1e5)&&(q.retry_in_ms===void 0||typeof q.retry_in_ms==="number"&&Number.isSafeInteger(q.retry_in_ms)&&q.retry_in_ms>=0&&q.retry_in_ms<=30000)&&(q.capabilities===void 0||Array.isArray(q.capabilities)&&q.capabilities.length<=BG&&q.capabilities.every((G)=>typeof G==="string"&&xq.test(G)))}var pG=/^(\d{22}-[0-9a-f-]{36}\.json)$/,rG=/^(\d{22}-[0-9a-f-]{36}\.json)\.sending-(\d+)-[0-9a-f-]{36}$/,nG=300000,t=0n;function iG(q){let G=BigInt(new Date(q.occurred_at).getTime())*1000000n;return t=G>t?G:t+1n,`${String(t).padStart(22,"0")}-${q.event_id}.json`}function Zq(q){try{return Iq(q.lifecycleEvents).filter((G)=>pG.test(G)).sort()}catch{return[]}}function Hq(q){try{let G=JSON.parse(g(q,"utf8"));return KG(G)?G:null}catch{return null}}function YG(q,G=$G,J=Date.now()){let Q;try{Q=Iq(q.lifecycleEvents)}catch{return}for(let R of Q){let U=R.match(rG);if(!U)continue;let W=K(q.lifecycleEvents,R),Z=K(q.lifecycleEvents,U[1]),_=!G(Number(U[2]));if(!_)try{_=J-x(W).mtimeMs>=nG}catch{continue}if(!_)continue;try{k(W,Z)}catch($){let Y=$.code;if(Y==="EEXIST")D(W);else if(Y!=="ENOENT")throw $}}}function aG(q){let J=Zq(q).flatMap((R)=>{try{return[{name:R,size:x(K(q.lifecycleEvents,R)).size}]}catch{return[]}}),Q=J.reduce((R,U)=>R+U.size,0);while(J.length>aq||Q>FG){let R=J.shift();if(!R)break;try{D(K(q.lifecycleEvents,R.name)),Q-=R.size}catch(U){if(U.code!=="ENOENT")throw U}}}function VJ(q){return YG(q),Zq(q).map((G)=>Hq(K(q.lifecycleEvents,G))).filter((G)=>G!==null).slice(-aq)}function M(q,G,J={}){let Q={schema_version:iq,event_id:J.eventId?.()??O(),occurred_at:(J.now?.()??new Date).toISOString(),...G};if(!KG(Q))throw new X("invalid_lifecycle_event","Managed runtime lifecycle event is invalid.");return y(q.lifecycleEvents),tq(K(q.lifecycleEvents,iG(Q)),`${JSON.stringify(Q)}
|
|
10
|
+
`),aG(q),Q}function PJ(q,G){if(G.length===0)return 0;let J=new Set(G),Q=0;for(let R of Zq(q)){let U=R.slice(23,-5);if(!J.has(U))continue;try{D(K(q.lifecycleEvents,R)),Q+=1}catch(W){if(W.code!=="ENOENT")throw W}}return Q}async function gJ(q,G,J){YG(q);let Q=0;for(let R of Zq(q)){let U=K(q.lifecycleEvents,R);if(J){let _=Hq(U);if(!_||!J(_))continue}let W=`${U}.sending-${process.pid}-${O()}`;try{k(U,W)}catch(_){if(_.code==="ENOENT")continue;throw _}let Z=Hq(W);if(!Z){D(W);continue}try{await G(Z),D(W),Q+=1}catch{try{k(W,U)}catch(_){if(_.code!=="ENOENT")throw _}break}}return Q}function yJ(q){let G=q.paths??Dq(),J=q.sourceExecutable??process.execPath,Q=q.sourceCredentialLibrary??Mq(I(C(J))),R=q.now?.()??new Date,U=B(S(G,q.version))&&Cq(G,q.version,q.allowDowngrade)!==null;if(!U)M(G,{event:"service.install_started",runtime_version:q.version,to_version:q.version},{now:()=>R});try{let W=g(J),Z;try{Z=g(Q)}catch{throw new X("credential_boundary_unavailable","Managed runtime credential boundary is unavailable.")}let _={url:"https://bootstrap.invalid/ara",sha256:h(W),size_bytes:W.byteLength},$={url:`https://bootstrap.invalid/${zq}`,sha256:h(Z),size_bytes:Z.byteLength},Y=JG({paths:G,version:q.version,artifact:_,bytes:W,credentialLibraryArtifact:$,credentialLibraryBytes:Z,...q.verifyCodeSignatures?{verifyCodeSignatures:q.verifyCodeSignatures}:{}}),H=oq(J);if(B(H))Nq({sourceApp:H,home:q.home??c()});let j=gG(G,q.version,{allowDowngrade:q.allowDowngrade});if(!U)$q(G);let z=q.home??c(),F=q.installLauncher===!1?"skipped":PG({paths:G,...q.launcherPath?{launcherPath:q.launcherPath}:{home:z}});if(q.installLauncher!==!1&&!q.launcherPath)RG(G,K(z,".local","bin","reason"));if(F==="conflict")M(G,{event:"service.launcher_conflict",runtime_version:q.version,to_version:q.version,reason_code:"existing_entrypoint"},{now:q.now});if(!U)M(G,{event:"service.install_completed",runtime_version:q.version,to_version:q.version,duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-R.getTime())},{now:q.now});return{installed:Y.installed,activated:j.changed,activeVersion:j.toVersion,executablePath:S(G,j.toVersion),launcher:F}}catch(W){throw M(G,{event:"service.install_failed",runtime_version:q.version,to_version:q.version,reason_code:W instanceof X?W.code:"install_failed",duration_ms:Math.max(0,(q.now?.()??new Date).getTime()-R.getTime())},{now:q.now}),W}}
|
|
11
|
+
export{Wq as L,iq as M,aq as N,FG as O,MG as P,NG as Q,IG as R,kq as S,TG as T,OG as U,Dq as V,CJ as W,S as X,n as Y,qG as Z,CG as _,SG as $,Eq as aa,u as ba,GG as ca,SJ as da,JG as ea,PG as fa,Xq as ga,L as ha,LJ as ia,wJ as ja,kJ as ka,gG as la,XG as ma,vG as na,jq as oa,xJ as pa,VJ as qa,M as ra,PJ as sa,gJ as ta,yJ as ua};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Fb as J7,Hb as f4,Ib as b4,Nb as Q7,Ob as B7,Yb as y4,ac as V7,bc as G7,cc as n4,dc as r4,fc as U7,hb as A4,hc as O8,ic as h0,jb as L2,jc as v0,kb as _4,kc as J2,lb as T4,mb as P4,nb as s6,nc as X7,ob as n6,pb as S4,qb as r6,qc as j8,rb as f3,rc as h4,sb as a6,tb as i6,tc as W7,ub as o6,vb as t6,wb as k4,xb as e6,yb as $7}from"./vm-hands-entry-lite-qbnz4h30.js";import{wc as F7,yc as N7,zc as H7}from"./vm-hands-entry-lite-22we2jrv.js";import{Ec as Z7}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as i0,Kc as o0,Rc as z0}from"./vm-hands-entry-lite-j05685sg.js";import{Sc as j1,Tc as I1,Uc as A1,Vc as _1,Wc as L0}from"./vm-hands-entry-lite-f4gvypnx.js";import{Xc as V1}from"./vm-hands-entry-lite-wry37am5.js";import{Yc as Y7}from"./vm-hands-entry-lite-wej1p1ry.js";import{ad as V2,bd as G2,cd as l3,ed as s3,gd as c3,hd as n3,ld as r3,nd as d6}from"./vm-hands-entry-lite-r5y08n0q.js";import{Ed as q7,sd as Q2,vd as z7}from"./vm-hands-entry-lite-n867d88m.js";import{$e as k6,Af as u8,Bf as d8,Ce as d,Cf as l8,De as h1,Df as s8,Ef as c8,Ff as n8,Ge as g8,Ie as m1,Ke as D6,Le as M6,Me as w6,Ne as L6,Oe as O6,Pe as j6,Qe as I6,Re as A6,Se as _6,Te as T6,Ue as P6,Ve as R6,We as z6,Xe as q6,Ye as E6,Ze as g6,_e as S6,af as f6,bf as b6,df as x6,ef as y6,ff as h6,gf as m6,hf as v6,if as p6,jf as u6,ne as P1,oe as R1,pe as S3,pf as S8,qe as F2,qf as k8,re as C6,rf as f8,se as k3,sf as b8,te as W4,tf as x8,ue as Y4,uf as y8,ve as w0,wf as h8,xf as m8,yf as v8,ze as H0,zf as p8}from"./vm-hands-entry-lite-szfy3kx7.js";import{Lf as Q6,Pf as L5,Qf as v5,Wf as E7,Zf as O5,_f as e1}from"./vm-hands-entry-lite-07er2w8q.js";import{$f as A7,ag as _7,bg as T7,fg as P7,ig as R7}from"./vm-hands-entry-lite-9z6k7898.js";import{rg as x4,yg as K7}from"./vm-hands-entry-lite-s98hjhz3.js";import{Dg as Z2}from"./vm-hands-entry-lite-3ew5ftk0.js";import{Ig as R3,Vg as l6}from"./vm-hands-entry-lite-v08mjs3f.js";import{Ri as E1,Si as c6,Ti as E4,Ui as g4}from"./vm-hands-entry-lite-1j9r1fca.js";import{Wi as P3,Yi as Q1,cj as L8,dj as D4}from"./vm-hands-entry-lite-w88zkzhr.js";import{Aj as O7,Cj as j7,Dj as I7,uj as C7,vj as D7,wj as M7,xj as w7,zj as L7}from"./vm-hands-entry-lite-ha1ej910.js";import{Oj as V}from"./vm-hands-entry-lite-kv0qat0x.js";import{Wj as C}from"./vm-hands-entry-lite-ygx9kj92.js";import{ak as W8}from"./vm-hands-entry-lite-h2xemq1f.js";import{request as i7}from"http";import{request as o7}from"https";import{lookup as t7}from"dns/promises";import{isIP as e7}from"net";async function $9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?o7:i7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:s3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var a3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),J9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function i3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(a3.has(Z))return"custom_endpoint_host_not_found";if(J9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=i3(Q,J+1);if(B)return B}return null}async function Z9($,J){let Z=i3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||e7(Q)!==0)return Z;let B;return await Promise.race([t7(Q).then(()=>!0,(G)=>!a3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?Z:"custom_endpoint_host_not_found"}function Q9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function B9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function o3($){$.signal.throwIfAborted();let J=n3.safeParse($.payload);if(!J.success)throw new C("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=r3.parse(await $.credential($.signal));if(!c3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new C("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,U=0,W=0,Y=Q9(Q.apiKey),X=B9(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()},(P)=>{$.signal.removeEventListener("abort",I),M(P)})})},H=async(N)=>{if(G+=N.length,G>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=V2){if(W>=l3)throw new C("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+V2).toString("base64")})}};try{let N=await $9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new C("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new C("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=B.headers[M];if(typeof I==="string")L[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:L});for await(let M of B){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await H(X(I))}return await H(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof C)throw N;throw new C((B?null:await Z9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as t3}from"path";function K9($,J){return $===t3(J,".ara","workspace")||$===t3(J,".reason","workspace")}function e3($,J){let Z=$.filter((Q)=>K9(Q.path,J));return Z.length===1?Z[0].path:null}var V9=/^[a-f0-9]{64}$/;var U2=32,G9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!G9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!V9.test(B)||!L1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function U9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function X9($){return U9($)??$.email.toLowerCase()}function X2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?X9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),W9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...I1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...A1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,..._1.map(($)=>`/[^/]*${n0($)}$`)],$4=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -34,7 +34,7 @@ Content-Length: 0\r
|
|
|
34
34
|
\r
|
|
35
35
|
`),s4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{K.once("error",W),K.listen(0,"127.0.0.1",()=>U())});let{port:G}=K.address();return{url:`http://127.0.0.1:${G}`,close(){K.close();for(let U of Q)U.destroy()}}}import{createHash as E2,randomUUID as e9}from"crypto";import{closeSync as J1,constants as s,fchownSync as $$,fstatSync as q0,fsyncSync as J$,linkSync as Z$,mkdirSync as Q$,openSync as Y8,readSync as F8,unlinkSync as B$,writeSync as K$}from"fs";import{platform as U8}from"os";import{getSystemErrorName as V$}from"util";var o4={type:"string",format:"uuid"},J8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,g1={type:"string",minLength:1,maxLength:4096,pattern:J8},T2=V.string().min(1).max(4096).regex(new RegExp(J8)),S1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},k1={device_id:o4,root_id:o4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},XK={read:{schema:V.object({...S1,path:T2,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:{...k1,path:g1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...S1,path:T2,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:{...k1,path:g1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...S1,command:V.string().min(1).max(16000),cwd:T2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...k1,command:{type:"string",minLength:1,maxLength:16000},cwd:g1,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}}},Y0=1073741824,e0=600000,t4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,Z8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${t4}(?:/${t4})*(?![\s\S])`,Q8=new RegExp(Z8);function B8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&Q8.test($)}var P2=V.string().min(1).max(4096).regex(Q8),R2={...g1,pattern:Z8},K8=V.string().regex(/^[a-f0-9]{64}$/),V8=V.object({kind:V.literal("workspace"),path:P2}).strict(),i9=V.discriminatedUnion("kind",[V8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:K8}).strict()]),f1=1,$1="cloud_workspace_id",z2="cloud_workspace",q2=1,o9=V.discriminatedUnion("kind",[V8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(Y0),sha256:K8}).strict()]),G8=V.object({source_version:V.literal(f1),source:o9,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(),[$1]:V.string().min(1).max(160).optional()}).strict(),WK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(f1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var e4=V.object({...S1,timeout_ms:V.number().int().min(1000).max(e0).optional(),source_path:P2,destination_path:P2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),$8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...k1,timeout_ms:{type:"integer",minimum:1000,maximum:e0},source_path:R2,destination_path:R2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},t9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:R2},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}]},YK=V.union([e4,e4.omit({source_path:!0}).extend({source:i9}).strict()]),FK={...$8,required:["device_id","root_id","destination_path"],properties:{...$8.properties,source:t9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var g2=65536;function u($){throw new C($,$)}function x1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function b1($,J,Z){if(J.throwIfAborted(),$ instanceof C||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function G$($,J,Z){let Q;switch(x1($)){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 b1($,J,Q)}function U$($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function X$(){if(U8()==="linux")return{open:(U,W,Y,X=384)=>Y8(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>Q$(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>Z$(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>B$(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(U8()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),B=$("/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}}),K=B.symbols.__error();if(K===null)return B.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=V$(-Q.i32(K));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(B.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(B.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(B.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(B.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>B.close()}}function N8($,J){let Z=q0($),Q=q0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)$$(J,Z.uid,Z.gid)}function W$($,J,Z,Q){if(!B8(Z))return u("transfer_path_invalid");let B=Z.split("/"),K=Y8(J,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW);try{for(let G of B.slice(0,-1)){let U;try{U=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW)}catch(W){if(!Q||x1(W)!=="ENOENT")throw W;try{$.mkdir(K,G)}catch(Y){if(x1(Y)!=="EEXIST")throw Y}U=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW),N8(K,U)}J1(K),K=U}return{fd:K,leaf:B.at(-1)}}catch(G){throw J1(K),G}}function X8($,J){let Z=q0($,{bigint:!0});if(!Z.isFile()||Z.size>Y0)return u("transfer_file_invalid");let Q=E2("sha256"),B=Buffer.alloc(g2),K=0;while(!0){J.throwIfAborted();let U=F8($,B,0,B.length,K);if(!U)break;if(K+=U,K>Y0)return u("transfer_size_exceeded");Q.update(B.subarray(0,U))}let G=q0($,{bigint:!0});if(BigInt(K)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:K,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=U$($.payload.url),Z=await X$(),Q,B,K;try{if(Q=W$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){B=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);let H=q0(B,{bigint:!0});if(!H.isFile()||H.size>Y0)return u("transfer_file_invalid");let N=E2("sha256"),D=0,L=B,M,I=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let O=Buffer.alloc(g2),E=F8(L,O,0,O.length,D);if(!E){v.close();return}if(D+=E,D>H.size)return u("transfer_source_changed");N.update(O.subarray(0,E)),v.enqueue(O.subarray(0,E))}catch(O){throw M=O,O}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:I,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(H.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return b1(v,$.signal,"transfer_upload_failed")}let P=q0(B,{bigint:!0});if(BigInt(D)!==H.size||P.size!==H.size||P.mtimeNs!==H.mtimeNs||P.ctimeNs!==H.ctimeNs)return u("transfer_source_changed");let j=N.digest("hex"),_=X8(B,$.signal);if(_.size_bytes!==D||_.sha256!==j)return u("transfer_source_changed");return{size_bytes:D,sha256:j,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>Y0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK)}catch(H){if(x1(H)!=="ENOENT")throw H}if(W!==void 0){try{let H=X8(W,$.signal);if(H.size_bytes===G&&H.sha256===U)return{...H,outcome:"already_present"}}finally{J1(W)}return u("transfer_destination_exists")}K=`.reason-copy-${e9()}`,B=Z.open(Q.fd,K,s.O_CREAT|s.O_EXCL|s.O_WRONLY|s.O_NOFOLLOW,384),N8(Q.fd,B);let Y;try{let H=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!H.ok||!H.body)return u("transfer_download_failed");Y=H.body.getReader()}catch(H){return b1(H,$.signal,"transfer_download_failed")}let X=E2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let H=await Y.read().catch((N)=>b1(N,$.signal,"transfer_download_failed"));if(H.done)break;if(F+=H.value.length,F>G)return u("transfer_size_mismatch");X.update(H.value);for(let N=0;N<H.value.length;)$.signal.throwIfAborted(),N+=K$(B,H.value,N,Math.min(g2,H.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return J$(B),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,K,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(B!==void 0)J1(B)}finally{try{if(Q){if(K)try{Z.unlink(Q.fd,K)}catch{}J1(Q.fd)}}finally{Z.close()}}}}catch(J){return G$(J,$.signal,$.direction)}}import{spawn as F$}from"child_process";import{mkdtempSync as N$,rmSync as H$,writeFileSync as C$}from"fs";import{constants as D$,platform as M$,tmpdir as w$}from"os";import{join as M8}from"path";import{gunzipSync as Y$,gzipSync as IK}from"zlib";var C8=900000,_K=C8+60000,Z1=49152,H8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),D8=V.object({version:V.literal(1),script_gzip:H8(163840),stdin_gzip:H8(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(C8)}).strict(),S2=V.string().max(Z1+256),TK=V.object({exit_code:V.number().int().min(0).max(255),stdout:S2,stderr:S2,combined:S2.optional()}).strict();function k2($){return Y$(Buffer.from($,"base64")).toString("utf8")}var L$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",O$=["RUSTUP_HOME","TZ","LC_ALL"],j$=2000,I$=100;function b2(){return M$()==="linux"&&process.geteuid?.()===0}function f2($){let J=Math.floor($/2),Z=[],Q=0,B=Buffer.alloc(0),K=0;return{push(G){K+=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)B=Buffer.concat([B,U]).subarray(-J)},text(){let G=K-Q-B.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
36
36
|
[reason: ${G} bytes of output omitted]
|
|
37
|
-
`:"")+B.toString("utf8")}}}async function w8($,J){if(!b2())throw new C("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new C("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=k2(Q.script_gzip),K=k2(Q.stdin_gzip)}catch{throw new C("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=N$(M8(w$(),"reason-workspace-setup-"));try{let U=M8(G,"setup.sh");C$(U,B,{mode:384});let W={PATH:L$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let _ of O$)if(process.env[_])W[_]=process.env[_];Object.assign(W,Q.env);let Y=F$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=f2(Z1),F=f2(Z1),H=f2(Z1);Y.stdout.on("data",(_)=>{X.push(_),H.push(_)}),Y.stderr.on("data",(_)=>{F.push(_),H.push(_)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(_)=>{try{if(Y.pid)process.kill(-Y.pid,_)}catch{}},D=!1,L,M=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),j$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let P=await new Promise((_,v)=>{Y.once("error",()=>v(new C("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(O,E)=>_({code:O,signal:E}))}).finally(()=>{clearTimeout(I),clearTimeout(L),J.removeEventListener("abort",M)});await new Promise((_)=>{let v=setTimeout(_,I$);Y.once("close",()=>{clearTimeout(v),_()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:P.signal?128+(D$.signals[P.signal]??0):P.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:H.text()}:{}}}finally{H$(G,{recursive:!0,force:!0})}}import{chmodSync as A$,mkdtempSync as _$,realpathSync as I8,rmSync as T$}from"fs";import{tmpdir as P$}from"os";import{dirname as R$,join as x2,sep as z$}from"path";function y2($){return j8($,O8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>R$(L8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(x2($,B));break}catch{}if(Q===void 0)throw new C("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${z$}`))throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function _8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=y2($.runtimeRoot);if(L0(Q)||L0(x2(Q,J.path)))throw new C("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=_$(x2(P$(),`reason-cloud-copy-${process.pid}-`));try{A$(Z,448);let Q=I8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let B=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new C("transfer_source_changed","The verified attachment changed before export.");return B}finally{T$(Z,{recursive:!0,force:!0})}}import{constants as _0}from"fs";import{closeSync as g7,existsSync as G0,fstatSync as S7,lstatSync as k7,mkdirSync as VQ,mkdtempSync as GQ,openSync as f7,readSync as UQ,realpathSync as U0,rmSync as XQ,statSync as D1,writeSync as WQ}from"fs";import{homedir as N1,platform as n,tmpdir as YQ}from"os";import{dirname as H1,isAbsolute as FQ,join as b7,relative as z3,resolve as NQ,sep as HQ}from"path";import{spawn as CQ}from"child_process";import{createHash as k$,randomBytes as f$}from"crypto";var h2=30000,q$=1800000,E$=5000,y1=30000,g$=m1+15000,T8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,S$=[/^\/app\/local-runtime\/operations\/claim$/,T8];class m2{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 B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(S$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},g$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,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(E$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(q$,h2*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(h1,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()+h2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.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[B,K]of Q.pending){if(!T8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(h2,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 p2=["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 oK($,J={}){let Z=b$($),Q=J.rootPathsSupported===!0?O1($.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((B)=>/^[a-f0-9]{64}$/.test(B))?{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 b$($){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 B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).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))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function x$($){return $===408||$===429||$===500||$===502||$===503||$===504}function y$($){if($ instanceof F0)return!1;if($ instanceof v1)return!0;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 h$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function m$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function tK($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return k$("sha256").update($??"").digest("hex")}function v$($){return S8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function z8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var p$=20000,u$=1e4,q8=[2000,4000],d$=30000,l$=15000;function E8($){return $?{keepalive:!1}:{}}class v2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class s${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 B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=k8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??q8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof v2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new v2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return f8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw U}finally{if(G)clearTimeout(G)}}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>=p$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,q8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=u$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=R8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>f$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(v$({method:$,route:J,timestamp:B,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:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!g8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new m2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...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&&P8(J.body)>H0)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 K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??m$,W=this.sessionFor($,J.device),Y=Math.max(d$,(J.holdMs??0)+l$),X={fresh:!1},F;for(let H=0;H<G;H+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,L=setTimeout(()=>D.abort(new v1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let I=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&H===0,H===0?J.issuedChallenge:void 0,X),P=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...I,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(X.fresh),signal:M});return await this.parseResponse(P)}catch(I){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw I}finally{clearTimeout(L)}}catch(N){if(F=N,N instanceof v1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),L=N instanceof F0&&x$(N.status),M=y$(N),I=J.transientRetryOwner!=="caller"&&(L||M);if((D||I)&&H+1<G){let P=D?0:h$(H,N,this.proofOptions.retryBaseDelayMs??500);if(P>0)await U(P,J.signal);continue}if(D&&H+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return b8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return x8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return y8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return h8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return m8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return v8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});u8(Q)}async localSubscription($,J,Z){return p8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!z8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))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}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return d8(K,p2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.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,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return l8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!z8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.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 s8(Q)}async completeOperation($,J,Z,Q){let B={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(P8(B)>H0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return n8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-j3e3zjd5.js");return Q.parse(await this.request(d.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 B=await this.request(d.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 c8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.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 c$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=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 p1($,J){if(c$.has($))return!1;if(B1.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($)||B1.has($)))return!1;return!0}import{accessSync as n$,constants as r$,existsSync as a$,statSync as i$}from"fs";import{basename as o$,isAbsolute as t$}from"path";var K1=["-lic"],e$="/bin/zsh",$J=new Set(["zsh","bash"]),r8=20000,u2=60000,JJ=65536,ZJ=64,QJ=8192,BJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),KJ=["DYLD_","LD_"];function VJ($){let J=$.toUpperCase();return BJ.has(J)||KJ.some((Z)=>J.startsWith(Z))}function a8($=process.env){return!0}function GJ($){if(!t$($)||$.includes("\x00"))return!1;if(!$J.has(o$($)))return!1;try{if(!i$($).isFile())return!1;return n$($,r$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&GJ(J))return J;return e$}function d2($=process.env){return a8($)&&a$(g0($))}function l2($=process.env){if(!a8($))throw new C("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function s2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>JJ)throw new C("invalid_payload","command is missing or too large.");return $}function c2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new C("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>ZJ)throw new C("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>QJ)throw new C("invalid_payload","env entry is invalid or too large.");if(VJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function i8($){let J=$.processEnv??process.env;if(l2(J),$.signal.aborted)throw new C("cancelled","Operation was cancelled.");let Z=s2($.command),Q=g0(J),{forwarded:B,ignored:K}=c2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});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:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function o8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.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:u2}}import{readFile as UJ,readdir as XJ,readlink as WJ,realpath as YJ}from"fs/promises";import{basename as FJ,relative as NJ,sep as HJ}from"path";var O0="/proc",CJ=250,t8=500,DJ=50,MJ=250,wJ=1024,e8=4096,LJ=1,OJ=3,$5=9,jJ="0A",IJ=/^socket:\[(\d+)\]$/,n2={readDirectory:($)=>XJ($),readLink:($)=>WJ($),readTextFile:($)=>UJ($,"utf8"),realPath:($)=>YJ($)};function Z5($,J){return J===$||J.startsWith(`${$}${HJ}`)}function AJ($,J){return NJ($,J)||"."}async function Q5($){let J;try{J=await $.readDirectory(O0)}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 B5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,e8).split(`
|
|
37
|
+
`:"")+B.toString("utf8")}}}async function w8($,J){if(!b2())throw new C("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new C("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=k2(Q.script_gzip),K=k2(Q.stdin_gzip)}catch{throw new C("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=N$(M8(w$(),"reason-workspace-setup-"));try{let U=M8(G,"setup.sh");C$(U,B,{mode:384});let W={PATH:L$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let _ of O$)if(process.env[_])W[_]=process.env[_];Object.assign(W,Q.env);let Y=F$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=f2(Z1),F=f2(Z1),H=f2(Z1);Y.stdout.on("data",(_)=>{X.push(_),H.push(_)}),Y.stderr.on("data",(_)=>{F.push(_),H.push(_)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(_)=>{try{if(Y.pid)process.kill(-Y.pid,_)}catch{}},D=!1,L,M=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),j$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let P=await new Promise((_,v)=>{Y.once("error",()=>v(new C("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(O,E)=>_({code:O,signal:E}))}).finally(()=>{clearTimeout(I),clearTimeout(L),J.removeEventListener("abort",M)});await new Promise((_)=>{let v=setTimeout(_,I$);Y.once("close",()=>{clearTimeout(v),_()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:P.signal?128+(D$.signals[P.signal]??0):P.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:H.text()}:{}}}finally{H$(G,{recursive:!0,force:!0})}}import{chmodSync as A$,mkdtempSync as _$,realpathSync as I8,rmSync as T$}from"fs";import{tmpdir as P$}from"os";import{dirname as R$,join as x2,sep as z$}from"path";function y2($){return j8($,O8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>R$(L8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(x2($,B));break}catch{}if(Q===void 0)throw new C("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${z$}`))throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function _8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=y2($.runtimeRoot);if(L0(Q)||L0(x2(Q,J.path)))throw new C("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=_$(x2(P$(),`reason-cloud-copy-${process.pid}-`));try{A$(Z,448);let Q=I8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let B=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new C("transfer_source_changed","The verified attachment changed before export.");return B}finally{T$(Z,{recursive:!0,force:!0})}}import{constants as _0}from"fs";import{closeSync as g7,existsSync as G0,fstatSync as S7,lstatSync as k7,mkdirSync as VQ,mkdtempSync as GQ,openSync as f7,readSync as UQ,realpathSync as U0,rmSync as XQ,statSync as D1,writeSync as WQ}from"fs";import{homedir as N1,platform as n,tmpdir as YQ}from"os";import{dirname as H1,isAbsolute as FQ,join as b7,relative as z3,resolve as NQ,sep as HQ}from"path";import{spawn as CQ}from"child_process";import{createHash as k$,randomBytes as f$}from"crypto";var h2=30000,q$=1800000,E$=5000,y1=30000,g$=m1+15000,T8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,S$=[/^\/app\/local-runtime\/operations\/claim$/,T8];class m2{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 B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(S$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},g$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,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(E$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(q$,h2*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(h1,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()+h2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.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[B,K]of Q.pending){if(!T8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(h2,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 p2=["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 oK($,J={}){let Z=b$($),Q=J.rootPathsSupported===!0?O1($.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((B)=>/^[a-f0-9]{64}$/.test(B))?{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 b$($){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 B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).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))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function x$($){return $===408||$===429||$===500||$===502||$===503||$===504}function y$($){if($ instanceof F0)return!1;if($ instanceof v1)return!0;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 h$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function m$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function tK($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return k$("sha256").update($??"").digest("hex")}function v$($){return S8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function z8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var p$=20000,u$=1e4,q8=[2000,4000],d$=30000,l$=15000;function E8($){return $?{keepalive:!1}:{}}class v2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class s${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 B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=k8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??q8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof v2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new v2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return f8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw U}finally{if(G)clearTimeout(G)}}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>=p$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,q8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=u$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=R8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>f$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(v$({method:$,route:J,timestamp:B,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:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!g8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new m2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...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&&P8(J.body)>H0)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 K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??m$,W=this.sessionFor($,J.device),Y=Math.max(d$,(J.holdMs??0)+l$),X={fresh:!1},F;for(let H=0;H<G;H+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,L=setTimeout(()=>D.abort(new v1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let I=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&H===0,H===0?J.issuedChallenge:void 0,X),P=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...I,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(X.fresh),signal:M});return await this.parseResponse(P)}catch(I){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw I}finally{clearTimeout(L)}}catch(N){if(F=N,N instanceof v1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),L=N instanceof F0&&x$(N.status),M=y$(N),I=J.transientRetryOwner!=="caller"&&(L||M);if((D||I)&&H+1<G){let P=D?0:h$(H,N,this.proofOptions.retryBaseDelayMs??500);if(P>0)await U(P,J.signal);continue}if(D&&H+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return b8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return x8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return y8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return h8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return m8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return v8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});u8(Q)}async localSubscription($,J,Z){return p8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!z8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))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}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return d8(K,p2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.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,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return l8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!z8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.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 s8(Q)}async completeOperation($,J,Z,Q){let B={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(P8(B)>H0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return n8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-bsanzqj2.js");return Q.parse(await this.request(d.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 B=await this.request(d.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 c8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.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 c$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=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 p1($,J){if(c$.has($))return!1;if(B1.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($)||B1.has($)))return!1;return!0}import{accessSync as n$,constants as r$,existsSync as a$,statSync as i$}from"fs";import{basename as o$,isAbsolute as t$}from"path";var K1=["-lic"],e$="/bin/zsh",$J=new Set(["zsh","bash"]),r8=20000,u2=60000,JJ=65536,ZJ=64,QJ=8192,BJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),KJ=["DYLD_","LD_"];function VJ($){let J=$.toUpperCase();return BJ.has(J)||KJ.some((Z)=>J.startsWith(Z))}function a8($=process.env){return!0}function GJ($){if(!t$($)||$.includes("\x00"))return!1;if(!$J.has(o$($)))return!1;try{if(!i$($).isFile())return!1;return n$($,r$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&GJ(J))return J;return e$}function d2($=process.env){return a8($)&&a$(g0($))}function l2($=process.env){if(!a8($))throw new C("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function s2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>JJ)throw new C("invalid_payload","command is missing or too large.");return $}function c2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new C("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>ZJ)throw new C("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>QJ)throw new C("invalid_payload","env entry is invalid or too large.");if(VJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function i8($){let J=$.processEnv??process.env;if(l2(J),$.signal.aborted)throw new C("cancelled","Operation was cancelled.");let Z=s2($.command),Q=g0(J),{forwarded:B,ignored:K}=c2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});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:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function o8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.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:u2}}import{readFile as UJ,readdir as XJ,readlink as WJ,realpath as YJ}from"fs/promises";import{basename as FJ,relative as NJ,sep as HJ}from"path";var O0="/proc",CJ=250,t8=500,DJ=50,MJ=250,wJ=1024,e8=4096,LJ=1,OJ=3,$5=9,jJ="0A",IJ=/^socket:\[(\d+)\]$/,n2={readDirectory:($)=>XJ($),readLink:($)=>WJ($),readTextFile:($)=>UJ($,"utf8"),realPath:($)=>YJ($)};function Z5($,J){return J===$||J.startsWith(`${$}${HJ}`)}function AJ($,J){return NJ($,J)||"."}async function Q5($){let J;try{J=await $.readDirectory(O0)}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 B5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,e8).split(`
|
|
38
38
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,e8).split("\x00",1)[0]?.trim();return Q?FJ(Q):null}catch{return null}}async function K5($,J=n2){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function V5($,J=n2){let Z=[];for(let Q of await Q5(J)){if(Z.length>=CJ)break;let B=await K5(Q,J);if(!B||!Z5($,B))continue;Z.push({pid:Q,command:await B5(Q,J),cwd:AJ($,B)})}return{processes:Z}}function J5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function _J($){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,B=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(B<0)B=W;continue}if(B>=0){let Y=W-B;if(Y>Q)Z=B,Q=Y;B=-1}}let K=J.map((W)=>W.toString(16));if(Q<2)return K.join(":");let G=K.slice(0,Z).join(":"),U=K.slice(Z+Q).join(":");return`${G}::${U}`}function TJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=J5($);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(...J5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${_J(Z)}]:${J}`}return null}function PJ($,J){let Z=[];for(let Q of $.split(`
|
|
39
39
|
`).slice(1)){if(Z.length>=J)break;let B=Q.trim().split(/\s+/);if(B.length<=$5)continue;if(B[OJ]?.toUpperCase()!==jJ)continue;let K=B[LJ]??"",G=K.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(K.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=TJ(K.slice(0,G),U),Y=B[$5];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function RJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=t8)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...PJ(Q,t8-J.length))}return J}async function zJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await Q5(J)){if(Z.size>=$.size)break;let B;try{B=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let K of B.slice(0,wJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${K}`)}catch{continue}let U=G.match(IJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function G5($,J=n2){let Z=await RJ(J),Q=await zJ(new Set(Z.map((X)=>X.inode)),J),B=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;B.push({pid:F,port:X.port,address:X.address})}B.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let K=[...new Set(B.map((X)=>X.pid))].slice(0,DJ),G=await Promise.all(K.map(async(X)=>[X,await K5(X,J)])),U=new Map(G),W=B.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&Z5($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await B5(X,J)])));return{ports:W.slice(0,MJ).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as a2}from"path";var u1=200,qJ=250,EJ=250;async function d1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new C("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],B=null;for(let K of Z.stdout.split(/\r?\n/))if(K.startsWith("p")){let G=Number(K.slice(1));if(B=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,B)Q.push(B)}else if(B&&K.startsWith("c"))B.command=K.slice(1)||null;else if(B&&K.startsWith("n"))B.names.push(K.slice(1));return Q}function r2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var U5="/System/Volumes/Data",gJ=["/tmp","/var","/etc"];function i2($){let J=a2.normalize($);if(J.startsWith(`${U5}/`))J=J.slice(U5.length);return gJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function X5($){return $&&a2.isAbsolute($)?i2($):null}async function W5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=u1){let B=J.slice(Q,Q+u1).join(",");for(let K of await d1($,["-a","-p",B,"-d","cwd","-Fpcn"]))Z.set(K.pid,{command:K.command,cwd:X5(K.names[0])})}return Z}async function Y5($,J){let Z=i2($),Q=(await d1(J,["-d","cwd","-Fpn"])).filter((K)=>{let G=X5(K.names[0]);return G!==null&&r2(Z,G)}).map((K)=>K.pid).slice(0,qJ),B=await W5(J,Q);return{processes:Q.flatMap((K)=>{let G=B.get(K);return G?.cwd&&r2(Z,G.cwd)?[{pid:K,command:G.command,cwd:a2.relative(Z,G.cwd)||"."}]:[]})}}async function F5($,J){let Z=i2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],B=await d1(J,Q),K=await W5(J,B.map((Y)=>Y.pid)),G=B.map((Y)=>Y.pid).filter((Y)=>{let X=K.get(Y)?.cwd;return Boolean(X&&r2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(B.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=u1){let X=G.slice(Y,Y+u1).join(",");for(let F of await d1(J,["-a","-p",X,...Q]))for(let H of F.names)if(U.has(`${F.pid} ${H}`))W.push({pid:F.pid,command:F.command,address:H})}return{ports:W.slice(0,EJ)}}import{join as lJ}from"path";import{spawn as hJ}from"child_process";import{randomUUID as mJ}from"crypto";import{chmodSync as C5,lstatSync as D5,mkdirSync as vJ,readdirSync as pJ,statSync as uJ,unlinkSync as dJ}from"fs";import{join as t2}from"path";var o2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var l1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var j0=()=>{throw Error("proof_visual_contract_invalid")};class N5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function kJ($){if(!V1($)||$.version!==1)return j0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new N5;if(!V1($.viewport)||!l1($.viewport.width,1,4096)||!l1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>o2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return j0();let J=$.targets.map((Q)=>{if(!V1(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((B)=>!["id","selector"].includes(B)))return j0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return j0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return j0();Z=$.additionalViewports.map((B)=>{if(!V1(B)||!l1(B.width,1,4096)||!Number.isInteger(B.width)||!l1(B.height,1,4096)||!Number.isInteger(B.height)||Object.keys(B).some((K)=>!["width","height"].includes(K)))return j0();return{width:B.width,height:B.height}});let Q=[$.viewport,...Z].map((B)=>`${B.width}x${B.height}`);if(new Set(Q).size!==Q.length)return j0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var bJ=["organizationId","userId","sessionId","runId"],xJ=[...bJ,"prUrl","headSha","skillDigest","evidenceKind"],MV=[...xJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var yJ={"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 H5($){return yJ[$].directory}var M5=10485760;function w5($={}){let J=$.directory??H5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let B=Q?.seconds;if(!Number.isInteger(B)||Number(B)<1||Number(B)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");vJ(J,{recursive:!0,mode:457});let K=D5(J);if(!K.isDirectory()||K.isSymbolicLink()||K.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");C5(J,457);let G=pJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:uJ(t2(J,M)).mtimeMs})).sort((M,I)=>I.time-M.time);for(let M of G.slice(9))dJ(t2(J,M.name));let U=t2(J,`${mJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??hJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(B),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(M5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,H=!1,N=new Promise((M,I)=>{X=M,F=I});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))H=!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",(P)=>{try{if(P!==0&&P!==255)throw Error();let j=D5(U);if(!H||!j.isFile()||j.isSymbolicLink()||j.uid!==process.getuid?.()||j.size<128||j.size>M5+65536)throw Error();C5(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(B)+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(B)}},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 j5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??L5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let B=lJ($.runtimeDirectory,"recordings"),K=null;return{async start(G){let U=await(J.desktop??O5)();return K??=w5({directory:B,display:U.display,ffmpeg:Q,env:{HOME:E1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),K.start(G)},async stop(){if(!K)throw Error("cloud_browser_recording_not_started");return K.stop()},async close(){await K?.close()}}}import{spawn as M3}from"child_process";import{createHash as VZ,randomUUID as GZ}from"crypto";import{existsSync as Q0,mkdirSync as F3,mkdtempSync as w3,readdirSync as t1,readFileSync as L3,renameSync as UZ,rmSync as X1,statSync as r1,writeFileSync as XZ}from"fs";import{homedir as O3,tmpdir as p5}from"os";import{basename as u5,dirname as N3,join as g,relative as d5,resolve as H3,sep as l5}from"path";var i=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),s1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),I5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),$3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),J3=["home","lock","side_button","siri","apple_pay"],sJ=V.enum(["tree","screenshot","both","none"]),cJ=V.object({...$3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:sJ.optional(),wait_for:cJ.optional(),timeout:V.number().min(0).max(20).optional()},e2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...$3.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(J3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),Z3=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:s1.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:s1.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(()=>e2)).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:s1.optional(),bundle_id:I5.optional(),steps:V.array(V.lazy(()=>e2)).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:I5}).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:s1.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(),...$3.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(J3),...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(e2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),A5=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(),xV=V.object({text:V.string(),error:V.string().optional(),device:A5.optional(),devices:V.array(A5).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 yV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),hV={type:"object",properties:{action:{type:"string",enum:Z3.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:[...J3]},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 V3}from"child_process";import{createHash as rJ}from"crypto";import{existsSync as B3,mkdirSync as c1,mkdtempSync as aJ,readdirSync as _5,readFileSync as T5,renameSync as iJ,rmSync as P5,symlinkSync as K3,writeFileSync as G1}from"fs";import{homedir as oJ}from"os";import{dirname as E5,join as f}from"path";import{createInterface as tJ}from"readline";var Q3=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
40
40
|
//
|
|
@@ -537,4 +537,4 @@ function run(argv) {
|
|
|
537
537
|
`:U>=32&&U<=126?String.fromCharCode(U):null;if(W===null)return;Q+=W,clearTimeout(B),B=setTimeout(()=>{let Y=Q;Q="",K({action:"type",text:Y})},250)},clipboard(G){V6($,G)},close(){clearTimeout(B),Z=null}}}function BQ($,J,Z){return new Promise((Q,B)=>{let K=B6($,J,{stdio:"ignore",signal:Z});K.once("error",B),K.once("exit",(G)=>Q(G??-1))})}async function KQ($,J){let Z=nZ($6(iZ(),"reason-simulator-stream-"));try{let Q=$6(Z,"screen.png");if(await BQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new C("simulator_not_booted","That simulator is not booted.");let B=rZ(Q).subarray(16,24);return{width:B.readUInt32BE(0),height:B.readUInt32BE(4)}}finally{aZ(Z,{recursive:!0,force:!0})}}async function G6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!oZ.test(Z)||!Q.video)throw new C("invalid_display_request","Reason simulator stream request is malformed.");let B=await s5().catch(()=>{throw new C("simulator_axe_missing","AXe could not be installed on this Mac.")}),K=await Y1({payload:{action:"screenshot",device:Z},root:$.root});if(K.error||!K.image)throw new C("simulator_not_booted","That simulator is not booted.");let G={width:K.image.width,height:K.image.height},U=await G3(B),W=U?await n1(B,Z,!0):null,Y=U?null:await Q6();if(!U&&!Y)throw new C("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let X={kind:"simulator",udid:Z,axe:B,points:G,sound:null,size:U?G:await KQ(Z,$.signal),stream:U?(F,H,N)=>S5(U,Z,Math.min(F,60),N,H):null,input:W?ZQ(Z,W):QQ(Z,$.root)};return await e1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...Y?{ffmpeg:()=>Y}:{}}})}var x7=131072,DQ=131072,MQ=128,y7=8192,b3=30000,x3=15000,wQ=/^[a-z][a-z0-9_]{0,63}$/,LQ=new Set(["jobs.control","fs.read","fs.write"]),U6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function $2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function X6($){return $.map($2).join("/")}function T3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var OQ=[...T3(j1,4).map(($)=>`/(${$.map(X6).join("|")})(/|$)`),...T3(I1,4).map(($)=>`/(${$.map(X6).join("|")})$`),...T3([...A1],6).map(($)=>`/(${$.map($2).join("|")})$`),`/${$2(".env")}\\.[^/]+$`,`/[^/]+(${_1.map($2).join("|")})$`],q3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),h7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function m7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function jQ($){return Y7($)}function E3(){if(n()==="darwin")return G0("/usr/bin/sandbox-exec");if(n()==="linux")return F7();return!1}function W6(){if(n()==="linux")return G0("/proc");if(!E3())return!1;if(n()==="darwin")return G0("/usr/sbin/lsof");return!1}function v7(){return n()==="darwin"?"/bin/zsh":N7()}function g3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function IQ($){if(!g3($))throw new C("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>H0)throw new C("payload_too_large","Operation payload exceeds 256 KB.");return $}function d0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new C("invalid_payload",`${J} must be a string.`);return Z}function B2($,J,Z=y7){let Q=d0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new C("invalid_payload",`${J} is missing or too large.`);return Q}function AQ($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new C("invalid_payload",`${J} is missing or too large.`);return Q}function C1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new C("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function p0($,J){return J===$||J.startsWith(`${$}${HQ}`)}function m0($){if(L0($))throw new C("protected_path","Credential and secret paths are unavailable to local tasks.")}function h($){let J;try{J=U0($.path)}catch(Z){if(process.platform==="darwin"&&V7(Z))throw G7($.path);throw new C("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!D1(J).isDirectory())throw new C("root_changed","The granted root changed after registration.");return m0(J),J}function y3($,J="."){if(!J||J.includes("\x00")||FQ(J))throw new C("path_outside_root","Paths must be relative to the granted root.");let Z=NQ($,J);if(!p0($,Z))throw new C("path_outside_root","Path escapes the granted root.");return Z}function u0($,J=".",Z=!1){let Q=y3($,J),B;try{B=U0(Q)}catch(K){if(l7(K))throw s7();throw new C("path_not_found","Path does not exist.")}if(!p0($,B))throw new C("symlink_escape","Path resolves outside the granted root.");if(!Z)m0(B);return B}function _Q($,J){let Z=y3($,J);if(m0(Z),G0(Z)){let K=U0(Z);if(!p0($,K))throw new C("symlink_escape","Write target resolves outside the granted root.");if(k7(Z).isSymbolicLink())throw new C("symlink_escape","Writing through a symlink is not allowed.");return m0(K),K}let Q=H1(Z);while(!G0(Q)){let K=H1(Q);if(K===Q)throw new C("path_outside_root","No safe write parent.");Q=K}let B=U0(Q);if(!p0($,B))throw new C("symlink_escape","Write parent resolves outside the granted root.");return m0(B),Z}function p7($,J){return z3($,J)||"."}function TQ($,J=x7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function u7($,J){return{...Z7({home:$,temporaryDirectory:J}),ZDOTDIR:J,BASH_ENV:"/dev/null",ENV:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}function PQ($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...OQ.map((B)=>`(deny file-read* file-write* (regex #"${B}"))`),"(deny network*)"].join(`
|
|
538
538
|
`)}async function h3($,J,Z){return new Promise((Q,B)=>{let K="",G="",U=!1,W=!1,Y=!1,X;try{X=CQ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],detached:!0})}catch(L){B(L);return}let F=(L,M)=>{if(Y)return;Y=!0,clearTimeout(D),Z.signal.removeEventListener("abort",N),Q({exitCode:L,signal:M,stdout:K,stderr:G,timedOut:W,truncated:U})},H=(L,M)=>{let I=`${L}${String(M)}`,P=TQ(I);return U||=P.truncated,P.value};X.stdout.on("data",(L)=>{K=H(K,L)}),X.stderr.on("data",(L)=>{G=H(G,L)}),X.once("error",B),X.once("exit",F);let N=()=>{try{X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",N,{once:!0});let D=setTimeout(()=>{W=!0,N()},Z.timeoutMs)})}var Y6=null;function RQ(){return Y6??=H7({scrubEnvironment:u7,spawnCaptured:h3,isProtectedPath:L0}),Y6}var zQ=async($,J,Z)=>{if(n()==="linux")return RQ()($,J,Z);if(n()!=="darwin"||!G0("/usr/bin/sandbox-exec"))throw new C("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=GQ(b7(YQ(),"reason-device-"));try{return await h3("/usr/bin/sandbox-exec",["-p",PQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:u7(Z.root,Q)})}finally{XQ(Q,{recursive:!0,force:!0})}};function qQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>MQ)throw new C("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>y7)throw new C("invalid_payload","Command argument is invalid or too large.");return Z})}async function d7($,J,Z,Q={}){if($.signal.aborted)throw new C("cancelled","Operation was cancelled.");let B=h($.root),K=Q.cwd??B,G=await $.runCommand(J,Z,{cwd:K,root:B,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??x3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function l7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var s7=()=>new C("path_unreadable","The path is not readable.");function EQ($){try{return f7($,_0.O_RDONLY)}catch(J){throw l7(J)?s7():J}}function F6($,J){let Z=v0()?Z2():null;return Z?Q2(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):gQ($,J)}function gQ($,J){return $==="fs.read"?SQ(J):fQ(J)}async function SQ($){let J=h($.root),Z=u0(J,B2($.payload,"path"));if(!D1(Z).isFile())throw new C("not_a_file","Read target is not a file.");let Q=C1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),B=C1($.payload.max_bytes,65536,1,x7),K=d0($.payload,"encoding");if(K!==void 0&&K!=="base64")throw new C("invalid_payload","encoding must be base64.");let G=EQ(Z),U,W;try{U=S7(G).size;let X=Buffer.alloc(Math.max(0,Math.min(B,U-Q)));W=X.subarray(0,X.byteLength?UQ(G,X,0,X.byteLength,Q):0)}finally{g7(G)}let Y=K==="base64"||W.includes(0);return{path:p7(J,Z),content:Y?W.toString("base64"):W.toString("utf8"),encoding:Y?"base64":"utf8",offset:Q,bytes:W.byteLength,size:U,truncated:Q+W.byteLength<U}}function kQ($,J){let Z=$==="append"?_0.O_APPEND:_0.O_TRUNC;return _0.O_WRONLY|_0.O_NOFOLLOW|Z|(J?0:_0.O_CREAT|_0.O_EXCL)}async function fQ($){let J=h($.root),Z=B2($.payload,"path"),Q=AQ($.payload,"content",DQ),B=d0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(B))throw new C("invalid_payload","mode must be create, overwrite, or append.");let K=_Q(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){VQ(H1(K),{recursive:!0,mode:448});let Y=U0(H1(K));if(!p0(J,Y))throw new C("symlink_escape","Write parent escaped root.")}if(!G0(H1(K)))throw new C("path_not_found","Write parent does not exist.");if(B==="create"&&G0(K))throw new C("path_exists","Create mode will not overwrite an existing file.");let G=G0(K),U=G?k7(K):null,W=f7(K,kQ(B,G),384);try{if(U){let Y=S7(W);if(Y.ino!==U.ino||Y.dev!==U.dev)throw new C("symlink_escape","The write target changed between validation and opening.")}WQ(W,Q,null,"utf8")}finally{g7(W)}return{path:p7(J,K),bytes_written:Buffer.byteLength(Q,"utf8"),mode:B}}async function bQ($){let J=h($.root),Z=B2($.payload,"command",65536),Q=u0(J,d0($.payload,"cwd")??".");if(!D1(Q).isDirectory())throw new C("invalid_cwd","cwd is not a directory.");let B=C1($.payload.timeout_ms,x3,100,b3);return d7($,v7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:B})}async function xQ($){let J=I4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:n()!=="darwin"))throw new C("preview_unavailable","Preview servers are unavailable on this computer.");let Q=h($.root),B=c6(Q,J.data.workspace),K=B.boundary===Q?Q:u0(B.anchor,z3(B.anchor,B.boundary)||"."),G=u0(K,z3(K,B.path)||".");if(!D1(G).isDirectory())throw new C("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+w4);if(!(U>Date.now()))throw new C("process_authority_lost","The preview server lease is unavailable.");let W=(I)=>$.emit("progress",{process:I});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new C("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await A2({claim:$.claim,root:K,cwd:G,command:J.data.command,mode:"host",shell:g0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:W})}}let Y={directory:b7(Z.runtimeDirectory,"processes")},X={deniedPorts:s6([$.apiOrigin])},F=Q7(),H=B7(),N=v0(),D=J.data.egress?J2(N):null;if(J.data.egress&&(D===null||!h0(Z.executionMode==="unsandboxed")))throw new C("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let L=J.data.egress?await i4(J.data.egress.allowed_domains):null,M=L?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((I)=>`${I}=${L.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
|
|
539
539
|
`):J.data.command;try{return{...await A2({claim:$.claim,root:G,cwd:G,command:M,mode:"host",shell:H,expiresAtMs:U,signal:$.signal,emit:W,...N?{jobsUser:{...N,...D!==null?{modelGid:D}:{}}}:{},environment:{...F.variables,HOME:F.home,PATH:F.path,TMPDIR:F.temporaryDirectory,SHELL:H},journals:Y,preview:X})}}finally{L?.close()}}async function yQ($){l2();let J=h($.root),Z=s2($.payload.command),Q=u0(J,d0($.payload,"cwd")??".");if(!D1(Q).isDirectory())throw new C("invalid_cwd","cwd is not a directory.");let B=C1($.payload.timeout_ms,r8,100,u2),{ignored:K}=c2($.payload.env);return await $.emit("progress",{shell:g0(),shell_flags:[...K1],sandbox:"none",ignored_env:K}),i8({command:Z,cwd:Q,timeoutMs:B,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function hQ($){let J=h($.root),Z=qQ($.payload),Q=Z[0];if(!Q||!h7.has(Q)&&!q3.has(Q))throw new C("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new C("git_argument_not_allowed","Git path/config overrides are not allowed.");let B=q3.has(Q);if(B&&!$.root.permissions.write)throw new C("permission_denied","Mutating Git commands require the write grant.");let K=u0(J,d0($.payload,"cwd")??".");return d7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:K,allowWrite:B,timeoutMs:C1($.payload.timeout_ms,x3,100,b3)})}function c7($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new C("cancelled","Operation was cancelled.");return Q}}async function mQ($){let J=h($.root);if(n()==="linux")return V5(J);return Y5(J,c7($,J))}async function vQ($){let J=h($.root);if(n()==="linux")return G5(J);return F5(J,c7($,J))}async function pQ($){let J=$.worker?j5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&m3({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},...$.worker.ownComputer?{ownComputer:!0}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:h($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(B,K,G)=>$.emit(B,K,G)})}async function uQ($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new C("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=n6($.payload,$.operationId);return o6({root:h($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,B)=>$.emit(Q,B)})}return $.runPtySession({root:h($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function N6($,J){let Z=v0()?Z2():null;return Z?Q2(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):dQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function dQ($,J){let Z=h(J.root),Q=$1 in J.payload;if(Q&&!J.worker)throw new C("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let B=Q?A8(Z,J.payload[$1]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new C("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let U=G8.safeParse(J.payload);if(!U.success)throw new C("invalid_payload","Invalid Cloud export request.");return _8({runtimeRoot:B,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let K=B2(J.payload,"path",4096),G=$==="import"&&Q?y2(B):B;return m0(y3(G,K)),E0({direction:$,root:G,path:K,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var n7={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new C("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return o3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>F6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>F6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>N6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>N6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>n()==="darwin"&&d2(),execute:xQ},"exec.run":{requiredPermission:"execute",available:E3,execute:bQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>d2(),execute:yQ},"git.run":{requiredPermission:"execute",available:()=>E3()&&jQ("git"),execute:hQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:W6,execute:mQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:W6,execute:vQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>n()==="darwin"||Boolean(U7()),execute:pQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:P7,execute:uQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:E7,execute:($)=>{let J=Z2();return J?Q2(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??K7)()},$.signal):e1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>z7(),execute:($)=>q7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:W1,execute:($)=>Y1({payload:$.payload,root:h($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:K6,execute:($)=>G6({payload:$.payload,root:h($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>t6({root:h($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>n()==="darwin"?G0("/usr/bin/sandbox-exec"):n()==="linux",execute:async($)=>{let J=P1.parse($.payload),Z=k3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!w0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return e6({root:h($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>F4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>f3({root:h($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new C("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>a6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>i6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:b2,execute:($)=>w8($.payload,$.signal)}};function lQ($,J){try{let Z=e3($,U0(J)),Q=Z?$.find((B)=>B.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function sQ($,J){try{let Z=U0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function cQ($,J){try{let Z=U0(J),Q=$.find((B)=>B.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function nQ($,J){try{let Z=U0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&p0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function rQ($,J){try{return O1({home:U0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&L1(Z.path)).slice(0,U2).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function MU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||n()==="darwin",B=Q?cQ($,N1()):void 0,K=!J.worker&&n()==="darwin"?lQ($,N1()):void 0,G=Q?sQ($,N1()):void 0,U=!J.worker&&n()==="darwin"?nQ($,N1()):void 0,W=Q?rQ($,N1()):void 0,Y=p2.filter((X)=>{if(B1.has(X)&&!J.worker)return!1;if(J.worker&&!p1(X,J.worker))return!1;let F=n7[X];if(!F)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:F.available?.()??!0)&&$.some((N)=>(!J.worker||X!=="pty.start"||N.permissions.read&&N.permissions.write)&&m7(F).every((D)=>N.permissions[D]))});return{supported_operations:Y,...B?{account_root_fingerprint:B}:{},...K?{workspace_root_fingerprint:K}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...W?{root_paths:W}:{},...Y.includes("hands.connect")?{hands_worker_artifact_sha256:z0,hands_worker_entrypoint:o0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:H0,max_result_bytes:H0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":H2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:v7(),sandbox:n()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:b3},...Y.includes("exec.full")?{"exec.full":o8()}:{},"git.run":{read_only_subcommands:[...h7].sort(),mutating_subcommands:[...q3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:e0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:e0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:i0,protocol_version:R3,worker_artifact_sha256:z0,worker_entrypoint:o0,policy_mode:"full_access",policy_version:1,workspace_base:P3,workspace_layout:Q1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":n()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...Y.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:T7,max_session_ms:A7,max_buffered_output_bytes:_7}}:{},...J.worker?Object.fromEntries(Y.filter((X)=>X!=="browser.pr-proof.v1").map((X)=>[X,{ready:J.worker?.readiness?.[X]===!0,...J.worker?.readiness?.[X]!==!0&&J.worker?.probing?.includes(X)?{probing:!0}:{},execution_mode:p1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:l6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!v0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:b6,...J.worker?.ownComputer?{[x6]:y6}:{},workspace_base:P3,workspace_layout:Q1,browser_state:"optional_headless",desktop:!1,worker_version:i0,protocol_version:R3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:D6,[L6]:w6}:{},...J.worker?{[j6]:O6}:{},...J.worker?.handsBrowser?{[P6]:T6}:{},[_6]:A6,[z6]:R6,...h0(J.worker?.executionMode==="unsandboxed")?{[E6]:q6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&J2()!==null?{[S6]:g6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&v0()?{[f6]:k6}:{}}:{},...X==="fs.export"?{cloud_source_version:f1,source_kinds:["workspace","attachment"],[z2]:q2}:{},...X==="fs.import"?{[z2]:q2}:{},...X===M4&&J2()!==null&&h0(J.worker?.executionMode==="unsandboxed")?{[j4]:M2}:{},...X==="tunnel.open"?{carried_jobs:h6}:{},...X==="jobs.control"?{[v6]:m6}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[D7]:C7,[w7]:M7.join(","),[L7]:O7,[j7]:I7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[p6]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[u6]:!0}:{}}])):{}}}}function m3($,J,Z,Q,B){let K=J7.safeParse(Q);return K.success&&B!==void 0&&B.device_id===$.deviceId&&K.data.device_id===$.deviceId&&K.data.root_id===J&&K.data.run_id===Z&&K.data.binding.kind===B.binding&&K.data.binding.target_revision===B.target_revision&&K.data.binding.root_grant_revision===B.root_grant_revision&&K.data.binding.target_generation===B.target_generation&&K.data.binding.target_fence_id===B.target_fence_id}async function wU($,J,Z,Q,B){if(J.capability!=="hands.connect"||Z.kind!==M6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let K=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof K!=="string"||Object.keys(Z.payload).length!==2)throw new C("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((Y)=>Y.id===J.root_id);if(!G)throw new C("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,K,B);if(!m3($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==K)throw new C("environment_unavailable","The delivered environment does not match this Hands.");let W=f3({root:h(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:W.snapshot_id,installed_revision:W.installed_revision,installed:!0},B),!0}async function LU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==I6)return!1;let{version:B,run_id:K,target_generation:G,target_fence_id:U}=Z.payload;if(B!==1||Object.keys(Z.payload).length!==4||typeof K!=="string"||typeof G!=="number"||typeof U!=="string")throw new C("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let W=$.roots.find((Y)=>Y.id===J.root_id);if(!W)throw new C("root_not_granted","The Hands root is no longer granted.");return await r6({operationId:J.operation_id,root:h(W),runId:K,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function OU($,J,Z){if(J.capability!=="github.local.v1")return H6($,J,Z);try{let Q=await H6($,J,Z);if(Q.status==="succeeded"||S3(J.payload,Q.status,Q.error_code))return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function H6($,J,Z){if(B1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!p1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=k3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=n7[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let B=$.roots.find((X)=>X.id===J.root_id);if(!B)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&g3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&$1 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!m3($,B.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(m7(Q).some((X)=>!B.permissions[X]))return{status:"failed",error_code:"permission_denied"};let K=0,G=async(X,F,H)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:K++,kind:X,capability:J.capability,data:F,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&H?{deliverySignal:H}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||LQ.has(J.capability)||J.capability==="pty.start",W,Y=async(X,F,H)=>{let N=W;W=void 0,await Promise.all([N,G(X,F,H)])};try{if(U)W=G("started"),W.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},F=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(H)=>G("pr-proof.started.v1",H))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:B,payload:IQ(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:X,runCommand:Z.runCommand??zQ,spawnFullControl:Z.spawnFullControl??h3,emit:U?Y:G,runHandsRelay:Z.runHandsRelay??((H)=>W7(H,X)),runPtySession:Z.runPtySession??R7});if(J.capability==="github.local.v1")C6.parse(F);if(!g3(F))throw new C("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(F)??"null","utf8")>H0)throw new C("result_too_large","Operation result exceeds 256 KB.");return await(U?Y:G)("completed",{ok:!0}),{status:"succeeded",result:F,error_code:null}}catch(X){let F=Z.signal.reason instanceof C&&U6.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof C&&U6.has(X.code)?X.code:null;if(Z.signal.aborted||F)return{status:"cancelled",...X instanceof a0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":F??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&X instanceof Error&&"code"in X&&["EACCES","EPERM"].includes(String(X.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let H=J.capability==="inference.custom.v1"?X instanceof C&&d6(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?X instanceof R1&&S3(J.payload,"failed",X.code)?X.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof C&&wQ.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof X7?$7(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:H,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:H}}}
|
|
540
|
-
export{L9 as
|
|
540
|
+
export{L9 as Ba,O9 as Ca,C4 as Da,zB as Ea,SB as Fa,$K as Ga,JK as Ha,b2 as Ia,oK as Ja,F0 as Ka,x$ as La,y$ as Ma,tK as Na,s$ as Oa,g0 as Pa,kJ as Qa,LQ as Ra,v7 as Sa,u7 as Ta,PQ as Ua,h3 as Va,zQ as Wa,gQ as Xa,dQ as Ya,n7 as Za,lQ as _a,sQ as $a,cQ as ab,nQ as bb,rQ as cb,MU as db,wU as eb,LU as fb,OU as gb};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{i as
|
|
2
|
+
import{Zj as e}from"./vm-hands-entry-lite-h2xemq1f.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
|
+
export{i as Aa};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{resolve as a,sep as i}from"path";var c=[[".ssh"],[".gnupg"],[".aws"],[".azure"],[".kube"],[".docker"],[".infisical"],[".password-store"],[".terraform.d"],[".config","ara"],[".config","reason"],[".config","gh"],[".config","gcloud"],[".config","infisical"],[".config","op"],[".config","1password"],[".config","pass"],[".local","share","keyrings"],["library","keychains"],["library","application support","so.ara.desktop"]],l=[[".codex","config.toml"],[".cursor","mcp.json"],[".claude","settings.json"],[".claude","settings.local.json"],[".cargo","credentials"],[".cargo","credentials.toml"],[".gem","credentials"],[".config","git","config"],[".config","git","credentials"],[".config","pip","pip.conf"]],f=new Set([".bash_login",".bash_profile",".bashrc",".bunfig.toml",".claude.json",".env",".envrc",".git-credentials",".gitconfig",".mcp.json",".netrc",".npmrc",".profile",".pypirc",".terraformrc",".yarnrc",".yarnrc.yml",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","auth.json","credentials.json","credentials.tfrc.json","local-daemon.json","local-device.json","mcp.json"]),g=[".key",".p12",".pfx",".pem"];function t(r,n){if(r.length<n.length)return!1;for(let e=0;e<=r.length-n.length;e+=1)if(n.every((o,s)=>r[e+s]===o))return!0;return!1}function d(r){let n=a(r).split(i).filter(Boolean).map((o)=>o.toLowerCase());if(c.some((o)=>t(n,o)))return!0;if(l.some((o)=>t(n,o)))return!0;let e=n.at(-1)??"";return f.has(e)||e.startsWith(".env.")||g.some((o)=>e.endsWith(o))}
|
|
3
|
-
export{c as
|
|
3
|
+
export{c as Sc,l as Tc,f as Uc,g as Vc,d as Wc};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Wc as X}from"./vm-hands-entry-lite-f4gvypnx.js";import{spawn as M}from"child_process";import{existsSync as C}from"fs";import{homedir as g}from"os";import{basename as D,join as N}from"path";var Y="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",G=Y.split(":"),f=5000,I=65536,U=new Set(["zsh","bash"]),V=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],j=(J,K)=>new Promise((W,Z)=>{let Q;try{Q=M(J,[...K],{detached:!0,stdio:["ignore","pipe","ignore"]})}catch($){Z($);return}let z=[],x=0,R=null,B=($)=>{R??=Error($);try{if(Q.pid!==void 0)process.kill(-Q.pid,"SIGKILL")}catch{}},F=setTimeout(()=>B("login_shell_timeout"),f);Q.stdout?.on("data",($)=>{if(x+=$.length,x>I)B("login_shell_output_too_large");else z.push($)}),Q.once("error",($)=>{clearTimeout(F),Z($)}),Q.once("close",($)=>{if(clearTimeout(F),R)Z(R);else if($!==0)Z(Error("login_shell_exit_nonzero"));else W(Buffer.concat(z).toString("utf8"))})});function O(J){return typeof J==="string"&&J.startsWith("/")&&!J.includes("\x00")&&U.has(D(J))}function q(J){let K=new Set,W=[];for(let Z of J){if(K.has(Z))continue;K.add(Z),W.push(Z)}return W}function H(J){let K=J.split(`
|
|
3
3
|
`).at(-1)??"",W=[];for(let Z of K.split(":")){let Q=Z.trim();if(!Q.startsWith("/"))continue;if(Q.includes("\x00"))continue;if(X(Q))continue;W.push(Q)}return q(W)}function k(J){let K=J?.home??g(),W=J?.directoryExists??C,Z=V.map((Q)=>N(K,...Q)).filter((Q)=>{try{return W(Q)}catch{return!1}});return q([...Z,...G]).join(":")}async function S(J){let K=J?.shell??process.env.SHELL,W=()=>({path:k({home:J?.home,directoryExists:J?.directoryExists}),source:"fallback"});if(!O(K))return W();let Z;try{Z=await(J?.runLoginShell??j)(K,["-lic",'printf %s "$PATH"'])}catch{return W()}if(Buffer.byteLength(Z,"utf8")>I)return W();let Q=H(Z);if(Q.length===0)return W();return{path:q([...Q,...G]).join(":"),source:"login_shell"}}function v(J){let K=null;return()=>{return K??=S(J),K}}function w(J){if(J===void 0||J.includes("\x00")||Buffer.byteLength(J,"utf8")>32768)return;return J}function P(J){let K=J.source??process.env,W={HOME:J.home,PATH:J.path??Y,TMPDIR:J.temporaryDirectory,SHELL:w(K.SHELL)??"/bin/zsh",LANG:w(K.LANG)??"C.UTF-8",LC_ALL:w(K.LC_ALL)??w(K.LANG)??"C.UTF-8"},Z=w(K.LC_CTYPE),Q=w(K.TERM),z=w(K.COLORTERM);if(Z)W.LC_CTYPE=Z;if(Q)W.TERM=Q;if(z)W.COLORTERM=z;return W}
|
|
4
|
-
export{Y as
|
|
4
|
+
export{Y as Ac,H as Bc,k as Cc,v as Dc,P as Ec};
|