@reason-machines/cli-linux-x64 0.2.520 → 0.2.522

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 (106) hide show
  1. package/bin/reason +2 -2
  2. package/bin/vm-hands/api-credentials-4q4j6kx0.js +2 -0
  3. package/bin/vm-hands/api-jbq4mscd.js +2 -0
  4. package/bin/vm-hands/connect-cli-4g0wanfs.js +2 -0
  5. package/bin/vm-hands/credentials-md79hkqh.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-hzgdnyx2.js +2 -0
  7. package/bin/vm-hands/desktop-account-gm7m5bwr.js +2 -0
  8. package/bin/vm-hands/{fsevents-sw63c1nr.js → fsevents-fev1pxw2.js} +1 -1
  9. package/bin/vm-hands/grok-dock-browser-pzw59wnd.png +0 -0
  10. package/bin/vm-hands/grok-dock-files-eckq444x.png +0 -0
  11. package/bin/vm-hands/grok-dock-terminal-hcpz3e43.png +0 -0
  12. package/bin/vm-hands/grok-wallpaper-71zwn2pj.jpg +0 -0
  13. package/bin/vm-hands/{hands-worker-source-h0qmr1jt.js → hands-worker-source-hzkacxxz.js} +1 -1
  14. package/bin/vm-hands/{index-j4gb3cze.js → index-gmsadq51.js} +4 -4
  15. package/bin/vm-hands/install-receipt-qtwtzafq.js +2 -0
  16. package/bin/vm-hands/local-automation-6vzg71yj.js +2 -0
  17. package/bin/vm-hands/local-capabilities-47zzxtv9.js +2 -0
  18. package/bin/vm-hands/local-desktop-users-qdpbfh6s.js +2 -0
  19. package/bin/vm-hands/local-display-mac-4654wqzs.js +2 -0
  20. package/bin/vm-hands/local-display-session-n9jw5nf3.js +2 -0
  21. package/bin/vm-hands/local-display-video-80nbkta7.js +2 -0
  22. package/bin/vm-hands/local-managed-process-js1zp3c3.js +2 -0
  23. package/bin/vm-hands/local-pty-session-s60ca00y.js +2 -0
  24. package/bin/vm-hands/managed-runtime-paqtph38.js +2 -0
  25. package/bin/vm-hands/network-contract-5wc6wbn2.js +2 -0
  26. package/bin/vm-hands/package-way7qesn.js +2 -0
  27. package/bin/vm-hands/permissions-7kac0k3h.js +2 -0
  28. package/bin/vm-hands/{reason-hands-protocol-6fxcbhzd.js → reason-hands-protocol-zffy7kc8.js} +1 -1
  29. package/bin/vm-hands/serve-service-yz2zdd2x.js +2 -0
  30. package/bin/vm-hands/{status-exfqneat.js → status-5zp28s1d.js} +1 -1
  31. package/bin/vm-hands/version-tvtjsedm.js +2 -0
  32. package/bin/vm-hands/vm-hands-entry-lite-0emgrj8j.js +2 -0
  33. package/bin/vm-hands/{vm-hands-entry-lite-wzq3qsh1.js → vm-hands-entry-lite-0tavq3p4.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-qz74j563.js → vm-hands-entry-lite-1kt82jes.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-x39tvhjw.js → vm-hands-entry-lite-3wra0xtg.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-70x16hkx.js → vm-hands-entry-lite-4cdn822w.js} +3 -3
  37. package/bin/vm-hands/{vm-hands-entry-lite-bp8kdega.js → vm-hands-entry-lite-59typww6.js} +3 -3
  38. package/bin/vm-hands/{vm-hands-entry-lite-qxeegp2n.js → vm-hands-entry-lite-5wsygx6n.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-ce250nr7.js → vm-hands-entry-lite-70n3bmjz.js} +4 -4
  40. package/bin/vm-hands/{vm-hands-entry-lite-7ek99e0k.js → vm-hands-entry-lite-7pne9e2e.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-029385a5.js → vm-hands-entry-lite-82ky5wgg.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-ydgedg8n.js → vm-hands-entry-lite-88yjxxvf.js} +5 -5
  43. package/bin/vm-hands/{vm-hands-entry-lite-q3dr2sz2.js → vm-hands-entry-lite-956sjtet.js} +4 -4
  44. package/bin/vm-hands/{vm-hands-entry-lite-148nz8be.js → vm-hands-entry-lite-9x81cr3a.js} +3 -3
  45. package/bin/vm-hands/{vm-hands-entry-lite-fcvf8md1.js → vm-hands-entry-lite-a3p6xz53.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-dcrz19xf.js → vm-hands-entry-lite-a6w60nv9.js} +3 -3
  47. package/bin/vm-hands/{vm-hands-entry-lite-wx1fmrbs.js → vm-hands-entry-lite-bvqwsd3b.js} +3 -3
  48. package/bin/vm-hands/{vm-hands-entry-lite-fgppp6x9.js → vm-hands-entry-lite-c0t5xpzh.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-ymqb2927.js → vm-hands-entry-lite-c4959xva.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-dtn5wds4.js → vm-hands-entry-lite-d467t8z5.js} +1 -1
  51. package/bin/vm-hands/vm-hands-entry-lite-f8ts9y2q.js +3 -0
  52. package/bin/vm-hands/{vm-hands-entry-lite-n9rwh8vy.js → vm-hands-entry-lite-fzq1je66.js} +19 -19
  53. package/bin/vm-hands/{vm-hands-entry-lite-k0enbx0h.js → vm-hands-entry-lite-g23v6zrd.js} +42 -42
  54. package/bin/vm-hands/{vm-hands-entry-lite-0sh835na.js → vm-hands-entry-lite-haws181e.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-gh0yjzye.js → vm-hands-entry-lite-hc11hecd.js} +1 -1
  56. package/bin/vm-hands/{vm-hands-entry-lite-8evapfhb.js → vm-hands-entry-lite-jnym8gwb.js} +5 -5
  57. package/bin/vm-hands/{vm-hands-entry-lite-v0zva5nj.js → vm-hands-entry-lite-krnvgf71.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-90y6pf98.js → vm-hands-entry-lite-kwmjn9y3.js} +3 -3
  59. package/bin/vm-hands/{vm-hands-entry-lite-mma9qt5r.js → vm-hands-entry-lite-mfvtp7py.js} +1 -1
  60. package/bin/vm-hands/{vm-hands-entry-lite-2crj59fq.js → vm-hands-entry-lite-mq1gw5t4.js} +3 -3
  61. package/bin/vm-hands/{vm-hands-entry-lite-19dpjtpb.js → vm-hands-entry-lite-n3274tws.js} +1 -1
  62. package/bin/vm-hands/{vm-hands-entry-lite-7gzn7myq.js → vm-hands-entry-lite-nc915j4r.js} +5 -5
  63. package/bin/vm-hands/{vm-hands-entry-lite-tdpnjywj.js → vm-hands-entry-lite-p6b8e7zr.js} +2 -2
  64. package/bin/vm-hands/vm-hands-entry-lite-paryp920.js +150 -0
  65. package/bin/vm-hands/{vm-hands-entry-lite-zc8fsn2e.js → vm-hands-entry-lite-pzj5s203.js} +2 -2
  66. package/bin/vm-hands/{vm-hands-entry-lite-svd5v9dr.js → vm-hands-entry-lite-q1yvw4xz.js} +1 -1
  67. package/bin/vm-hands/{vm-hands-entry-lite-1nrxnm0y.js → vm-hands-entry-lite-sfmeafdm.js} +9 -9
  68. package/bin/vm-hands/{vm-hands-entry-lite-5eg3tgdq.js → vm-hands-entry-lite-t82dzcxb.js} +2 -2
  69. package/bin/vm-hands/{vm-hands-entry-lite-q80xmhrx.js → vm-hands-entry-lite-tash5m18.js} +14 -14
  70. package/bin/vm-hands/{vm-hands-entry-lite-ndhspax6.js → vm-hands-entry-lite-tns12zqc.js} +2 -2
  71. package/bin/vm-hands/{vm-hands-entry-lite-5np5k3wb.js → vm-hands-entry-lite-wfc0agnt.js} +3 -3
  72. package/bin/vm-hands/{vm-hands-entry-lite-ft81ht65.js → vm-hands-entry-lite-wyb2wphg.js} +7 -7
  73. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  74. package/bin/vm-hands/{vm-hands-executor-wdk7j5ff.js → vm-hands-executor-mm2t3341.js} +3 -3
  75. package/bin/vm-hands/vm-hands-op-runner-q7xymef5.js +2 -0
  76. package/bin/vm-hands/{vm-hands-runtime-xsm007dw.js → vm-hands-runtime-s4ptwfrm.js} +3 -3
  77. package/bin/vm-hands/worker-preview-readiness-8ftb3nbw.js +2 -0
  78. package/bin/vm-hands/worker-sandbox-k0vx97tx.js +2 -0
  79. package/package.json +1 -1
  80. package/bin/vm-hands/api-19drw8h8.js +0 -2
  81. package/bin/vm-hands/api-credentials-51jbbsb9.js +0 -2
  82. package/bin/vm-hands/connect-cli-key5zmnv.js +0 -2
  83. package/bin/vm-hands/credentials-yf556ykn.js +0 -2
  84. package/bin/vm-hands/custom-endpoint-device-vbct7bj9.js +0 -2
  85. package/bin/vm-hands/desktop-account-j6fjngt1.js +0 -2
  86. package/bin/vm-hands/install-receipt-gwv1qv2m.js +0 -2
  87. package/bin/vm-hands/local-automation-qq5sskt4.js +0 -2
  88. package/bin/vm-hands/local-capabilities-46mncb6r.js +0 -2
  89. package/bin/vm-hands/local-desktop-users-4hc6jysa.js +0 -2
  90. package/bin/vm-hands/local-display-mac-fjeyb4h9.js +0 -2
  91. package/bin/vm-hands/local-display-session-591yjg8s.js +0 -2
  92. package/bin/vm-hands/local-display-video-yjg6cj63.js +0 -2
  93. package/bin/vm-hands/local-managed-process-f2cyg1ax.js +0 -2
  94. package/bin/vm-hands/local-pty-session-4h4ekakp.js +0 -2
  95. package/bin/vm-hands/managed-runtime-yf9asm5j.js +0 -2
  96. package/bin/vm-hands/network-contract-4wew8f21.js +0 -2
  97. package/bin/vm-hands/package-sng72tm1.js +0 -2
  98. package/bin/vm-hands/permissions-pkmd26vk.js +0 -2
  99. package/bin/vm-hands/serve-service-rna11dh7.js +0 -2
  100. package/bin/vm-hands/version-gpqwzy05.js +0 -2
  101. package/bin/vm-hands/vm-hands-entry-lite-60pnam39.js +0 -3
  102. package/bin/vm-hands/vm-hands-entry-lite-krrsffbp.js +0 -2
  103. package/bin/vm-hands/vm-hands-entry-lite-nrrgwj9v.js +0 -128
  104. package/bin/vm-hands/vm-hands-op-runner-wtm4g7ec.js +0 -2
  105. package/bin/vm-hands/worker-preview-readiness-ye6cvg3k.js +0 -2
  106. package/bin/vm-hands/worker-sandbox-j6cmex8e.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{nt,Et,cr,on,xt,kt,Oi,sn,Ii,Di,Ni}from"./vm-hands-entry-lite-mma9qt5r.js";import{Pe,sr,ri,wt,zo,oe,qo,Wo,tt,Te,nn,ii,vt,ci,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,pe,Y,Re,q,vi,Si,Ei,xi,ki,Ci,Ai,Pi,St,Ti}from"./vm-hands-entry-lite-ydgedg8n.js";import{ue,Z,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{P,Xt}from"./vm-hands-entry-lite-fgppp6x9.js";import{mr,Yi,Qi,at,eo,to,ro,no,io,oo,yr,wr,br,wn,bn,vr,ao,vn,Sr,me,ge,Dt,Er,kr,Nt}from"./vm-hands-entry-lite-n9rwh8vy.js";import{D,R,b}from"./vm-hands-entry-lite-q80xmhrx.js";import{Ki,Ji,_n,Zi,yn,Xi,st,fr}from"./vm-hands-entry-lite-2crj59fq.js";import{K}from"./vm-hands-entry-lite-wx1fmrbs.js";import{He}from"./vm-hands-entry-lite-dcrz19xf.js";import{j}from"./vm-hands-entry-lite-gh0yjzye.js";import{hr,gn,Gi}from"./vm-hands-entry-lite-5np5k3wb.js";import{wo,bo,dt,vo,So,Eo,xo,ko}from"./vm-hands-entry-lite-1nrxnm0y.js";import{Ir,Vt,Dr,jn,Un}from"./vm-hands-entry-lite-qxeegp2n.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-nrrgwj9v.js";import{Nn,x,go}from"./vm-hands-entry-lite-8evapfhb.js";import{_o,yo}from"./vm-hands-entry-lite-029385a5.js";import{Bt,Pn,Tn}from"./vm-hands-entry-lite-bp8kdega.js";import{ye,uo,po}from"./vm-hands-entry-lite-90y6pf98.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{$t}from"./vm-hands-entry-lite-ckezse0f.js";import{ve,Ht,zt,qt,E}from"./vm-hands-entry-lite-70hq7mrs.js";import{a,ie}from"./vm-hands-entry-lite-0sh835na.js";import{t,k,o,d,u,i,W,g,ee,s,n,Ko}from"./vm-hands-entry-lite-70x16hkx.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,Me,ln}from"./vm-hands-entry-lite-qz74j563.js";import{$e}from"./vm-hands-entry-lite-mcjca0ez.js";import{request as Nl}from"http";import{request as Ml}from"https";import{lookup as $l}from"dns/promises";import{isIP as Bl}from"net";async function Fl(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Ml:Nl)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:Oi},(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 Wi=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),Ul=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Vi(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(Wi.has(c))return"custom_endpoint_host_not_found";if(Ul.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=Vi(p,l+1);if(m)return m}return null}async function Hl(e,l){let c=Vi(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||Bl(p)!==0)return c;let m;return await Promise.race([$l(p).then(()=>!0,(h)=>!Wi.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function jl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function ql(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 zi(e){e.signal.throwIfAborted();let l=Ii.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=Di.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=jl(p.apiKey),_=ql(p.apiKey,w),v=async(I,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(I,A))).then(()=>{e.signal.removeEventListener("abort",L),M()},(B)=>{e.signal.removeEventListener("abort",L),N(B)})})},C=async(I)=>{if(h+=I.length,h>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<I.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:I.subarray(A,A+Et).toString("base64")})}};try{let I=await Fl({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=I.response,f=I.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 C(_(L))}return await C(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(I){if(e.signal.throwIfAborted(),I instanceof r)throw I;throw new r((m?null:await Hl(I,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as os}from"path";function Wl(e,l){return e===os(l,".ara","workspace")||e===os(l,".reason","workspace")}function ss(e,l){let c=e.filter((p)=>Wl(p.path,l));return c.length===1?c[0].path:null}var Vl=/^[a-f0-9]{64}$/;var an=32,zl=/^\/[^\x00-\x1f\x7f\\]*$/;function Cr(e){if(typeof e!=="string"||e.length>4096||!zl.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"||!Vl.test(m)||!Cr(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Gl(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 Yl(e){return Gl(e)??e.email.toLowerCase()}function un(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?Yl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var Gt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Kl=[...ve.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...Ht.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...[...zt].map((e)=>`/(${Gt(e)})$`),`/${Gt(".env.")}[^/]*$`,...qt.map((e)=>`/[^/]*${Gt(e)}$`)],as=`function localGithubSandboxProfile(root, temporary) {
2
+ import{nt,Et,cr,on,xt,kt,Ii,sn,Di,Ni,Li}from"./vm-hands-entry-lite-mfvtp7py.js";import{Pe,sr,ni,wt,Vo,oe,Go,Ko,tt,Re,nn,oi,vt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Y,Te,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ri,St,Ti}from"./vm-hands-entry-lite-88yjxxvf.js";import{ue,Z,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{P,Xt}from"./vm-hands-entry-lite-c0t5xpzh.js";import{mr,Qi,eo,at,to,ro,no,io,oo,so,yr,wr,br,wn,bn,vr,co,vn,Sr,me,ge,Dt,Er,kr,Nt}from"./vm-hands-entry-lite-fzq1je66.js";import{D,T,b}from"./vm-hands-entry-lite-tash5m18.js";import{Ji,Zi,_n,Xi,yn,Yi,st,fr}from"./vm-hands-entry-lite-mq1gw5t4.js";import{K}from"./vm-hands-entry-lite-bvqwsd3b.js";import{He}from"./vm-hands-entry-lite-a6w60nv9.js";import{j}from"./vm-hands-entry-lite-hc11hecd.js";import{hr,gn,Ki}from"./vm-hands-entry-lite-wfc0agnt.js";import{bo,vo,dt,So,Eo,xo,ko,Co,Ao,Po}from"./vm-hands-entry-lite-sfmeafdm.js";import{Ir,Vt,Dr,Un,Hn}from"./vm-hands-entry-lite-5wsygx6n.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-paryp920.js";import{Nn,x,_o}from"./vm-hands-entry-lite-jnym8gwb.js";import{yo,wo}from"./vm-hands-entry-lite-82ky5wgg.js";import{Bt,Pn,Rn}from"./vm-hands-entry-lite-59typww6.js";import{ye,po,ho}from"./vm-hands-entry-lite-kwmjn9y3.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{$t}from"./vm-hands-entry-lite-ckezse0f.js";import{ve,Ht,zt,qt,E}from"./vm-hands-entry-lite-70hq7mrs.js";import{a,ie}from"./vm-hands-entry-lite-haws181e.js";import{t,k,o,d,u,i,W,g,ee,s,n,Xo}from"./vm-hands-entry-lite-4cdn822w.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,Me,ln}from"./vm-hands-entry-lite-1kt82jes.js";import{$e}from"./vm-hands-entry-lite-mcjca0ez.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:Ii},(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 Gi=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(Gi.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)=>!Gi.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=Di.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,I)=>{e.signal.throwIfAborted(),await new Promise((M,N)=>{let A=()=>{e.signal.removeEventListener("abort",A),N(e.signal.reason)};if(e.signal.addEventListener("abort",A,{once:!0}),e.signal.aborted){A();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(C,I))).then(()=>{e.signal.removeEventListener("abort",A),M()},(B)=>{e.signal.removeEventListener("abort",A),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 I=0;I<C.length;I+=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(I,I+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 I=m.statusCode??500;if(I>=300&&I<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 A=m.headers[N];if(typeof A==="string")M[N]=A.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:I,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:M});for await(let N of m){e.signal.throwIfAborted();let A=Buffer.isBuffer(N)?N:Buffer.from(N);if(y+=A.length,y>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await R(_(A))}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("/")})(/|$)`),...Ht.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...[...zt].map((e)=>`/(${Gt(e)})$`),`/${Gt(".env.")}[^/]*$`,...qt.map((e)=>`/[^/]*${Gt(e)}$`)],cs=`function localGithubSandboxProfile(root, temporary) {
3
3
  return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
4
4
  '(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
5
5
  '(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
@@ -8,34 +8,34 @@ import{nt,Et,cr,on,xt,kt,Oi,sn,Ii,Di,Ni}from"./vm-hands-entry-lite-mma9qt5r.js";
8
8
  '(allow file-read-metadata (path-ancestors '+JSON.stringify(root)+') (path-ancestors '+JSON.stringify(temporary)+'))',
9
9
  '(deny file-read* file-write* (subpath "/opt/homebrew/etc") (subpath "/usr/local/etc") (literal "/private/etc/master.passwd"))',
10
10
  '(deny file-write* (subpath "/opt/homebrew") (subpath "/usr/local") (subpath "/Library/Developer") (subpath "/cores"))',
11
- ...${JSON.stringify(Kl)}.map(pattern => '(deny file-read* file-write* (regex #"'+pattern+'"))'),
11
+ ...${JSON.stringify(Jl)}.map(pattern => '(deny file-read* file-write* (regex #"'+pattern+'"))'),
12
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 Jl,spawnSync as Zl}from"child_process";import*as G from"fs";import*as se from"path";import{homedir as Ql}from"os";function ls(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 cs(e,l){let c=1;for(let p=0;p<l;p+=1)if(e.charCodeAt(p)===10)c+=1;return c}var us=[{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 ds(e){return[...new Set(e.map((l)=>l.trim()).filter((l)=>l.length>=8))]}function ps(e,l){return[...l.matchAll(new RegExp(e.regex.source,`${e.regex.flags}g`))]}function Or(e,l=[],c={}){let p=[],m=c.published??new Set,f=ds(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:cs(S,w[0].offset),..._.length>0?{secretNames:_}:{}})}for(let _ of us){let v=ps(_,S).find((C)=>!m.has(C[0]));if(v){p.push({path:h.path,reason:`credential_pattern_detected: ${_.name}`,pattern:_.name,ruleId:_.name,line:cs(S,v.index)});break}}}return{clean:p.length===0,violations:p,scannedObjectCount:e.length}}function ms(e,l=[]){let c=ds(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 us)for(let h of ps(f,m))p.add(h[0])}return[...p]}function Xl(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 fs(e,l,c){let p=(m,f)=>m.reduce((h,y)=>h+Xl(y,f),0);return new Set(e.filter((m)=>p(l,m)<=p(c,m)))}var ht=4194304,Ye=process.platform==="win32",Kt=process.env.SystemRoot??"C:\\Windows",ec=(e)=>Ye?Zl(se.win32.join(Kt,"System32","taskkill.exe"),["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-e,"SIGKILL"),Yt=Ye?[se.win32.join(Kt,"System32"),Kt].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",Ar=Ye?{SystemRoot:Kt,WINDIR:Kt}:{},tc=(e)=>Ye?se.win32.resolve(e,"..","..","bin","sh.exe"):"/bin/sh",hs=536870912,pn=/^[a-f0-9]{40}$/,rc=(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=Jl(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=(I)=>{if(y??=Error(I),m.pid)try{ec(m.pid)}catch{}},_=()=>w("cancelled"),v=setTimeout(()=>w("timeout"),c.timeout);c.signal?.addEventListener("abort",_,{once:!0});let C=(I)=>{if(S)return;S=!0,clearTimeout(v),c.signal?.removeEventListener("abort",_),p({status:I,stdout:f,stderr:h,...y?{error:y}:{}})};if(m.stdout.on("data",(I)=>{if(f.length+h.length+I.length>c.maxBuffer)w("output_limit");else f=Buffer.concat([f,I])}),m.stderr.on("data",(I)=>{if(f.length+h.length+I.length>c.maxBuffer)w("output_limit");else h=Buffer.concat([h,I])}),m.on("error",()=>{if(w("spawn_failed"),!m.pid)C(null)}),m.on("close",(I)=>C(I)),m.stdin.on("error",()=>w("input_failed")),m.stdin.end(c.input),c.signal?.aborted)_()}),nc={command:rc,gh:(e,l)=>ls(G,se,e,l),home:Ql};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 oc(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 ic=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),sc=(e)=>JSON.stringify(e,(l,c)=>ic.has(l)?void 0:c);function gs(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 _s(e,l,c=nc){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 T=Or([{path:"github-operation",content:sc(p)}],l.forbiddenSecretValues,l.secretNames?{secretNames:l.secretNames}:{});if(!T.clean)gs(T.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),Yt].join(";"):Yt,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((T)=>process.env[T]?[[T,process.env[T]]]:[])):{}},v=async(T,V,z=w,Q,ae=ht)=>{l.assertCurrent();let le=await c.command(T,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},C=async(T)=>(await v(h,T)).toString("utf8").trim(),I=async(T,V="application/vnd.github+json")=>{qo(p.repoFullName,T,{headers:{accept:V}}),l.assertCurrent();let z=await c.command(h,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${V}`,T],{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 I(p.path,p.accept);if(p.kind==="pr_review_context"){let[T,V]=p.repoFullName.split("/"),z=await C(["api","graphql","--hostname","github.com","-f",`query=${Wo}`,"-f",`owner=${T}`,"-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 T=await I(`/repos/${p.repoFullName}/pulls/${p.number}`),V=JSON.parse(T.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(T.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 C(["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 I(`/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 T=await C(["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(T))U("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:T}}if(p.kind==="pr_mutation"){let T=p.mutation,V=T.action==="edit"?["edit",...T.title!==void 0?[`--title=${T.title}`]:[],...T.body!==void 0?[`--body=${T.body}`]:[],...T.base?[`--base=${T.base}`]:[]]:T.action==="metadata"?["edit",`--${T.change}-${T.field}=${T.value}`]:T.action==="ready"?["ready"]:T.action==="draft"?["ready","--undo"]:["close"];return await C(["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=$e(as),B=(T,V,z)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",T,V,...z]]:[V,z],F=async(T,V,z,Q=ht)=>{let ae=hn(w,T),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,T,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:T,input:z,maxBuffer:Q,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Ar,PATH:Yt,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(T,V)=>(await F(T,V)).toString("utf8").trim(),ne=async(T,V)=>{let z=se.join(T,".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(T,z),tc(S),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",V]),{cwd:T,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Ar,PATH:Yt,HOME:T,TMPDIR:z}});if(l.assertCurrent(),Q.error||Q.status!==0)U("local_device_gh_materialization_failed")},_e=async(T)=>{let V=new Map;if(T.length===0)return V;let z=await F(he,["cat-file","--batch"],[...new Set(T)].join(`
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 Or(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",Kt=process.env.SystemRoot??"C:\\Windows",rc=(e)=>Ye?ec(se.win32.join(Kt,"System32","taskkill.exe"),["/PID",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-e,"SIGKILL"),Yt=Ye?[se.win32.join(Kt,"System32"),Kt].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",Ar=Ye?{SystemRoot:Kt,WINDIR:Kt}:{},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 L=Or([{path:"github-operation",content:lc(p)}],l.forbiddenSecretValues,l.secretNames?{secretNames:l.secretNames}:{});if(!L.clean)ys(L.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),Yt].join(";"):Yt,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((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},v=async(L,V,z=w,Q,ae=ht)=>{l.assertCurrent();let le=await c.command(L,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(L)=>(await v(h,L)).toString("utf8").trim(),C=async(L,V="application/vnd.github+json")=>{Go(p.repoFullName,L,{headers:{accept:V}}),l.assertCurrent();let z=await c.command(h,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${V}`,L],{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[L,V]=p.repoFullName.split("/"),z=await R(["api","graphql","--hostname","github.com","-f",`query=${Ko}`,"-f",`owner=${L}`,"-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 L=await C(`/repos/${p.repoFullName}/pulls/${p.number}`),V=JSON.parse(L.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(L.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 L=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(L))U("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(p.kind==="pr_mutation"){let L=p.mutation,V=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await 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 I=G.realpathSync(l.repoPath);if(!hn(f,I))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",A=$e(cs),B=(L,V,z)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,V,...z]]:[V,z],F=async(L,V,z,Q=ht)=>{let ae=hn(w,L),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,L,z,Q);let Ie=se.join(I,".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(A(I,Ie),S,le),{cwd:L,input:z,maxBuffer:Q,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Ar,PATH:Yt,HOME:I,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(L,V)=>(await F(L,V)).toString("utf8").trim(),ne=async(L,V)=>{let z=se.join(L,".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(A(L,z),nc(S),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",V]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Ar,PATH:Yt,HOME:L,TMPDIR:z}});if(l.assertCurrent(),Q.error||Q.status!==0)U("local_device_gh_materialization_failed")},_e=async(L)=>{let V=new Map;if(L.length===0)return V;let z=await F(he,["cat-file","--batch"],[...new Set(L)].join(`
14
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(T,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(T)}))
18
- (allow file-read-metadata (path-ancestors ${JSON.stringify(T)}))`,le=async(De,it)=>{l.assertCurrent();let Mt=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:Yt,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(),Mt.error||Mt.status!==0)U("local_device_gh_materialization_failed")},Ie=["--git-dir="+T,"--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 I(`/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
- `,hs);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 T=se.join(A,".git");if(!G.lstatSync(T).isDirectory()||G.lstatSync(T).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((we)=>G.existsSync(se.join(T,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 I(`/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 I(`/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(`
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(L,V,z)=>{let Q=se.join(I,".ara-local-gh-tmp"),ae=A(I,Q)+`
16
+ (allow file-read* file-write* (subpath ${JSON.stringify(I)}))
17
+ (allow file-read* (subpath ${JSON.stringify(L)}))
18
+ (allow file-read-metadata (path-ancestors ${JSON.stringify(L)}))`,le=async(De,it)=>{l.assertCurrent();let Mt=await c.command(...B(ae,De,it),{cwd:I,maxBuffer:ht,timeout:Math.max(1,Math.min(25000,(l.deadlineMs??Date.now()+25000)-Date.now())),signal:l.signal,env:{...Ar,PATH:Yt,HOME:I,TMPDIR:Q,GIT_INDEX_FILE:se.join(I,".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(),Mt.error||Mt.status!==0)U("local_device_gh_materialization_failed")},Ie=["--git-dir="+L,"--work-tree="+I,"-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(I,["update-ref","refs/heads/"+z,V]),await F(I,["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(I,".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(I,["rev-parse","--verify","-q","HEAD"]).then((Ce)=>Ce.toString("utf8").trim(),()=>null),ze=await F(I,["config","--local","--get","remote.origin.url"]).then((Ce)=>Ce.toString("utf8").trim(),()=>"");if(ke!==null||ze){if(ke!==p.baseSha||await H(I,["branch","--show-current"])!==p.branch)U("local_device_gh_checkout_exists");return{kind:"prepare",headSha:p.baseSha}}Ve=!0}let Be=G.readdirSync(I).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(I,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(I,["init","--template="]);m="local_device_gh_prepare_materialization";let Qe=await F(he,["pack-objects","--stdout","--revs"],p.baseSha+`
19
+ `,_s);return await ne(I,p.baseSha),await F(I,["index-pack","--strict","--stdin"],Qe,65536),await F(I,["remote","add","origin",M]),await Ee(he,p.baseSha,p.branch),{kind:"prepare",headSha:p.baseSha}}let L=se.join(I,".git");if(!G.lstatSync(L).isDirectory()||G.lstatSync(L).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((we)=>G.existsSync(se.join(L,we))))U("local_device_gh_repository_layout_invalid");if(await H(I,["branch","--show-current"])!==p.branch)U("local_device_gh_branch_changed");let V=await H(I,["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(I,["rev-list","--objects","--no-object-names",V,"--not",p.baseSha])).split(`
20
+ `),...(await H(I,["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(I,["pack-objects","--stdout"],[...new Set(ae)].join(`
22
22
  `)+`
23
- `,hs);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:oc(De,p.contributorTrailers)}:void 0,Mt=(await H(he,["rev-list","--objects","--no-object-names",V,"--not",p.baseSha,...p.remoteHeadSha?[p.remoteHeadSha]:[]])).split(`
25
- `).filter(Boolean);if(Mt.length>5000)U("local_device_gh_collection_too_large");let Ut=[],Fi=0;for(let we of Mt){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(Fi+=Be.length,Fi>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}}Ut.push({path:`object-${we}`,content:Be.toString("utf8")})}let Ui=l.secretNames?{secretNames:l.secretNames}:{},Wt=Or(Ut,l.forbiddenSecretValues,Ui),Hi=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[,Tl,Dl,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(Tl!=="160000"&&!/^0+$/.test(rn))Ve.push(rn);if(Dl!=="160000"&&!/^0+$/.test(xr))Be.push(xr),Hi.set(`object-${xr}`,we[Ce+1])}let Xe=await _e([...Ve,...Be]),Qe=new Set(Wt.violations.map((Ce)=>Ce.path)),ke=ms(Ut.filter((Ce)=>Qe.has(Ce.path)),l.forbiddenSecretValues),ze=fs(ke,Be.map((Ce)=>Xe.get(Ce)??""),Ve.map((Ce)=>Xe.get(Ce)??""));if(ze.size>0)Wt=Or(Ut,l.forbiddenSecretValues,{...Ui,published:ze})}catch{}if(!Wt.clean)gs(Wt.violations,(we)=>Hi.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 ji=await I(`/repos/${p.repoFullName}/git/ref/heads/${encodeURIComponent(p.branch)}`);if(ji.status!==200||JSON.parse(ji.body).object?.sha!==V)U("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:V,scannedObjectCount:Ut.length,...it?{attribution:it}:{}}}catch(T){throw Rr=!0,T}finally{try{G.rmSync(he,{recursive:!0,force:!0})}catch(T){if(!Rr||p.kind!=="prepare")throw m=null,T}}}catch(f){if(p.kind==="prepare"&&p.diagnosticsVersion===1&&m&&!l.signal?.aborted)throw new sr(m);throw f}}var gt=i({profile:t().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:t().min(1).max(1024)}).strict(),Rn={ready:n(!0),boot_generation:t().uuid(),proof_ready:n(!1),result:n("metadata_only")},ac=i({...Rn,version:n(2),development_only:n(!1),image:n(!0),video:n(!1),source_bound:n(!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),lc=i({...Rn,version:n(3),development_only:n(!1),image:n(!0),video:n(!0),source_bound:n(!1),max_seconds:n(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),xn=W([ac,lc]),xm=W([i({...Rn,version:n(1),development_only:n(!0),profile:gt.shape.profile,extension_instance_id:gt.shape.extension_instance_id,max_seconds:n(15)}).strict(),xn]);import{createServer as cc,request as uc}from"http";import{connect as dc,isIP as pc}from"net";var Ss=120000,mc=15000;function fc(e,l,c){let p=vr(l).toLowerCase().replace(/\.$/,"");if(!p||pc(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 hc(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 En(e,l,c){if(!fc(c,e,l))return null;let p=await ao(e);return p.ok?p.addresses[0]:null}function Jt(e,l){e.end(`HTTP/1.1 ${l} ${l===403?"Forbidden":"Bad Gateway"}\r
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,Mt=(await H(he,["rev-list","--objects","--no-object-names",V,"--not",p.baseSha,...p.remoteHeadSha?[p.remoteHeadSha]:[]])).split(`
25
+ `).filter(Boolean);if(Mt.length>5000)U("local_device_gh_collection_too_large");let Ut=[],ji=0;for(let we of Mt){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(ji+=Be.length,ji>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}}Ut.push({path:`object-${we}`,content:Be.toString("utf8")})}let qi=l.secretNames?{secretNames:l.secretNames}:{},Wt=Or(Ut,l.forbiddenSecretValues,qi),Vi=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),Vi.set(`object-${xr}`,we[Ce+1])}let Xe=await _e([...Ve,...Be]),Qe=new Set(Wt.violations.map((Ce)=>Ce.path)),ke=hs(Ut.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=Or(Ut,l.forbiddenSecretValues,{...qi,published:ze})}catch{}if(!Wt.clean)ys(Wt.violations,(we)=>Vi.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 zi=await C(`/repos/${p.repoFullName}/git/ref/heads/${encodeURIComponent(p.branch)}`);if(zi.status!==200||JSON.parse(zi.body).object?.sha!==V)U("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:V,scannedObjectCount:Ut.length,...it?{attribution:it}:{}}}catch(L){throw Rr=!0,L}finally{try{G.rmSync(he,{recursive:!0,force:!0})}catch(L){if(!Rr||p.kind!=="prepare")throw m=null,L}}}catch(f){if(p.kind==="prepare"&&p.diagnosticsVersion===1&&m&&!l.signal?.aborted)throw new sr(m);throw f}}var gt=i({profile:t().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:t().min(1).max(1024)}).strict(),xn={ready:n(!0),boot_generation:t().uuid(),proof_ready:n(!1),result:n("metadata_only")},cc=i({...xn,version:n(2),development_only:n(!1),image:n(!0),video:n(!1),source_bound:n(!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=i({...xn,version:n(3),development_only:n(!1),image:n(!0),video:n(!0),source_bound:n(!1),max_seconds:n(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([i({...xn,version:n(1),development_only:n(!0),profile:gt.shape.profile,extension_instance_id:gt.shape.extension_instance_id,max_seconds:n(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 co(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
26
  Connection: close\r
27
27
  Content-Length: 0\r
28
28
  \r
29
- `)}function ys(e,l){return new Promise((c,p)=>{let m=dc({host:e,port:l}),f=setTimeout(()=>m.destroy(Error("connect_timeout")),mc);m.once("connect",()=>{clearTimeout(f),c(m)}),m.once("error",(h)=>{clearTimeout(f),p(h)})})}function bs(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(Ss,()=>l.destroy()),c.length)l.write(c);e.pipe(l).pipe(e)}function ws(e,l){let c={...e,host:l};return delete c["proxy-authorization"],delete c["proxy-connection"],c}async function vs(e,l=()=>{}){let c=[...e],p=new Set,m=(y)=>{p.add(y),y.once("close",()=>p.delete(y))},f=cc((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 En(w.hostname,_,c):null;if(!v){l(),S.writeHead(403,{connection:"close"}).end();return}let C=uc({host:v,port:_,method:y.method,path:`${w.pathname}${w.search}`,headers:ws(y.headers,w.host),agent:!1,timeout:Ss},(I)=>{S.writeHead(I.statusCode??502,I.headers),I.pipe(S)});C.on("timeout",()=>C.destroy()),C.on("error",()=>{if(!S.headersSent)S.writeHead(502);S.end()}),S.on("close",()=>C.destroy()),y.pipe(C)})().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 _=hc(y.url??"",443),v=_?await En(_.host,_.port,c):null;if(!_||!v){l(),Jt(S,403);return}let C=await ys(v,_.port).catch(()=>null);if(!C){Jt(S,502);return}if(S.destroyed){C.destroy();return}m(C),S.write(`HTTP/1.1 200 Connection Established\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
30
  \r
31
- `),bs(S,C,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),C=["http:","ws:"].includes(_.protocol)?await En(_.hostname,v,c):null;if(!C){l(),Jt(S,403);return}let I=await ys(C,v).catch(()=>null);if(!I){Jt(S,502);return}m(I);let A=ws(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}`);I.write(`${M.join(`\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 I=vs(y.headers,_.host),M=[`${y.method} ${_.pathname}${_.search} HTTP/1.1`];for(let[N,A]of Object.entries(I))for(let B of Array.isArray(A)?A:A===void 0?[]:[A])M.push(`${N}: ${B}`);C.write(`${M.join(`\r
32
32
  `)}\r
33
33
  \r
34
- `),bs(S,I,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 bc}from"crypto";import{closeSync as Fr,constants as Fe,fchownSync as wc,fstatSync as lt,fsyncSync as Sc,linkSync as Bs,lstatSync as kn,mkdirSync as Fs,openSync as $r,readSync as js,realpathSync as Dn,unlinkSync as Us,writeSync as vc}from"fs";import{isAbsolute as Rc,join as xc,relative as Ec,sep as Cc}from"path";import{platform as Mn}from"os";import{getSystemErrorName as Pc}from"util";var Rs={type:"string",format:"uuid"},Ps=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,Lr={type:"string",minLength:1,maxLength:4096,pattern:Ps},Cn=t().min(1).max(4096).regex(new RegExp(Ps)),Tr={device_id:t().uuid(),root_id:t().uuid(),timeout_ms:o().int().min(1000).max(60000).optional()},Nr={device_id:Rs,root_id:Rs,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},km={read:{schema:i({...Tr,path:Cn,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:i({...Tr,path:Cn,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:i({...Tr,command:t().min(1).max(16000),cwd:Cn.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,xs=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,Os=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${xs}(?:/${xs})*(?![\s\S])`,Is=new RegExp(Os);function As(e){return typeof e==="string"&&e.length>0&&e.length<=4096&&Is.test(e)}var On=t().min(1).max(4096).regex(Is),In={...Lr,pattern:Os},ks=t().regex(/^[a-f0-9]{64}$/),Ts=i({kind:n("workspace"),path:On}).strict(),gc=g("kind",[Ts,i({kind:n("attachment"),attachment_id:t().min(1).max(120),sha256:ks}).strict()]),Mr=1,Qt="cloud_workspace_id",An="cloud_workspace",Ln=1,_c=g("kind",[Ts,i({kind:n("attachment"),download_url:t().min(1).max(16384),size_bytes:o().int().min(0).max(Je),sha256:ks}).strict()]),$s=i({source_version:n(Mr),source:_c,url:t().min(1).max(16384),transfer_cloud_scope:i({sandboxId:t().min(1).max(256),revision:o().int().nonnegative(),brainFence:t().uuid()}).strict().optional(),[Qt]:t().min(1).max(160).optional()}).strict(),Tm=i({ready:n(!0),cloud_source_version:n(Mr),source_kinds:u(s(["workspace","attachment"]))});var Es=i({...Tr,timeout_ms:o().int().min(1000).max(Zt).optional(),source_path:On,destination_path:On,idempotency_key:t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),Cs={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...Nr,timeout_ms:{type:"integer",minimum:1000,maximum:Zt},source_path:In,destination_path:In,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},yc={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:In},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}]},Dm=W([Es,Es.omit({source_path:!0}).extend({source:gc}).strict()]),Nm={...Cs,required:["device_id","root_id","destination_path"],properties:{...Cs.properties,source:yc},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 Oc(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 Ic(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 Ac(){if(Mn()==="win32"){let w=new Map,_,v=-1,C=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),I=(L)=>{let B=Ec(_,L);return B===""||B!==".."&&!B.startsWith(`..${Cc}`)&&!Rc(B)},A=(L)=>{let B=kn(L);if(B.isSymbolicLink())throw C();if(!B.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let F=Dn(L);if(_??=F,!I(F))throw C();return w.set(v,{path:L,real:F}),v--},M=(L)=>{let B=w.get(L);if(Dn(B.path)!==B.real)throw C();return B.path},N=(L,B)=>{if(ln(B))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return xc(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(kn(ne,{throwIfNoEntry:!1})?.isSymbolicLink())throw C();M(L);let _e=$r(ne,F,H);try{let Ee=lt(_e),Ze=kn(ne);if(Ze.isSymbolicLink()||Ee.ino!==Ze.ino||Ee.dev!==Ze.dev||!I(Dn(ne)))throw C()}catch(Ee){throw Fr(_e),Ee}return _e},mkdir:(L,B)=>{let F=N(L,B);M(L),Fs(F)},link:(L,B,F)=>{let H=N(L,B),ne=N(L,F);M(L),Bs(H,ne)},unlink:(L,B)=>Us(N(L,B)),closeDirectory:(L)=>{w.delete(L)},inherit:()=>{},close:()=>{}}}let e={root:(w)=>$r(w,$n),closeDirectory:Fr,inherit:Lc};if(Mn()==="linux")return{...e,openDirectory:(w,_)=>$r(`/proc/self/fd/${w}/${_}`,$n),open:(w,_,v,C=384)=>$r(`/proc/self/fd/${w}/${_}`,v,C),mkdir:(w,_)=>Fs(`/proc/self/fd/${w}/${_}`,{mode:448}),link:(w,_,v)=>Bs(`/proc/self/fd/${w}/${_}`,`/proc/self/fd/${w}/${v}`),unlink:(w,_)=>Us(`/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 _=Pc(-m.i32(h));throw Object.assign(Error("transfer_path_unavailable"),{code:_})}return w},S=(w,_,v,C=384)=>y(f.symbols.openat(w,p(Buffer.from(`${_}\x00`)),v,C,0,0,0,0,C));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 Lc(e,l){let c=lt(e),p=lt(l);if(p.uid!==c.uid||p.gid!==c.gid)wc(l,c.uid,c.gid)}function kc(e,l,c,p){if(!As(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 Hs(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=js(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=Ic(e.payload.url),c=await Ac(),p,m,f;try{if(p=kc(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 C=lt(m,{bigint:!0});if(!C.isFile()||C.size>Je)return Se("transfer_file_invalid");let I=Bn("sha256"),A=0,M=m,N,L=new ReadableStream({pull(ne){try{e.signal.throwIfAborted();let _e=Buffer.alloc(Fn),Ee=js(M,_e,0,_e.length,A);if(!Ee){ne.close();return}if(A+=Ee,A>C.size)return Se("transfer_source_changed");I.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(C.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)!==C.size||B.size!==C.size||B.mtimeNs!==C.mtimeNs||B.ctimeNs!==C.ctimeNs)return Se("transfer_source_changed");let F=I.digest("hex"),H=Hs(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(C){if(Ur(C)!=="ENOENT")throw C}if(S!==void 0){try{let C=Hs(S,e.signal);if(C.size_bytes===h&&C.sha256===y)return{...C,outcome:"already_present"}}finally{Fr(S)}return Se("transfer_destination_exists")}f=`.reason-copy-${bc()}`,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 C=await(e.fetchImpl??fetch)(l,{redirect:"error",signal:e.signal});if(!C.ok||!C.body)return Se("transfer_download_failed");w=C.body.getReader()}catch(C){return Br(C,e.signal,"transfer_download_failed")}let _=Bn("sha256"),v=0;try{while(!0){e.signal.throwIfAborted();let C=await w.read().catch((I)=>Br(I,e.signal,"transfer_download_failed"));if(C.done)break;if(v+=C.value.length,v>h)return Se("transfer_size_mismatch");_.update(C.value);for(let I=0;I<C.value.length;)e.signal.throwIfAborted(),I+=vc(m,C.value,I,Math.min(Fn,C.value.length-I))}}finally{await w.cancel().catch(()=>{})}if(v!==h||_.digest("hex")!==y)return Se("transfer_hash_mismatch");return Sc(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 Oc(l,e.signal,e.direction)}}import{spawn as Dc}from"child_process";import{mkdtempSync as Nc,rmSync as Mc,writeFileSync as $c}from"fs";import{constants as Bc,platform as Fc,tmpdir as Uc}from"os";import{join as zs}from"path";import{gunzipSync as Tc,gzipSync as Gm}from"zlib";var Ws=900000,Km=Ws+60000,er=49152,qs=(e)=>t().min(1).max(e).regex(/^[A-Za-z0-9+/]+=*$/),Vs=i({version:n(1),script_gzip:qs(163840),stdin_gzip:qs(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(Ws)}).strict(),Hn=t().max(er+256),Xm=i({exit_code:o().int().min(0).max(255),stdout:Hn,stderr:Hn,combined:Hn.optional()}).strict();function qn(e){return Tc(Buffer.from(e,"base64")).toString("utf8")}var Hc="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",jc=["RUSTUP_HOME","TZ","LC_ALL"],qc=2000,Wc=100;function Vn(){return Fc()==="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?`
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:i({...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:i({...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:i({...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=i({kind:n("workspace"),path:In}).strict(),yc=g("kind",[Ds,i({kind:n("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,i({kind:n("attachment"),download_url:t().min(1).max(16384),size_bytes:o().int().min(0).max(Je),sha256:Ts}).strict()]),Ns=i({source_version:n(Mr),source:bc,url:t().min(1).max(16384),transfer_cloud_scope:i({sandboxId:t().min(1).max(256),revision:o().int().nonnegative(),brainFence:t().uuid()}).strict().optional(),[Qt]:t().min(1).max(160).optional()}).strict(),Nm=i({ready:n(!0),cloud_source_version:n(Mr),source_kinds:u(s(["workspace","attachment"]))});var Ps=i({...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=(A)=>{let B=Pc(_,A);return B===""||B!==".."&&!B.startsWith(`..${Oc}`)&&!Ec(B)},I=(A)=>{let B=Tn(A);if(B.isSymbolicLink())throw R();if(!B.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let F=Dn(A);if(_??=F,!C(F))throw R();return w.set(v,{path:A,real:F}),v--},M=(A)=>{let B=w.get(A);if(Dn(B.path)!==B.real)throw R();return B.path},N=(A,B)=>{if(ln(B))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return Cc(w.get(A).path,B)};return{root:I,openDirectory:(A,B)=>I(N(A,B)),open:(A,B,F,H=384)=>{let ne=N(A,B);if(Tn(ne,{throwIfNoEntry:!1})?.isSymbolicLink())throw R();M(A);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:(A,B)=>{let F=N(A,B);M(A),Hs(F)},link:(A,B,F)=>{let H=N(A,B),ne=N(A,F);M(A),Us(H,ne)},unlink:(A,B)=>js(N(A,B)),closeDirectory:(A)=>{w.delete(A)},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"),I=0,M=m,N,A=new ReadableStream({pull(ne){try{e.signal.throwIfAborted();let _e=Buffer.alloc(Fn),Ee=Ws(M,_e,0,_e.length,I);if(!Ee){ne.close();return}if(I+=Ee,I>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:A,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(I)!==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!==I||H.sha256!==F)return Se("transfer_source_changed");return{size_bytes:I,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=i({version:n(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=i({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
35
  [reason: ${h} bytes of output omitted]
36
- `:"")+m.toString("utf8")}}}async function Gs(e,l){if(!Vn())throw new r("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let c=Vs.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=Nc(zs(Uc(),"reason-workspace-setup-"));try{let y=zs(h,"setup.sh");$c(y,m,{mode:384});let S={PATH:Hc,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let H of jc)if(process.env[H])S[H]=process.env[H];Object.assign(S,p.env);let w=Dc("/bin/bash",[y],{cwd:p.cwd,env:S,detached:!0,stdio:["pipe","pipe","pipe"]}),_=Wn(er),v=Wn(er),C=Wn(er);w.stdout.on("data",(H)=>{_.push(H),C.push(H)}),w.stderr.on("data",(H)=>{v.push(H),C.push(H)}),w.stdin.on("error",()=>{}),w.stdin.end(f);let I=(H)=>{try{if(w.pid)process.kill(-w.pid,H)}catch{}},A=!1,M,N=()=>{I("SIGTERM"),M??=setTimeout(()=>I("SIGKILL"),qc)},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,Wc);w.once("close",()=>{clearTimeout(ne),H()})}),w.stdout.destroy(),w.stderr.destroy(),l.throwIfAborted();let F=A?124:B.signal?128+(Bc.signals[B.signal]??0):B.code??1;return{exit_code:Math.min(255,F),stdout:_.text(),stderr:v.text(),...F!==0?{combined:C.text()}:{}}}finally{Mc(h,{recursive:!0,force:!0})}}import{chmodSync as Vc,mkdtempSync as zc,realpathSync as Ys,rmSync as Gc}from"fs";import{tmpdir as Yc}from"os";import{dirname as Kc,join as zn,sep as Xc}from"path";function Gn(e){return kr(e,Sr(e)!==null).repoPath}function Ks(e,l){let c;try{if(typeof l!=="string")throw Error("invalid");c=[Z,void 0].map((m)=>Kc(O({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=Ys(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}${Xc}`))throw new r("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return p}async function Xs(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=zc(zn(Yc(),`reason-cloud-copy-${process.pid}-`));try{Vc(c,448);let p=Ys(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{Gc(c,{recursive:!0,force:!0})}}import{constants as We}from"fs";import{closeSync as yl,existsSync as Ke,fstatSync as bl,ftruncateSync as fp,lstatSync as ni,mkdirSync as hp,mkdtempSync as gp,openSync as wl,readSync as _p,realpathSync as Ge,rmSync as yp,statSync as _r,writeSync as bp}from"fs";import{homedir as dr,platform as X,tmpdir as wp}from"os";import{dirname as pr,isAbsolute as Sp,join as Sl,relative as oi,resolve as vp,sep as Rp}from"path";import{spawn as xp}from"child_process";var _f=nn+15000;var Js=["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 Zc=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(Zc.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 Qc,constants as eu,existsSync as tu,statSync as ru}from"fs";import{basename as nu,isAbsolute as ou}from"path";var rr=["-lic"],Zs="/bin/zsh",iu=new Set(["zsh","bash"]),Qs=20000,Yn=60000,su=65536,au=64,lu=8192,cu=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),uu=["DYLD_","LD_"];function du(e){let l=e.toUpperCase();return cu.has(l)||uu.some((c)=>l.startsWith(c))}function ea(e=process.env){return!0}function pu(e){if(!ou(e)||e.includes("\x00"))return!1;if(!iu.has(nu(e)))return!1;try{if(!ru(e).isFile())return!1;return Qc(e,eu.X_OK),!0}catch{return!1}}function yt(e=process.env){if(process.platform==="win32")return fe()??Zs;let l=e.SHELL?.trim();if(l&&pu(l))return l;return Zs}function Kn(e=process.env){return ea(e)&&tu(yt(e))}function Xn(e=process.env){if(!ea(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")>su)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>au)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")>lu)throw new r("invalid_payload","env entry is invalid or too large.");if(du(m)){p.push(m);continue}c[m]=f}return{forwarded:c,ignored:p}}async function ta(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 ra(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 mu,readdir as fu,readlink as hu,realpath as gu}from"fs/promises";import{basename as _u,relative as yu,sep as bu}from"path";var ct="/proc",wu=250,na=500,Su=50,vu=250,Ru=1024,oa=4096,xu=1,Eu=3,ia=9,Cu="0A",Pu=/^socket:\[(\d+)\]$/,Qn={readDirectory:(e)=>fu(e),readLink:(e)=>hu(e),readTextFile:(e)=>mu(e,"utf8"),realPath:(e)=>gu(e)};function aa(e,l){return l===e||l.startsWith(`${e}${bu}`)}function Ou(e,l){return yu(e,l)||"."}async function la(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 ca(e,l){try{let p=(await l.readTextFile(`${ct}/${e}/comm`)).slice(0,oa).split(`
37
- `,1)[0]?.trim();if(p)return p}catch{}try{let p=(await l.readTextFile(`${ct}/${e}/cmdline`)).slice(0,oa).split("\x00",1)[0]?.trim();return p?_u(p):null}catch{return null}}async function ua(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 da(e,l=Qn){let c=[];for(let p of await la(l)){if(c.length>=wu)break;let m=await ua(p,l);if(!m||!aa(e,m))continue;c.push({pid:p,command:await ca(p,l),cwd:Ou(e,m)})}return{processes:c}}function sa(e){let l=[];for(let c=0;c<8;c+=2)l.unshift(Number.parseInt(e.slice(c,c+2),16));return l}function Iu(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 Au(e,l){if(/^[0-9A-Fa-f]{8}$/.test(e)){let c=sa(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(...sa(e.slice(p*8,p*8+8)));if(c.every((p)=>p===0))return`*:${l}`;return`[${Iu(c)}]:${l}`}return null}function Lu(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<=ia)continue;if(m[Eu]?.toUpperCase()!==Cu)continue;let f=m[xu]??"",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=Au(f.slice(0,h),y),w=m[ia];if(!S||!w||!/^[0-9]+$/.test(w))continue;c.push({inode:w,port:y,address:S})}return c}async function ku(e){let l=[];for(let c of["tcp","tcp6"]){if(l.length>=na)break;let p;try{p=await e.readTextFile(`${ct}/net/${c}`)}catch{continue}l.push(...Lu(p,na-l.length))}return l}async function Tu(e,l){let c=new Map;if(e.size===0)return c;for(let p of await la(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,Ru)){let h;try{h=await l.readLink(`${ct}/${p}/fd/${f}`)}catch{continue}let y=h.match(Pu)?.[1];if(!y||!e.has(y)||c.has(y))continue;c.set(y,p)}}return c}async function pa(e,l=Qn){let c=await ku(l),p=await Tu(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,Su),h=await Promise.all(f.map(async(_)=>[_,await ua(_,l)])),y=new Map(h),S=m.filter((_)=>{let v=y.get(_.pid);return Boolean(v&&aa(e,v))}),w=new Map(await Promise.all([...new Set(S.map((_)=>_.pid))].map(async(_)=>[_,await ca(_,l)])));return{ports:S.slice(0,vu).map((_)=>({pid:_.pid,command:w.get(_.pid)??null,address:_.address}))}}import{posix as lo}from"path";var jr=200,Du=250,Nu=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 so(e,l){return l===e||l.startsWith(e==="/"?e:`${e}/`)}var ma="/System/Volumes/Data",Mu=["/tmp","/var","/etc"];function co(e){let l=lo.normalize(e);if(l.startsWith(`${ma}/`))l=l.slice(ma.length);return Mu.find((p)=>l===p||l.startsWith(`${p}/`))?`/private${l}`:l}function fa(e){return e&&lo.isAbsolute(e)?co(e):null}async function ha(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:fa(f.names[0])})}return c}async function ga(e,l){let c=co(e),p=(await qr(l,["-d","cwd","-Fpn"])).filter((f)=>{let h=fa(f.names[0]);return h!==null&&so(c,h)}).map((f)=>f.pid).slice(0,Du),m=await ha(l,p);return{processes:p.flatMap((f)=>{let h=m.get(f);return h?.cwd&&so(c,h.cwd)?[{pid:f,command:h.command,cwd:lo.relative(c,h.cwd)||"."}]:[]})}}async function _a(e,l){let c=co(e),p=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],m=await qr(l,p),f=await ha(l,m.map((w)=>w.pid)),h=m.map((w)=>w.pid).filter((w)=>{let _=f.get(w)?.cwd;return Boolean(_&&so(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 C of v.names)if(y.has(`${v.pid} ${C}`))S.push({pid:v.pid,command:v.command,address:C})}return{ports:S.slice(0,Nu)}}import{join as Yu}from"path";import{spawn as ju}from"child_process";import{randomUUID as qu}from"crypto";import{chmodSync as wa,lstatSync as Sa,mkdirSync as Wu,readdirSync as Vu,statSync as zu,unlinkSync as Gu}from"fs";import{join as fo}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 ya 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 ya;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 Fu=["organizationId","userId","sessionId","runId"],Uu=[...Fu,"prUrl","headSha","skillDigest","evidenceKind"],ah=[...Uu,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var Hu={"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 ba(e){return Hu[e].directory}var va=10485760;function Ra(e={}){let l=e.directory??ba("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");Wu(l,{recursive:!0,mode:457});let f=Sa(l);if(!f.isDirectory()||f.isSymbolicLink()||f.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");wa(l,457);let h=Vu(l).filter((N)=>/^[a-f0-9-]{36}\.webm$/.test(N)).map((N)=>({name:N,time:zu(fo(l,N)).mtimeMs})).sort((N,L)=>L.time-N.time);for(let N of h.slice(9))Gu(fo(l,N.name));let y=fo(l,`${qu()}.webm`),S=["-f","x11grab","-framerate","12","-i",e.display??":99"],w=(e.spawn??ju)(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(va),"-progress","pipe:1",y],{stdio:["ignore","pipe","ignore"],...e.env?{env:e.env}:{}}),_,v,C=!1,I=new Promise((N,L)=>{_=N,v=L});w.stdout.on("data",(N)=>{if(/frame=\s*[1-9]/.test(String(N)))C=!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=Sa(y);if(!C||!F.isFile()||F.isSymbolicLink()||F.uid!==process.getuid?.()||F.size<128||F.size>va+65536)throw Error();wa(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 I}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 xa(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=Yu(e.runtimeDirectory,"recordings"),f=null;return{async start(h){let y=await(l.desktop??qe)();return f??=Ra({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 Vo}from"child_process";import{createHash as fd,randomUUID as hd}from"crypto";import{existsSync as je,mkdirSync as Bo,mkdtempSync as Go,readdirSync as Qr,readFileSync as Yo,renameSync as gd,rmSync as ir,statSync as Kr,writeFileSync as _d}from"fs";import{homedir as Xo,tmpdir as Va}from"os";import{basename as za,dirname as Fo,join as J,relative as Ga,resolve as Uo,sep as Ya}from"path";var Oe=t().min(1).max(200),Ue=o().finite().min(0).max(1e4),Vr=t().min(1).max(4096).refine((e)=>!e.includes("\x00")),Ea=t().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),Ro=i({id:t().min(1).max(500).optional(),label:t().min(1).max(500).optional()}).strict(),Co=["home","lock","side_button","siri","apple_pay"],Ku=s(["tree","screenshot","both","none"]),Xu=i({...Ro.shape,gone:d().optional()}).strict().refine((e)=>Boolean(e.id||e.label),"wait_for needs an id or label"),et={observe:Ku.optional(),wait_for:Xu.optional(),timeout:o().min(0).max(20).optional()},ho=g("action",[i({action:n("tap"),x:Ue.optional(),y:Ue.optional(),...Ro.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"),i({action:n("swipe"),x:Ue,y:Ue,x2:Ue,y2:Ue,duration:o().min(0.05).max(5).optional()}).strict(),i({action:n("type"),text:t().min(1).max(4000)}).strict(),i({action:n("button"),name:s(Co)}).strict(),i({action:n("sleep"),seconds:o().min(0).max(10)}).strict()]),Po=g("action",[i({action:n("devices")}).strict(),i({action:n("boot"),device:Oe}).strict(),i({action:n("shutdown"),device:Oe}).strict(),i({action:n("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(),i({action:n("run"),path:Vr.optional(),scheme:t().min(1).max(200).optional(),configuration:t().min(1).max(100).optional(),device:Oe.optional(),steps:u(Ko(()=>ho)).max(30).optional(),...et}).strict(),i({action:n("build_status"),build_id:t().regex(/^build-[0-9a-z-]{4,64}$/),device:Oe.optional(),wait:d().optional()}).strict(),i({action:n("launch"),device:Oe.optional(),app_path:Vr.optional(),bundle_id:Ea.optional(),steps:u(Ko(()=>ho)).max(30).optional(),...et}).strict().refine((e)=>Boolean(e.app_path)!==Boolean(e.bundle_id),"pass exactly one of app_path or bundle_id"),i({action:n("terminate"),device:Oe.optional(),bundle_id:Ea}).strict(),i({action:n("logs"),device:Oe.optional(),after:o().int().min(0).optional()}).strict(),i({action:n("screenshot"),device:Oe.optional(),scale:W([n(1),n(2)]).optional(),save_path:Vr.optional()}).strict(),i({action:n("chrome"),device:Oe.optional()}).strict(),i({action:n("inspect"),device:Oe.optional()}).strict(),i({action:n("tap"),device:Oe.optional(),x:Ue.optional(),y:Ue.optional(),...Ro.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"),i({action:n("swipe"),device:Oe.optional(),x:Ue,y:Ue,x2:Ue,y2:Ue,duration:o().min(0.05).max(5).optional(),...et}).strict(),i({action:n("type"),device:Oe.optional(),text:t().min(1).max(4000),...et}).strict(),i({action:n("button"),device:Oe.optional(),name:s(Co),...et}).strict(),i({action:n("open_url"),device:Oe.optional(),url:t().min(1).max(4000),...et}).strict(),i({action:n("steps"),device:Oe.optional(),steps:u(ho).min(1).max(30),...et}).strict(),i({action:n("appearance"),device:Oe.optional(),mode:s(["light","dark"])}).strict()]),Ca=i({udid:t(),name:t(),runtime:t(),state:s(["booted","shutdown","booting","shutting_down"]),kind:s(["iphone","ipad","other"])}).strict(),Ch=i({text:t(),error:t().optional(),device:Ca.optional(),devices:u(Ca).optional(),image:i({mime:n("image/jpeg"),data:t(),width:o(),height:o()}).strict().optional(),build:i({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:i({lines:u(t()),next:o()}).strict().optional(),screen:t().optional(),chrome:i({identifier:t(),screen:i({width:o(),height:o()}).strict(),inset:i({top:o(),left:o(),bottom:o(),right:o()}).strict(),padding:i({top:o(),left:o(),bottom:o(),right:o()}).strict(),screen_mask:t().optional(),pieces:ee(s(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),i({image:t(),width:o(),height:o()}).strict()),buttons:u(i({name:t(),image:t(),x:o(),y:o(),width:o(),height:o()}).strict())}).strict().optional()}).strict();var Ph=i({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:[...Co],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."}},Oa=Po.options.map((e)=>e.shape).filter((e)=>e.action.value!=="chrome"),Ju={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},Pa=new Set;function Zu(e,l){let{description:c,...p}=e==="steps"&&l==="steps"?{...zr.steps,minItems:1}:zr[e];if(c===void 0||Pa.has(e))return p;return Pa.add(e),{...p,description:c}}var Qu=Oa.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(Ju[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,Zu(f,l)])]),required:["action",...p,...m.required],additionalProperties:!1}))}),ed={type:"object",properties:{action:{type:"string",enum:Oa.map((e)=>e.action.value)},...zr},required:["action"],additionalProperties:!1},Oh={...ed,anyOf:Qu};import{spawn as Lo}from"child_process";import{createHash as rd}from"crypto";import{existsSync as Io,mkdirSync as Gr,mkdtempSync as nd,readdirSync as Ia,readFileSync as Aa,renameSync as od,rmSync as La,symlinkSync as Ao,writeFileSync as nr}from"fs";import{homedir as id}from"os";import{dirname as Na,join as re}from"path";import{createInterface as sd}from"readline";var Oo=`// Reason's simulator host: one warm process per booted iOS Simulator.
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{}},I=!1,M,N=()=>{C("SIGTERM"),M??=setTimeout(()=>C("SIGKILL"),Vc)},A=setTimeout(()=>{I=!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(A),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=I?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=[Z,void 0].map((m)=>Jc(O({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 ai,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 X,tmpdir as vp}from"os";import{dirname as pr,isAbsolute as Rp,join as Rl,relative as ci,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 lo}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 ao(e,l){return l===e||l.startsWith(e==="/"?e:`${e}/`)}var ha="/System/Volumes/Data",Bu=["/tmp","/var","/etc"];function uo(e){let l=lo.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&&lo.isAbsolute(e)?uo(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=uo(e),p=(await qr(l,["-d","cwd","-Fpn"])).filter((f)=>{let h=ga(f.names[0]);return h!==null&&ao(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&&ao(c,h.cwd)?[{pid:f,command:h.command,cwd:lo.relative(c,h.cwd)||"."}]:[]})}}async function ba(e,l){let c=uo(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(_&&ao(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 fo}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(fo(l,N)).mtimeMs})).sort((N,A)=>A.time-N.time);for(let N of h.slice(9))Ku(fo(l,N.name));let y=fo(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,A)=>{_=N,v=A});w.stdout.on("data",(N)=>{if(/frame=\s*[1-9]/.test(String(N)))R=!0,_()});let I=new Promise((N,A)=>{w.once("error",()=>{v(Error("cloud_browser_recording_unavailable")),A(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")),A(Error("cloud_browser_recording_failed"))}})});I.catch(()=>{});let M=setTimeout(()=>w.kill("SIGKILL"),(Number(m)+5)*1000);I.finally(()=>clearTimeout(M)).catch(()=>{}),c={done:I,stop:()=>(w.kill("SIGINT"),I)};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 Ho,mkdtempSync as Jo,readdirSync as Qr,readFileSync as Zo,renameSync as yd,rmSync as ir,statSync as Kr,writeFileSync as bd}from"fs";import{homedir as Qo,tmpdir as Ga}from"os";import{basename as Ya,dirname as jo,join as J,relative as Ka,resolve as qo,sep as Xa}from"path";var Oe=t().min(1).max(200),Ue=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}$/),Ro=i({id:t().min(1).max(500).optional(),label:t().min(1).max(500).optional()}).strict(),Oo=["home","lock","side_button","siri","apple_pay"],Ju=s(["tree","screenshot","both","none"]),Zu=i({...Ro.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()},go=g("action",[i({action:n("tap"),x:Ue.optional(),y:Ue.optional(),...Ro.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"),i({action:n("swipe"),x:Ue,y:Ue,x2:Ue,y2:Ue,duration:o().min(0.05).max(5).optional()}).strict(),i({action:n("type"),text:t().min(1).max(4000)}).strict(),i({action:n("button"),name:s(Oo)}).strict(),i({action:n("sleep"),seconds:o().min(0).max(10)}).strict()]),Io=g("action",[i({action:n("devices")}).strict(),i({action:n("boot"),device:Oe}).strict(),i({action:n("shutdown"),device:Oe}).strict(),i({action:n("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(),i({action:n("run"),path:Vr.optional(),scheme:t().min(1).max(200).optional(),configuration:t().min(1).max(100).optional(),device:Oe.optional(),steps:u(Xo(()=>go)).max(30).optional(),...et}).strict(),i({action:n("build_status"),build_id:t().regex(/^build-[0-9a-z-]{4,64}$/),device:Oe.optional(),wait:d().optional()}).strict(),i({action:n("launch"),device:Oe.optional(),app_path:Vr.optional(),bundle_id:Pa.optional(),steps:u(Xo(()=>go)).max(30).optional(),...et}).strict().refine((e)=>Boolean(e.app_path)!==Boolean(e.bundle_id),"pass exactly one of app_path or bundle_id"),i({action:n("terminate"),device:Oe.optional(),bundle_id:Pa}).strict(),i({action:n("logs"),device:Oe.optional(),after:o().int().min(0).optional()}).strict(),i({action:n("screenshot"),device:Oe.optional(),scale:W([n(1),n(2)]).optional(),save_path:Vr.optional()}).strict(),i({action:n("chrome"),device:Oe.optional()}).strict(),i({action:n("inspect"),device:Oe.optional()}).strict(),i({action:n("tap"),device:Oe.optional(),x:Ue.optional(),y:Ue.optional(),...Ro.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"),i({action:n("swipe"),device:Oe.optional(),x:Ue,y:Ue,x2:Ue,y2:Ue,duration:o().min(0.05).max(5).optional(),...et}).strict(),i({action:n("type"),device:Oe.optional(),text:t().min(1).max(4000),...et}).strict(),i({action:n("button"),device:Oe.optional(),name:s(Oo),...et}).strict(),i({action:n("open_url"),device:Oe.optional(),url:t().min(1).max(4000),...et}).strict(),i({action:n("steps"),device:Oe.optional(),steps:u(go).min(1).max(30),...et}).strict(),i({action:n("appearance"),device:Oe.optional(),mode:s(["light","dark"])}).strict()]),Oa=i({udid:t(),name:t(),runtime:t(),state:s(["booted","shutdown","booting","shutting_down"]),kind:s(["iphone","ipad","other"])}).strict(),Oh=i({text:t(),error:t().optional(),device:Oa.optional(),devices:u(Oa).optional(),image:i({mime:n("image/jpeg"),data:t(),width:o(),height:o()}).strict().optional(),build:i({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:i({lines:u(t()),next:o()}).strict().optional(),screen:t().optional(),chrome:i({identifier:t(),screen:i({width:o(),height:o()}).strict(),inset:i({top:o(),left:o(),bottom:o(),right:o()}).strict(),padding:i({top:o(),left:o(),bottom:o(),right:o()}).strict(),screen_mask:t().optional(),pieces:ee(s(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),i({image:t(),width:o(),height:o()}).strict()),buttons:u(i({name:t(),image:t(),x:o(),y:o(),width:o(),height:o()}).strict())}).strict().optional()}).strict();var Ih=i({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:[...Oo],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=Io.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 No}from"child_process";import{createHash as od}from"crypto";import{existsSync as To,mkdirSync as Gr,mkdtempSync as id,readdirSync as La,readFileSync as ka,renameSync as sd,rmSync as Ta,symlinkSync as Do,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 Lo=`// Reason's simulator host: one warm process per booted iOS Simulator.
39
39
  //
40
40
  // Built on the Mac on first use (cli/simulator-host.ts) against the MIT
41
41
  // FBSimulatorControl frameworks that the pinned AXe ships, so loading
@@ -494,33 +494,33 @@ case "stream":
494
494
  default:
495
495
  fail("usage: simulator-host serve|stream <udid> ...")
496
496
  }
497
- `;var ka=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",ad=180000,ld=15000,cd=30000,ud=600000,dd=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map((e)=>`@interface ${e} : NSObject
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
498
  @end
499
- `).join("");function Ta(e,l,c){return new Promise((p)=>{let m=Lo(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 Da=new Map;function To(e){let l=re(Na(e),"Frameworks"),c=Da.get(l);if(!c)Da.set(l,c=pd(l));return c}async function pd(e){if(process.platform!=="darwin"||!Io(re(e,"FBSimulatorControl.framework")))return null;let l=await Ta("xcrun",["swiftc","--version"],30000);if(l.code!==0)return null;let c=rd("sha256").update(Oo).update(l.output).update(e).digest("hex").slice(0,16),p=re(id(),".local","share","reason","simulator","host"),m=re(p,c,"simulator-host");if(Io(m))return m;Gr(p,{recursive:!0,mode:448});let f=nd(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 Ia(e))if(M!=="FBSimulatorControl.framework")Ao(re(e,M),re(h,M));let w=re(e,"FBSimulatorControl.framework");Ao(re(w,"FBSimulatorControl"),re(y,"FBSimulatorControl")),Ao(re(w,"Headers"),re(y,"Headers")),nr(re(y,"Modules","module.modulemap"),Aa(re(w,"Modules","module.modulemap")));let _=Aa(re(w,"Modules","FBSimulatorControl.swiftmodule",`${ka}.swiftinterface`),"utf8");nr(re(S,`${ka}.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 {
499
+ `).join("");function Na(e,l,c){return new Promise((p)=>{let m=No(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 Mo(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"||!To(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(Lo).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(To(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")Do(re(e,M),re(h,M));let w=re(e,"FBSimulatorControl.framework");Do(re(w,"FBSimulatorControl"),re(y,"FBSimulatorControl")),Do(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
500
  header "CoreSimulator.h"
501
501
  export *
502
502
  }
503
503
  `),nr(re(v,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
504
- ${dd}`);let C=re(f,"main.swift");nr(C,Oo);let I=re(f,"simulator-host"),A=await Ta("xcrun",["swiftc","-O","-F",h,"-I",re(f,"include"),"-module-cache-path",re(f,"cache"),"-Xlinker","-rpath","-Xlinker",e,C,"-o",I],ad);if(A.code!==0||!Io(I))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
505
- ${A.output.slice(-2000)}
506
- `),null;Gr(Na(m),{recursive:!0}),od(I,m);for(let M of Ia(p))if(M!==c&&!M.startsWith(".staging-"))La(re(p,M),{recursive:!0,force:!0});return m}catch{return null}finally{La(f,{recursive:!0,force:!0})}}class or extends Error{}class Rt extends Error{}class Ma{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor(e,l){this.child=e;this.onGone=l;sd({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()},cd);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(),ud),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:md(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 md(e,l){let c=await To(e);if(!c)return null;let p=Lo(c,["serve",l],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((h)=>{let y=setTimeout(()=>h(!1),ld);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 Ma(p,()=>{let h=bt.get(l);if(h&&(h.host===f||h.host===void 0))bt.delete(l)});return f}function $a(e,l,c,p,m){return Lo(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"},yd=50000,bd=112640,wd=174080,Do=2,Sd=60000,vd=2000,Rd=300,xd=40,Ed=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function It(e,l,c={}){return new Promise((p,m)=>{let f=Vo(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??yd);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 It(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 No=null;function pt(){return J(Xo(),".local","share","reason","simulator","axe")}function Jo(){let e=J(pt(),Ct.version,"axe");if(je(e))return Promise.resolve(e);return No??=(async()=>{Bo(pt(),{recursive:!0,mode:448});let l=Go(J(pt(),".staging-"));try{let c=J(l,"axe.tgz");await go(Ct.url,Ct.sha256,c);let p=J(l,"tree");if(Bo(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}),gd(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}),No=null}})(),No}var Ka=Jo;async function Xa(e){let l=await Jo().catch(()=>null);return l?Yr(l,e.udid).catch(()=>null):null}async function Xr(e,l,c){let p=await Jo().catch(()=>te("simulator_axe_missing","AXe could not be installed on this Mac.")),m=await It(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 Cd(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 Pd(e){switch(e){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function Zo(){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)Ho.set(f.udid,f.deviceTypeIdentifier);c.push({udid:f.udid,name:f.name,runtime:Cd(p),state:Pd(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 Ho=new Map,jo=null;async function Ae(e,l){let c=await Zo(),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===jo)??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 jo=p.udid,p}function ce(e){return`${e.name} (${e.runtime})`}async function Od(e){if(e.state!=="booted"){let l=await It("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 jo=e.udid,{...e,state:"booted"}}function Qo(e,l){let c=Uo(e,l),p=Ga(e,c);if(p.startsWith("..")||p.startsWith(Ya)||Uo(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 Ba=4,Id=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function Ad(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>=Ba)return;for(let h of f.sort()){if(h.startsWith(".")||Id.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 ${Ba} folders of ${e}; pass path.`);return te("simulator_project_not_found",`${e} holds several Xcode projects; pass path as one of: ${l.map((p)=>Ga(e,p)||".").join(", ")}.`)}var Ot=new Map;async function Ld(e){if(e.endsWith(".xcworkspace"))return{flag:"-workspace",path:e,dir:Fo(e)};if(e.endsWith(".xcodeproj"))return{flag:"-project",path:e,dir:Fo(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 Ja(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 kd(e){let l=(await Ja(e))[0];if(!l)te("simulator_build_no_scheme",`${e.path} has no schemes; pass scheme.`);return l}function Td(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 Dd(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 Ja(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 el(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 Fa(e,l){let c=e.path?Qo(l,e.path):Ad(l),p=await Ld(c),m=e.scheme??await kd(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=fd("sha256").update(p.path).digest("hex").slice(0,16),w=J(Xo(),"Library","Caches","reason","simulator-builds",S),_={id:`build-${hd().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:J(w,"Build","Products"),configuration:f};Ot.set(_.id,_);for(let[A,M]of Ot)if(Ot.size>20&&M.status!=="running")Ot.delete(A);let v=Vo("xcodebuild",[p.flag,p.path,"-scheme",m,"-configuration",f,"-destination",y,"-derivedDataPath",w,"-skipMacroValidation","build"],{cwd:p.dir,stdio:["ignore","pipe","pipe"]}),C="",I=(A)=>{let M=(C+A.toString("utf8")).split(`
509
- `);if(C=M.pop()??"",_.log.push(...M),_.log.length>5000)_.log.splice(0,_.log.length-5000)};return v.stdout.on("data",I),v.stderr.on("data",I),v.on("error",(A)=>{_.log.push(`error: ${A.message}`),_.status="failed",_.ended=Date.now()}),v.on("close",(A)=>{if(C)_.log.push(C);Dd(_,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:Za(_)}}function Za(e){return{id:e.id,status:e.status,errors:Td(e.log),log_tail:e.log.slice(-xd).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 Nd=45000,Md=30000;async function Mo(e,l=Nd){let c=Date.now()+l;while(Ot.get(e)?.status==="running"&&Date.now()<c)await Bun.sleep(500);let p=Qa(e);return p.build?.status==="running"?{...p,text:`${p.text} Still running: call build_status with wait again.`}:p}function Qa(e){let l=Ot.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=Za(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 el(e){return(await xe("plutil",["-extract","CFBundleIdentifier","raw","-o","-",J(e,"Info.plist")],"Reading the bundle id")).trim()}var rt=new Map;function $d(e,l){rt.get(e.udid)?.stop();let c=Vo("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-vd;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 Bd(e,l){let c=await Ae(e.device,{booted:!0}),p=e.bundle_id;if(e.app_path){let f=Fd(l,e.app_path);await xe("xcrun",["simctl","install",c.udid,f],`Installing ${za(f)}`),p=await el(f)}if(e.bundle_id){if((await It("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 $d(c,p);if(m===null){let f=rt.get(c.udid)?.lines.slice(-20).join(`
504
+ ${md}`);let R=re(f,"main.swift");nr(R,Lo);let C=re(f,"simulator-host"),I=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(I.code!==0||!To(C))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
505
+ ${I.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 Mo(e);if(!c)return null;let p=No(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 No(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,$o=2,Rd=60000,xd=2000,Ed=300,Cd=40,Pd=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function It(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 It(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 Bo=null;function pt(){return J(Qo(),".local","share","reason","simulator","axe")}function ei(){let e=J(pt(),Ct.version,"axe");if(je(e))return Promise.resolve(e);return Bo??=(async()=>{Ho(pt(),{recursive:!0,mode:448});let l=Jo(J(pt(),".staging-"));try{let c=J(l,"axe.tgz");await _o(Ct.url,Ct.sha256,c);let p=J(l,"tree");if(Ho(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}),Bo=null}})(),Bo}var Ja=ei;async function Za(e){let l=await ei().catch(()=>null);return l?Yr(l,e.udid).catch(()=>null):null}async function Xr(e,l,c){let p=await ei().catch(()=>te("simulator_axe_missing","AXe could not be installed on this Mac.")),m=await It(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 ti(){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)Wo.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 Wo=new Map,zo=null;async function Ae(e,l){let c=await ti(),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 It("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 ri(e,l){let c=qo(e,l),p=Ka(e,c);if(p.startsWith("..")||p.startsWith(Xa)||qo(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 Ot=new Map;async function Td(e){if(e.endsWith(".xcworkspace"))return{flag:"-workspace",path:e,dir:jo(e)};if(e.endsWith(".xcodeproj"))return{flag:"-project",path:e,dir:jo(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?ri(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(Qo(),"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};Ot.set(_.id,_);for(let[I,M]of Ot)if(Ot.size>20&&M.status!=="running")Ot.delete(I);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=(I)=>{let M=(R+I.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",(I)=>{_.log.push(`error: ${I.message}`),_.status="failed",_.ended=Date.now()}),v.on("close",(I)=>{if(R)_.log.push(R);Md(_,I??-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 Fo(e,l=$d){let c=Date.now()+l;while(Ot.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=Ot.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 It("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
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 Fd(e,l){let c=Uo(l),p=J(Xo(),"Library","Caches","reason","simulator-builds")+Ya;return c.startsWith(p)&&c.endsWith(".app")?c:Qo(e,c)}function Ud(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-Rd),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 Ua(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 Ha(e,l){if(e.kind==="ipad")return 2;return l===750||l===828||l===640?2:3}async function ei(e,l=1,c){let p=Go(J(Va(),"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){Bo(Fo(c),{recursive:!0});let I=await xe("sips",["-g","pixelWidth","-g","pixelHeight",m],"Reading the screenshot size"),A=Number(I.match(/pixelWidth: (\d+)/)?.[1]),M=Number(I.match(/pixelHeight: (\d+)/)?.[1]),N=2/Ha(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=Ha(e,h),w=Math.round(h/S),_=Math.round(y/S);Jr.set(e.udid,{width:w,height:_});let v=Buffer.alloc(0),C=l===2?wd:bd;for(let I of[70,50,35]){let A=J(p,`screen-${I}.jpg`);if(await xe("sips",["-z",String(_*l),String(w*l),"-s","format","jpeg","-s","formatOptions",String(I),m,"--out",A],"Encoding the screenshot"),v=Yo(A),v.byteLength<=C)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 Hd(e){let l=await Xa(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 Hd(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 C=Boolean(S||_||w||!["Group","Other"].includes(y));if(C){let I=`${" ".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(I);let A=y==="Image"&&!_,M=(y==="StaticText"||y==="Image")&&!_&&S!==""&&h.includes(S);if(!A&&!M)c.compact.push(I)}for(let I of m.children??[])p(I,C?f+1:f,S||h)};for(let m of l)p(m,0);return c}function tl(e,l,c=!1){let p=(c?e.compact:e.lines).join(`
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=qo(l),p=J(Qo(),"Library","Caches","reason","simulator-builds")+Xa;return c.startsWith(p)&&c.endsWith(".app")?c:ri(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 ii(e,l=1,c){let p=Jo(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){Ho(jo(c),{recursive:!0});let C=await xe("sips",["-g","pixelWidth","-g","pixelHeight",m],"Reading the screenshot size"),I=Number(C.match(/pixelWidth: (\d+)/)?.[1]),M=Number(C.match(/pixelHeight: (\d+)/)?.[1]),N=2/qa(e,I);await xe("sips",["-z",String(Math.round(M*N)),String(Math.round(I*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 I=J(p,`screen-${C}.jpg`);if(await xe("sips",["-z",String(_*l),String(w*l),"-s","format","jpeg","-s","formatOptions",String(C),m,"--out",I],"Encoding the screenshot"),v=Zo(I),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 I=y==="Image"&&!_,M=(y==="StaticText"||y==="Image")&&!_&&S!==""&&h.includes(S);if(!I&&!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
515
  `);return p.length>l?`${p.slice(0,l)}
516
- \u2026 (truncated)`:p}async function jd(e){let l=await Zr(e);return{text:`Accessibility tree of ${ce(e)} (frames in points; tap by id or label):
517
- ${tl(l,Sd)}`,device:e}}var qd=450,Wd=1e4;function Vd(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),Vd(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(qd);let h={...c,text:`${c.text}${f}`};if(p==="tree"||p==="both")m??=await Zr(e),h.screen=tl(m,Wd,!0),h.text+=`
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
518
  Screen now:
519
- ${h.screen}`;if(p==="screenshot"||p==="both"){let y=await ei(e);h.image=y.image}return h}function ja(e){return`'${e.replace(/'/g,"'\\''")}'`}function zd(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 ${ja(e.id)}`:`tap --label ${ja(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 rl=0.35,Gd=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function Yd(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)=>Gd.has(w.role)),S=(y.length?y:h)[0];return S?p(S):null}async function Kd(e,l,c,p,m){let f=Date.now()+c*1000;for(;;){let h=Yd(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]
519
+ ${h.screen}`;if(p==="screenshot"||p==="both"){let y=await ii(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
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 Xa(e);if(!p)return qa(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 Kd(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 qa(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(rl*1000)}return`Ran ${l.length} step(s) on ${ce(e)}.`}async function qa(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,C)=>{let I=m[Number(C)-1];return I?`Step ${I} 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(zd(w)),f+=1,m.push(S+1);let _=l[S+1];if(w.action!=="sleep"&&_&&_.action!=="sleep")p.push(`sleep ${rl}`),m.push(S+1)}return await y(),`Ran ${l.length} step(s) on ${ce(e)}.`}var Xd=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],Wa=new Map,Jd=`ObjC.import("AppKit");
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
524
  function run(argv) {
525
525
  const [input, output, width, height] = argv;
526
526
  const w = Number(width), h = Number(height);
@@ -532,8 +532,8 @@ function run(argv) {
532
532
  image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, $.NSCompositingOperationCopy, 1);
533
533
  $.NSGraphicsContext.restoreGraphicsState;
534
534
  rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(output, true);
535
- }`;async function $o(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=Go(J(Va(),"reason-chrome-"));try{let y=J(h,"render.js"),S=J(h,"out.png");if(_d(y,Jd),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 ${za(e)} produced no image.`);return{image:Yo(S).toString("base64"),width:m,height:f}}finally{ir(h,{recursive:!0,force:!0})}}async function Zd(e){if(!Ho.has(e.udid))await Zo();let l=Ho.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 Qd(e){let l=await Zd(e),c=Jr.get(e.udid)??(e.state==="booted"?(await ei(e),Jr.get(e.udid)):void 0);if(!c)te("simulator_not_booted",`${e.name} is not booted.`);let p=Wa.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 $o(h,Do,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(Yo(J(w,"chrome.json"),"utf8")),v={};for(let B of Xd){let F=_.images[B];if(!F)te("simulator_command_failed",`${e.name}'s frame has no ${B} piece.`);v[B]=await $o(J(w,`${F}.pdf`),Do)}let{sizing:C}=_.images,I={top:C.topHeight,left:C.leftWidth,bottom:C.bottomHeight,right:C.rightWidth},A=c.width+I.left+I.right,M=c.height+I.top+I.bottom,N=[];for(let B of _.inputs??[]){let F=J(w,`${B.image}.pdf`);if(!je(F))continue;let H=await $o(F,Do),{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:I,padding:_.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:v,buttons:N,...y?{screen_mask:y.image}:{}};return Wa.set(l,L),{text:`Frame of ${ce(e)}.`,device:e,chrome:L}}var ep=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 nl(e)}catch(l){if(l instanceof r&&ep.has(l.code))return{text:l.message,error:l.code};throw l}}async function nl(e){if(!ar())te("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let l=Po.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 Zo(),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 Od(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 It("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 Fa(c,e.root);return c.wait&&p.build?Mo(p.build.id):p}case"build_status":return c.wait?Mo(c.build_id):Qa(c.build_id);case"run":{let p=await Fa({...c,action:"build"},e.root),m=await Mo(p.build.id,Md);if(m.build?.status!=="succeeded"||!m.build.app_path)return m;let f=await nl({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 Bd(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 It("xcrun",["simctl","terminate",p.udid,c.bundle_id]),{text:`Terminated ${c.bundle_id} on ${ce(p)}.`,device:p}}case"logs":return Ud(await Ae(c.device,{booted:!1}),c.after);case"screenshot":return ei(await Ae(c.device,{booted:!0}),c.scale,c.save_path?Qo(e.root,c.save_path):void 0);case"chrome":return Qd(await Ae(c.device,{booted:!1}));case"inspect":return jd(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)Ua(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 Ua(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(Ed.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 tp,readFileSync as rp,rmSync as np}from"fs";import{tmpdir as op}from"os";import{join as ol}from"path";import{spawn as al}from"child_process";var ip=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,ur=1,sp=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],il=60,ap=8,ll=ar;var sl={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},lp=(()=>{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 cp(e){if(sl[e]!==void 0)return sl[e];return e>=32&&e<=126?lp[String.fromCharCode(e)]??null:null}function cl(e,l){let c=al("xcrun",["simctl","pbcopy",e],{stdio:["pipe","ignore","ignore"]});c.once("error",()=>{}),c.stdin.end(l)}function up(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 sp)if(y&w.bit&&!(c&w.bit))m({op:"swipe",x:f,y:h,x2:f+w.dx*il,y2:h+w.dy*il,duration:0.08});c=y,p={x:f,y:h}},key(f,h){let y=cp(h);if(y!==null)m({op:"key",usage:y,down:f})},clipboard(f){cl(e,f)},close(){if(c&ur)m({op:"touch",phase:"up",...p});c=0}}}function dp(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)>ap)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){cl(e,h)},close(){clearTimeout(m),c=null}}}function pp(e,l,c){return new Promise((p,m)=>{let f=al(e,l,{stdio:"ignore",signal:c});f.once("error",m),f.once("exit",(h)=>p(h??-1))})}async function mp(e,l){let c=tp(ol(op(),"reason-simulator-stream-"));try{let p=ol(c,"screen.png");if(await pp("xcrun",["simctl","io",e,"screenshot","--type=png",p],l)!==0)throw new r("simulator_not_booted","That simulator is not booted.");let m=rp(p).subarray(16,24);return{width:m.readUInt32BE(0),height:m.readUInt32BE(4)}}finally{np(c,{recursive:!0,force:!0})}}async function ul(e,l={}){let{udid:c,...p}=e.payload;if(typeof c!=="string"||!ip.test(c)||!p.video)throw new r("invalid_display_request","Reason simulator stream request is malformed.");let m=await Ka().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 To(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 mp(c,e.signal),stream:y?(v,C,I)=>$a(y,c,Math.min(v,60),I,C):null,input:S?up(c,S):dp(c,e.root)};return await jt({payload:p,signal:e.signal},{...l,video:{desktop:async()=>_,...w?{ffmpeg:()=>w}:{}}})}var vl=131072,Ep=131072,Cp=128,Rl=8192,Li=30000,Mi=15000,Pp=/^[a-z][a-z0-9_]{0,63}$/,es=new Set(["jobs.control","fs.read","fs.write"]),dl=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 pl(e){return e.map(en).join("/")}function ti(e,l){let c=[];for(let p=0;p<e.length;p+=l)c.push(e.slice(p,p+l));return c}var Op=[...ti(ve,4).map((e)=>`/(${e.map(pl).join("|")})(/|$)`),...ti(Ht,4).map((e)=>`/(${e.map(pl).join("|")})$`),...ti([...zt],6).map((e)=>`/(${e.map(en).join("|")})$`),`/${en(".env")}\\.[^/]+$`,`/[^/]+(${qt.map(en).join("|")})$`],si=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),xl=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function El(e){return[e.requiredPermission,...e.additionalPermissions??[]]}function Ip(e){return $t(e)}function ai(){if(X()==="darwin")return Ke("/usr/bin/sandbox-exec");if(X()==="linux"||X()==="win32")return hr();return!1}function ml(){if(X()==="linux")return Ke("/proc");if(X()==="win32")return ye()!==null;if(!ai())return!1;if(X()==="darwin")return Ke("/usr/sbin/lsof");return!1}function qi(){return X()==="darwin"?"/bin/zsh":gn()}function Ri(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Ap(e,l){if(!Ri(e))throw new r("invalid_payload","Operation payload must be an object.");let c=l===nt?kt:Te;if(Buffer.byteLength(JSON.stringify(e),"utf8")>c)throw new r("payload_too_large",`Operation payload exceeds ${c/1024} KB.`);return e}function Tt(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=Rl){let p=Tt(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 Lp(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(X()==="win32")[e,l]=[e.toLowerCase(),l.toLowerCase()];return l===e||l.startsWith(`${e}${Rp}`)}function At(e){if(_o(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 At(l),l}function $i(e,l="."){if(!l||l.includes("\x00")||Sp(l))throw new r("path_outside_root","Paths must be relative to the granted root.");if(X()==="win32"&&l.split(/[\\/]/).some(ln))throw new r("invalid_path","Windows reserves this file name.");let c=vp(e,l);if(!ft(e,c))throw new r("path_outside_root","Path escapes the granted root.");return c}function Lt(e,l=".",c=!1){let p=$i(e,l),m;try{m=Ge(p)}catch(f){if(Il(f))throw Al();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)At(m);return m}function kp(e,l){let c=$i(e,l);if(At(c),Ke(c)){let f=Ge(c);if(!ft(e,f))throw new r("symlink_escape","Write target resolves outside the granted root.");if(ni(c).isSymbolicLink())throw new r("symlink_escape","Writing through a symlink is not allowed.");return At(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 At(m),c}function Cl(e,l){return oi(e,l)||"."}function Tp(e,l=vl){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 Pl(e,l){return{...He({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 Dp(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)}))`]:[],...Op.map((m)=>`(deny file-read* file-write* (regex #"${m}"))`),...yo(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{_=xp(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",I),p({exitCode:M,signal:N,stdout:f,stderr:h,timedOut:S,truncated:y})},C=(M,N)=>{let L=`${M}${String(N)}`,B=Tp(L);return y||=B.truncated,B.value};_.stdout.on("data",(M)=>{f=C(f,M)}),_.stderr.on("data",(M)=>{h=C(h,M)}),_.once("error",m),_.once("exit",v);let I=()=>{try{if(X()==="win32"&&_.pid)Me(_.pid);else _.kill("SIGTERM")}catch{}};c.signal.addEventListener("abort",I,{once:!0});let A=setTimeout(()=>{S=!0,I()},c.timeoutMs)})}var fl=null;function Np(){return fl??=Gi({scrubEnvironment:Pl,spawnCaptured:mn,isProtectedPath:E}),fl}var ts=async(e,l,c)=>{if(X()==="linux"||X()==="win32")return Np()(e,l,c);if(X()!=="darwin"||!Ke("/usr/bin/sandbox-exec"))throw new r("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let p=gp(Sl(wp(),"reason-device-"));try{return await mn("/usr/bin/sandbox-exec",["-p",Dp(c.root,p,c.allowWrite,c.allowProcessInspection===!0),e,...l],{cwd:c.cwd,timeoutMs:c.timeoutMs,signal:c.signal,env:Pl(c.root,p)})}finally{yp(p,{recursive:!0,force:!0})}};function Mp(e){let l=e.args;if(l===void 0)return[];if(!Array.isArray(l)||l.length>Cp)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")>Rl)throw new r("invalid_payload","Command argument is invalid or too large.");return c})}async function Ol(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??Mi,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 Il(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EACCES"||l==="EPERM"}var Al=()=>new r("path_unreadable","The path is not readable.");function $p(e){try{return wl(e,We.O_RDONLY)}catch(l){throw Il(l)?Al():l}}function hl(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):rs(e,l)}function rs(e,l){return e==="fs.read"?Bp(l):Up(l)}async function Bp(e){let l=de(e.root),c=Lt(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,vl),f=Tt(e.payload,"encoding");if(f!==void 0&&f!=="base64")throw new r("invalid_payload","encoding must be base64.");let h=$p(c),y,S;try{y=bl(h).size;let _=Buffer.alloc(Math.max(0,Math.min(m,y-p)));S=_.subarray(0,_.byteLength?_p(h,_,0,_.byteLength,p):0)}finally{yl(h)}let w=f==="base64"||S.includes(0);return{path:Cl(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 Fp(e,l,c=X()){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 Up(e){let l=de(e.root),c=tn(e.payload,"path"),p=Lp(e.payload,"content",Ep),m=Tt(e.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(m))throw new r("invalid_payload","mode must be create, overwrite, or append.");let f=kp(l,c);if(e.payload.create_parents===!0||e.payload.create_directories===!0){hp(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?ni(f):null,S=wl(f,Fp(m,h),384);try{let w=bl(S),_=y??(X()==="win32"?ni(f):null);if(_&&(w.ino!==_.ino||w.dev!==_.dev||X()==="win32"&&!ft(l,Ge(f))))throw new r("symlink_escape","The write target changed between validation and opening.");if(X()==="win32"&&y&&m!=="append")fp(S,0);bp(S,p,null,"utf8")}finally{yl(S)}return{path:Cl(l,f),bytes_written:Buffer.byteLength(p,"utf8"),mode:m}}async function Hp(e){let l=de(e.root),c=tn(e.payload,"command",65536),p=Lt(l,Tt(e.payload,"cwd")??".");if(!_r(p).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let m=gr(e.payload.timeout_ms,Mi,100,Li);return Ol(e,qi(),["-lc",c],{cwd:p,allowWrite:e.root.permissions.write,timeoutMs:m})}async function jp(e){let l=Xi.safeParse(e.payload),c=e.worker;if(!l.success||!e.claimOwner||(c?!c.runtimeDirectory:X()!=="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:Lt(m.anchor,oi(m.anchor,m.boundary)||"."),h=Lt(f,oi(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()+Ji);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:Sl(c.runtimeDirectory,"processes")},_={deniedPorts:mr([e.apiOrigin])},v=wr(),C=br(),I=ge(),A=l.data.egress?Dt(I):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 vs(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:C,expiresAtMs:y,signal:e.signal,emit:S,...I?{jobsUser:{...I,...A!==null?{modelGid:A}:{}}}:{},environment:{...v.variables,HOME:v.home,PATH:v.path,TMPDIR:v.temporaryDirectory,SHELL:C},journals:w,preview:_})}}finally{M?.close()}}async function qp(e){Xn();let l=de(e.root),c=Jn(e.payload.command),p=Lt(l,Tt(e.payload,"cwd")??".");if(!_r(p).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let m=gr(e.payload.timeout_ms,Qs,100,Yn),{ignored:f}=Zn(e.payload.env);return await e.emit("progress",{shell:yt(),shell_flags:[...rr],sandbox:"none",ignored_env:f}),ta({command:c,cwd:p,timeoutMs:m,signal:e.signal,spawn:e.spawnFullControl,requestEnv:e.payload.env})}async function Wp(e){let l=de(e.root),c=Mp(e.payload),p=c[0];if(!p||!xl.has(p)&&!si.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=si.has(p);if(m&&!e.root.permissions.write)throw new r("permission_denied","Mutating Git commands require the write grant.");let f=Lt(l,Tt(e.payload,"cwd")??".");return Ol(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,Mi,100,Li)})}function Ll(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 Vp(e){let l=de(e.root);if(X()==="linux")return da(l);if(X()==="win32")return uo(l);return ga(l,Ll(e,l))}async function zp(e){let l=de(e.root);if(X()==="linux")return pa(l);if(X()==="win32")return po(l);return _a(l,Ll(e,l))}async function Gp(e){let l=e.worker?xa(e.worker):null,c=e.claim.environment;delete e.claim.environment;let p=e.worker&&c&&Bi({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 Yp(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}=Yi(e.payload,e.operationId);return ro({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 gl(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):ns(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 ns(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?Ks(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=$s.safeParse(l.payload);if(!y.success)throw new r("invalid_payload","Invalid Cloud export request.");return Xs({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 At($i(h,f)),_t({direction:e,root:h,path:f,payload:l.payload,signal:l.signal,fetchImpl:l.fetchImpl,beforeCommit:l.beforeCommit})}var kl={"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 zi({payload:e.payload,signal:e.signal,credential:e.customEndpointCredential,emit:(l,c)=>e.emit(l,c,e.signal)})}},"fs.read":{requiredPermission:"read",execute:(e)=>hl("fs.read",e)},"fs.write":{requiredPermission:"write",execute:(e)=>hl("fs.write",e)},"fs.export":{requiredPermission:"read",execute:(e)=>gl(e,"export")},"fs.import":{requiredPermission:"write",execute:(e)=>gl(e,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>X()==="darwin"&&Kn(),execute:jp},"exec.run":{requiredPermission:"execute",available:ai,execute:Hp},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Kn(),execute:qp},"git.run":{requiredPermission:"execute",available:()=>ai()&&Ip("git"),execute:Wp},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:ml,execute:Vp},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:ml,execute:zp},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>X()==="darwin"||Boolean(vn()),execute:Gp},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:jn,execute:Yp},"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)=>Tn({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:ll,execute:(e)=>ul({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)=>no({root:de(e.root),runId:e.runId,payload:e.payload,signal:e.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>X()==="darwin"?Ke("/usr/bin/sandbox-exec"):X()==="linux"||X()==="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 io({root:de(e.root),runId:e.runId,request:l,authority:c,signal:e.signal,leaseUntil:e.claim.lease_until},(p)=>_s(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)=>eo({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)=>to({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)=>Gs(e.payload,e.signal)}};function Kp(e,l){try{let c=ss(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 Xp(e,l){try{let c=Ge(l);return e.some((p)=>p.path===c)?Pr(c,X()):void 0}catch{return}}function Jp(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 Zp(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 is(e,l,c=X()){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 Ds(e,l={}){let c=l.worker?l.worker.handsSlots??1:l.handsSlots===1?1:void 0,p=Boolean(l.worker)||X()==="darwin",m=p?Jp(e,dr()):void 0,f=!l.worker&&X()==="darwin"?Kp(e,dr()):void 0,h=p?Xp(e,dr()):void 0,y=!l.worker&&X()==="darwin"?Zp(e,dr()):void 0,S=p?is(e,dr()):void 0,w=Js.filter((_)=>{if(tr.has(_)&&!l.worker)return!1;if(l.worker&&!Hr(_,l.worker))return!1;let v=kl[_];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((I)=>(!l.worker||_!=="pty.start"||I.permissions.read&&I.permissions.write)&&El(v).every((A)=>I.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:R,...c?{hands_slots:c}:{}}:{},max_payload_bytes:Te,max_result_bytes:Te,operation_constraints:{...w.includes("browser.pr-proof.v1")&&l.productionProof?{"browser.pr-proof.v1":xn.parse(l.productionProof)}:{},...w.includes("exec.run")?{"exec.run":{transport:"shell",shell:qi(),sandbox:X()==="linux"?"linux_sandbox_runtime":X()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:Li}}:{},...w.includes("exec.full")?{"exec.full":ra()}:{},"git.run":{read_only_subcommands:[...xl].sort(),mutating_subcommands:[...si].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:D,protocol_version:P,worker_artifact_sha256:b,worker_entrypoint:R,policy_mode:"full_access",policy_version:1,workspace_base:ue,workspace_layout:Z,...c?{slots:c}:{},browser_state:l.worker?"optional_headless":l.terminalOnlyHands===!0?"disabled_terminal_only":X()==="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:Dr,max_session_ms:Ir,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:Xt,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:Ei,...l.worker?.ownComputer?{[xi]:ki}:{},workspace_base:ue,workspace_layout:Z,browser_state:"optional_headless",desktop:!1,worker_version:D,protocol_version:P,...l.worker?.readiness?.["environment.install"]===!0&&w.includes("environment.install")?{environment_delivery:ii,[li]:ci}:{},...l.worker?{[hi]:pi}:{},...l.worker?{[di]:ui}:{},...l.worker?.handsBrowser?{[yi]:_i}:{},[gi]:mi,[bi]:wi,...me(l.worker?.executionMode==="unsandboxed")?{[Y]:pe}:{},...me(l.worker?.executionMode==="unsandboxed")&&Dt()!==null?{[q]:Re}:{},...me(l.worker?.executionMode==="unsandboxed")&&ge()?{[Si]:vi}:{}}:{},..._==="fs.export"?{cloud_source_version:Mr,source_kinds:["workspace","attachment"],[An]:Ln}:{},..._==="fs.import"?{[An]:Ln}:{},..._===Ki&&Dt()!==null&&me(l.worker?.executionMode==="unsandboxed")?{[Zi]:_n}:{},..._==="tunnel.open"?{carried_jobs:Ci}:{},..._==="jobs.control"?{[Pi]:Ai}:{},..._==="display.stream.v1"&&l.worker?.displayVideo?{[bo]:wo,[vo]:dt.join(","),[So]:Eo,[xo]:ko}:{},..._==="automation.call.v1"&&l.worker?.userChrome?{[St]:!0}:{},..._==="automation.call.v1"&&l.worker?.cloudSessions?{[Ti]:!0}:{}}])):{}}}}function Bi(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 Ns(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(!Bi(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 Ls(e,l,c,p){if(l.capability!=="hands.connect"||c.kind!==fi)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 Qi({operationId:l.operation_id,root:de(S),runId:f,targetGeneration:h,fenceId:y,...p?{signal:p}:{}}),!0}async function Ms(e,l,c){if(l.capability!=="github.local.v1")return _l(e,l,c);try{let p=await _l(e,l,c);if(p.status==="succeeded"||ri(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 _l(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=kl[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")&&Ri(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"&&!Bi(e,m.id,l.run_id,l.payload,l.authority))return{status:"failed",error_code:"environment_unavailable"};if(El(p).some((_)=>!m.permissions[_]))return{status:"failed",error_code:"permission_denied"};let f=0,h=async(_,v,C)=>{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")&&C?{deliverySignal:C}:{}})},y=l.capability==="hands.connect"||l.capability==="display.stream.v1"||l.capability==="simulator.stream.v1"||es.has(l.capability)||l.capability==="pty.start",S,w=async(_,v,C)=>{let I=S;S=void 0,await Promise.all([I,h(_,v,C)])};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,(C)=>h("pr-proof.started.v1",C))}:{},claim:l,worker:c.worker,claimOwner:l.owner,claimAuthority:l.authority,organizationId:e.orgId,deviceId:e.deviceId,apiOrigin:e.apiOrigin,root:m,payload:Ap(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??ts,spawnFullControl:c.spawnFullControl??mn,emit:y?w:h,runHandsRelay:c.runHandsRelay??((C)=>Nt(C,_)),runPtySession:c.runPtySession??Un});if(l.capability==="github.local.v1")zo.parse(v);if(!Ri(v))throw new r("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(v)??"null","utf8")>Te)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&&dl.has(c.signal.reason.code)?c.signal.reason.code:_ instanceof r&&dl.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 C=l.capability==="inference.custom.v1"?_ instanceof r&&Ni(_.code)?_.code:"custom_endpoint_unavailable":l.capability==="github.local.v1"?_ instanceof sr&&ri(l.payload,"failed",_.code)?_.code:"local_github_unavailable":l.capability==="environment.install"?"environment_install_failed":_ instanceof r&&Pp.test(_.code)?_.code:"capability_failed",I=l.capability==="hands.connect"&&_ instanceof Er?oo(_.expiryDiagnostic):null;return await h("completed",{ok:!1,error_code:C,...I?{expiry_diagnostic:I}:{}}),{status:"failed",error_code:C}}}
539
- export{fn,es,qi,mn,ts,rs,ns,is,Ds,Ns,Ls,Ms};
535
+ }`;async function Uo(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=Jo(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:Zo(S).toString("base64"),width:m,height:f}}finally{ir(h,{recursive:!0,force:!0})}}async function ep(e){if(!Wo.has(e.udid))await ti();let l=Wo.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 ii(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 Uo(h,$o,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(Zo(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 Uo(J(w,`${F}.pdf`),$o)}let{sizing:R}=_.images,C={top:R.topHeight,left:R.leftWidth,bottom:R.bottomHeight,right:R.rightWidth},I=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 Uo(F,$o),{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:I+ne,y:Ee(_e,M,H.height)}:B.anchor==="top"?{x:Ee(ne,I,H.width),y:_e-H.height}:{x:Ee(ne,I,H.width),y:M+_e};N.push({name:B.name,image:H.image,...Ze,width:H.width,height:H.height})}let A={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,A),{text:`Frame of ${ce(e)}.`,device:e,chrome:A}}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=Io.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 ti(),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 It("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?Fo(p.build.id):p}case"build_status":return c.wait?Fo(c.build_id):tl(c.build_id);case"run":{let p=await Ha({...c,action:"build"},e.root),m=await Fo(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 It("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 ii(await Ae(c.device,{booted:!0}),c.scale,c.save_path?ri(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 Mo(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,Bi=30000,Fi=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 si(e,l){let c=[];for(let p=0;p<e.length;p+=l)c.push(e.slice(p,p+l));return c}var Ap=[...si(ve,4).map((e)=>`/(${e.map(fl).join("|")})(/|$)`),...si(Ht,4).map((e)=>`/(${e.map(fl).join("|")})$`),...si([...zt],6).map((e)=>`/(${e.map(en).join("|")})$`),`/${en(".env")}\\.[^/]+$`,`/[^/]+(${qt.map(en).join("|")})$`],Oi=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 $t(e)}function Mi(){if(X()==="darwin")return Ke("/usr/bin/sandbox-exec");if(X()==="linux"||X()==="win32")return hr();return!1}function hl(){if(X()==="linux")return Ke("/proc");if(X()==="win32")return ye()!==null;if(!Mi())return!1;if(X()==="darwin")return Ke("/usr/sbin/lsof");return!1}function Wi(){return X()==="darwin"?"/bin/zsh":gn()}function $i(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function kp(e,l){if(!$i(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 Tt(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=Tt(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(X()==="win32")[e,l]=[e.toLowerCase(),l.toLowerCase()];return l===e||l.startsWith(`${e}${Ep}`)}function At(e){if(yo(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 At(l),l}function Ui(e,l="."){if(!l||l.includes("\x00")||Rp(l))throw new r("path_outside_root","Paths must be relative to the granted root.");if(X()==="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 Lt(e,l=".",c=!1){let p=Ui(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)At(m);return m}function Dp(e,l){let c=Ui(e,l);if(At(c),Ke(c)){let f=Ge(c);if(!ft(e,f))throw new r("symlink_escape","Write target resolves outside the granted root.");if(ai(c).isSymbolicLink())throw new r("symlink_escape","Writing through a symlink is not allowed.");return At(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 At(m),c}function Ol(e,l){return ci(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{...He({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}"))`),...wo(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(I),c.signal.removeEventListener("abort",C),p({exitCode:M,signal:N,stdout:f,stderr:h,timedOut:S,truncated:y})},R=(M,N)=>{let A=`${M}${String(N)}`,B=Np(A);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(X()==="win32"&&_.pid)Me(_.pid);else _.kill("SIGTERM")}catch{}};c.signal.addEventListener("abort",C,{once:!0});let I=setTimeout(()=>{S=!0,C()},c.timeoutMs)})}var gl=null;function $p(){return gl??=Ki({scrubEnvironment:Il,spawnCaptured:mn,isProtectedPath:E}),gl}var is=async(e,l,c)=>{if(X()==="linux"||X()==="win32")return $p()(e,l,c);if(X()!=="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??Fi,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=Lt(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=Tt(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=X()){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=Tt(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?ai(f):null,S=vl(f,Hp(m,h),384);try{let w=Sl(S),_=y??(X()==="win32"?ai(f):null);if(_&&(w.ino!==_.ino||w.dev!==_.dev||X()==="win32"&&!ft(l,Ge(f))))throw new r("symlink_escape","The write target changed between validation and opening.");if(X()==="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=Lt(l,Tt(e.payload,"cwd")??".");if(!_r(p).isDirectory())throw new r("invalid_cwd","cwd is not a directory.");let m=gr(e.payload.timeout_ms,Fi,100,Bi);return Al(e,Wi(),["-lc",c],{cwd:p,allowWrite:e.root.permissions.write,timeoutMs:m})}async function Wp(e){let l=Yi.safeParse(e.payload),c=e.worker;if(!l.success||!e.claimOwner||(c?!c.runtimeDirectory:X()!=="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:Lt(m.anchor,ci(m.anchor,m.boundary)||"."),h=Lt(f,ci(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()+Zi);if(!(y>Date.now()))throw new r("process_authority_lost","The preview server lease is unavailable.");let S=(A)=>e.emit("progress",{process:A});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(),I=l.data.egress?Dt(C):null;if(l.data.egress&&(I===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((A)=>`${A}=${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,...I!==null?{modelGid:I}:{}}}:{},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=Lt(l,Tt(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)&&!Oi.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=Oi.has(p);if(m&&!e.root.permissions.write)throw new r("permission_denied","Mutating Git commands require the write grant.");let f=Lt(l,Tt(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,Fi,100,Bi)})}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(X()==="linux")return ma(l);if(X()==="win32")return po(l);return ya(l,Tl(e,l))}async function Yp(e){let l=de(e.root);if(X()==="linux")return fa(l);if(X()==="win32")return ho(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&&Hi({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}=Qi(e.payload,e.operationId);return no({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 At(Ui(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:()=>X()==="darwin"&&Kn(),execute:Wp},"exec.run":{requiredPermission:"execute",available:Mi,execute:qp},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Kn(),execute:Vp},"git.run":{requiredPermission:"execute",available:()=>Mi()&&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:()=>X()==="darwin"||Boolean(vn()),execute:Kp},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:Un,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)=>io({root:de(e.root),runId:e.runId,payload:e.payload,signal:e.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>X()==="darwin"?Ke("/usr/bin/sandbox-exec"):X()==="linux"||X()==="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 oo({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)=>to({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)=>ro({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,X()):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=X()){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 Ms(e,l={}){let c=l.worker?l.worker.handsSlots??1:l.handsSlots===1?1:void 0,p=Boolean(l.worker)||X()==="darwin",m=p?Qp(e,dr()):void 0,f=!l.worker&&X()==="darwin"?Jp(e,dr()):void 0,h=p?Zp(e,dr()):void 0,y=!l.worker&&X()==="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((I)=>C.permissions[I]))});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:Wi(),sandbox:X()==="linux"?"linux_sandbox_runtime":X()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:Bi}}:{},...w.includes("exec.full")?{"exec.full":oa()}:{},"git.run":{read_only_subcommands:[...Cl].sort(),mutating_subcommands:[...Oi].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:D,protocol_version:P,worker_artifact_sha256:b,worker_entrypoint:T,policy_mode:"full_access",policy_version:1,workspace_base:ue,workspace_layout:Z,...c?{slots:c}:{},browser_state:l.worker?"optional_headless":l.terminalOnlyHands===!0?"disabled_terminal_only":X()==="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:Dr,max_session_ms:Ir,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:Xt,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:Z,browser_state:"optional_headless",desktop:!1,worker_version:D,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")?{[Y]:pe}:{},...me(l.worker?.executionMode==="unsandboxed")&&Dt()!==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}:{},..._===Ji&&Dt()!==null&&me(l.worker?.executionMode==="unsandboxed")?{[Xi]:_n}:{},..._==="tunnel.open"?{carried_jobs:Ai}:{},..._==="jobs.control"?{[Ri]:Pi}:{},..._==="display.stream.v1"&&l.worker?.displayVideo?{[vo]:bo,[So]:dt.join(","),[Eo]:xo,[ko]:Co,[Ao]:Po}:{},..._==="automation.call.v1"&&l.worker?.userChrome?{[St]:!0}:{},..._==="automation.call.v1"&&l.worker?.cloudSessions?{[Ti]:!0}:{}}])):{}}}}function Hi(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 $s(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(!Hi(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 eo({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")&&$i(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"&&!Hi(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??Hn});if(l.capability==="github.local.v1")Vo.parse(v);if(!$i(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?so(_.expiryDiagnostic):null;return await h("completed",{ok:!1,error_code:R,...C?{expiry_diagnostic:C}:{}}),{status:"failed",error_code:R}}}
539
+ export{fn,ns,Wi,mn,is,os,ss,as,Ms,$s,Bs,Fs};