@reason-machines/cli-linux-arm64-musl 0.2.359 → 0.2.361
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 +2 -2
- package/bin/vm-hands/api-credentials-vtpssnm1.js +2 -0
- package/bin/vm-hands/api-dvwzjwmh.js +2 -0
- package/bin/vm-hands/{ask-relay-fkb3bj30.js → ask-relay-tkvyxa1h.js} +5 -5
- package/bin/vm-hands/connect-cli-bc074w36.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-8v87dhjx.js +2 -0
- package/bin/vm-hands/desktop-account-q57958y1.js +2 -0
- package/bin/vm-hands/{device-workspace-fhbpenda.js → device-workspace-c05vq771.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-ze6q6h8b.js → hands-worker-source-wfv9csj2.js} +1 -1
- package/bin/vm-hands/{index-tv4kcb2a.js → index-80ep9259.js} +1 -1
- package/bin/vm-hands/{install-receipt-3s9amwp3.js → install-receipt-pbfhgaxc.js} +1 -1
- package/bin/vm-hands/local-automation-y118qzv6.js +2 -0
- package/bin/vm-hands/local-capabilities-fpjwj7a5.js +2 -0
- package/bin/vm-hands/local-desktop-users-m7rexsex.js +2 -0
- package/bin/vm-hands/local-display-mac-9de01n3r.js +2 -0
- package/bin/vm-hands/local-display-session-x25wfj8b.js +2 -0
- package/bin/vm-hands/local-pty-session-e7j0kj19.js +2 -0
- package/bin/vm-hands/{managed-runtime-mg7kmckn.js → managed-runtime-cv1vnm9k.js} +1 -1
- package/bin/vm-hands/{network-contract-gq8x3ehk.js → network-contract-zjq3w2n3.js} +1 -1
- package/bin/vm-hands/package-44a3p8yk.js +2 -0
- package/bin/vm-hands/permissions-ab559brd.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-67d4b6fm.js → reason-hands-protocol-aj1zwpk0.js} +1 -1
- package/bin/vm-hands/serve-service-csbg58wj.js +2 -0
- package/bin/vm-hands/{status-f146chye.js → status-00w678nv.js} +2 -2
- package/bin/vm-hands/version-x9tfh3sx.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-5xtkyx25.js → vm-hands-entry-lite-0763vz5v.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kxdw4myj.js → vm-hands-entry-lite-1hv536wk.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tg2bkah3.js → vm-hands-entry-lite-2vfv33yn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r6pap1kh.js → vm-hands-entry-lite-4xfs7y6w.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-p8662x7z.js → vm-hands-entry-lite-5wmh1c1y.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3ew5ftk0.js → vm-hands-entry-lite-5y2kfnv2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-qm18wqgz.js → vm-hands-entry-lite-6fvjbwqq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-d2hbz0r4.js → vm-hands-entry-lite-7nk0873d.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sx2gpbap.js → vm-hands-entry-lite-97zxda1y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pf1gagky.js → vm-hands-entry-lite-9grctmjf.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-kt4831mq.js → vm-hands-entry-lite-a43ss1hy.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ha1ej910.js → vm-hands-entry-lite-avstvbbc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-bybpy28m.js → vm-hands-entry-lite-cety9pka.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-22we2jrv.js → vm-hands-entry-lite-cwf21py1.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-w88zkzhr.js → vm-hands-entry-lite-dqnhebfx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qbnz4h30.js → vm-hands-entry-lite-dzkqn26g.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-szfy3kx7.js → vm-hands-entry-lite-fr2k6eah.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-qhgfnhjt.js → vm-hands-entry-lite-gj6znkxv.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-463aheya.js → vm-hands-entry-lite-hfq6jjnh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-h2xemq1f.js → vm-hands-entry-lite-hw8vgsmm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jn95s3j4.js → vm-hands-entry-lite-jjkkee8q.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-x4j4058x.js → vm-hands-entry-lite-jn8v1fp1.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-r5y08n0q.js → vm-hands-entry-lite-jpkf3569.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-kv0qat0x.js → vm-hands-entry-lite-k7fkfytm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-c7krpmd8.js → vm-hands-entry-lite-k8as28ss.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ygx9kj92.js → vm-hands-entry-lite-kxtjkzzh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-07er2w8q.js → vm-hands-entry-lite-mhvfdbq5.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-5kgvss4p.js → vm-hands-entry-lite-p1nb6n3r.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-gzxxsjmr.js → vm-hands-entry-lite-qkvwh6b7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9z6k7898.js → vm-hands-entry-lite-qy9xzp2m.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-c0m2jewa.js → vm-hands-entry-lite-t4gcrmbp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1j9r1fca.js → vm-hands-entry-lite-tbps80f1.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v08mjs3f.js → vm-hands-entry-lite-vcm4389c.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n867d88m.js → vm-hands-entry-lite-vgj22wxq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-j05685sg.js → vm-hands-entry-lite-xhr0m9r0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-s98hjhz3.js → vm-hands-entry-lite-xj0p1ax7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-taw01cp4.js → vm-hands-entry-lite-zn303jrg.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-5nqmf61x.js → vm-hands-executor-kmar1gzz.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-mm3bkzhq.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-hnpk8xmf.js → vm-hands-runtime-kxsr73mx.js} +3 -3
- package/bin/vm-hands/worker-sandbox-wb5thd4n.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-axffq0pk.js +0 -2
- package/bin/vm-hands/api-texm6ayv.js +0 -2
- package/bin/vm-hands/connect-cli-ev4xex04.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-bsanzqj2.js +0 -2
- package/bin/vm-hands/desktop-account-jxfva4m1.js +0 -2
- package/bin/vm-hands/local-automation-f8f33qpp.js +0 -2
- package/bin/vm-hands/local-capabilities-ya6yzxh5.js +0 -2
- package/bin/vm-hands/local-desktop-users-3th2aaac.js +0 -2
- package/bin/vm-hands/local-display-mac-neweyjpa.js +0 -2
- package/bin/vm-hands/local-display-session-v00nv1fm.js +0 -2
- package/bin/vm-hands/local-pty-session-2crsy5td.js +0 -2
- package/bin/vm-hands/package-s3eg9zrd.js +0 -2
- package/bin/vm-hands/permissions-3kjdp3ge.js +0 -2
- package/bin/vm-hands/serve-service-nqshfese.js +0 -2
- package/bin/vm-hands/version-ss25ccvh.js +0 -2
- package/bin/vm-hands/vm-hands-op-runner-zedtdcmk.js +0 -2
- package/bin/vm-hands/worker-sandbox-vmp22sk6.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
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-
|
|
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-dzkqn26g.js";import{wc as F7,yc as N7,zc as H7}from"./vm-hands-entry-lite-cwf21py1.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-xhr0m9r0.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-jpkf3569.js";import{Fd as q7,td as Q2,wd as z7}from"./vm-hands-entry-lite-vgj22wxq.js";import{$e as S6,Ae as H0,Af as p8,Bf as u8,Cf as d8,De as d,Df as l8,Ee as h1,Ef as s8,Ff as c8,Gf as n8,He as g8,Je as m1,Le as D6,Me as M6,Ne as w6,Oe as L6,Pe as O6,Qe as j6,Re as I6,Se as A6,Te as _6,Ue as T6,Ve as P6,We as R6,Xe as z6,Ye as q6,Ze as E6,_e as g6,af as k6,bf as f6,cf as b6,ef as x6,ff as y6,gf as h6,hf as m6,if as v6,jf as p6,kf as u6,oe as P1,pe as R1,qe as S3,qf as S8,re as F2,rf as k8,se as C6,sf as f8,te as k3,tf as b8,ue as W4,uf as x8,ve as Y4,vf as y8,we as w0,xf as h8,yf as m8,zf as v8}from"./vm-hands-entry-lite-fr2k6eah.js";import{$f as e1,Mf as Q6,Qf as L5,Rf as v5,Xf as E7,_f as O5}from"./vm-hands-entry-lite-mhvfdbq5.js";import{ag as A7,bg as _7,cg as T7,gg as P7,jg as R7}from"./vm-hands-entry-lite-qy9xzp2m.js";import{sg as x4,zg as K7}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Eg as Z2}from"./vm-hands-entry-lite-5y2kfnv2.js";import{Jg as R3,Wg as l6}from"./vm-hands-entry-lite-vcm4389c.js";import{Si as E1,Ti as c6,Ui as E4,Vi as g4}from"./vm-hands-entry-lite-tbps80f1.js";import{Xi as P3,Zi as Q1,dj as L8,ej as D4}from"./vm-hands-entry-lite-dqnhebfx.js";import{Aj as L7,Bj as O7,Dj as j7,Ej as I7,vj as C7,wj as D7,xj as M7,yj as w7}from"./vm-hands-entry-lite-avstvbbc.js";import{Pj as V}from"./vm-hands-entry-lite-k7fkfytm.js";import{Xj as C}from"./vm-hands-entry-lite-kxtjkzzh.js";import{bk as W8}from"./vm-hands-entry-lite-hw8vgsmm.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-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(`
|
|
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-8v87dhjx.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
|
//
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ig as j0}from"./vm-hands-entry-lite-qy9xzp2m.js";import{zg as U0}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Fg as Zq}from"./vm-hands-entry-lite-5y2kfnv2.js";import{Li as Aq}from"./vm-hands-entry-lite-jn8v1fp1.js";import{Si as d}from"./vm-hands-entry-lite-tbps80f1.js";import{Cj as L0,Fj as y0,Gj as T8,Hj as sq,Jj as $8,Mj as iq,Oj as nq,zj as H}from"./vm-hands-entry-lite-avstvbbc.js";import{Qj as W0}from"./vm-hands-entry-lite-jjkkee8q.js";import{Xj as M}from"./vm-hands-entry-lite-kxtjkzzh.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -178,4 +178,4 @@ Gtk.main()
|
|
|
178
178
|
`).flatMap((Q)=>{let P=Q.indexOf("=");return P>0?[[Q.slice(0,P),Q.slice(P+1)]]:[]})))}catch{return{}}}var N0=new Set;async function C1(q,x,X){let Q=await R1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===B8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??_(q,".Xauthority"),rfbSocket:_(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(N0.has(J)||!await s({path:`/tmp/.X11-unix/X${P}`},!1))return null;let y={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await R0(X,b,x,`x11vnc-${P}.log`,y))return{...b,sound:null};return N0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
|
|
179
179
|
`),null}function S1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!B0(`/usr/bin/${b}`)).map(([b])=>b),P=Rq({root:q,display:x,screen:t8,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])D8(_(q,b));for(let[b,J]of Object.entries(P.files))o8(_(q,b),J,{mode:384});for(let[b,J]of Object.entries(Dq))o8(_(q,`ara-${b}`),Q1(J),{mode:384});return{root:q,openboxConfig:_(q,"openbox","rc.xml"),start:P.start}}async function Z1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
|
|
180
180
|
`);await new Promise((Q)=>{let P=T0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},R8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function oX(q,x={}){let X=x.now??Date.now,Q=y1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new M("display_video_required","Reason desktops stream as video now; this request came without it.");let P=x.platform??process.platform;if(P!=="linux"&&P!=="darwin")throw new M("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>oq:B1))();return await A1(q.signal,Q,x,X,(y)=>Q0(y,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(y)=>T8({type:"error",code:y}))}function A1(q,x,X,Q,P,b){let J=Q();return new Promise((y,C)=>{let W=null,j=!1,R=!1,Z,B,Y,w=!1,N=null,D=(A)=>{if(R)return;if(N)A=N;R=!0,clearTimeout(Z),clearTimeout(B),q.removeEventListener("abort",F),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in A){C(A.error);return}y({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},G=()=>D({error:new M("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;D({error:A instanceof M?A:new M("cancelled","Reason closed the desktop session.")})},O=()=>{if(!N||!W)return;let A=N.error;try{W.send(b(A instanceof M?A.code:"display_unavailable"))}catch{}D(N)};if(Y=P({get done(){return R||N!==null},get open(){return j&&!R&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(A){if(R||N||!j||!W)return;try{W.send(A)}catch{D({reason:"relay_closed"})}},end:(A)=>{if(R||N)return;if(!("error"in A)){D(A);return}if(N=A,w&&j)O()}}),R){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),Z=setTimeout(()=>D({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),B=setTimeout(()=>D({reason:"viewer_absent"}),X.viewerWaitMs??N1);try{W=(X.connect??j0)(x.relay_url,(X.loadProxy??U0)()?.url)}catch{G();return}W.binaryType="arraybuffer",W.onopen=()=>{if(R||!W)return;j=!0,Y?.opened()},W.onmessage=(A)=>{if(R)return;let f=A.data,I=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!I||I.byteLength===0)return;if(clearTimeout(B),w=!0,N){O();return}Y?.received(I)},W.onclose=()=>{if(R)return;if(!j){G();return}D({reason:"relay_closed"})},W.onerror=()=>{if(R||j)return;G()}})}
|
|
181
|
-
export{_8 as
|
|
181
|
+
export{_8 as Hf,f1 as If,p1 as Jf,r as Kf,j8 as Lf,HX as Mf,J0 as Nf,Cq as Of,zq as Pf,k as Qf,UX as Rf,LX as Sf,yX as Tf,J1 as Uf,B8 as Vf,y1 as Wf,j1 as Xf,nX as Yf,D8 as Zf,B1 as _f,oX as $f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ni as m,oi as y}from"./vm-hands-entry-lite-r6pap1kh.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","reason-staging"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
|
|
3
|
-
export{f as
|
|
2
|
+
import{oi as m,pi as y}from"./vm-hands-entry-lite-4xfs7y6w.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","reason-staging"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
|
|
3
|
+
export{f as Zh,mJ as _h,yJ as $h,j as ai,sJ as bi,p as ci,cJ as di,lJ as ei,iJ as fi,rJ as gi,r as hi,jJ as ii,qQ as ji,BQ as ki,YQ as li,WQ as mi,LJ as ni};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{de as p,fe as V,ie as f}from"./vm-hands-entry-lite-cety9pka.js";import{_h as E}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as y}from"./vm-hands-entry-lite-4xfs7y6w.js";import{Bi as m,Pi as w,Ri as u}from"./vm-hands-entry-lite-jn8v1fp1.js";import{spawnSync as F}from"child_process";import{createHash as e,randomUUID as zz}from"crypto";import{chmodSync as Hz,existsSync as P,mkdirSync as Jz,readdirSync as Mz,readFileSync as L,renameSync as Qz,rmSync as T,statSync as Zz,writeFileSync as $z}from"fs";import{dirname as Bz,isAbsolute as v,join as A}from"path";var W="REASON_WORKER_SERVICE",jz="worker_identity_unavailable";function Iz(H){return{platform:process.platform,home:H,uid:process.getuid?.(),command:(z,M)=>F(z,[...M],{stdio:"ignore"}).status??1,read:(z,M)=>{let J=F(z,[...M],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return J.status===0?J.stdout:null},sleep:(z)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,z),workerIdentity:(z)=>u(H,z),insideService:(z)=>qz(z,process.platform,process.getuid?.())}}function qz(H,z,M){if(process.env[W]===H||process.env.XPC_SERVICE_NAME===H)return!0;if(z==="linux")try{return L("/proc/self/cgroup","utf8").includes(`/${H}.service`)}catch{return!0}if(z!=="darwin")return!1;if(typeof M!=="number")return!0;let J=F("/bin/launchctl",["print",`gui/${M}/${H}`],{encoding:"utf8",timeout:5000});if(J.status===Tz)return!1;if(J.error||J.status!==0)return!0;let Q=Number(/^\s*pid = (\d+)$/m.exec(J.stdout??"")?.[1]??0);if(!Q)return!1;let Z=process.pid;for(let B=0;B<64&&Z>1;B+=1){if(Z===Q)return!0;let $=F("/bin/ps",["-o","ppid=","-p",String(Z)],{encoding:"utf8",timeout:5000}),j=Number($.stdout?.trim());if($.error||$.status!==0||!Number.isSafeInteger(j)||j<=0)return!0;if(j===Z)return!1;Z=j}return Z>1}var Tz=113;class q extends Error{code;constructor(H,z){super(H);this.code=z}}function bz(H,z){if(H.platform!=="darwin"&&H.platform!=="linux")throw new q("A background service needs macOS (launchd) or Linux (systemd --user).");if(H.platform==="darwin")U(H);let J=[f(p(z,H.home))?.owned_paths.find((Q)=>Q.role==="launcher")?.path,y(z,"REASON_CLI_LAUNCHER_PATH")?.trim(),A(H.home,".local","bin",E({env:z})==="staging"?"ara-staging":"ara")];for(let Q of J)try{if(Q&&v(Q)&&Zz(Q).isFile())return V(Q)}catch{}throw new q("A background service runs the installed Reason launcher, which was not found. Install Reason with: curl -fsSL https://reasonmachines.com/install | sh","worker_launcher_missing")}var I=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,X=new RegExp(`(\\n\\s*<key>${w}</key>\\s*<string>)[^<]*(</string>)`),Gz=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Yz(H){return H.replaceAll("<","<").replaceAll(">",">").replaceAll(""",'"').replaceAll("'","'").replaceAll("&","&")}function b(H){let z=[...(I.exec(H)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((J)=>Yz(J[1])),M=z[1]==="--run-worker"?z.slice(2):z;return M[0]?{launcher:M[0],args:M.slice(1)}:null}function Sz(H,z){if(!Az(z))return null;try{return b(L(A(H,"Library","LaunchAgents",`${z}.plist`),"utf8"))?.launcher??null}catch{return null}}function d(H,z,M){let J=M.workerIdentity?.(H)??null;return{program:J?[J.executable,"--run-worker",H,...z]:[H,...z],identity:J}}function S(H){return H.map((z)=>` <string>${G(z)}</string>`).join(`
|
|
3
3
|
`)}function g(H,z){let M;try{M=L(H,"utf8")}catch{return null}let J=b(M);if(!J)return null;let Q=v(J.launcher)?V(J.launcher):J.launcher,{program:Z,identity:B}=d(Q,J.args,z),$=M.replace(I,(j,Y,N,R)=>`${Y}${S(Z)}
|
|
4
4
|
${R}`);if(!B)$=$.replace(X,"");else if(X.test($))$=$.replace(X,(j,Y,N)=>`${Y}${G(B.app)}${N}`);else $=$.replace(Gz,(j,Y,N)=>`${Y}
|
|
5
5
|
<key>${w}</key>
|
|
@@ -59,4 +59,4 @@ UMask=0077
|
|
|
59
59
|
[Install]
|
|
60
60
|
WantedBy=default.target
|
|
61
61
|
`}function C(H,z){Jz(Bz(H),{recursive:!0,mode:448});let M=`${H}.${zz()}.tmp`;try{$z(M,z,{mode:384,flag:"wx"}),Hz(M,384),Qz(M,H)}finally{T(M,{force:!0})}}function U(H){if(typeof H.uid!=="number"||!Number.isSafeInteger(H.uid)||H.uid<=0)throw new q("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${H.uid}`}function Ez(H){let{config:z,launcher:M,host:J}=H,Q=H.kind??"serve",Z=c(z,J,Q),B=Z!==null&&J.insideService?.(Z.label)===!0,$=D(z,J,Q,B?_:K);if(!$)throw new q("A background service needs macOS (launchd) or Linux (systemd --user).");if(J.platform==="darwin")U(J);if(J.platform==="linux"&&J.command("systemctl",["--user","show-environment"])!==0)throw new q("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let j=J.platform==="darwin"?r(z,Q,$,M,J,H.path):null;if(C($.definition,j?j.plist:s(z,Q,$,M,J.home,H.path)),i(z,J,$,B?null:Z),j)return j.identity?$:{...$,identityProblem:jz};return{...$,lingering:J.command("loginctl",["enable-linger"])===0}}function i(H,z,M,J){if(z.platform==="darwin"){let B=U(z);if(J)z.command("/bin/launchctl",["bootout",`${B}/${J.label}`]);if(t(H,M,z)){if(J)T(J.definition,{force:!0});return}if(T(M.definition,{force:!0}),J)z.command("/bin/launchctl",["bootstrap",B,J.definition]);throw new q("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}let Q=`${M.label}.service`,Z=J?`${J.label}.service`:null;if(z.command("systemctl",["--user","daemon-reload"])!==0||Z!==null&&z.command("systemctl",["--user","disable","--now",Z])!==0||z.command("systemctl",["--user","enable",Q])!==0||z.command("systemctl",["--user","restart",Q])!==0){if(z.command("systemctl",["--user","disable",Q]),T(M.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"]),Z)z.command("systemctl",["--user","enable","--now",Z]);throw new q("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(J)T(J.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"])}function t(H,z,M){let J=U(M);M.command("/bin/launchctl",["bootout",`${J}/${z.label}`]);let Q=(Math.ceil(H.shutdownGraceMs/1000)+10)*1000;for(let Z=0,B=100;;B=Math.min(B*2,2000)){if(M.command("/bin/launchctl",["bootstrap",J,z.definition])===0)return!0;if(Z>=Q)return!1;M.sleep(B),Z+=B}}function mz(H,z,M){let J=x(H,z,M);if(!J)return null;let Q=z.insideService?.(J.label)===!0;if(z.platform==="darwin"&&!Q)Nz(J.definition,z);let Z=D(H,z,M);if(Z&&J.label!==Z.label&&!Q)return C(Z.definition,L(J.definition,"utf8").replaceAll(J.label,Z.label)),i(H,z,Z,J),Z;let B=z.platform==="darwin"&&Q,$;if(B)$=z.command("/bin/launchctl",["kickstart","-k",`${U(z)}/${J.label}`])===0;else if(z.platform==="darwin")$=t(H,J,z);else z.command("systemctl",["--user","enable",`${J.label}.service`]),$=z.command("systemctl",["--user","restart",`${J.label}.service`])===0;if(!$)throw new q(`Could not restart the background service ${J.label}.`,"worker_service_restart_failed");if(Z&&J.label===Z.label)Lz(H,z,M);return J}function uz(H,z,M,J){let Q=x(H,M,J),Z=D(z,M,J);if(M.platform!=="darwin"||!Q||!Z)return;let B=`<string>${G(Q.logs)}</string>`,$=L(Q.definition,"utf8");if($.includes(B))C(Q.definition,$.replaceAll(B,`<string>${G(Z.logs)}</string>`))}function pz(H,z,M="serve"){let J=h(H,z,M);for(let Q of J){if(z.platform==="darwin"){if(typeof z.uid==="number"&&z.uid>0)z.command("/bin/launchctl",["bootout",`gui/${z.uid}/${Q.label}`]);T(Q.definition,{force:!0});continue}z.command("systemctl",["--user","disable","--now",`${Q.label}.service`]),T(Q.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"])}return J[0]??null}
|
|
62
|
-
export{W as
|
|
62
|
+
export{W as Gd,jz as Hd,Iz as Id,q as Jd,bz as Kd,Sz as Ld,_z as Md,l as Nd,xz as Od,Rz as Pd,x as Qd,Lz as Rd,kz as Sd,yz as Td,Ez as Ud,mz as Vd,uz as Wd,pz as Xd};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{r as
|
|
2
|
+
import{zg as m}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Ng as w}from"./vm-hands-entry-lite-vcm4389c.js";import{Ti as h}from"./vm-hands-entry-lite-tbps80f1.js";import{ej as x}from"./vm-hands-entry-lite-dqnhebfx.js";import{Xj as Q}from"./vm-hands-entry-lite-kxtjkzzh.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
|
|
3
|
+
export{r as ag,A as bg,l as cg,n as dg,U as eg,t as fg,Dz as gg,zz as hg,Hz as ig,Kz as jg};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Zc as dq,_c as cq}from"./vm-hands-entry-lite-wej1p1ry.js";import{
|
|
2
|
+
import{Zc as dq,_c as cq}from"./vm-hands-entry-lite-wej1p1ry.js";import{Hh as zq,Ih as fq,Mh as Rq,Nh as Uq,Oh as X,Rh as mq,Th as Fq,Uh as vq,Wh as h,Xh as P,Yh as Mq}from"./vm-hands-entry-lite-1hv536wk.js";import{oi as _q}from"./vm-hands-entry-lite-4xfs7y6w.js";import{Ci as hq,Ei as lq,Hi as oq,Ii as sq,Ji as uq,Ki as Nq}from"./vm-hands-entry-lite-jn8v1fp1.js";import{Si as c}from"./vm-hands-entry-lite-tbps80f1.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
3
|
`).includes(G)||!q.brokerDetail.split(`
|
|
4
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
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})
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{Q as
|
|
2
|
+
import{$i as X,bj as Y,dj as Z}from"./vm-hands-entry-lite-dqnhebfx.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
|
|
3
|
+
export{Q as Si,O as Ti,_ as Ui,b as Vi,g as Wi};
|