@reason-machines/cli-linux-x64 0.2.548 → 0.2.550

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