@reason-machines/cli-linux-x64 0.2.408 → 0.2.411

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