@reason-machines/cli-linux-arm64-musl 0.2.381 → 0.2.382
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/README.md +3 -1
- package/bin/ara +2 -2
- package/bin/vm-hands/api-credentials-xppmbg0m.js +2 -0
- package/bin/vm-hands/api-xmpbsm6b.js +2 -0
- package/bin/vm-hands/{ask-relay-fc0jc3t5.js → ask-relay-zjqyxvxe.js} +3 -3
- package/bin/vm-hands/connect-cli-ehxeg8m5.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-zhpake9f.js → custom-endpoint-device-bm94e9r0.js} +1 -1
- package/bin/vm-hands/desktop-account-3tnm4z5w.js +2 -0
- package/bin/vm-hands/{device-workspace-vbcry9d6.js → device-workspace-0xsj5ykf.js} +1 -1
- package/bin/vm-hands/hands-worker-source-azdrrhsz.js +2 -0
- package/bin/vm-hands/{index-bbk6a9sk.js → index-7f2kwwen.js} +1 -1
- package/bin/vm-hands/{install-receipt-7x81ek76.js → install-receipt-3xyx3rdd.js} +1 -1
- package/bin/vm-hands/local-automation-ynx1qr9v.js +2 -0
- package/bin/vm-hands/local-capabilities-855ch0dq.js +2 -0
- package/bin/vm-hands/local-desktop-users-ajb81vjm.js +2 -0
- package/bin/vm-hands/local-display-mac-9h6btvvq.js +2 -0
- package/bin/vm-hands/local-display-session-f9ywkbba.js +2 -0
- package/bin/vm-hands/local-pty-session-cjas515w.js +2 -0
- package/bin/vm-hands/managed-runtime-dars4628.js +2 -0
- package/bin/vm-hands/{network-contract-zqvt1v0t.js → network-contract-dsw79qkc.js} +1 -1
- package/bin/vm-hands/package-smk3nqjs.js +2 -0
- package/bin/vm-hands/permissions-pdmhp2s3.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-8fxjynte.js → reason-hands-protocol-7d7xj1h3.js} +1 -1
- package/bin/vm-hands/serve-service-n6xd6323.js +2 -0
- package/bin/vm-hands/status-2m75kz1h.js +96 -0
- package/bin/vm-hands/version-74zqccyz.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-06qnb2w1.js +458 -0
- package/bin/vm-hands/{vm-hands-entry-lite-7shpbsw8.js → vm-hands-entry-lite-1gxktkpe.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hgkf1svv.js → vm-hands-entry-lite-23bb8ce4.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-245929bs.js +346 -0
- package/bin/vm-hands/vm-hands-entry-lite-2e18tm6w.js +245 -0
- package/bin/vm-hands/{vm-hands-entry-lite-g036gtem.js → vm-hands-entry-lite-2t0vcvd8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0asdf4pm.js → vm-hands-entry-lite-2tcjqgfp.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-3n3xh0xv.js +540 -0
- package/bin/vm-hands/vm-hands-entry-lite-50n6vbfx.js +251 -0
- package/bin/vm-hands/{vm-hands-entry-lite-j2q1k9vb.js → vm-hands-entry-lite-51hmj6am.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-zfwg7ehq.js → vm-hands-entry-lite-5n4vsm6b.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-8fj07njx.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-4q8tsaqv.js → vm-hands-entry-lite-8zawqa9q.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3hbe4em3.js → vm-hands-entry-lite-9cmfthkq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-45j8qwsf.js → vm-hands-entry-lite-9w5vs9zv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-k7wwza46.js → vm-hands-entry-lite-aj1ccphg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-za55dtte.js → vm-hands-entry-lite-ammr3xbc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-yjn6sk08.js → vm-hands-entry-lite-ch7y4b1b.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-34e71nbe.js → vm-hands-entry-lite-cwe16c51.js} +174 -16
- package/bin/vm-hands/vm-hands-entry-lite-dh5gwmyf.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-dsdwzasy.js +105 -0
- package/bin/vm-hands/{vm-hands-entry-lite-5pm6bhb8.js → vm-hands-entry-lite-e0gdt6r5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-5kgvss4p.js → vm-hands-entry-lite-e2mjbqmr.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-ejm5er3h.js +7 -0
- package/bin/vm-hands/{vm-hands-entry-lite-mh0xecf3.js → vm-hands-entry-lite-f02906k8.js} +4 -4
- package/bin/vm-hands/vm-hands-entry-lite-f5230h6t.js +67 -0
- package/bin/vm-hands/{vm-hands-entry-lite-zh8p7ndn.js → vm-hands-entry-lite-fb5dzy9x.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-fyvgav60.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-g7h6wjqy.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-h8dbw0c7.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-nhtb458c.js → vm-hands-entry-lite-hnsm5t36.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r6pap1kh.js → vm-hands-entry-lite-ma001vzh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-anmv8hp7.js → vm-hands-entry-lite-mn64e4pt.js} +286 -104
- package/bin/vm-hands/{vm-hands-entry-lite-9cgm6g8t.js → vm-hands-entry-lite-pk3q774c.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-qef2ndkd.js +6 -0
- package/bin/vm-hands/vm-hands-entry-lite-qnnfvm5r.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-qwf78yqr.js +11 -0
- package/bin/vm-hands/vm-hands-entry-lite-r8qg3wp1.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-rd0ak4ye.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-00qsbphw.js → vm-hands-entry-lite-rpn0frzb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-g9rvf5qk.js → vm-hands-entry-lite-rtt2w6c6.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-sex82vb1.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-dgxxsdwb.js → vm-hands-entry-lite-xrthfx3q.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-kxdw4myj.js → vm-hands-entry-lite-y2s2w174.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-hc3p6r9p.js → vm-hands-entry-lite-zjfr0zh8.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-qssgfea1.js → vm-hands-executor-yx6mxa2p.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-yt3v3v6w.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-5me6cpmn.js → vm-hands-runtime-ygddqgbs.js} +3 -3
- package/bin/vm-hands/worker-sandbox-tgqbmy6b.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-af9g18n7.js +0 -2
- package/bin/vm-hands/api-credentials-65mrr3tn.js +0 -2
- package/bin/vm-hands/connect-cli-j478km3s.js +0 -2
- package/bin/vm-hands/desktop-account-5zvgspyw.js +0 -2
- package/bin/vm-hands/hands-worker-source-h0b1j53p.js +0 -2
- package/bin/vm-hands/local-automation-c86tjeft.js +0 -2
- package/bin/vm-hands/local-capabilities-1h99gkt6.js +0 -2
- package/bin/vm-hands/local-desktop-users-0hadyvx1.js +0 -2
- package/bin/vm-hands/local-display-mac-v1pc7177.js +0 -2
- package/bin/vm-hands/local-display-session-tzq0hne8.js +0 -2
- package/bin/vm-hands/local-pty-session-hs7rq03x.js +0 -2
- package/bin/vm-hands/managed-runtime-5dqaaw1x.js +0 -2
- package/bin/vm-hands/package-3cd7cfyv.js +0 -2
- package/bin/vm-hands/permissions-vbyqjbyb.js +0 -2
- package/bin/vm-hands/serve-service-be739c9s.js +0 -2
- package/bin/vm-hands/status-s8ny6men.js +0 -96
- package/bin/vm-hands/version-8s4syrp2.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-1085xsma.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-4m40gwkf.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-62wmnm7g.js +0 -540
- package/bin/vm-hands/vm-hands-entry-lite-98076n5g.js +0 -62
- package/bin/vm-hands/vm-hands-entry-lite-bvbfcp1k.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-c01eyep6.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-dcynw6t2.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-hh24bq0d.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-jb2sr2r7.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-kt5aj2ax.js +0 -11
- package/bin/vm-hands/vm-hands-entry-lite-n9nnb482.js +0 -459
- package/bin/vm-hands/vm-hands-entry-lite-sb9a1jcn.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-xg3d0a2y.js +0 -340
- package/bin/vm-hands/vm-hands-entry-lite-zamt8xp7.js +0 -181
- package/bin/vm-hands/vm-hands-entry-lite-ze9msfq1.js +0 -3
- package/bin/vm-hands/vm-hands-op-runner-b76rjaps.js +0 -2
- package/bin/vm-hands/worker-sandbox-wpzkvwer.js +0 -2
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ab as _7,Bb as i4,Cb as P7,Db as T7,Kb as R7,Ob as g7,Pb as E7,Zb as $8,bc as S7,cc as f7,dc as F8,ec as Y8,gc as b7,ib as h4,ic as y8,jc as v0,kb as q2,kc as p0,lb as m4,lc as F2,mb as v4,nb as H7,ob as C7,oc as x7,pb as D7,rb as u4,rc as h8,sb as w7,sc as J8,tb as j7,tc as Z8,ub as a4,uc as k1,vb as L7,wb as a3,wc as y7,xb as O7,yb as I7,zb as A7}from"./vm-hands-entry-lite-06qnb2w1.js";import{Dc as u7,Fc as p7,Gc as d7}from"./vm-hands-entry-lite-ejm5er3h.js";import{Lc as q7}from"./vm-hands-entry-lite-qef2ndkd.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-mn64e4pt.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as o4,bd as t4}from"./vm-hands-entry-lite-h8dbw0c7.js";import{dd as h7}from"./vm-hands-entry-lite-g7h6wjqy.js";import{hd as H2,id as C2,jd as B4,ld as V4,nd as G4,od as X4,sd as U4,ud as F7}from"./vm-hands-entry-lite-rpn0frzb.js";import{Cd as W2,Fd as Q9,Od as K9}from"./vm-hands-entry-lite-cwe16c51.js";import{$e as u6,Ae as n3,Be as O2,Ce as x6,Cf as a8,De as r3,Df as i8,Ee as _4,Ef as o8,Fe as P4,Ff as t8,Ge as j0,Gf as e8,Hf as $5,Jf as J5,Ke as C0,Kf as Z5,Lf as Q5,Mf as K5,Ne as s,Nf as B5,Oe as c1,Of as V5,Pf as G5,Qf as X5,Re as r8,Rf as U5,Sf as F5,Te as n1,Ve as y6,We as h6,Ze as m6,_e as v6,af as p6,bf as d6,cf as l6,df as s6,ef as c6,ff as n6,gf as r6,hf as a6,if as i6,jf as o6,kf as t6,lf as e6,mf as $7,nf as J7,of as Z7,qf as Q7,rf as K7,sf as B7,tf as V7,uf as G7,vf as X7,wf as U7,ye as g1,ze as E1}from"./vm-hands-entry-lite-5n4vsm6b.js";import{Yf as A6,ag as h5,bg as G6,hg as B9,kg as m5,lg as X2}from"./vm-hands-entry-lite-50n6vbfx.js";import{ng as t7,og as e7,pg as $9,tg as J9,wg as Z9}from"./vm-hands-entry-lite-dh5gwmyf.js";import{Fg as e4,Mg as k7}from"./vm-hands-entry-lite-xrthfx3q.js";import{Rg as Y2}from"./vm-hands-entry-lite-fb5dzy9x.js";import{Xg as u3,ih as Y7}from"./vm-hands-entry-lite-ammr3xbc.js";import{Ei as m7,Fi as v7}from"./vm-hands-entry-lite-2tcjqgfp.js";import{Ri as A1,Si as _1,Ti as P1,Ui as T1,Vi as k0}from"./vm-hands-entry-lite-sex82vb1.js";import{lj as b1,mj as M7,nj as n4,oj as r4}from"./vm-hands-entry-lite-fyvgav60.js";import{qj as v3,sj as B1,yj as x8,zj as E4}from"./vm-hands-entry-lite-pk3q774c.js";import{Qj as l7,Rj as s7,Sj as c7,Tj as n7,Vj as r7,Wj as a7,Yj as i7,Zj as o7}from"./vm-hands-entry-lite-1gxktkpe.js";import{ik as V}from"./vm-hands-entry-lite-zjfr0zh8.js";import{Ak as N7,Bk as c4,Ck as l1,sk as W5,tk as s4,yk as W7,zk as z7}from"./vm-hands-entry-lite-r8qg3wp1.js";import{Ek as H}from"./vm-hands-entry-lite-51hmj6am.js";import{Kk as q8}from"./vm-hands-entry-lite-2t0vcvd8.js";import{request as A9}from"http";import{request as _9}from"https";import{lookup as P9}from"dns/promises";import{isIP as T9}from"net";async function R9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?_9:A9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),q9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(q9.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 K=Y4(Q,J+1);if(K)return K}return null}async function g9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||T9(Q)!==0)return Z;let K;return await Promise.race([P9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function E9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function k9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,Y=0,F=E9(Q.apiKey),X=k9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await R9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await g9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function S9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>S9(Q.path,J));return Z.length===1?Z[0].path:null}var f9=/^[a-f0-9]{64}$/;var D2=32,b9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!b9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!f9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function x9($){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 y9($){return x9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?y9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),h9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
|
|
3
|
+
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
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
|
+
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
6
|
+
'(allow file-read* (subpath "/opt/homebrew/Cellar") (subpath "/opt/homebrew/opt") (subpath "/opt/homebrew/bin") (subpath "/opt/homebrew/lib") (subpath "/opt/homebrew/share") (subpath "/opt/homebrew/include") (subpath "/usr/local/Cellar") (subpath "/usr/local/opt") (subpath "/usr/local/bin") (subpath "/usr/local/lib") (subpath "/usr/local/share") (subpath "/usr/local/include") (subpath "/Library/Developer/CommandLineTools"))',
|
|
7
|
+
'(allow file-read* file-write* (subpath '+JSON.stringify(root)+') (subpath '+JSON.stringify(temporary)+'))',
|
|
8
|
+
'(allow file-read-metadata (path-ancestors '+JSON.stringify(root)+') (path-ancestors '+JSON.stringify(temporary)+'))',
|
|
9
|
+
'(deny file-read* file-write* (subpath "/opt/homebrew/etc") (subpath "/usr/local/etc") (literal "/private/etc/master.passwd"))',
|
|
10
|
+
'(deny file-write* (subpath "/opt/homebrew") (subpath "/usr/local") (subpath "/Library/Developer") (subpath "/cores"))',
|
|
11
|
+
...${JSON.stringify(h9)}.map(pattern => '(deny file-read* file-write* (regex #"'+pattern+'"))'),
|
|
12
|
+
'(deny network*)','(deny mach-lookup)','(deny process-info*)','(allow process-info* (target same-sandbox))','(allow process-info-listpids)','(allow file-read-metadata (subpath "/dev"))','(deny signal)','(allow signal (target same-sandbox))'].join('\\n');
|
|
13
|
+
}`;import{spawn as v9,spawnSync as u9}from"child_process";import*as g from"fs";import*as y from"path";import{homedir as p9}from"os";function C4($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z);if(process.platform==="win32"){let G=(U)=>U.toLowerCase()===K.toLowerCase()||U.toLowerCase().startsWith(K.toLowerCase()+J.sep);for(let U of new Set([process.env.ProgramW6432,process.env.ProgramFiles])){if(!U)continue;try{let Y=$.realpathSync(Q==="gh"?`${U}\\GitHub CLI\\gh.exe`:`${U}\\Git\\cmd\\git.exe`);if(!G(Y)&&Y.toLowerCase().startsWith(U.toLowerCase()+"\\")&&$.statSync(Y).isFile())return Y}catch{}}throw Error("local_device_gh_unavailable")}let B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((F)=>U.startsWith(F)))continue;let Y=$.statSync(U);if(!Y.isFile()||(Y.mode&18)!==0||![0,process.getuid()].includes(Y.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function D4($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var w4=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function M2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function M4($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function j4($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function R1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=M4(J).filter((G)=>!K.has(G));for(let G of $){let U=M2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let Y=G.content??"",F=B.map((X)=>({secret:X,offset:Y.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,W)=>X.offset-W.offset);if(F.length>0){let X=[...new Set(F.flatMap((W)=>Z.secretNames?.(W.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:D4(Y,F[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of w4){let W=j4(X,Y).find((z)=>!K.has(z[0]));if(W){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:D4(Y,W.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function L4($,J=[]){let Z=M4(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of w4)for(let G of j4(B,K))Q.add(G[0])}return[...Q]}function m9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function O4($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+m9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,U0=process.platform==="win32",i0=process.env.SystemRoot??"C:\\Windows",d9=($)=>U0?u9(y.win32.join(i0,"System32","taskkill.exe"),["/PID",String($),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-$,"SIGKILL"),a0=U0?[y.win32.join(i0,"System32"),i0].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",q1=U0?{SystemRoot:i0,WINDIR:i0}:{},l9=($)=>U0?y.win32.resolve($,"..","..","bin","sh.exe"):"/bin/sh",I4=536870912,j2=/^[a-f0-9]{40}$/,s9=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=v9($,J,{cwd:Z.cwd,env:Z.env,...U0?{windowsHide:!0}:{detached:!0},stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,Y=!1,F=(N)=>{if(U??=Error(N),K.pid)try{d9(K.pid)}catch{}},X=()=>F("cancelled"),W=setTimeout(()=>F("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let z=(N)=>{if(Y)return;Y=!0,clearTimeout(W),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)F("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)F("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(F("spawn_failed"),!K.pid)z(null)}),K.on("close",(N)=>z(N)),K.stdin.on("error",()=>F("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),c9={command:s9,gh:($,J)=>C4(g,y,$,J),home:p9};function _($){throw Error($)}function L2($,J){let[Z,Q]=U0?[$.toLowerCase(),J.toLowerCase()]:[$,J];return Q===Z||Q.startsWith(Z+y.sep)}function n9($,J){let Z=new Set($.split(/\r?\n/).map(w2));return J.filter((Q)=>{let K=w2(Q);if(Z.has(K))return!1;return Z.add(K),!0})}var r9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),a9=($)=>JSON.stringify($,(J,Z)=>r9.has(J)?void 0:Z);function A4($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");_(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function T4($,J,Z=c9){let Q=g1.parse($),K="local_device_gh_prepare_setup";try{if(!["darwin","linux","win32"].includes(process.platform))_("local_device_gh_platform_unavailable");J.assertCurrent();let B=g.realpathSync(J.root);if(B===y.parse(B).root)_("local_device_gh_root_unavailable");if(!j0(Q)&&!J.forbiddenSecretValues)_("local_device_gh_secret_scope_unavailable");if(!j0(Q)&&J.readOnly)_("local_device_gh_read_only");if(!j0(Q)){let L=R1([{path:"github-operation",content:a9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)A4(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let G=Z.gh(B),U=Z.home(),Y=Z.gh(B,"git"),F=J.privateDirectory?g.realpathSync(J.privateDirectory):g.realpathSync(U);if(!j0(Q)&&(!J.privateDirectory||L2(B,F)))_("local_device_gh_private_scope_unavailable");let X={...q1,PATH:U0?[y.dirname(Y),a0].join(";"):a0,HOME:U,GH_CONFIG_DIR:U0&&process.env.APPDATA?y.join(process.env.APPDATA,"GitHub CLI"):y.join(U,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:U0?"":"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},W=async(L,T,q=F,S,h=T0)=>{J.assertCurrent();let m=await Z.command(L,T,{cwd:q,env:X,input:S,maxBuffer:h,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),m.error||m.status!==0)_("local_device_gh_command_failed");return m.stdout},z=async(L)=>(await W(G,L)).toString("utf8").trim(),N=async(L,T="application/vnd.github+json")=>{_4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let q=await Z.command(G,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:F,env:X,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),q.error&&q.status===null)_("local_device_gh_response_unavailable");let S=q.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!S)_("local_device_gh_response_invalid");let h=Number(S[1]);if(h>=200&&h<300&&q.status!==0)_("local_device_gh_response_unavailable");if(Buffer.byteLength(S[3])>O2)_("local_device_gh_response_too_large");let m={};for(let i of S[2].split(/\r?\n/)){let e=i.indexOf(":"),M0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(M0))m[M0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:h,headers:m,body:h>=200&&h<300?S[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return N(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),q=await z(["api","graphql","--hostname","github.com","-f",`query=${P4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(q)>O2)_("local_device_gh_response_too_large");let S=JSON.parse(q);if(S.errors||S.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||S.data.repository.pullRequest?.number!==Q.number)_("local_device_gh_response_invalid");return{kind:"pr_review_context",body:q}}if(Q.kind==="pr_merge"){let L=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),q=(m)=>m.number===Q.number&&m.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&m.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&m.base?.ref===Q.expectedBaseRef&&m.head?.sha===Q.expectedHeadSha;if(L.status!==200||!q(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())_("local_device_gh_merge_target_changed");await z(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let S=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),h=JSON.parse(S.body);if(S.status!==200||!q(h)||h.merged!==!0)_("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)_("local_device_gh_default_branch");let L=await z(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))_("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await z(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)_("local_device_gh_workspace_unavailable");let C=g.realpathSync(J.repoPath);if(!L2(B,C))_("local_device_gh_workspace_unavailable");let M=`https://github.com/${Q.repoFullName}.git`,w="!'"+(U0?G.replace(/\\/g,"/"):G).replace(/'/g,"'\\''")+"' auth git-credential",D=Function("return ("+H4+")")(),j=(L,T,q)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...q]]:[T,q],O=async(L,T,q,S=T0)=>{let h=L2(F,L),m=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...h?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(h)return W(Y,m,L,q,S);let i=y.join(C,".ara-local-gh-tmp");if(g.mkdirSync(i,{recursive:!0,mode:448}),g.lstatSync(i).isSymbolicLink()||g.realpathSync(i)!==i)_("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(D(C,i),Y,m),{cwd:L,input:q,maxBuffer:S,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:C,TMPDIR:i,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),e.error||e.status!==0)_("local_device_gh_collection_failed");return e.stdout},A=async(L,T)=>(await O(L,T)).toString("utf8").trim(),b=async(L,T)=>{let q=y.join(L,".ara-local-gh-tmp");if(g.mkdirSync(q,{recursive:!0,mode:448}),g.lstatSync(q).isSymbolicLink()||g.realpathSync(q)!==q)_("local_device_gh_workspace_unavailable");J.assertCurrent();let S=await Z.command(...j(D(L,q),l9(Y),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:L,TMPDIR:q}});if(J.assertCurrent(),S.error||S.status!==0)_("local_device_gh_materialization_failed")},I=async(L)=>{let T=new Map;if(L.length===0)return T;let q=await O(p,["cat-file","--batch"],[...new Set(L)].join(`
|
|
14
|
+
`)+`
|
|
15
|
+
`,T0*8);for(let S=0;S<q.length;){let h=q.indexOf(10,S),[m,i,e]=q.subarray(S,h).toString("utf8").split(" ");if(h<0||!m||i!=="blob"||!/^[0-9]+$/.test(e??""))_("local_device_gh_object_invalid");T.set(m,q.subarray(h+1,h+1+Number(e)).toString("utf8")),S=h+1+Number(e)+1}return T},R=async(L,T,q)=>{let S=y.join(C,".ara-local-gh-tmp"),h=D(C,S)+`
|
|
16
|
+
(allow file-read* file-write* (subpath ${JSON.stringify(C)}))
|
|
17
|
+
(allow file-read* (subpath ${JSON.stringify(L)}))
|
|
18
|
+
(allow file-read-metadata (path-ancestors ${JSON.stringify(L)}))`,m=async(e,M0)=>{J.assertCurrent();let s0=await Z.command(...j(h,e,M0),{cwd:C,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:C,TMPDIR:S,GIT_INDEX_FILE:y.join(C,".git","index"),OPENSSL_CONF:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),s0.error||s0.status!==0)_("local_device_gh_materialization_failed")},i=["--git-dir="+L,"--work-tree="+C,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await m(Y,[...i,"read-tree",T]),await m(Y,[...i,"checkout-index","--all","--index"]),await O(C,["update-ref","refs/heads/"+q,T]),await O(C,["symbolic-ref","HEAD","refs/heads/"+q])};K="local_device_gh_prepare_metadata";let P=await N(`/repos/${Q.repoFullName}`);if(P.status!==200)_("local_device_gh_repository_unavailable");let c=JSON.parse(P.body);if(c.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||c.default_branch!==Q.defaultBranch||Q.kind==="publish"&&c.permissions?.push!==!0)_("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)_("local_device_gh_default_branch");K="local_device_gh_prepare_private_init";let p=g.mkdtempSync(y.join(F,"github-publication-"));g.chmodSync(p,448);let M1=!1;try{if(await O(p,["init","--bare","--template="]),Q.kind==="prepare"){if(K="local_device_gh_prepare_fetch",await O(p,["fetch","--depth=1","--no-tags","--no-recurse-submodules",M,Q.baseSha]),await A(p,["rev-parse","FETCH_HEAD"])!==Q.baseSha)K="local_device_gh_prepare_base_mismatch",_("local_device_gh_base_changed");K="local_device_gh_prepare_checkout_validation";let d=y.join(C,".git"),B0=!1;if(g.existsSync(d)){if(!g.lstatSync(d).isDirectory()||g.lstatSync(d).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((r)=>g.existsSync(y.join(d,r))))_("local_device_gh_repository_layout_invalid");let t=await O(C,["rev-parse","--verify","-q","HEAD"]).then((r)=>r.toString("utf8").trim(),()=>null),V0=await O(C,["config","--local","--get","remote.origin.url"]).then((r)=>r.toString("utf8").trim(),()=>"");if(t!==null||V0){if(t!==Q.baseSha||await A(C,["branch","--show-current"])!==Q.branch)_("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}B0=!0}let $0=g.readdirSync(C).filter((t)=>!(B0&&t===".git")),Y0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if($0.some((t)=>!Y0.includes(t))||$0.some((t)=>{let V0=y.join(C,t);return!g.lstatSync(V0).isDirectory()||g.lstatSync(V0).isSymbolicLink()||g.readdirSync(V0).length>0}))_("local_device_gh_checkout_not_empty");if(K="local_device_gh_prepare_checkout_init",!B0)await O(C,["init","--template="]);K="local_device_gh_prepare_materialization";let H0=await O(p,["pack-objects","--stdout","--revs"],Q.baseSha+`
|
|
19
|
+
`,I4);return await b(C,Q.baseSha),await O(C,["index-pack","--strict","--stdin"],H0,65536),await O(C,["remote","add","origin",M]),await R(p,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let L=y.join(C,".git");if(!g.lstatSync(L).isDirectory()||g.lstatSync(L).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((d)=>g.existsSync(y.join(L,d))))_("local_device_gh_repository_layout_invalid");if(await A(C,["branch","--show-current"])!==Q.branch)_("local_device_gh_branch_changed");let T=await A(C,["rev-parse","--verify","HEAD"]);if(!j2.test(T))_("local_device_gh_head_invalid");let q=await N(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(q.status!==200||JSON.parse(q.body).sha!==Q.baseSha)_("local_device_gh_base_unverified");let S=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?S.status!==404:S.status!==200||JSON.parse(S.body).object?.sha!==Q.remoteHeadSha)_("local_device_gh_remote_changed");let h=[...(await A(C,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha])).split(`
|
|
20
|
+
`),...(await A(C,["rev-list","--objects","--no-object-names","--no-walk",Q.baseSha])).split(`
|
|
21
|
+
`)].filter(Boolean);if(h.some((d)=>!j2.test(d)))_("local_device_gh_object_invalid");let m=await O(C,["pack-objects","--stdout"],[...new Set(h)].join(`
|
|
22
|
+
`)+`
|
|
23
|
+
`,I4);if(g.writeFileSync(y.join(p,"shallow"),Q.baseSha+`
|
|
24
|
+
`,{flag:"wx",mode:384}),await O(p,["index-pack","--strict","--stdin"],m,65536),await O(p,["merge-base","--is-ancestor",Q.baseSha,T]),Q.remoteHeadSha)await O(p,["merge-base","--is-ancestor",Q.remoteHeadSha,T]);let i=await O(p,["show","-s","--format=%B",T]),e=(await O(p,["interpret-trailers","--parse"],i)).toString("utf8"),M0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:n9(e,Q.contributorTrailers)}:void 0,s0=(await A(p,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
|
|
25
|
+
`).filter(Boolean);if(s0.length>5000)_("local_device_gh_collection_too_large");let c0=[],J4=0;for(let d of s0){if(!j2.test(d))_("local_device_gh_object_invalid");let B0=await A(p,["cat-file","-t",d]);if(!["blob","commit","tree"].includes(B0))_("local_device_gh_object_invalid");let $0=await O(p,["cat-file",B0,d]);if(J4+=$0.length,J4>T0)_("local_device_gh_collection_too_large");if(B0==="tree"){let Y0=0;while(Y0<$0.length){let H0=$0.indexOf(32,Y0),t=$0.indexOf(0,H0+1);if(H0<Y0||t<=H0||t+21>$0.length)_("local_device_gh_object_invalid");let V0=$0.subarray(H0+1,t).toString("utf8");if(V0.includes("/")||!M2(V0).valid)_("local_device_gh_object_invalid");Y0=t+21}}c0.push({path:`object-${d}`,content:$0.toString("utf8")})}let Z4=J.secretNames?{secretNames:J.secretNames}:{},n0=R1(c0,J.forbiddenSecretValues,Z4),Q4=new Map;if(!n0.clean)try{let d=(await O(p,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,T])).toString("utf8").split("\x00"),B0=[],$0=[];for(let r=0;r+1<d.length;r+=2){let[,O9,I9,N2,j1]=d[r].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!N2||!j1)continue;if(O9!=="160000"&&!/^0+$/.test(N2))B0.push(N2);if(I9!=="160000"&&!/^0+$/.test(j1))$0.push(j1),Q4.set(`object-${j1}`,d[r+1])}let Y0=await I([...B0,...$0]),H0=new Set(n0.violations.map((r)=>r.path)),t=L4(c0.filter((r)=>H0.has(r.path)),J.forbiddenSecretValues),V0=O4(t,$0.map((r)=>Y0.get(r)??""),B0.map((r)=>Y0.get(r)??""));if(V0.size>0)n0=R1(c0,J.forbiddenSecretValues,{...Z4,published:V0})}catch{}if(!n0.clean)A4(n0.violations,(d)=>Q4.get(d)??`an object in the pushed history (${d})`,"Remove it from the files and commit again; a commit or message in the pushed history that holds it must be amended before this branch can be pushed.");await O(p,["push","--no-recurse-submodules",M,`${T}:refs/heads/${Q.branch}`]);let K4=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(K4.status!==200||JSON.parse(K4.body).object?.sha!==T)_("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:T,scannedObjectCount:c0.length,...M0?{attribution:M0}:{}}}catch(L){throw M1=!0,L}finally{try{g.rmSync(p,{recursive:!0,force:!0})}catch(L){if(!M1||Q.kind!=="prepare")throw K=null,L}}}catch(B){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&K&&!J.signal?.aborted)throw new E1(K);throw B}}var R0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),I2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},i9=V.object({...I2,version:V.literal(2),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!1),source_bound:V.literal(!1),profiles:V.array(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),o9=V.object({...I2,version:V.literal(3),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!0),source_bound:V.literal(!1),max_seconds:V.literal(15),profiles:V.array(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),A2=V.union([i9,o9]),QB=V.union([V.object({...I2,version:V.literal(1),development_only:V.literal(!0),profile:R0.shape.profile,extension_instance_id:R0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),A2]);import{randomUUID as E2}from"crypto";import{spawn as Y$}from"child_process";import{existsSync as k2,lstatSync as Q8,mkdirSync as W$,readFileSync as z$,realpathSync as S1,rmSync as N$,writeFileSync as H$}from"fs";import{dirname as C$,join as W0,relative as D$,sep as w$}from"path";var t9=["process.run.v1","process.full.v1"],e9=600000,$$=1800000,J$=20000,R4="process.cancel.v1",q4=V.object({action:V.literal("start"),request_id:V.string().uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),cwd:V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")&&!$.startsWith("/")&&!$.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:V.enum(["host","confined"]).default("host"),timeout_ms:V.number().int().min(1000).max($$).default(e9).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),_2={device_id:V.string().uuid(),root_id:V.string().uuid()},Z$=V.discriminatedUnion("action",[q4.extend(_2),V.object({..._2,action:V.literal("inspect"),process_id:V.string().uuid(),after:V.number().int().min(0).default(0),wait_ms:V.number().int().min(0).max(J$).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),V.object({..._2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),VB=V.toJSONSchema(Z$,{io:"input"}),GB=q4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),o0=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:V.number().int().nullable(),first_cursor:V.number().int().min(0),next_cursor:V.number().int().min(0),truncated:V.boolean(),observed_at:V.iso.datetime(),output:V.array(V.object({cursor:V.number().int().min(1),stream:V.enum(["stdout","stderr"]),text:V.string().max(32768)}).strict()).max(128)}).strict().refine(($)=>{if(Buffer.byteLength(JSON.stringify($))>1e5||$.next_cursor<$.first_cursor-1)return!1;if(($.state==="starting"||$.state==="running"||$.state==="uncertain")&&$.exit_code!==null)return!1;if($.state==="exited"&&($.exit_code===null||$.exit_code<0||$.exit_code>255))return!1;if($.state==="cancelled"&&$.exit_code!==130||$.state==="expired"&&$.exit_code!==124)return!1;let Z=$.first_cursor-1;for(let Q of $.output){if(Q.cursor<=Z||Q.cursor>$.next_cursor)return!1;Z=Q.cursor}return!0});function g4($){return t9.includes($)}var XB=V.object({operation_constraints:V.record(V.string(),V.unknown())}),UB=V.object({ready:V.literal(!0),version:V.literal(1),execution_mode:V.enum(["host","confined"]),max_timeout_ms:V.number().int().min(1000).optional()});var Q$=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["queued","cancelled_before_start","not_started"]),exit_code:V.null(),output:V.array(V.never()).length(0),first_cursor:V.literal(0),next_cursor:V.literal(0),truncated:V.literal(!1),cancellation_requested:V.literal(!1),reason_code:V.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),K$=V.object({...o0.shape,state:V.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:V.iso.datetime().optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:V.boolean(),reason_code:V.string().nullable().optional(),execution_authority:V.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:V.object({cause:V.literal("brain_generation_changed"),terminal_confirmed:V.boolean(),next_step:V.enum(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:o0.shape.state.or(V.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),FB=V.toJSONSchema(K$),YB=V.union([o0,Q$.refine(($)=>$.state==="cancelled_before_start")]),P2=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["exited","cancelled","expired"]),exit_code:V.number().int().min(0).max(255),observed_at:V.iso.datetime()}).strict().refine(($)=>($.state!=="cancelled"||$.exit_code===130)&&($.state!=="expired"||$.exit_code===124)),B$=V.object({process_terminal_observation:P2}).strict();function WB($,J){let Z=B$.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var k4="preview.serve.v1",S4=43200000;var CB=3,f4="preview.open.v1",b4=1,T2="gid_proxy_v1",x4="egress",R2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,V$=V.object({version:V.literal(T2),allowed_domains:V.array(V.string().max(260).regex(R2)).max(1024)}).strict(),G$=V.custom(($)=>E4($)!==null,"invalid workspace"),X$=V.object({version:V.literal(1),request_id:V.uuid(),session_id:V.uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),port:V.number().int().min(1024).max(65535),workspace:G$,egress:V$.optional()}).strict(),y4=X$.extend({expires_at:V.iso.datetime()}).strict();var U$=4,F$=5000;function g2($,J,Z){let Q=null;try{Q=q2($)}catch{}m4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function p4($){let J=new Map;return{open(Z){let Q=(X)=>g2(Z,$.claim.operation_id,X),K;try{K=q2(Z)}catch{return Q("binding_invalid")}let{binding:B,deviceRelayUrl:G}=K,U=$.claim.owner;if(!U||B.organizationId!==U.organization_id||B.userId!==U.user_id||B.deviceId!==U.device_id||B.rootId!==$.claim.root_id||B.jobId!==$.claim.operation_id||B.fenceId!==$.claim.operation_id||B.generation!==b4||B.expiresAtMs>Math.min(Date.now()+h4.lifetimeMs+F$,$.expiresAtMs))return Q("binding_mismatch");if(B.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(B.port)?.abort(),J.delete(B.port),J.size>=U$)return Q("preview_capacity");let Y=new AbortController;J.set(B.port,Y);let F=u4({binding:B,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(Y.signal.aborted)return null;let X=await $.inspect();return X?{binding:B,executorLaunchId:$.executorLaunchId,job:X}:null}});v4({binding:B,deviceRelayUrl:G,port:F,signal:Y.signal}).then((X)=>X.closed,(X)=>{let W=X instanceof Error?X.message:"preview_failed";if(W!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:B.jobId,port:B.port,reason_code:W})}
|
|
26
|
+
`)}).finally(()=>{if(J.get(B.port)===Y)J.delete(B.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class t0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var K8=256,f1=new Map,B8="preview.serve.v1",q0=new Map;function V8($){let J=q0.get($.operation_id);if(J){if(J.claim!==$)throw G0("process_authority_lost");return J}if(q0.size>=K8)throw G0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return q0.set($.operation_id,Z),Z}function d4($){return{version:1,process_id:$,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var l4=($)=>new Promise((J)=>setTimeout(J,$)),G0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function M$($=b1(),J=j$()){let Z=C$(e4({},$)),Q=D$(n4($),Z),[K,...B]=Q.split(w$);return{directory:W0(J,Q,"processes"),previous:[W0(Z,"processes"),...K==="reason"?[W0(J,"ara",...B,"processes")]:[]]}}function j$(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=r4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function S2($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw G0("process_authority_lost");let J=V8($.claim);if(J.executing)throw G0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",d4($.claim.operation_id);J.phase="starting";let Z=$.journals??M$();W$(Z.directory,{recursive:!0,mode:448});let Q=a4({runtimeDirectory:S1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((I)=>k2(I)).map((I)=>S1(I)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:K8});try{for(let I of[$.root,$.cwd])if(!$8(S1(I),Q.journalDirectory))throw new H("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(I){throw Q.disposeSocket(),I}let K=Q8(Q.journalDirectory),B=$.claim.capability===B8,G=()=>f1.set($.claim.operation_id,{path:Q.journalDirectory,ino:K.ino,dev:K.dev,anyCompletion:B}),U=Q.launchDirectory,Y=W0(U,"config.json"),F={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:e0,protocolVersion:2,workerArtifactSha256:g0,workerEntrypoint:$1,targetGeneration:1,fenceId:E2(),...process.platform==="win32"?{bashExecutable:s4()}:{},workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:W0(U,"unused.env"),replSocketPath:W0(U,"unused.sock"),readyPath:W0(U,"ready.json"),directTerminalReceiptPath:W0(U,"terminal.json"),launchId:E2(),expiresAtMs:$.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Q.journalDirectory,scopeId:Q.scopeId},jobControlSocketPath:Q.socketPath,...$.prefix?{bashCommandPrefix:$.prefix}:{},...$.jobsUser?{jobsUser:$.jobsUser}:{}},X;try{H$(Y,JSON.stringify(F),{mode:384});let I=J8({configPath:Y,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(Y,F)??Y$(I.command,I.args,{...I.options,env:$.environment,stdio:[Z8,"ignore","ignore"]})}catch(I){throw Q.disposeSocket(),I}let W=!1,z=new Promise((I,R)=>{X.once("exit",(P)=>{W=!0,I(P)}),X.once("error",(P)=>{W=!0,R(P)})});z.catch(()=>{});let N={root:$.root,runId:$.claim.run_id,scopeId:Q.scopeId,socketPath:Q.socketPath,generation:1,fenceId:F.fenceId,executorLaunchId:F.launchId,expiresAtMs:F.expiresAtMs},C=async(I)=>{let R=await i4(N,{type:"job",version:2,generation:1,id:E2(),jobId:$.claim.operation_id,...I==="start"?{action:I,input:{script:$.command,leaseExpiresAtMs:$.expiresAtMs}}:I==="inspect"?{action:I,input:{after:0}}:I==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:I,input:{}}},new AbortController().signal);if(!R.ok)throw G0(R.error);return R.job},M=!1,w=!1,D,j=()=>{M=!0,k1(X,"SIGTERM")};$.signal.addEventListener("abort",j,{once:!0});let O,A=0,b=async(I)=>{let R=[...I.output],P={version:1,process_id:$.claim.operation_id,state:I.state,exit_code:I.exitCode,first_cursor:I.firstCursor,next_cursor:I.nextCursor,truncated:I.truncated,output:R,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(P))>90000&&R.length)R.shift(),P.truncated=!0,P.first_cursor=R[0]?.cursor??P.next_cursor+1;O=o0.parse(P),await $.emit(O),A=Date.now()};try{let I=Math.min(Date.now()+1e4,$.expiresAtMs);while(!k2(F.readyPath)){if(W)throw new H("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if($.signal.aborted||Date.now()>=I)throw G0("process_start_unconfirmed");await l4(25)}let R=JSON.parse(z$(F.readyPath,"utf8"));if(R.launchId!==F.launchId||R.fenceId!==F.fenceId||R.workerArtifactSha256!==g0)throw G0();if($.signal.throwIfAborted(),J.cancelRequested)return d4($.claim.operation_id);let P;try{w=!0,P=await C("start")}catch(c){if(!(c instanceof H)||c.code!=="hands_job_result_unknown")throw c;P=await C("inspect")}if(J.phase="running",J.cancel=async()=>{await C("cancel")},B&&$.preview)J.tunnels=p4({claim:$.claim,executorLaunchId:F.launchId,expiresAtMs:$.expiresAtMs,deniedPorts:$.preview.deniedPorts,inspect:async()=>J.phase==="running"&&!W?await C("probe"):null});if(J.cancelRequested)await J.cancel(),P=await C("inspect");for(;;){if(!["starting","running"].includes(P.state))J.phase="settling",J.cancel=void 0;if(!O||O.state!==P.state||O.next_cursor!==P.nextCursor&&Date.now()-A>=5000)await b(P);if(!["starting","running"].includes(P.state))break;if($.signal.aborted||W)throw G0();await l4(1000);try{P=await C("inspect"),D=void 0}catch(c){if(!(c instanceof H)||c.code!=="hands_job_result_unknown"||$.signal.aborted||W||Date.now()-(D??=Date.now())>120000)throw c}}if(!O||O.state==="uncertain")throw G0();return O}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",j),!W&&!M)k1(X,"SIGTERM");let I,R=await Promise.race([z.then((P)=>({code:P})),new Promise((P)=>{I=setTimeout(()=>P(null),6000)})]).finally(()=>{clearTimeout(I)});if(!R){try{k1(X,"SIGKILL")}catch{}try{await z}finally{if(W)Q.disposeSocket()}throw G0("process_cleanup_unconfirmed")}try{if((M||$.signal.aborted)&&R.code===0&&w){o4(U);let P=JSON.parse(t4(F.directTerminalReceiptPath)),c=P2.safeParse(P.observation);if(Object.keys(P).length===4&&P.launch_id===F.launchId&&P.fence_id===F.fenceId&&P.scope_id===Q.scopeId&&c.success&&c.data.process_id===$.claim.operation_id){if(B)G();throw new t0(c.data)}}}catch(P){if(P instanceof t0)throw P}finally{if(W)Q.disposeSocket()}if(R.code!==0&&!M&&w)throw G0("process_cleanup_unconfirmed");if(!M&&R.code===0&&(O&&["exited","cancelled","expired"].includes(O.state)||!w&&J.cancelRequested)||B&&R.code===0&&!w)G()}}async function mB($,J){if(J.kind===f4&&$.capability===B8){let K=q0.get($.operation_id);if(K?.claim===$&&K.tunnels)K.tunnels.open(J.payload);else g2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==R4||!g4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=q0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=V8($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function vB($,J){q0.delete($);let Z=f1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return f1.delete($),!1;try{let Q=Q8(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||!c4(Q)||S1(Z.path)!==Z.path||k2(W0(Z.path,"owner.lock")))return!1;return N$(Z.path,{recursive:!0}),f1.delete($),!0}catch{return!1}}import{createServer as L$,request as O$}from"http";import{connect as I$,isIP as A$}from"net";var W8=120000,_$=15000;function P$($,J,Z){let Q=F8(J).toLowerCase().replace(/\.$/,"");if(!Q||A$(Q))return!1;return $.some((K)=>{if(!R2.test(K))return!1;let B=K.lastIndexOf(":"),G=B>0?K.slice(0,B):K;if(B>0&&Number(K.slice(B+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function T$($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,K=Z?Number(Z[2]):J;return Q&&K>=1&&K<=65535?{host:Q,port:K}:null}async function f2($,J,Z){if(!P$(Z,$,J))return null;let Q=await Y8($);return Q.ok?Q.addresses[0]:null}function J1($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
|
|
27
|
+
Connection: close\r
|
|
28
|
+
Content-Length: 0\r
|
|
29
|
+
\r
|
|
30
|
+
`)}function G8($,J){return new Promise((Z,Q)=>{let K=I$({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),_$);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(G)=>{clearTimeout(B),Q(G)})})}function X8($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(W8,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function U8($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function z8($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=L$((U,Y)=>{(async()=>{let F;try{F=new URL(U.url??"")}catch{F=new URL("invalid:")}let X=Number(F.port||80),W=F.protocol==="http:"?await f2(F.hostname,X,Z):null;if(!W){J(),Y.writeHead(403,{connection:"close"}).end();return}let z=O$({host:W,port:X,method:U.method,path:`${F.pathname}${F.search}`,headers:U8(U.headers,F.host),agent:!1,timeout:W8},(N)=>{Y.writeHead(N.statusCode??502,N.headers),N.pipe(Y)});z.on("timeout",()=>z.destroy()),z.on("error",()=>{if(!Y.headersSent)Y.writeHead(502);Y.end()}),Y.on("close",()=>z.destroy()),U.pipe(z)})().catch(()=>{if(!Y.headersSent)Y.writeHead(502);Y.end()})});B.on("connection",K),B.on("connect",(U,Y,F)=>{K(Y),Y.on("error",()=>Y.destroy()),(async()=>{let X=T$(U.url??"",443),W=X?await f2(X.host,X.port,Z):null;if(!X||!W){J(),J1(Y,403);return}let z=await G8(W,X.port).catch(()=>null);if(!z){J1(Y,502);return}if(Y.destroyed){z.destroy();return}K(z),Y.write(`HTTP/1.1 200 Connection Established\r
|
|
31
|
+
\r
|
|
32
|
+
`),X8(Y,z,F)})().catch(()=>Y.destroy())}),B.on("upgrade",(U,Y,F)=>{K(Y),Y.on("error",()=>Y.destroy()),(async()=>{let X;try{X=new URL(U.url??"")}catch{J1(Y,403);return}let W=Number(X.port||80),z=["http:","ws:"].includes(X.protocol)?await f2(X.hostname,W,Z):null;if(!z){J(),J1(Y,403);return}let N=await G8(z,W).catch(()=>null);if(!N){J1(Y,502);return}K(N);let C=U8(U.headers,X.host),M=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[w,D]of Object.entries(C))for(let j of Array.isArray(D)?D:D===void 0?[]:[D])M.push(`${w}: ${j}`);N.write(`${M.join(`\r
|
|
33
|
+
`)}\r
|
|
34
|
+
\r
|
|
35
|
+
`),X8(Y,N,F)})().catch(()=>Y.destroy())}),await new Promise((U,Y)=>{B.once("error",Y),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as l2,randomUUID as E$}from"crypto";import{closeSync as p1,constants as J0,fchownSync as k$,fstatSync as L0,fsyncSync as S$,linkSync as _8,lstatSync as v2,mkdirSync as P8,openSync as v1,readSync as g8,realpathSync as u2,unlinkSync as T8,writeSync as f$}from"fs";import{isAbsolute as b$,join as x$,relative as y$,sep as h$}from"path";import{platform as p2}from"os";import{getSystemErrorName as m$}from"util";var N8={type:"string",format:"uuid"},w8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,x1={type:"string",minLength:1,maxLength:4096,pattern:w8},b2=V.string().min(1).max(4096).regex(new RegExp(w8)),y1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},h1={device_id:N8,root_id:N8,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},rB={read:{schema:V.object({...y1,path:b2,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:{...h1,path:x1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...y1,path:b2,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:{...h1,path:x1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...y1,command:V.string().min(1).max(16000),cwd:b2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...h1,command:{type:"string",minLength:1,maxLength:16000},cwd:x1,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}}},z0=1073741824,Z1=600000,H8=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,M8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${H8}(?:/${H8})*(?![\s\S])`,j8=new RegExp(M8);function L8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&j8.test($)}var x2=V.string().min(1).max(4096).regex(j8),y2={...x1,pattern:M8},O8=V.string().regex(/^[a-f0-9]{64}$/),I8=V.object({kind:V.literal("workspace"),path:x2}).strict(),R$=V.discriminatedUnion("kind",[I8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:O8}).strict()]),m1=1,Q1="cloud_workspace_id",h2="cloud_workspace",m2=1,q$=V.discriminatedUnion("kind",[I8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(z0),sha256:O8}).strict()]),A8=V.object({source_version:V.literal(m1),source:q$,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(),[Q1]:V.string().min(1).max(160).optional()}).strict(),aB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(m1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var C8=V.object({...y1,timeout_ms:V.number().int().min(1000).max(Z1).optional(),source_path:x2,destination_path:x2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),D8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...h1,timeout_ms:{type:"integer",minimum:1000,maximum:Z1},source_path:y2,destination_path:y2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},g$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:y2},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}]},iB=V.union([C8,C8.omit({source_path:!0}).extend({source:R$}).strict()]),oB={...D8,required:["device_id","root_id","destination_path"],properties:{...D8.properties,source:g$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var s2=65536;function l($){throw new H($,$)}function d1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function u1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return l(Z)}function v$($,J,Z){let Q;switch(d1($)){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 u1($,J,Q)}function u$($){if(typeof $!=="string"||$.length>16384)return l("transfer_url_invalid");let J;try{J=new URL($)}catch{return l("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return l("transfer_url_invalid");return J.href}var d2=J0.O_RDONLY|J0.O_DIRECTORY|J0.O_NOFOLLOW;async function p$(){if(p2()==="win32"){let F=new Map,X,W=-1,z=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(D)=>{let j=y$(X,D);return j===""||j!==".."&&!j.startsWith(`..${h$}`)&&!b$(j)},C=(D)=>{let j=v2(D);if(j.isSymbolicLink())throw z();if(!j.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let O=u2(D);if(X??=O,!N(O))throw z();return F.set(W,{path:D,real:O}),W--},M=(D)=>{let j=F.get(D);if(u2(j.path)!==j.real)throw z();return j.path},w=(D,j)=>{if(l1(j))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return x$(F.get(D).path,j)};return{root:C,openDirectory:(D,j)=>C(w(D,j)),open:(D,j,O,A=384)=>{let b=w(D,j);if(v2(b,{throwIfNoEntry:!1})?.isSymbolicLink())throw z();M(D);let I=v1(b,O,A);try{let R=L0(I),P=v2(b);if(P.isSymbolicLink()||R.ino!==P.ino||R.dev!==P.dev||!N(u2(b)))throw z()}catch(R){throw p1(I),R}return I},mkdir:(D,j)=>{let O=w(D,j);M(D),P8(O)},link:(D,j,O)=>{let A=w(D,j),b=w(D,O);M(D),_8(A,b)},unlink:(D,j)=>T8(w(D,j)),closeDirectory:(D)=>{F.delete(D)},inherit:()=>{},close:()=>{}}}let $={root:(F)=>v1(F,d2),closeDirectory:p1,inherit:d$};if(p2()==="linux")return{...$,openDirectory:(F,X)=>v1(`/proc/self/fd/${F}/${X}`,d2),open:(F,X,W,z=384)=>v1(`/proc/self/fd/${F}/${X}`,W,z),mkdir:(F,X)=>P8(`/proc/self/fd/${F}/${X}`,{mode:448}),link:(F,X,W)=>_8(`/proc/self/fd/${F}/${X}`,`/proc/self/fd/${F}/${W}`),unlink:(F,X)=>T8(`/proc/self/fd/${F}/${X}`),close:()=>{}};if(p2()!=="darwin")return l("transfer_platform_unsupported");let{dlopen:J,FFIType:Z,ptr:Q,read:K}=await import("bun:ffi"),B=J("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:Z.ptr},openat:{args:[Z.i32,Z.ptr,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32],returns:Z.i32},mkdirat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32},linkat:{args:[Z.i32,Z.ptr,Z.i32,Z.ptr,Z.i32],returns:Z.i32},unlinkat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32}}),G=B.symbols.__error();if(G===null)return B.close(),l("transfer_path_unavailable");let U=(F)=>{if(F<0){let X=m$(-K.i32(G));throw Object.assign(Error("transfer_path_unavailable"),{code:X})}return F},Y=(F,X,W,z=384)=>U(B.symbols.openat(F,Q(Buffer.from(`${X}\x00`)),W,z,0,0,0,0,z));return{...$,openDirectory:(F,X)=>Y(F,X,d2),open:Y,mkdir:(F,X)=>{U(B.symbols.mkdirat(F,Q(Buffer.from(`${X}\x00`)),448))},link:(F,X,W)=>{U(B.symbols.linkat(F,Q(Buffer.from(`${X}\x00`)),F,Q(Buffer.from(`${W}\x00`)),0))},unlink:(F,X)=>{U(B.symbols.unlinkat(F,Q(Buffer.from(`${X}\x00`)),0))},close:()=>B.close()}}function d$($,J){let Z=L0($),Q=L0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)k$(J,Z.uid,Z.gid)}function l$($,J,Z,Q){if(!L8(Z))return l("transfer_path_invalid");let K=Z.split("/"),B=$.root(J);try{for(let G of K.slice(0,-1)){let U;try{U=$.openDirectory(B,G)}catch(Y){if(!Q||d1(Y)!=="ENOENT")throw Y;try{$.mkdir(B,G)}catch(F){if(d1(F)!=="EEXIST")throw F}U=$.openDirectory(B,G),$.inherit(B,U)}$.closeDirectory(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw $.closeDirectory(B),G}}function R8($,J){let Z=L0($,{bigint:!0});if(!Z.isFile()||Z.size>z0)return l("transfer_file_invalid");let Q=l2("sha256"),K=Buffer.alloc(s2),B=0;while(!0){J.throwIfAborted();let U=g8($,K,0,K.length,B);if(!U)break;if(B+=U,B>z0)return l("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=L0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return l("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=u$($.payload.url),Z=await p$(),Q,K,B;try{if(Q=l$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK);let z=L0(K,{bigint:!0});if(!z.isFile()||z.size>z0)return l("transfer_file_invalid");let N=l2("sha256"),C=0,M=K,w,D=new ReadableStream({pull(b){try{$.signal.throwIfAborted();let I=Buffer.alloc(s2),R=g8(M,I,0,I.length,C);if(!R){b.close();return}if(C+=R,C>z.size)return l("transfer_source_changed");N.update(I.subarray(0,R)),b.enqueue(I.subarray(0,R))}catch(I){throw w=I,I}}});try{let b=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:D,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(z.size)}},{duplex:"half"}));if(w!==void 0)throw w;if(!b.ok)return l("transfer_upload_failed");await b.body?.cancel()}catch(b){if(w!==void 0)throw w;return u1(b,$.signal,"transfer_upload_failed")}let j=L0(K,{bigint:!0});if(BigInt(C)!==z.size||j.size!==z.size||j.mtimeNs!==z.mtimeNs||j.ctimeNs!==z.ctimeNs)return l("transfer_source_changed");let O=N.digest("hex"),A=R8(K,$.signal);if(A.size_bytes!==C||A.sha256!==O)return l("transfer_source_changed");return{size_bytes:C,sha256:O,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>z0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return l("transfer_receipt_invalid");let Y;try{Y=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK)}catch(z){if(d1(z)!=="ENOENT")throw z}if(Y!==void 0){try{let z=R8(Y,$.signal);if(z.size_bytes===G&&z.sha256===U)return{...z,outcome:"already_present"}}finally{p1(Y)}return l("transfer_destination_exists")}B=`.reason-copy-${E$()}`,K=Z.open(Q.fd,B,J0.O_CREAT|J0.O_EXCL|J0.O_WRONLY|J0.O_NOFOLLOW,384),Z.inherit(Q.fd,K);let F;try{let z=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!z.ok||!z.body)return l("transfer_download_failed");F=z.body.getReader()}catch(z){return u1(z,$.signal,"transfer_download_failed")}let X=l2("sha256"),W=0;try{while(!0){$.signal.throwIfAborted();let z=await F.read().catch((N)=>u1(N,$.signal,"transfer_download_failed"));if(z.done)break;if(W+=z.value.length,W>G)return l("transfer_size_mismatch");X.update(z.value);for(let N=0;N<z.value.length;)$.signal.throwIfAborted(),N+=f$(K,z.value,N,Math.min(s2,z.value.length-N))}}finally{await F.cancel().catch(()=>{})}if(W!==G||X.digest("hex")!==U)return l("transfer_hash_mismatch");return S$(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)p1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}Z.closeDirectory(Q.fd)}}finally{Z.close()}}}}catch(J){return v$(J,$.signal,$.direction)}}import{spawn as c$}from"child_process";import{mkdtempSync as n$,rmSync as r$,writeFileSync as a$}from"fs";import{constants as i$,platform as o$,tmpdir as t$}from"os";import{join as f8}from"path";import{gunzipSync as s$,gzipSync as UV}from"zlib";var k8=900000,YV=k8+60000,K1=49152,E8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),S8=V.object({version:V.literal(1),script_gzip:E8(163840),stdin_gzip:E8(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(k8)}).strict(),c2=V.string().max(K1+256),WV=V.object({exit_code:V.number().int().min(0).max(255),stdout:c2,stderr:c2,combined:c2.optional()}).strict();function n2($){return s$(Buffer.from($,"base64")).toString("utf8")}var e$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",$J=["RUSTUP_HOME","TZ","LC_ALL"],JJ=2000,ZJ=100;function a2(){return o$()==="linux"&&process.geteuid?.()===0}function r2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let Y=U.subarray(0,J-Q);Z.push(Y),Q+=Y.length,U=U.subarray(Y.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
36
|
+
[reason: ${G} bytes of output omitted]
|
|
37
|
+
`:"")+K.toString("utf8")}}}async function b8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=S8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=n$(f8(t$(),"reason-workspace-setup-"));try{let U=f8(G,"setup.sh");a$(U,K,{mode:384});let Y={PATH:e$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of $J)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=c$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),JJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,ZJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(i$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{r$(G,{recursive:!0,force:!0})}}import{chmodSync as QJ,mkdtempSync as KJ,realpathSync as m8,rmSync as BJ}from"fs";import{tmpdir as VJ}from"os";import{dirname as GJ,join as i2,sep as XJ}from"path";function o2($){return h8($,y8($)!==null).repoPath}function v8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>GJ(x8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=m8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${XJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function u8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("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=KJ(i2(VJ(),`reason-cloud-copy-${process.pid}-`));try{QJ(Z,448);let Q=m8(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 K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{BJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as V9,existsSync as F0,fstatSync as G9,ftruncateSync as dQ,lstatSync as p3,mkdirSync as lQ,mkdtempSync as sQ,openSync as X9,readSync as cQ,realpathSync as X0,rmSync as nQ,statSync as w1,writeSync as rQ}from"fs";import{homedir as H1,platform as E,tmpdir as aQ}from"os";import{dirname as C1,isAbsolute as iQ,join as U9,relative as d3,resolve as oQ,sep as tQ}from"path";import{spawn as eQ}from"child_process";import{createHash as zJ,randomBytes as NJ}from"crypto";var t2=30000,UJ=1800000,FJ=5000,s1=30000,YJ=n1+15000,p8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,WJ=[/^\/app\/local-runtime\/operations\/claim$/,p8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(WJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},YJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(FJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(UJ,t2*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(c1,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()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!p8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,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 J3=["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 hV($,J={}){let Z=HJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function HJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function CJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function DJ($){if($ instanceof N0)return!1;if($ instanceof r1)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 wJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function MJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function mV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function d8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function l8($){return zJ("sha256").update($??"").digest("hex")}function jJ($){return a8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function s8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var LJ=20000,OJ=1e4,c8=[2000,4000],IJ=30000,AJ=15000;function n8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class _J{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=i8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??c8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...n8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return o8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.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>=LJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,c8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=OJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=l8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>NJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(jJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!r8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,l8("")),...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&&d8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??MJ,Y=this.sessionFor($,J.device),F=Math.max(IJ,(J.holdMs??0)+AJ),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":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 C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...n8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&CJ(N.status),w=DJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:wJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return t8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return e8(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return $5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return J5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Z5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return Q5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});B5(Q)}async localSubscription($,J,Z){return K5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!s8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return V5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.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)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return G5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!s8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.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 X5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(d8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return F5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-bm94e9r0.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.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 U5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.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 PJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=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 a1($,J){if(PJ.has($))return!1;if(V1.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($)||V1.has($)))return!1;return!0}import{accessSync as TJ,constants as RJ,existsSync as qJ,statSync as gJ}from"fs";import{basename as EJ,isAbsolute as kJ}from"path";var G1=["-lic"],Y5="/bin/zsh",SJ=new Set(["zsh","bash"]),z5=20000,Z3=60000,fJ=65536,bJ=64,xJ=8192,yJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),hJ=["DYLD_","LD_"];function mJ($){let J=$.toUpperCase();return yJ.has(J)||hJ.some((Z)=>J.startsWith(Z))}function N5($=process.env){return!0}function vJ($){if(!kJ($)||$.includes("\x00"))return!1;if(!SJ.has(EJ($)))return!1;try{if(!gJ($).isFile())return!1;return TJ($,RJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return W5()??Y5;let J=$.SHELL?.trim();if(J&&vJ(J))return J;return Y5}function Q3($=process.env){return N5($)&&qJ(S0($))}function K3($=process.env){if(!N5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>fJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>bJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>xJ)throw new H("invalid_payload","env entry is invalid or too large.");if(mJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function H5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function C5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.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:Z3}}import{readFile as uJ,readdir as pJ,readlink as dJ,realpath as lJ}from"fs/promises";import{basename as sJ,relative as cJ,sep as nJ}from"path";var O0="/proc",rJ=250,D5=500,aJ=50,iJ=250,oJ=1024,w5=4096,tJ=1,eJ=3,M5=9,$Z="0A",JZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>pJ($),readLink:($)=>dJ($),readTextFile:($)=>uJ($,"utf8"),realPath:($)=>lJ($)};function L5($,J){return J===$||J.startsWith(`${$}${nJ}`)}function ZZ($,J){return cJ($,J)||"."}async function O5($){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 I5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,w5).split(`
|
|
38
|
+
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,w5).split("\x00",1)[0]?.trim();return Q?sJ(Q):null}catch{return null}}async function A5($,J=G3){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 _5($,J=G3){let Z=[];for(let Q of await O5(J)){if(Z.length>=rJ)break;let K=await A5(Q,J);if(!K||!L5($,K))continue;Z.push({pid:Q,command:await I5(Q,J),cwd:ZZ($,K)})}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 QZ($){let J=[];for(let Y=0;Y<16;Y+=2)J.push($[Y]<<8|$[Y+1]);if(J.slice(0,5).every((Y)=>Y===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let Y=0;Y<=J.length;Y+=1){if(Y<J.length&&J[Y]===0){if(K<0)K=Y;continue}if(K>=0){let F=Y-K;if(F>Q)Z=K,Q=F;K=-1}}let B=J.map((Y)=>Y.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function KZ($,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`[${QZ(Z)}]:${J}`}return null}function BZ($,J){let Z=[];for(let Q of $.split(`
|
|
39
|
+
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=M5)continue;if(K[eJ]?.toUpperCase()!==$Z)continue;let B=K[tJ]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let Y=KZ(B.slice(0,G),U),F=K[M5];if(!Y||!F||!/^[0-9]+$/.test(F))continue;Z.push({inode:F,port:U,address:Y})}return Z}async function VZ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=D5)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...BZ(Q,D5-J.length))}return J}async function GZ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await O5(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,oJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(JZ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function P5($,J=G3){let Z=await VZ(J),Q=await GZ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let W=Q.get(X.inode);if(W===void 0)continue;K.push({pid:W,port:X.port,address:X.address})}K.sort((X,W)=>X.pid-W.pid||X.port-W.port||(X.address<W.address?-1:X.address>W.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,aJ),G=await Promise.all(B.map(async(X)=>[X,await A5(X,J)])),U=new Map(G),Y=K.filter((X)=>{let W=U.get(X.pid);return Boolean(W&&L5($,W))}),F=new Map(await Promise.all([...new Set(Y.map((X)=>X.pid))].map(async(X)=>[X,await I5(X,J)])));return{ports:Y.slice(0,iJ).map((X)=>({pid:X.pid,command:F.get(X.pid)??null,address:X.address}))}}import{posix as U3}from"path";var i1=200,XZ=250,UZ=250;async function o1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function X3($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var T5="/System/Volumes/Data",FZ=["/tmp","/var","/etc"];function F3($){let J=U3.normalize($);if(J.startsWith(`${T5}/`))J=J.slice(T5.length);return FZ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function R5($){return $&&U3.isAbsolute($)?F3($):null}async function q5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=i1){let K=J.slice(Q,Q+i1).join(",");for(let B of await o1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:R5(B.names[0])})}return Z}async function g5($,J){let Z=F3($),Q=(await o1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=R5(B.names[0]);return G!==null&&X3(Z,G)}).map((B)=>B.pid).slice(0,XZ),K=await q5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&X3(Z,G.cwd)?[{pid:B,command:G.command,cwd:U3.relative(Z,G.cwd)||"."}]:[]})}}async function E5($,J){let Z=F3($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await o1(J,Q),B=await q5(J,K.map((F)=>F.pid)),G=K.map((F)=>F.pid).filter((F)=>{let X=B.get(F)?.cwd;return Boolean(X&&X3(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((F)=>F.names.map((X)=>`${F.pid} ${X}`))),Y=[];for(let F=0;F<G.length;F+=i1){let X=G.slice(F,F+i1).join(",");for(let W of await o1(J,["-a","-p",X,...Q]))for(let z of W.names)if(U.has(`${W.pid} ${z}`))Y.push({pid:W.pid,command:W.command,address:z})}return{ports:Y.slice(0,UZ)}}import{join as IZ}from"path";import{spawn as DZ}from"child_process";import{randomUUID as wZ}from"crypto";import{chmodSync as f5,lstatSync as b5,mkdirSync as MZ,readdirSync as jZ,statSync as LZ,unlinkSync as OZ}from"fs";import{join as W3}from"path";var Y3={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var t1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var I0=()=>{throw Error("proof_visual_contract_invalid")};class k5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function WZ($){if(!X1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new k5;if(!X1($.viewport)||!t1($.viewport.width,1,4096)||!t1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>Y3.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return I0();let J=$.targets.map((Q)=>{if(!X1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return I0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return I0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return I0();Z=$.additionalViewports.map((K)=>{if(!X1(K)||!t1(K.width,1,4096)||!Number.isInteger(K.width)||!t1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return I0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return I0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var NZ=["organizationId","userId","sessionId","runId"],HZ=[...NZ,"prUrl","headSha","skillDigest","evidenceKind"],BG=[...HZ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var CZ={"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 S5($){return CZ[$].directory}var x5=10485760;function y5($={}){let J=$.directory??S5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((w)=>w!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");MZ(J,{recursive:!0,mode:457});let B=b5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");f5(J,457);let G=jZ(J).filter((w)=>/^[a-f0-9-]{36}\.webm$/.test(w)).map((w)=>({name:w,time:LZ(W3(J,w)).mtimeMs})).sort((w,D)=>D.time-w.time);for(let w of G.slice(9))OZ(W3(J,w.name));let U=W3(J,`${wZ()}.webm`),Y=["-f","x11grab","-framerate","12","-i",$.display??":99"],F=($.spawn??DZ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...Y,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(x5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,W,z=!1,N=new Promise((w,D)=>{X=w,W=D});F.stdout.on("data",(w)=>{if(/frame=\s*[1-9]/.test(String(w)))z=!0,X()});let C=new Promise((w,D)=>{F.once("error",()=>{W(Error("cloud_browser_recording_unavailable")),D(Error("cloud_browser_recording_unavailable"))}),F.once("exit",(j)=>{try{if(j!==0&&j!==255)throw Error();let O=b5(U);if(!z||!O.isFile()||O.isSymbolicLink()||O.uid!==process.getuid?.()||O.size<128||O.size>x5+65536)throw Error();f5(U,420),X(),w({path:U,mimeType:"video/webm"})}catch{W(Error("cloud_browser_recording_failed")),D(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let M=setTimeout(()=>F.kill("SIGKILL"),(Number(K)+5)*1000);C.finally(()=>clearTimeout(M)).catch(()=>{}),Z={done:C,stop:()=>{return F.kill("SIGINT"),C}};try{await N}catch(w){throw Z=null,w}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function v5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??h5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=IZ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??m5)();return B??=y5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:b1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as E3}from"child_process";import{createHash as dZ,randomUUID as lZ}from"crypto";import{existsSync as Q0,mkdirSync as P3,mkdtempSync as k3,readdirSync as G2,readFileSync as S3,renameSync as sZ,rmSync as Y1,statSync as Q2,writeFileSync as cZ}from"fs";import{homedir as f3,tmpdir as X6}from"os";import{basename as U6,dirname as T3,join as k,relative as F6,resolve as R3,sep as Y6}from"path";var a=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),e1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),u5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),N3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),H3=["home","lock","side_button","siri","apple_pay"],AZ=V.enum(["tree","screenshot","both","none"]),_Z=V.object({...N3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),D0={observe:AZ.optional(),wait_for:_Z.optional(),timeout:V.number().min(0).max(20).optional()},z3=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...N3.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(H3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),C3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:a}).strict(),V.object({action:V.literal("shutdown"),device:a}).strict(),V.object({action:V.literal("build"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:a.optional(),app_path:e1.optional(),bundle_id:u5.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:a.optional(),bundle_id:u5}).strict(),V.object({action:V.literal("logs"),device:a.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:a.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:e1.optional()}).strict(),V.object({action:V.literal("chrome"),device:a.optional()}).strict(),V.object({action:V.literal("inspect"),device:a.optional()}).strict(),V.object({action:V.literal("tap"),device:a.optional(),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional(),...D0}).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:a.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...D0}).strict(),V.object({action:V.literal("type"),device:a.optional(),text:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("button"),device:a.optional(),name:V.enum(H3),...D0}).strict(),V.object({action:V.literal("open_url"),device:a.optional(),url:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("steps"),device:a.optional(),steps:V.array(z3).min(1).max(30),...D0}).strict(),V.object({action:V.literal("appearance"),device:a.optional(),mode:V.enum(["light","dark"])}).strict()]),p5=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(),AG=V.object({text:V.string(),error:V.string().optional(),device:p5.optional(),devices:V.array(p5).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 _G=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),$2={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. Required for boot and shutdown; for other actions omit it 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",description:"build_status (required): the build_id a build or run returned."},app_path:{type:"string",description:"launch: the built .app from build_status (or pass bundle_id instead)."},bundle_id:{type:"string",description:"terminate (required); launch: an installed app's bundle id instead of app_path."},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number",description:"tap (with y, unless id or label is given) or swipe (required): start point in device points."},y:{type:"number"},x2:{type:"number",description:"swipe (required, with y2): end point in device points."},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect (instead of x and y)."},label:{type:"string",description:"tap: accessibility label from inspect (instead of x and y)."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string",description:"type (required): the text to type."},name:{type:"string",enum:[...H3],description:"button (required)."},url:{type:"string",description:"open_url (required): the URL or deep link."},mode:{type:"string",enum:["light","dark"],description:"appearance (required)."},steps:{type:"array",maxItems:30,description:"steps (required, at least one) or launch and run: 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."}},l5=C3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),PZ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},d5=new Set;function TZ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...$2.steps,minItems:1}:$2[$];if(Z===void 0||d5.has($))return Q;return d5.add($),{...Q,description:Z}}var RZ=l5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn($2,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(PZ[J]??[{required:[]}]).map((K)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((B)=>!K.without?.includes(B)).map((B)=>[B,TZ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),qZ={type:"object",properties:{action:{type:"string",enum:l5.map(($)=>$.action.value)},...$2},required:["action"],additionalProperties:!1},PG={...qZ,anyOf:RZ};import{spawn as j3}from"child_process";import{createHash as EZ}from"crypto";import{existsSync as w3,mkdirSync as J2,mkdtempSync as kZ,readdirSync as s5,readFileSync as c5,renameSync as SZ,rmSync as n5,symlinkSync as M3,writeFileSync as U1}from"fs";import{homedir as fZ}from"os";import{dirname as o5,join as x}from"path";import{createInterface as bZ}from"readline";var D3=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
40
|
+
//
|
|
41
|
+
// Built on the Mac on first use (cli/simulator-host.ts) against the MIT
|
|
42
|
+
// FBSimulatorControl frameworks that the pinned AXe ships, so loading
|
|
43
|
+
// SimulatorKit and connecting to the simulator happen once per process
|
|
44
|
+
// instead of once per action (about a second each, three under load).
|
|
45
|
+
//
|
|
46
|
+
// simulator-host serve <udid>
|
|
47
|
+
// Newline JSON requests on stdin, one newline JSON reply each on stdout,
|
|
48
|
+
// in order: {"id":1,"op":"tap","x":100,"y":200} -> {"id":1,"ok":true}.
|
|
49
|
+
// Ops: touch (phase down|move|up), tap, swipe, button, text, key, tree.
|
|
50
|
+
// Coordinates are device points. \`tree\` answers AXe describe-ui's JSON.
|
|
51
|
+
// simulator-host stream <udid> <fps> <max pixels> <kbps>
|
|
52
|
+
// H.264 (Main, level 4.2) as Annex-B on stdout, encoded with VideoToolbox
|
|
53
|
+
// straight from the simulator's framebuffer. Every keyframe carries
|
|
54
|
+
// SPS/PPS, and every access unit is followed by an AUD, so a reader that
|
|
55
|
+
// splits at AUDs has each frame as soon as it is written.
|
|
56
|
+
//
|
|
57
|
+
// Both modes exit when stdin closes, so they never outlive the worker.
|
|
58
|
+
|
|
59
|
+
import CoreMedia
|
|
60
|
+
import CoreVideo
|
|
61
|
+
import Darwin
|
|
62
|
+
import FBControlCore
|
|
63
|
+
import FBSimulatorControl
|
|
64
|
+
import Foundation
|
|
65
|
+
import IOSurface
|
|
66
|
+
import VideoToolbox
|
|
67
|
+
|
|
68
|
+
@objc final class SilentReporter: NSObject, FBEventReporter {
|
|
69
|
+
var metadata: [String: String] = [:]
|
|
70
|
+
func report(_ subject: FBEventReporterSubject) {}
|
|
71
|
+
func addMetadata(_ metadata: [String: String]) {}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let logger: FBControlCoreLogger = FBControlCoreLoggerFactory.systemLoggerWriting(toStderr: false, withDebugLogging: false)
|
|
75
|
+
|
|
76
|
+
func fail(_ message: String) -> Never {
|
|
77
|
+
FileHandle.standardError.write(Data((message + "\\n").utf8))
|
|
78
|
+
exit(1)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// Writes all of \`data\` to stdout; a closed reader ends the process.
|
|
82
|
+
func writeOut(_ data: Data) {
|
|
83
|
+
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
|
|
84
|
+
var offset = 0
|
|
85
|
+
while offset < buffer.count {
|
|
86
|
+
let written = Darwin.write(1, buffer.baseAddress!.advanced(by: offset), buffer.count - offset)
|
|
87
|
+
if written <= 0 {
|
|
88
|
+
if written < 0 && errno == EINTR { continue }
|
|
89
|
+
exit(0)
|
|
90
|
+
}
|
|
91
|
+
offset += written
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
@MainActor
|
|
97
|
+
func simulator(_ udid: String) async throws -> FBSimulator {
|
|
98
|
+
try FBSimulatorControlFrameworkLoader.essentialFrameworks.loadPrivateFrameworks(logger)
|
|
99
|
+
try FBSimulatorControlFrameworkLoader.xcodeFrameworks.loadPrivateFrameworks(logger)
|
|
100
|
+
FBControlCoreGlobalConfiguration.defaultLogger = logger
|
|
101
|
+
let configuration = FBSimulatorControlConfiguration(deviceSetPath: nil, logger: logger, reporter: SilentReporter())
|
|
102
|
+
let set = try FBSimulatorControl.withConfiguration(configuration).set
|
|
103
|
+
guard let target = set.allSimulators.first(where: { $0.udid == udid }) else { fail("simulator_not_found") }
|
|
104
|
+
guard target.state == .booted else { fail("simulator_not_booted") }
|
|
105
|
+
return target
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// MARK: - serve
|
|
109
|
+
|
|
110
|
+
/// US keyboard: character -> (HID usage, shift).
|
|
111
|
+
let keyboard: [Character: (UInt32, Bool)] = {
|
|
112
|
+
var map: [Character: (UInt32, Bool)] = [:]
|
|
113
|
+
for (index, letter) in "abcdefghijklmnopqrstuvwxyz".enumerated() {
|
|
114
|
+
map[letter] = (UInt32(4 + index), false)
|
|
115
|
+
map[Character(letter.uppercased())] = (UInt32(4 + index), true)
|
|
116
|
+
}
|
|
117
|
+
for (index, digit) in "1234567890".enumerated() { map[digit] = (UInt32(30 + index), false) }
|
|
118
|
+
for (index, symbol) in "!@#$%^&*()".enumerated() { map[symbol] = (UInt32(30 + index), true) }
|
|
119
|
+
let plain: [(Character, UInt32)] = [("\\n", 40), ("\\t", 43), (" ", 44), ("-", 45), ("=", 46), ("[", 47), ("]", 48),
|
|
120
|
+
("\\\\", 49), (";", 51), ("'", 52), ("\`", 53), (",", 54), (".", 55), ("/", 56)]
|
|
121
|
+
let shifted: [(Character, UInt32)] = [("_", 45), ("+", 46), ("{", 47), ("}", 48), ("|", 49), (":", 51), ("\\"", 52),
|
|
122
|
+
("~", 53), ("<", 54), (">", 55), ("?", 56)]
|
|
123
|
+
for (character, usage) in plain { map[character] = (usage, false) }
|
|
124
|
+
for (character, usage) in shifted { map[character] = (usage, true) }
|
|
125
|
+
return map
|
|
126
|
+
}()
|
|
127
|
+
|
|
128
|
+
let buttons: [String: FBSimulatorHIDButton] = [
|
|
129
|
+
"home": .homeButton, "lock": .lock, "side_button": .sideButton, "siri": .siri, "apple_pay": .applePay,
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
/// AXe describe-ui's keys (its schema), so the worker parses one format either way.
|
|
133
|
+
let treeKeys: Set<FBAXKeys> = [.label, .frame, .value, .uniqueID, .type, .title, .frameDict, .help, .enabled,
|
|
134
|
+
.customActions, .role, .roleDescription, .subrole, .contentRequired, .pid]
|
|
135
|
+
|
|
136
|
+
func withTraits(_ value: Any) -> Any {
|
|
137
|
+
if let list = value as? [Any] { return list.map(withTraits) }
|
|
138
|
+
guard var element = value as? [String: Any] else { return value }
|
|
139
|
+
for (key, child) in element { element[key] = withTraits(child) }
|
|
140
|
+
if element["type"] != nil && element["traits"] == nil { element["traits"] = [String]() }
|
|
141
|
+
return element
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
func hasChildren(_ value: Any) -> Bool {
|
|
145
|
+
let roots = (value as? [[String: Any]]) ?? ((value as? [String: Any]).map { [$0] } ?? [])
|
|
146
|
+
return roots.contains { (($0["children"] as? [Any])?.isEmpty == false) }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
@MainActor
|
|
150
|
+
func readTree(_ target: FBSimulator) async throws -> String {
|
|
151
|
+
var latest: Any = []
|
|
152
|
+
for attempt in 0..<4 {
|
|
153
|
+
let element = try await target.accessibilityElementForFrontmostApplication()
|
|
154
|
+
defer { element.close() }
|
|
155
|
+
let response = try element.serialize(with: FBAccessibilityRequestOptions(nestedFormat: true, keys: treeKeys))
|
|
156
|
+
latest = withTraits(response.elements)
|
|
157
|
+
if hasChildren(latest) { break }
|
|
158
|
+
if attempt < 3 { try await Task.sleep(for: .milliseconds(50 << attempt)) }
|
|
159
|
+
}
|
|
160
|
+
let data = try JSONSerialization.data(withJSONObject: latest)
|
|
161
|
+
return String(decoding: data, as: UTF8.self)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
@MainActor
|
|
165
|
+
func handle(_ request: [String: Any], target: FBSimulator, hid: FBSimulatorHID) async throws -> [String: Any] {
|
|
166
|
+
let number = { (key: String) -> Double in
|
|
167
|
+
guard let value = request[key] as? Double else { throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "missing \\(key)"]) }
|
|
168
|
+
return value
|
|
169
|
+
}
|
|
170
|
+
switch request["op"] as? String {
|
|
171
|
+
case "touch":
|
|
172
|
+
let direction: FBSimulatorHIDDirection = (request["phase"] as? String) == "up" ? .up : .down
|
|
173
|
+
try await hid.send(event: .touch(direction: direction, x: try number("x"), y: try number("y")), logger: logger)
|
|
174
|
+
case "tap":
|
|
175
|
+
let duration = request["duration"] as? Double ?? 0
|
|
176
|
+
let event: FBSimulatorHIDEvent = duration > 0
|
|
177
|
+
? .tapAt(x: try number("x"), y: try number("y"), duration: duration) : .tapAt(x: try number("x"), y: try number("y"))
|
|
178
|
+
try await hid.send(event: event, logger: logger)
|
|
179
|
+
case "swipe":
|
|
180
|
+
try await hid.send(event: .swipe(try number("x"), yStart: try number("y"), xEnd: try number("x2"), yEnd: try number("y2"),
|
|
181
|
+
delta: request["delta"] as? Double ?? 10, duration: request["duration"] as? Double ?? 0.3), logger: logger)
|
|
182
|
+
case "button":
|
|
183
|
+
guard let button = buttons[request["name"] as? String ?? ""] else { throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "unknown button"]) }
|
|
184
|
+
try await hid.send(event: .shortButtonPress(button), logger: logger)
|
|
185
|
+
case "text":
|
|
186
|
+
var events: [FBSimulatorHIDEvent] = []
|
|
187
|
+
for character in request["text"] as? String ?? "" {
|
|
188
|
+
guard let (usage, shift) = keyboard[character] else {
|
|
189
|
+
throw NSError(domain: "simulator-host", code: 2, userInfo: [NSLocalizedDescriptionKey: "unsupported character"])
|
|
190
|
+
}
|
|
191
|
+
if shift { events.append(.keyboard(direction: .down, keyCode: 225)) }
|
|
192
|
+
events.append(.keyboard(direction: .down, keyCode: usage))
|
|
193
|
+
events.append(.keyboard(direction: .up, keyCode: usage))
|
|
194
|
+
if shift { events.append(.keyboard(direction: .up, keyCode: 225)) }
|
|
195
|
+
}
|
|
196
|
+
if !events.isEmpty { try await hid.send(event: .composite(events), logger: logger) }
|
|
197
|
+
case "key":
|
|
198
|
+
let direction: FBSimulatorHIDDirection = (request["down"] as? Bool) == false ? .up : .down
|
|
199
|
+
try await hid.send(event: .keyboard(direction: direction, keyCode: UInt32(try number("usage"))), logger: logger)
|
|
200
|
+
case "tree":
|
|
201
|
+
return ["tree": try await readTree(target)]
|
|
202
|
+
default:
|
|
203
|
+
throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "unknown op"])
|
|
204
|
+
}
|
|
205
|
+
return [:]
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
@MainActor
|
|
209
|
+
func serve(_ udid: String) async {
|
|
210
|
+
let target: FBSimulator
|
|
211
|
+
let hid: FBSimulatorHID
|
|
212
|
+
do {
|
|
213
|
+
target = try await simulator(udid)
|
|
214
|
+
hid = try await target.connectToHID()
|
|
215
|
+
} catch {
|
|
216
|
+
fail("connect_failed: \\(error.localizedDescription)")
|
|
217
|
+
}
|
|
218
|
+
writeOut(Data("{\\"ready\\":true}\\n".utf8))
|
|
219
|
+
do {
|
|
220
|
+
for try await line in FileHandle.standardInput.bytes.lines {
|
|
221
|
+
guard let request = (try? JSONSerialization.jsonObject(with: Data(line.utf8))) as? [String: Any] else { continue }
|
|
222
|
+
var reply: [String: Any]
|
|
223
|
+
do {
|
|
224
|
+
reply = try await handle(request, target: target, hid: hid)
|
|
225
|
+
reply["ok"] = true
|
|
226
|
+
} catch {
|
|
227
|
+
reply = ["ok": false, "error": error.localizedDescription]
|
|
228
|
+
}
|
|
229
|
+
reply["id"] = request["id"] ?? 0
|
|
230
|
+
var data = (try? JSONSerialization.data(withJSONObject: reply)) ?? Data("{\\"ok\\":false}".utf8)
|
|
231
|
+
data.append(0x0A)
|
|
232
|
+
writeOut(data)
|
|
233
|
+
}
|
|
234
|
+
} catch {}
|
|
235
|
+
exit(0)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// MARK: - stream
|
|
239
|
+
|
|
240
|
+
let startCode = Data([0, 0, 0, 1])
|
|
241
|
+
let accessUnitDelimiter = Data([0, 0, 0, 1, 0x09, 0xF0])
|
|
242
|
+
|
|
243
|
+
struct BitReader {
|
|
244
|
+
let bytes: [UInt8]
|
|
245
|
+
var position = 0
|
|
246
|
+
mutating func bit() -> UInt32? {
|
|
247
|
+
guard position < bytes.count * 8 else { return nil }
|
|
248
|
+
defer { position += 1 }
|
|
249
|
+
return UInt32(bytes[position >> 3] >> (7 - UInt8(position & 7)) & 1)
|
|
250
|
+
}
|
|
251
|
+
mutating func bits(_ count: Int) -> UInt32? {
|
|
252
|
+
var value: UInt32 = 0
|
|
253
|
+
for _ in 0..<count { guard let next = bit() else { return nil }; value = value << 1 | next }
|
|
254
|
+
return value
|
|
255
|
+
}
|
|
256
|
+
mutating func ue() -> UInt32? {
|
|
257
|
+
var zeros = 0
|
|
258
|
+
while true { guard let next = bit() else { return nil }; if next == 1 { break }; zeros += 1; if zeros > 31 { return nil } }
|
|
259
|
+
guard let rest = bits(zeros) else { return nil }
|
|
260
|
+
return (1 << zeros) - 1 + rest
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
struct BitWriter {
|
|
265
|
+
var bytes: [UInt8] = []
|
|
266
|
+
var count = 0
|
|
267
|
+
mutating func bit(_ value: UInt32) {
|
|
268
|
+
if count & 7 == 0 { bytes.append(0) }
|
|
269
|
+
if value & 1 == 1 { bytes[bytes.count - 1] |= 1 << (7 - UInt8(count & 7)) }
|
|
270
|
+
count += 1
|
|
271
|
+
}
|
|
272
|
+
mutating func bits(_ value: UInt32, _ width: Int) { for shift in stride(from: width - 1, through: 0, by: -1) { bit(value >> UInt32(shift)) } }
|
|
273
|
+
mutating func ue(_ value: UInt32) {
|
|
274
|
+
let coded = value + 1
|
|
275
|
+
let width = 32 - coded.leadingZeroBitCount
|
|
276
|
+
bits(0, width - 1)
|
|
277
|
+
bits(coded, width)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/// The SPS with a VUI that says frames come out in decode order, one at a time. VideoToolbox writes no
|
|
282
|
+
/// bitstream restriction, so a browser decoder may hold the newest frames back for reordering; on a
|
|
283
|
+
/// screen that stops changing, the last one would never be shown. Any SPS this does not expect is kept.
|
|
284
|
+
func lowDelaySps(_ nal: Data) -> Data {
|
|
285
|
+
var raw: [UInt8] = []
|
|
286
|
+
var zeros = 0
|
|
287
|
+
for byte in nal.dropFirst() {
|
|
288
|
+
if zeros >= 2 && byte == 3 { zeros = 0; continue }
|
|
289
|
+
raw.append(byte)
|
|
290
|
+
zeros = byte == 0 ? zeros + 1 : 0
|
|
291
|
+
}
|
|
292
|
+
var reader = BitReader(bytes: raw)
|
|
293
|
+
var writer = BitWriter()
|
|
294
|
+
func copyBits(_ width: Int) -> UInt32? { guard let value = reader.bits(width) else { return nil }; writer.bits(value, width); return value }
|
|
295
|
+
func copyUe() -> UInt32? { guard let value = reader.ue() else { return nil }; writer.ue(value); return value }
|
|
296
|
+
guard let profile = copyBits(8), copyBits(16) != nil, copyUe() != nil else { return nal }
|
|
297
|
+
if [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135].contains(profile) {
|
|
298
|
+
guard let chroma = copyUe() else { return nal }
|
|
299
|
+
if chroma == 3 { guard copyBits(1) != nil else { return nal } }
|
|
300
|
+
guard copyUe() != nil, copyUe() != nil, copyBits(1) != nil, let scaling = copyBits(1), scaling == 0 else { return nal }
|
|
301
|
+
}
|
|
302
|
+
guard copyUe() != nil, let pocType = copyUe() else { return nal }
|
|
303
|
+
if pocType == 0 { guard copyUe() != nil else { return nal } } else if pocType != 2 { return nal }
|
|
304
|
+
guard let references = copyUe(), copyBits(1) != nil, copyUe() != nil, copyUe() != nil, let frameOnly = copyBits(1) else { return nal }
|
|
305
|
+
if frameOnly == 0 { guard copyBits(1) != nil else { return nal } }
|
|
306
|
+
guard copyBits(1) != nil, let cropping = copyBits(1) else { return nal }
|
|
307
|
+
if cropping == 1 { for _ in 0..<4 { guard copyUe() != nil else { return nal } } }
|
|
308
|
+
guard reader.bits(1) == 0 else { return nal }
|
|
309
|
+
writer.bit(1) // vui_parameters_present_flag
|
|
310
|
+
writer.bits(0, 6) // aspect ratio, overscan, video signal, chroma location, timing, NAL HRD
|
|
311
|
+
writer.bit(0) // VCL HRD
|
|
312
|
+
writer.bit(0) // pic_struct_present_flag
|
|
313
|
+
writer.bit(1) // bitstream_restriction_flag
|
|
314
|
+
writer.bit(1) // motion_vectors_over_pic_boundaries_flag
|
|
315
|
+
writer.ue(2); writer.ue(1); writer.ue(16); writer.ue(16)
|
|
316
|
+
writer.ue(0) // max_num_reorder_frames
|
|
317
|
+
writer.ue(max(1, references)) // max_dec_frame_buffering
|
|
318
|
+
writer.bit(1) // rbsp_stop_one_bit
|
|
319
|
+
while writer.count & 7 != 0 { writer.bit(0) }
|
|
320
|
+
var out = Data([nal.first!])
|
|
321
|
+
zeros = 0
|
|
322
|
+
for byte in writer.bytes {
|
|
323
|
+
if zeros >= 2 && byte <= 3 { out.append(3); zeros = 0 }
|
|
324
|
+
out.append(byte)
|
|
325
|
+
zeros = byte == 0 ? zeros + 1 : 0
|
|
326
|
+
}
|
|
327
|
+
return out
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
final class Encoder: NSObject, FBFramebufferConsumer, @unchecked Sendable {
|
|
331
|
+
let queue = DispatchQueue(label: "simulator-host.encode")
|
|
332
|
+
let fps: Int
|
|
333
|
+
let maxPixels: Double
|
|
334
|
+
let kbps: Int
|
|
335
|
+
var surface: IOSurface?
|
|
336
|
+
var dirty = true
|
|
337
|
+
var forceKey = true
|
|
338
|
+
var session: VTCompressionSession?
|
|
339
|
+
var transfer: VTPixelTransferSession?
|
|
340
|
+
var size = (width: 0, height: 0)
|
|
341
|
+
var frames: Int64 = 0
|
|
342
|
+
|
|
343
|
+
init(fps: Int, maxPixels: Double, kbps: Int) {
|
|
344
|
+
self.fps = fps
|
|
345
|
+
self.maxPixels = maxPixels
|
|
346
|
+
self.kbps = kbps
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
func didChange(_ surface: IOSurface?) {
|
|
350
|
+
self.surface = surface
|
|
351
|
+
dirty = true
|
|
352
|
+
forceKey = true
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
func didReceiveDamageRect() { dirty = true }
|
|
356
|
+
|
|
357
|
+
/// The encoded picture: the framebuffer scaled to stay within \`maxPixels\`, even sides.
|
|
358
|
+
func outputSize(_ surface: IOSurface) -> (width: Int, height: Int) {
|
|
359
|
+
let width = Double(IOSurfaceGetWidth(surface)), height = Double(IOSurfaceGetHeight(surface))
|
|
360
|
+
let fit = min(1, (maxPixels / (width * height)).squareRoot())
|
|
361
|
+
let even = { (value: Double) in max(2, Int(value * fit) / 2 * 2) }
|
|
362
|
+
return (even(width), even(height))
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
func makeSession(_ width: Int, _ height: Int) {
|
|
366
|
+
if let session { VTCompressionSessionInvalidate(session) }
|
|
367
|
+
var created: VTCompressionSession?
|
|
368
|
+
let status = VTCompressionSessionCreate(allocator: nil, width: Int32(width), height: Int32(height),
|
|
369
|
+
codecType: kCMVideoCodecType_H264, encoderSpecification: nil, imageBufferAttributes: nil,
|
|
370
|
+
compressedDataAllocator: nil, outputCallback: nil, refcon: nil, compressionSessionOut: &created)
|
|
371
|
+
guard status == noErr, let created else { fail("encoder_failed \\(status)") }
|
|
372
|
+
let set = { (key: CFString, value: CFTypeRef) in _ = VTSessionSetProperty(created, key: key, value: value) }
|
|
373
|
+
set(kVTCompressionPropertyKey_RealTime, kCFBooleanTrue)
|
|
374
|
+
set(kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Main_4_2)
|
|
375
|
+
set(kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse)
|
|
376
|
+
set(kVTCompressionPropertyKey_MaxFrameDelayCount, 0 as CFNumber)
|
|
377
|
+
set(kVTCompressionPropertyKey_ExpectedFrameRate, fps as CFNumber)
|
|
378
|
+
set(kVTCompressionPropertyKey_AverageBitRate, (kbps * 1000) as CFNumber)
|
|
379
|
+
// Keyframes come from a (re)start or a framebuffer change; this is only a safety net.
|
|
380
|
+
set(kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 60 as CFNumber)
|
|
381
|
+
VTCompressionSessionPrepareToEncodeFrames(created)
|
|
382
|
+
session = created
|
|
383
|
+
size = (width, height)
|
|
384
|
+
var createdTransfer: VTPixelTransferSession?
|
|
385
|
+
VTPixelTransferSessionCreate(allocator: nil, pixelTransferSessionOut: &createdTransfer)
|
|
386
|
+
transfer = createdTransfer
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
func tick() {
|
|
390
|
+
guard dirty, let surface else { return }
|
|
391
|
+
dirty = false
|
|
392
|
+
let wanted = outputSize(surface)
|
|
393
|
+
if session == nil || wanted.width != size.width || wanted.height != size.height { makeSession(wanted.width, wanted.height) }
|
|
394
|
+
guard let session, let transfer, let pool = VTCompressionSessionGetPixelBufferPool(session) else { return }
|
|
395
|
+
var source: Unmanaged<CVPixelBuffer>?
|
|
396
|
+
guard CVPixelBufferCreateWithIOSurface(nil, surface, nil, &source) == kCVReturnSuccess, let source else { return }
|
|
397
|
+
let input = source.takeRetainedValue()
|
|
398
|
+
var output: CVPixelBuffer?
|
|
399
|
+
guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &output) == kCVReturnSuccess, let output else { return }
|
|
400
|
+
guard VTPixelTransferSessionTransferImage(transfer, from: input, to: output) == noErr else { return }
|
|
401
|
+
let time = CMTime(value: frames, timescale: CMTimeScale(fps))
|
|
402
|
+
frames += 1
|
|
403
|
+
let options = forceKey ? [kVTEncodeFrameOptionKey_ForceKeyFrame: kCFBooleanTrue] as CFDictionary : nil
|
|
404
|
+
forceKey = false
|
|
405
|
+
VTCompressionSessionEncodeFrame(session, imageBuffer: output, presentationTimeStamp: time, duration: .invalid,
|
|
406
|
+
frameProperties: options, infoFlagsOut: nil) { status, _, sample in
|
|
407
|
+
guard status == noErr, let sample else { return }
|
|
408
|
+
Encoder.write(sample)
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/// One access unit as Annex-B, then the next unit's AUD: the reader splits at AUDs, so the unit is complete now.
|
|
413
|
+
static func write(_ sample: CMSampleBuffer) {
|
|
414
|
+
guard let block = CMSampleBufferGetDataBuffer(sample), let format = CMSampleBufferGetFormatDescription(sample) else { return }
|
|
415
|
+
let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[CFString: Any]]
|
|
416
|
+
let key = !((attachments?.first?[kCMSampleAttachmentKey_NotSync] as? Bool) ?? false)
|
|
417
|
+
var unit = Data()
|
|
418
|
+
if key {
|
|
419
|
+
var count = 0
|
|
420
|
+
CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: 0, parameterSetPointerOut: nil,
|
|
421
|
+
parameterSetSizeOut: nil, parameterSetCountOut: &count, nalUnitHeaderLengthOut: nil)
|
|
422
|
+
for index in 0..<count {
|
|
423
|
+
var pointer: UnsafePointer<UInt8>?
|
|
424
|
+
var length = 0
|
|
425
|
+
CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: index, parameterSetPointerOut: &pointer,
|
|
426
|
+
parameterSetSizeOut: &length, parameterSetCountOut: nil, nalUnitHeaderLengthOut: nil)
|
|
427
|
+
guard let pointer, length > 0 else { continue }
|
|
428
|
+
let set = Data(bytes: pointer, count: length)
|
|
429
|
+
unit.append(startCode)
|
|
430
|
+
unit.append(set[set.startIndex] & 0x1F == 7 ? lowDelaySps(set) : set)
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
var total = 0
|
|
434
|
+
var base: UnsafeMutablePointer<CChar>?
|
|
435
|
+
guard CMBlockBufferGetDataPointer(block, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &total, dataPointerOut: &base) == noErr,
|
|
436
|
+
let base else { return }
|
|
437
|
+
var offset = 0
|
|
438
|
+
while offset + 4 <= total {
|
|
439
|
+
var length: UInt32 = 0
|
|
440
|
+
memcpy(&length, base.advanced(by: offset), 4)
|
|
441
|
+
let nal = Int(CFSwapInt32BigToHost(length))
|
|
442
|
+
offset += 4
|
|
443
|
+
guard offset + nal <= total else { break }
|
|
444
|
+
unit.append(startCode)
|
|
445
|
+
base.advanced(by: offset).withMemoryRebound(to: UInt8.self, capacity: nal) { unit.append($0, count: nal) }
|
|
446
|
+
offset += nal
|
|
447
|
+
}
|
|
448
|
+
unit.append(accessUnitDelimiter)
|
|
449
|
+
writeOut(unit)
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
@MainActor
|
|
454
|
+
func stream(_ udid: String, fps: Int, maxPixels: Double, kbps: Int) async {
|
|
455
|
+
let target: FBSimulator
|
|
456
|
+
let framebuffer: FBFramebuffer
|
|
457
|
+
do {
|
|
458
|
+
target = try await simulator(udid)
|
|
459
|
+
framebuffer = try FBFramebuffer.mainScreenSurface(for: target, logger: logger)
|
|
460
|
+
} catch {
|
|
461
|
+
fail("connect_failed: \\(error.localizedDescription)")
|
|
462
|
+
}
|
|
463
|
+
let encoder = Encoder(fps: fps, maxPixels: maxPixels, kbps: kbps)
|
|
464
|
+
let first = framebuffer.attach(encoder, on: encoder.queue)
|
|
465
|
+
encoder.queue.async { if let first, encoder.surface == nil { encoder.surface = first } }
|
|
466
|
+
writeOut(accessUnitDelimiter)
|
|
467
|
+
let timer = DispatchSource.makeTimerSource(queue: encoder.queue)
|
|
468
|
+
timer.schedule(deadline: .now(), repeating: .nanoseconds(1_000_000_000 / max(1, fps)))
|
|
469
|
+
timer.setEventHandler { encoder.tick() }
|
|
470
|
+
timer.resume()
|
|
471
|
+
// "key" on stdin asks for a keyframe; end of stdin ends the stream.
|
|
472
|
+
do {
|
|
473
|
+
for try await line in FileHandle.standardInput.bytes.lines where line == "key" {
|
|
474
|
+
encoder.queue.async { encoder.forceKey = true; encoder.dirty = true }
|
|
475
|
+
}
|
|
476
|
+
} catch {}
|
|
477
|
+
framebuffer.detach(encoder)
|
|
478
|
+
_ = target
|
|
479
|
+
exit(0)
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// MARK: - main
|
|
483
|
+
|
|
484
|
+
signal(SIGPIPE, SIG_IGN)
|
|
485
|
+
let arguments = CommandLine.arguments
|
|
486
|
+
guard arguments.count >= 3 else { fail("usage: simulator-host serve|stream <udid> ...") }
|
|
487
|
+
switch arguments[1] {
|
|
488
|
+
case "serve":
|
|
489
|
+
await serve(arguments[2])
|
|
490
|
+
case "stream":
|
|
491
|
+
guard arguments.count == 6, let fps = Int(arguments[3]), let maxPixels = Double(arguments[4]), let kbps = Int(arguments[5]) else {
|
|
492
|
+
fail("usage: simulator-host stream <udid> <fps> <max pixels> <kbps>")
|
|
493
|
+
}
|
|
494
|
+
await stream(arguments[2], fps: fps, maxPixels: maxPixels, kbps: kbps)
|
|
495
|
+
default:
|
|
496
|
+
fail("usage: simulator-host serve|stream <udid> ...")
|
|
497
|
+
}
|
|
498
|
+
`;var r5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",xZ=180000,yZ=15000,hZ=30000,mZ=600000,vZ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
|
|
499
|
+
@end
|
|
500
|
+
`).join("");function a5($,J,Z){return new Promise((Q)=>{let K=j3($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),B="";K.stdout.on("data",(G)=>{B+=G}),K.stderr.on("data",(G)=>{B+=G}),K.once("error",(G)=>Q({code:-1,output:String(G)})),K.once("close",(G)=>Q({code:G??-1,output:B}))})}var i5=new Map;function L3($){let J=x(o5($),"Frameworks"),Z=i5.get(J);if(!Z)i5.set(J,Z=uZ(J));return Z}async function uZ($){if(process.platform!=="darwin"||!w3(x($,"FBSimulatorControl.framework")))return null;let J=await a5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=EZ("sha256").update(D3).update(J.output).update($).digest("hex").slice(0,16),Q=x(fZ(),".local","share","reason","simulator","host"),K=x(Q,Z,"simulator-host");if(w3(K))return K;J2(Q,{recursive:!0,mode:448});let B=kZ(x(Q,".staging-"));try{let G=x(B,"Frameworks"),U=x(G,"FBSimulatorControl.framework"),Y=x(U,"Modules","FBSimulatorControl.swiftmodule");J2(Y,{recursive:!0});for(let M of s5($))if(M!=="FBSimulatorControl.framework")M3(x($,M),x(G,M));let F=x($,"FBSimulatorControl.framework");M3(x(F,"FBSimulatorControl"),x(U,"FBSimulatorControl")),M3(x(F,"Headers"),x(U,"Headers")),U1(x(U,"Modules","module.modulemap"),c5(x(F,"Modules","module.modulemap")));let X=c5(x(F,"Modules","FBSimulatorControl.swiftmodule",`${r5}.swiftinterface`),"utf8");U1(x(Y,`${r5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let W=x(B,"include","CoreSimulator");J2(W,{recursive:!0}),U1(x(W,"module.modulemap"),`module CoreSimulator {
|
|
501
|
+
header "CoreSimulator.h"
|
|
502
|
+
export *
|
|
503
|
+
}
|
|
504
|
+
`),U1(x(W,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
|
|
505
|
+
${vZ}`);let z=x(B,"main.swift");U1(z,D3);let N=x(B,"simulator-host"),C=await a5("xcrun",["swiftc","-O","-F",G,"-I",x(B,"include"),"-module-cache-path",x(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,z,"-o",N],xZ);if(C.code!==0||!w3(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
|
|
506
|
+
${C.output.slice(-2000)}
|
|
507
|
+
`),null;J2(o5(K),{recursive:!0}),SZ(N,K);for(let M of s5(Q))if(M!==Z&&!M.startsWith(".staging-"))n5(x(Q,M),{recursive:!0,force:!0});return K}catch{return null}finally{n5(B,{recursive:!0,force:!0})}}class F1 extends Error{}class b0 extends Error{}class t5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;bZ({input:$.stdout}).on("line",(Q)=>{let K;try{K=JSON.parse(Q)}catch{return}let B=this.pending.get(Number(K.id));if(!B)return;if(this.pending.delete(Number(K.id)),clearTimeout(B.timer),K.ok===!0)B.resolve(K);else B.reject(new F1(String(K.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new b0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let K=setTimeout(()=>{this.pending.delete(J),Q(new b0("The simulator host did not answer.")),this.close()},hZ);this.pending.set(J,{resolve:Z,reject:Q,timer:K}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
|
|
508
|
+
`)})}close(){if(this.child.exitCode===null&&this.child.signalCode===null)this.child.kill("SIGTERM");this.end()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>this.close(),mZ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new b0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var f0=new Map;async function Z2($,J,Z=!1){let Q=f0.get(J);if(!Q){let K={started:pZ($,J)};f0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&f0.get(J)===K)f0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function pZ($,J){let Z=await L3($);if(!Z)return null;let Q=j3(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),yZ);Q.stdout.once("data",(Y)=>{clearTimeout(U),G(String(Y).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(U),G(!1)}),Q.once("error",()=>{clearTimeout(U),G(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let B=new t5(Q,()=>{let G=f0.get(J);if(G&&(G.host===B||G.host===void 0))f0.delete(J)});return B}function e5($,J,Z,Q,K){return j3($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var x0={version:"1.8.0",url:"https://github.com/cameroncooke/AXe/releases/download/v1.8.0/AXe-macOS-v1.8.0-universal.tar.gz",sha256:"7b76340b72e90d0f211bc7c4636f15009076eff07acef2f2b632b175debd8834"},nZ=50000,rZ=112640,aZ=174080,O3=2,iZ=60000,oZ=2000,tZ=300,eZ=40,$Q=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function m0($,J,Z={}){return new Promise((Q,K)=>{let B=E3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],U=[];B.stdout.on("data",(F)=>G.push(F)),B.stderr.on("data",(F)=>U.push(F));let Y=setTimeout(()=>B.kill("SIGKILL"),Z.timeoutMs??nZ);B.on("error",(F)=>{clearTimeout(Y),K(F)}),B.on("close",(F)=>{clearTimeout(Y),Q({code:F??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function f($,J){throw new H($,J)}async function n($,J,Z,Q={}){let K=await m0($,J,Q);if(K.code!==0)f("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function W1(){return process.platform==="darwin"&&Q0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Q0("/usr/bin/xcrun")}var I3=null;function A0(){return k(f3(),".local","share","reason","simulator","axe")}function b3(){let $=k(A0(),x0.version,"axe");if(Q0($))return Promise.resolve($);return I3??=(async()=>{P3(A0(),{recursive:!0,mode:448});let J=k3(k(A0(),".staging-"));try{let Z=k(J,"axe.tgz");await G6(x0.url,x0.sha256,Z);let Q=k(J,"tree");if(P3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!Q0(k(Q,"axe"))||!Q0(k(Q,"Frameworks")))f("simulator_axe_missing","The AXe archive has an unexpected layout.");Y1(k(A0(),x0.version),{recursive:!0,force:!0}),sZ(Q,k(A0(),x0.version));for(let K of G2(A0()))if(K!==x0.version&&!K.startsWith(".staging-"))Y1(k(A0(),K),{recursive:!0,force:!0});return $}finally{Y1(J,{recursive:!0,force:!0}),I3=null}})(),I3}var W6=b3;async function z6($){let J=await b3().catch(()=>null);return J?Z2(J,$.udid).catch(()=>null):null}async function K2($,J,Z){let Q=await b3().catch(()=>f("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await m0(Q,[...$,"--udid",J]);if(K.code===0)return K.stdout;let B=(K.stderr||K.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(B))f("simulator_element_not_found",B.slice(-500));return f("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function JQ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function ZQ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function x3(){let J=JSON.parse(await n("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,K]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let B of K){if(B.isAvailable===!1)continue;let G=B.name.toLowerCase();if(B.deviceTypeIdentifier)q3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:JQ(Q),state:ZQ(B.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,K)=>Number(K.state==="booted")-Number(Q.state==="booted")||K.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(K.name))}var q3=new Map,g3=null;async function o($,J){let Z=await x3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)f("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let K=Z.filter((B)=>B.state==="booted");if(Q=K.find((B)=>B.udid===g3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)f("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")f("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return g3=Q.udid,Q}function v($){return`${$.name} (${$.runtime})`}async function QQ($){if($.state!=="booted"){let J=await m0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))f("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await n("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return g3=$.udid,{...$,state:"booted"}}function y3($,J){let Z=R3($,J),Q=F6($,Z);if(Q.startsWith("..")||Q.startsWith(Y6)||R3($,Q)!==Z)f("simulator_path_outside_root",`${J} is outside this machine's granted folder (${$}). Pass a path inside it, or one relative to it.`);return Z}var $6=4,KQ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function BQ($){let J=[],Z=(Q,K)=>{let B;try{B=G2(Q)}catch{return}if(B.includes("project.yml")||B.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=$6)return;for(let G of B.sort()){if(G.startsWith(".")||KQ.has(G))continue;let U=k(Q,G);try{if(Q2(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)f("simulator_project_not_found",`No Xcode project or project.yml within ${$6} folders of ${$}; pass path.`);return f("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>F6($,Q)||".").join(", ")}.`)}var h0=new Map;async function VQ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:T3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:T3($)};if(!Q2($).isDirectory())f("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>G2($).filter((B)=>B.endsWith(K)).sort();if(Q0(k($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>Q0("/opt/homebrew/bin/xcodegen")?n("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(K));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:k($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:k($,Q),dir:$};return f("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function N6($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function GQ($){let J=(await N6($))[0];if(!J)f("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function XQ($){let J=[],Z=new Set;return $.forEach((Q,K)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let B=$.slice(K+1,K+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...B].join(`
|
|
509
|
+
`).slice(0,800))}),J}async function UQ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await N6(Z).catch(()=>[]);if(B.length)$.log.push(`error: this project's schemes are: ${B.join(", ")}`)}$.status="failed";return}let Q=k($.productsDir,`${$.configuration}-iphonesimulator`),K=Q0(Q)?G2(Q).filter((B)=>B.endsWith(".app")).map((B)=>k(Q,B)).sort((B,G)=>Q2(G).mtimeMs-Q2(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await D6($.appPath).catch(()=>{return});if($.status=$.appPath?"succeeded":"failed",!$.appPath)$.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function J6($,J){let Z=$.path?y3(J,$.path):BQ(J),Q=await VQ(Z),K=$.scheme??await GQ(Q),B=$.configuration??"Debug",G=await o($.device,{booted:!1}).catch(()=>null),U=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",Y=dZ("sha256").update(Q.path).digest("hex").slice(0,16),F=k(f3(),"Library","Caches","reason","simulator-builds",Y),X={id:`build-${lZ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:k(F,"Build","Products"),configuration:B};h0.set(X.id,X);for(let[C,M]of h0)if(h0.size>20&&M.status!=="running")h0.delete(C);let W=E3("xcodebuild",[Q.flag,Q.path,"-scheme",K,"-configuration",B,"-destination",U,"-derivedDataPath",F,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),z="",N=(C)=>{let M=(z+C.toString("utf8")).split(`
|
|
510
|
+
`);if(z=M.pop()??"",X.log.push(...M),X.log.length>5000)X.log.splice(0,X.log.length-5000)};return W.stdout.on("data",N),W.stderr.on("data",N),W.on("error",(C)=>{X.log.push(`error: ${C.message}`),X.status="failed",X.ended=Date.now()}),W.on("close",(C)=>{if(z)X.log.push(z);UQ(X,C??-1,Q)}),{text:`Build ${X.id} started: ${K} (${B}) for ${G?v(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:H6(X)}}function H6($){return{id:$.id,status:$.status,errors:XQ($.log),log_tail:$.log.slice(-eZ).join(`
|
|
511
|
+
`).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var FQ=45000,YQ=30000;async function A3($,J=FQ){let Z=Date.now()+J;while(h0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=C6($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function C6($){let J=h0.get($);if(!J)f("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=H6(J);return{text:J.status==="running"?`Build ${$} is running (${Math.round(Z.elapsed_ms/1000)} s).`:J.status==="succeeded"?`Build ${$} succeeded: ${J.appPath}. Launch it with app_path.`:`Build ${$} failed with ${Z.errors.length} error(s).`,build:Z}}async function D6($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",k($,"Info.plist")],"Reading the bundle id")).trim()}var w0=new Map;function WQ($,J){w0.get($.udid)?.stop();let Z=E3("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",$.udid,J],{stdio:["ignore","pipe","pipe"]}),Q={udid:$.udid,bundleId:J,lines:[],first:0,stop:()=>Z.kill("SIGTERM")};w0.set($.udid,Q);let K="",B=(G)=>{let U=(K+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
|
|
512
|
+
`);K=U.pop()??"",Q.lines.push(...U);let Y=Q.lines.length-oZ;if(Y>0)Q.lines.splice(0,Y),Q.first+=Y};return Z.stdout.on("data",B),Z.stderr.on("data",B),new Promise((G)=>{let U=setTimeout(()=>G(null),15000),Y=()=>{let F=Q.lines.concat(K).join(`
|
|
513
|
+
`).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(F)clearTimeout(U),G(Number(F))};Z.stdout.on("data",Y),Z.on("close",()=>{clearTimeout(U),G(null)})})}async function zQ($,J){let Z=await o($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=NQ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,B],`Installing ${U6(B)}`),Q=await D6(B)}if($.bundle_id){if((await m0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)f("simulator_app_not_installed",`${$.bundle_id} is not installed on ${v(Z)}.`)}let K=await WQ(Z,Q);if(K===null){let B=w0.get(Z.udid)?.lines.slice(-20).join(`
|
|
514
|
+
`)??"";f("simulator_launch_failed",`${Q} did not start on ${v(Z)}.${B?`
|
|
515
|
+
${B}`:""}`)}return{text:`Launched ${Q} on ${v(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function NQ($,J){let Z=R3(J),Q=k(f3(),"Library","Caches","reason","simulator-builds")+Y6;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:y3($,Z)}function HQ($,J){let Z=w0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${v($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-tZ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${v($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var B2=new Map;function Z6($,...J){let Z=B2.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)f("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function Q6($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function h3($,J=1,Z){let Q=k3(k(X6(),"reason-sim-"));try{let K=k(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){P3(T3(Z),{recursive:!0});let N=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),C=Number(N.match(/pixelWidth: (\d+)/)?.[1]),M=Number(N.match(/pixelHeight: (\d+)/)?.[1]),w=2/Q6($,C);await n("sips",["-z",String(Math.round(M*w)),String(Math.round(C*w)),K,"--out",Z],"Saving the screenshot")}let B=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),G=Number(B.match(/pixelWidth: (\d+)/)?.[1]),U=Number(B.match(/pixelHeight: (\d+)/)?.[1]),Y=Q6($,G),F=Math.round(G/Y),X=Math.round(U/Y);B2.set($.udid,{width:F,height:X});let W=Buffer.alloc(0),z=J===2?aZ:rZ;for(let N of[70,50,35]){let C=k(Q,`screen-${N}.jpg`);if(await n("sips",["-z",String(X*J),String(F*J),"-s","format","jpeg","-s","formatOptions",String(N),K,"--out",C],"Encoding the screenshot"),W=S3(C),W.byteLength<=z)break}return{text:`Screenshot of ${v($)} at ${F}x${X} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:W.toString("base64"),width:F,height:X}}}finally{Y1(Q,{recursive:!0,force:!0})}}async function CQ($){let J=await z6($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return K2(["describe-ui"],$.udid,"Reading the accessibility tree")}async function V2($){let J=JSON.parse(await CQ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(K,B,G="")=>{let U=(K.role??K.type??"?").replace(/^AX/,""),Y=K.AXLabel||K.title||"",F=K.AXValue?` value="${String(K.AXValue).slice(0,120)}"`:"",X=K.AXUniqueId?` id=${K.AXUniqueId}`:"";if(K.AXUniqueId)Z.ids.add(K.AXUniqueId);if(Y)Z.labels.add(Y);let W=K.frame;if(U==="Application"&&W&&!Z.bounds)Z.bounds={width:W.width,height:W.height};if(W&&W.width>0&&W.height>0&&(K.AXUniqueId||K.AXLabel))Z.targets.push({...K.AXUniqueId?{id:K.AXUniqueId.trim()}:{},...K.AXLabel?{label:K.AXLabel.trim()}:{},role:U,frame:W});let z=Boolean(Y||X||F||!["Group","Other"].includes(U));if(z){let N=`${" ".repeat(Math.min(B,12))}${U} "${Y.slice(0,160)}"${X}${F}`+(W?` (${Math.round(W.x)},${Math.round(W.y)} ${Math.round(W.width)}x${Math.round(W.height)})`:"")+(K.enabled===!1?" disabled":"");Z.lines.push(N);let C=U==="Image"&&!X,M=(U==="StaticText"||U==="Image")&&!X&&Y!==""&&G.includes(Y);if(!C&&!M)Z.compact.push(N)}for(let N of K.children??[])Q(N,z?B+1:B,Y||G)};for(let K of J)Q(K,0);return Z}function w6($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
|
|
516
|
+
`);return Q.length>J?`${Q.slice(0,J)}
|
|
517
|
+
\u2026 (truncated)`:Q}async function DQ($){let J=await V2($);return{text:`Accessibility tree of ${v($)} (frames in points; tap by id or label):
|
|
518
|
+
${w6(J,iZ)}`,device:$}}var wQ=450,MQ=1e4;function jQ($,J){let Z=J.id?$.ids.has(J.id):[...$.labels].some((Q)=>Q===J.label||Q.includes(J.label));return J.gone?!Z:Z}async function _0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let K=null,B="";if(J.wait_for){let U=Date.now()+(J.timeout??5)*1000,Y=J.wait_for,F=Y.id?`id ${Y.id}`:`"${Y.label}"`;for(;;){if(K=await V2($),jQ(K,Y)){B=` ${F} is ${Y.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){B=Y.gone?` Waited ${J.timeout??5} s: ${F} is still on screen.`:` Waited ${J.timeout??5} s: ${F} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(wQ);let G={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await V2($),G.screen=w6(K,MQ,!0),G.text+=`
|
|
519
|
+
Screen now:
|
|
520
|
+
${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await h3($);G.image=U.image}return G}function K6($){return`'${$.replace(/'/g,"'\\''")}'`}function LQ($){switch($.action){case"tap":if($.x!==void 0&&$.y!==void 0)return $.duration?`touch -x ${$.x} -y ${$.y} --down --up --delay ${$.duration}`:`tap -x ${$.x} -y ${$.y}`;return $.id?`tap --id ${K6($.id)}`:`tap --label ${K6($.label)}`;case"swipe":return`swipe --start-x ${$.x} --start-y ${$.y} --end-x ${$.x2} --end-y ${$.y2} --duration ${$.duration??0.3}`;case"button":return`button ${$.name.replace("_","-")}`;case"sleep":return`sleep ${$.seconds}`}}var M6=0.35,OQ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function IQ($,J){let Z=$.targets.filter((F)=>J.id!==void 0?F.id===J.id.trim():F.label===J.label?.trim()),Q=(F)=>({x:F.frame.x+F.frame.width/2,y:F.frame.y+F.frame.height/2}),K=$.bounds,B=K?Z.filter((F)=>{let{x:X,y:W}=Q(F);return X>=0&&W>=0&&X<=K.width&&W<=K.height}):Z,G=B.length?B:Z,U=G.filter((F)=>OQ.has(F.role)),Y=(U.length?U:G)[0];return Y?Q(Y):null}async function AQ($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let G=IQ(await V2($),J);if(G)return G;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return f("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
|
|
521
|
+
No accessibility element matched ${U}. Make sure the app is on the expected screen, then inspect it and prefer an id when there is one.
|
|
522
|
+
(${Q-1} of ${K} steps had completed.)`)}await Bun.sleep(250)}}async function y0($,J,Z){let Q=await z6($);if(!Q)return B6($,J,Z);for(let[K,B]of J.entries()){try{switch(B.action){case"tap":{let U=B.x!==void 0&&B.y!==void 0?{x:B.x,y:B.y}:await AQ($,B,Z,K+1,J.length);await Q.call(B.duration?{op:"tap",...U,duration:B.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:B.x,y:B.y,x2:B.x2,y2:B.y2,duration:B.duration??0.3});break;case"button":await Q.call({op:"button",name:B.name});break;case"type":await Q.call({op:"text",text:B.text}).catch((U)=>U instanceof F1?K2(["type",B.text],$.udid,`Step ${K+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(B.seconds*1000);break}}catch(U){if(U instanceof b0)return await B6($,J.slice(K),Z),`Ran ${J.length} step(s) on ${v($)}.`;if(U instanceof F1)f("simulator_command_failed",`Step ${K+1} failed: ${U.message}
|
|
523
|
+
(${K} of ${J.length} steps had completed.)`);throw U}let G=J[K+1];if(B.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(M6*1000)}return`Ran ${J.length} step(s) on ${v($)}.`}async function B6($,J,Z){let Q=[],K=[],B=0,G=0,U=async()=>{if(Q.length===0)return;let Y=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let F of Q)Y.push("--step",F);try{await K2(Y,$.udid,`Steps ${G+1}-${G+B}`)}catch(F){if(F instanceof H){let X=F.message.replace(/Step (\d+) failed/,(W,z)=>{let N=K[Number(z)-1];return N?`Step ${N} failed`:W});f(F.code,`${X}
|
|
524
|
+
(${G} of ${J.length} steps had completed before this batch.)`)}throw F}G+=B,Q=[],K=[],B=0};for(let[Y,F]of J.entries()){if(F.action==="type"){await U(),await K2(["type",F.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(LQ(F)),B+=1,K.push(Y+1);let X=J[Y+1];if(F.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${M6}`),K.push(Y+1)}return await U(),`Ran ${J.length} step(s) on ${v($)}.`}var _Q=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],V6=new Map,PQ=`ObjC.import("AppKit");
|
|
525
|
+
function run(argv) {
|
|
526
|
+
const [input, output, width, height] = argv;
|
|
527
|
+
const w = Number(width), h = Number(height);
|
|
528
|
+
const image = $.NSImage.alloc.initWithContentsOfFile(input);
|
|
529
|
+
const rep = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
|
|
530
|
+
null, w, h, 8, 4, true, false, $.NSDeviceRGBColorSpace, 0, 0);
|
|
531
|
+
$.NSGraphicsContext.saveGraphicsState;
|
|
532
|
+
$.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(rep));
|
|
533
|
+
image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, $.NSCompositingOperationCopy, 1);
|
|
534
|
+
$.NSGraphicsContext.restoreGraphicsState;
|
|
535
|
+
rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(output, true);
|
|
536
|
+
}`;async function _3($,J,Z){let Q=await n("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),K=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),B=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)K=K*Z/B,B=Z;let G=k3(k(X6(),"reason-chrome-"));try{let U=k(G,"render.js"),Y=k(G,"out.png");if(cZ(U,PQ),await n("osascript",["-l","JavaScript",U,$,Y,String(Math.max(1,Math.round(K*J))),String(Math.max(1,Math.round(B*J)))],"Rendering the frame"),!Q0(Y))f("simulator_command_failed",`Rendering ${U6($)} produced no image.`);return{image:S3(Y).toString("base64"),width:K,height:B}}finally{Y1(G,{recursive:!0,force:!0})}}async function TQ($){if(!q3.has($.udid))await x3();let J=q3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)f("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function RQ($){let J=await TQ($),Z=B2.get($.udid)??($.state==="booted"?(await h3($),B2.get($.udid)):void 0);if(!Z)f("simulator_not_booted",`${$.name} is not booted.`);let Q=V6.get(J);if(Q)return{text:`Frame of ${v($)}.`,device:$,chrome:Q};let K=k(J,"Contents","Resources"),B=JSON.parse(await n("plutil",["-convert","json","-o","-",k(K,"profile.plist")],"Reading the device profile")),G=B.framebufferMask?k(K,`${B.framebufferMask}.pdf`):null,U=G&&Q0(G)?await _3(G,O3,Z.height):null,Y=B.chromeIdentifier?.split(".").pop(),F=Y?k("/Library/Developer/DeviceKit/Chrome",`${Y}.devicechrome`,"Contents","Resources"):"";if(!Y||!Q0(k(F,"chrome.json")))f("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(S3(k(F,"chrome.json"),"utf8")),W={};for(let j of _Q){let O=X.images[j];if(!O)f("simulator_command_failed",`${$.name}'s frame has no ${j} piece.`);W[j]=await _3(k(F,`${O}.pdf`),O3)}let{sizing:z}=X.images,N={top:z.topHeight,left:z.leftWidth,bottom:z.bottomHeight,right:z.rightWidth},C=Z.width+N.left+N.right,M=Z.height+N.top+N.bottom,w=[];for(let j of X.inputs??[]){let O=k(F,`${j.image}.pdf`);if(!Q0(O))continue;let A=await _3(O,O3),{x:b,y:I}=j.offsets.normal,R=(c,p,M1)=>c<0?p+c-M1:c,P=j.anchor==="left"?{x:b-A.width,y:R(I,M,A.height)}:j.anchor==="right"?{x:C+b,y:R(I,M,A.height)}:j.anchor==="top"?{x:R(b,C,A.width),y:I-A.height}:{x:R(b,C,A.width),y:M+I};w.push({name:j.name,image:A.image,...P,width:A.width,height:A.height})}let D={identifier:X.identifier,screen:{width:Z.width,height:Z.height},inset:N,padding:X.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:W,buttons:w,...U?{screen_mask:U.image}:{}};return V6.set(J,D),{text:`Frame of ${v($)}.`,device:$,chrome:D}}var qQ=new Set(["simulator_command_failed","simulator_launch_failed","simulator_point_off_screen","simulator_build_no_scheme","simulator_element_not_found","simulator_path_outside_root","simulator_project_not_found"]);async function z1($){try{return await j6($)}catch(J){if(J instanceof H&&qQ.has(J.code))return{text:J.message,error:J.code};throw J}}async function j6($){if(!W1())f("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=C3.safeParse($.payload);if(!J.success)f("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await x3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(v).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await QQ(await o(Z.device,{booted:!1}));return{text:`${v(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await o(Z.device,{booted:!1});w0.get(Q.udid)?.stop(),w0.delete(Q.udid);let K=await m0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))f("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${v(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await J6(Z,$.root);return Z.wait&&Q.build?A3(Q.build.id):Q}case"build_status":return Z.wait?A3(Z.build_id):C6(Z.build_id);case"run":{let Q=await J6({...Z,action:"build"},$.root),K=await A3(Q.build.id,YQ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await j6({root:$.root,payload:{action:"launch",app_path:K.build.app_path,...Z.device?{device:Z.device}:{},...Z.steps?{steps:Z.steps}:{},...Z.observe?{observe:Z.observe}:{},...Z.wait_for?{wait_for:Z.wait_for}:{},...Z.timeout!==void 0?{timeout:Z.timeout}:{}}});return{...B,text:`Built in ${Math.round(K.build.elapsed_ms/1000)} s. ${B.text}`,build:K.build}}case"launch":{let Q=await zQ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await y0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return _0(Q.device,Z,Q)}case"steps":{let Q=await o(Z.device,{booted:!0});return _0(Q,Z,{text:await y0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await o(Z.device,{booted:!0});if(w0.get(Q.udid)?.bundleId===Z.bundle_id)w0.get(Q.udid)?.stop();return await m0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${v(Q)}.`,device:Q}}case"logs":return HQ(await o(Z.device,{booted:!1}),Z.after);case"screenshot":return h3(await o(Z.device,{booted:!0}),Z.scale,Z.save_path?y3($.root,Z.save_path):void 0);case"chrome":return RQ(await o(Z.device,{booted:!1}));case"inspect":return DQ(await o(Z.device,{booted:!0}));case"tap":{let Q=await o(Z.device,{booted:!0}),K=Z.x!==void 0&&Z.y!==void 0;if(K)Z6(Q,[Z.x,Z.y]);await y0(Q,[K?{action:"tap",x:Z.x,y:Z.y,...Z.duration&&Z.duration>0?{duration:Z.duration}:{}}:Z.id?{action:"tap",id:Z.id}:{action:"tap",label:Z.label}],3);let B=K?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return _0(Q,Z,{text:`Tapped ${B} on ${v(Q)}.`,device:Q})}case"swipe":{let Q=await o(Z.device,{booted:!0});return Z6(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await y0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),_0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${v(Q)}.`,device:Q})}case"type":{let Q=await o(Z.device,{booted:!0});return await y0(Q,[{action:"type",text:Z.text}],3),_0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${v(Q)}.`,device:Q})}case"button":{let Q=await o(Z.device,{booted:!0});return await y0(Q,[{action:"button",name:Z.name}],3),_0(Q,Z,{text:`Pressed ${Z.name} on ${v(Q)}.`,device:Q})}case"open_url":{let Q=await o(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{f("simulator_invalid_request","open_url needs an absolute URL.")}if($Q.has(K.protocol))f("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),_0(Q,Z,{text:`Opened ${K.href} on ${v(Q)}.`,device:Q})}case"appearance":{let Q=await o(Z.device,{booted:!0});return await n("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${v(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as gQ,readFileSync as EQ,rmSync as kQ}from"fs";import{tmpdir as SQ}from"os";import{join as L6}from"path";import{spawn as _6}from"child_process";var fQ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,N1=1,bQ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],O6=60,xQ=8,P6=W1;var I6={65293:40,65421:40,65307:41,65288:42,65289:43,65535:76,65360:74,65367:77,65365:75,65366:78,65361:80,65362:82,65363:79,65364:81,65505:225,65506:229,65507:224,65508:228,65513:226,65514:230,65515:227,65516:231,65511:227,65512:231,65509:57},yQ=(()=>{let $={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((Z,Q)=>{$[Z]=4+Q,$[Z.toUpperCase()]=4+Q}),"1234567890".split("").forEach((Z,Q)=>{$[Z]=30+Q}),"!@#$%^&*()".split("").forEach((Z,Q)=>{$[Z]=30+Q});let J=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[Z,Q,K]of J)$[Z]=K,$[Q]=K;return $})();function hQ($){if(I6[$]!==void 0)return I6[$];return $>=32&&$<=126?yQ[String.fromCharCode($)]??null:null}function T6($,J){let Z=_6("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function mQ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,G,U){let Y=(U&N1)!==0;if(Y&&!(Z&N1))K({op:"touch",phase:"down",x:B,y:G});else if(Y&&(B!==Q.x||G!==Q.y))K({op:"touch",phase:"move",x:B,y:G});else if(!Y&&Z&N1)K({op:"touch",phase:"up",x:B,y:G});for(let F of bQ)if(U&F.bit&&!(Z&F.bit))K({op:"swipe",x:B,y:G,x2:B+F.dx*O6,y2:G+F.dy*O6,duration:0.08});Z=U,Q={x:B,y:G}},key(B,G){let U=hQ(G);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){T6($,B)},close(){if(Z&N1)K({op:"touch",phase:"up",...Q});Z=0}}}function vQ($,J){let Z=null,Q="",K,B=(G)=>{z1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,Y){let F=(Y&N1)!==0;if(F&&!Z)Z={x:G,y:U,at:Date.now()};if(!F&&Z){let X=(Date.now()-Z.at)/1000;if(Math.hypot(G-Z.x,U-Z.y)>xQ)B({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:U,duration:Math.min(Math.max(X,0.05),1)});else B({action:"tap",x:Z.x,y:Z.y,...X>0.5?{duration:Math.min(X,10)}:{}});Z=null}},key(G,U){if(!G)return;let Y=U===65293?`
|
|
537
|
+
`:U>=32&&U<=126?String.fromCharCode(U):null;if(Y===null)return;Q+=Y,clearTimeout(K),K=setTimeout(()=>{let F=Q;Q="",B({action:"type",text:F})},250)},clipboard(G){T6($,G)},close(){clearTimeout(K),Z=null}}}function uQ($,J,Z){return new Promise((Q,K)=>{let B=_6($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function pQ($,J){let Z=gQ(L6(SQ(),"reason-simulator-stream-"));try{let Q=L6(Z,"screen.png");if(await uQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=EQ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{kQ(Z,{recursive:!0,force:!0})}}async function R6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!fQ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await W6().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await z1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:B.image.width,height:B.image.height},U=await L3(K),Y=U?await Z2(K,Z,!0):null,F=U?null:await A6();if(!U&&!F)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let X={kind:"simulator",udid:Z,axe:K,points:G,sound:null,size:U?G:await pQ(Z,$.signal),stream:U?(W,z,N)=>e5(U,Z,Math.min(W,60),N,z):null,input:Y?mQ(Z,Y):vQ(Z,$.root)};return await X2({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...F?{ffmpeg:()=>F}:{}}})}var F9=131072,$K=131072,JK=128,Y9=8192,i3=30000,o3=15000,ZK=/^[a-z][a-z0-9_]{0,63}$/,QK=new Set(["jobs.control","fs.read","fs.write"]),q6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function U2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function g6($){return $.map(U2).join("/")}function m3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var KK=[...m3(A1,4).map(($)=>`/(${$.map(g6).join("|")})(/|$)`),...m3(_1,4).map(($)=>`/(${$.map(g6).join("|")})$`),...m3([...P1],6).map(($)=>`/(${$.map(U2).join("|")})$`),`/${U2(".env")}\\.[^/]+$`,`/[^/]+(${T1.map(U2).join("|")})$`],l3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),W9=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function z9($){return[$.requiredPermission,...$.additionalPermissions??[]]}function BK($){return h7($)}function s3(){if(E()==="darwin")return F0("/usr/bin/sandbox-exec");if(E()==="linux"||E()==="win32")return u7();return!1}function E6(){if(E()==="linux")return F0("/proc");if(E()==="win32")return H7()!==null;if(!s3())return!1;if(E()==="darwin")return F0("/usr/sbin/lsof");return!1}function N9(){return E()==="darwin"?"/bin/zsh":p7()}function c3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function VK($){if(!c3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>C0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function l0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function z2($,J,Z=Y9){let Q=l0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function GK($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function D1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function P0($,J){if(E()==="win32")[$,J]=[$.toLowerCase(),J.toLowerCase()];return J===$||J.startsWith(`${$}${tQ}`)}function u0($){if(m7($))throw new H("protected_path","This path is on Reason's credential denylist. The Mac's owner can allow it with `reason permissions protected allow <path>` or Request permission in Files.")}function u($){let J;try{J=X0($.path)}catch(Z){if(process.platform==="darwin"&&S7(Z))throw f7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!w1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return u0(J),J}function t3($,J="."){if(!J||J.includes("\x00")||iQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");if(E()==="win32"&&J.split(/[\\/]/).some(l1))throw new H("invalid_path","Windows reserves this file name.");let Z=oQ($,J);if(!P0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function d0($,J=".",Z=!1){let Q=t3($,J),K;try{K=X0(Q)}catch(B){if(w9(B))throw M9();throw new H("path_not_found","Path does not exist.")}if(!P0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)u0(K);return K}function XK($,J){let Z=t3($,J);if(u0(Z),F0(Z)){let B=X0(Z);if(!P0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(p3(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return u0(B),B}let Q=C1(Z);while(!F0(Q)){let B=C1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=X0(Q);if(!P0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return u0(K),Z}function H9($,J){return d3($,J)||"."}function UK($,J=F9){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function C9($,J){return{...q7({home:$,temporaryDirectory:J}),ZDOTDIR:J,BASH_ENV:"/dev/null",ENV:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}function FK($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...KK.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),...v7($,Z),"(deny network*)"].join(`
|
|
538
|
+
`)}async function e3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,Y=!1,F=!1,X;try{X=eQ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],...W7()}),z7(X)}catch(M){K(M);return}let W=(M,w)=>{if(F)return;F=!0,clearTimeout(C),Z.signal.removeEventListener("abort",N),Q({exitCode:M,signal:w,stdout:B,stderr:G,timedOut:Y,truncated:U})},z=(M,w)=>{let D=`${M}${String(w)}`,j=UK(D);return U||=j.truncated,j.value};X.stdout.on("data",(M)=>{B=z(B,M)}),X.stderr.on("data",(M)=>{G=z(G,M)}),X.once("error",K),X.once("exit",W);let N=()=>{try{if(E()==="win32"&&X.pid)N7(X.pid);else X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",N,{once:!0});let C=setTimeout(()=>{Y=!0,N()},Z.timeoutMs)})}var k6=null;function YK(){return k6??=d7({scrubEnvironment:C9,spawnCaptured:e3,isProtectedPath:k0}),k6}var WK=async($,J,Z)=>{if(E()==="linux"||E()==="win32")return YK()($,J,Z);if(E()!=="darwin"||!F0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=sQ(U9(aQ(),"reason-device-"));try{return await e3("/usr/bin/sandbox-exec",["-p",FK(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:C9(Z.root,Q)})}finally{nQ(Q,{recursive:!0,force:!0})}};function zK($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>JK)throw new H("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>Y9)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function D9($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=u($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??o3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function w9($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var M9=()=>new H("path_unreadable","The path is not readable.");function NK($){try{return X9($,K0.O_RDONLY)}catch(J){throw w9(J)?M9():J}}function S6($,J){let Z=p0()?Y2():null;return Z?W2(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):HK($,J)}function HK($,J){return $==="fs.read"?CK(J):wK(J)}async function CK($){let J=u($.root),Z=d0(J,z2($.payload,"path"));if(!w1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=D1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=D1($.payload.max_bytes,65536,1,F9),B=l0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=NK(Z),U,Y;try{U=G9(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));Y=X.subarray(0,X.byteLength?cQ(G,X,0,X.byteLength,Q):0)}finally{V9(G)}let F=B==="base64"||Y.includes(0);return{path:H9(J,Z),content:F?Y.toString("base64"):Y.toString("utf8"),encoding:F?"base64":"utf8",offset:Q,bytes:Y.byteLength,size:U,truncated:Q+Y.byteLength<U}}function DK($,J,Z=E()){let Q=$==="append"?K0.O_APPEND:K0.O_TRUNC;if(Z==="win32")return J?K0.O_WRONLY|($==="append"?K0.O_APPEND:0):K0.O_WRONLY|K0.O_CREAT|K0.O_EXCL;return K0.O_WRONLY|K0.O_NOFOLLOW|Q|(J?0:K0.O_CREAT|K0.O_EXCL)}async function wK($){let J=u($.root),Z=z2($.payload,"path"),Q=GK($.payload,"content",$K),K=l0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=XK(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){lQ(C1(B),{recursive:!0,mode:448});let F=X0(C1(B));if(!P0(J,F))throw new H("symlink_escape","Write parent escaped root.")}if(!F0(C1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&F0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=F0(B),U=G?p3(B):null,Y=X9(B,DK(K,G),384);try{let F=G9(Y),X=U??(E()==="win32"?p3(B):null);if(X&&(F.ino!==X.ino||F.dev!==X.dev||E()==="win32"&&!P0(J,X0(B))))throw new H("symlink_escape","The write target changed between validation and opening.");if(E()==="win32"&&U&&K!=="append")dQ(Y,0);rQ(Y,Q,null,"utf8")}finally{V9(Y)}return{path:H9(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function MK($){let J=u($.root),Z=z2($.payload,"command",65536),Q=d0(J,l0($.payload,"cwd")??".");if(!w1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=D1($.payload.timeout_ms,o3,100,i3);return D9($,N9(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function jK($){let J=y4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:E()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=u($.root),K=M7(Q,J.data.workspace),B=K.boundary===Q?Q:d0(K.anchor,d3(K.anchor,K.boundary)||"."),G=d0(B,d3(B,K.path)||".");if(!w1(G).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+S4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let Y=(D)=>$.emit("progress",{process:D});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await S2({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:S0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:Y})}}let F={directory:U9(Z.runtimeDirectory,"processes")},X={deniedPorts:w7([$.apiOrigin])},W=g7(),z=E7(),N=p0(),C=J.data.egress?F2(N):null;if(J.data.egress&&(C===null||!v0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let M=J.data.egress?await z8(J.data.egress.allowed_domains):null,w=M?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((D)=>`${D}=${M.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
|
|
539
|
+
`):J.data.command;try{return{...await S2({claim:$.claim,root:G,cwd:G,command:w,mode:"host",shell:z,expiresAtMs:U,signal:$.signal,emit:Y,...N?{jobsUser:{...N,...C!==null?{modelGid:C}:{}}}:{},environment:{...W.variables,HOME:W.home,PATH:W.path,TMPDIR:W.temporaryDirectory,SHELL:z},journals:F,preview:X})}}finally{M?.close()}}async function LK($){K3();let J=u($.root),Z=B3($.payload.command),Q=d0(J,l0($.payload,"cwd")??".");if(!w1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=D1($.payload.timeout_ms,z5,100,Z3),{ignored:B}=V3($.payload.env);return await $.emit("progress",{shell:S0(),shell_flags:[...G1],sandbox:"none",ignored_env:B}),H5({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function OK($){let J=u($.root),Z=zK($.payload),Q=Z[0];if(!Q||!W9.has(Q)&&!l3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=l3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=d0(J,l0($.payload,"cwd")??".");return D9($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K||process.platform==="win32"&&$.root.permissions.write,timeoutMs:D1($.payload.timeout_ms,o3,100,i3)})}function j9($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");return Q}}async function IK($){let J=u($.root);if(E()==="linux")return _5(J);if(E()==="win32")return C7(J);return g5(J,j9($,J))}async function AK($){let J=u($.root);if(E()==="linux")return P5(J);if(E()==="win32")return D7(J);return E5(J,j9($,J))}async function _K($){let J=$.worker?v5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&$4({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},...$.worker.ownComputer?{ownComputer:!0}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:u($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function PK($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new H("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=j7($.payload,$.operationId);return A7({root:u($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:u($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function f6($,J){let Z=p0()?Y2():null;return Z?W2(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):TK(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function TK($,J){let Z=u(J.root),Q=Q1 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let K=Q?v8(Z,J.payload[Q1]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new H("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let U=A8.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return u8({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=z2(J.payload,"path",4096),G=$==="import"&&Q?o2(K):K;return u0(t3(G,B)),E0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var L9={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new H("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return W4({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>S6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>S6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>f6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>f6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>E()==="darwin"&&Q3(),execute:jK},"exec.run":{requiredPermission:"execute",available:s3,execute:MK},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Q3(),execute:LK},"git.run":{requiredPermission:"execute",available:()=>s3()&&BK("git"),execute:OK},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:E6,execute:IK},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:E6,execute:AK},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>E()==="darwin"||Boolean(b7()),execute:_K},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:J9,execute:PK},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:B9,execute:($)=>{let J=Y2();return J?W2(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??k7)()},$.signal):X2({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>Q9(),execute:($)=>K9({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:W1,execute:($)=>z1({payload:$.payload,root:u($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:P6,execute:($)=>R6({payload:$.payload,root:u($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>_7({root:u($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>E()==="darwin"?F0("/usr/bin/sandbox-exec"):E()==="linux"||E()==="win32",execute:async($)=>{let J=g1.parse($.payload),Z=r3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!j0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return P7({root:u($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>T4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>a3({root:u($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>O7({root:u($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>I7({root:u($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:a2,execute:($)=>b8($.payload,$.signal)}};function RK($,J){try{let Z=N4($,X0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function qK($,J){try{let Z=X0(J);return $.some((Q)=>Q.path===Z)?O1(Z,E()):void 0}catch{return}}function gK($,J){try{let Z=X0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function EK($,J){try{let Z=X0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&P0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function kK($,J,Z=E()){try{return I1({home:O1(X0(J),Z),roots:$.map((Q)=>({path_fingerprint:Q.pathFingerprint,path:O1(Q.path,Z)})).filter((Q)=>/^[a-f0-9]{64}$/.test(Q.path_fingerprint)&&L1(Q.path)).slice(0,D2)})}catch{return}}function XU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||E()==="darwin",K=Q?gK($,H1()):void 0,B=!J.worker&&E()==="darwin"?RK($,H1()):void 0,G=Q?qK($,H1()):void 0,U=!J.worker&&E()==="darwin"?EK($,H1()):void 0,Y=Q?kK($,H1()):void 0,F=J3.filter((X)=>{if(V1.has(X)&&!J.worker)return!1;if(J.worker&&!a1(X,J.worker))return!1;let W=L9[X];if(!W)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:W.available?.()??!0)&&$.some((N)=>(!J.worker||X!=="pty.start"||N.permissions.read&&N.permissions.write)&&z9(W).every((C)=>N.permissions[C]))});return{supported_operations:F,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...Y?{root_paths:Y}:{},...F.includes("hands.connect")?{hands_worker_artifact_sha256:g0,hands_worker_entrypoint:$1,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:C0,max_result_bytes:C0,operation_constraints:{...F.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":A2.parse(J.productionProof)}:{},...F.includes("exec.run")?{"exec.run":{transport:"shell",shell:N9(),sandbox:E()==="linux"?"linux_sandbox_runtime":E()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:i3}}:{},...F.includes("exec.full")?{"exec.full":C5()}:{},"git.run":{read_only_subcommands:[...W9].sort(),mutating_subcommands:[...l3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:z0,max_timeout_ms:Z1,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:z0,max_timeout_ms:Z1,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:e0,protocol_version:u3,worker_artifact_sha256:g0,worker_entrypoint:$1,policy_mode:"full_access",policy_version:1,workspace_base:v3,workspace_layout:B1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":E()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...F.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:$9,max_session_ms:t7,max_buffered_output_bytes:e7}}:{},...J.worker?Object.fromEntries(F.filter((X)=>X!=="browser.pr-proof.v1").map((X)=>[X,{ready:J.worker?.readiness?.[X]===!0,...J.worker?.readiness?.[X]!==!0&&J.worker?.probing?.includes(X)?{probing:!0}:{},execution_mode:a1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:Y7,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!p0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:Z7,...J.worker?.ownComputer?{[Q7]:K7}:{},workspace_base:v3,workspace_layout:B1,browser_state:"optional_headless",desktop:!1,worker_version:e0,protocol_version:u3,...J.worker?.readiness?.["environment.install"]===!0&&F.includes("environment.install")?{environment_delivery:y6,[v6]:m6}:{},...J.worker?{[p6]:u6}:{},...J.worker?.handsBrowser?{[n6]:c6}:{},[s6]:l6,[a6]:r6,...v0(J.worker?.executionMode==="unsandboxed")?{[o6]:i6}:{},...v0(J.worker?.executionMode==="unsandboxed")&&F2()!==null?{[e6]:t6}:{},...v0(J.worker?.executionMode==="unsandboxed")&&p0()?{[J7]:$7}:{}}:{},...X==="fs.export"?{cloud_source_version:m1,source_kinds:["workspace","attachment"],[h2]:m2}:{},...X==="fs.import"?{[h2]:m2}:{},...X===k4&&F2()!==null&&v0(J.worker?.executionMode==="unsandboxed")?{[x4]:T2}:{},...X==="tunnel.open"?{carried_jobs:B7}:{},...X==="jobs.control"?{[G7]:V7}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[s7]:l7,[n7]:c7.join(","),[r7]:a7,[i7]:o7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[X7]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[U7]:!0}:{}}])):{}}}}function $4($,J,Z,Q,K){let B=R7.safeParse(Q);return B.success&&K!==void 0&&K.device_id===$.deviceId&&B.data.device_id===$.deviceId&&B.data.root_id===J&&B.data.run_id===Z&&B.data.binding.kind===K.binding&&B.data.binding.target_revision===K.target_revision&&B.data.binding.root_grant_revision===K.root_grant_revision&&B.data.binding.target_generation===K.target_generation&&B.data.binding.target_fence_id===K.target_fence_id}async function UU($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==h6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((F)=>F.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!$4($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let Y=a3({root:u(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:Y.snapshot_id,installed_revision:Y.installed_revision,installed:!0},K),!0}async function FU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==d6)return!1;let{version:K,run_id:B,target_generation:G,target_fence_id:U}=Z.payload;if(K!==1||Object.keys(Z.payload).length!==4||typeof B!=="string"||typeof G!=="number"||typeof U!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let Y=$.roots.find((F)=>F.id===J.root_id);if(!Y)throw new H("root_not_granted","The Hands root is no longer granted.");return await L7({operationId:J.operation_id,root:u(Y),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function YU($,J,Z){if(J.capability!=="github.local.v1")return b6($,J,Z);try{let Q=await b6($,J,Z);if(Q.status==="succeeded"||n3(J.payload,Q.status,Q.error_code))return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function b6($,J,Z){if(V1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!a1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=r3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=L9[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let K=$.roots.find((X)=>X.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&c3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&Q1 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!$4($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(z9(Q).some((X)=>!K.permissions[X]))return{status:"failed",error_code:"permission_denied"};let B=0,G=async(X,W,z)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:B++,kind:X,capability:J.capability,data:W,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&z?{deliverySignal:z}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||QK.has(J.capability)||J.capability==="pty.start",Y,F=async(X,W,z)=>{let N=Y;Y=void 0,await Promise.all([N,G(X,W,z)])};try{if(U)Y=G("started"),Y.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},W=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(z)=>G("pr-proof.started.v1",z))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:VK(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:X,runCommand:Z.runCommand??WK,spawnFullControl:Z.spawnFullControl??e3,emit:U?F:G,runHandsRelay:Z.runHandsRelay??((z)=>y7(z,X)),runPtySession:Z.runPtySession??Z9});if(J.capability==="github.local.v1")x6.parse(W);if(!c3(W))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(W)??"null","utf8")>C0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?F:G)("completed",{ok:!0}),{status:"succeeded",result:W,error_code:null}}catch(X){let W=Z.signal.reason instanceof H&&q6.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&q6.has(X.code)?X.code:null;if(Z.signal.aborted||W)return{status:"cancelled",...X instanceof t0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":W??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&X instanceof Error&&"code"in X&&["EACCES","EPERM"].includes(String(X.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let z=J.capability==="inference.custom.v1"?X instanceof H&&F7(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?X instanceof E1&&n3(J.payload,"failed",X.code)?X.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&ZK.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof x7?T7(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:z,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:z}}}
|
|
540
|
+
export{i9 as Ba,o9 as Ca,g4 as Da,WB as Ea,CB as Fa,mB as Ga,vB as Ha,a2 as Ia,hV as Ja,N0 as Ka,CJ as La,DJ as Ma,mV as Na,_J as Oa,S0 as Pa,WZ as Qa,QK as Ra,N9 as Sa,C9 as Ta,FK as Ua,e3 as Va,WK as Wa,HK as Xa,DK as Ya,TK as Za,L9 as _a,RK as $a,qK as ab,gK as bb,EK as cb,kK as db,XU as eb,UU as fb,FU as gb,YU as hb};
|