@reason-machines/cli-linux-x64 0.2.559 → 0.2.561
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-kk36zca7.js +2 -0
- package/bin/vm-hands/api-credentials-mtfdk175.js +2 -0
- package/bin/vm-hands/api-w6w7vfp3.js +2 -0
- package/bin/vm-hands/ask-relay-xx0rzpch.js +5 -0
- package/bin/vm-hands/connect-cli-dmwph620.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-vvt9d9xb.js +2 -0
- package/bin/vm-hands/local-capabilities-pwv76ns5.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-axh9mfdk.js +2 -0
- package/bin/vm-hands/local-display-video-pxhztqk7.js +2 -0
- package/bin/vm-hands/local-managed-process-4mgqn7tg.js +2 -0
- package/bin/vm-hands/local-pty-session-edd8ttf9.js +2 -0
- package/bin/vm-hands/managed-runtime-pcagtyfz.js +2 -0
- package/bin/vm-hands/network-auto-update-wkzb91qz.js +3 -0
- package/bin/vm-hands/network-contract-8mxtma3w.js +2 -0
- package/bin/vm-hands/network-sign-in-61gmpmaa.js +3 -0
- package/bin/vm-hands/package-vwvzjtn0.js +2 -0
- package/bin/vm-hands/permissions-348prrcx.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-1nkpw1v3.js +2 -0
- package/bin/vm-hands/serve-service-3dkyznay.js +2 -0
- package/bin/vm-hands/status-khqk4cjw.js +96 -0
- package/bin/vm-hands/version-c1hen0wn.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-0wb1n769.js +9 -0
- package/bin/vm-hands/{vm-hands-entry-lite-506b6pcz.js → vm-hands-entry-lite-2dak7e1h.js} +5 -5
- 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-52qz0n30.js +7 -0
- package/bin/vm-hands/vm-hands-entry-lite-57ajjwmh.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-5y4phfv1.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-6jxshhps.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-71ebge0c.js +42 -0
- package/bin/vm-hands/vm-hands-entry-lite-7pfhwxn5.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-84mc1f7h.js +3 -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-8rmbdm6c.js → vm-hands-entry-lite-9yfmkd1f.js} +2 -2
- 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-bj3w2ven.js +3 -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-gxpw14jv.js +11 -0
- package/bin/vm-hands/vm-hands-entry-lite-h7nk2848.js +539 -0
- package/bin/vm-hands/vm-hands-entry-lite-hjjbjpd7.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-hn9pq7zj.js +127 -0
- package/bin/vm-hands/vm-hands-entry-lite-hs6sdn60.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-ht6hzkgj.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-jgk5z8zc.js +10 -0
- 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-m1we91g4.js +105 -0
- 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-q9djb28r.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-q9s1e2y1.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-sy7dcccg.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-tcmye5ny.js +3 -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-vkhacd00.js +452 -0
- package/bin/vm-hands/vm-hands-entry-lite-wcgm41jq.js +52 -0
- package/bin/vm-hands/vm-hands-entry-lite-weqam12f.js +6 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jrce7v4r.js → vm-hands-entry-lite-xvccy3z4.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-y3nz20wb.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-z213y4pj.js +150 -0
- 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-csdtg7kj.js} +8 -8
- package/bin/vm-hands/vm-hands-op-runner-z7tsd84c.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-889hfy4p.js → vm-hands-runtime-1qxf96z7.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
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{rr,Dr,Bn,qi,Or,Nr,na,Wi,ia,oa,Lr}from"./vm-hands-entry-lite-57ajjwmh.js";import{xt,Ln,ds,Ar,Fc,Ke,jc,Hc,Qt,Je,M,Ct,fs,$n,ms,Rr,bs,vs,Ss,Es,ks,xs,Cs,As,Ps,Rs,Ts,Is,Ds,at,Le,At,xe,Os,Ns,Ls,$s,Ms,Bs,Fs,js,Tr,Hs,Ir,zs,zi,qs,Ws,Vs,Gs,Ks,Js,Xs,Ys,Zs,Qs,ea,ta,ra}from"./vm-hands-entry-lite-71ebge0c.js";import{st,Oe,X,te}from"./vm-hands-entry-lite-9g52kxyj.js";import{F,pn}from"./vm-hands-entry-lite-jpvmkce5.js";import{ei,Ma,Ba,Ze,Fa,ja,Xr,Ha,Ua,za,ri,ii,oi,wo,bo,si,Ka,vo,ai,Pe,J,Qr,ci,ui,Qe}from"./vm-hands-entry-lite-vkhacd00.js";import{U,H,R}from"./vm-hands-entry-lite-v4hr9x9h.js";import{Ta,Ia,fo,Oa,mo,Na,lr,Xn}from"./vm-hands-entry-lite-5y4phfv1.js";import{ue}from"./vm-hands-entry-lite-q9djb28r.js";import{je}from"./vm-hands-entry-lite-weqam12f.js";import{Se}from"./vm-hands-entry-lite-pxtycfdv.js";import{Gn,Kn,Pa}from"./vm-hands-entry-lite-52qz0n30.js";import{vc,Sc,Sr,Ec,kc,xc,Cc,Ac,Pc,Rc}from"./vm-hands-entry-lite-j10cw3d9.js";import{mi,an,gi,Lo,$o}from"./vm-hands-entry-lite-hxfxs7r9.js";import{on,Ft,sn}from"./vm-hands-entry-lite-z213y4pj.js";import{Go,T,dc}from"./vm-hands-entry-lite-hn9pq7zj.js";import{yc,wc}from"./vm-hands-entry-lite-wcgm41jq.js";import{nn,hr,Oo}from"./vm-hands-entry-lite-2dak7e1h.js";import{et,Za,Qa}from"./vm-hands-entry-lite-0wb1n769.js";import{rn}from"./vm-hands-entry-lite-tcmye5ny.js";import{q}from"./vm-hands-entry-lite-a6ss0ges.js";import{bt,Cn,An,Pn,L}from"./vm-hands-entry-lite-ptycjmkc.js";import{s,Ve}from"./vm-hands-entry-lite-zawytz09.js";import{t,V,o,_,d,n,we,A,$e,c,i,qc}from"./vm-hands-entry-lite-k5ytpgzz.js";import{Y,Me,It,Be,Ki}from"./vm-hands-entry-lite-8xv6c0rm.js";import{Dt}from"./vm-hands-entry-lite-ab1pq3xg.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{request as ic}from"http";import{request as sc}from"https";import{lookup as ac}from"dns/promises";import{isIP as lc}from"net";async function cc(e){let a=new URL(e.url);return await new Promise((l,u)=>{let p=(a.protocol==="https:"?sc:ic)(a,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:na},(m)=>l({response:m,close:()=>{m.destroy(),p.destroy(),m.socket?.destroy()}}));p.once("error",u),p.once("timeout",()=>p.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),p.end(e.body)})}var hi=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),uc=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function _i(e,a=0){if(!e||typeof e!=="object"||a>3)return null;let l=e.code;if(typeof l==="string"){if(hi.has(l))return"custom_endpoint_host_not_found";if(uc.has(l))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(l))return"custom_endpoint_tls_failed"}for(let u of[...e instanceof AggregateError?e.errors:[],e.cause]){let p=_i(u,a+1);if(p)return p}return null}async function pc(e,a){let l=_i(e),u=new URL(a).hostname.replace(/^\[|\]$/g,"");if(l!==null&&l!=="custom_endpoint_connection_failed"||lc(u)!==0)return l;let p;return await Promise.race([ac(u).then(()=>!0,(f)=>!hi.has(String(f?.code))),new Promise((f)=>{p=setTimeout(()=>f(!0),5000)})]).finally(()=>clearTimeout(p))?l:"custom_endpoint_host_not_found"}function mc(e){for(let a=42;;a++){if(a===127)a=256;let l=String.fromCodePoint(a);if(!e.includes(l))return l}}function fc(e,a){let l=Buffer.from(e),u=Buffer.from(a),p=new Uint32Array(l.length);for(let f=1,g=0;f<l.length;f++){while(g&&l[f]!==l[g])g=p[g-1];if(l[f]===l[g])g++;p[f]=g}let m=0;return(f,g=!1)=>{let b=Buffer.allocUnsafe(f.length*u.length+m),y=0;for(let h of f){while(m&&l[m]!==h){let w=p[m-1];y+=l.copy(b,y,0,m-w),m=w}if(l[m]===h){if(m++,m===l.length)y+=u.copy(b,y),m=0}else b[y++]=h}if(g)y+=l.copy(b,y,0,m),m=0;return b.subarray(0,y)}}async function yi(e){e.signal.throwIfAborted();let a=ia.safeParse(e.payload);if(!a.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let l=a.data,u=oa.parse(await e.credential(e.signal));if(!Wi(l,{baseUrl:l.baseUrl,api:u.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let p,m,f=0,g=0,b=0,y=mc(u.apiKey),h=fc(u.apiKey,y),w=async(v,x)=>{e.signal.throwIfAborted(),await new Promise((I,E)=>{let C=()=>{e.signal.removeEventListener("abort",C),E(e.signal.reason)};if(e.signal.addEventListener("abort",C,{once:!0}),e.signal.aborted){C();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(v,x))).then(()=>{e.signal.removeEventListener("abort",C),I()},(O)=>{e.signal.removeEventListener("abort",C),E(O)})})},S=async(v)=>{if(f+=v.length,f>Bn)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let x=0;x<v.length;x+=Dr){if(b>=qi)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await w(`custom_endpoint.chunk.${b++}`,{eof:!1,data:v.subarray(x,x+Dr).toString("base64")})}};try{let v=await cc({url:l.url,body:l.body,signal:e.signal,headers:{...l.headers,...u.api==="anthropic-messages"?{"x-api-key":u.apiKey}:{authorization:`Bearer ${u.apiKey}`}}});p=v.response,m=v.close;let x=p.statusCode??500;if(x>=300&&x<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(p.headers["content-encoding"]&&p.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let I={};for(let E of["content-type","retry-after","x-request-id","request-id"]){let C=p.headers[E];if(typeof C==="string")I[E]=C.replaceAll(u.apiKey,y).slice(0,4096)}await w("custom_endpoint.headers",{status:x,statusText:(p.statusMessage??"").replaceAll(u.apiKey,y).slice(0,256),headers:I});for await(let E of p){e.signal.throwIfAborted();let C=Buffer.isBuffer(E)?E:Buffer.from(E);if(g+=C.length,g>Bn)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await S(h(C))}return await S(h(Buffer.alloc(0),!0)),await w(`custom_endpoint.chunk.${b}`,{eof:!0}),{bytes:f,chunks:b}}catch(v){if(e.signal.throwIfAborted(),v instanceof r)throw v;throw new r((p?null:await pc(v,l.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{m?.()}}import{join as bi}from"path";function hc(e,a){return e===bi(a,".ara","workspace")||e===bi(a,".reason","workspace")}function wi(e,a){let l=e.filter((u)=>hc(u.path,a));return l.length===1?l[0].path:null}var gc=/^[a-f0-9]{64}$/;var Jr=32,_c=/^\/[^\x00-\x1f\x7f\\]*$/;function tr(e){if(typeof e!=="string"||e.length>4096||!_c.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((a)=>a!==""&&a!=="."&&a!=="..")}function nr(e,a){let l=a==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!l)return e;let u=l[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${l[1].toUpperCase()}:${u?`/${u}`:""}`}function ir(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let a=e;if(!tr(a.home)||!Array.isArray(a.roots)||a.roots.length>Jr)return;let l=[];for(let u of a.roots){if(!u||typeof u!=="object"||Array.isArray(u))return;let{path_fingerprint:p,path:m}=u;if(typeof p!=="string"||!gc.test(p)||!tr(m))return;l.push({path_fingerprint:p,path:m})}return{home:a.home,roots:l}}function bc(e){let a=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&a?a:void 0}function Oc(e){return bc(e)??e.email.toLowerCase()}function Zr(e){let a=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return a?Oc({name:a[1],email:a[2]}):e.trim().toLowerCase()}var Lt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(a)=>`[${a.toLowerCase()}${a.toUpperCase()}]`),Ic=[...bt.map((e)=>`/(${e.map(Lt).join("/")})(/|$)`),...Cn.map((e)=>`/(${e.map(Lt).join("/")})(/|$)`),...[...An].map((e)=>`/(${Lt(e)})$`),`/${Lt(".env.")}[^/]*$`,...Pn.map((e)=>`/[^/]*${Lt(e)}$`)],Si=`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(Ic)}.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 Dc}from"child_process";import*as z from"fs";import*as oe from"path";import{homedir as Nc}from"os";function vi(e,a,l,u="gh"){if(!["gh","git"].includes(u))throw Error("local_device_gh_unavailable");let p=e.realpathSync(l);if(process.platform==="win32"){let f=(g)=>g.toLowerCase()===p.toLowerCase()||g.toLowerCase().startsWith(p.toLowerCase()+a.sep);for(let g of new Set([process.env.ProgramW6432,process.env.ProgramFiles])){if(!g)continue;try{let b=e.realpathSync(u==="gh"?`${g}\\GitHub CLI\\gh.exe`:`${g}\\Git\\cmd\\git.exe`);if(!f(b)&&b.toLowerCase().startsWith(g.toLowerCase()+"\\")&&e.statSync(b).isFile())return b}catch{}}throw Error("local_device_gh_unavailable")}let m=u==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+u;for(let f of["/opt/homebrew/bin/"+u,"/usr/local/bin/"+u,m])try{let g=e.realpathSync(f);if(g===p||g.startsWith(p+a.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...u==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((y)=>g.startsWith(y)))continue;let b=e.statSync(g);if(!b.isFile()||(b.mode&18)!==0||![0,process.getuid()].includes(b.uid))continue;return e.accessSync(g,e.constants.X_OK),g}catch{continue}throw Error("local_device_gh_unavailable")}function Ri(e,a){let l=1;for(let u=0;u<a;u+=1)if(e.charCodeAt(u)===10)l+=1;return l}var xi=[{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 en(e){let a=e.trim().replaceAll("\\","/");if(!a)return{valid:!1,reason:"empty_path"};if(a.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(a.split("/").includes("..")||a.includes("../")||a.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(a===".git"||a.startsWith(".git/")||a.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function Ei(e){return[...new Set(e.map((a)=>a.trim()).filter((a)=>a.length>=8))]}function Ci(e,a){return[...a.matchAll(new RegExp(e.regex.source,`${e.regex.flags}g`))]}function cr(e,a=[],l={}){let u=[],p=l.published??new Set,m=Ei(a).filter((f)=>!p.has(f));for(let f of e){let g=en(f.path);if(!g.valid){u.push({path:f.path,reason:g.reason??"invalid_path"});continue}let b=f.content??"",y=m.map((h)=>({secret:h,offset:b.indexOf(h)})).filter((h)=>h.offset>=0).sort((h,w)=>h.offset-w.offset);if(y.length>0){let h=[...new Set(y.flatMap((w)=>l.secretNames?.(w.secret)??[]))];u.push({path:f.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:Ri(b,y[0].offset),...h.length>0?{secretNames:h}:{}})}for(let h of xi){let w=Ci(h,b).find((S)=>!p.has(S[0]));if(w){u.push({path:f.path,reason:`credential_pattern_detected: ${h.name}`,pattern:h.name,ruleId:h.name,line:Ri(b,w.index)});break}}}return{clean:u.length===0,violations:u,scannedObjectCount:e.length}}function Pi(e,a=[]){let l=Ei(a),u=new Set;for(let{content:p}of e){for(let m of l)if(p.includes(m))u.add(m);for(let m of xi)for(let f of Ci(m,p))u.add(f[0])}return[...u]}function Lc(e,a){let l=0;for(let u=e.indexOf(a);u>=0;u=e.indexOf(a,u+a.length))l+=1;return l}function Oi(e,a,l){let u=(p,m)=>p.reduce((f,g)=>f+Lc(g,m),0);return new Set(e.filter((p)=>u(a,p)<=u(l,p)))}var dt=4194304,Fe=process.platform==="win32",Tt=process.env.SystemRoot??"C:\\Windows",Mc=(e)=>Fe?Dc(oe.win32.join(Tt,"System32","taskkill.exe"),["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-e,"SIGKILL"),kt=Fe?[oe.win32.join(Tt,"System32"),Tt].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",ur=Fe?{SystemRoot:Tt,WINDIR:Tt}:{},$c=(e)=>Fe?oe.win32.resolve(e,"..","..","bin","sh.exe"):"/bin/sh",Ii=536870912,tn=/^[a-f0-9]{40}$/,Bc=(e,a,l)=>new Promise((u)=>{if(l.signal?.aborted){u({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let p;try{p=Tc(e,a,{cwd:l.cwd,env:l.env,...Fe?{windowsHide:!0}:{detached:!0},stdio:["pipe","pipe","pipe"]})}catch{u({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let m=Buffer.alloc(0),f=Buffer.alloc(0),g,b=!1,y=(v)=>{if(g??=Error(v),p.pid)try{Mc(p.pid)}catch{}},h=()=>y("cancelled"),w=setTimeout(()=>y("timeout"),l.timeout);l.signal?.addEventListener("abort",h,{once:!0});let S=(v)=>{if(b)return;b=!0,clearTimeout(w),l.signal?.removeEventListener("abort",h),u({status:v,stdout:m,stderr:f,...g?{error:g}:{}})};if(p.stdout.on("data",(v)=>{if(m.length+f.length+v.length>l.maxBuffer)y("output_limit");else m=Buffer.concat([m,v])}),p.stderr.on("data",(v)=>{if(m.length+f.length+v.length>l.maxBuffer)y("output_limit");else f=Buffer.concat([f,v])}),p.on("error",()=>{if(y("spawn_failed"),!p.pid)S(null)}),p.on("close",(v)=>S(v)),p.stdin.on("error",()=>y("input_failed")),p.stdin.end(l.input),l.signal?.aborted)h()}),Uc={command:Bc,gh:(e,a)=>vi(z,oe,e,a),home:Nc};function N(e){throw Error(e)}function ln(e,a){let[l,u]=Fe?[e.toLowerCase(),a.toLowerCase()]:[e,a];return u===l||u.startsWith(l+oe.sep)}function Wc(e,a){let l=new Set(e.split(/\r?\n/).map(Zr));return a.filter((u)=>{let p=Zr(u);if(l.has(p))return!1;return l.add(p),!0})}var Vc=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),zc=(e)=>JSON.stringify(e,(a,l)=>Vc.has(a)?void 0:l);function Ai(e,a,l){let u=[...new Set(e.map((m)=>`${a(m.path)}${m.line?`:${m.line}`:""} (${m.reason==="literal_secret_detected"?`value of ${m.secretNames?.length?m.secretNames.slice(0,3).join(", "):"a session variable"}`:`${m.ruleId??"credential"} credential`})`))].slice(0,10),p=e.some((m)=>m.reason==="literal_secret_detected");N(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${u.join("; ")}. Nothing was sent. ${l}${p?" 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 Li(e,a,l=Uc){let u=xt.parse(e),p="local_device_gh_prepare_setup";try{if(!["darwin","linux","win32"].includes(process.platform))N("local_device_gh_platform_unavailable");a.assertCurrent();let m=z.realpathSync(a.root);if(m===oe.parse(m).root)N("local_device_gh_root_unavailable");if(!Qt(u)&&!a.forbiddenSecretValues)N("local_device_gh_secret_scope_unavailable");if(!Qt(u)&&a.readOnly)N("local_device_gh_read_only");if(!Qt(u)){let P=cr([{path:"github-operation",content:zc(u)}],a.forbiddenSecretValues,a.secretNames?{secretNames:a.secretNames}:{});if(!P.clean)Ai(P.violations,()=>`the ${u.kind} request text`,"Remove it from the pull request text and try again.")}let f=l.gh(m),g=l.home(),b=l.gh(m,"git"),y=a.privateDirectory?z.realpathSync(a.privateDirectory):z.realpathSync(g);if(!Qt(u)&&(!a.privateDirectory||ln(m,y)))N("local_device_gh_private_scope_unavailable");let h={...ur,PATH:Fe?[oe.dirname(b),kt].join(";"):kt,HOME:g,GH_CONFIG_DIR:Fe&&process.env.APPDATA?oe.join(process.env.APPDATA,"GitHub CLI"):oe.join(g,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:Fe?"":"/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((P)=>process.env[P]?[[P,process.env[P]]]:[])):{}},w=async(P,j,W=y,Z,ie=dt)=>{a.assertCurrent();let se=await l.command(P,j,{cwd:W,env:h,input:Z,maxBuffer:ie,timeout:Math.max(1,Math.min(60000,(a.deadlineMs??Date.now()+60000)-Date.now())),signal:a.signal});if(a.assertCurrent(),se.error||se.status!==0)N("local_device_gh_command_failed");return se.stdout},S=async(P)=>(await w(f,P)).toString("utf8").trim(),v=async(P,j="application/vnd.github+json")=>{jc(u.repoFullName,P,{headers:{accept:j}}),a.assertCurrent();let W=await l.command(f,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${j}`,P],{cwd:y,env:h,maxBuffer:dt,timeout:Math.max(1,Math.min(25000,(a.deadlineMs??Date.now()+25000)-Date.now())),signal:a.signal});if(a.assertCurrent(),W.error&&W.status===null)N("local_device_gh_response_unavailable");let Z=W.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!Z)N("local_device_gh_response_invalid");let ie=Number(Z[1]);if(ie>=200&&ie<300&&W.status!==0)N("local_device_gh_response_unavailable");if(Buffer.byteLength(Z[3])>Ar)N("local_device_gh_response_too_large");let se={};for(let ye of Z[2].split(/\r?\n/)){let Re=ye.indexOf(":"),tt=ye.slice(0,Re).toLowerCase();if(["link","content-type"].includes(tt))se[tt]=ye.slice(Re+1).trim().slice(0,8192)}return{kind:"read",status:ie,headers:se,body:ie>=200&&ie<300?Z[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(u.kind==="read")return v(u.path,u.accept);if(u.kind==="pr_review_context"){let[P,j]=u.repoFullName.split("/"),W=await S(["api","graphql","--hostname","github.com","-f",`query=${Hc}`,"-f",`owner=${P}`,"-f",`repo=${j}`,"-F",`number=${u.number}`,...u.after?["-f",`after=${u.after}`]:[]]);if(Buffer.byteLength(W)>Ar)N("local_device_gh_response_too_large");let Z=JSON.parse(W);if(Z.errors||Z.data?.repository?.nameWithOwner?.toLowerCase()!==u.repoFullName.toLowerCase()||Z.data.repository.pullRequest?.number!==u.number)N("local_device_gh_response_invalid");return{kind:"pr_review_context",body:W}}if(u.kind==="pr_merge"){let P=await v(`/repos/${u.repoFullName}/pulls/${u.number}`),j=JSON.parse(P.body),W=(se)=>se.number===u.number&&se.html_url===`https://github.com/${u.repoFullName}/pull/${u.number}`&&se.base?.repo?.full_name?.toLowerCase()===u.repoFullName.toLowerCase()&&se.base?.ref===u.expectedBaseRef&&se.head?.sha===u.expectedHeadSha;if(P.status!==200||!W(j)||j.state!=="open"||j.draft!==!1||j.head?.sha!==u.expectedHeadSha||j.base?.repo?.full_name?.toLowerCase()!==u.repoFullName.toLowerCase())N("local_device_gh_merge_target_changed");await S(["pr","merge",String(u.number),`--repo=${u.repoFullName}`,`--${u.method}`,"--match-head-commit",u.expectedHeadSha,...u.commitBody!==void 0&&u.method!=="rebase"?[`--body=${u.commitBody}`]:[]]);let Z=await v(`/repos/${u.repoFullName}/pulls/${u.number}`),ie=JSON.parse(Z.body);if(Z.status!==200||!W(ie)||ie.merged!==!0)N("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:u.number,merged:!0}}if(u.kind==="pr_create"){if(u.head===u.base)N("local_device_gh_default_branch");let P=await S(["pr","create","--repo",u.repoFullName,"--head",u.head,"--base",u.base,`--title=${u.title}`,`--body=${u.body}`,...u.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+u.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(P))N("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:P}}if(u.kind==="pr_mutation"){let P=u.mutation,j=P.action==="edit"?["edit",...P.title!==void 0?[`--title=${P.title}`]:[],...P.body!==void 0?[`--body=${P.body}`]:[],...P.base?[`--base=${P.base}`]:[]]:P.action==="metadata"?["edit",`--${P.change}-${P.field}=${P.value}`]:P.action==="ready"?["ready"]:P.action==="draft"?["ready","--undo"]:["close"];return await S(["pr",...j,String(u.number),"--repo",u.repoFullName]),{kind:"pr_mutation",number:u.number,applied:!0}}if(!a.repoPath)N("local_device_gh_workspace_unavailable");let x=z.realpathSync(a.repoPath);if(!ln(m,x))N("local_device_gh_workspace_unavailable");let I=`https://github.com/${u.repoFullName}.git`,E="!'"+(Fe?f.replace(/\\/g,"/"):f).replace(/'/g,"'\\''")+"' auth git-credential",C=Dt(Si),O=(P,j,W)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",P,j,...W]]:[j,W],D=async(P,j,W,Z=dt)=>{let ie=ln(y,P),se=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...ie?["-c",`credential.https://github.com.helper=${E}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...j];if(ie)return w(b,se,P,W,Z);let ye=oe.join(x,".ara-local-gh-tmp");if(z.mkdirSync(ye,{recursive:!0,mode:448}),z.lstatSync(ye).isSymbolicLink()||z.realpathSync(ye)!==ye)N("local_device_gh_workspace_unavailable");a.assertCurrent();let Re=await l.command(...O(C(x,ye),b,se),{cwd:P,input:W,maxBuffer:Z,timeout:Math.max(1,Math.min(25000,(a.deadlineMs??Date.now()+25000)-Date.now())),signal:a.signal,env:{...ur,PATH:kt,HOME:x,TMPDIR:ye,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(a.assertCurrent(),Re.error||Re.status!==0)N("local_device_gh_collection_failed");return Re.stdout},B=async(P,j)=>(await D(P,j)).toString("utf8").trim(),ne=async(P,j)=>{let W=oe.join(P,".ara-local-gh-tmp");if(z.mkdirSync(W,{recursive:!0,mode:448}),z.lstatSync(W).isSymbolicLink()||z.realpathSync(W)!==W)N("local_device_gh_workspace_unavailable");a.assertCurrent();let Z=await l.command(...O(C(P,W),$c(b),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",j]),{cwd:P,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(a.deadlineMs??Date.now()+25000)-Date.now())),signal:a.signal,env:{...ur,PATH:kt,HOME:P,TMPDIR:W}});if(a.assertCurrent(),Z.error||Z.status!==0)N("local_device_gh_materialization_failed")},de=async(P)=>{let j=new Map;if(P.length===0)return j;let W=await D(ce,["cat-file","--batch"],[...new Set(P)].join(`
|
|
14
|
+
`)+`
|
|
15
|
+
`,dt*8);for(let Z=0;Z<W.length;){let ie=W.indexOf(10,Z),[se,ye,Re]=W.subarray(Z,ie).toString("utf8").split(" ");if(ie<0||!se||ye!=="blob"||!/^[0-9]+$/.test(Re??""))N("local_device_gh_object_invalid");j.set(se,W.subarray(ie+1,ie+1+Number(Re)).toString("utf8")),Z=ie+1+Number(Re)+1}return j},he=async(P,j,W)=>{let Z=oe.join(x,".ara-local-gh-tmp"),ie=C(x,Z)+`
|
|
16
|
+
(allow file-read* file-write* (subpath ${JSON.stringify(x)}))
|
|
17
|
+
(allow file-read* (subpath ${JSON.stringify(P)}))
|
|
18
|
+
(allow file-read-metadata (path-ancestors ${JSON.stringify(P)}))`,se=async(Re,tt)=>{a.assertCurrent();let Et=await l.command(...O(ie,Re,tt),{cwd:x,maxBuffer:dt,timeout:Math.max(1,Math.min(25000,(a.deadlineMs??Date.now()+25000)-Date.now())),signal:a.signal,env:{...ur,PATH:kt,HOME:x,TMPDIR:Z,GIT_INDEX_FILE:oe.join(x,".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(a.assertCurrent(),Et.error||Et.status!==0)N("local_device_gh_materialization_failed")},ye=["--git-dir="+P,"--work-tree="+x,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await se(b,[...ye,"read-tree",j]),await se(b,[...ye,"checkout-index","--all","--index"]),await D(x,["update-ref","refs/heads/"+W,j]),await D(x,["symbolic-ref","HEAD","refs/heads/"+W])};p="local_device_gh_prepare_metadata";let We=await v(`/repos/${u.repoFullName}`);if(We.status!==200)N("local_device_gh_repository_unavailable");let Xe=JSON.parse(We.body);if(Xe.full_name?.toLowerCase()!==u.repoFullName.toLowerCase()||Xe.default_branch!==u.defaultBranch||u.kind==="publish"&&Xe.permissions?.push!==!0)N("local_device_gh_repository_authority_changed");if(u.branch===u.defaultBranch)N("local_device_gh_default_branch");p="local_device_gh_prepare_private_init";let ce=z.mkdtempSync(oe.join(y,"github-publication-"));z.chmodSync(ce,448);let Zt=!1;try{if(await D(ce,["init","--bare","--template="]),u.kind==="prepare"){if(p="local_device_gh_prepare_fetch",await D(ce,["fetch","--depth=1","--no-tags","--no-recurse-submodules",I,u.baseSha]),await B(ce,["rev-parse","FETCH_HEAD"])!==u.baseSha)p="local_device_gh_prepare_base_mismatch",N("local_device_gh_base_changed");p="local_device_gh_prepare_checkout_validation";let pe=oe.join(x,".git"),Te=!1;if(z.existsSync(pe)){if(!z.lstatSync(pe).isDirectory()||z.lstatSync(pe).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((ge)=>z.existsSync(oe.join(pe,ge))))N("local_device_gh_repository_layout_invalid");let ve=await D(x,["rev-parse","--verify","-q","HEAD"]).then((ge)=>ge.toString("utf8").trim(),()=>null),De=await D(x,["config","--local","--get","remote.origin.url"]).then((ge)=>ge.toString("utf8").trim(),()=>"");if(ve!==null||De){if(ve!==u.baseSha||await B(x,["branch","--show-current"])!==u.branch)N("local_device_gh_checkout_exists");return{kind:"prepare",headSha:u.baseSha}}Te=!0}let Ee=z.readdirSync(x).filter((ve)=>!(Te&&ve===".git")),He=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if(Ee.some((ve)=>!He.includes(ve))||Ee.some((ve)=>{let De=oe.join(x,ve);return!z.lstatSync(De).isDirectory()||z.lstatSync(De).isSymbolicLink()||z.readdirSync(De).length>0}))N("local_device_gh_checkout_not_empty");if(p="local_device_gh_prepare_checkout_init",!Te)await D(x,["init","--template="]);p="local_device_gh_prepare_materialization";let ze=await D(ce,["pack-objects","--stdout","--revs"],u.baseSha+`
|
|
19
|
+
`,Ii);return await ne(x,u.baseSha),await D(x,["index-pack","--strict","--stdin"],ze,65536),await D(x,["remote","add","origin",I]),await he(ce,u.baseSha,u.branch),{kind:"prepare",headSha:u.baseSha}}let P=oe.join(x,".git");if(!z.lstatSync(P).isDirectory()||z.lstatSync(P).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((pe)=>z.existsSync(oe.join(P,pe))))N("local_device_gh_repository_layout_invalid");if(await B(x,["branch","--show-current"])!==u.branch)N("local_device_gh_branch_changed");let j=await B(x,["rev-parse","--verify","HEAD"]);if(!tn.test(j))N("local_device_gh_head_invalid");let W=await v(`/repos/${u.repoFullName}/commits/${u.baseSha}`);if(W.status!==200||JSON.parse(W.body).sha!==u.baseSha)N("local_device_gh_base_unverified");let Z=await v(`/repos/${u.repoFullName}/git/ref/heads/${encodeURIComponent(u.branch)}`);if(u.remoteHeadSha===null?Z.status!==404:Z.status!==200||JSON.parse(Z.body).object?.sha!==u.remoteHeadSha)N("local_device_gh_remote_changed");let ie=[...(await B(x,["rev-list","--objects","--no-object-names",j,"--not",u.baseSha])).split(`
|
|
20
|
+
`),...(await B(x,["rev-list","--objects","--no-object-names","--no-walk",u.baseSha])).split(`
|
|
21
|
+
`)].filter(Boolean);if(ie.some((pe)=>!tn.test(pe)))N("local_device_gh_object_invalid");let se=await D(x,["pack-objects","--stdout"],[...new Set(ie)].join(`
|
|
22
|
+
`)+`
|
|
23
|
+
`,Ii);if(z.writeFileSync(oe.join(ce,"shallow"),u.baseSha+`
|
|
24
|
+
`,{flag:"wx",mode:384}),await D(ce,["index-pack","--strict","--stdin"],se,65536),await D(ce,["merge-base","--is-ancestor",u.baseSha,j]),u.remoteHeadSha)await D(ce,["merge-base","--is-ancestor",u.remoteHeadSha,j]);let ye=await D(ce,["show","-s","--format=%B",j]),Re=(await D(ce,["interpret-trailers","--parse"],ye)).toString("utf8"),tt=u.contributorTrailers?{expectedTrailers:u.contributorTrailers,missingFromHead:Wc(Re,u.contributorTrailers)}:void 0,Et=(await B(ce,["rev-list","--objects","--no-object-names",j,"--not",u.baseSha,...u.remoteHeadSha?[u.remoteHeadSha]:[]])).split(`
|
|
25
|
+
`).filter(Boolean);if(Et.length>5000)N("local_device_gh_collection_too_large");let Pt=[],li=0;for(let pe of Et){if(!tn.test(pe))N("local_device_gh_object_invalid");let Te=await B(ce,["cat-file","-t",pe]);if(!["blob","commit","tree"].includes(Te))N("local_device_gh_object_invalid");let Ee=await D(ce,["cat-file",Te,pe]);if(li+=Ee.length,li>dt)N("local_device_gh_collection_too_large");if(Te==="tree"){let He=0;while(He<Ee.length){let ze=Ee.indexOf(32,He),ve=Ee.indexOf(0,ze+1);if(ze<He||ve<=ze||ve+21>Ee.length)N("local_device_gh_object_invalid");let De=Ee.subarray(ze+1,ve).toString("utf8");if(De.includes("/")||!en(De).valid)N("local_device_gh_object_invalid");He=ve+21}}Pt.push({path:`object-${pe}`,content:Ee.toString("utf8")})}let di=a.secretNames?{secretNames:a.secretNames}:{},Ot=cr(Pt,a.forbiddenSecretValues,di),pi=new Map;if(!Ot.clean)try{let pe=(await D(ce,["diff","--no-renames","--no-abbrev","--raw","-z",u.baseSha,j])).toString("utf8").split("\x00"),Te=[],Ee=[];for(let ge=0;ge+1<pe.length;ge+=2){let[,nc,oc,Yr,er]=pe[ge].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!Yr||!er)continue;if(nc!=="160000"&&!/^0+$/.test(Yr))Te.push(Yr);if(oc!=="160000"&&!/^0+$/.test(er))Ee.push(er),pi.set(`object-${er}`,pe[ge+1])}let He=await de([...Te,...Ee]),ze=new Set(Ot.violations.map((ge)=>ge.path)),ve=Pi(Pt.filter((ge)=>ze.has(ge.path)),a.forbiddenSecretValues),De=Oi(ve,Ee.map((ge)=>He.get(ge)??""),Te.map((ge)=>He.get(ge)??""));if(De.size>0)Ot=cr(Pt,a.forbiddenSecretValues,{...di,published:De})}catch{}if(!Ot.clean)Ai(Ot.violations,(pe)=>pi.get(pe)??`an object in the pushed history (${pe})`,"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 D(ce,["push","--no-recurse-submodules",I,`${j}:refs/heads/${u.branch}`]);let fi=await v(`/repos/${u.repoFullName}/git/ref/heads/${encodeURIComponent(u.branch)}`);if(fi.status!==200||JSON.parse(fi.body).object?.sha!==j)N("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:j,scannedObjectCount:Pt.length,...tt?{attribution:tt}:{}}}catch(P){throw Zt=!0,P}finally{try{z.rmSync(ce,{recursive:!0,force:!0})}catch(P){if(!Zt||u.kind!=="prepare")throw p=null,P}}}catch(m){if(u.kind==="prepare"&&u.diagnosticsVersion===1&&p&&!a.signal?.aborted)throw new Ln(p);throw m}}var pt=n({profile:t().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:t().min(1).max(1024)}).strict(),un={ready:i(!0),boot_generation:t().uuid(),proof_ready:i(!1),result:i("metadata_only")},so=n({...un,version:i(2),development_only:i(!1),image:i(!0),video:i(!1),source_bound:i(!1),profiles:d(pt.shape.profile).min(1).max(16),extension_instance_ids:d(pt.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),ao=n({...un,version:i(3),development_only:i(!1),image:i(!0),video:i(!0),source_bound:i(!1),max_seconds:i(15),profiles:d(pt.shape.profile).min(1).max(16),extension_instance_ids:d(pt.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),dn=we([so,ao]),xf=we([n({...un,version:i(1),development_only:i(!0),profile:pt.shape.profile,extension_instance_id:pt.shape.extension_instance_id,max_seconds:i(15)}).strict(),dn]);import{createServer as Gc,request as Yc}from"http";import{connect as Xc,isIP as Zc}from"net";var Ni=120000,Qc=15000;function eu(e,a,l){let u=si(a).toLowerCase().replace(/\.$/,"");if(!u||Zc(u))return!1;return e.some((p)=>{if(!mo.test(p))return!1;let m=p.lastIndexOf(":"),f=m>0?p.slice(0,m):p;if(m>0&&Number(p.slice(m+1))!==l)return!1;return f.startsWith("*.")?u.endsWith(f.slice(1)):u===f})}function tu(e,a){let l=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec(e),u=l?l[1]:e,p=l?Number(l[2]):a;return u&&p>=1&&p<=65535?{host:u,port:p}:null}async function mn(e,a,l){if(!eu(l,e,a))return null;let u=await Ka(e);return u.ok?u.addresses[0]:null}function Nt(e,a){e.end(`HTTP/1.1 ${a} ${a===403?"Forbidden":"Bad Gateway"}\r
|
|
26
|
+
Connection: close\r
|
|
27
|
+
Content-Length: 0\r
|
|
28
|
+
\r
|
|
29
|
+
`)}function ki(e,a){return new Promise((l,u)=>{let p=Xc({host:e,port:a}),m=setTimeout(()=>p.destroy(Error("connect_timeout")),Qc);p.once("connect",()=>{clearTimeout(m),l(p)}),p.once("error",(f)=>{clearTimeout(m),u(f)})})}function Ti(e,a,l){for(let u of[e,a])u.on("error",()=>{e.destroy(),a.destroy()}),u.on("close",()=>{e.destroy(),a.destroy()});if(a.setTimeout(Ni,()=>a.destroy()),l.length)a.write(l);e.pipe(a).pipe(e)}function Di(e,a){let l={...e,host:a};return delete l["proxy-authorization"],delete l["proxy-connection"],l}async function Mi(e,a=()=>{}){let l=[...e],u=new Set,p=(g)=>{u.add(g),g.once("close",()=>u.delete(g))},m=Gc((g,b)=>{(async()=>{let y;try{y=new URL(g.url??"")}catch{y=new URL("invalid:")}let h=Number(y.port||80),w=y.protocol==="http:"?await mn(y.hostname,h,l):null;if(!w){a(),b.writeHead(403,{connection:"close"}).end();return}let S=Yc({host:w,port:h,method:g.method,path:`${y.pathname}${y.search}`,headers:Di(g.headers,y.host),agent:!1,timeout:Ni},(v)=>{b.writeHead(v.statusCode??502,v.headers),v.pipe(b)});S.on("timeout",()=>S.destroy()),S.on("error",()=>{if(!b.headersSent)b.writeHead(502);b.end()}),b.on("close",()=>S.destroy()),g.pipe(S)})().catch(()=>{if(!b.headersSent)b.writeHead(502);b.end()})});m.on("connection",p),m.on("connect",(g,b,y)=>{p(b),b.on("error",()=>b.destroy()),(async()=>{let h=tu(g.url??"",443),w=h?await mn(h.host,h.port,l):null;if(!h||!w){a(),Nt(b,403);return}let S=await ki(w,h.port).catch(()=>null);if(!S){Nt(b,502);return}if(b.destroyed){S.destroy();return}p(S),b.write(`HTTP/1.1 200 Connection Established\r
|
|
30
|
+
\r
|
|
31
|
+
`),Ti(b,S,y)})().catch(()=>b.destroy())}),m.on("upgrade",(g,b,y)=>{p(b),b.on("error",()=>b.destroy()),(async()=>{let h;try{h=new URL(g.url??"")}catch{Nt(b,403);return}let w=Number(h.port||80),S=["http:","ws:"].includes(h.protocol)?await mn(h.hostname,w,l):null;if(!S){a(),Nt(b,403);return}let v=await ki(S,w).catch(()=>null);if(!v){Nt(b,502);return}p(v);let x=Di(g.headers,h.host),I=[`${g.method} ${h.pathname}${h.search} HTTP/1.1`];for(let[E,C]of Object.entries(x))for(let O of Array.isArray(C)?C:C===void 0?[]:[C])I.push(`${E}: ${O}`);v.write(`${I.join(`\r
|
|
32
|
+
`)}\r
|
|
33
|
+
\r
|
|
34
|
+
`),Ti(b,v,y)})().catch(()=>b.destroy())}),await new Promise((g,b)=>{m.once("error",b),m.listen(0,"127.0.0.1",()=>g())});let{port:f}=m.address();return{url:`http://127.0.0.1:${f}`,close(){m.close();for(let g of u)g.destroy()}}}import{createHash as Rn,randomUUID as iu}from"crypto";import{closeSync as yr,constants as Ce,fchownSync as su,fstatSync as rt,fsyncSync as au,linkSync as Zi,lstatSync as bn,mkdirSync as Qi,openSync as gr,readSync as rs,realpathSync as wn,unlinkSync as es,writeSync as lu}from"fs";import{isAbsolute as cu,join as uu,relative as du,sep as pu}from"path";import{platform as Sn}from"os";import{getSystemErrorName as mu}from"util";var $i={type:"string",format:"uuid"},Hi=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,dr={type:"string",minLength:1,maxLength:4096,pattern:Hi},fn=t().min(1).max(4096).regex(new RegExp(Hi)),pr={device_id:t().uuid(),root_id:t().uuid(),timeout_ms:o().int().min(1000).max(60000).optional()},mr={device_id:$i,root_id:$i,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},kf={read:{schema:n({...pr,path:fn,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({...pr,path:fn,content:t().max(131072),mode:c(["overwrite","append"]).optional(),create_parents:_().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({...pr,command:t().min(1).max(16000),cwd:fn.optional(),mode:c(["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}}},qe=1073741824,Mt=600000,Bi=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,ji=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${Bi}(?:/${Bi})*(?![\s\S])`,Vi=new RegExp(ji);function Gi(e){return typeof e==="string"&&e.length>0&&e.length<=4096&&Vi.test(e)}var hn=t().min(1).max(4096).regex(Vi),gn={...dr,pattern:ji},Yi=t().regex(/^[a-f0-9]{64}$/),Xi=n({kind:i("workspace"),path:hn}).strict(),ru=A("kind",[Xi,n({kind:i("attachment"),attachment_id:t().min(1).max(120),sha256:Yi}).strict()]),fr=1,$t="cloud_workspace_id",_n="cloud_workspace",yn=1,nu=A("kind",[Xi,n({kind:i("attachment"),download_url:t().min(1).max(16384),size_bytes:o().int().min(0).max(qe),sha256:Yi}).strict()]),Ji=n({source_version:i(fr),source:nu,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(),[$t]:t().min(1).max(160).optional()}).strict(),Tf=n({ready:i(!0),cloud_source_version:i(fr),source_kinds:d(c(["workspace","attachment"]))});var Fi=n({...pr,timeout_ms:o().int().min(1000).max(Mt).optional(),source_path:hn,destination_path:hn,idempotency_key:t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),Ui={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...mr,timeout_ms:{type:"integer",minimum:1000,maximum:Mt},source_path:gn,destination_path:gn,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},ou={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:gn},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}]},Df=we([Fi,Fi.omit({source_path:!0}).extend({source:ru}).strict()]),Nf={...Ui,required:["device_id","root_id","destination_path"],properties:{...Ui.properties,source:ou},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var xn=65536;function me(e){throw new r(e,e)}function br(e){return typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"?e.code:void 0}function _r(e,a,l){if(a.throwIfAborted(),e instanceof r||e instanceof Error&&e.name==="AbortError")throw e;return me(l)}function fu(e,a,l){let u;switch(br(e)){case"ENOENT":u=l==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":u="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":u="transfer_path_unsafe";break;case"EEXIST":u="transfer_destination_exists";break;default:u="transfer_path_unavailable"}return _r(e,a,u)}function hu(e){if(typeof e!=="string"||e.length>16384)return me("transfer_url_invalid");let a;try{a=new URL(e)}catch{return me("transfer_url_invalid")}if(a.protocol!=="https:"||a.username||a.password||a.hash)return me("transfer_url_invalid");return a.href}var vn=Ce.O_RDONLY|Ce.O_DIRECTORY|Ce.O_NOFOLLOW;async function gu(){if(Sn()==="win32"){let y=new Map,h,w=-1,S=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),v=(C)=>{let O=du(h,C);return O===""||O!==".."&&!O.startsWith(`..${pu}`)&&!cu(O)},x=(C)=>{let O=bn(C);if(O.isSymbolicLink())throw S();if(!O.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let D=wn(C);if(h??=D,!v(D))throw S();return y.set(w,{path:C,real:D}),w--},I=(C)=>{let O=y.get(C);if(wn(O.path)!==O.real)throw S();return O.path},E=(C,O)=>{if(Ki(O))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return uu(y.get(C).path,O)};return{root:x,openDirectory:(C,O)=>x(E(C,O)),open:(C,O,D,B=384)=>{let ne=E(C,O);if(bn(ne,{throwIfNoEntry:!1})?.isSymbolicLink())throw S();I(C);let de=gr(ne,D,B);try{let he=rt(de),We=bn(ne);if(We.isSymbolicLink()||he.ino!==We.ino||he.dev!==We.dev||!v(wn(ne)))throw S()}catch(he){throw yr(de),he}return de},mkdir:(C,O)=>{let D=E(C,O);I(C),Qi(D)},link:(C,O,D)=>{let B=E(C,O),ne=E(C,D);I(C),Zi(B,ne)},unlink:(C,O)=>es(E(C,O)),closeDirectory:(C)=>{y.delete(C)},inherit:()=>{},close:()=>{}}}let e={root:(y)=>gr(y,vn),closeDirectory:yr,inherit:_u};if(Sn()==="linux")return{...e,openDirectory:(y,h)=>gr(`/proc/self/fd/${y}/${h}`,vn),open:(y,h,w,S=384)=>gr(`/proc/self/fd/${y}/${h}`,w,S),mkdir:(y,h)=>Qi(`/proc/self/fd/${y}/${h}`,{mode:448}),link:(y,h,w)=>Zi(`/proc/self/fd/${y}/${h}`,`/proc/self/fd/${y}/${w}`),unlink:(y,h)=>es(`/proc/self/fd/${y}/${h}`),close:()=>{}};if(Sn()!=="darwin")return me("transfer_platform_unsupported");let{dlopen:a,FFIType:l,ptr:u,read:p}=await import("bun:ffi"),m=a("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:l.ptr},openat:{args:[l.i32,l.ptr,l.i32,l.i32,l.i32,l.i32,l.i32,l.i32,l.i32],returns:l.i32},mkdirat:{args:[l.i32,l.ptr,l.i32],returns:l.i32},linkat:{args:[l.i32,l.ptr,l.i32,l.ptr,l.i32],returns:l.i32},unlinkat:{args:[l.i32,l.ptr,l.i32],returns:l.i32}}),f=m.symbols.__error();if(f===null)return m.close(),me("transfer_path_unavailable");let g=(y)=>{if(y<0){let h=mu(-p.i32(f));throw Object.assign(Error("transfer_path_unavailable"),{code:h})}return y},b=(y,h,w,S=384)=>g(m.symbols.openat(y,u(Buffer.from(`${h}\x00`)),w,S,0,0,0,0,S));return{...e,openDirectory:(y,h)=>b(y,h,vn),open:b,mkdir:(y,h)=>{g(m.symbols.mkdirat(y,u(Buffer.from(`${h}\x00`)),448))},link:(y,h,w)=>{g(m.symbols.linkat(y,u(Buffer.from(`${h}\x00`)),y,u(Buffer.from(`${w}\x00`)),0))},unlink:(y,h)=>{g(m.symbols.unlinkat(y,u(Buffer.from(`${h}\x00`)),0))},close:()=>m.close()}}function _u(e,a){let l=rt(e),u=rt(a);if(u.uid!==l.uid||u.gid!==l.gid)su(a,l.uid,l.gid)}function yu(e,a,l,u){if(!Gi(l))return me("transfer_path_invalid");let p=l.split("/"),m=e.root(a);try{for(let f of p.slice(0,-1)){let g;try{g=e.openDirectory(m,f)}catch(b){if(!u||br(b)!=="ENOENT")throw b;try{e.mkdir(m,f)}catch(y){if(br(y)!=="EEXIST")throw y}g=e.openDirectory(m,f),e.inherit(m,g)}e.closeDirectory(m),m=g}return{fd:m,leaf:p.at(-1)}}catch(f){throw e.closeDirectory(m),f}}function ts(e,a){let l=rt(e,{bigint:!0});if(!l.isFile()||l.size>qe)return me("transfer_file_invalid");let u=Rn("sha256"),p=Buffer.alloc(xn),m=0;while(!0){a.throwIfAborted();let g=rs(e,p,0,p.length,m);if(!g)break;if(m+=g,m>qe)return me("transfer_size_exceeded");u.update(p.subarray(0,g))}let f=rt(e,{bigint:!0});if(BigInt(m)!==l.size||f.size!==l.size||f.mtimeNs!==l.mtimeNs||f.ctimeNs!==l.ctimeNs)return me("transfer_source_changed");return{size_bytes:m,sha256:u.digest("hex")}}async function mt(e){e.signal.throwIfAborted();try{let a=hu(e.payload.url),l=await gu(),u,p,m;try{if(u=yu(l,e.root,e.path,e.direction==="import"),e.direction==="export"){p=l.open(u.fd,u.leaf,Ce.O_RDONLY|Ce.O_NOFOLLOW|Ce.O_NONBLOCK);let S=rt(p,{bigint:!0});if(!S.isFile()||S.size>qe)return me("transfer_file_invalid");let v=Rn("sha256"),x=0,I=p,E,C=new ReadableStream({pull(ne){try{e.signal.throwIfAborted();let de=Buffer.alloc(xn),he=rs(I,de,0,de.length,x);if(!he){ne.close();return}if(x+=he,x>S.size)return me("transfer_source_changed");v.update(de.subarray(0,he)),ne.enqueue(de.subarray(0,he))}catch(de){throw E=de,de}}});try{let ne=await(e.fetchImpl??fetch)(a,Object.assign({method:"PUT",body:C,redirect:"error",signal:e.signal,headers:{"content-type":"application/octet-stream","content-length":String(S.size)}},{duplex:"half"}));if(E!==void 0)throw E;if(!ne.ok)return me("transfer_upload_failed");await ne.body?.cancel()}catch(ne){if(E!==void 0)throw E;return _r(ne,e.signal,"transfer_upload_failed")}let O=rt(p,{bigint:!0});if(BigInt(x)!==S.size||O.size!==S.size||O.mtimeNs!==S.mtimeNs||O.ctimeNs!==S.ctimeNs)return me("transfer_source_changed");let D=v.digest("hex"),B=ts(p,e.signal);if(B.size_bytes!==x||B.sha256!==D)return me("transfer_source_changed");return{size_bytes:x,sha256:D,outcome:"copied"}}let f=e.payload.size_bytes,g=e.payload.sha256;if(typeof f!=="number"||!Number.isSafeInteger(f)||f<0||f>qe||typeof g!=="string"||!/^[a-f0-9]{64}$/.test(g))return me("transfer_receipt_invalid");let b;try{b=l.open(u.fd,u.leaf,Ce.O_RDONLY|Ce.O_NOFOLLOW|Ce.O_NONBLOCK)}catch(S){if(br(S)!=="ENOENT")throw S}if(b!==void 0){try{let S=ts(b,e.signal);if(S.size_bytes===f&&S.sha256===g)return{...S,outcome:"already_present"}}finally{yr(b)}return me("transfer_destination_exists")}m=`.reason-copy-${iu()}`,p=l.open(u.fd,m,Ce.O_CREAT|Ce.O_EXCL|Ce.O_WRONLY|Ce.O_NOFOLLOW,384),l.inherit(u.fd,p);let y;try{let S=await(e.fetchImpl??fetch)(a,{redirect:"error",signal:e.signal});if(!S.ok||!S.body)return me("transfer_download_failed");y=S.body.getReader()}catch(S){return _r(S,e.signal,"transfer_download_failed")}let h=Rn("sha256"),w=0;try{while(!0){e.signal.throwIfAborted();let S=await y.read().catch((v)=>_r(v,e.signal,"transfer_download_failed"));if(S.done)break;if(w+=S.value.length,w>f)return me("transfer_size_mismatch");h.update(S.value);for(let v=0;v<S.value.length;)e.signal.throwIfAborted(),v+=lu(p,S.value,v,Math.min(xn,S.value.length-v))}}finally{await y.cancel().catch(()=>{})}if(w!==f||h.digest("hex")!==g)return me("transfer_hash_mismatch");return au(p),await e.beforeCommit?.(),e.signal.throwIfAborted(),l.link(u.fd,m,u.leaf),{size_bytes:f,sha256:g,outcome:"copied"}}finally{try{if(p!==void 0)yr(p)}finally{try{if(u){if(m)try{l.unlink(u.fd,m)}catch{}l.closeDirectory(u.fd)}}finally{l.close()}}}}catch(a){return fu(a,e.signal,e.direction)}}import{spawn as wu}from"child_process";import{mkdtempSync as Su,rmSync as vu,writeFileSync as Ru}from"fs";import{constants as xu,platform as Eu,tmpdir as Cu}from"os";import{join as ss}from"path";import{gunzipSync as bu,gzipSync as Gf}from"zlib";var os=900000,Kf=os+60000,Bt=49152,ns=(e)=>t().min(1).max(e).regex(/^[A-Za-z0-9+/]+=*$/),is=n({version:i(1),script_gzip:ns(163840),stdin_gzip:ns(65536),cwd:t().min(1).max(4096).startsWith("/"),env:$e(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(os)}).strict(),En=t().max(Bt+256),Xf=n({exit_code:o().int().min(0).max(255),stdout:En,stderr:En,combined:En.optional()}).strict();function On(e){return bu(Buffer.from(e,"base64")).toString("utf8")}var Pu="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",Ou=["RUSTUP_HOME","TZ","LC_ALL"],Iu=2000,Au=100;function Vr(){return Eu()==="linux"&&process.geteuid?.()===0}function In(e){let a=Math.floor(e/2),l=[],u=0,p=Buffer.alloc(0),m=0;return{push(f){m+=f.length;let g=f;if(u<a){let b=g.subarray(0,a-u);l.push(b),u+=b.length,g=g.subarray(b.length)}if(g.length)p=Buffer.concat([p,g]).subarray(-a)},text(){let f=m-u-p.length;return Buffer.concat(l).toString("utf8")+(f>0?`
|
|
35
|
+
[reason: ${f} bytes of output omitted]
|
|
36
|
+
`:"")+p.toString("utf8")}}}async function as(e,a){if(!Vr())throw new r("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let l=is.safeParse(e);if(!l.success)throw new r("invalid_request","Reason sent an invalid workspace setup.");let u=l.data,p,m;try{p=On(u.script_gzip),m=On(u.stdin_gzip)}catch{throw new r("invalid_request","Reason sent an unreadable workspace setup.")}a.throwIfAborted();let f=Su(ss(Cu(),"reason-workspace-setup-"));try{let g=ss(f,"setup.sh");Ru(g,p,{mode:384});let b={PATH:Pu,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let B of Ou)if(process.env[B])b[B]=process.env[B];Object.assign(b,u.env);let y=wu("/bin/bash",[g],{cwd:u.cwd,env:b,detached:!0,stdio:["pipe","pipe","pipe"]}),h=In(Bt),w=In(Bt),S=In(Bt);y.stdout.on("data",(B)=>{h.push(B),S.push(B)}),y.stderr.on("data",(B)=>{w.push(B),S.push(B)}),y.stdin.on("error",()=>{}),y.stdin.end(m);let v=(B)=>{try{if(y.pid)process.kill(-y.pid,B)}catch{}},x=!1,I,E=()=>{v("SIGTERM"),I??=setTimeout(()=>v("SIGKILL"),Iu)},C=setTimeout(()=>{x=!0,E()},u.timeout_ms);a.addEventListener("abort",E,{once:!0});let O=await new Promise((B,ne)=>{y.once("error",()=>ne(new r("workspace_setup_start_failed","The workspace setup did not start."))),y.once("exit",(de,he)=>B({code:de,signal:he}))}).finally(()=>{clearTimeout(C),clearTimeout(I),a.removeEventListener("abort",E)});await new Promise((B)=>{let ne=setTimeout(B,Au);y.once("close",()=>{clearTimeout(ne),B()})}),y.stdout.destroy(),y.stderr.destroy(),a.throwIfAborted();let D=x?124:O.signal?128+(xu.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,D),stdout:h.text(),stderr:w.text(),...D!==0?{combined:S.text()}:{}}}finally{vu(f,{recursive:!0,force:!0})}}import{chmodSync as Lu,mkdtempSync as ku,realpathSync as ls,rmSync as Tu}from"fs";import{tmpdir as Du}from"os";import{dirname as Nu,join as kn,sep as Mu}from"path";function Tn(e){return ui(e,ai(e)!==null).repoPath}function cs(e,a){let l;try{if(typeof a!=="string")throw Error("invalid");l=[Oe,void 0].map((p)=>Nu(X({kind:"managed",workspaceId:a,...p?{layout:p}:{}})))}catch{throw new r("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let u;for(let p of l)try{u=ls(kn(e,p));break}catch{}if(u===void 0)throw new r("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!u.startsWith(`${e}${Mu}`))throw new r("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return u}async function us(e){e.signal.throwIfAborted();let a=e.source;if(a.kind==="workspace"){let u=Tn(e.runtimeRoot);if(L(u)||L(kn(u,a.path)))throw new r("protected_path","Credential and secret paths are unavailable to local tasks.");return mt({direction:"export",root:u,path:a.path,payload:{url:e.url},signal:e.signal,fetchImpl:e.fetchImpl})}let l=ku(kn(Du(),`reason-cloud-copy-${process.pid}-`));try{Lu(l,448);let u=ls(l);await mt({direction:"import",root:u,path:"source",payload:{url:a.download_url,size_bytes:a.size_bytes,sha256:a.sha256},signal:e.signal,fetchImpl:e.fetchImpl});let p=await mt({direction:"export",root:u,path:"source",payload:{url:e.url},signal:e.signal,fetchImpl:e.fetchImpl});if(p.size_bytes!==a.size_bytes||p.sha256!==a.sha256)throw new r("transfer_source_changed","The verified attachment changed before export.");return p}finally{Tu(l,{recursive:!0,force:!0})}}import{constants as ke}from"fs";import{closeSync as Hl,existsSync as Ue,fstatSync as jl,ftruncateSync as mm,lstatSync as zo,mkdirSync as fm,mkdtempSync as hm,openSync as ql,readSync as gm,realpathSync as Ne,rmSync as _m,statSync as Jt,writeSync as ym}from"fs";import{homedir as Yt,platform as G,tmpdir as bm}from"os";import{dirname as Kt,isAbsolute as wm,join as Wl,relative as Yo,resolve as Sm,sep as vm}from"path";import{spawn as Rm}from"child_process";import{createHash as Hu,randomBytes as ju}from"crypto";var Dn=30000,$u=1800000,Bu=5000,wr=30000,Fu=$n+15000,ps=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,Uu=[/^\/app\/local-runtime\/operations\/claim$/,ps];class Nn{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor(e){this.options=e}now(){return(this.options.now??Date.now)()}jitter(e){return Math.floor((this.options.random??Math.random)()*e)}async request(e,a,l){l?.throwIfAborted();let u=this.current;if(!u)return this.connect(),null;if(u.pending.size>=u.maxInFlight)return null;let p=String(++this.nextId),m=new Promise((b)=>u.pending.set(p,{path:e,resolve:b}));if(!this.send(u,{t:"req",id:p,path:e,body:a}))return u.pending.delete(p),null;let f;if(Uu.some((b)=>b.test(e)))f=setTimeout(()=>{if(u.pending.has(p))this.drop(u)},Fu);else{let b=()=>{if(!u.pending.has(p))return;let y=this.now()-u.lastFrameAt;if(y>=wr)this.drop(u);else f=setTimeout(b,wr-y)};f=setTimeout(b,wr)}if(m.finally(()=>clearTimeout(f)),!l)return await m;let g=new Promise((b,y)=>{let h=()=>{if(u.pending.delete(p),clearTimeout(f),this.send(u,{t:"abort",id:p}),this.now()-u.lastFrameAt>wr)this.drop(u);y(l.reason)};if(l.aborted)h();else l.addEventListener("abort",h,{once:!0}),m.finally(()=>l.removeEventListener("abort",h))});return await Promise.race([m,g])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let e of[this.current,this.connecting])if(e)this.drop(e)}send(e,a){try{return e.socket.send(JSON.stringify(a)),!0}catch{return this.drop(e),!1}}drop(e){if(e.dropped)return;e.dropped=!0,this.settle(e);try{e.socket.close()}catch{}}settle(e){for(let a of e.pending.values())a.resolve(null);if(e.pending.clear(),this.current===e)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(Bu));if(this.connecting===e){this.connecting=null,this.failures+=1;let a=Math.min($u,Dn*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+a/2+this.jitter(a/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let e=this.options.WebSocket??globalThis.WebSocket;if(!e){this.retryAt=Number.POSITIVE_INFINITY;return}let a=new URL(Ct,this.options.apiOrigin);a.protocol=a.protocol==="https:"?"wss:":"ws:",a.searchParams.set("device_id",this.options.deviceId);let l;try{l=new e(a.toString())}catch{this.failures+=1,this.retryAt=this.now()+Dn;return}let u={socket:l,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=u,l.onmessage=(p)=>this.receive(u,p.data),l.onclose=()=>this.settle(u),l.onerror=()=>this.settle(u)}receive(e,a){if(typeof a!=="string")return;let l;try{l=JSON.parse(a)}catch{return}if(e.lastFrameAt=this.now(),l.t==="res"){let u=e.pending.get(l.id);e.pending.delete(l.id),u?.resolve({status:l.status,body:l.body,retryAfter:l.retry_after??null});return}if(l.t==="challenge"&&this.connecting===e){let u;try{u=this.options.signHello(l.challenge)}catch{this.drop(e);return}this.send(e,{t:"hello",...u});return}if(l.t==="ready"&&this.connecting===e){this.connecting=null,this.failures=0,e.maxInFlight=Math.max(1,Math.min(l.max_in_flight,1000)),e.cadence=l.cadence??null;let u=this.current;if(this.current=e,u){for(let[p,m]of u.pending){if(!ps.test(m.path))continue;u.pending.delete(p),this.send(u,{t:"abort",id:p}),m.resolve(null)}if(u.pending.size===0)this.drop(u)}return}if(l.t==="fallback"){this.retryAt=this.now()+Math.max(Dn,Math.min(l.retry_after_ms,86400000)),this.drop(e);return}if(l.t==="reconnect"&&this.current===e&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(l.after_ms,60000)))}}var Fn=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function Ea(e,a={}){let l=qu(e),u=a.rootPathsSupported===!0?ir(e.root_paths):void 0;return{supported_operations:[...e.supported_operations],...a.accountRootMetadataSupported===!0&&typeof e.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test(e.account_root_fingerprint)?{account_root_fingerprint:e.account_root_fingerprint}:{},...a.workspaceRootMetadataSupported===!0&&typeof e.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test(e.workspace_root_fingerprint)?{workspace_root_fingerprint:e.workspace_root_fingerprint}:{},...a.accountRootPathSupported===!0&&typeof e.account_root_path==="string"&&e.account_root_path.startsWith("/")&&e.account_root_path.length<=4096?{account_root_path:e.account_root_path}:{},...a.homeContainedRootsSupported===!0&&Array.isArray(e.home_contained_root_fingerprints)&&e.home_contained_root_fingerprints.length<=32&&e.home_contained_root_fingerprints.every((p)=>/^[a-f0-9]{64}$/.test(p))?{home_contained_root_fingerprints:[...e.home_contained_root_fingerprints]}:{},...u?{root_paths:u}:{},...Object.keys(l).length?{operation_constraints:l}:{},...e.hands_worker_artifact_sha256&&e.hands_worker_entrypoint?{hands_worker_artifact_sha256:e.hands_worker_artifact_sha256,hands_worker_entrypoint:e.hands_worker_entrypoint}:{},...e.hands_slots!==void 0?{hands_slots:e.hands_slots}:{}}}function qu(e){let a=(u)=>u===null||typeof u==="boolean"||typeof u==="number"&&Number.isFinite(u)||typeof u==="string"&&u.length<=512,l={};for(let u of e.supported_operations){let p=e.operation_constraints?.[u];if(!p||typeof p!=="object"||Array.isArray(p))continue;if(!("ready"in p)||typeof p.ready!=="boolean")continue;let m={};for(let[f,g]of Object.entries(p).slice(0,32)){if(!f.length||f.length>64||["__proto__","constructor","prototype"].includes(f))continue;if(a(g)||Array.isArray(g)&&g.length<=64&&g.every(a))m[f]=g}if(Object.keys(m).length)l[u]=m}return l}class k extends Error{status;code;retryAfter;constructor(e,a,l,u=null){super(l);this.status=e;this.code=a;this.retryAfter=u;this.name="LocalRuntimeHttpError"}}class vr extends Error{timeoutMs;constructor(e){super(`Reason Device request did not answer within ${e}ms.`);this.timeoutMs=e;this.name="LocalRuntimeRequestTimeoutError"}}function or(e){return e===408||e===429||e===500||e===502||e===503||e===504}function sr(e){if(e instanceof k)return!1;if(e instanceof vr)return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!1;if(e instanceof TypeError&&e.message.toLowerCase().includes("fetch failed"))return!0;for(let a of[e,e.cause])if(a&&typeof a==="object"&&"code"in a){let l=String(a.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(l))return!0}return!1}function Wu(e,a,l=500){if(a instanceof k&&a.retryAfter){let m=parseFloat(a.retryAfter);if(Number.isFinite(m)&&m>0)return Math.min(m*1000,1e4)}let u=l*2**e,p=Math.floor(Math.random()*200);return Math.min(u+p,5000)}async function Vu(e,a){if(a?.aborted)throw a.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((l,u)=>{let p=()=>{clearTimeout(m),u(a?.reason??new DOMException("The operation was aborted.","AbortError"))},m=setTimeout(()=>{a?.removeEventListener("abort",p),l()},e);a?.addEventListener("abort",p,{once:!0})})}function ee(e){return e instanceof k&&e.status===401&&(e.code==="device_revoked"||e.code==="invalid_device_credential")}function hs(e){return Buffer.byteLength(JSON.stringify(e)??"null","utf8")}function gs(e){return Hu("sha256").update(e??"").digest("hex")}function zu(e){return Ir({method:e.method,pathAndQuery:e.route,timestamp:e.timestamp,nonce:e.nonce,challenge:e.challenge,bodySha256:e.bodySha256})}function _s(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Gu=20000,Yu=1e4,ys=[2000,4000],Ku=30000,Xu=15000;function ws(e){return e?{keepalive:!1}:{}}class Mn extends Error{constructor(e){super(`Reason Device proof challenge did not answer within ${e}ms.`)}}class ar{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor(e,a=fetch,l,u={}){this.fetchImpl=a;this.proofStore=l;this.proofOptions=u;let p=new URL(e);if(p.protocol!=="https:"&&p.hostname!=="127.0.0.1"&&p.hostname!=="localhost"&&p.hostname!=="[::1]"&&p.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=p.origin}async parseResponse(e){if(e.status===204)return null;let a=await e.json().catch(()=>({}));if(!e.ok){let{code:l,message:u}=zs(a,e.status),p=e.headers?.get?.("retry-after")??null;throw new k(e.status,l,u,p)}return a}async challenge(e,a,l={fresh:!1}){let u=this.proofOptions.challengeAttemptTimeoutsMs??ys;for(let p of u)try{return await this.challengeAttempt(e,a,p,l.fresh)}catch(m){if(a?.aborted||!(m instanceof Mn))throw m;l.fresh=!0}return await this.challengeAttempt(e,a,null,l.fresh)}async challengeAttempt(e,a,l,u=!1){let p=JSON.stringify({device_id:e}),m=l===null?null:new AbortController,f=m&&l!==null?setTimeout(()=>m.abort(new Mn(l)),l):null;try{let g=await this.fetchImpl(`${this.apiOrigin}${M.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:p,...ws(u),signal:m?a?AbortSignal.any([a,m.signal]):m.signal:a});return zi(await this.parseResponse(g))}catch(g){if(!a?.aborted&&m?.signal.aborted)throw m.signal.reason;throw g}finally{if(f)clearTimeout(f)}}async takeSpareChallenge(e){let a=this.spareChallenge;if(this.spareChallenge=null,!a||a.deviceId!==e)return null;let l=await a.challenge,u=(this.proofOptions.now??Date.now)();return l&&Date.parse(l.expires_at)-u>=Gu?l:null}refillSpareChallenge(e){let a=this.challengeAttempt(e,void 0,ys[0]??2000).catch(()=>null);this.spareChallenge={deviceId:e,challenge:a}}async proofHeaders(e,a,l,u,p=!1,m,f){let g=m&&Date.parse(m.expires_at)-(this.proofOptions.now??Date.now)()>=Yu?m:null,b=!g&&p?await this.takeSpareChallenge(l.deviceId):null,y=g??b??await this.challenge(l.deviceId,u,f);if(p)this.refillSpareChallenge(l.deviceId);let h=gs(a),w=this.signProof("POST",e,y.challenge,h);return{"x-device-id":l.deviceId,"x-device-timestamp":w.timestamp,"x-device-nonce":w.nonce,"x-device-challenge":y.challenge,"x-device-body-sha256":h,"x-device-signature":w.signature}}signProof(e,a,l,u){let p=String(Math.trunc((this.proofOptions.now??Date.now)())),m=(this.proofOptions.nonce??(()=>ju(24)))();if(m.byteLength<16||m.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let f=Buffer.from(m).toString("base64url"),g=this.proofStore.sign(zu({method:e,route:a,timestamp:p,nonce:f,challenge:l,bodySha256:u}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(g))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:p,nonce:f,signature:g}}sessionFor(e,a){if(!this.proofOptions.deviceSession||this.sessionsClosed||!a||!fs(e.path))return null;let l=this.sessions.get(a.deviceId);if(!l)l=new Nn({apiOrigin:this.apiOrigin,deviceId:a.deviceId,signHello:(u)=>this.signProof("GET",Ct,u,gs("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(a.deviceId,l);return l}sessionCadence(e){let a=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get(e.deviceId)?.cadence()??null:null;return a?{presenceIntervalMs:a.presence_interval_ms,claimWaitMs:a.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let e of this.sessions.values())e.close();this.sessions.clear()}async request(e,a){if(a.body!==void 0&&hs(a.body)>Je)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(a.authorization!==void 0&&a.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let l=a.authorization!==void 0,u=a.device!==void 0;if(!(e.auth==="none"?!l&&!u:e.auth==="registration_bearer"?l&&!u:l!==u))throw Error(`Reason Device request used invalid authentication for ${e.path}.`);let m=a.body===void 0?void 0:JSON.stringify(a.body),f=this.proofOptions.maxAttempts??4,g=this.proofOptions.sleep??Vu,b=this.sessionFor(e,a.device),y=Math.max(Ku,(a.holdMs??0)+Xu),h={fresh:!1},w;for(let S=0;S<f;S+=1)try{let v=await b?.request(e.path,a.sessionBody===void 0?m??"":JSON.stringify(a.sessionBody),a.signal)??null;if(v)return await this.parseResponse(new Response(v.status===204?null:v.body,{status:v.status,headers:v.retryAfter===null?{}:{"retry-after":v.retryAfter}}));let x=new AbortController,I=setTimeout(()=>x.abort(new vr(y)),y),E=a.signal?AbortSignal.any([a.signal,x.signal]):x.signal;try{let C=a.device===void 0?{}:await this.proofHeaders(e.path,m,a.device,E,a.useSpareChallenge===!0&&S===0,S===0?a.issuedChallenge:void 0,h),O=await this.fetchImpl(`${this.apiOrigin}${e.path}`,{method:"POST",redirect:"error",headers:{...a.authorization===void 0?{}:{authorization:`Bearer ${a.authorization}`},...C,accept:"application/json",...a.body===void 0?{}:{"content-type":"application/json"}},body:m,...ws(h.fresh),signal:E});return await this.parseResponse(O)}catch(C){if(!a.signal?.aborted&&x.signal.aborted)throw x.signal.reason;throw C}finally{clearTimeout(I)}}catch(v){if(w=v,v instanceof vr)h.fresh=!0;if(a.signal?.aborted)throw v;let x=a.device!==void 0&&v instanceof k&&v.status===401&&["invalid_device_proof","device_proof_replayed"].includes(v.code),I=v instanceof k&&or(v.status),E=sr(v),C=a.transientRetryOwner!=="caller"&&(I||E);if((x||C)&&S+1<f){let O=x?0:Wu(S,v,this.proofOptions.retryBaseDelayMs??500);if(O>0)await g(O,a.signal);continue}throw v}throw w??Error("Reason Device request failed.")}async register(e,a,l){let u=await this.request(M.register,{authorization:e,body:a,signal:l});return qs(u)}async enroll(e,a,l,u){let p=await this.request(M.enroll,{body:{...l,enrollment_ticket:e,code_verifier:a},signal:u});return Ws(p)}async heartbeat(e,a,l,u){let p=await this.request(M.heartbeat,{device:e,body:a,signal:l,...u?{issuedChallenge:u}:{}});return Vs(p)}async syncRoots(e,a,l){let u=await this.request(M.rootsSync,{device:e,body:{roots:a},signal:l});return Gs(u)}async identity(e,a){let l=await this.request(M.identity,{device:e,signal:a});return Ks(l)}async disconnect(e,a,l,u=[]){let p=await this.request(M.disconnect,{device:e,body:l?{successor_device_id:l,...u.length?{successor_roots:u}:{}}:{},signal:a});return Js(p)}async deviceLifecycle(e,a,l){let u=await this.request(M.lifecycle,{device:e,body:a,signal:l});Ys(u)}async localSubscription(e,a,l){return Xs(await this.request(M.localSubscription,{device:e,body:a,signal:l}))}async ownerWorkspaces(e,a){let u=(await this.request(M.ownerWorkspaces,{device:e,body:{},signal:a}))?.organizations;if(!Array.isArray(u))throw Error("Reason returned an invalid workspace list.");return u.flatMap((p)=>{let m=p;return typeof m?.id==="string"?[{id:m.id,...typeof m.name==="string"&&m.name.trim()?{name:m.name.trim()}:{},blocked:m.blocked===!0}]:[]})}async ownerWorkspaceEnrollment(e,a,l){return this.request(M.ownerWorkspaceEnrollment,{device:e,body:a,signal:l})}async liveSessionWorktrees(e,a,l){let u=await this.request(M.sessionWorktrees,{device:e,body:{worktree_ids:[...a]},signal:l}).catch((p)=>{if(p instanceof k&&p.status===404)return null;throw p});if(u===null)return null;if(!_s(u)||!Array.isArray(u.live)||!u.live.every((p)=>typeof p==="string"&&a.includes(p)))throw Error("Reason returned an invalid Session worktree answer.");return u.live}async claimOperation(e,a={}){let l=Math.max(a.waitMs??25000,0),u=(f)=>({wait_ms:Math.min(l,f),...a.instanceGeneration===void 0?{}:{instance_generation:a.instanceGeneration}}),p=this.sessionCadence(e)?.claimWaitMs,m=await this.request(M.operationClaim,{device:e,body:u(30000),holdMs:Math.min(l,30000),...p===void 0?{}:{sessionBody:u(Math.min(p,$n))},signal:a.signal});if(m===null)return null;return Zs(m,Fn)}async operationHeartbeat(e,a,l={}){let u=(f)=>this.request(M.operationHeartbeat.forOperation(a.operation_id),{device:e,body:{attempt_id:a.attempt_id,attempt_token:a.attempt_token,...l.controlAckSeq===void 0?{}:{control_ack_seq:l.controlAckSeq},...f?{client_retry_count:l.clientRetryCount}:{},...f&&l.waitMs!==void 0?{wait_ms:Math.min(Math.max(l.waitMs,0),30000)}:{}},signal:l.signal,transientRetryOwner:l.transientRetryOwner,...f&&l.waitMs!==void 0?{holdMs:Math.min(Math.max(l.waitMs,0),30000)}:{}}),p=(l.clientRetryCount??0)>0||l.waitMs!==void 0,m;try{m=await u(p)}catch(f){if(!p||!(f instanceof k)||f.status!==400||f.code!=="invalid_operation_heartbeat")throw f;m=await u(!1)}return Qs(m)}async operationEvents(e,a,l){if(!Number.isInteger(l.eventSeqStart)||l.eventSeqStart<0||l.events.length<1||l.events.length>100||l.events.some((p)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(p.kind)||!_s(p.payload)))throw Error("Invalid Reason Device operation event batch.");let u=await this.request(M.operationEvents.forOperation(a.operation_id),{device:e,body:{attempt_id:a.attempt_id,attempt_token:a.attempt_token,event_seq_start:l.eventSeqStart,events:l.events},signal:l.signal,transientRetryOwner:l.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return ea(u)}async completeOperation(e,a,l,u){let p={attempt_id:a.attempt_id,attempt_token:a.attempt_token,status:l.status,...l.result===void 0?{}:{result:l.result},...l.error_code?{error_code:l.error_code}:{}};if(hs(p)>Je)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let m=await this.request(M.operationComplete.forOperation(a.operation_id),{device:e,body:p,signal:u});return ra(m)}async operationCustomEndpointCredential(e,a,l){let{CustomEndpointDeviceCredentialSchema:u}=await import("./custom-endpoint-device-3xnrp33e.js");return u.parse(await this.request(M.operationCustomEndpointCredential.forOperation(a.operation_id),{device:e,body:{attempt_id:a.attempt_id,attempt_token:a.attempt_token},signal:l}))}async operationEnvironment(e,a,l,u){let p=await this.request(M.operationEnvironment.forOperation(a.operation_id),{device:e,body:{attempt_id:a.attempt_id,attempt_token:a.attempt_token,snapshot_id:l},signal:u,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return ta(p)}async acknowledgeOperationEnvironment(e,a,l,u){await this.request(M.operationEnvironmentAck.forOperation(a.operation_id),{device:e,body:{attempt_id:a.attempt_id,attempt_token:a.attempt_token,...l},signal:u,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var Ju=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),Ut=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 xr(e,a){if(Ju.has(e))return!1;if(Ut.has(e)&&!a.runtimeDirectory)return!1;if((e==="inference.custom.v1"||e==="preview.serve.v1"||e==="simulator.call.v1"||e==="simulator.stream.v1")&&(a.executionMode!=="unsandboxed"||!a.runtimeDirectory))return!1;if(a.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes(e)||Ut.has(e)))return!1;return!0}import{accessSync as Zu,constants as Qu,existsSync as ed,statSync as td}from"fs";import{basename as rd,isAbsolute as nd}from"path";var Ht=["-lic"],Us="/bin/zsh",od=new Set(["zsh","bash"]),sa=20000,Un=60000,id=65536,sd=64,ad=8192,ld=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),cd=["DYLD_","LD_"];function ud(e){let a=e.toUpperCase();return ld.has(a)||cd.some((l)=>a.startsWith(l))}function aa(e=process.env){return!0}function dd(e){if(!nd(e)||e.includes("\x00"))return!1;if(!od.has(rd(e)))return!1;try{if(!td(e).isFile())return!1;return Zu(e,Qu.X_OK),!0}catch{return!1}}function ut(e=process.env){if(process.platform==="win32")return Y()??Us;let a=e.SHELL?.trim();if(a&&dd(a))return a;return Us}function Hn(e=process.env){return aa(e)&&ed(ut(e))}function jn(e=process.env){if(!aa(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")>id)throw new r("invalid_payload","command is missing or too large.");return e}function Yn(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 a=Object.entries(e);if(a.length>sd)throw new r("invalid_payload","env has too many entries.");let l={},u=[];for(let[p,m]of a){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(p)||typeof m!=="string"||m.includes("\x00")||Buffer.byteLength(m,"utf8")>ad)throw new r("invalid_payload","env entry is invalid or too large.");if(ud(p)){u.push(p);continue}l[p]=m}return{forwarded:l,ignored:u}}async function la(e){let a=e.processEnv??process.env;if(jn(a),e.signal.aborted)throw new r("cancelled","Operation was cancelled.");let l=zn(e.command),u=ut(a),{forwarded:p,ignored:m}=Yn(e.requestEnv),f=await e.spawn(u,[...Ht,l],{cwd:e.cwd,timeoutMs:e.timeoutMs,signal:e.signal,env:{...a,...p}});return{exit_code:f.exitCode,signal:f.signal,stdout:f.stdout,stderr:f.stderr,timed_out:f.timedOut,truncated:f.truncated,shell:u,shell_flags:[...Ht],login:!0,interactive:!0,sandbox:"none",ignored_env:m}}function ca(e=process.env){return{transport:"shell",shell:`${ut(e)} ${Ht.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:Un}}import{readFile as pd,readdir as md,readlink as fd,realpath as hd}from"fs/promises";import{basename as gd,relative as _d,sep as yd}from"path";var nt="/proc",bd=250,ua=500,wd=50,Sd=250,vd=1024,da=4096,Rd=1,xd=3,pa=9,Ed="0A",Cd=/^socket:\[(\d+)\]$/,Jn={readDirectory:(e)=>md(e),readLink:(e)=>fd(e),readTextFile:(e)=>pd(e,"utf8"),realPath:(e)=>hd(e)};function fa(e,a){return a===e||a.startsWith(`${e}${yd}`)}function Pd(e,a){return _d(e,a)||"."}async function ha(e){let a;try{a=await e.readDirectory(nt)}catch{return[]}return a.filter((l)=>/^[0-9]+$/.test(l)).map((l)=>Number(l)).filter((l)=>Number.isSafeInteger(l)&&l>0).sort((l,u)=>l-u)}async function ga(e,a){try{let u=(await a.readTextFile(`${nt}/${e}/comm`)).slice(0,da).split(`
|
|
37
|
+
`,1)[0]?.trim();if(u)return u}catch{}try{let u=(await a.readTextFile(`${nt}/${e}/cmdline`)).slice(0,da).split("\x00",1)[0]?.trim();return u?gd(u):null}catch{return null}}async function _a(e,a=Jn){let l;try{l=await a.readLink(`${nt}/${e}/cwd`)}catch{return null}if(!l)return null;try{return await a.realPath(l)}catch{return null}}async function ya(e,a=Jn){let l=[];for(let u of await ha(a)){if(l.length>=bd)break;let p=await _a(u,a);if(!p||!fa(e,p))continue;l.push({pid:u,command:await ga(u,a),cwd:Pd(e,p)})}return{processes:l}}function ma(e){let a=[];for(let l=0;l<8;l+=2)a.unshift(Number.parseInt(e.slice(l,l+2),16));return a}function Od(e){let a=[];for(let b=0;b<16;b+=2)a.push(e[b]<<8|e[b+1]);if(a.slice(0,5).every((b)=>b===0)&&a[5]===65535)return`::ffff:${e.slice(12).join(".")}`;let l=-1,u=0,p=-1;for(let b=0;b<=a.length;b+=1){if(b<a.length&&a[b]===0){if(p<0)p=b;continue}if(p>=0){let y=b-p;if(y>u)l=p,u=y;p=-1}}let m=a.map((b)=>b.toString(16));if(u<2)return m.join(":");let f=m.slice(0,l).join(":"),g=m.slice(l+u).join(":");return`${f}::${g}`}function Id(e,a){if(/^[0-9A-Fa-f]{8}$/.test(e)){let l=ma(e);if(l.every((u)=>u===0))return`*:${a}`;return`${l.join(".")}:${a}`}if(/^[0-9A-Fa-f]{32}$/.test(e)){let l=[];for(let u=0;u<4;u+=1)l.push(...ma(e.slice(u*8,u*8+8)));if(l.every((u)=>u===0))return`*:${a}`;return`[${Od(l)}]:${a}`}return null}function Ad(e,a){let l=[];for(let u of e.split(`
|
|
38
|
+
`).slice(1)){if(l.length>=a)break;let p=u.trim().split(/\s+/);if(p.length<=pa)continue;if(p[xd]?.toUpperCase()!==Ed)continue;let m=p[Rd]??"",f=m.lastIndexOf(":");if(f<0)continue;let g=Number.parseInt(m.slice(f+1),16);if(!Number.isInteger(g)||g<=0||g>65535)continue;let b=Id(m.slice(0,f),g),y=p[pa];if(!b||!y||!/^[0-9]+$/.test(y))continue;l.push({inode:y,port:g,address:b})}return l}async function Ld(e){let a=[];for(let l of["tcp","tcp6"]){if(a.length>=ua)break;let u;try{u=await e.readTextFile(`${nt}/net/${l}`)}catch{continue}a.push(...Ad(u,ua-a.length))}return a}async function kd(e,a){let l=new Map;if(e.size===0)return l;for(let u of await ha(a)){if(l.size>=e.size)break;let p;try{p=await a.readDirectory(`${nt}/${u}/fd`)}catch{continue}for(let m of p.slice(0,vd)){let f;try{f=await a.readLink(`${nt}/${u}/fd/${m}`)}catch{continue}let g=f.match(Cd)?.[1];if(!g||!e.has(g)||l.has(g))continue;l.set(g,u)}}return l}async function ba(e,a=Jn){let l=await Ld(a),u=await kd(new Set(l.map((h)=>h.inode)),a),p=[];for(let h of l){let w=u.get(h.inode);if(w===void 0)continue;p.push({pid:w,port:h.port,address:h.address})}p.sort((h,w)=>h.pid-w.pid||h.port-w.port||(h.address<w.address?-1:h.address>w.address?1:0));let m=[...new Set(p.map((h)=>h.pid))].slice(0,wd),f=await Promise.all(m.map(async(h)=>[h,await _a(h,a)])),g=new Map(f),b=p.filter((h)=>{let w=g.get(h.pid);return Boolean(w&&fa(e,w))}),y=new Map(await Promise.all([...new Set(b.map((h)=>h.pid))].map(async(h)=>[h,await ga(h,a)])));return{ports:b.slice(0,Sd).map((h)=>({pid:h.pid,command:y.get(h.pid)??null,address:h.address}))}}import{posix as Qn}from"path";var Er=200,Td=250,Dd=250;async function Cr(e,a){let l=await e(a);if(l.timedOut||l.truncated||l.exitCode!==0&&l.exitCode!==1)throw new r("process_inspection_failed","Reading this Mac's processes did not complete.");let u=[],p=null;for(let m of l.stdout.split(/\r?\n/))if(m.startsWith("p")){let f=Number(m.slice(1));if(p=Number.isInteger(f)&&f>0?{pid:f,command:null,names:[]}:null,p)u.push(p)}else if(p&&m.startsWith("c"))p.command=m.slice(1)||null;else if(p&&m.startsWith("n"))p.names.push(m.slice(1));return u}function Zn(e,a){return a===e||a.startsWith(e==="/"?e:`${e}/`)}var wa="/System/Volumes/Data",Nd=["/tmp","/var","/etc"];function eo(e){let a=Qn.normalize(e);if(a.startsWith(`${wa}/`))a=a.slice(wa.length);return Nd.find((u)=>a===u||a.startsWith(`${u}/`))?`/private${a}`:a}function Sa(e){return e&&Qn.isAbsolute(e)?eo(e):null}async function va(e,a){let l=new Map;for(let u=0;u<a.length;u+=Er){let p=a.slice(u,u+Er).join(",");for(let m of await Cr(e,["-a","-p",p,"-d","cwd","-Fpcn"]))l.set(m.pid,{command:m.command,cwd:Sa(m.names[0])})}return l}async function Ra(e,a){let l=eo(e),u=(await Cr(a,["-d","cwd","-Fpn"])).filter((m)=>{let f=Sa(m.names[0]);return f!==null&&Zn(l,f)}).map((m)=>m.pid).slice(0,Td),p=await va(a,u);return{processes:u.flatMap((m)=>{let f=p.get(m);return f?.cwd&&Zn(l,f.cwd)?[{pid:m,command:f.command,cwd:Qn.relative(l,f.cwd)||"."}]:[]})}}async function xa(e,a){let l=eo(e),u=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],p=await Cr(a,u),m=await va(a,p.map((y)=>y.pid)),f=p.map((y)=>y.pid).filter((y)=>{let h=m.get(y)?.cwd;return Boolean(h&&Zn(l,h))});if(f.length===0)return{ports:[]};let g=new Set(p.flatMap((y)=>y.names.map((h)=>`${y.pid} ${h}`))),b=[];for(let y=0;y<f.length;y+=Er){let h=f.slice(y,y+Er).join(",");for(let w of await Cr(a,["-a","-p",h,...u]))for(let S of w.names)if(g.has(`${w.pid} ${S}`))b.push({pid:w.pid,command:w.command,address:S})}return{ports:b.slice(0,Dd)}}import{join as Gd}from"path";import{spawn as Hd}from"child_process";import{randomUUID as jd}from"crypto";import{chmodSync as La,lstatSync as ka,mkdirSync as qd,readdirSync as Wd,statSync as Vd,unlinkSync as zd}from"fs";import{join as ro}from"path";var to={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var Pr=(e,a=0,l=1e6)=>typeof e==="number"&&Number.isFinite(e)&&e>=a&&e<=l;var ot=()=>{throw Error("proof_visual_contract_invalid")};class Ca extends Error{constructor(){super("proof_visual_contract_invalid")}}function co(e){if(!q(e)||e.version!==1)return ot();if(typeof e.route!=="string"||!e.route.startsWith("/")||e.route.length>512||/[\x00-\x20\x7f\\?#%]/.test(e.route)||e.route.startsWith("//"))throw new Ca;if(!q(e.viewport)||!Pr(e.viewport.width,1,4096)||!Pr(e.viewport.height,1,4096)||!Array.isArray(e.targets)||e.targets.length<1||e.targets.length>to.targets||Object.keys(e).some((u)=>!["version","route","viewport","targets","additionalViewports"].includes(u)))return ot();let a=e.targets.map((u)=>{if(!q(u)||typeof u.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(u.id)||typeof u.selector!=="string"||!u.selector.trim()||u.selector.length>256||/[\x00-\x1f\x7f]/.test(u.selector)||Object.keys(u).some((p)=>!["id","selector"].includes(p)))return ot();return{id:u.id,selector:u.selector}});if(new Set(a.map((u)=>u.id)).size!==a.length)return ot();let l;if(e.additionalViewports!==void 0){if(!Array.isArray(e.additionalViewports)||e.additionalViewports.length<1||e.additionalViewports.length>3)return ot();l=e.additionalViewports.map((p)=>{if(!q(p)||!Pr(p.width,1,4096)||!Number.isInteger(p.width)||!Pr(p.height,1,4096)||!Number.isInteger(p.height)||Object.keys(p).some((m)=>!["width","height"].includes(m)))return ot();return{width:p.width,height:p.height}});let u=[e.viewport,...l].map((p)=>`${p.width}x${p.height}`);if(new Set(u).size!==u.length)return ot()}return{version:1,route:e.route,viewport:{width:e.viewport.width,height:e.viewport.height},targets:a,...l?{additionalViewports:l}:{}}}var Bd=["organizationId","userId","sessionId","runId"],Fd=[...Bd,"prUrl","headSha","skillDigest","evidenceKind"],Hh=[...Fd,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var Ud={"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 Aa(e){return Ud[e].directory}var Da=10485760;function $a(e={}){let a=e.directory??Aa("video/webm"),l=null;return{async start(u){if(l)throw Error("cloud_browser_recording_active");let p=u?.seconds;if(!Number.isInteger(p)||Number(p)<1||Number(p)>15||!u||Object.keys(u).some((E)=>E!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");qd(a,{recursive:!0,mode:457});let m=ka(a);if(!m.isDirectory()||m.isSymbolicLink()||m.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");La(a,457);let f=Wd(a).filter((E)=>/^[a-f0-9-]{36}\.webm$/.test(E)).map((E)=>({name:E,time:Vd(ro(a,E)).mtimeMs})).sort((E,C)=>C.time-E.time);for(let E of f.slice(9))zd(ro(a,E.name));let g=ro(a,`${jd()}.webm`),b=["-f","x11grab","-framerate","12","-i",e.display??":99"],y=(e.spawn??Hd)(e.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...b,"-t",String(p),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(Da),"-progress","pipe:1",g],{stdio:["ignore","pipe","ignore"],...e.env?{env:e.env}:{}}),h,w,S=!1,v=new Promise((E,C)=>{h=E,w=C});y.stdout.on("data",(E)=>{if(/frame=\s*[1-9]/.test(String(E)))S=!0,h()});let x=new Promise((E,C)=>{y.once("error",()=>{w(Error("cloud_browser_recording_unavailable")),C(Error("cloud_browser_recording_unavailable"))}),y.once("exit",(O)=>{try{if(O!==0&&O!==255)throw Error();let D=ka(g);if(!S||!D.isFile()||D.isSymbolicLink()||D.uid!==process.getuid?.()||D.size<128||D.size>Da+65536)throw Error();La(g,420),h(),E({path:g,mimeType:"video/webm"})}catch{w(Error("cloud_browser_recording_failed")),C(Error("cloud_browser_recording_failed"))}})});x.catch(()=>{});let I=setTimeout(()=>y.kill("SIGKILL"),(Number(p)+5)*1000);x.finally(()=>clearTimeout(I)).catch(()=>{}),l={done:x,stop:()=>(y.kill("SIGINT"),x)};try{await v}catch(E){throw l=null,E}return{recording:!0,seconds:Number(p)}},async stop(){if(!l)throw Error("cloud_browser_recording_not_started");let u=l;return l=null,u.stop()},async close(){if(l)await this.stop().catch(()=>{})}}}function qa(e,a={}){if(e.executionMode!=="unsandboxed"||!e.runtimeDirectory||(a.platform??process.platform)!=="linux")return null;let l=(a.components??T)(),u=l?.features.display?l.ffmpeg:null;if(!u)return null;let p=Gd(e.runtimeDirectory,"recordings"),m=null;return{async start(f){let g=await(a.desktop??Ft)();return m??=$a({directory:p,display:g.display,ffmpeg:u,env:{HOME:s(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:g.xauthority},...a.spawn?{spawn:a.spawn}:{}}),m.start(f)},async stop(){if(!m)throw Error("cloud_browser_recording_not_started");return m.stop()},async close(){await m?.close()}}}import{spawn as Mo}from"child_process";import{createHash as mp,randomUUID as fp}from"crypto";import{existsSync as Ae,mkdirSync as Ao,mkdtempSync as Bo,readdirSync as qr,readFileSync as Fo,renameSync as hp,rmSync as Wt,statSync as Fr,writeFileSync as gp}from"fs";import{homedir as Uo,tmpdir as fl}from"os";import{basename as hl,dirname as ko,join as K,relative as gl,resolve as To,sep as _l}from"path";var _e=t().min(1).max(200),Ie=o().finite().min(0).max(1e4),kr=t().min(1).max(4096).refine((e)=>!e.includes("\x00")),Wa=t().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),oo=n({id:t().min(1).max(500).optional(),label:t().min(1).max(500).optional()}).strict(),io=["home","lock","side_button","siri","apple_pay"],Yd=c(["tree","screenshot","both","none"]),Kd=n({...oo.shape,gone:_().optional()}).strict().refine((e)=>Boolean(e.id||e.label),"wait_for needs an id or label"),Ge={observe:Yd.optional(),wait_for:Kd.optional(),timeout:o().min(0).max(20).optional()},no=A("action",[n({action:i("tap"),x:Ie.optional(),y:Ie.optional(),...oo.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:Ie,y:Ie,x2:Ie,y2:Ie,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:c(io)}).strict(),n({action:i("sleep"),seconds:o().min(0).max(10)}).strict()]),go=A("action",[n({action:i("devices")}).strict(),n({action:i("boot"),device:_e}).strict(),n({action:i("shutdown"),device:_e}).strict(),n({action:i("build"),path:kr.optional(),scheme:t().min(1).max(200).optional(),configuration:t().min(1).max(100).optional(),device:_e.optional(),wait:_().optional()}).strict(),n({action:i("run"),path:kr.optional(),scheme:t().min(1).max(200).optional(),configuration:t().min(1).max(100).optional(),device:_e.optional(),steps:d(qc(()=>no)).max(30).optional(),...Ge}).strict(),n({action:i("build_status"),build_id:t().regex(/^build-[0-9a-z-]{4,64}$/),device:_e.optional(),wait:_().optional()}).strict(),n({action:i("launch"),device:_e.optional(),app_path:kr.optional(),bundle_id:Wa.optional(),steps:d(qc(()=>no)).max(30).optional(),...Ge}).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:_e.optional(),bundle_id:Wa}).strict(),n({action:i("logs"),device:_e.optional(),after:o().int().min(0).optional()}).strict(),n({action:i("screenshot"),device:_e.optional(),scale:we([i(1),i(2)]).optional(),save_path:kr.optional()}).strict(),n({action:i("chrome"),device:_e.optional()}).strict(),n({action:i("inspect"),device:_e.optional()}).strict(),n({action:i("tap"),device:_e.optional(),x:Ie.optional(),y:Ie.optional(),...oo.shape,duration:o().min(0).max(10).optional(),...Ge}).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:_e.optional(),x:Ie,y:Ie,x2:Ie,y2:Ie,duration:o().min(0.05).max(5).optional(),...Ge}).strict(),n({action:i("type"),device:_e.optional(),text:t().min(1).max(4000),...Ge}).strict(),n({action:i("button"),device:_e.optional(),name:c(io),...Ge}).strict(),n({action:i("open_url"),device:_e.optional(),url:t().min(1).max(4000),...Ge}).strict(),n({action:i("steps"),device:_e.optional(),steps:d(no).min(1).max(30),...Ge}).strict(),n({action:i("appearance"),device:_e.optional(),mode:c(["light","dark"])}).strict()]),Va=n({udid:t(),name:t(),runtime:t(),state:c(["booted","shutdown","booting","shutting_down"]),kind:c(["iphone","ipad","other"])}).strict(),sg=n({text:t(),error:t().optional(),device:Va.optional(),devices:d(Va).optional(),image:n({mime:i("image/jpeg"),data:t(),width:o(),height:o()}).strict().optional(),build:n({id:t(),status:c(["running","succeeded","failed"]),app_path:t().optional(),bundle_id:t().optional(),errors:d(t()),log_tail:t(),elapsed_ms:o()}).strict().optional(),logs:n({lines:d(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:$e(c(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),n({image:t(),width:o(),height:o()}).strict()),buttons:d(n({name:t(),image:t(),x:o(),y:o(),width:o(),height:o()}).strict())}).strict().optional()}).strict();var ag=n({device_id:V().optional(),root_id:V().optional()}),Mr={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:[...io],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."}},Ya=go.options.map((e)=>e.shape).filter((e)=>e.action.value!=="chrome"),Xd={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},Ga=new Set;function Jd(e,a){let{description:l,...u}=e==="steps"&&a==="steps"?{...Mr.steps,minItems:1}:Mr[e];if(l===void 0||Ga.has(e))return u;return Ga.add(e),{...u,description:l}}var Zd=Ya.flatMap((e)=>{let a=e.action.value,l=Object.keys(e).filter((p)=>Object.hasOwn(Mr,p)),u=l.filter((p)=>!e[p].safeParse(void 0).success);return(Xd[a]??[{required:[]}]).map((p)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:a}],...["device_id","root_id",...l].filter((m)=>!p.without?.includes(m)).map((m)=>[m,Jd(m,a)])]),required:["action",...u,...p.required],additionalProperties:!1}))}),Qd={type:"object",properties:{action:{type:"string",enum:Ya.map((e)=>e.action.value)},...Mr},required:["action"],additionalProperties:!1},lg={...Qd,anyOf:Zd};import{spawn as Ro}from"child_process";import{createHash as tp}from"crypto";import{existsSync as yo,mkdirSync as $r,mkdtempSync as rp,readdirSync as Xa,readFileSync as Ja,renameSync as np,rmSync as el,symlinkSync as So,writeFileSync as jt}from"fs";import{homedir as op}from"os";import{dirname as ol,join as re}from"path";import{createInterface as ip}from"readline";var _o=`// 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 tl=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",sp=180000,ap=15000,lp=30000,cp=600000,up=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map((e)=>`@interface ${e} : NSObject
|
|
498
|
+
@end
|
|
499
|
+
`).join("");function rl(e,a,l){return new Promise((u)=>{let p=Ro(e,a,{stdio:["ignore","pipe","pipe"],timeout:l}),m="";p.stdout.on("data",(f)=>{m+=f}),p.stderr.on("data",(f)=>{m+=f}),p.once("error",(f)=>u({code:-1,output:String(f)})),p.once("close",(f)=>u({code:f??-1,output:m}))})}var nl=new Map;function xo(e){let a=re(ol(e),"Frameworks"),l=nl.get(a);if(!l)nl.set(a,l=dp(a));return l}async function dp(e){if(process.platform!=="darwin"||!yo(re(e,"FBSimulatorControl.framework")))return null;let a=await rl("xcrun",["swiftc","--version"],30000);if(a.code!==0)return null;let l=tp("sha256").update(_o).update(a.output).update(e).digest("hex").slice(0,16),u=re(op(),".local","share","reason","simulator","host"),p=re(u,l,"simulator-host");if(yo(p))return p;$r(u,{recursive:!0,mode:448});let m=rp(re(u,".staging-"));try{let f=re(m,"Frameworks"),g=re(f,"FBSimulatorControl.framework"),b=re(g,"Modules","FBSimulatorControl.swiftmodule");$r(b,{recursive:!0});for(let I of Xa(e))if(I!=="FBSimulatorControl.framework")So(re(e,I),re(f,I));let y=re(e,"FBSimulatorControl.framework");So(re(y,"FBSimulatorControl"),re(g,"FBSimulatorControl")),So(re(y,"Headers"),re(g,"Headers")),jt(re(g,"Modules","module.modulemap"),Ja(re(y,"Modules","module.modulemap")));let h=Ja(re(y,"Modules","FBSimulatorControl.swiftmodule",`${tl}.swiftinterface`),"utf8");jt(re(b,`${tl}.swiftinterface`),h.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let w=re(m,"include","CoreSimulator");$r(w,{recursive:!0}),jt(re(w,"module.modulemap"),`module CoreSimulator {
|
|
500
|
+
header "CoreSimulator.h"
|
|
501
|
+
export *
|
|
502
|
+
}
|
|
503
|
+
`),jt(re(w,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
|
|
504
|
+
${up}`);let S=re(m,"main.swift");jt(S,_o);let v=re(m,"simulator-host"),x=await rl("xcrun",["swiftc","-O","-F",f,"-I",re(m,"include"),"-module-cache-path",re(m,"cache"),"-Xlinker","-rpath","-Xlinker",e,S,"-o",v],sp);if(x.code!==0||!yo(v))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
|
|
505
|
+
${x.output.slice(-2000)}
|
|
506
|
+
`),null;$r(ol(p),{recursive:!0}),np(v,p);for(let I of Xa(u))if(I!==l&&!I.startsWith(".staging-"))el(re(u,I),{recursive:!0,force:!0});return p}catch{return null}finally{el(m,{recursive:!0,force:!0})}}class qt extends Error{}class ht extends Error{}class il{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor(e,a){this.child=e;this.onGone=a;ip({input:e.stdout}).on("line",(u)=>{let p;try{p=JSON.parse(u)}catch{return}let m=this.pending.get(Number(p.id));if(!m)return;if(this.pending.delete(Number(p.id)),clearTimeout(m.timer),p.ok===!0)m.resolve(p);else m.reject(new qt(String(p.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 ht("The simulator host has exited."));this.touch();let a=this.nextId++;return new Promise((l,u)=>{let p=setTimeout(()=>{this.pending.delete(a),u(new ht("The simulator host did not answer.")),this.close()},lp);this.pending.set(a,{resolve:l,reject:u,timer:p}),this.child.stdin.write(`${JSON.stringify({id:a,...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(),cp),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 ht("The simulator host has exited."));this.pending.clear(),this.onGone()}}var ft=new Map;async function Br(e,a,l=!1){let u=ft.get(a);if(!u){let p={started:pp(e,a)};ft.set(a,u=p),p.started.then((m)=>{if(p.host=m,!m&&ft.get(a)===p)ft.delete(a)})}if(u.host!==void 0)return u.host;return l?u.started:null}async function pp(e,a){let l=await xo(e);if(!l)return null;let u=Ro(l,["serve",a],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((f)=>{let g=setTimeout(()=>f(!1),ap);u.stdout.once("data",(b)=>{clearTimeout(g),f(String(b).includes('"ready":true'))}),u.once("exit",()=>{clearTimeout(g),f(!1)}),u.once("error",()=>{clearTimeout(g),f(!1)})})){if(u.exitCode===null)u.kill("SIGTERM");return null}let m=new il(u,()=>{let f=ft.get(a);if(f&&(f.host===m||f.host===void 0))ft.delete(a)});return m}function sl(e,a,l,u,p){return Ro(e,["stream",a,String(l),String(Math.round(u)),String(p)],{stdio:["pipe","pipe","ignore"]})}var gt={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"},_p=50000,yp=112640,bp=174080,Eo=2,wp=60000,Sp=2000,vp=300,Rp=40,xp=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function wt(e,a,l={}){return new Promise((u,p)=>{let m=Mo(e,a,{cwd:l.cwd,stdio:["ignore","pipe","pipe"],signal:l.signal}),f=[],g=[];m.stdout.on("data",(y)=>f.push(y)),m.stderr.on("data",(y)=>g.push(y));let b=setTimeout(()=>m.kill("SIGKILL"),l.timeoutMs??_p);m.on("error",(y)=>{clearTimeout(b),p(y)}),m.on("close",(y)=>{clearTimeout(b),u({code:y??-1,stdout:Buffer.concat(f).toString("utf8"),stderr:Buffer.concat(g).toString("utf8")})})})}function Q(e,a){throw new r(e,a)}async function fe(e,a,l,u={}){let p=await wt(e,a,u);if(p.code!==0)Q("simulator_command_failed",`${l} failed: ${(p.stderr||p.stdout).trim().slice(-1500)}`);return p.stdout}function Vt(){return process.platform==="darwin"&&Ae("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Ae("/usr/bin/xcrun")}var Co=null;function it(){return K(Uo(),".local","share","reason","simulator","axe")}function Ho(){let e=K(it(),gt.version,"axe");if(Ae(e))return Promise.resolve(e);return Co??=(async()=>{Ao(it(),{recursive:!0,mode:448});let a=Bo(K(it(),".staging-"));try{let l=K(a,"axe.tgz");await dc(gt.url,gt.sha256,l);let u=K(a,"tree");if(Ao(u),await fe("tar",["-xzf",l,"-C",u],"Extracting AXe"),!Ae(K(u,"axe"))||!Ae(K(u,"Frameworks")))Q("simulator_axe_missing","The AXe archive has an unexpected layout.");Wt(K(it(),gt.version),{recursive:!0,force:!0}),hp(u,K(it(),gt.version));for(let p of qr(it()))if(p!==gt.version&&!p.startsWith(".staging-"))Wt(K(it(),p),{recursive:!0,force:!0});return e}finally{Wt(a,{recursive:!0,force:!0}),Co=null}})(),Co}var yl=Ho;async function bl(e){let a=await Ho().catch(()=>null);return a?Br(a,e.udid).catch(()=>null):null}async function Ur(e,a,l){let u=await Ho().catch(()=>Q("simulator_axe_missing","AXe could not be installed on this Mac.")),p=await wt(u,[...e,"--udid",a]);if(p.code===0)return p.stdout;let m=(p.stderr||p.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(m))Q("simulator_element_not_found",m.slice(-500));return Q("simulator_command_failed",`${l} failed: ${m.slice(-1500)}`)}function Ep(e){let a=e.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return a?`${a[1]} ${a[2]}.${a[3]}${a[4]?`.${a[4]}`:""}`:e}function Cp(e){switch(e){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function jo(){let a=JSON.parse(await fe("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},l=[];for(let[u,p]of Object.entries(a)){if(!u.includes("SimRuntime.iOS"))continue;for(let m of p){if(m.isAvailable===!1)continue;let f=m.name.toLowerCase();if(m.deviceTypeIdentifier)Do.set(m.udid,m.deviceTypeIdentifier);l.push({udid:m.udid,name:m.name,runtime:Ep(u),state:Cp(m.state),kind:f.includes("iphone")?"iphone":f.includes("ipad")?"ipad":"other"})}}return l.sort((u,p)=>Number(p.state==="booted")-Number(u.state==="booted")||p.runtime.localeCompare(u.runtime,void 0,{numeric:!0})||u.name.localeCompare(p.name))}var Do=new Map,No=null;async function be(e,a){let l=await jo(),u;if(e){let p=l.filter((m)=>m.udid===e||m.name===e);if(u=p.find((m)=>m.state==="booted")??p[0],!u)Q("simulator_device_not_found",`No simulator named "${e}". Call devices to list them.`)}else{let p=l.filter((m)=>m.state==="booted");if(u=p.find((m)=>m.udid===No)??p.find((m)=>m.kind==="iphone")??p[0],!u)Q("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(a.booted&&u.state!=="booted")Q("simulator_not_booted",`${u.name} is not booted. Boot it first.`);return No=u.udid,u}function ae(e){return`${e.name} (${e.runtime})`}async function Pp(e){if(e.state!=="booted"){let a=await wt("xcrun",["simctl","boot",e.udid]);if(a.code!==0&&!/current state: Booted/i.test(a.stderr))Q("simulator_command_failed",`Booting ${e.name} failed: ${a.stderr.trim().slice(-1000)}`);await fe("xcrun",["simctl","bootstatus",e.udid,"-b"],`Waiting for ${e.name} to boot`,{timeoutMs:45000})}return No=e.udid,{...e,state:"booted"}}function qo(e,a){let l=To(e,a),u=gl(e,l);if(u.startsWith("..")||u.startsWith(_l)||To(e,u)!==l)Q("simulator_path_outside_root",`${a} is outside this machine's granted folder (${e}). Pass a path inside it, or one relative to it.`);return l}var al=4,Op=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function Ip(e){let a=[],l=(u,p)=>{let m;try{m=qr(u)}catch{return}if(m.includes("project.yml")||m.some((f)=>f.endsWith(".xcworkspace")||f.endsWith(".xcodeproj"))){a.push(u);return}if(p>=al)return;for(let f of m.sort()){if(f.startsWith(".")||Op.has(f))continue;let g=K(u,f);try{if(Fr(g).isDirectory())l(g,p+1)}catch{}}};if(l(e,0),a.length===1)return a[0];if(!a.length)Q("simulator_project_not_found",`No Xcode project or project.yml within ${al} folders of ${e}; pass path.`);return Q("simulator_project_not_found",`${e} holds several Xcode projects; pass path as one of: ${a.map((u)=>gl(e,u)||".").join(", ")}.`)}var yt=new Map;async function Ap(e){if(e.endsWith(".xcworkspace"))return{flag:"-workspace",path:e,dir:ko(e)};if(e.endsWith(".xcodeproj"))return{flag:"-project",path:e,dir:ko(e)};if(!Fr(e).isDirectory())Q("simulator_project_not_found",`${e} is not a project, workspace or folder.`);let a=(p)=>qr(e).filter((m)=>m.endsWith(p)).sort();if(Ae(K(e,"project.yml")))await fe("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:e,timeoutMs:45000}).catch((p)=>Ae("/opt/homebrew/bin/xcodegen")?fe("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:e,timeoutMs:45000}):Promise.reject(p));let l=a(".xcworkspace")[0];if(l)return{flag:"-workspace",path:K(e,l),dir:e};let u=a(".xcodeproj")[0];if(u)return{flag:"-project",path:K(e,u),dir:e};return Q("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${e}.`)}async function wl(e){let a=JSON.parse(await fe("xcodebuild",["-list","-json",e.flag,e.path],"Listing schemes"));return a.workspace?.schemes??a.project?.schemes??[]}async function Lp(e){let a=(await wl(e))[0];if(!a)Q("simulator_build_no_scheme",`${e.path} has no schemes; pass scheme.`);return a}function kp(e){let a=[],l=new Set;return e.forEach((u,p)=>{if(a.length>=20||!/(^|\s)error: /.test(u)||u.startsWith("note:")||l.has(u))return;l.add(u);let m=e.slice(p+1,p+3).filter((f)=>f.trim()!==""&&!/(^|\s)(error|warning|note): /.test(f));a.push([u,...m].join(`
|
|
508
|
+
`).slice(0,800))}),a}async function Tp(e,a,l){if(e.ended=Date.now(),a!==0){if(e.log.some((m)=>m.includes("does not contain a scheme named"))){let m=await wl(l).catch(()=>[]);if(m.length)e.log.push(`error: this project's schemes are: ${m.join(", ")}`)}e.status="failed";return}let u=K(e.productsDir,`${e.configuration}-iphonesimulator`),p=Ae(u)?qr(u).filter((m)=>m.endsWith(".app")).map((m)=>K(u,m)).sort((m,f)=>Fr(f).mtimeMs-Fr(m).mtimeMs):[];if(e.appPath=p[0],e.appPath)e.bundleId=await Rl(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 ll(e,a){let l=e.path?qo(a,e.path):Ip(a),u=await Ap(l),p=e.scheme??await Lp(u),m=e.configuration??"Debug",f=await be(e.device,{booted:!1}).catch(()=>null),g=f?`platform=iOS Simulator,id=${f.udid}`:"generic/platform=iOS Simulator",b=mp("sha256").update(u.path).digest("hex").slice(0,16),y=K(Uo(),"Library","Caches","reason","simulator-builds",b),h={id:`build-${fp().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:K(y,"Build","Products"),configuration:m};yt.set(h.id,h);for(let[x,I]of yt)if(yt.size>20&&I.status!=="running")yt.delete(x);let w=Mo("xcodebuild",[u.flag,u.path,"-scheme",p,"-configuration",m,"-destination",g,"-derivedDataPath",y,"-skipMacroValidation","build"],{cwd:u.dir,stdio:["ignore","pipe","pipe"]}),S="",v=(x)=>{let I=(S+x.toString("utf8")).split(`
|
|
509
|
+
`);if(S=I.pop()??"",h.log.push(...I),h.log.length>5000)h.log.splice(0,h.log.length-5000)};return w.stdout.on("data",v),w.stderr.on("data",v),w.on("error",(x)=>{h.log.push(`error: ${x.message}`),h.status="failed",h.ended=Date.now()}),w.on("close",(x)=>{if(S)h.log.push(S);Tp(h,x??-1,u)}),{text:`Build ${h.id} started: ${p} (${m}) for ${f?ae(f):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:Sl(h)}}function Sl(e){return{id:e.id,status:e.status,errors:kp(e.log),log_tail:e.log.slice(-Rp).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 Dp=45000,Np=30000;async function Po(e,a=Dp){let l=Date.now()+a;while(yt.get(e)?.status==="running"&&Date.now()<l)await Bun.sleep(500);let u=vl(e);return u.build?.status==="running"?{...u,text:`${u.text} Still running: call build_status with wait again.`}:u}function vl(e){let a=yt.get(e);if(!a)Q("simulator_build_not_found",`No build ${e} on this Mac (a worker restart forgets builds); start a new one.`);let l=Sl(a);return{text:a.status==="running"?`Build ${e} is running (${Math.round(l.elapsed_ms/1000)} s).`:a.status==="succeeded"?`Build ${e} succeeded: ${a.appPath}. Launch it with app_path.`:`Build ${e} failed with ${l.errors.length} error(s).`,build:l}}async function Rl(e){return(await fe("plutil",["-extract","CFBundleIdentifier","raw","-o","-",K(e,"Info.plist")],"Reading the bundle id")).trim()}var Ye=new Map;function Mp(e,a){Ye.get(e.udid)?.stop();let l=Mo("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",e.udid,a],{stdio:["ignore","pipe","pipe"]}),u={udid:e.udid,bundleId:a,lines:[],first:0,stop:()=>l.kill("SIGTERM")};Ye.set(e.udid,u);let p="",m=(f)=>{let g=(p+f.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
|
|
511
|
+
`);p=g.pop()??"",u.lines.push(...g);let b=u.lines.length-Sp;if(b>0)u.lines.splice(0,b),u.first+=b};return l.stdout.on("data",m),l.stderr.on("data",m),new Promise((f)=>{let g=setTimeout(()=>f(null),15000),b=()=>{let y=u.lines.concat(p).join(`
|
|
512
|
+
`).match(new RegExp(`${a.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(y)clearTimeout(g),f(Number(y))};l.stdout.on("data",b),l.on("close",()=>{clearTimeout(g),f(null)})})}async function $p(e,a){let l=await be(e.device,{booted:!0}),u=e.bundle_id;if(e.app_path){let m=Bp(a,e.app_path);await fe("xcrun",["simctl","install",l.udid,m],`Installing ${hl(m)}`),u=await Rl(m)}if(e.bundle_id){if((await wt("xcrun",["simctl","get_app_container",l.udid,e.bundle_id])).code!==0)Q("simulator_app_not_installed",`${e.bundle_id} is not installed on ${ae(l)}.`)}let p=await Mp(l,u);if(p===null){let m=Ye.get(l.udid)?.lines.slice(-20).join(`
|
|
513
|
+
`)??"";Q("simulator_launch_failed",`${u} did not start on ${ae(l)}.${m?`
|
|
514
|
+
${m}`:""}`)}return{text:`Launched ${u} on ${ae(l)} (pid ${p}). Its console is captured; read it with logs.`,device:l}}function Bp(e,a){let l=To(a),u=K(Uo(),"Library","Caches","reason","simulator-builds")+_l;return l.startsWith(u)&&l.endsWith(".app")?l:qo(e,l)}function Fp(e,a){let l=Ye.get(e.udid);if(!l)return{text:`No app launched by Reason is running on ${ae(e)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let u=Math.max(a??0,l.first,l.first+l.lines.length-vp),p=l.lines.slice(u-l.first).map((m)=>m.slice(0,2000));return{text:`${p.length} console line(s) from ${l.bundleId} on ${ae(e)}.`,logs:{lines:p,next:l.first+l.lines.length}}}var Hr=new Map;function cl(e,...a){let l=Hr.get(e.udid);if(!l)return;for(let[u,p]of a)if(u>l.width||p>l.height)Q("simulator_point_off_screen",`(${u}, ${p}) is off ${e.name}'s ${l.width}x${l.height}-point screen.`)}function ul(e,a){if(e.kind==="ipad")return 2;return a===750||a===828||a===640?2:3}async function Wo(e,a=1,l){let u=Bo(K(fl(),"reason-sim-"));try{let p=K(u,"screen.png");if(await fe("xcrun",["simctl","io",e.udid,"screenshot","--type=png",p],"Taking a screenshot"),l){Ao(ko(l),{recursive:!0});let v=await fe("sips",["-g","pixelWidth","-g","pixelHeight",p],"Reading the screenshot size"),x=Number(v.match(/pixelWidth: (\d+)/)?.[1]),I=Number(v.match(/pixelHeight: (\d+)/)?.[1]),E=2/ul(e,x);await fe("sips",["-z",String(Math.round(I*E)),String(Math.round(x*E)),p,"--out",l],"Saving the screenshot")}let m=await fe("sips",["-g","pixelWidth","-g","pixelHeight",p],"Reading the screenshot size"),f=Number(m.match(/pixelWidth: (\d+)/)?.[1]),g=Number(m.match(/pixelHeight: (\d+)/)?.[1]),b=ul(e,f),y=Math.round(f/b),h=Math.round(g/b);Hr.set(e.udid,{width:y,height:h});let w=Buffer.alloc(0),S=a===2?bp:yp;for(let v of[70,50,35]){let x=K(u,`screen-${v}.jpg`);if(await fe("sips",["-z",String(h*a),String(y*a),"-s","format","jpeg","-s","formatOptions",String(v),p,"--out",x],"Encoding the screenshot"),w=Fo(x),w.byteLength<=S)break}return{text:`Screenshot of ${ae(e)} at ${y}x${h} points: image pixels are tap coordinates.`+(l?` Saved at ${l}.`:""),device:e,image:{mime:"image/jpeg",data:w.toString("base64"),width:y,height:h}}}finally{Wt(u,{recursive:!0,force:!0})}}async function Up(e){let a=await bl(e);if(a)try{return String((await a.call({op:"tree"})).tree)}catch{}return Ur(["describe-ui"],e.udid,"Reading the accessibility tree")}async function jr(e){let a=JSON.parse(await Up(e)),l={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},u=(p,m,f="")=>{let g=(p.role??p.type??"?").replace(/^AX/,""),b=p.AXLabel||p.title||"",y=p.AXValue?` value="${String(p.AXValue).slice(0,120)}"`:"",h=p.AXUniqueId?` id=${p.AXUniqueId}`:"";if(p.AXUniqueId)l.ids.add(p.AXUniqueId);if(b)l.labels.add(b);let w=p.frame;if(g==="Application"&&w&&!l.bounds)l.bounds={width:w.width,height:w.height};if(w&&w.width>0&&w.height>0&&(p.AXUniqueId||p.AXLabel))l.targets.push({...p.AXUniqueId?{id:p.AXUniqueId.trim()}:{},...p.AXLabel?{label:p.AXLabel.trim()}:{},role:g,frame:w});let S=Boolean(b||h||y||!["Group","Other"].includes(g));if(S){let v=`${" ".repeat(Math.min(m,12))}${g} "${b.slice(0,160)}"${h}${y}`+(w?` (${Math.round(w.x)},${Math.round(w.y)} ${Math.round(w.width)}x${Math.round(w.height)})`:"")+(p.enabled===!1?" disabled":"");l.lines.push(v);let x=g==="Image"&&!h,I=(g==="StaticText"||g==="Image")&&!h&&b!==""&&f.includes(b);if(!x&&!I)l.compact.push(v)}for(let v of p.children??[])u(v,S?m+1:m,b||f)};for(let p of a)u(p,0);return l}function xl(e,a,l=!1){let u=(l?e.compact:e.lines).join(`
|
|
515
|
+
`);return u.length>a?`${u.slice(0,a)}
|
|
516
|
+
\u2026 (truncated)`:u}async function Hp(e){let a=await jr(e);return{text:`Accessibility tree of ${ae(e)} (frames in points; tap by id or label):
|
|
517
|
+
${xl(a,wp)}`,device:e}}var jp=450,qp=1e4;function Wp(e,a){let l=a.id?e.ids.has(a.id):[...e.labels].some((u)=>u===a.label||u.includes(a.label));return a.gone?!l:l}async function lt(e,a,l){let u=a.observe??"tree";if(u==="none"&&!a.wait_for)return l;let p=null,m="";if(a.wait_for){let g=Date.now()+(a.timeout??5)*1000,b=a.wait_for,y=b.id?`id ${b.id}`:`"${b.label}"`;for(;;){if(p=await jr(e),Wp(p,b)){m=` ${y} is ${b.gone?"gone":"on screen"}.`;break}if(Date.now()>=g){m=b.gone?` Waited ${a.timeout??5} s: ${y} is still on screen.`:` Waited ${a.timeout??5} s: ${y} 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(jp);let f={...l,text:`${l.text}${m}`};if(u==="tree"||u==="both")p??=await jr(e),f.screen=xl(p,qp,!0),f.text+=`
|
|
518
|
+
Screen now:
|
|
519
|
+
${f.screen}`;if(u==="screenshot"||u==="both"){let g=await Wo(e);f.image=g.image}return f}function dl(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vp(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 ${dl(e.id)}`:`tap --label ${dl(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 El=0.35,zp=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function Gp(e,a){let l=e.targets.filter((y)=>a.id!==void 0?y.id===a.id.trim():y.label===a.label?.trim()),u=(y)=>({x:y.frame.x+y.frame.width/2,y:y.frame.y+y.frame.height/2}),p=e.bounds,m=p?l.filter((y)=>{let{x:h,y:w}=u(y);return h>=0&&w>=0&&h<=p.width&&w<=p.height}):l,f=m.length?m:l,g=f.filter((y)=>zp.has(y.role)),b=(g.length?g:f)[0];return b?u(b):null}async function Yp(e,a,l,u,p){let m=Date.now()+l*1000;for(;;){let f=Gp(await jr(e),a);if(f)return f;if(Date.now()>=m){let g=a.id!==void 0?`--id '${a.id}'`:`--label '${a.label}'`;return Q("simulator_element_not_found",`Error: Step ${u} failed: [tap]
|
|
520
|
+
No accessibility element matched ${g}. Make sure the app is on the expected screen, then inspect it and prefer an id when there is one.
|
|
521
|
+
(${u-1} of ${p} steps had completed.)`)}await Bun.sleep(250)}}async function _t(e,a,l){let u=await bl(e);if(!u)return pl(e,a,l);for(let[p,m]of a.entries()){try{switch(m.action){case"tap":{let g=m.x!==void 0&&m.y!==void 0?{x:m.x,y:m.y}:await Yp(e,m,l,p+1,a.length);await u.call(m.duration?{op:"tap",...g,duration:m.duration}:{op:"tap",...g});break}case"swipe":await u.call({op:"swipe",x:m.x,y:m.y,x2:m.x2,y2:m.y2,duration:m.duration??0.3});break;case"button":await u.call({op:"button",name:m.name});break;case"type":await u.call({op:"text",text:m.text}).catch((g)=>g instanceof qt?Ur(["type",m.text],e.udid,`Step ${p+1} (typing)`):Promise.reject(g));break;case"sleep":await Bun.sleep(m.seconds*1000);break}}catch(g){if(g instanceof ht)return await pl(e,a.slice(p),l),`Ran ${a.length} step(s) on ${ae(e)}.`;if(g instanceof qt)Q("simulator_command_failed",`Step ${p+1} failed: ${g.message}
|
|
522
|
+
(${p} of ${a.length} steps had completed.)`);throw g}let f=a[p+1];if(m.action!=="sleep"&&f&&f.action!=="sleep")await Bun.sleep(El*1000)}return`Ran ${a.length} step(s) on ${ae(e)}.`}async function pl(e,a,l){let u=[],p=[],m=0,f=0,g=async()=>{if(u.length===0)return;let b=["batch","--ax-cache","perStep","--wait-timeout",String(l)];for(let y of u)b.push("--step",y);try{await Ur(b,e.udid,`Steps ${f+1}-${f+m}`)}catch(y){if(y instanceof r){let h=y.message.replace(/Step (\d+) failed/,(w,S)=>{let v=p[Number(S)-1];return v?`Step ${v} failed`:w});Q(y.code,`${h}
|
|
523
|
+
(${f} of ${a.length} steps had completed before this batch.)`)}throw y}f+=m,u=[],p=[],m=0};for(let[b,y]of a.entries()){if(y.action==="type"){await g(),await Ur(["type",y.text],e.udid,`Step ${f+1} (typing)`),f+=1;continue}u.push(Vp(y)),m+=1,p.push(b+1);let h=a[b+1];if(y.action!=="sleep"&&h&&h.action!=="sleep")u.push(`sleep ${El}`),p.push(b+1)}return await g(),`Ran ${a.length} step(s) on ${ae(e)}.`}var Kp=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],ml=new Map,Xp=`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 Io(e,a,l){let u=await fe("sips",["-g","pixelWidth","-g","pixelHeight",e],"Reading the frame size"),p=Number(u.match(/pixelWidth: ([\d.]+)/)?.[1]),m=Number(u.match(/pixelHeight: ([\d.]+)/)?.[1]);if(l!==void 0)p=p*l/m,m=l;let f=Bo(K(fl(),"reason-chrome-"));try{let g=K(f,"render.js"),b=K(f,"out.png");if(gp(g,Xp),await fe("osascript",["-l","JavaScript",g,e,b,String(Math.max(1,Math.round(p*a))),String(Math.max(1,Math.round(m*a)))],"Rendering the frame"),!Ae(b))Q("simulator_command_failed",`Rendering ${hl(e)} produced no image.`);return{image:Fo(b).toString("base64"),width:p,height:m}}finally{Wt(f,{recursive:!0,force:!0})}}async function Jp(e){if(!Do.has(e.udid))await jo();let a=Do.get(e.udid),u=JSON.parse(await fe("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((p)=>p.identifier===a)?.bundlePath;if(!u)Q("simulator_command_failed",`No device type bundle for ${e.name}.`);return u}async function Zp(e){let a=await Jp(e),l=Hr.get(e.udid)??(e.state==="booted"?(await Wo(e),Hr.get(e.udid)):void 0);if(!l)Q("simulator_not_booted",`${e.name} is not booted.`);let u=ml.get(a);if(u)return{text:`Frame of ${ae(e)}.`,device:e,chrome:u};let p=K(a,"Contents","Resources"),m=JSON.parse(await fe("plutil",["-convert","json","-o","-",K(p,"profile.plist")],"Reading the device profile")),f=m.framebufferMask?K(p,`${m.framebufferMask}.pdf`):null,g=f&&Ae(f)?await Io(f,Eo,l.height):null,b=m.chromeIdentifier?.split(".").pop(),y=b?K("/Library/Developer/DeviceKit/Chrome",`${b}.devicechrome`,"Contents","Resources"):"";if(!b||!Ae(K(y,"chrome.json")))Q("simulator_command_failed",`${e.name} has no device frame in this Xcode.`);let h=JSON.parse(Fo(K(y,"chrome.json"),"utf8")),w={};for(let O of Kp){let D=h.images[O];if(!D)Q("simulator_command_failed",`${e.name}'s frame has no ${O} piece.`);w[O]=await Io(K(y,`${D}.pdf`),Eo)}let{sizing:S}=h.images,v={top:S.topHeight,left:S.leftWidth,bottom:S.bottomHeight,right:S.rightWidth},x=l.width+v.left+v.right,I=l.height+v.top+v.bottom,E=[];for(let O of h.inputs??[]){let D=K(y,`${O.image}.pdf`);if(!Ae(D))continue;let B=await Io(D,Eo),{x:ne,y:de}=O.offsets.normal,he=(Xe,ce,Zt)=>Xe<0?ce+Xe-Zt:Xe,We=O.anchor==="left"?{x:ne-B.width,y:he(de,I,B.height)}:O.anchor==="right"?{x:x+ne,y:he(de,I,B.height)}:O.anchor==="top"?{x:he(ne,x,B.width),y:de-B.height}:{x:he(ne,x,B.width),y:I+de};E.push({name:O.name,image:B.image,...We,width:B.width,height:B.height})}let C={identifier:h.identifier,screen:{width:l.width,height:l.height},inset:v,padding:h.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:w,buttons:E,...g?{screen_mask:g.image}:{}};return ml.set(a,C),{text:`Frame of ${ae(e)}.`,device:e,chrome:C}}var Qp=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 zt(e){try{return await Cl(e)}catch(a){if(a instanceof r&&Qp.has(a.code))return{text:a.message,error:a.code};throw a}}async function Cl(e){if(!Vt())Q("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let a=go.safeParse(e.payload);if(!a.success)Q("simulator_invalid_request",a.error.issues.map((u)=>u.message).join("; "));let l=a.data;switch(l.action){case"devices":{let u=await jo(),p=u.filter((m)=>m.state==="booted");return{text:`${p.length} booted (${p.map(ae).join(", ")||"none"}), ${u.length} available.`,devices:u}}case"boot":{let u=await Pp(await be(l.device,{booted:!1}));return{text:`${ae(u)} is booted.`,device:u}}case"shutdown":{let u=await be(l.device,{booted:!1});Ye.get(u.udid)?.stop(),Ye.delete(u.udid);let p=await wt("xcrun",["simctl","shutdown",u.udid]);if(p.code!==0&&!/current state: Shutdown/i.test(p.stderr))Q("simulator_command_failed",p.stderr.trim().slice(-1000));return{text:`${ae(u)} is shut down.`,device:{...u,state:"shutdown"}}}case"build":{let u=await ll(l,e.root);return l.wait&&u.build?Po(u.build.id):u}case"build_status":return l.wait?Po(l.build_id):vl(l.build_id);case"run":{let u=await ll({...l,action:"build"},e.root),p=await Po(u.build.id,Np);if(p.build?.status!=="succeeded"||!p.build.app_path)return p;let m=await Cl({root:e.root,payload:{action:"launch",app_path:p.build.app_path,...l.device?{device:l.device}:{},...l.steps?{steps:l.steps}:{},...l.observe?{observe:l.observe}:{},...l.wait_for?{wait_for:l.wait_for}:{},...l.timeout!==void 0?{timeout:l.timeout}:{}}});return{...m,text:`Built in ${Math.round(p.build.elapsed_ms/1000)} s. ${m.text}`,build:p.build}}case"launch":{let u=await $p(l,e.root);if(!u.device)return u;if(l.steps?.length)u.text+=` ${await _t(u.device,l.steps,l.timeout??8)}`;else if(!l.wait_for)await Bun.sleep(1000);return lt(u.device,l,u)}case"steps":{let u=await be(l.device,{booted:!0});return lt(u,l,{text:await _t(u,l.steps,l.timeout??5),device:u})}case"terminate":{let u=await be(l.device,{booted:!0});if(Ye.get(u.udid)?.bundleId===l.bundle_id)Ye.get(u.udid)?.stop();return await wt("xcrun",["simctl","terminate",u.udid,l.bundle_id]),{text:`Terminated ${l.bundle_id} on ${ae(u)}.`,device:u}}case"logs":return Fp(await be(l.device,{booted:!1}),l.after);case"screenshot":return Wo(await be(l.device,{booted:!0}),l.scale,l.save_path?qo(e.root,l.save_path):void 0);case"chrome":return Zp(await be(l.device,{booted:!1}));case"inspect":return Hp(await be(l.device,{booted:!0}));case"tap":{let u=await be(l.device,{booted:!0}),p=l.x!==void 0&&l.y!==void 0;if(p)cl(u,[l.x,l.y]);await _t(u,[p?{action:"tap",x:l.x,y:l.y,...l.duration&&l.duration>0?{duration:l.duration}:{}}:l.id?{action:"tap",id:l.id}:{action:"tap",label:l.label}],3);let m=p?`(${l.x}, ${l.y})`:l.id?`id ${l.id}`:`"${l.label}"`;return lt(u,l,{text:`Tapped ${m} on ${ae(u)}.`,device:u})}case"swipe":{let u=await be(l.device,{booted:!0});return cl(u,[l.x,l.y],[l.x2,l.y2]),await _t(u,[{action:"swipe",x:l.x,y:l.y,x2:l.x2,y2:l.y2,...l.duration!==void 0?{duration:l.duration}:{}}],3),lt(u,l,{text:`Swiped (${l.x}, ${l.y}) \u2192 (${l.x2}, ${l.y2}) on ${ae(u)}.`,device:u})}case"type":{let u=await be(l.device,{booted:!0});return await _t(u,[{action:"type",text:l.text}],3),lt(u,l,{text:`Typed ${l.text.length} character(s) on ${ae(u)}.`,device:u})}case"button":{let u=await be(l.device,{booted:!0});return await _t(u,[{action:"button",name:l.name}],3),lt(u,l,{text:`Pressed ${l.name} on ${ae(u)}.`,device:u})}case"open_url":{let u=await be(l.device,{booted:!0}),p;try{p=new URL(l.url)}catch{Q("simulator_invalid_request","open_url needs an absolute URL.")}if(xp.has(p.protocol))Q("simulator_invalid_request",`${p.protocol} URLs are not allowed.`);return await fe("xcrun",["simctl","openurl",u.udid,p.href],"Opening the URL"),lt(u,l,{text:`Opened ${p.href} on ${ae(u)}.`,device:u})}case"appearance":{let u=await be(l.device,{booted:!0});return await fe("xcrun",["simctl","ui",u.udid,"appearance",l.mode],"Setting the appearance"),{text:`${ae(u)} is in ${l.mode} mode.`,device:u}}}}import{mkdtempSync as em,readFileSync as tm,rmSync as rm}from"fs";import{tmpdir as nm}from"os";import{join as Pl}from"path";import{spawn as Al}from"child_process";var om=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,Gt=1,im=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],Ol=60,sm=8,Ll=Vt;var Il={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},am=(()=>{let e={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((l,u)=>{e[l]=4+u,e[l.toUpperCase()]=4+u}),"1234567890".split("").forEach((l,u)=>{e[l]=30+u}),"!@#$%^&*()".split("").forEach((l,u)=>{e[l]=30+u});let a=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[l,u,p]of a)e[l]=p,e[u]=p;return e})();function lm(e){if(Il[e]!==void 0)return Il[e];return e>=32&&e<=126?am[String.fromCharCode(e)]??null:null}function kl(e,a){let l=Al("xcrun",["simctl","pbcopy",e],{stdio:["pipe","ignore","ignore"]});l.once("error",()=>{}),l.stdin.end(a)}function cm(e,a){let l=0,u={x:0,y:0},p=(m)=>{a.call(m).catch(()=>{})};return{pointer(m,f,g){let b=(g&Gt)!==0;if(b&&!(l&Gt))p({op:"touch",phase:"down",x:m,y:f});else if(b&&(m!==u.x||f!==u.y))p({op:"touch",phase:"move",x:m,y:f});else if(!b&&l&Gt)p({op:"touch",phase:"up",x:m,y:f});for(let y of im)if(g&y.bit&&!(l&y.bit))p({op:"swipe",x:m,y:f,x2:m+y.dx*Ol,y2:f+y.dy*Ol,duration:0.08});l=g,u={x:m,y:f}},key(m,f){let g=lm(f);if(g!==null)p({op:"key",usage:g,down:m})},clipboard(m){kl(e,m)},close(){if(l&Gt)p({op:"touch",phase:"up",...u});l=0}}}function um(e,a){let l=null,u="",p,m=(f)=>{zt({payload:{...f,device:e,observe:"none"},root:a}).catch(()=>{})};return{pointer(f,g,b){let y=(b&Gt)!==0;if(y&&!l)l={x:f,y:g,at:Date.now()};if(!y&&l){let h=(Date.now()-l.at)/1000;if(Math.hypot(f-l.x,g-l.y)>sm)m({action:"swipe",x:l.x,y:l.y,x2:f,y2:g,duration:Math.min(Math.max(h,0.05),1)});else m({action:"tap",x:l.x,y:l.y,...h>0.5?{duration:Math.min(h,10)}:{}});l=null}},key(f,g){if(!f)return;let b=g===65293?`
|
|
536
|
+
`:g>=32&&g<=126?String.fromCharCode(g):null;if(b===null)return;u+=b,clearTimeout(p),p=setTimeout(()=>{let y=u;u="",m({action:"type",text:y})},250)},clipboard(f){kl(e,f)},close(){clearTimeout(p),l=null}}}function dm(e,a,l){return new Promise((u,p)=>{let m=Al(e,a,{stdio:"ignore",signal:l});m.once("error",p),m.once("exit",(f)=>u(f??-1))})}async function pm(e,a){let l=em(Pl(nm(),"reason-simulator-stream-"));try{let u=Pl(l,"screen.png");if(await dm("xcrun",["simctl","io",e,"screenshot","--type=png",u],a)!==0)throw new r("simulator_not_booted","That simulator is not booted.");let p=tm(u).subarray(16,24);return{width:p.readUInt32BE(0),height:p.readUInt32BE(4)}}finally{rm(l,{recursive:!0,force:!0})}}async function Tl(e,a={}){let{udid:l,...u}=e.payload;if(typeof l!=="string"||!om.test(l)||!u.video)throw new r("invalid_display_request","Reason simulator stream request is malformed.");let p=await yl().catch(()=>{throw new r("simulator_axe_missing","AXe could not be installed on this Mac.")}),m=await zt({payload:{action:"screenshot",device:l},root:e.root});if(m.error||!m.image)throw new r("simulator_not_booted","That simulator is not booted.");let f={width:m.image.width,height:m.image.height},g=await xo(p),b=g?await Br(p,l,!0):null,y=g?null:await Go();if(!g&&!y)throw new r("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let h={kind:"simulator",udid:l,axe:p,points:f,sound:null,size:g?f:await pm(l,e.signal),stream:g?(w,S,v)=>sl(g,l,Math.min(w,60),v,S):null,input:b?cm(l,b):um(l,e.root)};return await sn({payload:u,signal:e.signal},{...a,video:{desktop:async()=>h,...y?{ffmpeg:()=>y}:{}}})}var Vl=131072,xm=131072,Em=128,zl=8192,Zo=30000,Qo=15000,Cm=/^[a-z][a-z0-9_]{0,63}$/,Gr=new Set(["jobs.control","fs.read","fs.write"]),Dl=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function Wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(a)=>`[${a.toLowerCase()}${a.toUpperCase()}]`)}function Nl(e){return e.map(Wr).join("/")}function Vo(e,a){let l=[];for(let u=0;u<e.length;u+=a)l.push(e.slice(u,u+a));return l}var Pm=[...Vo(bt,4).map((e)=>`/(${e.map(Nl).join("|")})(/|$)`),...Vo(Cn,4).map((e)=>`/(${e.map(Nl).join("|")})$`),...Vo([...An],6).map((e)=>`/(${e.map(Wr).join("|")})$`),`/${Wr(".env")}\\.[^/]+$`,`/[^/]+(${Pn.map(Wr).join("|")})$`],Ko=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),Gl=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function Yl(e){return[e.requiredPermission,...e.additionalPermissions??[]]}function Om(e){return rn(e)}function Xo(){if(G()==="darwin")return Ue("/usr/bin/sandbox-exec");if(G()==="linux"||G()==="win32")return Gn();return!1}function Ml(){if(G()==="linux")return Ue("/proc");if(G()==="win32")return et()!==null;if(!Xo())return!1;if(G()==="darwin")return Ue("/usr/sbin/lsof");return!1}function Kr(){return G()==="darwin"?"/bin/zsh":Kn()}function Jo(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Im(e,a){if(!Jo(e))throw new r("invalid_payload","Operation payload must be an object.");let l=a===rr?Nr:Je;if(Buffer.byteLength(JSON.stringify(e),"utf8")>l)throw new r("payload_too_large",`Operation payload exceeds ${l/1024} KB.`);return e}function Rt(e,a){let l=e[a];if(l===void 0||l===null)return;if(typeof l!=="string")throw new r("invalid_payload",`${a} must be a string.`);return l}function zr(e,a,l=zl){let u=Rt(e,a);if(!u||Buffer.byteLength(u,"utf8")>l||u.includes("\x00"))throw new r("invalid_payload",`${a} is missing or too large.`);return u}function Am(e,a,l){let u=e[a];if(typeof u!=="string"||u.includes("\x00")||Buffer.byteLength(u,"utf8")>l)throw new r("invalid_payload",`${a} is missing or too large.`);return u}function Xt(e,a,l,u){if(e===void 0||e===null)return a;if(typeof e!=="number"||!Number.isInteger(e))throw new r("invalid_payload","Expected a bounded integer.");return Math.min(Math.max(e,l),u)}function ct(e,a){if(G()==="win32")[e,a]=[e.toLowerCase(),a.toLowerCase()];return a===e||a.startsWith(`${e}${vm}`)}function St(e){if(yc(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 le(e){let a;try{a=Ne(e.path)}catch(l){if(process.platform==="darwin"&&wo(l))throw bo(e.path);throw new r("root_unavailable","The granted root is unavailable.")}if(a!==e.path||!Jt(a).isDirectory())throw new r("root_changed","The granted root changed after registration.");return St(a),a}function ti(e,a="."){if(!a||a.includes("\x00")||wm(a))throw new r("path_outside_root","Paths must be relative to the granted root.");if(G()==="win32"&&a.split(/[\\/]/).some(Ki))throw new r("invalid_path","Windows reserves this file name.");let l=Sm(e,a);if(!ct(e,l))throw new r("path_outside_root","Path escapes the granted root.");return l}function vt(e,a=".",l=!1){let u=ti(e,a),p;try{p=Ne(u)}catch(m){if(Zl(m))throw Ql();throw new r("path_not_found","Path does not exist.")}if(!ct(e,p))throw new r("symlink_escape","Path resolves outside the granted root.");if(!l)St(p);return p}function Lm(e,a){let l=ti(e,a);if(St(l),Ue(l)){let m=Ne(l);if(!ct(e,m))throw new r("symlink_escape","Write target resolves outside the granted root.");if(zo(l).isSymbolicLink())throw new r("symlink_escape","Writing through a symlink is not allowed.");return St(m),m}let u=Kt(l);while(!Ue(u)){let m=Kt(u);if(m===u)throw new r("path_outside_root","No safe write parent.");u=m}let p=Ne(u);if(!ct(e,p))throw new r("symlink_escape","Write parent resolves outside the granted root.");return St(p),l}function Kl(e,a){return Yo(e,a)||"."}function km(e,a=Vl){let l=Buffer.from(e,"utf8");if(l.byteLength<=a)return{value:e,truncated:!1};return{value:l.subarray(0,a).toString("utf8"),truncated:!0}}function Xl(e,a){return{...je({home:e,temporaryDirectory:a}),ZDOTDIR:a,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 Tm(e,a,l,u=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...u?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify(e)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(a)}))`,...l?[`(allow file-write* (subpath ${JSON.stringify(e)}))`]:[],...Pm.map((p)=>`(deny file-read* file-write* (regex #"${p}"))`),...wc(e,l),"(deny network*)"].join(`
|
|
537
|
+
`)}async function lo(e,a,l){return new Promise((u,p)=>{let m="",f="",g=!1,b=!1,y=!1,h;try{h=Rm(e,a,{cwd:l.cwd,env:l.env,shell:!1,stdio:["ignore","pipe","pipe"],...Me()}),It(h)}catch(I){p(I);return}let w=(I,E)=>{if(y)return;y=!0,clearTimeout(x),l.signal.removeEventListener("abort",v),u({exitCode:I,signal:E,stdout:m,stderr:f,timedOut:b,truncated:g})},S=(I,E)=>{let C=`${I}${String(E)}`,O=km(C);return g||=O.truncated,O.value};h.stdout.on("data",(I)=>{m=S(m,I)}),h.stderr.on("data",(I)=>{f=S(f,I)}),h.once("error",p),h.once("exit",w);let v=()=>{try{if(G()==="win32"&&h.pid)Be(h.pid);else h.kill("SIGTERM")}catch{}};l.signal.addEventListener("abort",v,{once:!0});let x=setTimeout(()=>{b=!0,v()},l.timeoutMs)})}var $l=null;function Dm(){return $l??=Pa({scrubEnvironment:Xl,spawnCaptured:lo,isProtectedPath:L}),$l}var qn=async(e,a,l)=>{if(G()==="linux"||G()==="win32")return Dm()(e,a,l);if(G()!=="darwin"||!Ue("/usr/bin/sandbox-exec"))throw new r("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let u=hm(Wl(bm(),"reason-device-"));try{return await lo("/usr/bin/sandbox-exec",["-p",Tm(l.root,u,l.allowWrite,l.allowProcessInspection===!0),e,...a],{cwd:l.cwd,timeoutMs:l.timeoutMs,signal:l.signal,env:Xl(l.root,u)})}finally{_m(u,{recursive:!0,force:!0})}};function Nm(e){let a=e.args;if(a===void 0)return[];if(!Array.isArray(a)||a.length>Em)throw new r("invalid_payload","args must be a bounded string array.");return a.map((l)=>{if(typeof l!=="string"||l.includes("\x00")||Buffer.byteLength(l,"utf8")>zl)throw new r("invalid_payload","Command argument is invalid or too large.");return l})}async function Jl(e,a,l,u={}){if(e.signal.aborted)throw new r("cancelled","Operation was cancelled.");let p=le(e.root),m=u.cwd??p,f=await e.runCommand(a,l,{cwd:m,root:p,allowWrite:u.allowWrite===!0,timeoutMs:u.timeoutMs??Qo,signal:e.signal});if(f.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(f.stderr))await e.emit("permission.denied",{operation:"bash",provenance:e.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:f.exitCode,signal:f.signal,stdout:f.stdout,stderr:f.stderr,timed_out:f.timedOut,truncated:f.truncated}}function Zl(e){let a=e instanceof Error&&"code"in e?e.code:null;return a==="EACCES"||a==="EPERM"}var Ql=()=>new r("path_unreadable","The path is not readable.");function Mm(e){try{return ql(e,ke.O_RDONLY)}catch(a){throw Zl(a)?Ql():a}}function Bl(e,a){let l=J()?ue():null;return l?nn(l,{op:"fs",capability:e,root:a.root,payload:a.payload},a.signal).then((u)=>u.value):Kc(e,a)}function Kc(e,a){return e==="fs.read"?$m(a):Fm(a)}async function $m(e){let a=le(e.root),l=vt(a,zr(e.payload,"path"));if(!Jt(l).isFile())throw new r("not_a_file","Read target is not a file.");let u=Xt(e.payload.offset,0,0,Number.MAX_SAFE_INTEGER),p=Xt(e.payload.max_bytes,65536,1,Vl),m=Rt(e.payload,"encoding");if(m!==void 0&&m!=="base64")throw new r("invalid_payload","encoding must be base64.");let f=Mm(l),g,b;try{g=jl(f).size;let h=Buffer.alloc(Math.max(0,Math.min(p,g-u)));b=h.subarray(0,h.byteLength?gm(f,h,0,h.byteLength,u):0)}finally{Hl(f)}let y=m==="base64"||b.includes(0);return{path:Kl(a,l),content:y?b.toString("base64"):b.toString("utf8"),encoding:y?"base64":"utf8",offset:u,bytes:b.byteLength,size:g,truncated:u+b.byteLength<g}}function Bm(e,a,l=G()){let u=e==="append"?ke.O_APPEND:ke.O_TRUNC;if(l==="win32")return a?ke.O_WRONLY|(e==="append"?ke.O_APPEND:0):ke.O_WRONLY|ke.O_CREAT|ke.O_EXCL;return ke.O_WRONLY|ke.O_NOFOLLOW|u|(a?0:ke.O_CREAT|ke.O_EXCL)}async function Fm(e){let a=le(e.root),l=zr(e.payload,"path"),u=Am(e.payload,"content",xm),p=Rt(e.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(p))throw new r("invalid_payload","mode must be create, overwrite, or append.");let m=Lm(a,l);if(e.payload.create_parents===!0||e.payload.create_directories===!0){fm(Kt(m),{recursive:!0,mode:448});let y=Ne(Kt(m));if(!ct(a,y))throw new r("symlink_escape","Write parent escaped root.")}if(!Ue(Kt(m)))throw new r("path_not_found","Write parent does not exist.");if(p==="create"&&Ue(m))throw new r("path_exists","Create mode will not overwrite an existing file.");let f=Ue(m),g=f?zo(m):null,b=ql(m,Bm(p,f),384);try{let y=jl(b),h=g??(G()==="win32"?zo(m):null);if(h&&(y.ino!==h.ino||y.dev!==h.dev||G()==="win32"&&!ct(a,Ne(m))))throw new r("symlink_escape","The write target changed between validation and opening.");if(G()==="win32"&&g&&p!=="append")mm(b,0);ym(b,u,null,"utf8")}finally{Hl(b)}return{path:Kl(a,m),bytes_written:Buffer.byteLength(u,"utf8"),mode:p}}async function Um(e){let a=le(e.root),l=zr(e.payload,"command",65536),u=vt(a,Rt(e.payload,"cwd")??".");if(!Jt(u).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let p=Xt(e.payload.timeout_ms,Qo,100,Zo);return Jl(e,Kr(),["-lc",l],{cwd:u,allowWrite:e.root.permissions.write,timeoutMs:p})}function ec(e,a){let l=Ve(e,a),u=l.boundary===e?e:vt(l.anchor,Yo(l.anchor,l.boundary)||".");return{boundary:u,checkout:vt(u,Yo(u,l.path)||".")}}async function Hm(e){let a=Na.safeParse(e.payload),l=e.worker;if(!a.success||!e.claimOwner||(l?!l.runtimeDirectory:G()!=="darwin"))throw new r("preview_unavailable","Preview servers are unavailable on this computer.");let u=le(e.root),{boundary:p,checkout:m}=ec(u,a.data.workspace);if(!Jt(m).isDirectory())throw new r("invalid_cwd","The Session checkout is not a directory.");let f=Math.min(Date.parse(a.data.expires_at),Date.now()+Ia);if(!(f>Date.now()))throw new r("process_authority_lost","The preview server lease is unavailable.");let g=(E)=>e.emit("progress",{process:E});if(!l?.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 Xn({claim:e.claim,root:p,cwd:m,command:a.data.command,mode:"host",shell:ut(),environment:process.env,expiresAtMs:f,signal:e.signal,emit:g})}}let b={directory:Wl(l.runtimeDirectory,"processes")},y={deniedPorts:ei([e.apiOrigin])},h=ii(),w=oi(),S=J(),v=a.data.egress?Qr(S):null;if(a.data.egress&&(v===null||!Pe(l.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 x=a.data.egress?await Mi(a.data.egress.allowed_domains):null,I=x?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((E)=>`${E}=${x.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",a.data.command].join(`
|
|
538
|
+
`):a.data.command;try{return{...await Xn({claim:e.claim,root:m,cwd:m,command:I,mode:"host",shell:w,expiresAtMs:f,signal:e.signal,emit:g,...S?{jobsUser:{...S,...v!==null?{modelGid:v}:{}}}:{},environment:{...h.variables,HOME:h.home,PATH:h.path,TMPDIR:h.temporaryDirectory,SHELL:w},journals:b,preview:y})}}finally{x?.close()}}async function jm(e){jn();let a=le(e.root),l=zn(e.payload.command),u=vt(a,Rt(e.payload,"cwd")??".");if(!Jt(u).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let p=Xt(e.payload.timeout_ms,sa,100,Un),{ignored:m}=Yn(e.payload.env);return await e.emit("progress",{shell:ut(),shell_flags:[...Ht],sandbox:"none",ignored_env:m}),la({command:l,cwd:u,timeoutMs:p,signal:e.signal,spawn:e.spawnFullControl,requestEnv:e.payload.env})}async function qm(e){let a=le(e.root),l=Nm(e.payload),u=l[0];if(!u||!Gl.has(u)&&!Ko.has(u))throw new r("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(l.some((f)=>f==="-C"||f==="-c"||f.startsWith("--git-dir")||f.startsWith("--work-tree")||f.startsWith("--config-env")||f.startsWith("--exec-path")))throw new r("git_argument_not_allowed","Git path/config overrides are not allowed.");let p=Ko.has(u);if(p&&!e.root.permissions.write)throw new r("permission_denied","Mutating Git commands require the write grant.");let m=vt(a,Rt(e.payload,"cwd")??".");return Jl(e,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...l],{cwd:m,allowWrite:p||process.platform==="win32"&&e.root.permissions.write,timeoutMs:Xt(e.payload.timeout_ms,Qo,100,Zo)})}function tc(e,a){return async(l)=>{let u=await e.runCommand("/usr/sbin/lsof",l,{cwd:a,root:a,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:e.signal});if(e.signal.aborted)throw new r("cancelled","Operation was cancelled.");return u}}async function Wm(e){let a=le(e.root);if(G()==="linux")return ya(a);if(G()==="win32")return Za(a);return Ra(a,tc(e,a))}async function Vm(e){let a=le(e.root),l=a;if(e.payload.workspace!==void 0){let u=te(e.payload.workspace);if(!u)throw new r("invalid_workspace","The workspace is not a valid Device workspace.");l=ec(a,u).checkout}if(G()==="linux")return ba(l);if(G()==="win32")return Qa(l);return xa(l,tc(e,a))}async function zm(e){let a=e.worker?qa(e.worker):null,l=e.claim.environment;delete e.claim.environment;let u=e.worker&&l&&ni({deviceId:e.deviceId},e.root.id,e.runId,l.payload,l.authority)?l.payload:void 0;return e.runHandsRelay({...e.claimedAtMs===void 0?{}:{claimedAtMs:e.claimedAtMs},claimOwner:e.claimOwner,...u?{claimEnvironment:u}:{},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},...a?{desktopRecording:a}:{}}:{},root:le(e.root),runId:e.runId,operationId:e.operationId,attemptId:e.attemptId,payload:e.payload,signal:e.signal,emitEvent:(p,m,f)=>e.emit(p,m,f)})}async function Gm(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:a,session:l}=Ma(e.payload,e.operationId);return Xr({root:le(e.root),runId:e.runId,deviceId:e.deviceId,rootId:e.root.id,workspace:a,session:l,owner:e.claimOwner,authority:e.claimAuthority,signal:e.signal,emit:(u,p)=>e.emit(u,p)})}return e.runPtySession({root:le(e.root),runId:e.runId,operationId:e.operationId,payload:e.payload,signal:e.signal,emitEvent:(a,l)=>e.emit(a,l)})}function Fl(e,a){let l=J()?ue():null;return l?nn(l,{op:"transfer",direction:a,root:e.root,payload:e.payload,worker:Boolean(e.worker)},e.signal).then((u)=>u.value):Jc(a,{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 Jc(e,a){let l=le(a.root),u=$t in a.payload;if(u&&!a.worker)throw new r("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let p=u?cs(l,a.payload[$t]):l;if("source"in a.payload||"source_version"in a.payload){if(e!=="export"||!u)throw new r("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let g=Ji.safeParse(a.payload);if(!g.success)throw new r("invalid_payload","Invalid Cloud export request.");return us({runtimeRoot:p,source:g.data.source,url:g.data.url,signal:a.signal,fetchImpl:a.fetchImpl})}let m=zr(a.payload,"path",4096),f=e==="import"&&u?Tn(p):p;return St(ti(f,m)),mt({direction:e,root:f,path:m,payload:a.payload,signal:a.signal,fetchImpl:a.fetchImpl,beforeCommit:a.beforeCommit})}var rc={"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 yi({payload:e.payload,signal:e.signal,credential:e.customEndpointCredential,emit:(a,l)=>e.emit(a,l,e.signal)})}},"fs.read":{requiredPermission:"read",execute:(e)=>Bl("fs.read",e)},"fs.write":{requiredPermission:"write",execute:(e)=>Bl("fs.write",e)},"fs.export":{requiredPermission:"read",execute:(e)=>Fl(e,"export")},"fs.import":{requiredPermission:"write",execute:(e)=>Fl(e,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>G()==="darwin"&&Hn(),execute:Hm},"exec.run":{requiredPermission:"execute",available:Xo,execute:Um},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Hn(),execute:jm},"git.run":{requiredPermission:"execute",available:()=>Xo()&&Om("git"),execute:qm},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:Ml,execute:Wm},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:Ml,execute:Vm},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>G()==="darwin"||Boolean(vo()),execute:zm},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:Lo,execute:Gm},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:on,execute:(e)=>{let a=ue();return a?nn(a,{op:"display",payload:e.payload,proxy:(e.relay.loadProxy??Se)()},e.signal):sn({payload:e.payload,signal:e.signal},e.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>hr(),execute:(e)=>Oo({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:Vt,execute:(e)=>zt({payload:e.payload,root:le(e.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:Ll,execute:(e)=>Tl({payload:e.payload,root:le(e.root),signal:e.signal},e.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:(e)=>Ha({root:le(e.root),runId:e.runId,payload:e.payload,signal:e.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>G()==="darwin"?Ue("/usr/bin/sandbox-exec"):G()==="linux"||G()==="win32",execute:async(e)=>{let a=xt.parse(e.payload),l=Ke.parse(e.claim.local_github_authority);if(l.userId!==e.claimOwner?.user_id||l.deviceId!==e.deviceId||l.rootId!==e.root.id||l.runId!==e.runId||l.repoFullName!==a.repoFullName||!l.readOnly&&!e.root.permissions.write||!Qt(a)&&(l.readOnly||l.generation===null&&!(a.kind==="pr_merge"&&l.merge?.source==="human")&&!(a.kind==="pr_mutation"&&l.contributorRefresh)))throw Error("local_device_gh_authority_changed");return Ua({root:le(e.root),runId:e.runId,request:a,authority:l,signal:e.signal,leaseUntil:e.claim.lease_until},(u)=>Li(a,u))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async(e)=>Ze({root:le(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)=>Fa({root:le(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)=>ja({root:le(e.root),runId:e.runId,owner:e.claimOwner,payload:e.payload,signal:e.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:Vr,execute:(e)=>as(e.payload,e.signal)}};function Ym(e,a){try{let l=wi(e,Ne(a)),u=l?e.find((p)=>p.path===l):void 0;return u&&/^[a-f0-9]{64}$/.test(u.pathFingerprint)?u.pathFingerprint:void 0}catch{return}}function Km(e,a){try{let l=Ne(a);return e.some((u)=>u.path===l)?nr(l,G()):void 0}catch{return}}function Xm(e,a){try{let l=Ne(a),u=e.find((p)=>p.path===l);return u&&/^[a-f0-9]{64}$/.test(u.pathFingerprint)?u.pathFingerprint:void 0}catch{return}}function Jm(e,a){try{let l=Ne(a);if(!e.some((u)=>u.path===l))return;return e.filter((u)=>u.path!==l&&ct(l,u.path)&&/^[a-f0-9]{64}$/.test(u.pathFingerprint)).map((u)=>u.pathFingerprint)}catch{return}}function Wn(e,a,l=G()){try{return ir({home:nr(Ne(a),l),roots:e.map((u)=>({path_fingerprint:u.pathFingerprint,path:nr(u.path,l)})).filter((u)=>/^[a-f0-9]{64}$/.test(u.path_fingerprint)&&tr(u.path)).slice(0,Jr)})}catch{return}}function uo(e,a={}){let l=a.worker?a.worker.handsSlots??1:a.handsSlots===1?1:void 0,u=Boolean(a.worker)||G()==="darwin",p=u?Xm(e,Yt()):void 0,m=!a.worker&&G()==="darwin"?Ym(e,Yt()):void 0,f=u?Km(e,Yt()):void 0,g=!a.worker&&G()==="darwin"?Jm(e,Yt()):void 0,b=u?Wn(e,Yt()):void 0,y=Fn.filter((h)=>{if(Ut.has(h)&&!a.worker)return!1;if(a.worker&&!xr(h,a.worker))return!1;let w=rc[h];if(!w)return!1;return(h==="hands.connect"&&(a.terminalOnlyHands===!0||Boolean(a.worker))||(h==="pty.start"||h==="preview.serve.v1")&&Boolean(a.worker)||h==="browser.pr-proof.v1"&&Boolean(a.productionProof)?!0:w.available?.()??!0)&&e.some((v)=>(!a.worker||h!=="pty.start"||v.permissions.read&&v.permissions.write)&&Yl(w).every((x)=>v.permissions[x]))});return{supported_operations:y,...p?{account_root_fingerprint:p}:{},...m?{workspace_root_fingerprint:m}:{},...f?{account_root_path:f}:{},...g?{home_contained_root_fingerprints:g}:{},...b?{root_paths:b}:{},...y.includes("hands.connect")?{hands_worker_artifact_sha256:R,hands_worker_entrypoint:H,...l?{hands_slots:l}:{}}:{},max_payload_bytes:Je,max_result_bytes:Je,operation_constraints:{...y.includes("browser.pr-proof.v1")&&a.productionProof?{"browser.pr-proof.v1":dn.parse(a.productionProof)}:{},...y.includes("exec.run")?{"exec.run":{transport:"shell",shell:Kr(),sandbox:G()==="linux"?"linux_sandbox_runtime":G()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:Zo}}:{},...y.includes("exec.full")?{"exec.full":ca()}:{},"git.run":{read_only_subcommands:[...Gl].sort(),mutating_subcommands:[...Ko].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:qe,max_timeout_ms:Mt,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:qe,max_timeout_ms:Mt,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:U,protocol_version:F,worker_artifact_sha256:R,worker_entrypoint:H,policy_mode:"full_access",policy_version:1,workspace_base:st,workspace_layout:Oe,...l?{slots:l}:{},browser_state:a.worker?"optional_headless":a.terminalOnlyHands===!0?"disabled_terminal_only":G()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...y.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:gi,max_session_ms:mi,max_buffered_output_bytes:an}}:{},...a.worker?Object.fromEntries(y.filter((h)=>h!=="browser.pr-proof.v1").map((h)=>[h,{ready:a.worker?.readiness?.[h]===!0,...a.worker?.readiness?.[h]!==!0&&a.worker?.probing?.includes(h)?{probing:!0}:{},execution_mode:xr(h,{...a.worker,executionMode:"sandboxed"})?"confined":"host",...h==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:pn,environment:"private_snapshot",receipt:"metadata_only",...a.worker?.persistentTerminals&&!J()?{persistent_terminals:!0}:{}}:{},...h===rr?{max_body_bytes:Or}:{},...h==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...a.worker?.githubSignedIn!==void 0?{gh_authenticated:a.worker.githubSignedIn}:{}}:{},...h==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:l,session_group:Ls,...a.worker?.ownComputer?{[$s]:Ms}:{},workspace_base:st,workspace_layout:Oe,browser_state:"optional_headless",desktop:!1,worker_version:U,protocol_version:F,...a.worker?.readiness?.["environment.install"]===!0&&y.includes("environment.install")?{environment_delivery:ms,[vs]:bs}:{},...a.worker?{[xs]:ks}:{},...a.worker?{[Es]:Ss}:{},...a.worker?.handsBrowser?{[Ts]:Rs}:{},[Ps]:As,[Ds]:Is,...Pe(a.worker?.executionMode==="unsandboxed")?{[Le]:at}:{},...Pe(a.worker?.executionMode==="unsandboxed")&&Qr()!==null?{[xe]:At}:{},...Pe(a.worker?.executionMode==="unsandboxed")&&J()?{[Ns]:Os}:{}}:{},...h==="fs.export"?{cloud_source_version:fr,source_kinds:["workspace","attachment"],[_n]:yn}:{},...h==="fs.import"?{[_n]:yn}:{},...h===Ta&&Qr()!==null&&Pe(a.worker?.executionMode==="unsandboxed")?{[Oa]:fo}:{},...h==="tunnel.open"?{carried_jobs:Bs}:{},...h==="jobs.control"?{[js]:Fs}:{},...h==="display.stream.v1"&&a.worker?.displayVideo?{[Sc]:vc,[Ec]:Sr.join(","),[kc]:xc,[Cc]:Ac,[Pc]:Rc}:{},...h==="automation.call.v1"&&a.worker?.userChrome?{[Tr]:!0}:{},...h==="automation.call.v1"&&a.worker?.cloudSessions?{[Hs]:!0}:{}}])):{}}}}function ni(e,a,l,u,p){let m=ri.safeParse(u);return m.success&&p!==void 0&&p.device_id===e.deviceId&&m.data.device_id===e.deviceId&&m.data.root_id===a&&m.data.run_id===l&&m.data.binding.kind===p.binding&&m.data.binding.target_revision===p.target_revision&&m.data.binding.root_grant_revision===p.root_grant_revision&&m.data.binding.target_generation===p.target_generation&&m.data.binding.target_fence_id===p.target_fence_id}async function po(e,a,l,u,p){if(a.capability!=="hands.connect"||l.kind!==Rr||!u.operationEnvironment||!u.acknowledgeOperationEnvironment)return!1;let m=l.payload.snapshot_id;if(l.payload.version!==1||typeof m!=="string"||Object.keys(l.payload).length!==2)throw new r("environment_unavailable","Reason sent an invalid environment delivery.");let f=e.roots.find((y)=>y.id===a.root_id);if(!f)throw new r("root_not_granted","The Hands root is no longer granted.");let g=await u.operationEnvironment(e,a,m,p);if(!ni(e,f.id,a.run_id,g.payload,g.authority)||g.payload.snapshot_id!==m)throw new r("environment_unavailable","The delivered environment does not match this Hands.");let b=Ze({root:le(f),operationId:a.operation_id,payload:g.payload});return await u.acknowledgeOperationEnvironment(e,a,{snapshot_id:b.snapshot_id,installed_revision:b.installed_revision,installed:!0},p),!0}async function ho(e,a,l,u){if(a.capability!=="hands.connect"||l.kind!==Cs)return!1;let{version:p,run_id:m,target_generation:f,target_fence_id:g}=l.payload;if(p!==1||Object.keys(l.payload).length!==4||typeof m!=="string"||typeof f!=="number"||typeof g!=="string")throw new r("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let b=e.roots.find((y)=>y.id===a.root_id);if(!b)throw new r("root_not_granted","The Hands root is no longer granted.");return await Ba({operationId:a.operation_id,root:le(b),runId:m,targetGeneration:f,fenceId:g,...u?{signal:u}:{}}),!0}async function Vn(e,a,l){if(a.capability!=="github.local.v1")return Ul(e,a,l);try{let u=await Ul(e,a,l);if(u.status==="succeeded"||ds(a.payload,u.status,u.error_code))return u;return{status:u.status,error_code:u.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:l.signal.aborted?"cancelled":"failed",error_code:l.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function Ul(e,a,l){if(Ut.has(a.capability)&&!l.worker)return{status:"failed",error_code:"capability_not_granted"};if(l.worker&&!xr(a.capability,l.worker))return{status:"failed",error_code:"capability_not_granted"};if(l.worker&&l.worker.readiness?.[a.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(a.local_github_authority){let h=Ke.safeParse(a.local_github_authority);if(!h.success||h.data.deviceId!==e.deviceId||h.data.rootId!==a.root_id||h.data.runId!==a.run_id||h.data.userId!==a.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(a.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let u=rc[a.capability];if(!u)return{status:"failed",error_code:"capability_unsupported"};if(u.available&&!u.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(a.capability)&&l.worker)&&!l.runCommand&&!l.runHandsRelay&&!l.spawnFullControl&&!l.runPtySession&&!(a.capability==="browser.pr-proof.v1"&&l.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(a.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let p=e.roots.find((h)=>h.id===a.root_id);if(!p)return{status:"failed",error_code:"root_not_granted"};if((a.capability==="fs.export"||a.capability==="fs.import")&&Jo(a.payload)&&(("source"in a.payload)||("source_version"in a.payload))){let h=Boolean(l.worker||e.worker)&&$t in a.payload;if(a.capability!=="fs.export"||!h)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(a.owner&&(a.owner.device_id!==e.deviceId||a.owner.organization_id!==e.orgId))return{status:"failed",error_code:"capability_not_granted"};if((a.capability==="tunnel.open"||a.capability==="tunnel.close")&&!a.owner)return{status:"failed",error_code:"preview_unavailable"};if(a.capability==="environment.install"&&!ni(e,p.id,a.run_id,a.payload,a.authority))return{status:"failed",error_code:"environment_unavailable"};if(Yl(u).some((h)=>!p.permissions[h]))return{status:"failed",error_code:"permission_denied"};let m=0,f=async(h,w,S)=>{if(["environment.install","github.local.v1"].includes(a.capability)||a.capability==="inference.custom.v1"&&(h==="started"||h==="completed"))return;await l.emit?.({sequence:m++,kind:h,capability:a.capability,data:w,...(h==="hands.reconnected"||a.capability==="inference.custom.v1")&&S?{deliverySignal:S}:{}})},g=a.capability==="hands.connect"||a.capability==="display.stream.v1"||a.capability==="simulator.stream.v1"||Gr.has(a.capability)||a.capability==="pty.start",b,y=async(h,w,S)=>{let v=b;b=void 0,await Promise.all([v,f(h,w,S)])};try{if(g)b=f("started"),b.catch(()=>{return});else await f("started");let h={...l.proxy===void 0?{}:{loadProxy:()=>l.proxy??null},...l.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:l.handsLaunch.takePrespawnedWorker}:{},...l.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:l.handsLaunch.adoptSpawnedWorker}:{}},w=await u.execute({...l.proveMac?{proveMac:()=>l.proveMac(a,l.signal,(S)=>f("pr-proof.started.v1",S))}:{},claim:a,worker:l.worker,claimOwner:a.owner,claimAuthority:a.authority,organizationId:e.orgId,deviceId:e.deviceId,apiOrigin:e.apiOrigin,root:p,payload:Im(a.payload,a.capability),runId:a.run_id,operationId:a.operation_id,attemptId:a.attempt_id,...l.handsLaunch?{claimedAtMs:l.handsLaunch.claimedAtMs}:{},signal:l.signal,...l.customEndpointCredential?{customEndpointCredential:l.customEndpointCredential}:{},fetchImpl:l.fetchImpl??fetch,relay:h,runCommand:l.runCommand??qn,spawnFullControl:l.spawnFullControl??lo,emit:g?y:f,runHandsRelay:l.runHandsRelay??((S)=>Qe(S,h)),runPtySession:l.runPtySession??$o});if(a.capability==="github.local.v1")Fc.parse(w);if(!Jo(w))throw new r("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(w)??"null","utf8")>Je)throw new r("result_too_large","Operation result exceeds 256 KB.");return await(g?y:f)("completed",{ok:!0}),{status:"succeeded",result:w,error_code:null}}catch(h){let w=l.signal.reason instanceof r&&Dl.has(l.signal.reason.code)?l.signal.reason.code:h instanceof r&&Dl.has(h.code)?h.code:null;if(l.signal.aborted||w)return{status:"cancelled",...h instanceof lr?{result:{process_terminal_observation:h.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(a.capability)?"operation_cancelled":w??"cancelled"};if(["fs.read","fs.write"].includes(a.capability)&&h instanceof Error&&"code"in h&&["EACCES","EPERM"].includes(String(h.code)))await f("permission.denied",{operation:a.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let S=a.capability==="inference.custom.v1"?h instanceof r&&Lr(h.code)?h.code:"custom_endpoint_unavailable":a.capability==="github.local.v1"?h instanceof Ln&&ds(a.payload,"failed",h.code)?h.code:"local_github_unavailable":a.capability==="environment.install"?"environment_install_failed":h instanceof r&&Cm.test(h.code)?h.code:"capability_failed",v=a.capability==="hands.connect"&&h instanceof ci?za(h.expiryDiagnostic):null;return await f("completed",{ok:!1,error_code:S,...v?{expiry_diagnostic:v}:{}}),{status:"failed",error_code:S}}}
|
|
539
|
+
export{Ea,k,or,sr,ee,ar,so,ao,Vr,ut,co,Gr,Kr,lo,qn,Kc,Jc,Wn,uo,po,ho,Vn};
|