@reason-machines/cli-linux-x64 0.2.559 → 0.2.560
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +2 -2
- package/bin/vm-hands/agent-network-j5f603sy.js +2 -0
- package/bin/vm-hands/api-credentials-7rhpwe7n.js +2 -0
- package/bin/vm-hands/api-vkgf7wma.js +2 -0
- package/bin/vm-hands/ask-relay-2vf6fa2t.js +5 -0
- package/bin/vm-hands/connect-cli-06x1wfgv.js +2 -0
- package/bin/vm-hands/credentials-s7ps7y6s.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-3xnrp33e.js +2 -0
- package/bin/vm-hands/desktop-account-eg8thn79.js +2 -0
- package/bin/vm-hands/device-workspace-h5rsecq8.js +2 -0
- package/bin/vm-hands/{fsevents-fev1pxw2.js → fsevents-vxv56sp5.js} +1 -1
- package/bin/vm-hands/hands-worker-source-vk664w8p.js +2 -0
- package/bin/vm-hands/{index-j6wffzfd.js → index-03p9c17x.js} +106 -106
- package/bin/vm-hands/install-receipt-j04hdw1k.js +2 -0
- package/bin/vm-hands/local-automation-8b1znx0p.js +2 -0
- package/bin/vm-hands/local-capabilities-m6pzcc94.js +2 -0
- package/bin/vm-hands/local-desktop-users-sq4trh07.js +2 -0
- package/bin/vm-hands/local-display-mac-yxcxvg2z.js +2 -0
- package/bin/vm-hands/local-display-session-zyd8s6n6.js +2 -0
- package/bin/vm-hands/local-display-video-rk680vwg.js +2 -0
- package/bin/vm-hands/local-managed-process-w26jhyfg.js +2 -0
- package/bin/vm-hands/local-pty-session-edd8ttf9.js +2 -0
- package/bin/vm-hands/managed-runtime-ykv5nyva.js +2 -0
- package/bin/vm-hands/network-auto-update-mrjz964a.js +3 -0
- package/bin/vm-hands/network-contract-8mxtma3w.js +2 -0
- package/bin/vm-hands/network-sign-in-8yvdx5rm.js +3 -0
- package/bin/vm-hands/package-vwvzjtn0.js +2 -0
- package/bin/vm-hands/permissions-nmxr8238.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-1nkpw1v3.js +2 -0
- package/bin/vm-hands/serve-service-det934tz.js +2 -0
- package/bin/vm-hands/status-fr7192eh.js +96 -0
- package/bin/vm-hands/version-5d6gbmrd.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-0as6nsks.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-0ex2twm5.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-0wb1n769.js +9 -0
- package/bin/vm-hands/{vm-hands-entry-lite-a3p6xz53.js → vm-hands-entry-lite-2rgf8866.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-4jgykvd3.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-52qz0n30.js +7 -0
- package/bin/vm-hands/vm-hands-entry-lite-57ajjwmh.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-71ebge0c.js +42 -0
- package/bin/vm-hands/vm-hands-entry-lite-84mc1f7h.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-8pcs85ak.js +105 -0
- package/bin/vm-hands/vm-hands-entry-lite-8w0ah5j9.js +11 -0
- package/bin/vm-hands/vm-hands-entry-lite-8xv6c0rm.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-9g52kxyj.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-a6ss0ges.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-a7bf7xr7.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-ab1pq3xg.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-bnpdn6fw.js +127 -0
- package/bin/vm-hands/vm-hands-entry-lite-cspd38hc.js +539 -0
- package/bin/vm-hands/{vm-hands-entry-lite-q1yvw4xz.js → vm-hands-entry-lite-e3fn8ys2.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-f8p11q6h.js +452 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jrce7v4r.js → vm-hands-entry-lite-f95mg81d.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-fhx46jny.js +10 -0
- package/bin/vm-hands/{vm-hands-entry-lite-506b6pcz.js → vm-hands-entry-lite-fk2s50nc.js} +5 -5
- package/bin/vm-hands/vm-hands-entry-lite-hjjbjpd7.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-hs6sdn60.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-hxfxs7r9.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-2v4zh9ze.js → vm-hands-entry-lite-j10cw3d9.js} +9 -9
- package/bin/vm-hands/{vm-hands-entry-lite-8rmbdm6c.js → vm-hands-entry-lite-jhsa4av7.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-jpvmkce5.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-k5ytpgzz.js +65 -0
- package/bin/vm-hands/{vm-hands-entry-lite-s85p7tqp.js → vm-hands-entry-lite-krpqqx12.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-q2h781jg.js → vm-hands-entry-lite-ms99mzp0.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-nn6zcvmp.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-46pwqvpf.js → vm-hands-entry-lite-ptycjmkc.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-pxtycfdv.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-q3er9m6y.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-q9djb28r.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-q9s1e2y1.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-qegwyvyz.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-pzj5s203.js → vm-hands-entry-lite-qf990rxw.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-rhx6adbr.js +52 -0
- package/bin/vm-hands/vm-hands-entry-lite-sy7dcccg.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-tcmye5ny.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-tvnfm4xg.js +150 -0
- package/bin/vm-hands/{vm-hands-entry-lite-1yv5qqew.js → vm-hands-entry-lite-v4hr9x9h.js} +45 -45
- package/bin/vm-hands/vm-hands-entry-lite-vdv4nm5f.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-weqam12f.js +6 -0
- package/bin/vm-hands/vm-hands-entry-lite-y4df9n3f.js +345 -0
- package/bin/vm-hands/vm-hands-entry-lite-yvws5zpx.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-qd46yhvz.js → vm-hands-entry-lite-z0ht62s4.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-zawytz09.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-h2rq71rj.js → vm-hands-entry-lite-zh6ncdjn.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-p2jvbq5w.js → vm-hands-executor-qny3mx8f.js} +8 -8
- package/bin/vm-hands/vm-hands-op-runner-5q01rhkc.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-889hfy4p.js → vm-hands-runtime-gjjm5fzd.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-06tygyjs.js +2 -0
- package/bin/vm-hands/worker-sandbox-e1cpkzfz.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-x30e4ezb.js +0 -2
- package/bin/vm-hands/api-y6v8wdsq.js +0 -2
- package/bin/vm-hands/connect-cli-32wrv6sw.js +0 -2
- package/bin/vm-hands/credentials-sbza33ac.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-mydksbg8.js +0 -2
- package/bin/vm-hands/desktop-account-t0afsge2.js +0 -2
- package/bin/vm-hands/device-workspace-b534qy2c.js +0 -2
- package/bin/vm-hands/hands-worker-source-qj7s9dk5.js +0 -2
- package/bin/vm-hands/install-receipt-zv1bjbgh.js +0 -2
- package/bin/vm-hands/local-automation-pwwqrnt7.js +0 -2
- package/bin/vm-hands/local-capabilities-scnpxe96.js +0 -2
- package/bin/vm-hands/local-desktop-users-5scb9930.js +0 -2
- package/bin/vm-hands/local-display-mac-pft73te9.js +0 -2
- package/bin/vm-hands/local-display-session-9362hqsn.js +0 -2
- package/bin/vm-hands/local-display-video-dndhr5v1.js +0 -2
- package/bin/vm-hands/local-managed-process-zm639p1g.js +0 -2
- package/bin/vm-hands/local-pty-session-njd0tprg.js +0 -2
- package/bin/vm-hands/managed-runtime-cqkw2mtn.js +0 -2
- package/bin/vm-hands/network-contract-kx0hz3wt.js +0 -2
- package/bin/vm-hands/package-way7qesn.js +0 -2
- package/bin/vm-hands/permissions-jxycbgay.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-g54rtrhd.js +0 -2
- package/bin/vm-hands/serve-service-byvya1ym.js +0 -2
- package/bin/vm-hands/status-f1k1qmck.js +0 -10
- package/bin/vm-hands/version-czwf27v3.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-04x5xjt6.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-07apxfh8.js +0 -42
- package/bin/vm-hands/vm-hands-entry-lite-0wsr8edk.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-1tgxze8w.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-2twtpxmp.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-3gbf905c.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-48rphbjm.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-4anjdcth.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-73f4cgkf.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-8dfw96ym.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ak0hd94p.js +0 -7
- package/bin/vm-hands/vm-hands-entry-lite-bpamn7ny.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-dgfx0rbn.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-ecz6fzds.js +0 -126
- package/bin/vm-hands/vm-hands-entry-lite-frd7e74y.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-fxzadxz4.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-gje7xvy9.js +0 -6
- package/bin/vm-hands/vm-hands-entry-lite-h1qjggz0.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-j3fw7x65.js +0 -14
- package/bin/vm-hands/vm-hands-entry-lite-jydpev8e.js +0 -452
- package/bin/vm-hands/vm-hands-entry-lite-k84zsash.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-kf2jgke1.js +0 -150
- package/bin/vm-hands/vm-hands-entry-lite-m0gsez4t.js +0 -539
- package/bin/vm-hands/vm-hands-entry-lite-n7bd44rm.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-p5ny1pw4.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-qcktp8d9.js +0 -52
- package/bin/vm-hands/vm-hands-entry-lite-ravxhygk.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-s0rx4fm8.js +0 -105
- package/bin/vm-hands/vm-hands-entry-lite-tyem93c1.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-vj7xzb3y.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-wghmyfba.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-wzv13c8k.js +0 -65
- package/bin/vm-hands/vm-hands-entry-lite-yptpy066.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-zf0h0qjy.js +0 -2
- package/bin/vm-hands/vm-hands-op-runner-2bfbyj4e.js +0 -2
- package/bin/vm-hands/worker-preview-readiness-gy36ejp9.js +0 -2
- package/bin/vm-hands/worker-sandbox-f1tfb3y0.js +0 -2
|
@@ -1,539 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{nt,Et,cr,on,xt,kt,Di,sn,Oi,Ni,Li}from"./vm-hands-entry-lite-fxzadxz4.js";import{Pe,sr,ni,wt,Go,oe,Ko,Jo,tt,Re,nn,oi,vt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Z,Te,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ri,St,Ti}from"./vm-hands-entry-lite-07apxfh8.js";import{ue,X,I,N}from"./vm-hands-entry-lite-48rphbjm.js";import{P,Vt}from"./vm-hands-entry-lite-n7bd44rm.js";import{mr,eo,to,at,ro,no,io,oo,so,ao,yr,wr,br,wn,bn,vr,lo,vn,Sr,me,ge,Ot,Er,kr,Nt}from"./vm-hands-entry-lite-jydpev8e.js";import{O,T,b}from"./vm-hands-entry-lite-1yv5qqew.js";import{Xi,Yi,_n,Zi,yn,Qi,st,fr}from"./vm-hands-entry-lite-p5ny1pw4.js";import{K}from"./vm-hands-entry-lite-wghmyfba.js";import{Ue}from"./vm-hands-entry-lite-gje7xvy9.js";import{j}from"./vm-hands-entry-lite-dgfx0rbn.js";import{hr,gn,Ji}from"./vm-hands-entry-lite-ak0hd94p.js";import{xo,ko,ht,Co,Ao,Po,Ro,To,Io,Do}from"./vm-hands-entry-lite-2v4zh9ze.js";import{Rr,Ht,Tr,Tn,In}from"./vm-hands-entry-lite-0wsr8edk.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-kf2jgke1.js";import{Un,x,vo}from"./vm-hands-entry-lite-ecz6fzds.js";import{So,Eo}from"./vm-hands-entry-lite-j3fw7x65.js";import{Bt,Pn,Rn}from"./vm-hands-entry-lite-506b6pcz.js";import{ye,ho,fo}from"./vm-hands-entry-lite-bpamn7ny.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{Mt}from"./vm-hands-entry-lite-yptpy066.js";import{Ee,Xt,Yt,Zt,E}from"./vm-hands-entry-lite-46pwqvpf.js";import{a,ie}from"./vm-hands-entry-lite-8dfw96ym.js";import{t,k,o,d,u,n,W,g,ee,s,i,Zo}from"./vm-hands-entry-lite-wzv13c8k.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,$e,ln}from"./vm-hands-entry-lite-tyem93c1.js";import{Me}from"./vm-hands-entry-lite-3gbf905c.js";import{request as Fl}from"http";import{request as Ul}from"https";import{lookup as Hl}from"dns/promises";import{isIP as jl}from"net";async function ql(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Ul:Fl)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:Di},(f)=>c({response:f,close:()=>{f.destroy(),m.destroy(),f.socket?.destroy()}}));m.once("error",p),m.once("timeout",()=>m.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),m.end(e.body)})}var es=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),Wl=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function ts(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(es.has(c))return"custom_endpoint_host_not_found";if(Wl.has(c))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(c))return"custom_endpoint_tls_failed"}for(let p of[...e instanceof AggregateError?e.errors:[],e.cause]){let m=ts(p,l+1);if(m)return m}return null}async function Vl(e,l){let c=ts(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||jl(p)!==0)return c;let m;return await Promise.race([Hl(p).then(()=>!0,(h)=>!es.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function zl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function Gl(e,l){let c=Buffer.from(e),p=Buffer.from(l),m=new Uint32Array(c.length);for(let h=1,y=0;h<c.length;h++){while(y&&c[h]!==c[y])y=m[y-1];if(c[h]===c[y])y++;m[h]=y}let f=0;return(h,y=!1)=>{let S=Buffer.allocUnsafe(h.length*p.length+f),w=0;for(let _ of h){while(f&&c[f]!==_){let v=m[f-1];w+=c.copy(S,w,0,f-v),f=v}if(c[f]===_){if(f++,f===c.length)w+=p.copy(S,w),f=0}else S[w++]=_}if(y)w+=c.copy(S,w,0,f),f=0;return S.subarray(0,w)}}async function rs(e){e.signal.throwIfAborted();let l=Oi.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=Ni.parse(await e.credential(e.signal));if(!sn(c,{baseUrl:c.baseUrl,api:p.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let m,f,h=0,y=0,S=0,w=zl(p.apiKey),_=Gl(p.apiKey,w),v=async(C,A)=>{e.signal.throwIfAborted(),await new Promise((F,L)=>{let M=()=>{e.signal.removeEventListener("abort",M),L(e.signal.reason)};if(e.signal.addEventListener("abort",M,{once:!0}),e.signal.aborted){M();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(C,A))).then(()=>{e.signal.removeEventListener("abort",M),F()},(B)=>{e.signal.removeEventListener("abort",M),L(B)})})},R=async(C)=>{if(h+=C.length,h>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<C.length;A+=Et){if(S>=on)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await v(`custom_endpoint.chunk.${S++}`,{eof:!1,data:C.subarray(A,A+Et).toString("base64")})}};try{let C=await ql({url:c.url,body:c.body,signal:e.signal,headers:{...c.headers,...p.api==="anthropic-messages"?{"x-api-key":p.apiKey}:{authorization:`Bearer ${p.apiKey}`}}});m=C.response,f=C.close;let A=m.statusCode??500;if(A>=300&&A<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(m.headers["content-encoding"]&&m.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let F={};for(let L of["content-type","retry-after","x-request-id","request-id"]){let M=m.headers[L];if(typeof M==="string")F[L]=M.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:A,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:F});for await(let L of m){e.signal.throwIfAborted();let M=Buffer.isBuffer(L)?L:Buffer.from(L);if(y+=M.length,y>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await R(_(M))}return await R(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(C){if(e.signal.throwIfAborted(),C instanceof r)throw C;throw new r((m?null:await Vl(C,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as ls}from"path";function Yl(e,l){return e===ls(l,".ara","workspace")||e===ls(l,".reason","workspace")}function cs(e,l){let c=e.filter((p)=>Yl(p.path,l));return c.length===1?c[0].path:null}var Kl=/^[a-f0-9]{64}$/;var cn=32,Xl=/^\/[^\x00-\x1f\x7f\\]*$/;function Or(e){if(typeof e!=="string"||e.length>4096||!Xl.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((l)=>l!==""&&l!=="."&&l!=="..")}function Ir(e,l){let c=l==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!c)return e;let p=c[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${c[1].toUpperCase()}:${p?`/${p}`:""}`}function un(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let l=e;if(!Or(l.home)||!Array.isArray(l.roots)||l.roots.length>cn)return;let c=[];for(let p of l.roots){if(!p||typeof p!=="object"||Array.isArray(p))return;let{path_fingerprint:m,path:f}=p;if(typeof m!=="string"||!Kl.test(m)||!Or(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Jl(e){let l=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&l?l:void 0}function Zl(e){return Jl(e)??e.email.toLowerCase()}function dn(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?Zl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var zt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Ql=[...Ee.map((e)=>`/(${e.map(zt).join("/")})(/|$)`),...Xt.map((e)=>`/(${e.map(zt).join("/")})(/|$)`),...[...Yt].map((e)=>`/(${zt(e)})$`),`/${zt(".env.")}[^/]*$`,...Zt.map((e)=>`/[^/]*${zt(e)}$`)],us=`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(Ql)}.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 tc,spawnSync as rc}from"child_process";import*as Y from"fs";import*as ae from"path";import{homedir as nc}from"os";function ds(e,l,c,p="gh"){if(!["gh","git"].includes(p))throw Error("local_device_gh_unavailable");let m=e.realpathSync(c);if(process.platform==="win32"){let h=(y)=>y.toLowerCase()===m.toLowerCase()||y.toLowerCase().startsWith(m.toLowerCase()+l.sep);for(let y of new Set([process.env.ProgramW6432,process.env.ProgramFiles])){if(!y)continue;try{let S=e.realpathSync(p==="gh"?`${y}\\GitHub CLI\\gh.exe`:`${y}\\Git\\cmd\\git.exe`);if(!h(S)&&S.toLowerCase().startsWith(y.toLowerCase()+"\\")&&e.statSync(S).isFile())return S}catch{}}throw Error("local_device_gh_unavailable")}let f=p==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+p;for(let h of["/opt/homebrew/bin/"+p,"/usr/local/bin/"+p,f])try{let y=e.realpathSync(h);if(y===m||y.startsWith(m+l.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...p==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((w)=>y.startsWith(w)))continue;let S=e.statSync(y);if(!S.isFile()||(S.mode&18)!==0||![0,process.getuid()].includes(S.uid))continue;return e.accessSync(y,e.constants.X_OK),y}catch{continue}throw Error("local_device_gh_unavailable")}function ps(e,l){let c=1;for(let p=0;p<l;p+=1)if(e.charCodeAt(p)===10)c+=1;return c}var ms=[{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 pn(e){let l=e.trim().replaceAll("\\","/");if(!l)return{valid:!1,reason:"empty_path"};if(l.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(l.split("/").includes("..")||l.includes("../")||l.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(l===".git"||l.startsWith(".git/")||l.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function fs(e){return[...new Set(e.map((l)=>l.trim()).filter((l)=>l.length>=8))]}function hs(e,l){return[...l.matchAll(new RegExp(e.regex.source,`${e.regex.flags}g`))]}function Ar(e,l=[],c={}){let p=[],m=c.published??new Set,f=fs(l).filter((h)=>!m.has(h));for(let h of e){let y=pn(h.path);if(!y.valid){p.push({path:h.path,reason:y.reason??"invalid_path"});continue}let S=h.content??"",w=f.map((_)=>({secret:_,offset:S.indexOf(_)})).filter((_)=>_.offset>=0).sort((_,v)=>_.offset-v.offset);if(w.length>0){let _=[...new Set(w.flatMap((v)=>c.secretNames?.(v.secret)??[]))];p.push({path:h.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:ps(S,w[0].offset),..._.length>0?{secretNames:_}:{}})}for(let _ of ms){let v=hs(_,S).find((R)=>!m.has(R[0]));if(v){p.push({path:h.path,reason:`credential_pattern_detected: ${_.name}`,pattern:_.name,ruleId:_.name,line:ps(S,v.index)});break}}}return{clean:p.length===0,violations:p,scannedObjectCount:e.length}}function gs(e,l=[]){let c=fs(l),p=new Set;for(let{content:m}of e){for(let f of c)if(m.includes(f))p.add(f);for(let f of ms)for(let h of hs(f,m))p.add(h[0])}return[...p]}function ec(e,l){let c=0;for(let p=e.indexOf(l);p>=0;p=e.indexOf(l,p+l.length))c+=1;return c}function _s(e,l,c){let p=(m,f)=>m.reduce((h,y)=>h+ec(y,f),0);return new Set(e.filter((m)=>p(l,m)<=p(c,m)))}var gt=4194304,Ke=process.platform==="win32",Kt=process.env.SystemRoot??"C:\\Windows",oc=(e)=>Ke?rc(ae.win32.join(Kt,"System32","taskkill.exe"),["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-e,"SIGKILL"),Gt=Ke?[ae.win32.join(Kt,"System32"),Kt].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",Lr=Ke?{SystemRoot:Kt,WINDIR:Kt}:{},ic=(e)=>Ke?ae.win32.resolve(e,"..","..","bin","sh.exe"):"/bin/sh",ys=536870912,hn=/^[a-f0-9]{40}$/,sc=(e,l,c)=>new Promise((p)=>{if(c.signal?.aborted){p({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let m;try{m=tc(e,l,{cwd:c.cwd,env:c.env,...Ke?{windowsHide:!0}:{detached:!0},stdio:["pipe","pipe","pipe"]})}catch{p({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let f=Buffer.alloc(0),h=Buffer.alloc(0),y,S=!1,w=(C)=>{if(y??=Error(C),m.pid)try{oc(m.pid)}catch{}},_=()=>w("cancelled"),v=setTimeout(()=>w("timeout"),c.timeout);c.signal?.addEventListener("abort",_,{once:!0});let R=(C)=>{if(S)return;S=!0,clearTimeout(v),c.signal?.removeEventListener("abort",_),p({status:C,stdout:f,stderr:h,...y?{error:y}:{}})};if(m.stdout.on("data",(C)=>{if(f.length+h.length+C.length>c.maxBuffer)w("output_limit");else f=Buffer.concat([f,C])}),m.stderr.on("data",(C)=>{if(f.length+h.length+C.length>c.maxBuffer)w("output_limit");else h=Buffer.concat([h,C])}),m.on("error",()=>{if(w("spawn_failed"),!m.pid)R(null)}),m.on("close",(C)=>R(C)),m.stdin.on("error",()=>w("input_failed")),m.stdin.end(c.input),c.signal?.aborted)_()}),ac={command:sc,gh:(e,l)=>ds(Y,ae,e,l),home:nc};function H(e){throw Error(e)}function Sn(e,l){let[c,p]=Ke?[e.toLowerCase(),l.toLowerCase()]:[e,l];return p===c||p.startsWith(c+ae.sep)}function lc(e,l){let c=new Set(e.split(/\r?\n/).map(dn));return l.filter((p)=>{let m=dn(p);if(c.has(m))return!1;return c.add(m),!0})}var cc=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),uc=(e)=>JSON.stringify(e,(l,c)=>cc.has(l)?void 0:c);function bs(e,l,c){let p=[...new Set(e.map((f)=>`${l(f.path)}${f.line?`:${f.line}`:""} (${f.reason==="literal_secret_detected"?`value of ${f.secretNames?.length?f.secretNames.slice(0,3).join(", "):"a session variable"}`:`${f.ruleId??"credential"} credential`})`))].slice(0,10),m=e.some((f)=>f.reason==="literal_secret_detected");H(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${p.join("; ")}. Nothing was sent. ${c}${m?" 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 ws(e,l,c=ac){let p=Pe.parse(e),m="local_device_gh_prepare_setup";try{if(!["darwin","linux","win32"].includes(process.platform))H("local_device_gh_platform_unavailable");l.assertCurrent();let f=Y.realpathSync(l.root);if(f===ae.parse(f).root)H("local_device_gh_root_unavailable");if(!tt(p)&&!l.forbiddenSecretValues)H("local_device_gh_secret_scope_unavailable");if(!tt(p)&&l.readOnly)H("local_device_gh_read_only");if(!tt(p)){let D=Ar([{path:"github-operation",content:uc(p)}],l.forbiddenSecretValues,l.secretNames?{secretNames:l.secretNames}:{});if(!D.clean)bs(D.violations,()=>`the ${p.kind} request text`,"Remove it from the pull request text and try again.")}let h=c.gh(f),y=c.home(),S=c.gh(f,"git"),w=l.privateDirectory?Y.realpathSync(l.privateDirectory):Y.realpathSync(y);if(!tt(p)&&(!l.privateDirectory||Sn(f,w)))H("local_device_gh_private_scope_unavailable");let _={...Lr,PATH:Ke?[ae.dirname(S),Gt].join(";"):Gt,HOME:y,GH_CONFIG_DIR:Ke&&process.env.APPDATA?ae.join(process.env.APPDATA,"GitHub CLI"):ae.join(y,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:Ke?"":"/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((D)=>process.env[D]?[[D,process.env[D]]]:[])):{}},v=async(D,z,G=w,te,le=gt)=>{l.assertCurrent();let ce=await c.command(D,z,{cwd:G,env:_,input:te,maxBuffer:le,timeout:Math.max(1,Math.min(60000,(l.deadlineMs??Date.now()+60000)-Date.now())),signal:l.signal});if(l.assertCurrent(),ce.error||ce.status!==0)H("local_device_gh_command_failed");return ce.stdout},R=async(D)=>(await v(h,D)).toString("utf8").trim(),C=async(D,z="application/vnd.github+json")=>{Ko(p.repoFullName,D,{headers:{accept:z}}),l.assertCurrent();let G=await c.command(h,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${z}`,D],{cwd:w,env:_,maxBuffer:gt,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal});if(l.assertCurrent(),G.error&&G.status===null)H("local_device_gh_response_unavailable");let te=G.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!te)H("local_device_gh_response_invalid");let le=Number(te[1]);if(le>=200&&le<300&&G.status!==0)H("local_device_gh_response_unavailable");if(Buffer.byteLength(te[3])>wt)H("local_device_gh_response_too_large");let ce={};for(let Ae of te[2].split(/\r?\n/)){let Be=Ae.indexOf(":"),lt=Ae.slice(0,Be).toLowerCase();if(["link","content-type"].includes(lt))ce[lt]=Ae.slice(Be+1).trim().slice(0,8192)}return{kind:"read",status:le,headers:ce,body:le>=200&&le<300?te[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(p.kind==="read")return C(p.path,p.accept);if(p.kind==="pr_review_context"){let[D,z]=p.repoFullName.split("/"),G=await R(["api","graphql","--hostname","github.com","-f",`query=${Jo}`,"-f",`owner=${D}`,"-f",`repo=${z}`,"-F",`number=${p.number}`,...p.after?["-f",`after=${p.after}`]:[]]);if(Buffer.byteLength(G)>wt)H("local_device_gh_response_too_large");let te=JSON.parse(G);if(te.errors||te.data?.repository?.nameWithOwner?.toLowerCase()!==p.repoFullName.toLowerCase()||te.data.repository.pullRequest?.number!==p.number)H("local_device_gh_response_invalid");return{kind:"pr_review_context",body:G}}if(p.kind==="pr_merge"){let D=await C(`/repos/${p.repoFullName}/pulls/${p.number}`),z=JSON.parse(D.body),G=(ce)=>ce.number===p.number&&ce.html_url===`https://github.com/${p.repoFullName}/pull/${p.number}`&&ce.base?.repo?.full_name?.toLowerCase()===p.repoFullName.toLowerCase()&&ce.base?.ref===p.expectedBaseRef&&ce.head?.sha===p.expectedHeadSha;if(D.status!==200||!G(z)||z.state!=="open"||z.draft!==!1||z.head?.sha!==p.expectedHeadSha||z.base?.repo?.full_name?.toLowerCase()!==p.repoFullName.toLowerCase())H("local_device_gh_merge_target_changed");await R(["pr","merge",String(p.number),`--repo=${p.repoFullName}`,`--${p.method}`,"--match-head-commit",p.expectedHeadSha,...p.commitBody!==void 0&&p.method!=="rebase"?[`--body=${p.commitBody}`]:[]]);let te=await C(`/repos/${p.repoFullName}/pulls/${p.number}`),le=JSON.parse(te.body);if(te.status!==200||!G(le)||le.merged!==!0)H("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:p.number,merged:!0}}if(p.kind==="pr_create"){if(p.head===p.base)H("local_device_gh_default_branch");let D=await R(["pr","create","--repo",p.repoFullName,"--head",p.head,"--base",p.base,`--title=${p.title}`,`--body=${p.body}`,...p.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+p.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(D))H("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:D}}if(p.kind==="pr_mutation"){let D=p.mutation,z=D.action==="edit"?["edit",...D.title!==void 0?[`--title=${D.title}`]:[],...D.body!==void 0?[`--body=${D.body}`]:[],...D.base?[`--base=${D.base}`]:[]]:D.action==="metadata"?["edit",`--${D.change}-${D.field}=${D.value}`]:D.action==="ready"?["ready"]:D.action==="draft"?["ready","--undo"]:["close"];return await R(["pr",...z,String(p.number),"--repo",p.repoFullName]),{kind:"pr_mutation",number:p.number,applied:!0}}if(!l.repoPath)H("local_device_gh_workspace_unavailable");let A=Y.realpathSync(l.repoPath);if(!Sn(f,A))H("local_device_gh_workspace_unavailable");let F=`https://github.com/${p.repoFullName}.git`,L="!'"+(Ke?h.replace(/\\/g,"/"):h).replace(/'/g,"'\\''")+"' auth git-credential",M=Me(us),B=(D,z,G)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",D,z,...G]]:[z,G],U=async(D,z,G,te=gt)=>{let le=Sn(w,D),ce=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...le?["-c",`credential.https://github.com.helper=${L}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...z];if(le)return v(S,ce,D,G,te);let Ae=ae.join(A,".ara-local-gh-tmp");if(Y.mkdirSync(Ae,{recursive:!0,mode:448}),Y.lstatSync(Ae).isSymbolicLink()||Y.realpathSync(Ae)!==Ae)H("local_device_gh_workspace_unavailable");l.assertCurrent();let Be=await c.command(...B(M(A,Ae),S,ce),{cwd:D,input:G,maxBuffer:te,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Lr,PATH:Gt,HOME:A,TMPDIR:Ae,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(l.assertCurrent(),Be.error||Be.status!==0)H("local_device_gh_collection_failed");return Be.stdout},V=async(D,z)=>(await U(D,z)).toString("utf8").trim(),se=async(D,z)=>{let G=ae.join(D,".ara-local-gh-tmp");if(Y.mkdirSync(G,{recursive:!0,mode:448}),Y.lstatSync(G).isSymbolicLink()||Y.realpathSync(G)!==G)H("local_device_gh_workspace_unavailable");l.assertCurrent();let te=await c.command(...B(M(D,G),ic(S),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",z]),{cwd:D,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Lr,PATH:Gt,HOME:D,TMPDIR:G}});if(l.assertCurrent(),te.error||te.status!==0)H("local_device_gh_materialization_failed")},we=async(D)=>{let z=new Map;if(D.length===0)return z;let G=await U(_e,["cat-file","--batch"],[...new Set(D)].join(`
|
|
14
|
-
`)+`
|
|
15
|
-
`,gt*8);for(let te=0;te<G.length;){let le=G.indexOf(10,te),[ce,Ae,Be]=G.subarray(te,le).toString("utf8").split(" ");if(le<0||!ce||Ae!=="blob"||!/^[0-9]+$/.test(Be??""))H("local_device_gh_object_invalid");z.set(ce,G.subarray(le+1,le+1+Number(Be)).toString("utf8")),te=le+1+Number(Be)+1}return z},Ce=async(D,z,G)=>{let te=ae.join(A,".ara-local-gh-tmp"),le=M(A,te)+`
|
|
16
|
-
(allow file-read* file-write* (subpath ${JSON.stringify(A)}))
|
|
17
|
-
(allow file-read* (subpath ${JSON.stringify(D)}))
|
|
18
|
-
(allow file-read-metadata (path-ancestors ${JSON.stringify(D)}))`,ce=async(Be,lt)=>{l.assertCurrent();let Ut=await c.command(...B(le,Be,lt),{cwd:A,maxBuffer:gt,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Lr,PATH:Gt,HOME:A,TMPDIR:te,GIT_INDEX_FILE:ae.join(A,".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(l.assertCurrent(),Ut.error||Ut.status!==0)H("local_device_gh_materialization_failed")},Ae=["--git-dir="+D,"--work-tree="+A,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await ce(S,[...Ae,"read-tree",z]),await ce(S,[...Ae,"checkout-index","--all","--index"]),await U(A,["update-ref","refs/heads/"+G,z]),await U(A,["symbolic-ref","HEAD","refs/heads/"+G])};m="local_device_gh_prepare_metadata";let Qe=await C(`/repos/${p.repoFullName}`);if(Qe.status!==200)H("local_device_gh_repository_unavailable");let it=JSON.parse(Qe.body);if(it.full_name?.toLowerCase()!==p.repoFullName.toLowerCase()||it.default_branch!==p.defaultBranch||p.kind==="publish"&&it.permissions?.push!==!0)H("local_device_gh_repository_authority_changed");if(p.branch===p.defaultBranch)H("local_device_gh_default_branch");m="local_device_gh_prepare_private_init";let _e=Y.mkdtempSync(ae.join(w,"github-publication-"));Y.chmodSync(_e,448);let Cr=!1;try{if(await U(_e,["init","--bare","--template="]),p.kind==="prepare"){if(m="local_device_gh_prepare_fetch",await U(_e,["fetch","--depth=1","--no-tags","--no-recurse-submodules",F,p.baseSha]),await V(_e,["rev-parse","FETCH_HEAD"])!==p.baseSha)m="local_device_gh_prepare_base_mismatch",H("local_device_gh_base_changed");m="local_device_gh_prepare_checkout_validation";let Se=ae.join(A,".git"),ze=!1;if(Y.existsSync(Se)){if(!Y.lstatSync(Se).isDirectory()||Y.lstatSync(Se).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((Oe)=>Y.existsSync(ae.join(Se,Oe))))H("local_device_gh_repository_layout_invalid");let De=await U(A,["rev-parse","--verify","-q","HEAD"]).then((Oe)=>Oe.toString("utf8").trim(),()=>null),Ge=await U(A,["config","--local","--get","remote.origin.url"]).then((Oe)=>Oe.toString("utf8").trim(),()=>"");if(De!==null||Ge){if(De!==p.baseSha||await V(A,["branch","--show-current"])!==p.branch)H("local_device_gh_checkout_exists");return{kind:"prepare",headSha:p.baseSha}}ze=!0}let Fe=Y.readdirSync(A).filter((De)=>!(ze&&De===".git")),Je=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if(Fe.some((De)=>!Je.includes(De))||Fe.some((De)=>{let Ge=ae.join(A,De);return!Y.lstatSync(Ge).isDirectory()||Y.lstatSync(Ge).isSymbolicLink()||Y.readdirSync(Ge).length>0}))H("local_device_gh_checkout_not_empty");if(m="local_device_gh_prepare_checkout_init",!ze)await U(A,["init","--template="]);m="local_device_gh_prepare_materialization";let et=await U(_e,["pack-objects","--stdout","--revs"],p.baseSha+`
|
|
19
|
-
`,ys);return await se(A,p.baseSha),await U(A,["index-pack","--strict","--stdin"],et,65536),await U(A,["remote","add","origin",F]),await Ce(_e,p.baseSha,p.branch),{kind:"prepare",headSha:p.baseSha}}let D=ae.join(A,".git");if(!Y.lstatSync(D).isDirectory()||Y.lstatSync(D).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((Se)=>Y.existsSync(ae.join(D,Se))))H("local_device_gh_repository_layout_invalid");if(await V(A,["branch","--show-current"])!==p.branch)H("local_device_gh_branch_changed");let z=await V(A,["rev-parse","--verify","HEAD"]);if(!hn.test(z))H("local_device_gh_head_invalid");let G=await C(`/repos/${p.repoFullName}/commits/${p.baseSha}`);if(G.status!==200||JSON.parse(G.body).sha!==p.baseSha)H("local_device_gh_base_unverified");let te=await C(`/repos/${p.repoFullName}/git/ref/heads/${encodeURIComponent(p.branch)}`);if(p.remoteHeadSha===null?te.status!==404:te.status!==200||JSON.parse(te.body).object?.sha!==p.remoteHeadSha)H("local_device_gh_remote_changed");let le=[...(await V(A,["rev-list","--objects","--no-object-names",z,"--not",p.baseSha])).split(`
|
|
20
|
-
`),...(await V(A,["rev-list","--objects","--no-object-names","--no-walk",p.baseSha])).split(`
|
|
21
|
-
`)].filter(Boolean);if(le.some((Se)=>!hn.test(Se)))H("local_device_gh_object_invalid");let ce=await U(A,["pack-objects","--stdout"],[...new Set(le)].join(`
|
|
22
|
-
`)+`
|
|
23
|
-
`,ys);if(Y.writeFileSync(ae.join(_e,"shallow"),p.baseSha+`
|
|
24
|
-
`,{flag:"wx",mode:384}),await U(_e,["index-pack","--strict","--stdin"],ce,65536),await U(_e,["merge-base","--is-ancestor",p.baseSha,z]),p.remoteHeadSha)await U(_e,["merge-base","--is-ancestor",p.remoteHeadSha,z]);let Ae=await U(_e,["show","-s","--format=%B",z]),Be=(await U(_e,["interpret-trailers","--parse"],Ae)).toString("utf8"),lt=p.contributorTrailers?{expectedTrailers:p.contributorTrailers,missingFromHead:lc(Be,p.contributorTrailers)}:void 0,Ut=(await V(_e,["rev-list","--objects","--no-object-names",z,"--not",p.baseSha,...p.remoteHeadSha?[p.remoteHeadSha]:[]])).split(`
|
|
25
|
-
`).filter(Boolean);if(Ut.length>5000)H("local_device_gh_collection_too_large");let qt=[],Wi=0;for(let Se of Ut){if(!hn.test(Se))H("local_device_gh_object_invalid");let ze=await V(_e,["cat-file","-t",Se]);if(!["blob","commit","tree"].includes(ze))H("local_device_gh_object_invalid");let Fe=await U(_e,["cat-file",ze,Se]);if(Wi+=Fe.length,Wi>gt)H("local_device_gh_collection_too_large");if(ze==="tree"){let Je=0;while(Je<Fe.length){let et=Fe.indexOf(32,Je),De=Fe.indexOf(0,et+1);if(et<Je||De<=et||De+21>Fe.length)H("local_device_gh_object_invalid");let Ge=Fe.subarray(et+1,De).toString("utf8");if(Ge.includes("/")||!pn(Ge).valid)H("local_device_gh_object_invalid");Je=De+21}}qt.push({path:`object-${Se}`,content:Fe.toString("utf8")})}let zi=l.secretNames?{secretNames:l.secretNames}:{},Wt=Ar(qt,l.forbiddenSecretValues,zi),Gi=new Map;if(!Wt.clean)try{let Se=(await U(_e,["diff","--no-renames","--no-abbrev","--raw","-z",p.baseSha,z])).toString("utf8").split("\x00"),ze=[],Fe=[];for(let Oe=0;Oe+1<Se.length;Oe+=2){let[,$l,Bl,an,Pr]=Se[Oe].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!an||!Pr)continue;if($l!=="160000"&&!/^0+$/.test(an))ze.push(an);if(Bl!=="160000"&&!/^0+$/.test(Pr))Fe.push(Pr),Gi.set(`object-${Pr}`,Se[Oe+1])}let Je=await we([...ze,...Fe]),et=new Set(Wt.violations.map((Oe)=>Oe.path)),De=gs(qt.filter((Oe)=>et.has(Oe.path)),l.forbiddenSecretValues),Ge=_s(De,Fe.map((Oe)=>Je.get(Oe)??""),ze.map((Oe)=>Je.get(Oe)??""));if(Ge.size>0)Wt=Ar(qt,l.forbiddenSecretValues,{...zi,published:Ge})}catch{}if(!Wt.clean)bs(Wt.violations,(Se)=>Gi.get(Se)??`an object in the pushed history (${Se})`,"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 U(_e,["push","--no-recurse-submodules",F,`${z}:refs/heads/${p.branch}`]);let Ki=await C(`/repos/${p.repoFullName}/git/ref/heads/${encodeURIComponent(p.branch)}`);if(Ki.status!==200||JSON.parse(Ki.body).object?.sha!==z)H("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:z,scannedObjectCount:qt.length,...lt?{attribution:lt}:{}}}catch(D){throw Cr=!0,D}finally{try{Y.rmSync(_e,{recursive:!0,force:!0})}catch(D){if(!Cr||p.kind!=="prepare")throw m=null,D}}}catch(f){if(p.kind==="prepare"&&p.diagnosticsVersion===1&&m&&!l.signal?.aborted)throw new sr(m);throw f}}var _t=n({profile:t().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:t().min(1).max(1024)}).strict(),En={ready:i(!0),boot_generation:t().uuid(),proof_ready:i(!1),result:i("metadata_only")},dc=n({...En,version:i(2),development_only:i(!1),image:i(!0),video:i(!1),source_bound:i(!1),profiles:u(_t.shape.profile).min(1).max(16),extension_instance_ids:u(_t.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine((e)=>new Set(e.profiles).size===e.profiles.length&&e.profiles.length===e.extension_instance_ids.length),pc=n({...En,version:i(3),development_only:i(!1),image:i(!0),video:i(!0),source_bound:i(!1),max_seconds:i(15),profiles:u(_t.shape.profile).min(1).max(16),extension_instance_ids:u(_t.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine((e)=>new Set(e.profiles).size===e.profiles.length&&e.profiles.length===e.extension_instance_ids.length),Cn=W([dc,pc]),Om=W([n({...En,version:i(1),development_only:i(!0),profile:_t.shape.profile,extension_instance_id:_t.shape.extension_instance_id,max_seconds:i(15)}).strict(),Cn]);import{createServer as mc,request as fc}from"http";import{connect as hc,isIP as gc}from"net";var xs=120000,_c=15000;function yc(e,l,c){let p=vr(l).toLowerCase().replace(/\.$/,"");if(!p||gc(p))return!1;return e.some((m)=>{if(!yn.test(m))return!1;let f=m.lastIndexOf(":"),h=f>0?m.slice(0,f):m;if(f>0&&Number(m.slice(f+1))!==c)return!1;return h.startsWith("*.")?p.endsWith(h.slice(1)):p===h})}function bc(e,l){let c=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec(e),p=c?c[1]:e,m=c?Number(c[2]):l;return p&&m>=1&&m<=65535?{host:p,port:m}:null}async function On(e,l,c){if(!yc(c,e,l))return null;let p=await lo(e);return p.ok?p.addresses[0]:null}function Jt(e,l){e.end(`HTTP/1.1 ${l} ${l===403?"Forbidden":"Bad Gateway"}\r
|
|
26
|
-
Connection: close\r
|
|
27
|
-
Content-Length: 0\r
|
|
28
|
-
\r
|
|
29
|
-
`)}function Ss(e,l){return new Promise((c,p)=>{let m=hc({host:e,port:l}),f=setTimeout(()=>m.destroy(Error("connect_timeout")),_c);m.once("connect",()=>{clearTimeout(f),c(m)}),m.once("error",(h)=>{clearTimeout(f),p(h)})})}function vs(e,l,c){for(let p of[e,l])p.on("error",()=>{e.destroy(),l.destroy()}),p.on("close",()=>{e.destroy(),l.destroy()});if(l.setTimeout(xs,()=>l.destroy()),c.length)l.write(c);e.pipe(l).pipe(e)}function Rs(e,l){let c={...e,host:l};return delete c["proxy-authorization"],delete c["proxy-connection"],c}async function Es(e,l=()=>{}){let c=[...e],p=new Set,m=(y)=>{p.add(y),y.once("close",()=>p.delete(y))},f=mc((y,S)=>{(async()=>{let w;try{w=new URL(y.url??"")}catch{w=new URL("invalid:")}let _=Number(w.port||80),v=w.protocol==="http:"?await On(w.hostname,_,c):null;if(!v){l(),S.writeHead(403,{connection:"close"}).end();return}let R=fc({host:v,port:_,method:y.method,path:`${w.pathname}${w.search}`,headers:Rs(y.headers,w.host),agent:!1,timeout:xs},(C)=>{S.writeHead(C.statusCode??502,C.headers),C.pipe(S)});R.on("timeout",()=>R.destroy()),R.on("error",()=>{if(!S.headersSent)S.writeHead(502);S.end()}),S.on("close",()=>R.destroy()),y.pipe(R)})().catch(()=>{if(!S.headersSent)S.writeHead(502);S.end()})});f.on("connection",m),f.on("connect",(y,S,w)=>{m(S),S.on("error",()=>S.destroy()),(async()=>{let _=bc(y.url??"",443),v=_?await On(_.host,_.port,c):null;if(!_||!v){l(),Jt(S,403);return}let R=await Ss(v,_.port).catch(()=>null);if(!R){Jt(S,502);return}if(S.destroyed){R.destroy();return}m(R),S.write(`HTTP/1.1 200 Connection Established\r
|
|
30
|
-
\r
|
|
31
|
-
`),vs(S,R,w)})().catch(()=>S.destroy())}),f.on("upgrade",(y,S,w)=>{m(S),S.on("error",()=>S.destroy()),(async()=>{let _;try{_=new URL(y.url??"")}catch{Jt(S,403);return}let v=Number(_.port||80),R=["http:","ws:"].includes(_.protocol)?await On(_.hostname,v,c):null;if(!R){l(),Jt(S,403);return}let C=await Ss(R,v).catch(()=>null);if(!C){Jt(S,502);return}m(C);let A=Rs(y.headers,_.host),F=[`${y.method} ${_.pathname}${_.search} HTTP/1.1`];for(let[L,M]of Object.entries(A))for(let B of Array.isArray(M)?M:M===void 0?[]:[M])F.push(`${L}: ${B}`);C.write(`${F.join(`\r
|
|
32
|
-
`)}\r
|
|
33
|
-
\r
|
|
34
|
-
`),vs(S,C,w)})().catch(()=>S.destroy())}),await new Promise((y,S)=>{f.once("error",S),f.listen(0,"127.0.0.1",()=>y())});let{port:h}=f.address();return{url:`http://127.0.0.1:${h}`,close(){f.close();for(let y of p)y.destroy()}}}import{createHash as Hn,randomUUID as Rc}from"crypto";import{closeSync as Ur,constants as He,fchownSync as xc,fstatSync as ct,fsyncSync as Ec,linkSync as Hs,lstatSync as Mn,mkdirSync as js,openSync as Br,readSync as Vs,realpathSync as $n,unlinkSync as qs,writeSync as Cc}from"fs";import{isAbsolute as Pc,join as Oc,relative as Ic,sep as Ac}from"path";import{platform as Bn}from"os";import{getSystemErrorName as Lc}from"util";var Cs={type:"string",format:"uuid"},As=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,Dr={type:"string",minLength:1,maxLength:4096,pattern:As},An=t().min(1).max(4096).regex(new RegExp(As)),Nr={device_id:t().uuid(),root_id:t().uuid(),timeout_ms:o().int().min(1000).max(60000).optional()},Mr={device_id:Cs,root_id:Cs,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},Mm={read:{schema:n({...Nr,path:An,offset:o().int().min(0).optional(),max_bytes:o().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...Mr,path:Dr,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:n({...Nr,path:An,content:t().max(131072),mode:s(["overwrite","append"]).optional(),create_parents:d().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...Mr,path:Dr,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:n({...Nr,command:t().min(1).max(16000),cwd:An.optional(),mode:s(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...Mr,command:{type:"string",minLength:1,maxLength:16000},cwd:Dr,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}}},Ze=1073741824,Qt=600000,Ps=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,Ls=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${Ps}(?:/${Ps})*(?![\s\S])`,ks=new RegExp(Ls);function Ts(e){return typeof e==="string"&&e.length>0&&e.length<=4096&&ks.test(e)}var Ln=t().min(1).max(4096).regex(ks),kn={...Dr,pattern:Ls},Ds=t().regex(/^[a-f0-9]{64}$/),Ns=n({kind:i("workspace"),path:Ln}).strict(),wc=g("kind",[Ns,n({kind:i("attachment"),attachment_id:t().min(1).max(120),sha256:Ds}).strict()]),$r=1,er="cloud_workspace_id",Dn="cloud_workspace",Nn=1,Sc=g("kind",[Ns,n({kind:i("attachment"),download_url:t().min(1).max(16384),size_bytes:o().int().min(0).max(Ze),sha256:Ds}).strict()]),Us=n({source_version:i($r),source:Sc,url:t().min(1).max(16384),transfer_cloud_scope:n({sandboxId:t().min(1).max(256),revision:o().int().nonnegative(),brainFence:t().uuid()}).strict().optional(),[er]:t().min(1).max(160).optional()}).strict(),$m=n({ready:i(!0),cloud_source_version:i($r),source_kinds:u(s(["workspace","attachment"]))});var Os=n({...Nr,timeout_ms:o().int().min(1000).max(Qt).optional(),source_path:Ln,destination_path:Ln,idempotency_key:t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),Is={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...Mr,timeout_ms:{type:"integer",minimum:1000,maximum:Qt},source_path:kn,destination_path:kn,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},vc={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:kn},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}]},Bm=W([Os,Os.omit({source_path:!0}).extend({source:wc}).strict()]),Fm={...Is,required:["device_id","root_id","destination_path"],properties:{...Is.properties,source:vc},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var jn=65536;function ve(e){throw new r(e,e)}function Hr(e){return typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"?e.code:void 0}function Fr(e,l,c){if(l.throwIfAborted(),e instanceof r||e instanceof Error&&e.name==="AbortError")throw e;return ve(c)}function kc(e,l,c){let p;switch(Hr(e)){case"ENOENT":p=c==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":p="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":p="transfer_path_unsafe";break;case"EEXIST":p="transfer_destination_exists";break;default:p="transfer_path_unavailable"}return Fr(e,l,p)}function Tc(e){if(typeof e!=="string"||e.length>16384)return ve("transfer_url_invalid");let l;try{l=new URL(e)}catch{return ve("transfer_url_invalid")}if(l.protocol!=="https:"||l.username||l.password||l.hash)return ve("transfer_url_invalid");return l.href}var Fn=He.O_RDONLY|He.O_DIRECTORY|He.O_NOFOLLOW;async function Dc(){if(Bn()==="win32"){let w=new Map,_,v=-1,R=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),C=(M)=>{let B=Ic(_,M);return B===""||B!==".."&&!B.startsWith(`..${Ac}`)&&!Pc(B)},A=(M)=>{let B=Mn(M);if(B.isSymbolicLink())throw R();if(!B.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let U=$n(M);if(_??=U,!C(U))throw R();return w.set(v,{path:M,real:U}),v--},F=(M)=>{let B=w.get(M);if($n(B.path)!==B.real)throw R();return B.path},L=(M,B)=>{if(ln(B))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return Oc(w.get(M).path,B)};return{root:A,openDirectory:(M,B)=>A(L(M,B)),open:(M,B,U,V=384)=>{let se=L(M,B);if(Mn(se,{throwIfNoEntry:!1})?.isSymbolicLink())throw R();F(M);let we=Br(se,U,V);try{let Ce=ct(we),Qe=Mn(se);if(Qe.isSymbolicLink()||Ce.ino!==Qe.ino||Ce.dev!==Qe.dev||!C($n(se)))throw R()}catch(Ce){throw Ur(we),Ce}return we},mkdir:(M,B)=>{let U=L(M,B);F(M),js(U)},link:(M,B,U)=>{let V=L(M,B),se=L(M,U);F(M),Hs(V,se)},unlink:(M,B)=>qs(L(M,B)),closeDirectory:(M)=>{w.delete(M)},inherit:()=>{},close:()=>{}}}let e={root:(w)=>Br(w,Fn),closeDirectory:Ur,inherit:Nc};if(Bn()==="linux")return{...e,openDirectory:(w,_)=>Br(`/proc/self/fd/${w}/${_}`,Fn),open:(w,_,v,R=384)=>Br(`/proc/self/fd/${w}/${_}`,v,R),mkdir:(w,_)=>js(`/proc/self/fd/${w}/${_}`,{mode:448}),link:(w,_,v)=>Hs(`/proc/self/fd/${w}/${_}`,`/proc/self/fd/${w}/${v}`),unlink:(w,_)=>qs(`/proc/self/fd/${w}/${_}`),close:()=>{}};if(Bn()!=="darwin")return ve("transfer_platform_unsupported");let{dlopen:l,FFIType:c,ptr:p,read:m}=await import("bun:ffi"),f=l("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:c.ptr},openat:{args:[c.i32,c.ptr,c.i32,c.i32,c.i32,c.i32,c.i32,c.i32,c.i32],returns:c.i32},mkdirat:{args:[c.i32,c.ptr,c.i32],returns:c.i32},linkat:{args:[c.i32,c.ptr,c.i32,c.ptr,c.i32],returns:c.i32},unlinkat:{args:[c.i32,c.ptr,c.i32],returns:c.i32}}),h=f.symbols.__error();if(h===null)return f.close(),ve("transfer_path_unavailable");let y=(w)=>{if(w<0){let _=Lc(-m.i32(h));throw Object.assign(Error("transfer_path_unavailable"),{code:_})}return w},S=(w,_,v,R=384)=>y(f.symbols.openat(w,p(Buffer.from(`${_}\x00`)),v,R,0,0,0,0,R));return{...e,openDirectory:(w,_)=>S(w,_,Fn),open:S,mkdir:(w,_)=>{y(f.symbols.mkdirat(w,p(Buffer.from(`${_}\x00`)),448))},link:(w,_,v)=>{y(f.symbols.linkat(w,p(Buffer.from(`${_}\x00`)),w,p(Buffer.from(`${v}\x00`)),0))},unlink:(w,_)=>{y(f.symbols.unlinkat(w,p(Buffer.from(`${_}\x00`)),0))},close:()=>f.close()}}function Nc(e,l){let c=ct(e),p=ct(l);if(p.uid!==c.uid||p.gid!==c.gid)xc(l,c.uid,c.gid)}function Mc(e,l,c,p){if(!Ts(c))return ve("transfer_path_invalid");let m=c.split("/"),f=e.root(l);try{for(let h of m.slice(0,-1)){let y;try{y=e.openDirectory(f,h)}catch(S){if(!p||Hr(S)!=="ENOENT")throw S;try{e.mkdir(f,h)}catch(w){if(Hr(w)!=="EEXIST")throw w}y=e.openDirectory(f,h),e.inherit(f,y)}e.closeDirectory(f),f=y}return{fd:f,leaf:m.at(-1)}}catch(h){throw e.closeDirectory(f),h}}function Ws(e,l){let c=ct(e,{bigint:!0});if(!c.isFile()||c.size>Ze)return ve("transfer_file_invalid");let p=Hn("sha256"),m=Buffer.alloc(jn),f=0;while(!0){l.throwIfAborted();let y=Vs(e,m,0,m.length,f);if(!y)break;if(f+=y,f>Ze)return ve("transfer_size_exceeded");p.update(m.subarray(0,y))}let h=ct(e,{bigint:!0});if(BigInt(f)!==c.size||h.size!==c.size||h.mtimeNs!==c.mtimeNs||h.ctimeNs!==c.ctimeNs)return ve("transfer_source_changed");return{size_bytes:f,sha256:p.digest("hex")}}async function yt(e){e.signal.throwIfAborted();try{let l=Tc(e.payload.url),c=await Dc(),p,m,f;try{if(p=Mc(c,e.root,e.path,e.direction==="import"),e.direction==="export"){m=c.open(p.fd,p.leaf,He.O_RDONLY|He.O_NOFOLLOW|He.O_NONBLOCK);let R=ct(m,{bigint:!0});if(!R.isFile()||R.size>Ze)return ve("transfer_file_invalid");let C=Hn("sha256"),A=0,F=m,L,M=new ReadableStream({pull(se){try{e.signal.throwIfAborted();let we=Buffer.alloc(jn),Ce=Vs(F,we,0,we.length,A);if(!Ce){se.close();return}if(A+=Ce,A>R.size)return ve("transfer_source_changed");C.update(we.subarray(0,Ce)),se.enqueue(we.subarray(0,Ce))}catch(we){throw L=we,we}}});try{let se=await(e.fetchImpl??fetch)(l,Object.assign({method:"PUT",body:M,redirect:"error",signal:e.signal,headers:{"content-type":"application/octet-stream","content-length":String(R.size)}},{duplex:"half"}));if(L!==void 0)throw L;if(!se.ok)return ve("transfer_upload_failed");await se.body?.cancel()}catch(se){if(L!==void 0)throw L;return Fr(se,e.signal,"transfer_upload_failed")}let B=ct(m,{bigint:!0});if(BigInt(A)!==R.size||B.size!==R.size||B.mtimeNs!==R.mtimeNs||B.ctimeNs!==R.ctimeNs)return ve("transfer_source_changed");let U=C.digest("hex"),V=Ws(m,e.signal);if(V.size_bytes!==A||V.sha256!==U)return ve("transfer_source_changed");return{size_bytes:A,sha256:U,outcome:"copied"}}let h=e.payload.size_bytes,y=e.payload.sha256;if(typeof h!=="number"||!Number.isSafeInteger(h)||h<0||h>Ze||typeof y!=="string"||!/^[a-f0-9]{64}$/.test(y))return ve("transfer_receipt_invalid");let S;try{S=c.open(p.fd,p.leaf,He.O_RDONLY|He.O_NOFOLLOW|He.O_NONBLOCK)}catch(R){if(Hr(R)!=="ENOENT")throw R}if(S!==void 0){try{let R=Ws(S,e.signal);if(R.size_bytes===h&&R.sha256===y)return{...R,outcome:"already_present"}}finally{Ur(S)}return ve("transfer_destination_exists")}f=`.reason-copy-${Rc()}`,m=c.open(p.fd,f,He.O_CREAT|He.O_EXCL|He.O_WRONLY|He.O_NOFOLLOW,384),c.inherit(p.fd,m);let w;try{let R=await(e.fetchImpl??fetch)(l,{redirect:"error",signal:e.signal});if(!R.ok||!R.body)return ve("transfer_download_failed");w=R.body.getReader()}catch(R){return Fr(R,e.signal,"transfer_download_failed")}let _=Hn("sha256"),v=0;try{while(!0){e.signal.throwIfAborted();let R=await w.read().catch((C)=>Fr(C,e.signal,"transfer_download_failed"));if(R.done)break;if(v+=R.value.length,v>h)return ve("transfer_size_mismatch");_.update(R.value);for(let C=0;C<R.value.length;)e.signal.throwIfAborted(),C+=Cc(m,R.value,C,Math.min(jn,R.value.length-C))}}finally{await w.cancel().catch(()=>{})}if(v!==h||_.digest("hex")!==y)return ve("transfer_hash_mismatch");return Ec(m),await e.beforeCommit?.(),e.signal.throwIfAborted(),c.link(p.fd,f,p.leaf),{size_bytes:h,sha256:y,outcome:"copied"}}finally{try{if(m!==void 0)Ur(m)}finally{try{if(p){if(f)try{c.unlink(p.fd,f)}catch{}c.closeDirectory(p.fd)}}finally{c.close()}}}}catch(l){return kc(l,e.signal,e.direction)}}import{spawn as Bc}from"child_process";import{mkdtempSync as Fc,rmSync as Uc,writeFileSync as Hc}from"fs";import{constants as jc,platform as qc,tmpdir as Wc}from"os";import{join as Ks}from"path";import{gunzipSync as $c,gzipSync as Jm}from"zlib";var Gs=900000,Qm=Gs+60000,tr=49152,zs=(e)=>t().min(1).max(e).regex(/^[A-Za-z0-9+/]+=*$/),Ys=n({version:i(1),script_gzip:zs(163840),stdin_gzip:zs(65536),cwd:t().min(1).max(4096).startsWith("/"),env:ee(t().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),t().max(4096)).refine((e)=>Object.keys(e).length<=16,"too many variables"),timeout_ms:o().int().min(1000).max(Gs)}).strict(),qn=t().max(tr+256),ef=n({exit_code:o().int().min(0).max(255),stdout:qn,stderr:qn,combined:qn.optional()}).strict();function Wn(e){return $c(Buffer.from(e,"base64")).toString("utf8")}var Vc="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",zc=["RUSTUP_HOME","TZ","LC_ALL"],Gc=2000,Yc=100;function zn(){return qc()==="linux"&&process.geteuid?.()===0}function Vn(e){let l=Math.floor(e/2),c=[],p=0,m=Buffer.alloc(0),f=0;return{push(h){f+=h.length;let y=h;if(p<l){let S=y.subarray(0,l-p);c.push(S),p+=S.length,y=y.subarray(S.length)}if(y.length)m=Buffer.concat([m,y]).subarray(-l)},text(){let h=f-p-m.length;return Buffer.concat(c).toString("utf8")+(h>0?`
|
|
35
|
-
[reason: ${h} bytes of output omitted]
|
|
36
|
-
`:"")+m.toString("utf8")}}}async function Xs(e,l){if(!zn())throw new r("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let c=Ys.safeParse(e);if(!c.success)throw new r("invalid_request","Reason sent an invalid workspace setup.");let p=c.data,m,f;try{m=Wn(p.script_gzip),f=Wn(p.stdin_gzip)}catch{throw new r("invalid_request","Reason sent an unreadable workspace setup.")}l.throwIfAborted();let h=Fc(Ks(Wc(),"reason-workspace-setup-"));try{let y=Ks(h,"setup.sh");Hc(y,m,{mode:384});let S={PATH:Vc,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let V of zc)if(process.env[V])S[V]=process.env[V];Object.assign(S,p.env);let w=Bc("/bin/bash",[y],{cwd:p.cwd,env:S,detached:!0,stdio:["pipe","pipe","pipe"]}),_=Vn(tr),v=Vn(tr),R=Vn(tr);w.stdout.on("data",(V)=>{_.push(V),R.push(V)}),w.stderr.on("data",(V)=>{v.push(V),R.push(V)}),w.stdin.on("error",()=>{}),w.stdin.end(f);let C=(V)=>{try{if(w.pid)process.kill(-w.pid,V)}catch{}},A=!1,F,L=()=>{C("SIGTERM"),F??=setTimeout(()=>C("SIGKILL"),Gc)},M=setTimeout(()=>{A=!0,L()},p.timeout_ms);l.addEventListener("abort",L,{once:!0});let B=await new Promise((V,se)=>{w.once("error",()=>se(new r("workspace_setup_start_failed","The workspace setup did not start."))),w.once("exit",(we,Ce)=>V({code:we,signal:Ce}))}).finally(()=>{clearTimeout(M),clearTimeout(F),l.removeEventListener("abort",L)});await new Promise((V)=>{let se=setTimeout(V,Yc);w.once("close",()=>{clearTimeout(se),V()})}),w.stdout.destroy(),w.stderr.destroy(),l.throwIfAborted();let U=A?124:B.signal?128+(jc.signals[B.signal]??0):B.code??1;return{exit_code:Math.min(255,U),stdout:_.text(),stderr:v.text(),...U!==0?{combined:R.text()}:{}}}finally{Uc(h,{recursive:!0,force:!0})}}import{chmodSync as Kc,mkdtempSync as Xc,realpathSync as Js,rmSync as Jc}from"fs";import{tmpdir as Zc}from"os";import{dirname as Qc,join as Gn,sep as eu}from"path";function Yn(e){return kr(e,Sr(e)!==null).repoPath}function Zs(e,l){let c;try{if(typeof l!=="string")throw Error("invalid");c=[X,void 0].map((m)=>Qc(I({kind:"managed",workspaceId:l,...m?{layout:m}:{}})))}catch{throw new r("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let p;for(let m of c)try{p=Js(Gn(e,m));break}catch{}if(p===void 0)throw new r("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!p.startsWith(`${e}${eu}`))throw new r("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return p}async function Qs(e){e.signal.throwIfAborted();let l=e.source;if(l.kind==="workspace"){let p=Yn(e.runtimeRoot);if(E(p)||E(Gn(p,l.path)))throw new r("protected_path","Credential and secret paths are unavailable to local tasks.");return yt({direction:"export",root:p,path:l.path,payload:{url:e.url},signal:e.signal,fetchImpl:e.fetchImpl})}let c=Xc(Gn(Zc(),`reason-cloud-copy-${process.pid}-`));try{Kc(c,448);let p=Js(c);await yt({direction:"import",root:p,path:"source",payload:{url:l.download_url,size_bytes:l.size_bytes,sha256:l.sha256},signal:e.signal,fetchImpl:e.fetchImpl});let m=await yt({direction:"export",root:p,path:"source",payload:{url:e.url},signal:e.signal,fetchImpl:e.fetchImpl});if(m.size_bytes!==l.size_bytes||m.sha256!==l.sha256)throw new r("transfer_source_changed","The verified attachment changed before export.");return m}finally{Jc(c,{recursive:!0,force:!0})}}import{constants as Ve}from"fs";import{closeSync as Sl,existsSync as Xe,fstatSync as vl,ftruncateSync as yp,lstatSync as Ii,mkdirSync as bp,mkdtempSync as wp,openSync as Rl,readSync as Sp,realpathSync as Ye,rmSync as vp,statSync as xr,writeSync as Rp}from"fs";import{homedir as pr,platform as J,tmpdir as xp}from"os";import{dirname as gr,isAbsolute as Ep,join as xl,relative as Mi,resolve as Cp,sep as Pp}from"path";import{spawn as Op}from"child_process";var Sf=nn+15000;var ea=["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"];var ru=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),rr=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 jr(e,l){if(ru.has(e))return!1;if(rr.has(e)&&!l.runtimeDirectory)return!1;if((e==="inference.custom.v1"||e==="preview.serve.v1"||e==="simulator.call.v1"||e==="simulator.stream.v1")&&(l.executionMode!=="unsandboxed"||!l.runtimeDirectory))return!1;if(l.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes(e)||rr.has(e)))return!1;return!0}import{accessSync as nu,constants as ou,existsSync as iu,statSync as su}from"fs";import{basename as au,isAbsolute as lu}from"path";var nr=["-lic"],ta="/bin/zsh",cu=new Set(["zsh","bash"]),ra=20000,Kn=60000,uu=65536,du=64,pu=8192,mu=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),fu=["DYLD_","LD_"];function hu(e){let l=e.toUpperCase();return mu.has(l)||fu.some((c)=>l.startsWith(c))}function na(e=process.env){return!0}function gu(e){if(!lu(e)||e.includes("\x00"))return!1;if(!cu.has(au(e)))return!1;try{if(!su(e).isFile())return!1;return nu(e,ou.X_OK),!0}catch{return!1}}function bt(e=process.env){if(process.platform==="win32")return fe()??ta;let l=e.SHELL?.trim();if(l&&gu(l))return l;return ta}function Xn(e=process.env){return na(e)&&iu(bt(e))}function Jn(e=process.env){if(!na(e))throw new r("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function Zn(e){if(typeof e!=="string"||e.length===0||e.includes("\x00")||Buffer.byteLength(e,"utf8")>uu)throw new r("invalid_payload","command is missing or too large.");return e}function Qn(e){if(e===void 0||e===null)return{forwarded:{},ignored:[]};if(typeof e!=="object"||Array.isArray(e))throw new r("invalid_payload","env must be an object of strings.");let l=Object.entries(e);if(l.length>du)throw new r("invalid_payload","env has too many entries.");let c={},p=[];for(let[m,f]of l){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m)||typeof f!=="string"||f.includes("\x00")||Buffer.byteLength(f,"utf8")>pu)throw new r("invalid_payload","env entry is invalid or too large.");if(hu(m)){p.push(m);continue}c[m]=f}return{forwarded:c,ignored:p}}async function oa(e){let l=e.processEnv??process.env;if(Jn(l),e.signal.aborted)throw new r("cancelled","Operation was cancelled.");let c=Zn(e.command),p=bt(l),{forwarded:m,ignored:f}=Qn(e.requestEnv),h=await e.spawn(p,[...nr,c],{cwd:e.cwd,timeoutMs:e.timeoutMs,signal:e.signal,env:{...l,...m}});return{exit_code:h.exitCode,signal:h.signal,stdout:h.stdout,stderr:h.stderr,timed_out:h.timedOut,truncated:h.truncated,shell:p,shell_flags:[...nr],login:!0,interactive:!0,sandbox:"none",ignored_env:f}}function ia(e=process.env){return{transport:"shell",shell:`${bt(e)} ${nr.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:Kn}}import{readFile as _u,readdir as yu,readlink as bu,realpath as wu}from"fs/promises";import{basename as Su,relative as vu,sep as Ru}from"path";var ut="/proc",xu=250,sa=500,Eu=50,Cu=250,Pu=1024,aa=4096,Ou=1,Iu=3,la=9,Au="0A",Lu=/^socket:\[(\d+)\]$/,co={readDirectory:(e)=>yu(e),readLink:(e)=>bu(e),readTextFile:(e)=>_u(e,"utf8"),realPath:(e)=>wu(e)};function ua(e,l){return l===e||l.startsWith(`${e}${Ru}`)}function ku(e,l){return vu(e,l)||"."}async function da(e){let l;try{l=await e.readDirectory(ut)}catch{return[]}return l.filter((c)=>/^[0-9]+$/.test(c)).map((c)=>Number(c)).filter((c)=>Number.isSafeInteger(c)&&c>0).sort((c,p)=>c-p)}async function pa(e,l){try{let p=(await l.readTextFile(`${ut}/${e}/comm`)).slice(0,aa).split(`
|
|
37
|
-
`,1)[0]?.trim();if(p)return p}catch{}try{let p=(await l.readTextFile(`${ut}/${e}/cmdline`)).slice(0,aa).split("\x00",1)[0]?.trim();return p?Su(p):null}catch{return null}}async function ma(e,l=co){let c;try{c=await l.readLink(`${ut}/${e}/cwd`)}catch{return null}if(!c)return null;try{return await l.realPath(c)}catch{return null}}async function fa(e,l=co){let c=[];for(let p of await da(l)){if(c.length>=xu)break;let m=await ma(p,l);if(!m||!ua(e,m))continue;c.push({pid:p,command:await pa(p,l),cwd:ku(e,m)})}return{processes:c}}function ca(e){let l=[];for(let c=0;c<8;c+=2)l.unshift(Number.parseInt(e.slice(c,c+2),16));return l}function Tu(e){let l=[];for(let S=0;S<16;S+=2)l.push(e[S]<<8|e[S+1]);if(l.slice(0,5).every((S)=>S===0)&&l[5]===65535)return`::ffff:${e.slice(12).join(".")}`;let c=-1,p=0,m=-1;for(let S=0;S<=l.length;S+=1){if(S<l.length&&l[S]===0){if(m<0)m=S;continue}if(m>=0){let w=S-m;if(w>p)c=m,p=w;m=-1}}let f=l.map((S)=>S.toString(16));if(p<2)return f.join(":");let h=f.slice(0,c).join(":"),y=f.slice(c+p).join(":");return`${h}::${y}`}function Du(e,l){if(/^[0-9A-Fa-f]{8}$/.test(e)){let c=ca(e);if(c.every((p)=>p===0))return`*:${l}`;return`${c.join(".")}:${l}`}if(/^[0-9A-Fa-f]{32}$/.test(e)){let c=[];for(let p=0;p<4;p+=1)c.push(...ca(e.slice(p*8,p*8+8)));if(c.every((p)=>p===0))return`*:${l}`;return`[${Tu(c)}]:${l}`}return null}function Nu(e,l){let c=[];for(let p of e.split(`
|
|
38
|
-
`).slice(1)){if(c.length>=l)break;let m=p.trim().split(/\s+/);if(m.length<=la)continue;if(m[Iu]?.toUpperCase()!==Au)continue;let f=m[Ou]??"",h=f.lastIndexOf(":");if(h<0)continue;let y=Number.parseInt(f.slice(h+1),16);if(!Number.isInteger(y)||y<=0||y>65535)continue;let S=Du(f.slice(0,h),y),w=m[la];if(!S||!w||!/^[0-9]+$/.test(w))continue;c.push({inode:w,port:y,address:S})}return c}async function Mu(e){let l=[];for(let c of["tcp","tcp6"]){if(l.length>=sa)break;let p;try{p=await e.readTextFile(`${ut}/net/${c}`)}catch{continue}l.push(...Nu(p,sa-l.length))}return l}async function $u(e,l){let c=new Map;if(e.size===0)return c;for(let p of await da(l)){if(c.size>=e.size)break;let m;try{m=await l.readDirectory(`${ut}/${p}/fd`)}catch{continue}for(let f of m.slice(0,Pu)){let h;try{h=await l.readLink(`${ut}/${p}/fd/${f}`)}catch{continue}let y=h.match(Lu)?.[1];if(!y||!e.has(y)||c.has(y))continue;c.set(y,p)}}return c}async function ha(e,l=co){let c=await Mu(l),p=await $u(new Set(c.map((_)=>_.inode)),l),m=[];for(let _ of c){let v=p.get(_.inode);if(v===void 0)continue;m.push({pid:v,port:_.port,address:_.address})}m.sort((_,v)=>_.pid-v.pid||_.port-v.port||(_.address<v.address?-1:_.address>v.address?1:0));let f=[...new Set(m.map((_)=>_.pid))].slice(0,Eu),h=await Promise.all(f.map(async(_)=>[_,await ma(_,l)])),y=new Map(h),S=m.filter((_)=>{let v=y.get(_.pid);return Boolean(v&&ua(e,v))}),w=new Map(await Promise.all([...new Set(S.map((_)=>_.pid))].map(async(_)=>[_,await pa(_,l)])));return{ports:S.slice(0,Cu).map((_)=>({pid:_.pid,command:w.get(_.pid)??null,address:_.address}))}}import{posix as po}from"path";var qr=200,Bu=250,Fu=250;async function Wr(e,l){let c=await e(l);if(c.timedOut||c.truncated||c.exitCode!==0&&c.exitCode!==1)throw new r("process_inspection_failed","Reading this Mac's processes did not complete.");let p=[],m=null;for(let f of c.stdout.split(/\r?\n/))if(f.startsWith("p")){let h=Number(f.slice(1));if(m=Number.isInteger(h)&&h>0?{pid:h,command:null,names:[]}:null,m)p.push(m)}else if(m&&f.startsWith("c"))m.command=f.slice(1)||null;else if(m&&f.startsWith("n"))m.names.push(f.slice(1));return p}function uo(e,l){return l===e||l.startsWith(e==="/"?e:`${e}/`)}var ga="/System/Volumes/Data",Uu=["/tmp","/var","/etc"];function mo(e){let l=po.normalize(e);if(l.startsWith(`${ga}/`))l=l.slice(ga.length);return Uu.find((p)=>l===p||l.startsWith(`${p}/`))?`/private${l}`:l}function _a(e){return e&&po.isAbsolute(e)?mo(e):null}async function ya(e,l){let c=new Map;for(let p=0;p<l.length;p+=qr){let m=l.slice(p,p+qr).join(",");for(let f of await Wr(e,["-a","-p",m,"-d","cwd","-Fpcn"]))c.set(f.pid,{command:f.command,cwd:_a(f.names[0])})}return c}async function ba(e,l){let c=mo(e),p=(await Wr(l,["-d","cwd","-Fpn"])).filter((f)=>{let h=_a(f.names[0]);return h!==null&&uo(c,h)}).map((f)=>f.pid).slice(0,Bu),m=await ya(l,p);return{processes:p.flatMap((f)=>{let h=m.get(f);return h?.cwd&&uo(c,h.cwd)?[{pid:f,command:h.command,cwd:po.relative(c,h.cwd)||"."}]:[]})}}async function wa(e,l){let c=mo(e),p=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],m=await Wr(l,p),f=await ya(l,m.map((w)=>w.pid)),h=m.map((w)=>w.pid).filter((w)=>{let _=f.get(w)?.cwd;return Boolean(_&&uo(c,_))});if(h.length===0)return{ports:[]};let y=new Set(m.flatMap((w)=>w.names.map((_)=>`${w.pid} ${_}`))),S=[];for(let w=0;w<h.length;w+=qr){let _=h.slice(w,w+qr).join(",");for(let v of await Wr(l,["-a","-p",_,...p]))for(let R of v.names)if(y.has(`${v.pid} ${R}`))S.push({pid:v.pid,command:v.command,address:R})}return{ports:S.slice(0,Fu)}}import{join as Zu}from"path";import{spawn as zu}from"child_process";import{randomUUID as Gu}from"crypto";import{chmodSync as Ra,lstatSync as xa,mkdirSync as Yu,readdirSync as Ku,statSync as Xu,unlinkSync as Ju}from"fs";import{join as _o}from"path";var go={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var Vr=(e,l=0,c=1e6)=>typeof e==="number"&&Number.isFinite(e)&&e>=l&&e<=c;var dt=()=>{throw Error("proof_visual_contract_invalid")};class Sa extends Error{constructor(){super("proof_visual_contract_invalid")}}function fn(e){if(!be(e)||e.version!==1)return dt();if(typeof e.route!=="string"||!e.route.startsWith("/")||e.route.length>512||/[\x00-\x20\x7f\\?#%]/.test(e.route)||e.route.startsWith("//"))throw new Sa;if(!be(e.viewport)||!Vr(e.viewport.width,1,4096)||!Vr(e.viewport.height,1,4096)||!Array.isArray(e.targets)||e.targets.length<1||e.targets.length>go.targets||Object.keys(e).some((p)=>!["version","route","viewport","targets","additionalViewports"].includes(p)))return dt();let l=e.targets.map((p)=>{if(!be(p)||typeof p.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(p.id)||typeof p.selector!=="string"||!p.selector.trim()||p.selector.length>256||/[\x00-\x1f\x7f]/.test(p.selector)||Object.keys(p).some((m)=>!["id","selector"].includes(m)))return dt();return{id:p.id,selector:p.selector}});if(new Set(l.map((p)=>p.id)).size!==l.length)return dt();let c;if(e.additionalViewports!==void 0){if(!Array.isArray(e.additionalViewports)||e.additionalViewports.length<1||e.additionalViewports.length>3)return dt();c=e.additionalViewports.map((m)=>{if(!be(m)||!Vr(m.width,1,4096)||!Number.isInteger(m.width)||!Vr(m.height,1,4096)||!Number.isInteger(m.height)||Object.keys(m).some((f)=>!["width","height"].includes(f)))return dt();return{width:m.width,height:m.height}});let p=[e.viewport,...c].map((m)=>`${m.width}x${m.height}`);if(new Set(p).size!==p.length)return dt()}return{version:1,route:e.route,viewport:{width:e.viewport.width,height:e.viewport.height},targets:l,...c?{additionalViewports:c}:{}}}var qu=["organizationId","userId","sessionId","runId"],Wu=[...qu,"prUrl","headSha","skillDigest","evidenceKind"],dh=[...Wu,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var Vu={"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 va(e){return Vu[e].directory}var Ea=10485760;function Ca(e={}){let l=e.directory??va("video/webm"),c=null;return{async start(p){if(c)throw Error("cloud_browser_recording_active");let m=p?.seconds;if(!Number.isInteger(m)||Number(m)<1||Number(m)>15||!p||Object.keys(p).some((L)=>L!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");Yu(l,{recursive:!0,mode:457});let f=xa(l);if(!f.isDirectory()||f.isSymbolicLink()||f.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");Ra(l,457);let h=Ku(l).filter((L)=>/^[a-f0-9-]{36}\.webm$/.test(L)).map((L)=>({name:L,time:Xu(_o(l,L)).mtimeMs})).sort((L,M)=>M.time-L.time);for(let L of h.slice(9))Ju(_o(l,L.name));let y=_o(l,`${Gu()}.webm`),S=["-f","x11grab","-framerate","12","-i",e.display??":99"],w=(e.spawn??zu)(e.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...S,"-t",String(m),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(Ea),"-progress","pipe:1",y],{stdio:["ignore","pipe","ignore"],...e.env?{env:e.env}:{}}),_,v,R=!1,C=new Promise((L,M)=>{_=L,v=M});w.stdout.on("data",(L)=>{if(/frame=\s*[1-9]/.test(String(L)))R=!0,_()});let A=new Promise((L,M)=>{w.once("error",()=>{v(Error("cloud_browser_recording_unavailable")),M(Error("cloud_browser_recording_unavailable"))}),w.once("exit",(B)=>{try{if(B!==0&&B!==255)throw Error();let U=xa(y);if(!R||!U.isFile()||U.isSymbolicLink()||U.uid!==process.getuid?.()||U.size<128||U.size>Ea+65536)throw Error();Ra(y,420),_(),L({path:y,mimeType:"video/webm"})}catch{v(Error("cloud_browser_recording_failed")),M(Error("cloud_browser_recording_failed"))}})});A.catch(()=>{});let F=setTimeout(()=>w.kill("SIGKILL"),(Number(m)+5)*1000);A.finally(()=>clearTimeout(F)).catch(()=>{}),c={done:A,stop:()=>(w.kill("SIGINT"),A)};try{await C}catch(L){throw c=null,L}return{recording:!0,seconds:Number(m)}},async stop(){if(!c)throw Error("cloud_browser_recording_not_started");let p=c;return c=null,p.stop()},async close(){if(c)await this.stop().catch(()=>{})}}}function Pa(e,l={}){if(e.executionMode!=="unsandboxed"||!e.runtimeDirectory||(l.platform??process.platform)!=="linux")return null;let c=(l.components??x)(),p=c?.features.display?c.ffmpeg:null;if(!p)return null;let m=Zu(e.runtimeDirectory,"recordings"),f=null;return{async start(h){let y=await(l.desktop??qe)();return f??=Ca({directory:m,display:y.display,ffmpeg:p,env:{HOME:a(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:y.xauthority},...l.spawn?{spawn:l.spawn}:{}}),f.start(h)},async stop(){if(!f)throw Error("cloud_browser_recording_not_started");return f.stop()},async close(){await f?.close()}}}import{spawn as Xo}from"child_process";import{createHash as yd,randomUUID as bd}from"crypto";import{existsSync as We,mkdirSync as qo,mkdtempSync as Qo,readdirSync as en,readFileSync as ei,renameSync as wd,rmSync as ar,statSync as Xr,writeFileSync as Sd}from"fs";import{homedir as ti,tmpdir as Ya}from"os";import{basename as Ka,dirname as Wo,join as Q,relative as Xa,resolve as Vo,sep as Ja}from"path";var Ie=t().min(1).max(200),je=o().finite().min(0).max(1e4),zr=t().min(1).max(4096).refine((e)=>!e.includes("\x00")),Oa=t().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),bo=n({id:t().min(1).max(500).optional(),label:t().min(1).max(500).optional()}).strict(),wo=["home","lock","side_button","siri","apple_pay"],Qu=s(["tree","screenshot","both","none"]),ed=n({...bo.shape,gone:d().optional()}).strict().refine((e)=>Boolean(e.id||e.label),"wait_for needs an id or label"),rt={observe:Qu.optional(),wait_for:ed.optional(),timeout:o().min(0).max(20).optional()},yo=g("action",[n({action:i("tap"),x:je.optional(),y:je.optional(),...bo.shape,duration:o().min(0).max(10).optional()}).strict().refine((e)=>e.x!==void 0&&e.y!==void 0||Boolean(e.id||e.label),"pass x and y, or an id or label"),n({action:i("swipe"),x:je,y:je,x2:je,y2:je,duration:o().min(0.05).max(5).optional()}).strict(),n({action:i("type"),text:t().min(1).max(4000)}).strict(),n({action:i("button"),name:s(wo)}).strict(),n({action:i("sleep"),seconds:o().min(0).max(10)}).strict()]),Oo=g("action",[n({action:i("devices")}).strict(),n({action:i("boot"),device:Ie}).strict(),n({action:i("shutdown"),device:Ie}).strict(),n({action:i("build"),path:zr.optional(),scheme:t().min(1).max(200).optional(),configuration:t().min(1).max(100).optional(),device:Ie.optional(),wait:d().optional()}).strict(),n({action:i("run"),path:zr.optional(),scheme:t().min(1).max(200).optional(),configuration:t().min(1).max(100).optional(),device:Ie.optional(),steps:u(Zo(()=>yo)).max(30).optional(),...rt}).strict(),n({action:i("build_status"),build_id:t().regex(/^build-[0-9a-z-]{4,64}$/),device:Ie.optional(),wait:d().optional()}).strict(),n({action:i("launch"),device:Ie.optional(),app_path:zr.optional(),bundle_id:Oa.optional(),steps:u(Zo(()=>yo)).max(30).optional(),...rt}).strict().refine((e)=>Boolean(e.app_path)!==Boolean(e.bundle_id),"pass exactly one of app_path or bundle_id"),n({action:i("terminate"),device:Ie.optional(),bundle_id:Oa}).strict(),n({action:i("logs"),device:Ie.optional(),after:o().int().min(0).optional()}).strict(),n({action:i("screenshot"),device:Ie.optional(),scale:W([i(1),i(2)]).optional(),save_path:zr.optional()}).strict(),n({action:i("chrome"),device:Ie.optional()}).strict(),n({action:i("inspect"),device:Ie.optional()}).strict(),n({action:i("tap"),device:Ie.optional(),x:je.optional(),y:je.optional(),...bo.shape,duration:o().min(0).max(10).optional(),...rt}).strict().refine((e)=>e.x!==void 0&&e.y!==void 0||Boolean(e.id||e.label),"pass x and y, or an id or label"),n({action:i("swipe"),device:Ie.optional(),x:je,y:je,x2:je,y2:je,duration:o().min(0.05).max(5).optional(),...rt}).strict(),n({action:i("type"),device:Ie.optional(),text:t().min(1).max(4000),...rt}).strict(),n({action:i("button"),device:Ie.optional(),name:s(wo),...rt}).strict(),n({action:i("open_url"),device:Ie.optional(),url:t().min(1).max(4000),...rt}).strict(),n({action:i("steps"),device:Ie.optional(),steps:u(yo).min(1).max(30),...rt}).strict(),n({action:i("appearance"),device:Ie.optional(),mode:s(["light","dark"])}).strict()]),Ia=n({udid:t(),name:t(),runtime:t(),state:s(["booted","shutdown","booting","shutting_down"]),kind:s(["iphone","ipad","other"])}).strict(),Ah=n({text:t(),error:t().optional(),device:Ia.optional(),devices:u(Ia).optional(),image:n({mime:i("image/jpeg"),data:t(),width:o(),height:o()}).strict().optional(),build:n({id:t(),status:s(["running","succeeded","failed"]),app_path:t().optional(),bundle_id:t().optional(),errors:u(t()),log_tail:t(),elapsed_ms:o()}).strict().optional(),logs:n({lines:u(t()),next:o()}).strict().optional(),screen:t().optional(),chrome:n({identifier:t(),screen:n({width:o(),height:o()}).strict(),inset:n({top:o(),left:o(),bottom:o(),right:o()}).strict(),padding:n({top:o(),left:o(),bottom:o(),right:o()}).strict(),screen_mask:t().optional(),pieces:ee(s(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),n({image:t(),width:o(),height:o()}).strict()),buttons:u(n({name:t(),image:t(),x:o(),y:o(),width:o(),height:o()}).strict())}).strict().optional()}).strict();var Lh=n({device_id:k().optional(),root_id:k().optional()}),Gr={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:[...wo],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."}},La=Oo.options.map((e)=>e.shape).filter((e)=>e.action.value!=="chrome"),td={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},Aa=new Set;function rd(e,l){let{description:c,...p}=e==="steps"&&l==="steps"?{...Gr.steps,minItems:1}:Gr[e];if(c===void 0||Aa.has(e))return p;return Aa.add(e),{...p,description:c}}var nd=La.flatMap((e)=>{let l=e.action.value,c=Object.keys(e).filter((m)=>Object.hasOwn(Gr,m)),p=c.filter((m)=>!e[m].safeParse(void 0).success);return(td[l]??[{required:[]}]).map((m)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:l}],...["device_id","root_id",...c].filter((f)=>!m.without?.includes(f)).map((f)=>[f,rd(f,l)])]),required:["action",...p,...m.required],additionalProperties:!1}))}),od={type:"object",properties:{action:{type:"string",enum:La.map((e)=>e.action.value)},...Gr},required:["action"],additionalProperties:!1},kh={...od,anyOf:nd};import{spawn as $o}from"child_process";import{createHash as sd}from"crypto";import{existsSync as No,mkdirSync as Yr,mkdtempSync as ad,readdirSync as ka,readFileSync as Ta,renameSync as ld,rmSync as Da,symlinkSync as Mo,writeFileSync as or}from"fs";import{homedir as cd}from"os";import{dirname as Ba,join as ne}from"path";import{createInterface as ud}from"readline";var Lo=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
39
|
-
//
|
|
40
|
-
// Built on the Mac on first use (cli/simulator-host.ts) against the MIT
|
|
41
|
-
// FBSimulatorControl frameworks that the pinned AXe ships, so loading
|
|
42
|
-
// SimulatorKit and connecting to the simulator happen once per process
|
|
43
|
-
// instead of once per action (about a second each, three under load).
|
|
44
|
-
//
|
|
45
|
-
// simulator-host serve <udid>
|
|
46
|
-
// Newline JSON requests on stdin, one newline JSON reply each on stdout,
|
|
47
|
-
// in order: {"id":1,"op":"tap","x":100,"y":200} -> {"id":1,"ok":true}.
|
|
48
|
-
// Ops: touch (phase down|move|up), tap, swipe, button, text, key, tree.
|
|
49
|
-
// Coordinates are device points. \`tree\` answers AXe describe-ui's JSON.
|
|
50
|
-
// simulator-host stream <udid> <fps> <max pixels> <kbps>
|
|
51
|
-
// H.264 (Main, level 4.2) as Annex-B on stdout, encoded with VideoToolbox
|
|
52
|
-
// straight from the simulator's framebuffer. Every keyframe carries
|
|
53
|
-
// SPS/PPS, and every access unit is followed by an AUD, so a reader that
|
|
54
|
-
// splits at AUDs has each frame as soon as it is written.
|
|
55
|
-
//
|
|
56
|
-
// Both modes exit when stdin closes, so they never outlive the worker.
|
|
57
|
-
|
|
58
|
-
import CoreMedia
|
|
59
|
-
import CoreVideo
|
|
60
|
-
import Darwin
|
|
61
|
-
import FBControlCore
|
|
62
|
-
import FBSimulatorControl
|
|
63
|
-
import Foundation
|
|
64
|
-
import IOSurface
|
|
65
|
-
import VideoToolbox
|
|
66
|
-
|
|
67
|
-
@objc final class SilentReporter: NSObject, FBEventReporter {
|
|
68
|
-
var metadata: [String: String] = [:]
|
|
69
|
-
func report(_ subject: FBEventReporterSubject) {}
|
|
70
|
-
func addMetadata(_ metadata: [String: String]) {}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
let logger: FBControlCoreLogger = FBControlCoreLoggerFactory.systemLoggerWriting(toStderr: false, withDebugLogging: false)
|
|
74
|
-
|
|
75
|
-
func fail(_ message: String) -> Never {
|
|
76
|
-
FileHandle.standardError.write(Data((message + "\\n").utf8))
|
|
77
|
-
exit(1)
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/// Writes all of \`data\` to stdout; a closed reader ends the process.
|
|
81
|
-
func writeOut(_ data: Data) {
|
|
82
|
-
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
|
|
83
|
-
var offset = 0
|
|
84
|
-
while offset < buffer.count {
|
|
85
|
-
let written = Darwin.write(1, buffer.baseAddress!.advanced(by: offset), buffer.count - offset)
|
|
86
|
-
if written <= 0 {
|
|
87
|
-
if written < 0 && errno == EINTR { continue }
|
|
88
|
-
exit(0)
|
|
89
|
-
}
|
|
90
|
-
offset += written
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
@MainActor
|
|
96
|
-
func simulator(_ udid: String) async throws -> FBSimulator {
|
|
97
|
-
try FBSimulatorControlFrameworkLoader.essentialFrameworks.loadPrivateFrameworks(logger)
|
|
98
|
-
try FBSimulatorControlFrameworkLoader.xcodeFrameworks.loadPrivateFrameworks(logger)
|
|
99
|
-
FBControlCoreGlobalConfiguration.defaultLogger = logger
|
|
100
|
-
let configuration = FBSimulatorControlConfiguration(deviceSetPath: nil, logger: logger, reporter: SilentReporter())
|
|
101
|
-
let set = try FBSimulatorControl.withConfiguration(configuration).set
|
|
102
|
-
guard let target = set.allSimulators.first(where: { $0.udid == udid }) else { fail("simulator_not_found") }
|
|
103
|
-
guard target.state == .booted else { fail("simulator_not_booted") }
|
|
104
|
-
return target
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// MARK: - serve
|
|
108
|
-
|
|
109
|
-
/// US keyboard: character -> (HID usage, shift).
|
|
110
|
-
let keyboard: [Character: (UInt32, Bool)] = {
|
|
111
|
-
var map: [Character: (UInt32, Bool)] = [:]
|
|
112
|
-
for (index, letter) in "abcdefghijklmnopqrstuvwxyz".enumerated() {
|
|
113
|
-
map[letter] = (UInt32(4 + index), false)
|
|
114
|
-
map[Character(letter.uppercased())] = (UInt32(4 + index), true)
|
|
115
|
-
}
|
|
116
|
-
for (index, digit) in "1234567890".enumerated() { map[digit] = (UInt32(30 + index), false) }
|
|
117
|
-
for (index, symbol) in "!@#$%^&*()".enumerated() { map[symbol] = (UInt32(30 + index), true) }
|
|
118
|
-
let plain: [(Character, UInt32)] = [("\\n", 40), ("\\t", 43), (" ", 44), ("-", 45), ("=", 46), ("[", 47), ("]", 48),
|
|
119
|
-
("\\\\", 49), (";", 51), ("'", 52), ("\`", 53), (",", 54), (".", 55), ("/", 56)]
|
|
120
|
-
let shifted: [(Character, UInt32)] = [("_", 45), ("+", 46), ("{", 47), ("}", 48), ("|", 49), (":", 51), ("\\"", 52),
|
|
121
|
-
("~", 53), ("<", 54), (">", 55), ("?", 56)]
|
|
122
|
-
for (character, usage) in plain { map[character] = (usage, false) }
|
|
123
|
-
for (character, usage) in shifted { map[character] = (usage, true) }
|
|
124
|
-
return map
|
|
125
|
-
}()
|
|
126
|
-
|
|
127
|
-
let buttons: [String: FBSimulatorHIDButton] = [
|
|
128
|
-
"home": .homeButton, "lock": .lock, "side_button": .sideButton, "siri": .siri, "apple_pay": .applePay,
|
|
129
|
-
]
|
|
130
|
-
|
|
131
|
-
/// AXe describe-ui's keys (its schema), so the worker parses one format either way.
|
|
132
|
-
let treeKeys: Set<FBAXKeys> = [.label, .frame, .value, .uniqueID, .type, .title, .frameDict, .help, .enabled,
|
|
133
|
-
.customActions, .role, .roleDescription, .subrole, .contentRequired, .pid]
|
|
134
|
-
|
|
135
|
-
func withTraits(_ value: Any) -> Any {
|
|
136
|
-
if let list = value as? [Any] { return list.map(withTraits) }
|
|
137
|
-
guard var element = value as? [String: Any] else { return value }
|
|
138
|
-
for (key, child) in element { element[key] = withTraits(child) }
|
|
139
|
-
if element["type"] != nil && element["traits"] == nil { element["traits"] = [String]() }
|
|
140
|
-
return element
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
func hasChildren(_ value: Any) -> Bool {
|
|
144
|
-
let roots = (value as? [[String: Any]]) ?? ((value as? [String: Any]).map { [$0] } ?? [])
|
|
145
|
-
return roots.contains { (($0["children"] as? [Any])?.isEmpty == false) }
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
@MainActor
|
|
149
|
-
func readTree(_ target: FBSimulator) async throws -> String {
|
|
150
|
-
var latest: Any = []
|
|
151
|
-
for attempt in 0..<4 {
|
|
152
|
-
let element = try await target.accessibilityElementForFrontmostApplication()
|
|
153
|
-
defer { element.close() }
|
|
154
|
-
let response = try element.serialize(with: FBAccessibilityRequestOptions(nestedFormat: true, keys: treeKeys))
|
|
155
|
-
latest = withTraits(response.elements)
|
|
156
|
-
if hasChildren(latest) { break }
|
|
157
|
-
if attempt < 3 { try await Task.sleep(for: .milliseconds(50 << attempt)) }
|
|
158
|
-
}
|
|
159
|
-
let data = try JSONSerialization.data(withJSONObject: latest)
|
|
160
|
-
return String(decoding: data, as: UTF8.self)
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
@MainActor
|
|
164
|
-
func handle(_ request: [String: Any], target: FBSimulator, hid: FBSimulatorHID) async throws -> [String: Any] {
|
|
165
|
-
let number = { (key: String) -> Double in
|
|
166
|
-
guard let value = request[key] as? Double else { throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "missing \\(key)"]) }
|
|
167
|
-
return value
|
|
168
|
-
}
|
|
169
|
-
switch request["op"] as? String {
|
|
170
|
-
case "touch":
|
|
171
|
-
let direction: FBSimulatorHIDDirection = (request["phase"] as? String) == "up" ? .up : .down
|
|
172
|
-
try await hid.send(event: .touch(direction: direction, x: try number("x"), y: try number("y")), logger: logger)
|
|
173
|
-
case "tap":
|
|
174
|
-
let duration = request["duration"] as? Double ?? 0
|
|
175
|
-
let event: FBSimulatorHIDEvent = duration > 0
|
|
176
|
-
? .tapAt(x: try number("x"), y: try number("y"), duration: duration) : .tapAt(x: try number("x"), y: try number("y"))
|
|
177
|
-
try await hid.send(event: event, logger: logger)
|
|
178
|
-
case "swipe":
|
|
179
|
-
try await hid.send(event: .swipe(try number("x"), yStart: try number("y"), xEnd: try number("x2"), yEnd: try number("y2"),
|
|
180
|
-
delta: request["delta"] as? Double ?? 10, duration: request["duration"] as? Double ?? 0.3), logger: logger)
|
|
181
|
-
case "button":
|
|
182
|
-
guard let button = buttons[request["name"] as? String ?? ""] else { throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "unknown button"]) }
|
|
183
|
-
try await hid.send(event: .shortButtonPress(button), logger: logger)
|
|
184
|
-
case "text":
|
|
185
|
-
var events: [FBSimulatorHIDEvent] = []
|
|
186
|
-
for character in request["text"] as? String ?? "" {
|
|
187
|
-
guard let (usage, shift) = keyboard[character] else {
|
|
188
|
-
throw NSError(domain: "simulator-host", code: 2, userInfo: [NSLocalizedDescriptionKey: "unsupported character"])
|
|
189
|
-
}
|
|
190
|
-
if shift { events.append(.keyboard(direction: .down, keyCode: 225)) }
|
|
191
|
-
events.append(.keyboard(direction: .down, keyCode: usage))
|
|
192
|
-
events.append(.keyboard(direction: .up, keyCode: usage))
|
|
193
|
-
if shift { events.append(.keyboard(direction: .up, keyCode: 225)) }
|
|
194
|
-
}
|
|
195
|
-
if !events.isEmpty { try await hid.send(event: .composite(events), logger: logger) }
|
|
196
|
-
case "key":
|
|
197
|
-
let direction: FBSimulatorHIDDirection = (request["down"] as? Bool) == false ? .up : .down
|
|
198
|
-
try await hid.send(event: .keyboard(direction: direction, keyCode: UInt32(try number("usage"))), logger: logger)
|
|
199
|
-
case "tree":
|
|
200
|
-
return ["tree": try await readTree(target)]
|
|
201
|
-
default:
|
|
202
|
-
throw NSError(domain: "simulator-host", code: 1, userInfo: [NSLocalizedDescriptionKey: "unknown op"])
|
|
203
|
-
}
|
|
204
|
-
return [:]
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
@MainActor
|
|
208
|
-
func serve(_ udid: String) async {
|
|
209
|
-
let target: FBSimulator
|
|
210
|
-
let hid: FBSimulatorHID
|
|
211
|
-
do {
|
|
212
|
-
target = try await simulator(udid)
|
|
213
|
-
hid = try await target.connectToHID()
|
|
214
|
-
} catch {
|
|
215
|
-
fail("connect_failed: \\(error.localizedDescription)")
|
|
216
|
-
}
|
|
217
|
-
writeOut(Data("{\\"ready\\":true}\\n".utf8))
|
|
218
|
-
do {
|
|
219
|
-
for try await line in FileHandle.standardInput.bytes.lines {
|
|
220
|
-
guard let request = (try? JSONSerialization.jsonObject(with: Data(line.utf8))) as? [String: Any] else { continue }
|
|
221
|
-
var reply: [String: Any]
|
|
222
|
-
do {
|
|
223
|
-
reply = try await handle(request, target: target, hid: hid)
|
|
224
|
-
reply["ok"] = true
|
|
225
|
-
} catch {
|
|
226
|
-
reply = ["ok": false, "error": error.localizedDescription]
|
|
227
|
-
}
|
|
228
|
-
reply["id"] = request["id"] ?? 0
|
|
229
|
-
var data = (try? JSONSerialization.data(withJSONObject: reply)) ?? Data("{\\"ok\\":false}".utf8)
|
|
230
|
-
data.append(0x0A)
|
|
231
|
-
writeOut(data)
|
|
232
|
-
}
|
|
233
|
-
} catch {}
|
|
234
|
-
exit(0)
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// MARK: - stream
|
|
238
|
-
|
|
239
|
-
let startCode = Data([0, 0, 0, 1])
|
|
240
|
-
let accessUnitDelimiter = Data([0, 0, 0, 1, 0x09, 0xF0])
|
|
241
|
-
|
|
242
|
-
struct BitReader {
|
|
243
|
-
let bytes: [UInt8]
|
|
244
|
-
var position = 0
|
|
245
|
-
mutating func bit() -> UInt32? {
|
|
246
|
-
guard position < bytes.count * 8 else { return nil }
|
|
247
|
-
defer { position += 1 }
|
|
248
|
-
return UInt32(bytes[position >> 3] >> (7 - UInt8(position & 7)) & 1)
|
|
249
|
-
}
|
|
250
|
-
mutating func bits(_ count: Int) -> UInt32? {
|
|
251
|
-
var value: UInt32 = 0
|
|
252
|
-
for _ in 0..<count { guard let next = bit() else { return nil }; value = value << 1 | next }
|
|
253
|
-
return value
|
|
254
|
-
}
|
|
255
|
-
mutating func ue() -> UInt32? {
|
|
256
|
-
var zeros = 0
|
|
257
|
-
while true { guard let next = bit() else { return nil }; if next == 1 { break }; zeros += 1; if zeros > 31 { return nil } }
|
|
258
|
-
guard let rest = bits(zeros) else { return nil }
|
|
259
|
-
return (1 << zeros) - 1 + rest
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
struct BitWriter {
|
|
264
|
-
var bytes: [UInt8] = []
|
|
265
|
-
var count = 0
|
|
266
|
-
mutating func bit(_ value: UInt32) {
|
|
267
|
-
if count & 7 == 0 { bytes.append(0) }
|
|
268
|
-
if value & 1 == 1 { bytes[bytes.count - 1] |= 1 << (7 - UInt8(count & 7)) }
|
|
269
|
-
count += 1
|
|
270
|
-
}
|
|
271
|
-
mutating func bits(_ value: UInt32, _ width: Int) { for shift in stride(from: width - 1, through: 0, by: -1) { bit(value >> UInt32(shift)) } }
|
|
272
|
-
mutating func ue(_ value: UInt32) {
|
|
273
|
-
let coded = value + 1
|
|
274
|
-
let width = 32 - coded.leadingZeroBitCount
|
|
275
|
-
bits(0, width - 1)
|
|
276
|
-
bits(coded, width)
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/// The SPS with a VUI that says frames come out in decode order, one at a time. VideoToolbox writes no
|
|
281
|
-
/// bitstream restriction, so a browser decoder may hold the newest frames back for reordering; on a
|
|
282
|
-
/// screen that stops changing, the last one would never be shown. Any SPS this does not expect is kept.
|
|
283
|
-
func lowDelaySps(_ nal: Data) -> Data {
|
|
284
|
-
var raw: [UInt8] = []
|
|
285
|
-
var zeros = 0
|
|
286
|
-
for byte in nal.dropFirst() {
|
|
287
|
-
if zeros >= 2 && byte == 3 { zeros = 0; continue }
|
|
288
|
-
raw.append(byte)
|
|
289
|
-
zeros = byte == 0 ? zeros + 1 : 0
|
|
290
|
-
}
|
|
291
|
-
var reader = BitReader(bytes: raw)
|
|
292
|
-
var writer = BitWriter()
|
|
293
|
-
func copyBits(_ width: Int) -> UInt32? { guard let value = reader.bits(width) else { return nil }; writer.bits(value, width); return value }
|
|
294
|
-
func copyUe() -> UInt32? { guard let value = reader.ue() else { return nil }; writer.ue(value); return value }
|
|
295
|
-
guard let profile = copyBits(8), copyBits(16) != nil, copyUe() != nil else { return nal }
|
|
296
|
-
if [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135].contains(profile) {
|
|
297
|
-
guard let chroma = copyUe() else { return nal }
|
|
298
|
-
if chroma == 3 { guard copyBits(1) != nil else { return nal } }
|
|
299
|
-
guard copyUe() != nil, copyUe() != nil, copyBits(1) != nil, let scaling = copyBits(1), scaling == 0 else { return nal }
|
|
300
|
-
}
|
|
301
|
-
guard copyUe() != nil, let pocType = copyUe() else { return nal }
|
|
302
|
-
if pocType == 0 { guard copyUe() != nil else { return nal } } else if pocType != 2 { return nal }
|
|
303
|
-
guard let references = copyUe(), copyBits(1) != nil, copyUe() != nil, copyUe() != nil, let frameOnly = copyBits(1) else { return nal }
|
|
304
|
-
if frameOnly == 0 { guard copyBits(1) != nil else { return nal } }
|
|
305
|
-
guard copyBits(1) != nil, let cropping = copyBits(1) else { return nal }
|
|
306
|
-
if cropping == 1 { for _ in 0..<4 { guard copyUe() != nil else { return nal } } }
|
|
307
|
-
guard reader.bits(1) == 0 else { return nal }
|
|
308
|
-
writer.bit(1) // vui_parameters_present_flag
|
|
309
|
-
writer.bits(0, 6) // aspect ratio, overscan, video signal, chroma location, timing, NAL HRD
|
|
310
|
-
writer.bit(0) // VCL HRD
|
|
311
|
-
writer.bit(0) // pic_struct_present_flag
|
|
312
|
-
writer.bit(1) // bitstream_restriction_flag
|
|
313
|
-
writer.bit(1) // motion_vectors_over_pic_boundaries_flag
|
|
314
|
-
writer.ue(2); writer.ue(1); writer.ue(16); writer.ue(16)
|
|
315
|
-
writer.ue(0) // max_num_reorder_frames
|
|
316
|
-
writer.ue(max(1, references)) // max_dec_frame_buffering
|
|
317
|
-
writer.bit(1) // rbsp_stop_one_bit
|
|
318
|
-
while writer.count & 7 != 0 { writer.bit(0) }
|
|
319
|
-
var out = Data([nal.first!])
|
|
320
|
-
zeros = 0
|
|
321
|
-
for byte in writer.bytes {
|
|
322
|
-
if zeros >= 2 && byte <= 3 { out.append(3); zeros = 0 }
|
|
323
|
-
out.append(byte)
|
|
324
|
-
zeros = byte == 0 ? zeros + 1 : 0
|
|
325
|
-
}
|
|
326
|
-
return out
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
final class Encoder: NSObject, FBFramebufferConsumer, @unchecked Sendable {
|
|
330
|
-
let queue = DispatchQueue(label: "simulator-host.encode")
|
|
331
|
-
let fps: Int
|
|
332
|
-
let maxPixels: Double
|
|
333
|
-
let kbps: Int
|
|
334
|
-
var surface: IOSurface?
|
|
335
|
-
var dirty = true
|
|
336
|
-
var forceKey = true
|
|
337
|
-
var session: VTCompressionSession?
|
|
338
|
-
var transfer: VTPixelTransferSession?
|
|
339
|
-
var size = (width: 0, height: 0)
|
|
340
|
-
var frames: Int64 = 0
|
|
341
|
-
|
|
342
|
-
init(fps: Int, maxPixels: Double, kbps: Int) {
|
|
343
|
-
self.fps = fps
|
|
344
|
-
self.maxPixels = maxPixels
|
|
345
|
-
self.kbps = kbps
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
func didChange(_ surface: IOSurface?) {
|
|
349
|
-
self.surface = surface
|
|
350
|
-
dirty = true
|
|
351
|
-
forceKey = true
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
func didReceiveDamageRect() { dirty = true }
|
|
355
|
-
|
|
356
|
-
/// The encoded picture: the framebuffer scaled to stay within \`maxPixels\`, even sides.
|
|
357
|
-
func outputSize(_ surface: IOSurface) -> (width: Int, height: Int) {
|
|
358
|
-
let width = Double(IOSurfaceGetWidth(surface)), height = Double(IOSurfaceGetHeight(surface))
|
|
359
|
-
let fit = min(1, (maxPixels / (width * height)).squareRoot())
|
|
360
|
-
let even = { (value: Double) in max(2, Int(value * fit) / 2 * 2) }
|
|
361
|
-
return (even(width), even(height))
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
func makeSession(_ width: Int, _ height: Int) {
|
|
365
|
-
if let session { VTCompressionSessionInvalidate(session) }
|
|
366
|
-
var created: VTCompressionSession?
|
|
367
|
-
let status = VTCompressionSessionCreate(allocator: nil, width: Int32(width), height: Int32(height),
|
|
368
|
-
codecType: kCMVideoCodecType_H264, encoderSpecification: nil, imageBufferAttributes: nil,
|
|
369
|
-
compressedDataAllocator: nil, outputCallback: nil, refcon: nil, compressionSessionOut: &created)
|
|
370
|
-
guard status == noErr, let created else { fail("encoder_failed \\(status)") }
|
|
371
|
-
let set = { (key: CFString, value: CFTypeRef) in _ = VTSessionSetProperty(created, key: key, value: value) }
|
|
372
|
-
set(kVTCompressionPropertyKey_RealTime, kCFBooleanTrue)
|
|
373
|
-
set(kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Main_4_2)
|
|
374
|
-
set(kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse)
|
|
375
|
-
set(kVTCompressionPropertyKey_MaxFrameDelayCount, 0 as CFNumber)
|
|
376
|
-
set(kVTCompressionPropertyKey_ExpectedFrameRate, fps as CFNumber)
|
|
377
|
-
set(kVTCompressionPropertyKey_AverageBitRate, (kbps * 1000) as CFNumber)
|
|
378
|
-
// Keyframes come from a (re)start or a framebuffer change; this is only a safety net.
|
|
379
|
-
set(kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 60 as CFNumber)
|
|
380
|
-
VTCompressionSessionPrepareToEncodeFrames(created)
|
|
381
|
-
session = created
|
|
382
|
-
size = (width, height)
|
|
383
|
-
var createdTransfer: VTPixelTransferSession?
|
|
384
|
-
VTPixelTransferSessionCreate(allocator: nil, pixelTransferSessionOut: &createdTransfer)
|
|
385
|
-
transfer = createdTransfer
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
func tick() {
|
|
389
|
-
guard dirty, let surface else { return }
|
|
390
|
-
dirty = false
|
|
391
|
-
let wanted = outputSize(surface)
|
|
392
|
-
if session == nil || wanted.width != size.width || wanted.height != size.height { makeSession(wanted.width, wanted.height) }
|
|
393
|
-
guard let session, let transfer, let pool = VTCompressionSessionGetPixelBufferPool(session) else { return }
|
|
394
|
-
var source: Unmanaged<CVPixelBuffer>?
|
|
395
|
-
guard CVPixelBufferCreateWithIOSurface(nil, surface, nil, &source) == kCVReturnSuccess, let source else { return }
|
|
396
|
-
let input = source.takeRetainedValue()
|
|
397
|
-
var output: CVPixelBuffer?
|
|
398
|
-
guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &output) == kCVReturnSuccess, let output else { return }
|
|
399
|
-
guard VTPixelTransferSessionTransferImage(transfer, from: input, to: output) == noErr else { return }
|
|
400
|
-
let time = CMTime(value: frames, timescale: CMTimeScale(fps))
|
|
401
|
-
frames += 1
|
|
402
|
-
let options = forceKey ? [kVTEncodeFrameOptionKey_ForceKeyFrame: kCFBooleanTrue] as CFDictionary : nil
|
|
403
|
-
forceKey = false
|
|
404
|
-
VTCompressionSessionEncodeFrame(session, imageBuffer: output, presentationTimeStamp: time, duration: .invalid,
|
|
405
|
-
frameProperties: options, infoFlagsOut: nil) { status, _, sample in
|
|
406
|
-
guard status == noErr, let sample else { return }
|
|
407
|
-
Encoder.write(sample)
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
/// One access unit as Annex-B, then the next unit's AUD: the reader splits at AUDs, so the unit is complete now.
|
|
412
|
-
static func write(_ sample: CMSampleBuffer) {
|
|
413
|
-
guard let block = CMSampleBufferGetDataBuffer(sample), let format = CMSampleBufferGetFormatDescription(sample) else { return }
|
|
414
|
-
let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[CFString: Any]]
|
|
415
|
-
let key = !((attachments?.first?[kCMSampleAttachmentKey_NotSync] as? Bool) ?? false)
|
|
416
|
-
var unit = Data()
|
|
417
|
-
if key {
|
|
418
|
-
var count = 0
|
|
419
|
-
CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: 0, parameterSetPointerOut: nil,
|
|
420
|
-
parameterSetSizeOut: nil, parameterSetCountOut: &count, nalUnitHeaderLengthOut: nil)
|
|
421
|
-
for index in 0..<count {
|
|
422
|
-
var pointer: UnsafePointer<UInt8>?
|
|
423
|
-
var length = 0
|
|
424
|
-
CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, parameterSetIndex: index, parameterSetPointerOut: &pointer,
|
|
425
|
-
parameterSetSizeOut: &length, parameterSetCountOut: nil, nalUnitHeaderLengthOut: nil)
|
|
426
|
-
guard let pointer, length > 0 else { continue }
|
|
427
|
-
let set = Data(bytes: pointer, count: length)
|
|
428
|
-
unit.append(startCode)
|
|
429
|
-
unit.append(set[set.startIndex] & 0x1F == 7 ? lowDelaySps(set) : set)
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
var total = 0
|
|
433
|
-
var base: UnsafeMutablePointer<CChar>?
|
|
434
|
-
guard CMBlockBufferGetDataPointer(block, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &total, dataPointerOut: &base) == noErr,
|
|
435
|
-
let base else { return }
|
|
436
|
-
var offset = 0
|
|
437
|
-
while offset + 4 <= total {
|
|
438
|
-
var length: UInt32 = 0
|
|
439
|
-
memcpy(&length, base.advanced(by: offset), 4)
|
|
440
|
-
let nal = Int(CFSwapInt32BigToHost(length))
|
|
441
|
-
offset += 4
|
|
442
|
-
guard offset + nal <= total else { break }
|
|
443
|
-
unit.append(startCode)
|
|
444
|
-
base.advanced(by: offset).withMemoryRebound(to: UInt8.self, capacity: nal) { unit.append($0, count: nal) }
|
|
445
|
-
offset += nal
|
|
446
|
-
}
|
|
447
|
-
unit.append(accessUnitDelimiter)
|
|
448
|
-
writeOut(unit)
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
@MainActor
|
|
453
|
-
func stream(_ udid: String, fps: Int, maxPixels: Double, kbps: Int) async {
|
|
454
|
-
let target: FBSimulator
|
|
455
|
-
let framebuffer: FBFramebuffer
|
|
456
|
-
do {
|
|
457
|
-
target = try await simulator(udid)
|
|
458
|
-
framebuffer = try FBFramebuffer.mainScreenSurface(for: target, logger: logger)
|
|
459
|
-
} catch {
|
|
460
|
-
fail("connect_failed: \\(error.localizedDescription)")
|
|
461
|
-
}
|
|
462
|
-
let encoder = Encoder(fps: fps, maxPixels: maxPixels, kbps: kbps)
|
|
463
|
-
let first = framebuffer.attach(encoder, on: encoder.queue)
|
|
464
|
-
encoder.queue.async { if let first, encoder.surface == nil { encoder.surface = first } }
|
|
465
|
-
writeOut(accessUnitDelimiter)
|
|
466
|
-
let timer = DispatchSource.makeTimerSource(queue: encoder.queue)
|
|
467
|
-
timer.schedule(deadline: .now(), repeating: .nanoseconds(1_000_000_000 / max(1, fps)))
|
|
468
|
-
timer.setEventHandler { encoder.tick() }
|
|
469
|
-
timer.resume()
|
|
470
|
-
// "key" on stdin asks for a keyframe; end of stdin ends the stream.
|
|
471
|
-
do {
|
|
472
|
-
for try await line in FileHandle.standardInput.bytes.lines where line == "key" {
|
|
473
|
-
encoder.queue.async { encoder.forceKey = true; encoder.dirty = true }
|
|
474
|
-
}
|
|
475
|
-
} catch {}
|
|
476
|
-
framebuffer.detach(encoder)
|
|
477
|
-
_ = target
|
|
478
|
-
exit(0)
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
// MARK: - main
|
|
482
|
-
|
|
483
|
-
signal(SIGPIPE, SIG_IGN)
|
|
484
|
-
let arguments = CommandLine.arguments
|
|
485
|
-
guard arguments.count >= 3 else { fail("usage: simulator-host serve|stream <udid> ...") }
|
|
486
|
-
switch arguments[1] {
|
|
487
|
-
case "serve":
|
|
488
|
-
await serve(arguments[2])
|
|
489
|
-
case "stream":
|
|
490
|
-
guard arguments.count == 6, let fps = Int(arguments[3]), let maxPixels = Double(arguments[4]), let kbps = Int(arguments[5]) else {
|
|
491
|
-
fail("usage: simulator-host stream <udid> <fps> <max pixels> <kbps>")
|
|
492
|
-
}
|
|
493
|
-
await stream(arguments[2], fps: fps, maxPixels: maxPixels, kbps: kbps)
|
|
494
|
-
default:
|
|
495
|
-
fail("usage: simulator-host serve|stream <udid> ...")
|
|
496
|
-
}
|
|
497
|
-
`;var Na=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",dd=180000,pd=15000,md=30000,fd=600000,hd=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map((e)=>`@interface ${e} : NSObject
|
|
498
|
-
@end
|
|
499
|
-
`).join("");function Ma(e,l,c){return new Promise((p)=>{let m=$o(e,l,{stdio:["ignore","pipe","pipe"],timeout:c}),f="";m.stdout.on("data",(h)=>{f+=h}),m.stderr.on("data",(h)=>{f+=h}),m.once("error",(h)=>p({code:-1,output:String(h)})),m.once("close",(h)=>p({code:h??-1,output:f}))})}var $a=new Map;function Bo(e){let l=ne(Ba(e),"Frameworks"),c=$a.get(l);if(!c)$a.set(l,c=gd(l));return c}async function gd(e){if(process.platform!=="darwin"||!No(ne(e,"FBSimulatorControl.framework")))return null;let l=await Ma("xcrun",["swiftc","--version"],30000);if(l.code!==0)return null;let c=sd("sha256").update(Lo).update(l.output).update(e).digest("hex").slice(0,16),p=ne(cd(),".local","share","reason","simulator","host"),m=ne(p,c,"simulator-host");if(No(m))return m;Yr(p,{recursive:!0,mode:448});let f=ad(ne(p,".staging-"));try{let h=ne(f,"Frameworks"),y=ne(h,"FBSimulatorControl.framework"),S=ne(y,"Modules","FBSimulatorControl.swiftmodule");Yr(S,{recursive:!0});for(let F of ka(e))if(F!=="FBSimulatorControl.framework")Mo(ne(e,F),ne(h,F));let w=ne(e,"FBSimulatorControl.framework");Mo(ne(w,"FBSimulatorControl"),ne(y,"FBSimulatorControl")),Mo(ne(w,"Headers"),ne(y,"Headers")),or(ne(y,"Modules","module.modulemap"),Ta(ne(w,"Modules","module.modulemap")));let _=Ta(ne(w,"Modules","FBSimulatorControl.swiftmodule",`${Na}.swiftinterface`),"utf8");or(ne(S,`${Na}.swiftinterface`),_.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let v=ne(f,"include","CoreSimulator");Yr(v,{recursive:!0}),or(ne(v,"module.modulemap"),`module CoreSimulator {
|
|
500
|
-
header "CoreSimulator.h"
|
|
501
|
-
export *
|
|
502
|
-
}
|
|
503
|
-
`),or(ne(v,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
|
|
504
|
-
${hd}`);let R=ne(f,"main.swift");or(R,Lo);let C=ne(f,"simulator-host"),A=await Ma("xcrun",["swiftc","-O","-F",h,"-I",ne(f,"include"),"-module-cache-path",ne(f,"cache"),"-Xlinker","-rpath","-Xlinker",e,R,"-o",C],dd);if(A.code!==0||!No(C))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
|
|
505
|
-
${A.output.slice(-2000)}
|
|
506
|
-
`),null;Yr(Ba(m),{recursive:!0}),ld(C,m);for(let F of ka(p))if(F!==c&&!F.startsWith(".staging-"))Da(ne(p,F),{recursive:!0,force:!0});return m}catch{return null}finally{Da(f,{recursive:!0,force:!0})}}class ir extends Error{}class Ct extends Error{}class Fa{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor(e,l){this.child=e;this.onGone=l;ud({input:e.stdout}).on("line",(p)=>{let m;try{m=JSON.parse(p)}catch{return}let f=this.pending.get(Number(m.id));if(!f)return;if(this.pending.delete(Number(m.id)),clearTimeout(f.timer),m.ok===!0)f.resolve(m);else f.reject(new ir(String(m.error??"The simulator refused the action.")))}),e.once("exit",()=>this.end()),e.once("error",()=>this.end()),this.touch()}call(e){if(this.gone)return Promise.reject(new Ct("The simulator host has exited."));this.touch();let l=this.nextId++;return new Promise((c,p)=>{let m=setTimeout(()=>{this.pending.delete(l),p(new Ct("The simulator host did not answer.")),this.close()},md);this.pending.set(l,{resolve:c,reject:p,timer:m}),this.child.stdin.write(`${JSON.stringify({id:l,...e})}
|
|
507
|
-
`)})}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(),fd),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let e of this.pending.values())clearTimeout(e.timer),e.reject(new Ct("The simulator host has exited."));this.pending.clear(),this.onGone()}}var Rt=new Map;async function Kr(e,l,c=!1){let p=Rt.get(l);if(!p){let m={started:_d(e,l)};Rt.set(l,p=m),m.started.then((f)=>{if(m.host=f,!f&&Rt.get(l)===m)Rt.delete(l)})}if(p.host!==void 0)return p.host;return c?p.started:null}async function _d(e,l){let c=await Bo(e);if(!c)return null;let p=$o(c,["serve",l],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((h)=>{let y=setTimeout(()=>h(!1),pd);p.stdout.once("data",(S)=>{clearTimeout(y),h(String(S).includes('"ready":true'))}),p.once("exit",()=>{clearTimeout(y),h(!1)}),p.once("error",()=>{clearTimeout(y),h(!1)})})){if(p.exitCode===null)p.kill("SIGTERM");return null}let f=new Fa(p,()=>{let h=Rt.get(l);if(h&&(h.host===f||h.host===void 0))Rt.delete(l)});return f}function Ua(e,l,c,p,m){return $o(e,["stream",l,String(c),String(Math.round(p)),String(m)],{stdio:["pipe","pipe","ignore"]})}var Pt={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"},vd=50000,Rd=112640,xd=174080,Fo=2,Ed=60000,Cd=2000,Pd=300,Od=40,Id=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function Lt(e,l,c={}){return new Promise((p,m)=>{let f=Xo(e,l,{cwd:c.cwd,stdio:["ignore","pipe","pipe"],signal:c.signal}),h=[],y=[];f.stdout.on("data",(w)=>h.push(w)),f.stderr.on("data",(w)=>y.push(w));let S=setTimeout(()=>f.kill("SIGKILL"),c.timeoutMs??vd);f.on("error",(w)=>{clearTimeout(S),m(w)}),f.on("close",(w)=>{clearTimeout(S),p({code:w??-1,stdout:Buffer.concat(h).toString("utf8"),stderr:Buffer.concat(y).toString("utf8")})})})}function re(e,l){throw new r(e,l)}async function xe(e,l,c,p={}){let m=await Lt(e,l,p);if(m.code!==0)re("simulator_command_failed",`${c} failed: ${(m.stderr||m.stdout).trim().slice(-1500)}`);return m.stdout}function lr(){return process.platform==="darwin"&&We("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&We("/usr/bin/xcrun")}var Uo=null;function pt(){return Q(ti(),".local","share","reason","simulator","axe")}function ri(){let e=Q(pt(),Pt.version,"axe");if(We(e))return Promise.resolve(e);return Uo??=(async()=>{qo(pt(),{recursive:!0,mode:448});let l=Qo(Q(pt(),".staging-"));try{let c=Q(l,"axe.tgz");await vo(Pt.url,Pt.sha256,c);let p=Q(l,"tree");if(qo(p),await xe("tar",["-xzf",c,"-C",p],"Extracting AXe"),!We(Q(p,"axe"))||!We(Q(p,"Frameworks")))re("simulator_axe_missing","The AXe archive has an unexpected layout.");ar(Q(pt(),Pt.version),{recursive:!0,force:!0}),wd(p,Q(pt(),Pt.version));for(let m of en(pt()))if(m!==Pt.version&&!m.startsWith(".staging-"))ar(Q(pt(),m),{recursive:!0,force:!0});return e}finally{ar(l,{recursive:!0,force:!0}),Uo=null}})(),Uo}var Za=ri;async function Qa(e){let l=await ri().catch(()=>null);return l?Kr(l,e.udid).catch(()=>null):null}async function Jr(e,l,c){let p=await ri().catch(()=>re("simulator_axe_missing","AXe could not be installed on this Mac.")),m=await Lt(p,[...e,"--udid",l]);if(m.code===0)return m.stdout;let f=(m.stderr||m.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(f))re("simulator_element_not_found",f.slice(-500));return re("simulator_command_failed",`${c} failed: ${f.slice(-1500)}`)}function Ad(e){let l=e.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return l?`${l[1]} ${l[2]}.${l[3]}${l[4]?`.${l[4]}`:""}`:e}function Ld(e){switch(e){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function ii(){let l=JSON.parse(await xe("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},c=[];for(let[p,m]of Object.entries(l)){if(!p.includes("SimRuntime.iOS"))continue;for(let f of m){if(f.isAvailable===!1)continue;let h=f.name.toLowerCase();if(f.deviceTypeIdentifier)zo.set(f.udid,f.deviceTypeIdentifier);c.push({udid:f.udid,name:f.name,runtime:Ad(p),state:Ld(f.state),kind:h.includes("iphone")?"iphone":h.includes("ipad")?"ipad":"other"})}}return c.sort((p,m)=>Number(m.state==="booted")-Number(p.state==="booted")||m.runtime.localeCompare(p.runtime,void 0,{numeric:!0})||p.name.localeCompare(m.name))}var zo=new Map,Yo=null;async function ke(e,l){let c=await ii(),p;if(e){let m=c.filter((f)=>f.udid===e||f.name===e);if(p=m.find((f)=>f.state==="booted")??m[0],!p)re("simulator_device_not_found",`No simulator named "${e}". Call devices to list them.`)}else{let m=c.filter((f)=>f.state==="booted");if(p=m.find((f)=>f.udid===Yo)??m.find((f)=>f.kind==="iphone")??m[0],!p)re("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(l.booted&&p.state!=="booted")re("simulator_not_booted",`${p.name} is not booted. Boot it first.`);return Yo=p.udid,p}function de(e){return`${e.name} (${e.runtime})`}async function kd(e){if(e.state!=="booted"){let l=await Lt("xcrun",["simctl","boot",e.udid]);if(l.code!==0&&!/current state: Booted/i.test(l.stderr))re("simulator_command_failed",`Booting ${e.name} failed: ${l.stderr.trim().slice(-1000)}`);await xe("xcrun",["simctl","bootstatus",e.udid,"-b"],`Waiting for ${e.name} to boot`,{timeoutMs:45000})}return Yo=e.udid,{...e,state:"booted"}}function si(e,l){let c=Vo(e,l),p=Xa(e,c);if(p.startsWith("..")||p.startsWith(Ja)||Vo(e,p)!==c)re("simulator_path_outside_root",`${l} is outside this machine's granted folder (${e}). Pass a path inside it, or one relative to it.`);return c}var Ha=4,Td=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function Dd(e){let l=[],c=(p,m)=>{let f;try{f=en(p)}catch{return}if(f.includes("project.yml")||f.some((h)=>h.endsWith(".xcworkspace")||h.endsWith(".xcodeproj"))){l.push(p);return}if(m>=Ha)return;for(let h of f.sort()){if(h.startsWith(".")||Td.has(h))continue;let y=Q(p,h);try{if(Xr(y).isDirectory())c(y,m+1)}catch{}}};if(c(e,0),l.length===1)return l[0];if(!l.length)re("simulator_project_not_found",`No Xcode project or project.yml within ${Ha} folders of ${e}; pass path.`);return re("simulator_project_not_found",`${e} holds several Xcode projects; pass path as one of: ${l.map((p)=>Xa(e,p)||".").join(", ")}.`)}var At=new Map;async function Nd(e){if(e.endsWith(".xcworkspace"))return{flag:"-workspace",path:e,dir:Wo(e)};if(e.endsWith(".xcodeproj"))return{flag:"-project",path:e,dir:Wo(e)};if(!Xr(e).isDirectory())re("simulator_project_not_found",`${e} is not a project, workspace or folder.`);let l=(m)=>en(e).filter((f)=>f.endsWith(m)).sort();if(We(Q(e,"project.yml")))await xe("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:e,timeoutMs:45000}).catch((m)=>We("/opt/homebrew/bin/xcodegen")?xe("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:e,timeoutMs:45000}):Promise.reject(m));let c=l(".xcworkspace")[0];if(c)return{flag:"-workspace",path:Q(e,c),dir:e};let p=l(".xcodeproj")[0];if(p)return{flag:"-project",path:Q(e,p),dir:e};return re("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${e}.`)}async function el(e){let l=JSON.parse(await xe("xcodebuild",["-list","-json",e.flag,e.path],"Listing schemes"));return l.workspace?.schemes??l.project?.schemes??[]}async function Md(e){let l=(await el(e))[0];if(!l)re("simulator_build_no_scheme",`${e.path} has no schemes; pass scheme.`);return l}function $d(e){let l=[],c=new Set;return e.forEach((p,m)=>{if(l.length>=20||!/(^|\s)error: /.test(p)||p.startsWith("note:")||c.has(p))return;c.add(p);let f=e.slice(m+1,m+3).filter((h)=>h.trim()!==""&&!/(^|\s)(error|warning|note): /.test(h));l.push([p,...f].join(`
|
|
508
|
-
`).slice(0,800))}),l}async function Bd(e,l,c){if(e.ended=Date.now(),l!==0){if(e.log.some((f)=>f.includes("does not contain a scheme named"))){let f=await el(c).catch(()=>[]);if(f.length)e.log.push(`error: this project's schemes are: ${f.join(", ")}`)}e.status="failed";return}let p=Q(e.productsDir,`${e.configuration}-iphonesimulator`),m=We(p)?en(p).filter((f)=>f.endsWith(".app")).map((f)=>Q(p,f)).sort((f,h)=>Xr(h).mtimeMs-Xr(f).mtimeMs):[];if(e.appPath=m[0],e.appPath)e.bundleId=await nl(e.appPath).catch(()=>{return});if(e.status=e.appPath?"succeeded":"failed",!e.appPath)e.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function ja(e,l){let c=e.path?si(l,e.path):Dd(l),p=await Nd(c),m=e.scheme??await Md(p),f=e.configuration??"Debug",h=await ke(e.device,{booted:!1}).catch(()=>null),y=h?`platform=iOS Simulator,id=${h.udid}`:"generic/platform=iOS Simulator",S=yd("sha256").update(p.path).digest("hex").slice(0,16),w=Q(ti(),"Library","Caches","reason","simulator-builds",S),_={id:`build-${bd().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:Q(w,"Build","Products"),configuration:f};At.set(_.id,_);for(let[A,F]of At)if(At.size>20&&F.status!=="running")At.delete(A);let v=Xo("xcodebuild",[p.flag,p.path,"-scheme",m,"-configuration",f,"-destination",y,"-derivedDataPath",w,"-skipMacroValidation","build"],{cwd:p.dir,stdio:["ignore","pipe","pipe"]}),R="",C=(A)=>{let F=(R+A.toString("utf8")).split(`
|
|
509
|
-
`);if(R=F.pop()??"",_.log.push(...F),_.log.length>5000)_.log.splice(0,_.log.length-5000)};return v.stdout.on("data",C),v.stderr.on("data",C),v.on("error",(A)=>{_.log.push(`error: ${A.message}`),_.status="failed",_.ended=Date.now()}),v.on("close",(A)=>{if(R)_.log.push(R);Bd(_,A??-1,p)}),{text:`Build ${_.id} started: ${m} (${f}) for ${h?de(h):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:tl(_)}}function tl(e){return{id:e.id,status:e.status,errors:$d(e.log),log_tail:e.log.slice(-Od).join(`
|
|
510
|
-
`).slice(-4000),elapsed_ms:(e.ended??Date.now())-e.started,...e.appPath?{app_path:e.appPath}:{},...e.bundleId?{bundle_id:e.bundleId}:{}}}var Fd=45000,Ud=30000;async function Ho(e,l=Fd){let c=Date.now()+l;while(At.get(e)?.status==="running"&&Date.now()<c)await Bun.sleep(500);let p=rl(e);return p.build?.status==="running"?{...p,text:`${p.text} Still running: call build_status with wait again.`}:p}function rl(e){let l=At.get(e);if(!l)re("simulator_build_not_found",`No build ${e} on this Mac (a worker restart forgets builds); start a new one.`);let c=tl(l);return{text:l.status==="running"?`Build ${e} is running (${Math.round(c.elapsed_ms/1000)} s).`:l.status==="succeeded"?`Build ${e} succeeded: ${l.appPath}. Launch it with app_path.`:`Build ${e} failed with ${c.errors.length} error(s).`,build:c}}async function nl(e){return(await xe("plutil",["-extract","CFBundleIdentifier","raw","-o","-",Q(e,"Info.plist")],"Reading the bundle id")).trim()}var ot=new Map;function Hd(e,l){ot.get(e.udid)?.stop();let c=Xo("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",e.udid,l],{stdio:["ignore","pipe","pipe"]}),p={udid:e.udid,bundleId:l,lines:[],first:0,stop:()=>c.kill("SIGTERM")};ot.set(e.udid,p);let m="",f=(h)=>{let y=(m+h.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
|
|
511
|
-
`);m=y.pop()??"",p.lines.push(...y);let S=p.lines.length-Cd;if(S>0)p.lines.splice(0,S),p.first+=S};return c.stdout.on("data",f),c.stderr.on("data",f),new Promise((h)=>{let y=setTimeout(()=>h(null),15000),S=()=>{let w=p.lines.concat(m).join(`
|
|
512
|
-
`).match(new RegExp(`${l.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(w)clearTimeout(y),h(Number(w))};c.stdout.on("data",S),c.on("close",()=>{clearTimeout(y),h(null)})})}async function jd(e,l){let c=await ke(e.device,{booted:!0}),p=e.bundle_id;if(e.app_path){let f=qd(l,e.app_path);await xe("xcrun",["simctl","install",c.udid,f],`Installing ${Ka(f)}`),p=await nl(f)}if(e.bundle_id){if((await Lt("xcrun",["simctl","get_app_container",c.udid,e.bundle_id])).code!==0)re("simulator_app_not_installed",`${e.bundle_id} is not installed on ${de(c)}.`)}let m=await Hd(c,p);if(m===null){let f=ot.get(c.udid)?.lines.slice(-20).join(`
|
|
513
|
-
`)??"";re("simulator_launch_failed",`${p} did not start on ${de(c)}.${f?`
|
|
514
|
-
${f}`:""}`)}return{text:`Launched ${p} on ${de(c)} (pid ${m}). Its console is captured; read it with logs.`,device:c}}function qd(e,l){let c=Vo(l),p=Q(ti(),"Library","Caches","reason","simulator-builds")+Ja;return c.startsWith(p)&&c.endsWith(".app")?c:si(e,c)}function Wd(e,l){let c=ot.get(e.udid);if(!c)return{text:`No app launched by Reason is running on ${de(e)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let p=Math.max(l??0,c.first,c.first+c.lines.length-Pd),m=c.lines.slice(p-c.first).map((f)=>f.slice(0,2000));return{text:`${m.length} console line(s) from ${c.bundleId} on ${de(e)}.`,logs:{lines:m,next:c.first+c.lines.length}}}var Zr=new Map;function qa(e,...l){let c=Zr.get(e.udid);if(!c)return;for(let[p,m]of l)if(p>c.width||m>c.height)re("simulator_point_off_screen",`(${p}, ${m}) is off ${e.name}'s ${c.width}x${c.height}-point screen.`)}function Wa(e,l){if(e.kind==="ipad")return 2;return l===750||l===828||l===640?2:3}async function ai(e,l=1,c){let p=Qo(Q(Ya(),"reason-sim-"));try{let m=Q(p,"screen.png");if(await xe("xcrun",["simctl","io",e.udid,"screenshot","--type=png",m],"Taking a screenshot"),c){qo(Wo(c),{recursive:!0});let C=await xe("sips",["-g","pixelWidth","-g","pixelHeight",m],"Reading the screenshot size"),A=Number(C.match(/pixelWidth: (\d+)/)?.[1]),F=Number(C.match(/pixelHeight: (\d+)/)?.[1]),L=2/Wa(e,A);await xe("sips",["-z",String(Math.round(F*L)),String(Math.round(A*L)),m,"--out",c],"Saving the screenshot")}let f=await xe("sips",["-g","pixelWidth","-g","pixelHeight",m],"Reading the screenshot size"),h=Number(f.match(/pixelWidth: (\d+)/)?.[1]),y=Number(f.match(/pixelHeight: (\d+)/)?.[1]),S=Wa(e,h),w=Math.round(h/S),_=Math.round(y/S);Zr.set(e.udid,{width:w,height:_});let v=Buffer.alloc(0),R=l===2?xd:Rd;for(let C of[70,50,35]){let A=Q(p,`screen-${C}.jpg`);if(await xe("sips",["-z",String(_*l),String(w*l),"-s","format","jpeg","-s","formatOptions",String(C),m,"--out",A],"Encoding the screenshot"),v=ei(A),v.byteLength<=R)break}return{text:`Screenshot of ${de(e)} at ${w}x${_} points: image pixels are tap coordinates.`+(c?` Saved at ${c}.`:""),device:e,image:{mime:"image/jpeg",data:v.toString("base64"),width:w,height:_}}}finally{ar(p,{recursive:!0,force:!0})}}async function Vd(e){let l=await Qa(e);if(l)try{return String((await l.call({op:"tree"})).tree)}catch{}return Jr(["describe-ui"],e.udid,"Reading the accessibility tree")}async function Qr(e){let l=JSON.parse(await Vd(e)),c={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},p=(m,f,h="")=>{let y=(m.role??m.type??"?").replace(/^AX/,""),S=m.AXLabel||m.title||"",w=m.AXValue?` value="${String(m.AXValue).slice(0,120)}"`:"",_=m.AXUniqueId?` id=${m.AXUniqueId}`:"";if(m.AXUniqueId)c.ids.add(m.AXUniqueId);if(S)c.labels.add(S);let v=m.frame;if(y==="Application"&&v&&!c.bounds)c.bounds={width:v.width,height:v.height};if(v&&v.width>0&&v.height>0&&(m.AXUniqueId||m.AXLabel))c.targets.push({...m.AXUniqueId?{id:m.AXUniqueId.trim()}:{},...m.AXLabel?{label:m.AXLabel.trim()}:{},role:y,frame:v});let R=Boolean(S||_||w||!["Group","Other"].includes(y));if(R){let C=`${" ".repeat(Math.min(f,12))}${y} "${S.slice(0,160)}"${_}${w}`+(v?` (${Math.round(v.x)},${Math.round(v.y)} ${Math.round(v.width)}x${Math.round(v.height)})`:"")+(m.enabled===!1?" disabled":"");c.lines.push(C);let A=y==="Image"&&!_,F=(y==="StaticText"||y==="Image")&&!_&&S!==""&&h.includes(S);if(!A&&!F)c.compact.push(C)}for(let C of m.children??[])p(C,R?f+1:f,S||h)};for(let m of l)p(m,0);return c}function ol(e,l,c=!1){let p=(c?e.compact:e.lines).join(`
|
|
515
|
-
`);return p.length>l?`${p.slice(0,l)}
|
|
516
|
-
\u2026 (truncated)`:p}async function zd(e){let l=await Qr(e);return{text:`Accessibility tree of ${de(e)} (frames in points; tap by id or label):
|
|
517
|
-
${ol(l,Ed)}`,device:e}}var Gd=450,Yd=1e4;function Kd(e,l){let c=l.id?e.ids.has(l.id):[...e.labels].some((p)=>p===l.label||p.includes(l.label));return l.gone?!c:c}async function mt(e,l,c){let p=l.observe??"tree";if(p==="none"&&!l.wait_for)return c;let m=null,f="";if(l.wait_for){let y=Date.now()+(l.timeout??5)*1000,S=l.wait_for,w=S.id?`id ${S.id}`:`"${S.label}"`;for(;;){if(m=await Qr(e),Kd(m,S)){f=` ${w} is ${S.gone?"gone":"on screen"}.`;break}if(Date.now()>=y){f=S.gone?` Waited ${l.timeout??5} s: ${w} is still on screen.`:` Waited ${l.timeout??5} s: ${w} 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(Gd);let h={...c,text:`${c.text}${f}`};if(p==="tree"||p==="both")m??=await Qr(e),h.screen=ol(m,Yd,!0),h.text+=`
|
|
518
|
-
Screen now:
|
|
519
|
-
${h.screen}`;if(p==="screenshot"||p==="both"){let y=await ai(e);h.image=y.image}return h}function Va(e){return`'${e.replace(/'/g,"'\\''")}'`}function Xd(e){switch(e.action){case"tap":if(e.x!==void 0&&e.y!==void 0)return e.duration?`touch -x ${e.x} -y ${e.y} --down --up --delay ${e.duration}`:`tap -x ${e.x} -y ${e.y}`;return e.id?`tap --id ${Va(e.id)}`:`tap --label ${Va(e.label)}`;case"swipe":return`swipe --start-x ${e.x} --start-y ${e.y} --end-x ${e.x2} --end-y ${e.y2} --duration ${e.duration??0.3}`;case"button":return`button ${e.name.replace("_","-")}`;case"sleep":return`sleep ${e.seconds}`}}var il=0.35,Jd=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function Zd(e,l){let c=e.targets.filter((w)=>l.id!==void 0?w.id===l.id.trim():w.label===l.label?.trim()),p=(w)=>({x:w.frame.x+w.frame.width/2,y:w.frame.y+w.frame.height/2}),m=e.bounds,f=m?c.filter((w)=>{let{x:_,y:v}=p(w);return _>=0&&v>=0&&_<=m.width&&v<=m.height}):c,h=f.length?f:c,y=h.filter((w)=>Jd.has(w.role)),S=(y.length?y:h)[0];return S?p(S):null}async function Qd(e,l,c,p,m){let f=Date.now()+c*1000;for(;;){let h=Zd(await Qr(e),l);if(h)return h;if(Date.now()>=f){let y=l.id!==void 0?`--id '${l.id}'`:`--label '${l.label}'`;return re("simulator_element_not_found",`Error: Step ${p} failed: [tap]
|
|
520
|
-
No accessibility element matched ${y}. Make sure the app is on the expected screen, then inspect it and prefer an id when there is one.
|
|
521
|
-
(${p-1} of ${m} steps had completed.)`)}await Bun.sleep(250)}}async function It(e,l,c){let p=await Qa(e);if(!p)return za(e,l,c);for(let[m,f]of l.entries()){try{switch(f.action){case"tap":{let y=f.x!==void 0&&f.y!==void 0?{x:f.x,y:f.y}:await Qd(e,f,c,m+1,l.length);await p.call(f.duration?{op:"tap",...y,duration:f.duration}:{op:"tap",...y});break}case"swipe":await p.call({op:"swipe",x:f.x,y:f.y,x2:f.x2,y2:f.y2,duration:f.duration??0.3});break;case"button":await p.call({op:"button",name:f.name});break;case"type":await p.call({op:"text",text:f.text}).catch((y)=>y instanceof ir?Jr(["type",f.text],e.udid,`Step ${m+1} (typing)`):Promise.reject(y));break;case"sleep":await Bun.sleep(f.seconds*1000);break}}catch(y){if(y instanceof Ct)return await za(e,l.slice(m),c),`Ran ${l.length} step(s) on ${de(e)}.`;if(y instanceof ir)re("simulator_command_failed",`Step ${m+1} failed: ${y.message}
|
|
522
|
-
(${m} of ${l.length} steps had completed.)`);throw y}let h=l[m+1];if(f.action!=="sleep"&&h&&h.action!=="sleep")await Bun.sleep(il*1000)}return`Ran ${l.length} step(s) on ${de(e)}.`}async function za(e,l,c){let p=[],m=[],f=0,h=0,y=async()=>{if(p.length===0)return;let S=["batch","--ax-cache","perStep","--wait-timeout",String(c)];for(let w of p)S.push("--step",w);try{await Jr(S,e.udid,`Steps ${h+1}-${h+f}`)}catch(w){if(w instanceof r){let _=w.message.replace(/Step (\d+) failed/,(v,R)=>{let C=m[Number(R)-1];return C?`Step ${C} failed`:v});re(w.code,`${_}
|
|
523
|
-
(${h} of ${l.length} steps had completed before this batch.)`)}throw w}h+=f,p=[],m=[],f=0};for(let[S,w]of l.entries()){if(w.action==="type"){await y(),await Jr(["type",w.text],e.udid,`Step ${h+1} (typing)`),h+=1;continue}p.push(Xd(w)),f+=1,m.push(S+1);let _=l[S+1];if(w.action!=="sleep"&&_&&_.action!=="sleep")p.push(`sleep ${il}`),m.push(S+1)}return await y(),`Ran ${l.length} step(s) on ${de(e)}.`}var ep=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],Ga=new Map,tp=`ObjC.import("AppKit");
|
|
524
|
-
function run(argv) {
|
|
525
|
-
const [input, output, width, height] = argv;
|
|
526
|
-
const w = Number(width), h = Number(height);
|
|
527
|
-
const image = $.NSImage.alloc.initWithContentsOfFile(input);
|
|
528
|
-
const rep = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
|
|
529
|
-
null, w, h, 8, 4, true, false, $.NSDeviceRGBColorSpace, 0, 0);
|
|
530
|
-
$.NSGraphicsContext.saveGraphicsState;
|
|
531
|
-
$.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(rep));
|
|
532
|
-
image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, $.NSCompositingOperationCopy, 1);
|
|
533
|
-
$.NSGraphicsContext.restoreGraphicsState;
|
|
534
|
-
rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(output, true);
|
|
535
|
-
}`;async function jo(e,l,c){let p=await xe("sips",["-g","pixelWidth","-g","pixelHeight",e],"Reading the frame size"),m=Number(p.match(/pixelWidth: ([\d.]+)/)?.[1]),f=Number(p.match(/pixelHeight: ([\d.]+)/)?.[1]);if(c!==void 0)m=m*c/f,f=c;let h=Qo(Q(Ya(),"reason-chrome-"));try{let y=Q(h,"render.js"),S=Q(h,"out.png");if(Sd(y,tp),await xe("osascript",["-l","JavaScript",y,e,S,String(Math.max(1,Math.round(m*l))),String(Math.max(1,Math.round(f*l)))],"Rendering the frame"),!We(S))re("simulator_command_failed",`Rendering ${Ka(e)} produced no image.`);return{image:ei(S).toString("base64"),width:m,height:f}}finally{ar(h,{recursive:!0,force:!0})}}async function rp(e){if(!zo.has(e.udid))await ii();let l=zo.get(e.udid),p=JSON.parse(await xe("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((m)=>m.identifier===l)?.bundlePath;if(!p)re("simulator_command_failed",`No device type bundle for ${e.name}.`);return p}async function np(e){let l=await rp(e),c=Zr.get(e.udid)??(e.state==="booted"?(await ai(e),Zr.get(e.udid)):void 0);if(!c)re("simulator_not_booted",`${e.name} is not booted.`);let p=Ga.get(l);if(p)return{text:`Frame of ${de(e)}.`,device:e,chrome:p};let m=Q(l,"Contents","Resources"),f=JSON.parse(await xe("plutil",["-convert","json","-o","-",Q(m,"profile.plist")],"Reading the device profile")),h=f.framebufferMask?Q(m,`${f.framebufferMask}.pdf`):null,y=h&&We(h)?await jo(h,Fo,c.height):null,S=f.chromeIdentifier?.split(".").pop(),w=S?Q("/Library/Developer/DeviceKit/Chrome",`${S}.devicechrome`,"Contents","Resources"):"";if(!S||!We(Q(w,"chrome.json")))re("simulator_command_failed",`${e.name} has no device frame in this Xcode.`);let _=JSON.parse(ei(Q(w,"chrome.json"),"utf8")),v={};for(let B of ep){let U=_.images[B];if(!U)re("simulator_command_failed",`${e.name}'s frame has no ${B} piece.`);v[B]=await jo(Q(w,`${U}.pdf`),Fo)}let{sizing:R}=_.images,C={top:R.topHeight,left:R.leftWidth,bottom:R.bottomHeight,right:R.rightWidth},A=c.width+C.left+C.right,F=c.height+C.top+C.bottom,L=[];for(let B of _.inputs??[]){let U=Q(w,`${B.image}.pdf`);if(!We(U))continue;let V=await jo(U,Fo),{x:se,y:we}=B.offsets.normal,Ce=(it,_e,Cr)=>it<0?_e+it-Cr:it,Qe=B.anchor==="left"?{x:se-V.width,y:Ce(we,F,V.height)}:B.anchor==="right"?{x:A+se,y:Ce(we,F,V.height)}:B.anchor==="top"?{x:Ce(se,A,V.width),y:we-V.height}:{x:Ce(se,A,V.width),y:F+we};L.push({name:B.name,image:V.image,...Qe,width:V.width,height:V.height})}let M={identifier:_.identifier,screen:{width:c.width,height:c.height},inset:C,padding:_.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:v,buttons:L,...y?{screen_mask:y.image}:{}};return Ga.set(l,M),{text:`Frame of ${de(e)}.`,device:e,chrome:M}}var op=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 ur(e){try{return await sl(e)}catch(l){if(l instanceof r&&op.has(l.code))return{text:l.message,error:l.code};throw l}}async function sl(e){if(!lr())re("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let l=Oo.safeParse(e.payload);if(!l.success)re("simulator_invalid_request",l.error.issues.map((p)=>p.message).join("; "));let c=l.data;switch(c.action){case"devices":{let p=await ii(),m=p.filter((f)=>f.state==="booted");return{text:`${m.length} booted (${m.map(de).join(", ")||"none"}), ${p.length} available.`,devices:p}}case"boot":{let p=await kd(await ke(c.device,{booted:!1}));return{text:`${de(p)} is booted.`,device:p}}case"shutdown":{let p=await ke(c.device,{booted:!1});ot.get(p.udid)?.stop(),ot.delete(p.udid);let m=await Lt("xcrun",["simctl","shutdown",p.udid]);if(m.code!==0&&!/current state: Shutdown/i.test(m.stderr))re("simulator_command_failed",m.stderr.trim().slice(-1000));return{text:`${de(p)} is shut down.`,device:{...p,state:"shutdown"}}}case"build":{let p=await ja(c,e.root);return c.wait&&p.build?Ho(p.build.id):p}case"build_status":return c.wait?Ho(c.build_id):rl(c.build_id);case"run":{let p=await ja({...c,action:"build"},e.root),m=await Ho(p.build.id,Ud);if(m.build?.status!=="succeeded"||!m.build.app_path)return m;let f=await sl({root:e.root,payload:{action:"launch",app_path:m.build.app_path,...c.device?{device:c.device}:{},...c.steps?{steps:c.steps}:{},...c.observe?{observe:c.observe}:{},...c.wait_for?{wait_for:c.wait_for}:{},...c.timeout!==void 0?{timeout:c.timeout}:{}}});return{...f,text:`Built in ${Math.round(m.build.elapsed_ms/1000)} s. ${f.text}`,build:m.build}}case"launch":{let p=await jd(c,e.root);if(!p.device)return p;if(c.steps?.length)p.text+=` ${await It(p.device,c.steps,c.timeout??8)}`;else if(!c.wait_for)await Bun.sleep(1000);return mt(p.device,c,p)}case"steps":{let p=await ke(c.device,{booted:!0});return mt(p,c,{text:await It(p,c.steps,c.timeout??5),device:p})}case"terminate":{let p=await ke(c.device,{booted:!0});if(ot.get(p.udid)?.bundleId===c.bundle_id)ot.get(p.udid)?.stop();return await Lt("xcrun",["simctl","terminate",p.udid,c.bundle_id]),{text:`Terminated ${c.bundle_id} on ${de(p)}.`,device:p}}case"logs":return Wd(await ke(c.device,{booted:!1}),c.after);case"screenshot":return ai(await ke(c.device,{booted:!0}),c.scale,c.save_path?si(e.root,c.save_path):void 0);case"chrome":return np(await ke(c.device,{booted:!1}));case"inspect":return zd(await ke(c.device,{booted:!0}));case"tap":{let p=await ke(c.device,{booted:!0}),m=c.x!==void 0&&c.y!==void 0;if(m)qa(p,[c.x,c.y]);await It(p,[m?{action:"tap",x:c.x,y:c.y,...c.duration&&c.duration>0?{duration:c.duration}:{}}:c.id?{action:"tap",id:c.id}:{action:"tap",label:c.label}],3);let f=m?`(${c.x}, ${c.y})`:c.id?`id ${c.id}`:`"${c.label}"`;return mt(p,c,{text:`Tapped ${f} on ${de(p)}.`,device:p})}case"swipe":{let p=await ke(c.device,{booted:!0});return qa(p,[c.x,c.y],[c.x2,c.y2]),await It(p,[{action:"swipe",x:c.x,y:c.y,x2:c.x2,y2:c.y2,...c.duration!==void 0?{duration:c.duration}:{}}],3),mt(p,c,{text:`Swiped (${c.x}, ${c.y}) \u2192 (${c.x2}, ${c.y2}) on ${de(p)}.`,device:p})}case"type":{let p=await ke(c.device,{booted:!0});return await It(p,[{action:"type",text:c.text}],3),mt(p,c,{text:`Typed ${c.text.length} character(s) on ${de(p)}.`,device:p})}case"button":{let p=await ke(c.device,{booted:!0});return await It(p,[{action:"button",name:c.name}],3),mt(p,c,{text:`Pressed ${c.name} on ${de(p)}.`,device:p})}case"open_url":{let p=await ke(c.device,{booted:!0}),m;try{m=new URL(c.url)}catch{re("simulator_invalid_request","open_url needs an absolute URL.")}if(Id.has(m.protocol))re("simulator_invalid_request",`${m.protocol} URLs are not allowed.`);return await xe("xcrun",["simctl","openurl",p.udid,m.href],"Opening the URL"),mt(p,c,{text:`Opened ${m.href} on ${de(p)}.`,device:p})}case"appearance":{let p=await ke(c.device,{booted:!0});return await xe("xcrun",["simctl","ui",p.udid,"appearance",c.mode],"Setting the appearance"),{text:`${de(p)} is in ${c.mode} mode.`,device:p}}}}import{mkdtempSync as ip,readFileSync as sp,rmSync as ap}from"fs";import{tmpdir as lp}from"os";import{join as al}from"path";import{spawn as ul}from"child_process";var cp=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,dr=1,up=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],ll=60,dp=8,dl=lr;var cl={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},pp=(()=>{let e={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((c,p)=>{e[c]=4+p,e[c.toUpperCase()]=4+p}),"1234567890".split("").forEach((c,p)=>{e[c]=30+p}),"!@#$%^&*()".split("").forEach((c,p)=>{e[c]=30+p});let l=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[c,p,m]of l)e[c]=m,e[p]=m;return e})();function mp(e){if(cl[e]!==void 0)return cl[e];return e>=32&&e<=126?pp[String.fromCharCode(e)]??null:null}function pl(e,l){let c=ul("xcrun",["simctl","pbcopy",e],{stdio:["pipe","ignore","ignore"]});c.once("error",()=>{}),c.stdin.end(l)}function fp(e,l){let c=0,p={x:0,y:0},m=(f)=>{l.call(f).catch(()=>{})};return{pointer(f,h,y){let S=(y&dr)!==0;if(S&&!(c&dr))m({op:"touch",phase:"down",x:f,y:h});else if(S&&(f!==p.x||h!==p.y))m({op:"touch",phase:"move",x:f,y:h});else if(!S&&c&dr)m({op:"touch",phase:"up",x:f,y:h});for(let w of up)if(y&w.bit&&!(c&w.bit))m({op:"swipe",x:f,y:h,x2:f+w.dx*ll,y2:h+w.dy*ll,duration:0.08});c=y,p={x:f,y:h}},key(f,h){let y=mp(h);if(y!==null)m({op:"key",usage:y,down:f})},clipboard(f){pl(e,f)},close(){if(c&dr)m({op:"touch",phase:"up",...p});c=0}}}function hp(e,l){let c=null,p="",m,f=(h)=>{ur({payload:{...h,device:e,observe:"none"},root:l}).catch(()=>{})};return{pointer(h,y,S){let w=(S&dr)!==0;if(w&&!c)c={x:h,y,at:Date.now()};if(!w&&c){let _=(Date.now()-c.at)/1000;if(Math.hypot(h-c.x,y-c.y)>dp)f({action:"swipe",x:c.x,y:c.y,x2:h,y2:y,duration:Math.min(Math.max(_,0.05),1)});else f({action:"tap",x:c.x,y:c.y,..._>0.5?{duration:Math.min(_,10)}:{}});c=null}},key(h,y){if(!h)return;let S=y===65293?`
|
|
536
|
-
`:y>=32&&y<=126?String.fromCharCode(y):null;if(S===null)return;p+=S,clearTimeout(m),m=setTimeout(()=>{let w=p;p="",f({action:"type",text:w})},250)},clipboard(h){pl(e,h)},close(){clearTimeout(m),c=null}}}function gp(e,l,c){return new Promise((p,m)=>{let f=ul(e,l,{stdio:"ignore",signal:c});f.once("error",m),f.once("exit",(h)=>p(h??-1))})}async function _p(e,l){let c=ip(al(lp(),"reason-simulator-stream-"));try{let p=al(c,"screen.png");if(await gp("xcrun",["simctl","io",e,"screenshot","--type=png",p],l)!==0)throw new r("simulator_not_booted","That simulator is not booted.");let m=sp(p).subarray(16,24);return{width:m.readUInt32BE(0),height:m.readUInt32BE(4)}}finally{ap(c,{recursive:!0,force:!0})}}async function ml(e,l={}){let{udid:c,...p}=e.payload;if(typeof c!=="string"||!cp.test(c)||!p.video)throw new r("invalid_display_request","Reason simulator stream request is malformed.");let m=await Za().catch(()=>{throw new r("simulator_axe_missing","AXe could not be installed on this Mac.")}),f=await ur({payload:{action:"screenshot",device:c},root:e.root});if(f.error||!f.image)throw new r("simulator_not_booted","That simulator is not booted.");let h={width:f.image.width,height:f.image.height},y=await Bo(m),S=y?await Kr(m,c,!0):null,w=y?null:await Un();if(!y&&!w)throw new r("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let _={kind:"simulator",udid:c,axe:m,points:h,sound:null,size:y?h:await _p(c,e.signal),stream:y?(v,R,C)=>Ua(y,c,Math.min(v,60),C,R):null,input:S?fp(c,S):hp(c,e.root)};return await jt({payload:p,signal:e.signal},{...l,video:{desktop:async()=>_,...w?{ffmpeg:()=>w}:{}}})}var El=131072,Ip=131072,Ap=128,Cl=8192,Ui=30000,Hi=15000,Lp=/^[a-z][a-z0-9_]{0,63}$/,ns=new Set(["jobs.control","fs.read","fs.write"]),fl=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function tn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`)}function hl(e){return e.map(tn).join("/")}function ci(e,l){let c=[];for(let p=0;p<e.length;p+=l)c.push(e.slice(p,p+l));return c}var kp=[...ci(Ee,4).map((e)=>`/(${e.map(hl).join("|")})(/|$)`),...ci(Xt,4).map((e)=>`/(${e.map(hl).join("|")})$`),...ci([...Yt],6).map((e)=>`/(${e.map(tn).join("|")})$`),`/${tn(".env")}\\.[^/]+$`,`/[^/]+(${Zt.map(tn).join("|")})$`],$i=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),Pl=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function Ol(e){return[e.requiredPermission,...e.additionalPermissions??[]]}function Tp(e){return Mt(e)}function Bi(){if(J()==="darwin")return Xe("/usr/bin/sandbox-exec");if(J()==="linux"||J()==="win32")return hr();return!1}function gl(){if(J()==="linux")return Xe("/proc");if(J()==="win32")return ye()!==null;if(!Bi())return!1;if(J()==="darwin")return Xe("/usr/sbin/lsof");return!1}function Vi(){return J()==="darwin"?"/bin/zsh":gn()}function Fi(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Dp(e,l){if(!Fi(e))throw new r("invalid_payload","Operation payload must be an object.");let c=l===nt?kt:Re;if(Buffer.byteLength(JSON.stringify(e),"utf8")>c)throw new r("payload_too_large",`Operation payload exceeds ${c/1024} KB.`);return e}function $t(e,l){let c=e[l];if(c===void 0||c===null)return;if(typeof c!=="string")throw new r("invalid_payload",`${l} must be a string.`);return c}function rn(e,l,c=Cl){let p=$t(e,l);if(!p||Buffer.byteLength(p,"utf8")>c||p.includes("\x00"))throw new r("invalid_payload",`${l} is missing or too large.`);return p}function Np(e,l,c){let p=e[l];if(typeof p!=="string"||p.includes("\x00")||Buffer.byteLength(p,"utf8")>c)throw new r("invalid_payload",`${l} is missing or too large.`);return p}function _r(e,l,c,p){if(e===void 0||e===null)return l;if(typeof e!=="number"||!Number.isInteger(e))throw new r("invalid_payload","Expected a bounded integer.");return Math.min(Math.max(e,c),p)}function ft(e,l){if(J()==="win32")[e,l]=[e.toLowerCase(),l.toLowerCase()];return l===e||l.startsWith(`${e}${Pp}`)}function Tt(e){if(So(e))throw new r("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 he(e){let l;try{l=Ye(e.path)}catch(c){if(process.platform==="darwin"&&wn(c))throw bn(e.path);throw new r("root_unavailable","The granted root is unavailable.")}if(l!==e.path||!xr(l).isDirectory())throw new r("root_changed","The granted root changed after registration.");return Tt(l),l}function ji(e,l="."){if(!l||l.includes("\x00")||Ep(l))throw new r("path_outside_root","Paths must be relative to the granted root.");if(J()==="win32"&&l.split(/[\\/]/).some(ln))throw new r("invalid_path","Windows reserves this file name.");let c=Cp(e,l);if(!ft(e,c))throw new r("path_outside_root","Path escapes the granted root.");return c}function Dt(e,l=".",c=!1){let p=ji(e,l),m;try{m=Ye(p)}catch(f){if(kl(f))throw Tl();throw new r("path_not_found","Path does not exist.")}if(!ft(e,m))throw new r("symlink_escape","Path resolves outside the granted root.");if(!c)Tt(m);return m}function Mp(e,l){let c=ji(e,l);if(Tt(c),Xe(c)){let f=Ye(c);if(!ft(e,f))throw new r("symlink_escape","Write target resolves outside the granted root.");if(Ii(c).isSymbolicLink())throw new r("symlink_escape","Writing through a symlink is not allowed.");return Tt(f),f}let p=gr(c);while(!Xe(p)){let f=gr(p);if(f===p)throw new r("path_outside_root","No safe write parent.");p=f}let m=Ye(p);if(!ft(e,m))throw new r("symlink_escape","Write parent resolves outside the granted root.");return Tt(m),c}function Il(e,l){return Mi(e,l)||"."}function $p(e,l=El){let c=Buffer.from(e,"utf8");if(c.byteLength<=l)return{value:e,truncated:!1};return{value:c.subarray(0,l).toString("utf8"),truncated:!0}}function Al(e,l){return{...Ue({home:e,temporaryDirectory:l}),ZDOTDIR:l,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 Bp(e,l,c,p=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...p?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify(e)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(l)}))`,...c?[`(allow file-write* (subpath ${JSON.stringify(e)}))`]:[],...kp.map((m)=>`(deny file-read* file-write* (regex #"${m}"))`),...Eo(e,c),"(deny network*)"].join(`
|
|
537
|
-
`)}async function mn(e,l,c){return new Promise((p,m)=>{let f="",h="",y=!1,S=!1,w=!1,_;try{_=Op(e,l,{cwd:c.cwd,env:c.env,shell:!1,stdio:["ignore","pipe","pipe"],...Ne()}),Le(_)}catch(F){m(F);return}let v=(F,L)=>{if(w)return;w=!0,clearTimeout(A),c.signal.removeEventListener("abort",C),p({exitCode:F,signal:L,stdout:f,stderr:h,timedOut:S,truncated:y})},R=(F,L)=>{let M=`${F}${String(L)}`,B=$p(M);return y||=B.truncated,B.value};_.stdout.on("data",(F)=>{f=R(f,F)}),_.stderr.on("data",(F)=>{h=R(h,F)}),_.once("error",m),_.once("exit",v);let C=()=>{try{if(J()==="win32"&&_.pid)$e(_.pid);else _.kill("SIGTERM")}catch{}};c.signal.addEventListener("abort",C,{once:!0});let A=setTimeout(()=>{S=!0,C()},c.timeoutMs)})}var _l=null;function Fp(){return _l??=Ji({scrubEnvironment:Al,spawnCaptured:mn,isProtectedPath:E}),_l}var is=async(e,l,c)=>{if(J()==="linux"||J()==="win32")return Fp()(e,l,c);if(J()!=="darwin"||!Xe("/usr/bin/sandbox-exec"))throw new r("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let p=wp(xl(xp(),"reason-device-"));try{return await mn("/usr/bin/sandbox-exec",["-p",Bp(c.root,p,c.allowWrite,c.allowProcessInspection===!0),e,...l],{cwd:c.cwd,timeoutMs:c.timeoutMs,signal:c.signal,env:Al(c.root,p)})}finally{vp(p,{recursive:!0,force:!0})}};function Up(e){let l=e.args;if(l===void 0)return[];if(!Array.isArray(l)||l.length>Ap)throw new r("invalid_payload","args must be a bounded string array.");return l.map((c)=>{if(typeof c!=="string"||c.includes("\x00")||Buffer.byteLength(c,"utf8")>Cl)throw new r("invalid_payload","Command argument is invalid or too large.");return c})}async function Ll(e,l,c,p={}){if(e.signal.aborted)throw new r("cancelled","Operation was cancelled.");let m=he(e.root),f=p.cwd??m,h=await e.runCommand(l,c,{cwd:f,root:m,allowWrite:p.allowWrite===!0,timeoutMs:p.timeoutMs??Hi,signal:e.signal});if(h.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(h.stderr))await e.emit("permission.denied",{operation:"bash",provenance:e.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:h.exitCode,signal:h.signal,stdout:h.stdout,stderr:h.stderr,timed_out:h.timedOut,truncated:h.truncated}}function kl(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EACCES"||l==="EPERM"}var Tl=()=>new r("path_unreadable","The path is not readable.");function Hp(e){try{return Rl(e,Ve.O_RDONLY)}catch(l){throw kl(l)?Tl():l}}function yl(e,l){let c=ge()?K():null;return c?Bt(c,{op:"fs",capability:e,root:l.root,payload:l.payload},l.signal).then((p)=>p.value):os(e,l)}function os(e,l){return e==="fs.read"?jp(l):Wp(l)}async function jp(e){let l=he(e.root),c=Dt(l,rn(e.payload,"path"));if(!xr(c).isFile())throw new r("not_a_file","Read target is not a file.");let p=_r(e.payload.offset,0,0,Number.MAX_SAFE_INTEGER),m=_r(e.payload.max_bytes,65536,1,El),f=$t(e.payload,"encoding");if(f!==void 0&&f!=="base64")throw new r("invalid_payload","encoding must be base64.");let h=Hp(c),y,S;try{y=vl(h).size;let _=Buffer.alloc(Math.max(0,Math.min(m,y-p)));S=_.subarray(0,_.byteLength?Sp(h,_,0,_.byteLength,p):0)}finally{Sl(h)}let w=f==="base64"||S.includes(0);return{path:Il(l,c),content:w?S.toString("base64"):S.toString("utf8"),encoding:w?"base64":"utf8",offset:p,bytes:S.byteLength,size:y,truncated:p+S.byteLength<y}}function qp(e,l,c=J()){let p=e==="append"?Ve.O_APPEND:Ve.O_TRUNC;if(c==="win32")return l?Ve.O_WRONLY|(e==="append"?Ve.O_APPEND:0):Ve.O_WRONLY|Ve.O_CREAT|Ve.O_EXCL;return Ve.O_WRONLY|Ve.O_NOFOLLOW|p|(l?0:Ve.O_CREAT|Ve.O_EXCL)}async function Wp(e){let l=he(e.root),c=rn(e.payload,"path"),p=Np(e.payload,"content",Ip),m=$t(e.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(m))throw new r("invalid_payload","mode must be create, overwrite, or append.");let f=Mp(l,c);if(e.payload.create_parents===!0||e.payload.create_directories===!0){bp(gr(f),{recursive:!0,mode:448});let w=Ye(gr(f));if(!ft(l,w))throw new r("symlink_escape","Write parent escaped root.")}if(!Xe(gr(f)))throw new r("path_not_found","Write parent does not exist.");if(m==="create"&&Xe(f))throw new r("path_exists","Create mode will not overwrite an existing file.");let h=Xe(f),y=h?Ii(f):null,S=Rl(f,qp(m,h),384);try{let w=vl(S),_=y??(J()==="win32"?Ii(f):null);if(_&&(w.ino!==_.ino||w.dev!==_.dev||J()==="win32"&&!ft(l,Ye(f))))throw new r("symlink_escape","The write target changed between validation and opening.");if(J()==="win32"&&y&&m!=="append")yp(S,0);Rp(S,p,null,"utf8")}finally{Sl(S)}return{path:Il(l,f),bytes_written:Buffer.byteLength(p,"utf8"),mode:m}}async function Vp(e){let l=he(e.root),c=rn(e.payload,"command",65536),p=Dt(l,$t(e.payload,"cwd")??".");if(!xr(p).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let m=_r(e.payload.timeout_ms,Hi,100,Ui);return Ll(e,Vi(),["-lc",c],{cwd:p,allowWrite:e.root.permissions.write,timeoutMs:m})}function Dl(e,l){let c=ie(e,l),p=c.boundary===e?e:Dt(c.anchor,Mi(c.anchor,c.boundary)||".");return{boundary:p,checkout:Dt(p,Mi(p,c.path)||".")}}async function zp(e){let l=Qi.safeParse(e.payload),c=e.worker;if(!l.success||!e.claimOwner||(c?!c.runtimeDirectory:J()!=="darwin"))throw new r("preview_unavailable","Preview servers are unavailable on this computer.");let p=he(e.root),{boundary:m,checkout:f}=Dl(p,l.data.workspace);if(!xr(f).isDirectory())throw new r("invalid_cwd","The Session checkout is not a directory.");let h=Math.min(Date.parse(l.data.expires_at),Date.now()+Yi);if(!(h>Date.now()))throw new r("process_authority_lost","The preview server lease is unavailable.");let y=(L)=>e.emit("progress",{process:L});if(!c?.runtimeDirectory){if(e.claim.local_github_authority)throw new r("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await fr({claim:e.claim,root:m,cwd:f,command:l.data.command,mode:"host",shell:bt(),environment:process.env,expiresAtMs:h,signal:e.signal,emit:y})}}let S={directory:xl(c.runtimeDirectory,"processes")},w={deniedPorts:mr([e.apiOrigin])},_=wr(),v=br(),R=ge(),C=l.data.egress?Ot(R):null;if(l.data.egress&&(C===null||!me(c.executionMode==="unsandboxed")))throw new r("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let A=l.data.egress?await Es(l.data.egress.allowed_domains):null,F=A?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((L)=>`${L}=${A.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",l.data.command].join(`
|
|
538
|
-
`):l.data.command;try{return{...await fr({claim:e.claim,root:f,cwd:f,command:F,mode:"host",shell:v,expiresAtMs:h,signal:e.signal,emit:y,...R?{jobsUser:{...R,...C!==null?{modelGid:C}:{}}}:{},environment:{..._.variables,HOME:_.home,PATH:_.path,TMPDIR:_.temporaryDirectory,SHELL:v},journals:S,preview:w})}}finally{A?.close()}}async function Gp(e){Jn();let l=he(e.root),c=Zn(e.payload.command),p=Dt(l,$t(e.payload,"cwd")??".");if(!xr(p).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let m=_r(e.payload.timeout_ms,ra,100,Kn),{ignored:f}=Qn(e.payload.env);return await e.emit("progress",{shell:bt(),shell_flags:[...nr],sandbox:"none",ignored_env:f}),oa({command:c,cwd:p,timeoutMs:m,signal:e.signal,spawn:e.spawnFullControl,requestEnv:e.payload.env})}async function Yp(e){let l=he(e.root),c=Up(e.payload),p=c[0];if(!p||!Pl.has(p)&&!$i.has(p))throw new r("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(c.some((h)=>h==="-C"||h==="-c"||h.startsWith("--git-dir")||h.startsWith("--work-tree")||h.startsWith("--config-env")||h.startsWith("--exec-path")))throw new r("git_argument_not_allowed","Git path/config overrides are not allowed.");let m=$i.has(p);if(m&&!e.root.permissions.write)throw new r("permission_denied","Mutating Git commands require the write grant.");let f=Dt(l,$t(e.payload,"cwd")??".");return Ll(e,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...c],{cwd:f,allowWrite:m||process.platform==="win32"&&e.root.permissions.write,timeoutMs:_r(e.payload.timeout_ms,Hi,100,Ui)})}function Nl(e,l){return async(c)=>{let p=await e.runCommand("/usr/sbin/lsof",c,{cwd:l,root:l,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:e.signal});if(e.signal.aborted)throw new r("cancelled","Operation was cancelled.");return p}}async function Kp(e){let l=he(e.root);if(J()==="linux")return fa(l);if(J()==="win32")return ho(l);return ba(l,Nl(e,l))}async function Xp(e){let l=he(e.root),c=l;if(e.payload.workspace!==void 0){let p=N(e.payload.workspace);if(!p)throw new r("invalid_workspace","The workspace is not a valid Device workspace.");c=Dl(l,p).checkout}if(J()==="linux")return ha(c);if(J()==="win32")return fo(c);return wa(c,Nl(e,l))}async function Jp(e){let l=e.worker?Pa(e.worker):null,c=e.claim.environment;delete e.claim.environment;let p=e.worker&&c&&qi({deviceId:e.deviceId},e.root.id,e.runId,c.payload,c.authority)?c.payload:void 0;return e.runHandsRelay({...e.claimedAtMs===void 0?{}:{claimedAtMs:e.claimedAtMs},claimOwner:e.claimOwner,...p?{claimEnvironment:p}:{},localGithubConfinement:Boolean(e.claim.local_github_authority),...e.worker?{headless:!0,runtimeDirectory:e.worker.runtimeDirectory,...e.worker.handsSlots?{handsSlots:e.worker.handsSlots}:{},...e.worker.ownComputer?{ownComputer:!0}:{},hostExecution:e.worker.executionMode==="unsandboxed",...e.worker.executionMode==="unsandboxed"&&e.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:e.deviceId,rootId:e.root.id,apiOrigin:e.apiOrigin},...l?{desktopRecording:l}:{}}:{},root:he(e.root),runId:e.runId,operationId:e.operationId,attemptId:e.attemptId,payload:e.payload,signal:e.signal,emitEvent:(m,f,h)=>e.emit(m,f,h)})}async function Zp(e){if(e.worker){if(!e.root.permissions.read||!e.root.permissions.write)throw new r("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:l,session:c}=eo(e.payload,e.operationId);return io({root:he(e.root),runId:e.runId,deviceId:e.deviceId,rootId:e.root.id,workspace:l,session:c,owner:e.claimOwner,authority:e.claimAuthority,signal:e.signal,emit:(p,m)=>e.emit(p,m)})}return e.runPtySession({root:he(e.root),runId:e.runId,operationId:e.operationId,payload:e.payload,signal:e.signal,emitEvent:(l,c)=>e.emit(l,c)})}function bl(e,l){let c=ge()?K():null;return c?Bt(c,{op:"transfer",direction:l,root:e.root,payload:e.payload,worker:Boolean(e.worker)},e.signal).then((p)=>p.value):ss(l,{root:e.root,payload:e.payload,signal:e.signal,worker:Boolean(e.worker),fetchImpl:e.fetchImpl,beforeCommit:()=>e.emit("progress",{phase:"file_transfer_verified"})})}async function ss(e,l){let c=he(l.root),p=er in l.payload;if(p&&!l.worker)throw new r("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let m=p?Zs(c,l.payload[er]):c;if("source"in l.payload||"source_version"in l.payload){if(e!=="export"||!p)throw new r("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let y=Us.safeParse(l.payload);if(!y.success)throw new r("invalid_payload","Invalid Cloud export request.");return Qs({runtimeRoot:m,source:y.data.source,url:y.data.url,signal:l.signal,fetchImpl:l.fetchImpl})}let f=rn(l.payload,"path",4096),h=e==="import"&&p?Yn(m):m;return Tt(ji(h,f)),yt({direction:e,root:h,path:f,payload:l.payload,signal:l.signal,fetchImpl:l.fetchImpl,beforeCommit:l.beforeCommit})}var Ml={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:(e)=>{if(!e.customEndpointCredential||!e.claimOwner)throw new r("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return rs({payload:e.payload,signal:e.signal,credential:e.customEndpointCredential,emit:(l,c)=>e.emit(l,c,e.signal)})}},"fs.read":{requiredPermission:"read",execute:(e)=>yl("fs.read",e)},"fs.write":{requiredPermission:"write",execute:(e)=>yl("fs.write",e)},"fs.export":{requiredPermission:"read",execute:(e)=>bl(e,"export")},"fs.import":{requiredPermission:"write",execute:(e)=>bl(e,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>J()==="darwin"&&Xn(),execute:zp},"exec.run":{requiredPermission:"execute",available:Bi,execute:Vp},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Xn(),execute:Gp},"git.run":{requiredPermission:"execute",available:()=>Bi()&&Tp("git"),execute:Yp},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:gl,execute:Kp},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:gl,execute:Xp},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>J()==="darwin"||Boolean(vn()),execute:Jp},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:Tn,execute:Zp},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:Ft,execute:(e)=>{let l=K();return l?Bt(l,{op:"display",payload:e.payload,proxy:(e.relay.loadProxy??j)()},e.signal):jt({payload:e.payload,signal:e.signal},e.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>Pn(),execute:(e)=>Rn({runId:e.runId,payload:e.payload,signal:e.signal,...e.worker?.userChrome?{userChrome:e.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:lr,execute:(e)=>ur({payload:e.payload,root:he(e.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:dl,execute:(e)=>ml({payload:e.payload,root:he(e.root),signal:e.signal},e.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:(e)=>oo({root:he(e.root),runId:e.runId,payload:e.payload,signal:e.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>J()==="darwin"?Xe("/usr/bin/sandbox-exec"):J()==="linux"||J()==="win32",execute:async(e)=>{let l=Pe.parse(e.payload),c=oe.parse(e.claim.local_github_authority);if(c.userId!==e.claimOwner?.user_id||c.deviceId!==e.deviceId||c.rootId!==e.root.id||c.runId!==e.runId||c.repoFullName!==l.repoFullName||!c.readOnly&&!e.root.permissions.write||!tt(l)&&(c.readOnly||c.generation===null&&!(l.kind==="pr_merge"&&c.merge?.source==="human")&&!(l.kind==="pr_mutation"&&c.contributorRefresh)))throw Error("local_device_gh_authority_changed");return so({root:he(e.root),runId:e.runId,request:l,authority:c,signal:e.signal,leaseUntil:e.claim.lease_until},(p)=>ws(l,p))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async(e)=>at({root:he(e.root),runId:e.runId,payload:e.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async(e)=>{if(!e.proveMac)throw new r("capability_unsupported","PR proof host is not installed.");return e.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:(e)=>ro({root:he(e.root),runId:e.runId,owner:e.claimOwner,payload:e.payload,signal:e.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:(e)=>no({root:he(e.root),runId:e.runId,owner:e.claimOwner,payload:e.payload,signal:e.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:zn,execute:(e)=>Xs(e.payload,e.signal)}};function Qp(e,l){try{let c=cs(e,Ye(l)),p=c?e.find((m)=>m.path===c):void 0;return p&&/^[a-f0-9]{64}$/.test(p.pathFingerprint)?p.pathFingerprint:void 0}catch{return}}function em(e,l){try{let c=Ye(l);return e.some((p)=>p.path===c)?Ir(c,J()):void 0}catch{return}}function tm(e,l){try{let c=Ye(l),p=e.find((m)=>m.path===c);return p&&/^[a-f0-9]{64}$/.test(p.pathFingerprint)?p.pathFingerprint:void 0}catch{return}}function rm(e,l){try{let c=Ye(l);if(!e.some((p)=>p.path===c))return;return e.filter((p)=>p.path!==c&&ft(c,p.path)&&/^[a-f0-9]{64}$/.test(p.pathFingerprint)).map((p)=>p.pathFingerprint)}catch{return}}function as(e,l,c=J()){try{return un({home:Ir(Ye(l),c),roots:e.map((p)=>({path_fingerprint:p.pathFingerprint,path:Ir(p.path,c)})).filter((p)=>/^[a-f0-9]{64}$/.test(p.path_fingerprint)&&Or(p.path)).slice(0,cn)})}catch{return}}function $s(e,l={}){let c=l.worker?l.worker.handsSlots??1:l.handsSlots===1?1:void 0,p=Boolean(l.worker)||J()==="darwin",m=p?tm(e,pr()):void 0,f=!l.worker&&J()==="darwin"?Qp(e,pr()):void 0,h=p?em(e,pr()):void 0,y=!l.worker&&J()==="darwin"?rm(e,pr()):void 0,S=p?as(e,pr()):void 0,w=ea.filter((_)=>{if(rr.has(_)&&!l.worker)return!1;if(l.worker&&!jr(_,l.worker))return!1;let v=Ml[_];if(!v)return!1;return(_==="hands.connect"&&(l.terminalOnlyHands===!0||Boolean(l.worker))||(_==="pty.start"||_==="preview.serve.v1")&&Boolean(l.worker)||_==="browser.pr-proof.v1"&&Boolean(l.productionProof)?!0:v.available?.()??!0)&&e.some((C)=>(!l.worker||_!=="pty.start"||C.permissions.read&&C.permissions.write)&&Ol(v).every((A)=>C.permissions[A]))});return{supported_operations:w,...m?{account_root_fingerprint:m}:{},...f?{workspace_root_fingerprint:f}:{},...h?{account_root_path:h}:{},...y?{home_contained_root_fingerprints:y}:{},...S?{root_paths:S}:{},...w.includes("hands.connect")?{hands_worker_artifact_sha256:b,hands_worker_entrypoint:T,...c?{hands_slots:c}:{}}:{},max_payload_bytes:Re,max_result_bytes:Re,operation_constraints:{...w.includes("browser.pr-proof.v1")&&l.productionProof?{"browser.pr-proof.v1":Cn.parse(l.productionProof)}:{},...w.includes("exec.run")?{"exec.run":{transport:"shell",shell:Vi(),sandbox:J()==="linux"?"linux_sandbox_runtime":J()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:Ui}}:{},...w.includes("exec.full")?{"exec.full":ia()}:{},"git.run":{read_only_subcommands:[...Pl].sort(),mutating_subcommands:[...$i].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:Ze,max_timeout_ms:Qt,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:Ze,max_timeout_ms:Qt,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:O,protocol_version:P,worker_artifact_sha256:b,worker_entrypoint:T,policy_mode:"full_access",policy_version:1,workspace_base:ue,workspace_layout:X,...c?{slots:c}:{},browser_state:l.worker?"optional_headless":l.terminalOnlyHands===!0?"disabled_terminal_only":J()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...w.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:Tr,max_session_ms:Rr,max_buffered_output_bytes:Ht}}:{},...l.worker?Object.fromEntries(w.filter((_)=>_!=="browser.pr-proof.v1").map((_)=>[_,{ready:l.worker?.readiness?.[_]===!0,...l.worker?.readiness?.[_]!==!0&&l.worker?.probing?.includes(_)?{probing:!0}:{},execution_mode:jr(_,{...l.worker,executionMode:"sandboxed"})?"confined":"host",..._==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:Vt,environment:"private_snapshot",receipt:"metadata_only",...l.worker?.persistentTerminals&&!ge()?{persistent_terminals:!0}:{}}:{},..._===nt?{max_body_bytes:xt}:{},..._==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...l.worker?.githubSignedIn!==void 0?{gh_authenticated:l.worker.githubSignedIn}:{}}:{},..._==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:c,session_group:xi,...l.worker?.ownComputer?{[ki]:Ci}:{},workspace_base:ue,workspace_layout:X,browser_state:"optional_headless",desktop:!1,worker_version:O,protocol_version:P,...l.worker?.readiness?.["environment.install"]===!0&&w.includes("environment.install")?{environment_delivery:oi,[ui]:li}:{},...l.worker?{[fi]:hi}:{},...l.worker?{[pi]:di}:{},...l.worker?.handsBrowser?{[wi]:yi}:{},[_i]:gi,[vi]:bi,...me(l.worker?.executionMode==="unsandboxed")?{[Z]:pe}:{},...me(l.worker?.executionMode==="unsandboxed")&&Ot()!==null?{[q]:Te}:{},...me(l.worker?.executionMode==="unsandboxed")&&ge()?{[Ei]:Si}:{}}:{},..._==="fs.export"?{cloud_source_version:$r,source_kinds:["workspace","attachment"],[Dn]:Nn}:{},..._==="fs.import"?{[Dn]:Nn}:{},..._===Xi&&Ot()!==null&&me(l.worker?.executionMode==="unsandboxed")?{[Zi]:_n}:{},..._==="tunnel.open"?{carried_jobs:Ai}:{},..._==="jobs.control"?{[Ri]:Pi}:{},..._==="display.stream.v1"&&l.worker?.displayVideo?{[ko]:xo,[Co]:ht.join(","),[Ao]:Po,[Ro]:To,[Io]:Do}:{},..._==="automation.call.v1"&&l.worker?.userChrome?{[St]:!0}:{},..._==="automation.call.v1"&&l.worker?.cloudSessions?{[Ti]:!0}:{}}])):{}}}}function qi(e,l,c,p,m){let f=yr.safeParse(p);return f.success&&m!==void 0&&m.device_id===e.deviceId&&f.data.device_id===e.deviceId&&f.data.root_id===l&&f.data.run_id===c&&f.data.binding.kind===m.binding&&f.data.binding.target_revision===m.target_revision&&f.data.binding.root_grant_revision===m.root_grant_revision&&f.data.binding.target_generation===m.target_generation&&f.data.binding.target_fence_id===m.target_fence_id}async function Ms(e,l,c,p,m){if(l.capability!=="hands.connect"||c.kind!==vt||!p.operationEnvironment||!p.acknowledgeOperationEnvironment)return!1;let f=c.payload.snapshot_id;if(c.payload.version!==1||typeof f!=="string"||Object.keys(c.payload).length!==2)throw new r("environment_unavailable","Reason sent an invalid environment delivery.");let h=e.roots.find((w)=>w.id===l.root_id);if(!h)throw new r("root_not_granted","The Hands root is no longer granted.");let y=await p.operationEnvironment(e,l,f,m);if(!qi(e,h.id,l.run_id,y.payload,y.authority)||y.payload.snapshot_id!==f)throw new r("environment_unavailable","The delivered environment does not match this Hands.");let S=at({root:he(h),operationId:l.operation_id,payload:y.payload});return await p.acknowledgeOperationEnvironment(e,l,{snapshot_id:S.snapshot_id,installed_revision:S.installed_revision,installed:!0},m),!0}async function Bs(e,l,c,p){if(l.capability!=="hands.connect"||c.kind!==mi)return!1;let{version:m,run_id:f,target_generation:h,target_fence_id:y}=c.payload;if(m!==1||Object.keys(c.payload).length!==4||typeof f!=="string"||typeof h!=="number"||typeof y!=="string")throw new r("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let S=e.roots.find((w)=>w.id===l.root_id);if(!S)throw new r("root_not_granted","The Hands root is no longer granted.");return await to({operationId:l.operation_id,root:he(S),runId:f,targetGeneration:h,fenceId:y,...p?{signal:p}:{}}),!0}async function Fs(e,l,c){if(l.capability!=="github.local.v1")return wl(e,l,c);try{let p=await wl(e,l,c);if(p.status==="succeeded"||ni(l.payload,p.status,p.error_code))return p;return{status:p.status,error_code:p.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:c.signal.aborted?"cancelled":"failed",error_code:c.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function wl(e,l,c){if(rr.has(l.capability)&&!c.worker)return{status:"failed",error_code:"capability_not_granted"};if(c.worker&&!jr(l.capability,c.worker))return{status:"failed",error_code:"capability_not_granted"};if(c.worker&&c.worker.readiness?.[l.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(l.local_github_authority){let _=oe.safeParse(l.local_github_authority);if(!_.success||_.data.deviceId!==e.deviceId||_.data.rootId!==l.root_id||_.data.runId!==l.run_id||_.data.userId!==l.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(l.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let p=Ml[l.capability];if(!p)return{status:"failed",error_code:"capability_unsupported"};if(p.available&&!p.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(l.capability)&&c.worker)&&!c.runCommand&&!c.runHandsRelay&&!c.spawnFullControl&&!c.runPtySession&&!(l.capability==="browser.pr-proof.v1"&&c.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(l.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let m=e.roots.find((_)=>_.id===l.root_id);if(!m)return{status:"failed",error_code:"root_not_granted"};if((l.capability==="fs.export"||l.capability==="fs.import")&&Fi(l.payload)&&(("source"in l.payload)||("source_version"in l.payload))){let _=Boolean(c.worker||e.worker)&&er in l.payload;if(l.capability!=="fs.export"||!_)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(l.owner&&(l.owner.device_id!==e.deviceId||l.owner.organization_id!==e.orgId))return{status:"failed",error_code:"capability_not_granted"};if((l.capability==="tunnel.open"||l.capability==="tunnel.close")&&!l.owner)return{status:"failed",error_code:"preview_unavailable"};if(l.capability==="environment.install"&&!qi(e,m.id,l.run_id,l.payload,l.authority))return{status:"failed",error_code:"environment_unavailable"};if(Ol(p).some((_)=>!m.permissions[_]))return{status:"failed",error_code:"permission_denied"};let f=0,h=async(_,v,R)=>{if(["environment.install","github.local.v1"].includes(l.capability)||l.capability==="inference.custom.v1"&&(_==="started"||_==="completed"))return;await c.emit?.({sequence:f++,kind:_,capability:l.capability,data:v,...(_==="hands.reconnected"||l.capability==="inference.custom.v1")&&R?{deliverySignal:R}:{}})},y=l.capability==="hands.connect"||l.capability==="display.stream.v1"||l.capability==="simulator.stream.v1"||ns.has(l.capability)||l.capability==="pty.start",S,w=async(_,v,R)=>{let C=S;S=void 0,await Promise.all([C,h(_,v,R)])};try{if(y)S=h("started"),S.catch(()=>{return});else await h("started");let _={...c.proxy===void 0?{}:{loadProxy:()=>c.proxy??null},...c.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:c.handsLaunch.takePrespawnedWorker}:{},...c.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:c.handsLaunch.adoptSpawnedWorker}:{}},v=await p.execute({...c.proveMac?{proveMac:()=>c.proveMac(l,c.signal,(R)=>h("pr-proof.started.v1",R))}:{},claim:l,worker:c.worker,claimOwner:l.owner,claimAuthority:l.authority,organizationId:e.orgId,deviceId:e.deviceId,apiOrigin:e.apiOrigin,root:m,payload:Dp(l.payload,l.capability),runId:l.run_id,operationId:l.operation_id,attemptId:l.attempt_id,...c.handsLaunch?{claimedAtMs:c.handsLaunch.claimedAtMs}:{},signal:c.signal,...c.customEndpointCredential?{customEndpointCredential:c.customEndpointCredential}:{},fetchImpl:c.fetchImpl??fetch,relay:_,runCommand:c.runCommand??is,spawnFullControl:c.spawnFullControl??mn,emit:y?w:h,runHandsRelay:c.runHandsRelay??((R)=>Nt(R,_)),runPtySession:c.runPtySession??In});if(l.capability==="github.local.v1")Go.parse(v);if(!Fi(v))throw new r("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(v)??"null","utf8")>Re)throw new r("result_too_large","Operation result exceeds 256 KB.");return await(y?w:h)("completed",{ok:!0}),{status:"succeeded",result:v,error_code:null}}catch(_){let v=c.signal.reason instanceof r&&fl.has(c.signal.reason.code)?c.signal.reason.code:_ instanceof r&&fl.has(_.code)?_.code:null;if(c.signal.aborted||v)return{status:"cancelled",..._ instanceof st?{result:{process_terminal_observation:_.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(l.capability)?"operation_cancelled":v??"cancelled"};if(["fs.read","fs.write"].includes(l.capability)&&_ instanceof Error&&"code"in _&&["EACCES","EPERM"].includes(String(_.code)))await h("permission.denied",{operation:l.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let R=l.capability==="inference.custom.v1"?_ instanceof r&&Li(_.code)?_.code:"custom_endpoint_unavailable":l.capability==="github.local.v1"?_ instanceof sr&&ni(l.payload,"failed",_.code)?_.code:"local_github_unavailable":l.capability==="environment.install"?"environment_install_failed":_ instanceof r&&Lp.test(_.code)?_.code:"capability_failed",C=l.capability==="hands.connect"&&_ instanceof Er?ao(_.expiryDiagnostic):null;return await h("completed",{ok:!1,error_code:R,...C?{expiry_diagnostic:C}:{}}),{status:"failed",error_code:R}}}
|
|
539
|
-
export{fn,ns,Vi,mn,is,os,ss,as,$s,Ms,Bs,Fs};
|