@reason-machines/cli-linux-arm64-musl 0.2.381 → 0.2.382

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 (111) hide show
  1. package/README.md +3 -1
  2. package/bin/ara +2 -2
  3. package/bin/vm-hands/api-credentials-xppmbg0m.js +2 -0
  4. package/bin/vm-hands/api-xmpbsm6b.js +2 -0
  5. package/bin/vm-hands/{ask-relay-fc0jc3t5.js → ask-relay-zjqyxvxe.js} +3 -3
  6. package/bin/vm-hands/connect-cli-ehxeg8m5.js +2 -0
  7. package/bin/vm-hands/{custom-endpoint-device-zhpake9f.js → custom-endpoint-device-bm94e9r0.js} +1 -1
  8. package/bin/vm-hands/desktop-account-3tnm4z5w.js +2 -0
  9. package/bin/vm-hands/{device-workspace-vbcry9d6.js → device-workspace-0xsj5ykf.js} +1 -1
  10. package/bin/vm-hands/hands-worker-source-azdrrhsz.js +2 -0
  11. package/bin/vm-hands/{index-bbk6a9sk.js → index-7f2kwwen.js} +1 -1
  12. package/bin/vm-hands/{install-receipt-7x81ek76.js → install-receipt-3xyx3rdd.js} +1 -1
  13. package/bin/vm-hands/local-automation-ynx1qr9v.js +2 -0
  14. package/bin/vm-hands/local-capabilities-855ch0dq.js +2 -0
  15. package/bin/vm-hands/local-desktop-users-ajb81vjm.js +2 -0
  16. package/bin/vm-hands/local-display-mac-9h6btvvq.js +2 -0
  17. package/bin/vm-hands/local-display-session-f9ywkbba.js +2 -0
  18. package/bin/vm-hands/local-pty-session-cjas515w.js +2 -0
  19. package/bin/vm-hands/managed-runtime-dars4628.js +2 -0
  20. package/bin/vm-hands/{network-contract-zqvt1v0t.js → network-contract-dsw79qkc.js} +1 -1
  21. package/bin/vm-hands/package-smk3nqjs.js +2 -0
  22. package/bin/vm-hands/permissions-pdmhp2s3.js +2 -0
  23. package/bin/vm-hands/{reason-hands-protocol-8fxjynte.js → reason-hands-protocol-7d7xj1h3.js} +1 -1
  24. package/bin/vm-hands/serve-service-n6xd6323.js +2 -0
  25. package/bin/vm-hands/status-2m75kz1h.js +96 -0
  26. package/bin/vm-hands/version-74zqccyz.js +2 -0
  27. package/bin/vm-hands/vm-hands-entry-lite-06qnb2w1.js +458 -0
  28. package/bin/vm-hands/{vm-hands-entry-lite-7shpbsw8.js → vm-hands-entry-lite-1gxktkpe.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-hgkf1svv.js → vm-hands-entry-lite-23bb8ce4.js} +2 -2
  30. package/bin/vm-hands/vm-hands-entry-lite-245929bs.js +346 -0
  31. package/bin/vm-hands/vm-hands-entry-lite-2e18tm6w.js +245 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-g036gtem.js → vm-hands-entry-lite-2t0vcvd8.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-0asdf4pm.js → vm-hands-entry-lite-2tcjqgfp.js} +3 -3
  34. package/bin/vm-hands/vm-hands-entry-lite-3n3xh0xv.js +540 -0
  35. package/bin/vm-hands/vm-hands-entry-lite-50n6vbfx.js +251 -0
  36. package/bin/vm-hands/{vm-hands-entry-lite-j2q1k9vb.js → vm-hands-entry-lite-51hmj6am.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-zfwg7ehq.js → vm-hands-entry-lite-5n4vsm6b.js} +2 -2
  38. package/bin/vm-hands/vm-hands-entry-lite-8fj07njx.js +3 -0
  39. package/bin/vm-hands/{vm-hands-entry-lite-4q8tsaqv.js → vm-hands-entry-lite-8zawqa9q.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-3hbe4em3.js → vm-hands-entry-lite-9cmfthkq.js} +1 -1
  41. package/bin/vm-hands/{vm-hands-entry-lite-45j8qwsf.js → vm-hands-entry-lite-9w5vs9zv.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-k7wwza46.js → vm-hands-entry-lite-aj1ccphg.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-za55dtte.js → vm-hands-entry-lite-ammr3xbc.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-yjn6sk08.js → vm-hands-entry-lite-ch7y4b1b.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-34e71nbe.js → vm-hands-entry-lite-cwe16c51.js} +174 -16
  46. package/bin/vm-hands/vm-hands-entry-lite-dh5gwmyf.js +3 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-dsdwzasy.js +105 -0
  48. package/bin/vm-hands/{vm-hands-entry-lite-5pm6bhb8.js → vm-hands-entry-lite-e0gdt6r5.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-5kgvss4p.js → vm-hands-entry-lite-e2mjbqmr.js} +2 -2
  50. package/bin/vm-hands/vm-hands-entry-lite-ejm5er3h.js +7 -0
  51. package/bin/vm-hands/{vm-hands-entry-lite-mh0xecf3.js → vm-hands-entry-lite-f02906k8.js} +4 -4
  52. package/bin/vm-hands/vm-hands-entry-lite-f5230h6t.js +67 -0
  53. package/bin/vm-hands/{vm-hands-entry-lite-zh8p7ndn.js → vm-hands-entry-lite-fb5dzy9x.js} +2 -2
  54. package/bin/vm-hands/vm-hands-entry-lite-fyvgav60.js +3 -0
  55. package/bin/vm-hands/vm-hands-entry-lite-g7h6wjqy.js +3 -0
  56. package/bin/vm-hands/vm-hands-entry-lite-h8dbw0c7.js +4 -0
  57. package/bin/vm-hands/{vm-hands-entry-lite-nhtb458c.js → vm-hands-entry-lite-hnsm5t36.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-r6pap1kh.js → vm-hands-entry-lite-ma001vzh.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-anmv8hp7.js → vm-hands-entry-lite-mn64e4pt.js} +286 -104
  60. package/bin/vm-hands/{vm-hands-entry-lite-9cgm6g8t.js → vm-hands-entry-lite-pk3q774c.js} +1 -1
  61. package/bin/vm-hands/vm-hands-entry-lite-qef2ndkd.js +6 -0
  62. package/bin/vm-hands/vm-hands-entry-lite-qnnfvm5r.js +5 -0
  63. package/bin/vm-hands/vm-hands-entry-lite-qwf78yqr.js +11 -0
  64. package/bin/vm-hands/vm-hands-entry-lite-r8qg3wp1.js +3 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-rd0ak4ye.js +4 -0
  66. package/bin/vm-hands/{vm-hands-entry-lite-00qsbphw.js → vm-hands-entry-lite-rpn0frzb.js} +2 -2
  67. package/bin/vm-hands/{vm-hands-entry-lite-g9rvf5qk.js → vm-hands-entry-lite-rtt2w6c6.js} +1 -1
  68. package/bin/vm-hands/vm-hands-entry-lite-sex82vb1.js +3 -0
  69. package/bin/vm-hands/{vm-hands-entry-lite-dgxxsdwb.js → vm-hands-entry-lite-xrthfx3q.js} +2 -2
  70. package/bin/vm-hands/{vm-hands-entry-lite-kxdw4myj.js → vm-hands-entry-lite-y2s2w174.js} +1 -1
  71. package/bin/vm-hands/{vm-hands-entry-lite-hc3p6r9p.js → vm-hands-entry-lite-zjfr0zh8.js} +2 -2
  72. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  73. package/bin/vm-hands/{vm-hands-executor-qssgfea1.js → vm-hands-executor-yx6mxa2p.js} +1 -1
  74. package/bin/vm-hands/vm-hands-op-runner-yt3v3v6w.js +2 -0
  75. package/bin/vm-hands/{vm-hands-runtime-5me6cpmn.js → vm-hands-runtime-ygddqgbs.js} +3 -3
  76. package/bin/vm-hands/worker-sandbox-tgqbmy6b.js +2 -0
  77. package/package.json +1 -1
  78. package/bin/vm-hands/api-af9g18n7.js +0 -2
  79. package/bin/vm-hands/api-credentials-65mrr3tn.js +0 -2
  80. package/bin/vm-hands/connect-cli-j478km3s.js +0 -2
  81. package/bin/vm-hands/desktop-account-5zvgspyw.js +0 -2
  82. package/bin/vm-hands/hands-worker-source-h0b1j53p.js +0 -2
  83. package/bin/vm-hands/local-automation-c86tjeft.js +0 -2
  84. package/bin/vm-hands/local-capabilities-1h99gkt6.js +0 -2
  85. package/bin/vm-hands/local-desktop-users-0hadyvx1.js +0 -2
  86. package/bin/vm-hands/local-display-mac-v1pc7177.js +0 -2
  87. package/bin/vm-hands/local-display-session-tzq0hne8.js +0 -2
  88. package/bin/vm-hands/local-pty-session-hs7rq03x.js +0 -2
  89. package/bin/vm-hands/managed-runtime-5dqaaw1x.js +0 -2
  90. package/bin/vm-hands/package-3cd7cfyv.js +0 -2
  91. package/bin/vm-hands/permissions-vbyqjbyb.js +0 -2
  92. package/bin/vm-hands/serve-service-be739c9s.js +0 -2
  93. package/bin/vm-hands/status-s8ny6men.js +0 -96
  94. package/bin/vm-hands/version-8s4syrp2.js +0 -2
  95. package/bin/vm-hands/vm-hands-entry-lite-1085xsma.js +0 -5
  96. package/bin/vm-hands/vm-hands-entry-lite-4m40gwkf.js +0 -3
  97. package/bin/vm-hands/vm-hands-entry-lite-62wmnm7g.js +0 -540
  98. package/bin/vm-hands/vm-hands-entry-lite-98076n5g.js +0 -62
  99. package/bin/vm-hands/vm-hands-entry-lite-bvbfcp1k.js +0 -4
  100. package/bin/vm-hands/vm-hands-entry-lite-c01eyep6.js +0 -3
  101. package/bin/vm-hands/vm-hands-entry-lite-dcynw6t2.js +0 -3
  102. package/bin/vm-hands/vm-hands-entry-lite-hh24bq0d.js +0 -3
  103. package/bin/vm-hands/vm-hands-entry-lite-jb2sr2r7.js +0 -3
  104. package/bin/vm-hands/vm-hands-entry-lite-kt5aj2ax.js +0 -11
  105. package/bin/vm-hands/vm-hands-entry-lite-n9nnb482.js +0 -459
  106. package/bin/vm-hands/vm-hands-entry-lite-sb9a1jcn.js +0 -4
  107. package/bin/vm-hands/vm-hands-entry-lite-xg3d0a2y.js +0 -340
  108. package/bin/vm-hands/vm-hands-entry-lite-zamt8xp7.js +0 -181
  109. package/bin/vm-hands/vm-hands-entry-lite-ze9msfq1.js +0 -3
  110. package/bin/vm-hands/vm-hands-op-runner-b76rjaps.js +0 -2
  111. package/bin/vm-hands/worker-sandbox-wpzkvwer.js +0 -2
@@ -1,540 +0,0 @@
1
- // @bun
2
- import{Fb as B7,Hb as b4,Ib as x4,Nb as V7,Ob as G7,Yb as h4,ac as U7,bc as W7,cc as r4,dc as a4,fc as Y7,hb as A4,hc as j8,ic as h0,jb as L2,jc as v0,kb as T4,kc as Z2,lb as _4,mb as P4,nb as r6,nc as F7,ob as i6,pb as k4,qb as o6,qc as O8,rb as b3,rc as m4,sb as t6,tb as e6,tc as z7,ub as $7,vb as J7,wb as f4,xb as Z7,yb as Q7}from"./vm-hands-entry-lite-n9nnb482.js";import{wc as D7,yc as M7,zc as w7}from"./vm-hands-entry-lite-dcynw6t2.js";import{Ec as K7}from"./vm-hands-entry-lite-sb9a1jcn.js";import{Jc as i0,Kc as o0,Rc as P0}from"./vm-hands-entry-lite-anmv8hp7.js";import{Sc as V1}from"./vm-hands-entry-lite-g9rvf5qk.js";import{Tc as N7}from"./vm-hands-entry-lite-hh24bq0d.js";import{$c as c3,Xc as G2,Yc as X2,Zc as s3,bd as n3,cd as r3,gd as a3,id as c6}from"./vm-hands-entry-lite-00qsbphw.js";import{Cd as f7,qd as B2,td as k7}from"./vm-hands-entry-lite-34e71nbe.js";import{$e as x6,Ae as d,Af as d8,Be as h1,Bf as l8,Cf as s8,Df as c8,Ee as S8,Ef as n8,Ff as r8,Ge as m1,Ie as w6,Je as L6,Me as j6,Ne as O6,Oe as I6,Pe as A6,Qe as T6,Re as _6,Se as P6,Te as R6,Ue as q6,Ve as g6,We as E6,Xe as S6,Ye as k6,Ze as f6,_e as b6,af as y6,bf as h6,df as m6,ef as v6,ff as p6,gf as u6,hf as d6,if as l6,jf as s6,le as _1,me as P1,ne as k3,oe as z2,pe as M6,pf as k8,qe as f3,qf as f8,re as Y4,rf as b8,se as F4,sf as x8,te as M0,tf as y8,uf as h8,wf as m8,xe as N0,xf as v8,yf as p8,zf as u8}from"./vm-hands-entry-lite-zfwg7ehq.js";import{Lf as V6,Pf as L5,Qf as d5,Wf as b7,Zf as j5,_f as $2}from"./vm-hands-entry-lite-zamt8xp7.js";import{$f as R7,ag as q7,bg as g7,fg as E7,ig as S7}from"./vm-hands-entry-lite-ze9msfq1.js";import{rg as y4,yg as X7}from"./vm-hands-entry-lite-dgxxsdwb.js";import{Dg as Q2}from"./vm-hands-entry-lite-zh8p7ndn.js";import{Ig as R3,Vg as n6}from"./vm-hands-entry-lite-za55dtte.js";import{pi as H7,qi as C7}from"./vm-hands-entry-lite-0asdf4pm.js";import{Ci as j1,Di as O1,Ei as I1,Fi as A1,Gi as g0}from"./vm-hands-entry-lite-4m40gwkf.js";import{$i as S4,Yi as g1,Zi as a6,_i as E4}from"./vm-hands-entry-lite-c01eyep6.js";import{bj as P3,dj as Q1,jj as L8,kj as D4}from"./vm-hands-entry-lite-9cgm6g8t.js";import{Bj as L7,Cj as j7,Dj as O7,Ej as I7,Gj as A7,Hj as T7,Jj as _7,Kj as P7}from"./vm-hands-entry-lite-7shpbsw8.js";import{Vj as V}from"./vm-hands-entry-lite-hc3p6r9p.js";import{bk as H}from"./vm-hands-entry-lite-j2q1k9vb.js";import{hk as Y8}from"./vm-hands-entry-lite-g036gtem.js";import{request as J9}from"http";import{request as Z9}from"https";import{lookup as Q9}from"dns/promises";import{isIP as B9}from"net";async function K9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?Z9:J9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:c3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var i3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),V9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function o3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(i3.has(Z))return"custom_endpoint_host_not_found";if(V9.has(Z))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(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=o3(Q,J+1);if(B)return B}return null}async function G9($,J){let Z=o3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||B9(Q)!==0)return Z;let B;return await Promise.race([Q9(Q).then(()=>!0,(G)=>!i3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?Z:"custom_endpoint_host_not_found"}function X9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function U9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,X=0;G<Z.length;G++){while(X&&Z[G]!==Z[X])X=B[X-1];if(Z[G]===Z[X])X++;B[G]=X}let K=0;return(G,X=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let U of G){while(K&&Z[K]!==U){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===U){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=U}if(X)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function t3($){$.signal.throwIfAborted();let J=r3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=a3.parse(await $.credential($.signal));if(!n3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,X=0,W=0,Y=X9(Q.apiKey),U=U9(Q.apiKey,Y),F=async(z,C)=>{$.signal.throwIfAborted(),await new Promise((w,D)=>{let O=()=>{$.signal.removeEventListener("abort",O),D($.signal.reason)};if($.signal.addEventListener("abort",O,{once:!0}),$.signal.aborted){O();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(z,C)}).then(()=>{$.signal.removeEventListener("abort",O),w()},(_)=>{$.signal.removeEventListener("abort",O),D(_)})})},N=async(z)=>{if(G+=z.length,G>X2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<z.length;C+=G2){if(W>=s3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:z.subarray(C,C+G2).toString("base64")})}};try{let z=await K9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=z.response,K=z.close;let C=B.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let D of["content-type","retry-after","x-request-id","request-id"]){let O=B.headers[D];if(typeof O==="string")w[D]=O.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:C,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let D of B){$.signal.throwIfAborted();let O=Buffer.isBuffer(D)?D:Buffer.from(D);if(X+=O.length,X>X2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await N(U(O))}return await N(U(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(z){if($.signal.throwIfAborted(),z instanceof H)throw z;throw new H((B?null:await G9(z,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as e3}from"path";function W9($,J){return $===e3(J,".ara","workspace")||$===e3(J,".reason","workspace")}function $4($,J){let Z=$.filter((Q)=>W9(Q.path,J));return Z.length===1?Z[0].path:null}var Y9=/^[a-f0-9]{64}$/;var U2=32,F9=/^\/[^\x00-\x1f\x7f\\]*$/;function w1($){if(typeof $!=="string"||$.length>4096||!F9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function L1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!w1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!Y9.test(B)||!w1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function z9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function N9($){return z9($)??$.email.toLowerCase()}function W2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?N9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),H9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...O1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...I1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,...A1.map(($)=>`/[^/]*${n0($)}$`)],J4=`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(H9)}.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 D9}from"child_process";import*as q from"fs";import*as a from"path";import{homedir as M9}from"os";function Z4($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let B=$.realpathSync(Z),K=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,K])try{let X=$.realpathSync(G);if(X===B||X.startsWith(B+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>X.startsWith(Y)))continue;let W=$.statSync(X);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(X,$.constants.X_OK),X}catch{continue}throw Error("local_device_gh_unavailable")}function Q4($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var B4=[{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 Y2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function K4($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function V4($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function T1($,J=[],Z={}){let Q=[],B=Z.published??new Set,K=K4(J).filter((G)=>!B.has(G));for(let G of $){let X=Y2(G.path);if(!X.valid){Q.push({path:G.path,reason:X.reason??"invalid_path"});continue}let W=G.content??"",Y=K.map((U)=>({secret:U,offset:W.indexOf(U)})).filter((U)=>U.offset>=0).sort((U,F)=>U.offset-F.offset);if(Y.length>0){let U=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:Q4(W,Y[0].offset),...U.length>0?{secretNames:U}:{}})}for(let U of B4){let F=V4(U,W).find((N)=>!B.has(N[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${U.name}`,pattern:U.name,ruleId:U.name,line:Q4(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function G4($,J=[]){let Z=K4(J),Q=new Set;for(let{content:B}of $){for(let K of Z)if(B.includes(K))Q.add(K);for(let K of B4)for(let G of V4(K,B))Q.add(G[0])}return[...Q]}function C9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function X4($,J,Z){let Q=(B,K)=>B.reduce((G,X)=>G+C9(X,K),0);return new Set($.filter((B)=>Q(J,B)<=Q(Z,B)))}var A0=4194304,U4=536870912,F2=/^[a-f0-9]{40}$/,w9=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B;try{B=D9($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K=Buffer.alloc(0),G=Buffer.alloc(0),X,W=!1,Y=(z)=>{if(X??=Error(z),B.pid)try{process.kill(-B.pid,"SIGKILL")}catch{}},U=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",U,{once:!0});let N=(z)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",U),Q({status:z,stdout:K,stderr:G,...X?{error:X}:{}})};if(B.stdout.on("data",(z)=>{if(K.length+G.length+z.length>Z.maxBuffer)Y("output_limit");else K=Buffer.concat([K,z])}),B.stderr.on("data",(z)=>{if(K.length+G.length+z.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,z])}),B.on("error",()=>{if(Y("spawn_failed"),!B.pid)N(null)}),B.on("close",(z)=>N(z)),B.stdin.on("error",()=>Y("input_failed")),B.stdin.end(Z.input),Z.signal?.aborted)U()}),L9={command:w9,gh:($,J)=>Z4(q,a,$,J),home:M9};function I($){throw Error($)}function j9($,J){let Z=new Set($.split(/\r?\n/).map(W2));return J.filter((Q)=>{let B=W2(Q);if(Z.has(B))return!1;return Z.add(B),!0})}var O9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),I9=($)=>JSON.stringify($,(J,Z)=>O9.has(J)?void 0:Z);function W4($,J,Z){let Q=[...new Set($.map((K)=>`${J(K.path)}${K.line?`:${K.line}`:""} (${K.reason==="literal_secret_detected"?`value of ${K.secretNames?.length?K.secretNames.slice(0,3).join(", "):"a session variable"}`:`${K.ruleId??"credential"} credential`})`))].slice(0,10),B=$.some((K)=>K.reason==="literal_secret_detected");I(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${B?" 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 z4($,J,Z=L9){let Q=_1.parse($),B="local_device_gh_prepare_setup";try{if(!["darwin","linux"].includes(process.platform))I("local_device_gh_platform_unavailable");J.assertCurrent();let K=q.realpathSync(J.root);if(K==="/")I("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)I("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)I("local_device_gh_read_only");if(!M0(Q)){let M=T1([{path:"github-operation",content:I9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!M.clean)W4(M.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let G=Z.gh(K),X=Z.home(),W=Z.gh(K,"git"),Y=J.privateDirectory?q.realpathSync(J.privateDirectory):q.realpathSync(X);if(!M0(Q)&&(!J.privateDirectory||Y===K||Y.startsWith(K+a.sep)))I("local_device_gh_private_scope_unavailable");let U={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:X,GH_CONFIG_DIR:a.join(X,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/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((M)=>process.env[M]?[[M,process.env[M]]]:[])):{}},F=async(M,T,R=Y,S,b=A0)=>{J.assertCurrent();let x=await Z.command(M,T,{cwd:R,env:U,input:S,maxBuffer:b,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),x.error||x.status!==0)I("local_device_gh_command_failed");return x.stdout},N=async(M)=>(await F(G,M)).toString("utf8").trim(),z=async(M,T="application/vnd.github+json")=>{Y4(Q.repoFullName,M,{headers:{accept:T}}),J.assertCurrent();let R=await Z.command(G,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,M],{cwd:Y,env:U,maxBuffer:A0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),R.error&&R.status===null)I("local_device_gh_response_unavailable");let S=R.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!S)I("local_device_gh_response_invalid");let b=Number(S[1]);if(b>=200&&b<300&&R.status!==0)I("local_device_gh_response_unavailable");if(Buffer.byteLength(S[3])>z2)I("local_device_gh_response_too_large");let x={};for(let o of S[2].split(/\r?\n/)){let $0=o.indexOf(":"),D0=o.slice(0,$0).toLowerCase();if(["link","content-type"].includes(D0))x[D0]=o.slice($0+1).trim().slice(0,8192)}return{kind:"read",status:b,headers:x,body:b>=200&&b<300?S[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return z(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[M,T]=Q.repoFullName.split("/"),R=await N(["api","graphql","--hostname","github.com","-f",`query=${F4}`,"-f",`owner=${M}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(R)>z2)I("local_device_gh_response_too_large");let S=JSON.parse(R);if(S.errors||S.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||S.data.repository.pullRequest?.number!==Q.number)I("local_device_gh_response_invalid");return{kind:"pr_review_context",body:R}}if(Q.kind==="pr_merge"){let M=await z(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(M.body),R=(x)=>x.number===Q.number&&x.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&x.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&x.base?.ref===Q.expectedBaseRef&&x.head?.sha===Q.expectedHeadSha;if(M.status!==200||!R(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())I("local_device_gh_merge_target_changed");await N(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let S=await z(`/repos/${Q.repoFullName}/pulls/${Q.number}`),b=JSON.parse(S.body);if(S.status!==200||!R(b)||b.merged!==!0)I("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)I("local_device_gh_default_branch");let M=await N(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(M))I("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:M}}if(Q.kind==="pr_mutation"){let M=Q.mutation,T=M.action==="edit"?["edit",...M.title!==void 0?[`--title=${M.title}`]:[],...M.body!==void 0?[`--body=${M.body}`]:[],...M.base?[`--base=${M.base}`]:[]]:M.action==="metadata"?["edit",`--${M.change}-${M.field}=${M.value}`]:M.action==="ready"?["ready"]:M.action==="draft"?["ready","--undo"]:["close"];return await N(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)I("local_device_gh_workspace_unavailable");let C=q.realpathSync(J.repoPath);if(C!==K&&!C.startsWith(K+a.sep))I("local_device_gh_workspace_unavailable");let w=`https://github.com/${Q.repoFullName}.git`,D="!'"+G.replace(/'/g,"'\\''")+"' auth git-credential",O=Function("return ("+J4+")")(),_=(M,T,R)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",M,T,...R]]:[T,R],j=async(M,T,R,S=A0)=>{let b=M===Y||M.startsWith(Y+a.sep),x=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...b?["-c",`credential.https://github.com.helper=${D}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(b)return F(W,x,M,R,S);let o=a.join(C,".ara-local-gh-tmp");if(q.mkdirSync(o,{recursive:!0,mode:448}),q.lstatSync(o).isSymbolicLink()||q.realpathSync(o)!==o)I("local_device_gh_workspace_unavailable");J.assertCurrent();let $0=await Z.command(..._(O(C,o),W,x),{cwd:M,input:R,maxBuffer:S,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:C,TMPDIR:o,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(J.assertCurrent(),$0.error||$0.status!==0)I("local_device_gh_collection_failed");return $0.stdout},A=async(M,T)=>(await j(M,T)).toString("utf8").trim(),v=async(M,T)=>{let R=a.join(M,".ara-local-gh-tmp");if(q.mkdirSync(R,{recursive:!0,mode:448}),q.lstatSync(R).isSymbolicLink()||q.realpathSync(R)!==R)I("local_device_gh_workspace_unavailable");J.assertCurrent();let S=await Z.command(..._(O(M,R),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:M,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:M,TMPDIR:R}});if(J.assertCurrent(),S.error||S.status!==0)I("local_device_gh_materialization_failed")},L=async(M)=>{let T=new Map;if(M.length===0)return T;let R=await j(m,["cat-file","--batch"],[...new Set(M)].join(`
14
- `)+`
15
- `,A0*8);for(let S=0;S<R.length;){let b=R.indexOf(10,S),[x,o,$0]=R.subarray(S,b).toString("utf8").split(" ");if(b<0||!x||o!=="blob"||!/^[0-9]+$/.test($0??""))I("local_device_gh_object_invalid");T.set(x,R.subarray(b+1,b+1+Number($0)).toString("utf8")),S=b+1+Number($0)+1}return T},g=async(M,T,R)=>{let S=a.join(C,".ara-local-gh-tmp"),b=O(C,S)+`
16
- (allow file-read* file-write* (subpath ${JSON.stringify(C)}))
17
- (allow file-read* (subpath ${JSON.stringify(M)}))
18
- (allow file-read-metadata (path-ancestors ${JSON.stringify(M)}))`,x=async($0,D0)=>{J.assertCurrent();let l0=await Z.command(..._(b,$0,D0),{cwd:C,maxBuffer:A0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:C,TMPDIR:S,GIT_INDEX_FILE:a.join(C,".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(J.assertCurrent(),l0.error||l0.status!==0)I("local_device_gh_materialization_failed")},o=["--git-dir="+M,"--work-tree="+C,"-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=","-c","protocol.allow=never"];await x(W,[...o,"read-tree",T]),await x(W,[...o,"checkout-index","--all","--index"]),await j(C,["update-ref","refs/heads/"+R,T]),await j(C,["symbolic-ref","HEAD","refs/heads/"+R])};B="local_device_gh_prepare_metadata";let P=await z(`/repos/${Q.repoFullName}`);if(P.status!==200)I("local_device_gh_repository_unavailable");let l=JSON.parse(P.body);if(l.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase()||l.default_branch!==Q.defaultBranch||Q.kind==="publish"&&l.permissions?.push!==!0)I("local_device_gh_repository_authority_changed");if(Q.branch===Q.defaultBranch)I("local_device_gh_default_branch");B="local_device_gh_prepare_private_init";let m=q.mkdtempSync(a.join(Y,"github-publication-"));q.chmodSync(m,448);let D1=!1;try{if(await j(m,["init","--bare","--template="]),Q.kind==="prepare"){if(B="local_device_gh_prepare_fetch",await j(m,["fetch","--depth=1","--no-tags","--no-recurse-submodules",w,Q.baseSha]),await A(m,["rev-parse","FETCH_HEAD"])!==Q.baseSha)B="local_device_gh_prepare_base_mismatch",I("local_device_gh_base_changed");B="local_device_gh_prepare_checkout_validation";let p=a.join(C,".git"),B0=!1;if(q.existsSync(p)){if(!q.lstatSync(p).isDirectory()||q.lstatSync(p).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((r)=>q.existsSync(a.join(p,r))))I("local_device_gh_repository_layout_invalid");let e=await j(C,["rev-parse","--verify","-q","HEAD"]).then((r)=>r.toString("utf8").trim(),()=>null),K0=await j(C,["config","--local","--get","remote.origin.url"]).then((r)=>r.toString("utf8").trim(),()=>"");if(e!==null||K0){if(e!==Q.baseSha||await A(C,["branch","--show-current"])!==Q.branch)I("local_device_gh_checkout_exists");return{kind:"prepare",headSha:Q.baseSha}}B0=!0}let J0=q.readdirSync(C).filter((e)=>!(B0&&e===".git")),U0=[".ara-local-gh-tmp",".reason-local-gh-tmp"];if(J0.some((e)=>!U0.includes(e))||J0.some((e)=>{let K0=a.join(C,e);return!q.lstatSync(K0).isDirectory()||q.lstatSync(K0).isSymbolicLink()||q.readdirSync(K0).length>0}))I("local_device_gh_checkout_not_empty");if(B="local_device_gh_prepare_checkout_init",!B0)await j(C,["init","--template="]);B="local_device_gh_prepare_materialization";let z0=await j(m,["pack-objects","--stdout","--revs"],Q.baseSha+`
19
- `,U4);return await v(C,Q.baseSha),await j(C,["index-pack","--strict","--stdin"],z0,65536),await j(C,["remote","add","origin",w]),await g(m,Q.baseSha,Q.branch),{kind:"prepare",headSha:Q.baseSha}}let M=a.join(C,".git");if(!q.lstatSync(M).isDirectory()||q.lstatSync(M).isSymbolicLink()||["objects/info/alternates","info/grafts"].some((p)=>q.existsSync(a.join(M,p))))I("local_device_gh_repository_layout_invalid");if(await A(C,["branch","--show-current"])!==Q.branch)I("local_device_gh_branch_changed");let T=await A(C,["rev-parse","--verify","HEAD"]);if(!F2.test(T))I("local_device_gh_head_invalid");let R=await z(`/repos/${Q.repoFullName}/commits/${Q.baseSha}`);if(R.status!==200||JSON.parse(R.body).sha!==Q.baseSha)I("local_device_gh_base_unverified");let S=await z(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(Q.remoteHeadSha===null?S.status!==404:S.status!==200||JSON.parse(S.body).object?.sha!==Q.remoteHeadSha)I("local_device_gh_remote_changed");let b=[...(await A(C,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha])).split(`
20
- `),...(await A(C,["rev-list","--objects","--no-object-names","--no-walk",Q.baseSha])).split(`
21
- `)].filter(Boolean);if(b.some((p)=>!F2.test(p)))I("local_device_gh_object_invalid");let x=await j(C,["pack-objects","--stdout"],[...new Set(b)].join(`
22
- `)+`
23
- `,U4);if(q.writeFileSync(a.join(m,"shallow"),Q.baseSha+`
24
- `,{flag:"wx",mode:384}),await j(m,["index-pack","--strict","--stdin"],x,65536),await j(m,["merge-base","--is-ancestor",Q.baseSha,T]),Q.remoteHeadSha)await j(m,["merge-base","--is-ancestor",Q.remoteHeadSha,T]);let o=await j(m,["show","-s","--format=%B",T]),$0=(await j(m,["interpret-trailers","--parse"],o)).toString("utf8"),D0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:j9($0,Q.contributorTrailers)}:void 0,l0=(await A(m,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
25
- `).filter(Boolean);if(l0.length>5000)I("local_device_gh_collection_too_large");let s0=[],p3=0;for(let p of l0){if(!F2.test(p))I("local_device_gh_object_invalid");let B0=await A(m,["cat-file","-t",p]);if(!["blob","commit","tree"].includes(B0))I("local_device_gh_object_invalid");let J0=await j(m,["cat-file",B0,p]);if(p3+=J0.length,p3>A0)I("local_device_gh_collection_too_large");if(B0==="tree"){let U0=0;while(U0<J0.length){let z0=J0.indexOf(32,U0),e=J0.indexOf(0,z0+1);if(z0<U0||e<=z0||e+21>J0.length)I("local_device_gh_object_invalid");let K0=J0.subarray(z0+1,e).toString("utf8");if(K0.includes("/")||!Y2(K0).valid)I("local_device_gh_object_invalid");U0=e+21}}s0.push({path:`object-${p}`,content:J0.toString("utf8")})}let u3=J.secretNames?{secretNames:J.secretNames}:{},c0=T1(s0,J.forbiddenSecretValues,u3),d3=new Map;if(!c0.clean)try{let p=(await j(m,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,T])).toString("utf8").split("\x00"),B0=[],J0=[];for(let r=0;r+1<p.length;r+=2){let[,e7,$9,V2,M1]=p[r].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!V2||!M1)continue;if(e7!=="160000"&&!/^0+$/.test(V2))B0.push(V2);if($9!=="160000"&&!/^0+$/.test(M1))J0.push(M1),d3.set(`object-${M1}`,p[r+1])}let U0=await L([...B0,...J0]),z0=new Set(c0.violations.map((r)=>r.path)),e=G4(s0.filter((r)=>z0.has(r.path)),J.forbiddenSecretValues),K0=X4(e,J0.map((r)=>U0.get(r)??""),B0.map((r)=>U0.get(r)??""));if(K0.size>0)c0=T1(s0,J.forbiddenSecretValues,{...u3,published:K0})}catch{}if(!c0.clean)W4(c0.violations,(p)=>d3.get(p)??`an object in the pushed history (${p})`,"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 j(m,["push","--no-recurse-submodules",w,`${T}:refs/heads/${Q.branch}`]);let l3=await z(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(l3.status!==200||JSON.parse(l3.body).object?.sha!==T)I("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:T,scannedObjectCount:s0.length,...D0?{attribution:D0}:{}}}catch(M){throw D1=!0,M}finally{try{q.rmSync(m,{recursive:!0,force:!0})}catch(M){if(!D1||Q.kind!=="prepare")throw B=null,M}}}catch(K){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&B&&!J.signal?.aborted)throw new P1(B);throw K}}var T0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),N2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},A9=V.object({...N2,version:V.literal(2),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!1),source_bound:V.literal(!1),profiles:V.array(T0.shape.profile).min(1).max(16),extension_instance_ids:V.array(T0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),T9=V.object({...N2,version:V.literal(3),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!0),source_bound:V.literal(!1),max_seconds:V.literal(15),profiles:V.array(T0.shape.profile).min(1).max(16),extension_instance_ids:V.array(T0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),H2=V.union([A9,T9]),RB=V.union([V.object({...N2,version:V.literal(1),development_only:V.literal(!0),profile:T0.shape.profile,extension_instance_id:T0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),H2]);import{randomUUID as O2}from"crypto";import{spawn as m9}from"child_process";import{existsSync as I2,lstatSync as v4,mkdirSync as v9,readFileSync as p9,realpathSync as R1,rmSync as u9,writeFileSync as d9}from"fs";import{dirname as p4,join as W0,relative as l9,sep as s9}from"path";var _9=["process.run.v1","process.full.v1"],P9=600000,R9=1800000,q9=20000,N4="process.cancel.v1",H4=V.object({action:V.literal("start"),request_id:V.string().uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),cwd:V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")&&!$.startsWith("/")&&!$.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:V.enum(["host","confined"]).default("host"),timeout_ms:V.number().int().min(1000).max(R9).default(P9).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(),C2={device_id:V.string().uuid(),root_id:V.string().uuid()},g9=V.discriminatedUnion("action",[H4.extend(C2),V.object({...C2,action:V.literal("inspect"),process_id:V.string().uuid(),after:V.number().int().min(0).default(0),wait_ms:V.number().int().min(0).max(q9).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(),V.object({...C2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),EB=V.toJSONSchema(g9,{io:"input"}),SB=H4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),r0=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:V.number().int().nullable(),first_cursor:V.number().int().min(0),next_cursor:V.number().int().min(0),truncated:V.boolean(),observed_at:V.iso.datetime(),output:V.array(V.object({cursor:V.number().int().min(1),stream:V.enum(["stdout","stderr"]),text:V.string().max(32768)}).strict()).max(128)}).strict().refine(($)=>{if(Buffer.byteLength(JSON.stringify($))>1e5||$.next_cursor<$.first_cursor-1)return!1;if(($.state==="starting"||$.state==="running"||$.state==="uncertain")&&$.exit_code!==null)return!1;if($.state==="exited"&&($.exit_code===null||$.exit_code<0||$.exit_code>255))return!1;if($.state==="cancelled"&&$.exit_code!==130||$.state==="expired"&&$.exit_code!==124)return!1;let Z=$.first_cursor-1;for(let Q of $.output){if(Q.cursor<=Z||Q.cursor>$.next_cursor)return!1;Z=Q.cursor}return!0});function C4($){return _9.includes($)}var kB=V.object({operation_constraints:V.record(V.string(),V.unknown())}),fB=V.object({ready:V.literal(!0),version:V.literal(1),execution_mode:V.enum(["host","confined"]),max_timeout_ms:V.number().int().min(1000).optional()});var E9=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["queued","cancelled_before_start","not_started"]),exit_code:V.null(),output:V.array(V.never()).length(0),first_cursor:V.literal(0),next_cursor:V.literal(0),truncated:V.literal(!1),cancellation_requested:V.literal(!1),reason_code:V.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),S9=V.object({...r0.shape,state:V.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:V.iso.datetime().optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:V.boolean(),reason_code:V.string().nullable().optional(),execution_authority:V.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:V.object({cause:V.literal("brain_generation_changed"),terminal_confirmed:V.boolean(),next_step:V.enum(["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:r0.shape.state.or(V.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),bB=V.toJSONSchema(S9),xB=V.union([r0,E9.refine(($)=>$.state==="cancelled_before_start")]),D2=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["exited","cancelled","expired"]),exit_code:V.number().int().min(0).max(255),observed_at:V.iso.datetime()}).strict().refine(($)=>($.state!=="cancelled"||$.exit_code===130)&&($.state!=="expired"||$.exit_code===124)),k9=V.object({process_terminal_observation:D2}).strict();function yB($,J){let Z=k9.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var M4="preview.serve.v1",w4=43200000;var pB=3,L4="preview.open.v1",j4=1,M2="gid_proxy_v1",O4="egress",w2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,f9=V.object({version:V.literal(M2),allowed_domains:V.array(V.string().max(260).regex(w2)).max(1024)}).strict(),b9=V.custom(($)=>D4($)!==null,"invalid workspace"),x9=V.object({version:V.literal(1),request_id:V.uuid(),session_id:V.uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),port:V.number().int().min(1024).max(65535),workspace:b9,egress:f9.optional()}).strict(),I4=x9.extend({expires_at:V.iso.datetime()}).strict();var y9=4,h9=5000;function j2($,J,Z){let Q=null;try{Q=L2($)}catch{}T4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function R4($){let J=new Map;return{open(Z){let Q=(U)=>j2(Z,$.claim.operation_id,U),B;try{B=L2(Z)}catch{return Q("binding_invalid")}let{binding:K,deviceRelayUrl:G}=B,X=$.claim.owner;if(!X||K.organizationId!==X.organization_id||K.userId!==X.user_id||K.deviceId!==X.device_id||K.rootId!==$.claim.root_id||K.jobId!==$.claim.operation_id||K.fenceId!==$.claim.operation_id||K.generation!==j4||K.expiresAtMs>Math.min(Date.now()+A4.lifetimeMs+h9,$.expiresAtMs))return Q("binding_mismatch");if(K.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(K.port)?.abort(),J.delete(K.port),J.size>=y9)return Q("preview_capacity");let W=new AbortController;J.set(K.port,W);let Y=P4({binding:K,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(W.signal.aborted)return null;let U=await $.inspect();return U?{binding:K,executorLaunchId:$.executorLaunchId,job:U}:null}});_4({binding:K,deviceRelayUrl:G,port:Y,signal:W.signal}).then((U)=>U.closed,(U)=>{let F=U instanceof Error?U.message:"preview_failed";if(F!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:K.jobId,port:K.port,reason_code:F})}
26
- `)}).finally(()=>{if(J.get(K.port)===W)J.delete(K.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class a0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var u4=256,q1=new Map,d4="preview.serve.v1",_0=new Map;function l4($){let J=_0.get($.operation_id);if(J){if(J.claim!==$)throw V0("process_authority_lost");return J}if(_0.size>=u4)throw V0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return _0.set($.operation_id,Z),Z}function q4($){return{version:1,process_id:$,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 g4=($)=>new Promise((J)=>setTimeout(J,$)),V0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function c9($=g1(),J=n9()){let Z=p4(y4({},$)),Q=l9(E4($),Z),[B,...K]=Q.split(s9);return{directory:W0(J,Q,"processes"),previous:[W0(Z,"processes"),...B==="reason"?[W0(J,"ara",...K,"processes")]:[]]}}function n9(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=S4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function A2($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw V0("process_authority_lost");let J=l4($.claim);if(J.executing)throw V0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",q4($.claim.operation_id);J.phase="starting";let Z=$.journals??c9();v9(Z.directory,{recursive:!0,mode:448});let Q=k4({runtimeDirectory:R1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((L)=>I2(L)).map((L)=>R1(L)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:u4});try{for(let L of[$.root,$.cwd])if(!h4(R1(L),Q.journalDirectory))throw new H("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(L){throw Q.disposeSocket(),L}let B=v4(Q.journalDirectory),K=$.claim.capability===d4,G=()=>q1.set($.claim.operation_id,{path:Q.journalDirectory,ino:B.ino,dev:B.dev,anyCompletion:K}),X=p4(Q.socketPath),W=W0(X,"config.json"),Y={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:i0,protocolVersion:2,workerArtifactSha256:P0,workerEntrypoint:o0,targetGeneration:1,fenceId:O2(),workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:W0(X,"unused.env"),replSocketPath:W0(X,"unused.sock"),readyPath:W0(X,"ready.json"),directTerminalReceiptPath:W0(X,"terminal.json"),launchId:O2(),expiresAtMs:$.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Q.journalDirectory,scopeId:Q.scopeId},jobControlSocketPath:Q.socketPath,...$.prefix?{bashCommandPrefix:$.prefix}:{},...$.jobsUser?{jobsUser:$.jobsUser}:{}},U;try{d9(W,JSON.stringify(Y),{mode:384});let L=m4({configPath:W,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:X});U=$.spawnWorker?.(W,Y)??m9(L.command,L.args,{...L.options,env:$.environment,stdio:["ignore","ignore","ignore"]})}catch(L){throw Q.disposeSocket(),L}let F=!1,N=new Promise((L,g)=>{U.once("exit",(P)=>{F=!0,L(P)}),U.once("error",(P)=>{F=!0,g(P)})});N.catch(()=>{});let z={root:$.root,runId:$.claim.run_id,scopeId:Q.scopeId,socketPath:Q.socketPath,generation:1,fenceId:Y.fenceId,executorLaunchId:Y.launchId,expiresAtMs:Y.expiresAtMs},C=async(L)=>{let g=await f4(z,{type:"job",version:2,generation:1,id:O2(),jobId:$.claim.operation_id,...L==="start"?{action:L,input:{script:$.command,leaseExpiresAtMs:$.expiresAtMs}}:L==="inspect"?{action:L,input:{after:0}}:L==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:L,input:{}}},new AbortController().signal);if(!g.ok)throw V0(g.error);return g.job},w=!1,D=!1,O,_=()=>{w=!0,U.kill("SIGTERM")};$.signal.addEventListener("abort",_,{once:!0});let j,A=0,v=async(L)=>{let g=[...L.output],P={version:1,process_id:$.claim.operation_id,state:L.state,exit_code:L.exitCode,first_cursor:L.firstCursor,next_cursor:L.nextCursor,truncated:L.truncated,output:g,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(P))>90000&&g.length)g.shift(),P.truncated=!0,P.first_cursor=g[0]?.cursor??P.next_cursor+1;j=r0.parse(P),await $.emit(j),A=Date.now()};try{let L=Math.min(Date.now()+1e4,$.expiresAtMs);while(!I2(Y.readyPath)){if(F)throw new H("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if($.signal.aborted||Date.now()>=L)throw V0("process_start_unconfirmed");await g4(25)}let g=JSON.parse(p9(Y.readyPath,"utf8"));if(g.launchId!==Y.launchId||g.fenceId!==Y.fenceId||g.workerArtifactSha256!==P0)throw V0();if($.signal.throwIfAborted(),J.cancelRequested)return q4($.claim.operation_id);let P;try{D=!0,P=await C("start")}catch(l){if(!(l instanceof H)||l.code!=="hands_job_result_unknown")throw l;P=await C("inspect")}if(J.phase="running",J.cancel=async()=>{await C("cancel")},K&&$.preview)J.tunnels=R4({claim:$.claim,executorLaunchId:Y.launchId,expiresAtMs:$.expiresAtMs,deniedPorts:$.preview.deniedPorts,inspect:async()=>J.phase==="running"&&!F?await C("probe"):null});if(J.cancelRequested)await J.cancel(),P=await C("inspect");for(;;){if(!["starting","running"].includes(P.state))J.phase="settling",J.cancel=void 0;if(!j||j.state!==P.state||j.next_cursor!==P.nextCursor&&Date.now()-A>=5000)await v(P);if(!["starting","running"].includes(P.state))break;if($.signal.aborted||F)throw V0();await g4(1000);try{P=await C("inspect"),O=void 0}catch(l){if(!(l instanceof H)||l.code!=="hands_job_result_unknown"||$.signal.aborted||F||Date.now()-(O??=Date.now())>120000)throw l}}if(!j||j.state==="uncertain")throw V0();return j}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",_),!F&&!w)U.kill("SIGTERM");let L,g=await Promise.race([N.then((P)=>({code:P})),new Promise((P)=>{L=setTimeout(()=>P(null),6000)})]).finally(()=>{clearTimeout(L)});if(!g){U.kill("SIGKILL");try{await N}finally{if(F)Q.disposeSocket()}throw V0("process_cleanup_unconfirmed")}try{if((w||$.signal.aborted)&&g.code===0&&D){b4(X);let P=JSON.parse(x4(Y.directTerminalReceiptPath)),l=D2.safeParse(P.observation);if(Object.keys(P).length===4&&P.launch_id===Y.launchId&&P.fence_id===Y.fenceId&&P.scope_id===Q.scopeId&&l.success&&l.data.process_id===$.claim.operation_id){if(K)G();throw new a0(l.data)}}}catch(P){if(P instanceof a0)throw P}finally{if(F)Q.disposeSocket()}if(g.code!==0&&!w&&D)throw V0("process_cleanup_unconfirmed");if(!w&&g.code===0&&(j&&["exited","cancelled","expired"].includes(j.state)||!D&&J.cancelRequested)||K&&g.code===0&&!D)G()}}async function UK($,J){if(J.kind===L4&&$.capability===d4){let B=_0.get($.operation_id);if(B?.claim===$&&B.tunnels)B.tunnels.open(J.payload);else j2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==N4||!C4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=_0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=l4($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function WK($,J){_0.delete($);let Z=q1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return q1.delete($),!1;try{let Q=v4(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||Q.uid!==process.getuid?.()||(Q.mode&63)!==0||R1(Z.path)!==Z.path||I2(W0(Z.path,"owner.lock")))return!1;return u9(Z.path,{recursive:!0}),q1.delete($),!0}catch{return!1}}import{createServer as r9,request as a9}from"http";import{connect as i9,isIP as o9}from"net";var i4=120000,t9=15000;function e9($,J,Z){let Q=r4(J).toLowerCase().replace(/\.$/,"");if(!Q||o9(Q))return!1;return $.some((B)=>{if(!w2.test(B))return!1;let K=B.lastIndexOf(":"),G=K>0?B.slice(0,K):B;if(K>0&&Number(B.slice(K+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function $$($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,B=Z?Number(Z[2]):J;return Q&&B>=1&&B<=65535?{host:Q,port:B}:null}async function T2($,J,Z){if(!e9(Z,$,J))return null;let Q=await a4($);return Q.ok?Q.addresses[0]:null}function t0($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
27
- Connection: close\r
28
- Content-Length: 0\r
29
- \r
30
- `)}function s4($,J){return new Promise((Z,Q)=>{let B=i9({host:$,port:J}),K=setTimeout(()=>B.destroy(Error("connect_timeout")),t9);B.once("connect",()=>{clearTimeout(K),Z(B)}),B.once("error",(G)=>{clearTimeout(K),Q(G)})})}function c4($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(i4,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function n4($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function o4($,J=()=>{}){let Z=[...$],Q=new Set,B=(X)=>{Q.add(X),X.once("close",()=>Q.delete(X))},K=r9((X,W)=>{(async()=>{let Y;try{Y=new URL(X.url??"")}catch{Y=new URL("invalid:")}let U=Number(Y.port||80),F=Y.protocol==="http:"?await T2(Y.hostname,U,Z):null;if(!F){J(),W.writeHead(403,{connection:"close"}).end();return}let N=a9({host:F,port:U,method:X.method,path:`${Y.pathname}${Y.search}`,headers:n4(X.headers,Y.host),agent:!1,timeout:i4},(z)=>{W.writeHead(z.statusCode??502,z.headers),z.pipe(W)});N.on("timeout",()=>N.destroy()),N.on("error",()=>{if(!W.headersSent)W.writeHead(502);W.end()}),W.on("close",()=>N.destroy()),X.pipe(N)})().catch(()=>{if(!W.headersSent)W.writeHead(502);W.end()})});K.on("connection",B),K.on("connect",(X,W,Y)=>{B(W),W.on("error",()=>W.destroy()),(async()=>{let U=$$(X.url??"",443),F=U?await T2(U.host,U.port,Z):null;if(!U||!F){J(),t0(W,403);return}let N=await s4(F,U.port).catch(()=>null);if(!N){t0(W,502);return}if(W.destroyed){N.destroy();return}B(N),W.write(`HTTP/1.1 200 Connection Established\r
31
- \r
32
- `),c4(W,N,Y)})().catch(()=>W.destroy())}),K.on("upgrade",(X,W,Y)=>{B(W),W.on("error",()=>W.destroy()),(async()=>{let U;try{U=new URL(X.url??"")}catch{t0(W,403);return}let F=Number(U.port||80),N=["http:","ws:"].includes(U.protocol)?await T2(U.hostname,F,Z):null;if(!N){J(),t0(W,403);return}let z=await s4(N,F).catch(()=>null);if(!z){t0(W,502);return}B(z);let C=n4(X.headers,U.host),w=[`${X.method} ${U.pathname}${U.search} HTTP/1.1`];for(let[D,O]of Object.entries(C))for(let _ of Array.isArray(O)?O:O===void 0?[]:[O])w.push(`${D}: ${_}`);z.write(`${w.join(`\r
33
- `)}\r
34
- \r
35
- `),c4(W,z,Y)})().catch(()=>W.destroy())}),await new Promise((X,W)=>{K.once("error",W),K.listen(0,"127.0.0.1",()=>X())});let{port:G}=K.address();return{url:`http://127.0.0.1:${G}`,close(){K.close();for(let X of Q)X.destroy()}}}import{createHash as E2,randomUUID as B$}from"crypto";import{closeSync as J1,constants as s,fchownSync as K$,fstatSync as R0,fsyncSync as V$,linkSync as G$,mkdirSync as X$,openSync as F8,readSync as z8,unlinkSync as U$,writeSync as W$}from"fs";import{platform as U8}from"os";import{getSystemErrorName as Y$}from"util";var t4={type:"string",format:"uuid"},Z8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,E1={type:"string",minLength:1,maxLength:4096,pattern:Z8},_2=V.string().min(1).max(4096).regex(new RegExp(Z8)),S1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},k1={device_id:t4,root_id:t4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},MK={read:{schema:V.object({...S1,path:_2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...k1,path:E1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...S1,path:_2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...k1,path:E1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...S1,command:V.string().min(1).max(16000),cwd:_2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...k1,command:{type:"string",minLength:1,maxLength:16000},cwd:E1,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}}},Y0=1073741824,e0=600000,e4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,Q8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${e4}(?:/${e4})*(?![\s\S])`,B8=new RegExp(Q8);function K8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&B8.test($)}var P2=V.string().min(1).max(4096).regex(B8),R2={...E1,pattern:Q8},V8=V.string().regex(/^[a-f0-9]{64}$/),G8=V.object({kind:V.literal("workspace"),path:P2}).strict(),J$=V.discriminatedUnion("kind",[G8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:V8}).strict()]),f1=1,$1="cloud_workspace_id",q2="cloud_workspace",g2=1,Z$=V.discriminatedUnion("kind",[G8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(Y0),sha256:V8}).strict()]),X8=V.object({source_version:V.literal(f1),source:Z$,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[$1]:V.string().min(1).max(160).optional()}).strict(),wK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(f1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var $8=V.object({...S1,timeout_ms:V.number().int().min(1000).max(e0).optional(),source_path:P2,destination_path:P2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),J8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...k1,timeout_ms:{type:"integer",minimum:1000,maximum:e0},source_path:R2,destination_path:R2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},Q$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:R2},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}]},LK=V.union([$8,$8.omit({source_path:!0}).extend({source:J$}).strict()]),jK={...J8,required:["device_id","root_id","destination_path"],properties:{...J8.properties,source:Q$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var S2=65536;function u($){throw new H($,$)}function x1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function b1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function F$($,J,Z){let Q;switch(x1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return b1($,J,Q)}function z$($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function N$(){if(U8()==="linux")return{open:(X,W,Y,U=384)=>F8(`/proc/self/fd/${X}/${W}`,Y,U),mkdir:(X,W)=>X$(`/proc/self/fd/${X}/${W}`,{mode:448}),link:(X,W,Y)=>G$(`/proc/self/fd/${X}/${W}`,`/proc/self/fd/${X}/${Y}`),unlink:(X,W)=>U$(`/proc/self/fd/${X}/${W}`),close:()=>{}};if(U8()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),B=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),K=B.symbols.__error();if(K===null)return B.close(),u("transfer_path_unavailable");let G=(X)=>{if(X<0){let W=Y$(-Q.i32(K));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return X};return{open:(X,W,Y,U=384)=>G(B.symbols.openat(X,Z(Buffer.from(`${W}\x00`)),Y,U,0,0,0,0,U)),mkdir:(X,W)=>{G(B.symbols.mkdirat(X,Z(Buffer.from(`${W}\x00`)),448))},link:(X,W,Y)=>{G(B.symbols.linkat(X,Z(Buffer.from(`${W}\x00`)),X,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(X,W)=>{G(B.symbols.unlinkat(X,Z(Buffer.from(`${W}\x00`)),0))},close:()=>B.close()}}function N8($,J){let Z=R0($),Q=R0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)K$(J,Z.uid,Z.gid)}function H$($,J,Z,Q){if(!K8(Z))return u("transfer_path_invalid");let B=Z.split("/"),K=F8(J,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW);try{for(let G of B.slice(0,-1)){let X;try{X=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW)}catch(W){if(!Q||x1(W)!=="ENOENT")throw W;try{$.mkdir(K,G)}catch(Y){if(x1(Y)!=="EEXIST")throw Y}X=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW),N8(K,X)}J1(K),K=X}return{fd:K,leaf:B.at(-1)}}catch(G){throw J1(K),G}}function W8($,J){let Z=R0($,{bigint:!0});if(!Z.isFile()||Z.size>Y0)return u("transfer_file_invalid");let Q=E2("sha256"),B=Buffer.alloc(S2),K=0;while(!0){J.throwIfAborted();let X=z8($,B,0,B.length,K);if(!X)break;if(K+=X,K>Y0)return u("transfer_size_exceeded");Q.update(B.subarray(0,X))}let G=R0($,{bigint:!0});if(BigInt(K)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:K,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=z$($.payload.url),Z=await N$(),Q,B,K;try{if(Q=H$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){B=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);let N=R0(B,{bigint:!0});if(!N.isFile()||N.size>Y0)return u("transfer_file_invalid");let z=E2("sha256"),C=0,w=B,D,O=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let L=Buffer.alloc(S2),g=z8(w,L,0,L.length,C);if(!g){v.close();return}if(C+=g,C>N.size)return u("transfer_source_changed");z.update(L.subarray(0,g)),v.enqueue(L.subarray(0,g))}catch(L){throw D=L,L}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:O,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(N.size)}},{duplex:"half"}));if(D!==void 0)throw D;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(D!==void 0)throw D;return b1(v,$.signal,"transfer_upload_failed")}let _=R0(B,{bigint:!0});if(BigInt(C)!==N.size||_.size!==N.size||_.mtimeNs!==N.mtimeNs||_.ctimeNs!==N.ctimeNs)return u("transfer_source_changed");let j=z.digest("hex"),A=W8(B,$.signal);if(A.size_bytes!==C||A.sha256!==j)return u("transfer_source_changed");return{size_bytes:C,sha256:j,outcome:"copied"}}let G=$.payload.size_bytes,X=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>Y0||typeof X!=="string"||!/^[a-f0-9]{64}$/.test(X))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK)}catch(N){if(x1(N)!=="ENOENT")throw N}if(W!==void 0){try{let N=W8(W,$.signal);if(N.size_bytes===G&&N.sha256===X)return{...N,outcome:"already_present"}}finally{J1(W)}return u("transfer_destination_exists")}K=`.reason-copy-${B$()}`,B=Z.open(Q.fd,K,s.O_CREAT|s.O_EXCL|s.O_WRONLY|s.O_NOFOLLOW,384),N8(Q.fd,B);let Y;try{let N=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!N.ok||!N.body)return u("transfer_download_failed");Y=N.body.getReader()}catch(N){return b1(N,$.signal,"transfer_download_failed")}let U=E2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let N=await Y.read().catch((z)=>b1(z,$.signal,"transfer_download_failed"));if(N.done)break;if(F+=N.value.length,F>G)return u("transfer_size_mismatch");U.update(N.value);for(let z=0;z<N.value.length;)$.signal.throwIfAborted(),z+=W$(B,N.value,z,Math.min(S2,N.value.length-z))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||U.digest("hex")!==X)return u("transfer_hash_mismatch");return V$(B),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,K,Q.leaf),{size_bytes:G,sha256:X,outcome:"copied"}}finally{try{if(B!==void 0)J1(B)}finally{try{if(Q){if(K)try{Z.unlink(Q.fd,K)}catch{}J1(Q.fd)}}finally{Z.close()}}}}catch(J){return F$(J,$.signal,$.direction)}}import{spawn as D$}from"child_process";import{mkdtempSync as M$,rmSync as w$,writeFileSync as L$}from"fs";import{constants as j$,platform as O$,tmpdir as I$}from"os";import{join as M8}from"path";import{gunzipSync as C$,gzipSync as EK}from"zlib";var C8=900000,kK=C8+60000,Z1=49152,H8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),D8=V.object({version:V.literal(1),script_gzip:H8(163840),stdin_gzip:H8(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max(C8)}).strict(),k2=V.string().max(Z1+256),fK=V.object({exit_code:V.number().int().min(0).max(255),stdout:k2,stderr:k2,combined:k2.optional()}).strict();function f2($){return C$(Buffer.from($,"base64")).toString("utf8")}var A$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",T$=["RUSTUP_HOME","TZ","LC_ALL"],_$=2000,P$=100;function x2(){return O$()==="linux"&&process.geteuid?.()===0}function b2($){let J=Math.floor($/2),Z=[],Q=0,B=Buffer.alloc(0),K=0;return{push(G){K+=G.length;let X=G;if(Q<J){let W=X.subarray(0,J-Q);Z.push(W),Q+=W.length,X=X.subarray(W.length)}if(X.length)B=Buffer.concat([B,X]).subarray(-J)},text(){let G=K-Q-B.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
36
- [reason: ${G} bytes of output omitted]
37
- `:"")+B.toString("utf8")}}}async function w8($,J){if(!x2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=f2(Q.script_gzip),K=f2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=M$(M8(I$(),"reason-workspace-setup-"));try{let X=M8(G,"setup.sh");L$(X,B,{mode:384});let W={PATH:A$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of T$)if(process.env[A])W[A]=process.env[A];Object.assign(W,Q.env);let Y=D$("/bin/bash",[X],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),U=b2(Z1),F=b2(Z1),N=b2(Z1);Y.stdout.on("data",(A)=>{U.push(A),N.push(A)}),Y.stderr.on("data",(A)=>{F.push(A),N.push(A)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let z=(A)=>{try{if(Y.pid)process.kill(-Y.pid,A)}catch{}},C=!1,w,D=()=>{z("SIGTERM"),w??=setTimeout(()=>z("SIGKILL"),_$)},O=setTimeout(()=>{C=!0,D()},Q.timeout_ms);J.addEventListener("abort",D,{once:!0});let _=await new Promise((A,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(L,g)=>A({code:L,signal:g}))}).finally(()=>{clearTimeout(O),clearTimeout(w),J.removeEventListener("abort",D)});await new Promise((A)=>{let v=setTimeout(A,P$);Y.once("close",()=>{clearTimeout(v),A()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=C?124:_.signal?128+(j$.signals[_.signal]??0):_.code??1;return{exit_code:Math.min(255,j),stdout:U.text(),stderr:F.text(),...j!==0?{combined:N.text()}:{}}}finally{w$(G,{recursive:!0,force:!0})}}import{chmodSync as R$,mkdtempSync as q$,realpathSync as I8,rmSync as g$}from"fs";import{tmpdir as E$}from"os";import{dirname as S$,join as y2,sep as k$}from"path";function h2($){return O8($,j8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>S$(L8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(y2($,B));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${k$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function T8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=h2($.runtimeRoot);if(g0(Q)||g0(y2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=q$(y2(E$(),`reason-cloud-copy-${process.pid}-`));try{R$(Z,448);let Q=I8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let B=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return B}finally{g$(Z,{recursive:!0,force:!0})}}import{constants as I0}from"fs";import{closeSync as x7,existsSync as G0,fstatSync as y7,lstatSync as h7,mkdirSync as HQ,mkdtempSync as CQ,openSync as m7,readSync as DQ,realpathSync as X0,rmSync as MQ,statSync as C1,writeSync as wQ}from"fs";import{homedir as z1,platform as n,tmpdir as LQ}from"os";import{dirname as N1,isAbsolute as jQ,join as v7,relative as q3,resolve as OQ,sep as IQ}from"path";import{spawn as AQ}from"child_process";import{createHash as h$,randomBytes as m$}from"crypto";var m2=30000,f$=1800000,b$=5000,y1=30000,x$=m1+15000,_8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,y$=[/^\/app\/local-runtime\/operations\/claim$/,_8];class v2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(y$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},x$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let X=new Promise((W,Y)=>{let U=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)U();else Z.addEventListener("abort",U,{once:!0}),K.finally(()=>Z.removeEventListener("abort",U))});return await Promise.race([K,X])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(b$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(f$,m2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(h1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+m2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[B,K]of Q.pending){if(!_8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(m2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var u2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function VV($,J={}){let Z=v$($),Q=J.rootPathsSupported===!0?L1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((B)=>/^[a-f0-9]{64}$/.test(B))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function v$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,X]of Object.entries(B).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(X)||Array.isArray(X)&&X.length<=64&&X.every(J))K[G]=X}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function p$($){return $===408||$===429||$===500||$===502||$===503||$===504}function u$($){if($ instanceof F0)return!1;if($ instanceof v1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function d$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function l$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function GV($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return h$("sha256").update($??"").digest("hex")}function s$($){return k8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function q8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var c$=20000,n$=1e4,g8=[2000,4000],r$=30000,a$=15000;function E8($){return $?{keepalive:!1}:{}}class p2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class i${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=f8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??g8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof p2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new p2(Z)),Z):null;try{let X=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return b8(await this.parseResponse(X))}catch(X){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw X}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=c$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,g8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let X=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=n$?K:null,W=!X&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=X??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let U=R8(J),F=this.signProof("POST",$,Y.challenge,U);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":U,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>m$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),X=this.proofStore.sign(s$({method:$,route:J,timestamp:B,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(X))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:B,nonce:G,signature:X}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!S8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new v2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&P8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,X=this.proofOptions.sleep??l$,W=this.sessionFor($,J.device),Y=Math.max(r$,(J.holdMs??0)+a$),U={fresh:!1},F;for(let N=0;N<G;N+=1)try{let z=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(z)return await this.parseResponse(new Response(z.status===204?null:z.body,{status:z.status,headers:z.retryAfter===null?{}:{"retry-after":z.retryAfter}}));let C=new AbortController,w=setTimeout(()=>C.abort(new v1(Y)),Y),D=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let O=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,D,J.useSpareChallenge===!0&&N===0,N===0?J.issuedChallenge:void 0,U),_=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...O,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(U.fresh),signal:D});return await this.parseResponse(_)}catch(O){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw O}finally{clearTimeout(w)}}catch(z){if(F=z,z instanceof v1)U.fresh=!0;if(J.signal?.aborted)throw z;let C=J.device!==void 0&&z instanceof F0&&z.status===401&&["invalid_device_proof","device_proof_replayed"].includes(z.code),w=z instanceof F0&&p$(z.status),D=u$(z),O=J.transientRetryOwner!=="caller"&&(w||D);if((C||O)&&N+1<G){let _=C?0:d$(N,z,this.proofOptions.retryBaseDelayMs??500);if(_>0)await X(_,J.signal);continue}if(C&&N+1>=G)throw Error("Reason Device proof retry was exhausted.");throw z}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return x8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return y8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return h8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return m8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return v8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return p8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});d8(Q)}async localSubscription($,J,Z){return u8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!q8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return l8(K,u2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return s8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!q8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return c8(Q)}async completeOperation($,J,Z,Q){let B={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(P8(B)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return r8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-zhpake9f.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let B=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return n8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var o$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=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 p1($,J){if(o$.has($))return!1;if(B1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||B1.has($)))return!1;return!0}import{accessSync as t$,constants as e$,existsSync as $J,statSync as JJ}from"fs";import{basename as ZJ,isAbsolute as QJ}from"path";var K1=["-lic"],BJ="/bin/zsh",KJ=new Set(["zsh","bash"]),a8=20000,d2=60000,VJ=65536,GJ=64,XJ=8192,UJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),WJ=["DYLD_","LD_"];function YJ($){let J=$.toUpperCase();return UJ.has(J)||WJ.some((Z)=>J.startsWith(Z))}function i8($=process.env){return!0}function FJ($){if(!QJ($)||$.includes("\x00"))return!1;if(!KJ.has(ZJ($)))return!1;try{if(!JJ($).isFile())return!1;return t$($,e$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&FJ(J))return J;return BJ}function l2($=process.env){return i8($)&&$J(E0($))}function s2($=process.env){if(!i8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function c2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>VJ)throw new H("invalid_payload","command is missing or too large.");return $}function n2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>GJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>XJ)throw new H("invalid_payload","env entry is invalid or too large.");if(YJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function o8($){let J=$.processEnv??process.env;if(s2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=c2($.command),Q=E0(J),{forwarded:B,ignored:K}=n2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function t8($=process.env){return{transport:"shell",shell:`${E0($)} ${K1.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:d2}}import{readFile as zJ,readdir as NJ,readlink as HJ,realpath as CJ}from"fs/promises";import{basename as DJ,relative as MJ,sep as wJ}from"path";var w0="/proc",LJ=250,e8=500,jJ=50,OJ=250,IJ=1024,$5=4096,AJ=1,TJ=3,J5=9,_J="0A",PJ=/^socket:\[(\d+)\]$/,r2={readDirectory:($)=>NJ($),readLink:($)=>HJ($),readTextFile:($)=>zJ($,"utf8"),realPath:($)=>CJ($)};function Q5($,J){return J===$||J.startsWith(`${$}${wJ}`)}function RJ($,J){return MJ($,J)||"."}async function B5($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function K5($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,$5).split(`
38
- `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${w0}/${$}/cmdline`)).slice(0,$5).split("\x00",1)[0]?.trim();return Q?DJ(Q):null}catch{return null}}async function V5($,J=r2){let Z;try{Z=await J.readLink(`${w0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function G5($,J=r2){let Z=[];for(let Q of await B5(J)){if(Z.length>=LJ)break;let B=await V5(Q,J);if(!B||!Q5($,B))continue;Z.push({pid:Q,command:await K5(Q,J),cwd:RJ($,B)})}return{processes:Z}}function Z5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function qJ($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,B=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(B<0)B=W;continue}if(B>=0){let Y=W-B;if(Y>Q)Z=B,Q=Y;B=-1}}let K=J.map((W)=>W.toString(16));if(Q<2)return K.join(":");let G=K.slice(0,Z).join(":"),X=K.slice(Z+Q).join(":");return`${G}::${X}`}function gJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=Z5($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...Z5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${qJ(Z)}]:${J}`}return null}function EJ($,J){let Z=[];for(let Q of $.split(`
39
- `).slice(1)){if(Z.length>=J)break;let B=Q.trim().split(/\s+/);if(B.length<=J5)continue;if(B[TJ]?.toUpperCase()!==_J)continue;let K=B[AJ]??"",G=K.lastIndexOf(":");if(G<0)continue;let X=Number.parseInt(K.slice(G+1),16);if(!Number.isInteger(X)||X<=0||X>65535)continue;let W=gJ(K.slice(0,G),X),Y=B[J5];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:X,address:W})}return Z}async function SJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=e8)break;let Q;try{Q=await $.readTextFile(`${w0}/net/${Z}`)}catch{continue}J.push(...EJ(Q,e8-J.length))}return J}async function kJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await B5(J)){if(Z.size>=$.size)break;let B;try{B=await J.readDirectory(`${w0}/${Q}/fd`)}catch{continue}for(let K of B.slice(0,IJ)){let G;try{G=await J.readLink(`${w0}/${Q}/fd/${K}`)}catch{continue}let X=G.match(PJ)?.[1];if(!X||!$.has(X)||Z.has(X))continue;Z.set(X,Q)}}return Z}async function X5($,J=r2){let Z=await SJ(J),Q=await kJ(new Set(Z.map((U)=>U.inode)),J),B=[];for(let U of Z){let F=Q.get(U.inode);if(F===void 0)continue;B.push({pid:F,port:U.port,address:U.address})}B.sort((U,F)=>U.pid-F.pid||U.port-F.port||(U.address<F.address?-1:U.address>F.address?1:0));let K=[...new Set(B.map((U)=>U.pid))].slice(0,jJ),G=await Promise.all(K.map(async(U)=>[U,await V5(U,J)])),X=new Map(G),W=B.filter((U)=>{let F=X.get(U.pid);return Boolean(F&&Q5($,F))}),Y=new Map(await Promise.all([...new Set(W.map((U)=>U.pid))].map(async(U)=>[U,await K5(U,J)])));return{ports:W.slice(0,OJ).map((U)=>({pid:U.pid,command:Y.get(U.pid)??null,address:U.address}))}}import{posix as i2}from"path";var u1=200,fJ=250,bJ=250;async function d1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],B=null;for(let K of Z.stdout.split(/\r?\n/))if(K.startsWith("p")){let G=Number(K.slice(1));if(B=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,B)Q.push(B)}else if(B&&K.startsWith("c"))B.command=K.slice(1)||null;else if(B&&K.startsWith("n"))B.names.push(K.slice(1));return Q}function a2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var U5="/System/Volumes/Data",xJ=["/tmp","/var","/etc"];function o2($){let J=i2.normalize($);if(J.startsWith(`${U5}/`))J=J.slice(U5.length);return xJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function W5($){return $&&i2.isAbsolute($)?o2($):null}async function Y5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=u1){let B=J.slice(Q,Q+u1).join(",");for(let K of await d1($,["-a","-p",B,"-d","cwd","-Fpcn"]))Z.set(K.pid,{command:K.command,cwd:W5(K.names[0])})}return Z}async function F5($,J){let Z=o2($),Q=(await d1(J,["-d","cwd","-Fpn"])).filter((K)=>{let G=W5(K.names[0]);return G!==null&&a2(Z,G)}).map((K)=>K.pid).slice(0,fJ),B=await Y5(J,Q);return{processes:Q.flatMap((K)=>{let G=B.get(K);return G?.cwd&&a2(Z,G.cwd)?[{pid:K,command:G.command,cwd:i2.relative(Z,G.cwd)||"."}]:[]})}}async function z5($,J){let Z=o2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],B=await d1(J,Q),K=await Y5(J,B.map((Y)=>Y.pid)),G=B.map((Y)=>Y.pid).filter((Y)=>{let U=K.get(Y)?.cwd;return Boolean(U&&a2(Z,U))});if(G.length===0)return{ports:[]};let X=new Set(B.flatMap((Y)=>Y.names.map((U)=>`${Y.pid} ${U}`))),W=[];for(let Y=0;Y<G.length;Y+=u1){let U=G.slice(Y,Y+u1).join(",");for(let F of await d1(J,["-a","-p",U,...Q]))for(let N of F.names)if(X.has(`${F.pid} ${N}`))W.push({pid:F.pid,command:F.command,address:N})}return{ports:W.slice(0,bJ)}}import{join as aJ}from"path";import{spawn as dJ}from"child_process";import{randomUUID as lJ}from"crypto";import{chmodSync as C5,lstatSync as D5,mkdirSync as sJ,readdirSync as cJ,statSync as nJ,unlinkSync as rJ}from"fs";import{join as e2}from"path";var t2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var l1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var L0=()=>{throw Error("proof_visual_contract_invalid")};class N5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function hJ($){if(!V1($)||$.version!==1)return L0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new N5;if(!V1($.viewport)||!l1($.viewport.width,1,4096)||!l1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>t2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return L0();let J=$.targets.map((Q)=>{if(!V1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((B)=>!["id","selector"].includes(B)))return L0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return L0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return L0();Z=$.additionalViewports.map((B)=>{if(!V1(B)||!l1(B.width,1,4096)||!Number.isInteger(B.width)||!l1(B.height,1,4096)||!Number.isInteger(B.height)||Object.keys(B).some((K)=>!["width","height"].includes(K)))return L0();return{width:B.width,height:B.height}});let Q=[$.viewport,...Z].map((B)=>`${B.width}x${B.height}`);if(new Set(Q).size!==Q.length)return L0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var vJ=["organizationId","userId","sessionId","runId"],pJ=[...vJ,"prUrl","headSha","skillDigest","evidenceKind"],_V=[...pJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var uJ={"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 H5($){return uJ[$].directory}var M5=10485760;function w5($={}){let J=$.directory??H5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let B=Q?.seconds;if(!Number.isInteger(B)||Number(B)<1||Number(B)>15||!Q||Object.keys(Q).some((D)=>D!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");sJ(J,{recursive:!0,mode:457});let K=D5(J);if(!K.isDirectory()||K.isSymbolicLink()||K.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");C5(J,457);let G=cJ(J).filter((D)=>/^[a-f0-9-]{36}\.webm$/.test(D)).map((D)=>({name:D,time:nJ(e2(J,D)).mtimeMs})).sort((D,O)=>O.time-D.time);for(let D of G.slice(9))rJ(e2(J,D.name));let X=e2(J,`${lJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??dJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(B),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(M5),"-progress","pipe:1",X],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),U,F,N=!1,z=new Promise((D,O)=>{U=D,F=O});Y.stdout.on("data",(D)=>{if(/frame=\s*[1-9]/.test(String(D)))N=!0,U()});let C=new Promise((D,O)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),O(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(_)=>{try{if(_!==0&&_!==255)throw Error();let j=D5(X);if(!N||!j.isFile()||j.isSymbolicLink()||j.uid!==process.getuid?.()||j.size<128||j.size>M5+65536)throw Error();C5(X,420),U(),D({path:X,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),O(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(B)+5)*1000);C.finally(()=>clearTimeout(w)).catch(()=>{}),Z={done:C,stop:()=>{return Y.kill("SIGINT"),C}};try{await z}catch(D){throw Z=null,D}return{recording:!0,seconds:Number(B)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function O5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??L5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let B=aJ($.runtimeDirectory,"recordings"),K=null;return{async start(G){let X=await(J.desktop??j5)();return K??=w5({directory:B,display:X.display,ffmpeg:Q,env:{HOME:g1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:X.xauthority},...J.spawn?{spawn:J.spawn}:{}}),K.start(G)},async stop(){if(!K)throw Error("cloud_browser_recording_not_started");return K.stop()},async close(){await K?.close()}}}import{spawn as M3}from"child_process";import{createHash as HZ,randomUUID as CZ}from"crypto";import{existsSync as Q0,mkdirSync as z3,mkdtempSync as w3,readdirSync as e1,readFileSync as L3,renameSync as DZ,rmSync as U1,statSync as a1,writeFileSync as MZ}from"fs";import{homedir as j3,tmpdir as l5}from"os";import{basename as s5,dirname as N3,join as E,relative as c5,resolve as H3,sep as n5}from"path";var i=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),s1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),I5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),J3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),Z3=["home","lock","side_button","siri","apple_pay"],iJ=V.enum(["tree","screenshot","both","none"]),oJ=V.object({...J3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),H0={observe:iJ.optional(),wait_for:oJ.optional(),timeout:V.number().min(0).max(20).optional()},$3=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...J3.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(Z3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),Q3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:i}).strict(),V.object({action:V.literal("shutdown"),device:i}).strict(),V.object({action:V.literal("build"),path:s1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:s1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),steps:V.array(V.lazy(()=>$3)).max(30).optional(),...H0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:i.optional(),app_path:s1.optional(),bundle_id:I5.optional(),steps:V.array(V.lazy(()=>$3)).max(30).optional(),...H0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:i.optional(),bundle_id:I5}).strict(),V.object({action:V.literal("logs"),device:i.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:i.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:s1.optional()}).strict(),V.object({action:V.literal("chrome"),device:i.optional()}).strict(),V.object({action:V.literal("inspect"),device:i.optional()}).strict(),V.object({action:V.literal("tap"),device:i.optional(),x:Z0.optional(),y:Z0.optional(),...J3.shape,duration:V.number().min(0).max(10).optional(),...H0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:i.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...H0}).strict(),V.object({action:V.literal("type"),device:i.optional(),text:V.string().min(1).max(4000),...H0}).strict(),V.object({action:V.literal("button"),device:i.optional(),name:V.enum(Z3),...H0}).strict(),V.object({action:V.literal("open_url"),device:i.optional(),url:V.string().min(1).max(4000),...H0}).strict(),V.object({action:V.literal("steps"),device:i.optional(),steps:V.array($3).min(1).max(30),...H0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),A5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),sV=V.object({text:V.string(),error:V.string().optional(),device:A5.optional(),devices:V.array(A5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var cV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),c1={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:[...Z3],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."}},_5=Q3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),tJ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},T5=new Set;function eJ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...c1.steps,minItems:1}:c1[$];if(Z===void 0||T5.has($))return Q;return T5.add($),{...Q,description:Z}}var $Z=_5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((B)=>Object.hasOwn(c1,B)),Q=Z.filter((B)=>!$[B].safeParse(void 0).success);return(tJ[J]??[{required:[]}]).map((B)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((K)=>!B.without?.includes(K)).map((K)=>[K,eJ(K,J)])]),required:["action",...Q,...B.required],additionalProperties:!1}))}),JZ={type:"object",properties:{action:{type:"string",enum:_5.map(($)=>$.action.value)},...c1},required:["action"],additionalProperties:!1},nV={...JZ,anyOf:$Z};import{spawn as G3}from"child_process";import{createHash as QZ}from"crypto";import{existsSync as K3,mkdirSync as n1,mkdtempSync as BZ,readdirSync as P5,readFileSync as R5,renameSync as KZ,rmSync as q5,symlinkSync as V3,writeFileSync as G1}from"fs";import{homedir as VZ}from"os";import{dirname as k5,join as f}from"path";import{createInterface as GZ}from"readline";var B3=`// 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 g5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",XZ=180000,UZ=15000,WZ=30000,YZ=600000,FZ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
499
- @end
500
- `).join("");function E5($,J,Z){return new Promise((Q)=>{let B=G3($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),K="";B.stdout.on("data",(G)=>{K+=G}),B.stderr.on("data",(G)=>{K+=G}),B.once("error",(G)=>Q({code:-1,output:String(G)})),B.once("close",(G)=>Q({code:G??-1,output:K}))})}var S5=new Map;function X3($){let J=f(k5($),"Frameworks"),Z=S5.get(J);if(!Z)S5.set(J,Z=zZ(J));return Z}async function zZ($){if(process.platform!=="darwin"||!K3(f($,"FBSimulatorControl.framework")))return null;let J=await E5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=QZ("sha256").update(B3).update(J.output).update($).digest("hex").slice(0,16),Q=f(VZ(),".local","share","reason","simulator","host"),B=f(Q,Z,"simulator-host");if(K3(B))return B;n1(Q,{recursive:!0,mode:448});let K=BZ(f(Q,".staging-"));try{let G=f(K,"Frameworks"),X=f(G,"FBSimulatorControl.framework"),W=f(X,"Modules","FBSimulatorControl.swiftmodule");n1(W,{recursive:!0});for(let w of P5($))if(w!=="FBSimulatorControl.framework")V3(f($,w),f(G,w));let Y=f($,"FBSimulatorControl.framework");V3(f(Y,"FBSimulatorControl"),f(X,"FBSimulatorControl")),V3(f(Y,"Headers"),f(X,"Headers")),G1(f(X,"Modules","module.modulemap"),R5(f(Y,"Modules","module.modulemap")));let U=R5(f(Y,"Modules","FBSimulatorControl.swiftmodule",`${g5}.swiftinterface`),"utf8");G1(f(W,`${g5}.swiftinterface`),U.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let F=f(K,"include","CoreSimulator");n1(F,{recursive:!0}),G1(f(F,"module.modulemap"),`module CoreSimulator {
501
- header "CoreSimulator.h"
502
- export *
503
- }
504
- `),G1(f(F,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
505
- ${FZ}`);let N=f(K,"main.swift");G1(N,B3);let z=f(K,"simulator-host"),C=await E5("xcrun",["swiftc","-O","-F",G,"-I",f(K,"include"),"-module-cache-path",f(K,"cache"),"-Xlinker","-rpath","-Xlinker",$,N,"-o",z],XZ);if(C.code!==0||!K3(z))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
506
- ${C.output.slice(-2000)}
507
- `),null;n1(k5(B),{recursive:!0}),KZ(z,B);for(let w of P5(Q))if(w!==Z&&!w.startsWith(".staging-"))q5(f(Q,w),{recursive:!0,force:!0});return B}catch{return null}finally{q5(K,{recursive:!0,force:!0})}}class X1 extends Error{}class k0 extends Error{}class f5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;GZ({input:$.stdout}).on("line",(Q)=>{let B;try{B=JSON.parse(Q)}catch{return}let K=this.pending.get(Number(B.id));if(!K)return;if(this.pending.delete(Number(B.id)),clearTimeout(K.timer),B.ok===!0)K.resolve(B);else K.reject(new X1(String(B.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new k0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let B=setTimeout(()=>{this.pending.delete(J),Q(new k0("The simulator host did not answer.")),this.close()},WZ);this.pending.set(J,{resolve:Z,reject:Q,timer:B}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
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(),YZ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new k0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var S0=new Map;async function r1($,J,Z=!1){let Q=S0.get(J);if(!Q){let B={started:NZ($,J)};S0.set(J,Q=B),B.started.then((K)=>{if(B.host=K,!K&&S0.get(J)===B)S0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function NZ($,J){let Z=await X3($);if(!Z)return null;let Q=G3(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let X=setTimeout(()=>G(!1),UZ);Q.stdout.once("data",(W)=>{clearTimeout(X),G(String(W).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(X),G(!1)}),Q.once("error",()=>{clearTimeout(X),G(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let K=new f5(Q,()=>{let G=S0.get(J);if(G&&(G.host===K||G.host===void 0))S0.delete(J)});return K}function b5($,J,Z,Q,B){return G3($,["stream",J,String(Z),String(Math.round(Q)),String(B)],{stdio:["pipe","pipe","ignore"]})}var f0={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"},wZ=50000,LZ=112640,jZ=174080,U3=2,OZ=60000,IZ=2000,AZ=300,TZ=40,_Z=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function y0($,J,Z={}){return new Promise((Q,B)=>{let K=M3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],X=[];K.stdout.on("data",(Y)=>G.push(Y)),K.stderr.on("data",(Y)=>X.push(Y));let W=setTimeout(()=>K.kill("SIGKILL"),Z.timeoutMs??wZ);K.on("error",(Y)=>{clearTimeout(W),B(Y)}),K.on("close",(Y)=>{clearTimeout(W),Q({code:Y??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(X).toString("utf8")})})})}function k($,J){throw new H($,J)}async function c($,J,Z,Q={}){let B=await y0($,J,Q);if(B.code!==0)k("simulator_command_failed",`${Z} failed: ${(B.stderr||B.stdout).trim().slice(-1500)}`);return B.stdout}function W1(){return process.platform==="darwin"&&Q0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Q0("/usr/bin/xcrun")}var W3=null;function j0(){return E(j3(),".local","share","reason","simulator","axe")}function O3(){let $=E(j0(),f0.version,"axe");if(Q0($))return Promise.resolve($);return W3??=(async()=>{z3(j0(),{recursive:!0,mode:448});let J=w3(E(j0(),".staging-"));try{let Z=E(J,"axe.tgz");await d5(f0.url,f0.sha256,Z);let Q=E(J,"tree");if(z3(Q),await c("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!Q0(E(Q,"axe"))||!Q0(E(Q,"Frameworks")))k("simulator_axe_missing","The AXe archive has an unexpected layout.");U1(E(j0(),f0.version),{recursive:!0,force:!0}),DZ(Q,E(j0(),f0.version));for(let B of e1(j0()))if(B!==f0.version&&!B.startsWith(".staging-"))U1(E(j0(),B),{recursive:!0,force:!0});return $}finally{U1(J,{recursive:!0,force:!0}),W3=null}})(),W3}var r5=O3;async function a5($){let J=await O3().catch(()=>null);return J?r1(J,$.udid).catch(()=>null):null}async function i1($,J,Z){let Q=await O3().catch(()=>k("simulator_axe_missing","AXe could not be installed on this Mac.")),B=await y0(Q,[...$,"--udid",J]);if(B.code===0)return B.stdout;let K=(B.stderr||B.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(K))k("simulator_element_not_found",K.slice(-500));return k("simulator_command_failed",`${Z} failed: ${K.slice(-1500)}`)}function PZ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function RZ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function I3(){let J=JSON.parse(await c("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,B]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let K of B){if(K.isAvailable===!1)continue;let G=K.name.toLowerCase();if(K.deviceTypeIdentifier)C3.set(K.udid,K.deviceTypeIdentifier);Z.push({udid:K.udid,name:K.name,runtime:PZ(Q),state:RZ(K.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,B)=>Number(B.state==="booted")-Number(Q.state==="booted")||B.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(B.name))}var C3=new Map,D3=null;async function t($,J){let Z=await I3(),Q;if($){let B=Z.filter((K)=>K.udid===$||K.name===$);if(Q=B.find((K)=>K.state==="booted")??B[0],!Q)k("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let B=Z.filter((K)=>K.state==="booted");if(Q=B.find((K)=>K.udid===D3)??B.find((K)=>K.kind==="iphone")??B[0],!Q)k("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")k("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return D3=Q.udid,Q}function y($){return`${$.name} (${$.runtime})`}async function qZ($){if($.state!=="booted"){let J=await y0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))k("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await c("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return D3=$.udid,{...$,state:"booted"}}function A3($,J){let Z=H3($,J),Q=c5($,Z);if(Q.startsWith("..")||Q.startsWith(n5)||H3($,Q)!==Z)k("simulator_path_outside_root",`${J} is outside this machine's granted folder (${$}). Pass a path inside it, or one relative to it.`);return Z}var x5=4,gZ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function EZ($){let J=[],Z=(Q,B)=>{let K;try{K=e1(Q)}catch{return}if(K.includes("project.yml")||K.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(B>=x5)return;for(let G of K.sort()){if(G.startsWith(".")||gZ.has(G))continue;let X=E(Q,G);try{if(a1(X).isDirectory())Z(X,B+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)k("simulator_project_not_found",`No Xcode project or project.yml within ${x5} folders of ${$}; pass path.`);return k("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>c5($,Q)||".").join(", ")}.`)}var x0=new Map;async function SZ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:N3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:N3($)};if(!a1($).isDirectory())k("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(B)=>e1($).filter((K)=>K.endsWith(B)).sort();if(Q0(E($,"project.yml")))await c("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((B)=>Q0("/opt/homebrew/bin/xcodegen")?c("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(B));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:E($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:E($,Q),dir:$};return k("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function i5($){let J=JSON.parse(await c("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function kZ($){let J=(await i5($))[0];if(!J)k("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function fZ($){let J=[],Z=new Set;return $.forEach((Q,B)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let K=$.slice(B+1,B+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...K].join(`
509
- `).slice(0,800))}),J}async function bZ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((K)=>K.includes("does not contain a scheme named"))){let K=await i5(Z).catch(()=>[]);if(K.length)$.log.push(`error: this project's schemes are: ${K.join(", ")}`)}$.status="failed";return}let Q=E($.productsDir,`${$.configuration}-iphonesimulator`),B=Q0(Q)?e1(Q).filter((K)=>K.endsWith(".app")).map((K)=>E(Q,K)).sort((K,G)=>a1(G).mtimeMs-a1(K).mtimeMs):[];if($.appPath=B[0],$.appPath)$.bundleId=await e5($.appPath).catch(()=>{return});if($.status=$.appPath?"succeeded":"failed",!$.appPath)$.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function y5($,J){let Z=$.path?A3(J,$.path):EZ(J),Q=await SZ(Z),B=$.scheme??await kZ(Q),K=$.configuration??"Debug",G=await t($.device,{booted:!1}).catch(()=>null),X=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",W=HZ("sha256").update(Q.path).digest("hex").slice(0,16),Y=E(j3(),"Library","Caches","reason","simulator-builds",W),U={id:`build-${CZ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:E(Y,"Build","Products"),configuration:K};x0.set(U.id,U);for(let[C,w]of x0)if(x0.size>20&&w.status!=="running")x0.delete(C);let F=M3("xcodebuild",[Q.flag,Q.path,"-scheme",B,"-configuration",K,"-destination",X,"-derivedDataPath",Y,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),N="",z=(C)=>{let w=(N+C.toString("utf8")).split(`
510
- `);if(N=w.pop()??"",U.log.push(...w),U.log.length>5000)U.log.splice(0,U.log.length-5000)};return F.stdout.on("data",z),F.stderr.on("data",z),F.on("error",(C)=>{U.log.push(`error: ${C.message}`),U.status="failed",U.ended=Date.now()}),F.on("close",(C)=>{if(N)U.log.push(N);bZ(U,C??-1,Q)}),{text:`Build ${U.id} started: ${B} (${K}) for ${G?y(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:o5(U)}}function o5($){return{id:$.id,status:$.status,errors:fZ($.log),log_tail:$.log.slice(-TZ).join(`
511
- `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var xZ=45000,yZ=30000;async function Y3($,J=xZ){let Z=Date.now()+J;while(x0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=t5($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function t5($){let J=x0.get($);if(!J)k("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=o5(J);return{text:J.status==="running"?`Build ${$} is running (${Math.round(Z.elapsed_ms/1000)} s).`:J.status==="succeeded"?`Build ${$} succeeded: ${J.appPath}. Launch it with app_path.`:`Build ${$} failed with ${Z.errors.length} error(s).`,build:Z}}async function e5($){return(await c("plutil",["-extract","CFBundleIdentifier","raw","-o","-",E($,"Info.plist")],"Reading the bundle id")).trim()}var C0=new Map;function hZ($,J){C0.get($.udid)?.stop();let Z=M3("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",$.udid,J],{stdio:["ignore","pipe","pipe"]}),Q={udid:$.udid,bundleId:J,lines:[],first:0,stop:()=>Z.kill("SIGTERM")};C0.set($.udid,Q);let B="",K=(G)=>{let X=(B+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
512
- `);B=X.pop()??"",Q.lines.push(...X);let W=Q.lines.length-IZ;if(W>0)Q.lines.splice(0,W),Q.first+=W};return Z.stdout.on("data",K),Z.stderr.on("data",K),new Promise((G)=>{let X=setTimeout(()=>G(null),15000),W=()=>{let Y=Q.lines.concat(B).join(`
513
- `).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(Y)clearTimeout(X),G(Number(Y))};Z.stdout.on("data",W),Z.on("close",()=>{clearTimeout(X),G(null)})})}async function mZ($,J){let Z=await t($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let K=vZ(J,$.app_path);await c("xcrun",["simctl","install",Z.udid,K],`Installing ${s5(K)}`),Q=await e5(K)}if($.bundle_id){if((await y0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)k("simulator_app_not_installed",`${$.bundle_id} is not installed on ${y(Z)}.`)}let B=await hZ(Z,Q);if(B===null){let K=C0.get(Z.udid)?.lines.slice(-20).join(`
514
- `)??"";k("simulator_launch_failed",`${Q} did not start on ${y(Z)}.${K?`
515
- ${K}`:""}`)}return{text:`Launched ${Q} on ${y(Z)} (pid ${B}). Its console is captured; read it with logs.`,device:Z}}function vZ($,J){let Z=H3(J),Q=E(j3(),"Library","Caches","reason","simulator-builds")+n5;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:A3($,Z)}function pZ($,J){let Z=C0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${y($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-AZ),B=Z.lines.slice(Q-Z.first).map((K)=>K.slice(0,2000));return{text:`${B.length} console line(s) from ${Z.bundleId} on ${y($)}.`,logs:{lines:B,next:Z.first+Z.lines.length}}}var o1=new Map;function h5($,...J){let Z=o1.get($.udid);if(!Z)return;for(let[Q,B]of J)if(Q>Z.width||B>Z.height)k("simulator_point_off_screen",`(${Q}, ${B}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function m5($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function T3($,J=1,Z){let Q=w3(E(l5(),"reason-sim-"));try{let B=E(Q,"screen.png");if(await c("xcrun",["simctl","io",$.udid,"screenshot","--type=png",B],"Taking a screenshot"),Z){z3(N3(Z),{recursive:!0});let z=await c("sips",["-g","pixelWidth","-g","pixelHeight",B],"Reading the screenshot size"),C=Number(z.match(/pixelWidth: (\d+)/)?.[1]),w=Number(z.match(/pixelHeight: (\d+)/)?.[1]),D=2/m5($,C);await c("sips",["-z",String(Math.round(w*D)),String(Math.round(C*D)),B,"--out",Z],"Saving the screenshot")}let K=await c("sips",["-g","pixelWidth","-g","pixelHeight",B],"Reading the screenshot size"),G=Number(K.match(/pixelWidth: (\d+)/)?.[1]),X=Number(K.match(/pixelHeight: (\d+)/)?.[1]),W=m5($,G),Y=Math.round(G/W),U=Math.round(X/W);o1.set($.udid,{width:Y,height:U});let F=Buffer.alloc(0),N=J===2?jZ:LZ;for(let z of[70,50,35]){let C=E(Q,`screen-${z}.jpg`);if(await c("sips",["-z",String(U*J),String(Y*J),"-s","format","jpeg","-s","formatOptions",String(z),B,"--out",C],"Encoding the screenshot"),F=L3(C),F.byteLength<=N)break}return{text:`Screenshot of ${y($)} at ${Y}x${U} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:F.toString("base64"),width:Y,height:U}}}finally{U1(Q,{recursive:!0,force:!0})}}async function uZ($){let J=await a5($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return i1(["describe-ui"],$.udid,"Reading the accessibility tree")}async function t1($){let J=JSON.parse(await uZ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(B,K,G="")=>{let X=(B.role??B.type??"?").replace(/^AX/,""),W=B.AXLabel||B.title||"",Y=B.AXValue?` value="${String(B.AXValue).slice(0,120)}"`:"",U=B.AXUniqueId?` id=${B.AXUniqueId}`:"";if(B.AXUniqueId)Z.ids.add(B.AXUniqueId);if(W)Z.labels.add(W);let F=B.frame;if(X==="Application"&&F&&!Z.bounds)Z.bounds={width:F.width,height:F.height};if(F&&F.width>0&&F.height>0&&(B.AXUniqueId||B.AXLabel))Z.targets.push({...B.AXUniqueId?{id:B.AXUniqueId.trim()}:{},...B.AXLabel?{label:B.AXLabel.trim()}:{},role:X,frame:F});let N=Boolean(W||U||Y||!["Group","Other"].includes(X));if(N){let z=`${" ".repeat(Math.min(K,12))}${X} "${W.slice(0,160)}"${U}${Y}`+(F?` (${Math.round(F.x)},${Math.round(F.y)} ${Math.round(F.width)}x${Math.round(F.height)})`:"")+(B.enabled===!1?" disabled":"");Z.lines.push(z);let C=X==="Image"&&!U,w=(X==="StaticText"||X==="Image")&&!U&&W!==""&&G.includes(W);if(!C&&!w)Z.compact.push(z)}for(let z of B.children??[])Q(z,N?K+1:K,W||G)};for(let B of J)Q(B,0);return Z}function $6($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
516
- `);return Q.length>J?`${Q.slice(0,J)}
517
- \u2026 (truncated)`:Q}async function dZ($){let J=await t1($);return{text:`Accessibility tree of ${y($)} (frames in points; tap by id or label):
518
- ${$6(J,OZ)}`,device:$}}var lZ=450,sZ=1e4;function cZ($,J){let Z=J.id?$.ids.has(J.id):[...$.labels].some((Q)=>Q===J.label||Q.includes(J.label));return J.gone?!Z:Z}async function O0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let B=null,K="";if(J.wait_for){let X=Date.now()+(J.timeout??5)*1000,W=J.wait_for,Y=W.id?`id ${W.id}`:`"${W.label}"`;for(;;){if(B=await t1($),cZ(B,W)){K=` ${Y} is ${W.gone?"gone":"on screen"}.`;break}if(Date.now()>=X){K=W.gone?` Waited ${J.timeout??5} s: ${Y} is still on screen.`:` Waited ${J.timeout??5} s: ${Y} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(lZ);let G={...Z,text:`${Z.text}${K}`};if(Q==="tree"||Q==="both")B??=await t1($),G.screen=$6(B,sZ,!0),G.text+=`
519
- Screen now:
520
- ${G.screen}`;if(Q==="screenshot"||Q==="both"){let X=await T3($);G.image=X.image}return G}function v5($){return`'${$.replace(/'/g,"'\\''")}'`}function nZ($){switch($.action){case"tap":if($.x!==void 0&&$.y!==void 0)return $.duration?`touch -x ${$.x} -y ${$.y} --down --up --delay ${$.duration}`:`tap -x ${$.x} -y ${$.y}`;return $.id?`tap --id ${v5($.id)}`:`tap --label ${v5($.label)}`;case"swipe":return`swipe --start-x ${$.x} --start-y ${$.y} --end-x ${$.x2} --end-y ${$.y2} --duration ${$.duration??0.3}`;case"button":return`button ${$.name.replace("_","-")}`;case"sleep":return`sleep ${$.seconds}`}}var J6=0.35,rZ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function aZ($,J){let Z=$.targets.filter((Y)=>J.id!==void 0?Y.id===J.id.trim():Y.label===J.label?.trim()),Q=(Y)=>({x:Y.frame.x+Y.frame.width/2,y:Y.frame.y+Y.frame.height/2}),B=$.bounds,K=B?Z.filter((Y)=>{let{x:U,y:F}=Q(Y);return U>=0&&F>=0&&U<=B.width&&F<=B.height}):Z,G=K.length?K:Z,X=G.filter((Y)=>rZ.has(Y.role)),W=(X.length?X:G)[0];return W?Q(W):null}async function iZ($,J,Z,Q,B){let K=Date.now()+Z*1000;for(;;){let G=aZ(await t1($),J);if(G)return G;if(Date.now()>=K){let X=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return k("simulator_element_not_found",`Error: Step ${Q} 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
- (${Q-1} of ${B} steps had completed.)`)}await Bun.sleep(250)}}async function b0($,J,Z){let Q=await a5($);if(!Q)return p5($,J,Z);for(let[B,K]of J.entries()){try{switch(K.action){case"tap":{let X=K.x!==void 0&&K.y!==void 0?{x:K.x,y:K.y}:await iZ($,K,Z,B+1,J.length);await Q.call(K.duration?{op:"tap",...X,duration:K.duration}:{op:"tap",...X});break}case"swipe":await Q.call({op:"swipe",x:K.x,y:K.y,x2:K.x2,y2:K.y2,duration:K.duration??0.3});break;case"button":await Q.call({op:"button",name:K.name});break;case"type":await Q.call({op:"text",text:K.text}).catch((X)=>X instanceof X1?i1(["type",K.text],$.udid,`Step ${B+1} (typing)`):Promise.reject(X));break;case"sleep":await Bun.sleep(K.seconds*1000);break}}catch(X){if(X instanceof k0)return await p5($,J.slice(B),Z),`Ran ${J.length} step(s) on ${y($)}.`;if(X instanceof X1)k("simulator_command_failed",`Step ${B+1} failed: ${X.message}
523
- (${B} of ${J.length} steps had completed.)`);throw X}let G=J[B+1];if(K.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(J6*1000)}return`Ran ${J.length} step(s) on ${y($)}.`}async function p5($,J,Z){let Q=[],B=[],K=0,G=0,X=async()=>{if(Q.length===0)return;let W=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let Y of Q)W.push("--step",Y);try{await i1(W,$.udid,`Steps ${G+1}-${G+K}`)}catch(Y){if(Y instanceof H){let U=Y.message.replace(/Step (\d+) failed/,(F,N)=>{let z=B[Number(N)-1];return z?`Step ${z} failed`:F});k(Y.code,`${U}
524
- (${G} of ${J.length} steps had completed before this batch.)`)}throw Y}G+=K,Q=[],B=[],K=0};for(let[W,Y]of J.entries()){if(Y.action==="type"){await X(),await i1(["type",Y.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(nZ(Y)),K+=1,B.push(W+1);let U=J[W+1];if(Y.action!=="sleep"&&U&&U.action!=="sleep")Q.push(`sleep ${J6}`),B.push(W+1)}return await X(),`Ran ${J.length} step(s) on ${y($)}.`}var oZ=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],u5=new Map,tZ=`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 F3($,J,Z){let Q=await c("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),B=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),K=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)B=B*Z/K,K=Z;let G=w3(E(l5(),"reason-chrome-"));try{let X=E(G,"render.js"),W=E(G,"out.png");if(MZ(X,tZ),await c("osascript",["-l","JavaScript",X,$,W,String(Math.max(1,Math.round(B*J))),String(Math.max(1,Math.round(K*J)))],"Rendering the frame"),!Q0(W))k("simulator_command_failed",`Rendering ${s5($)} produced no image.`);return{image:L3(W).toString("base64"),width:B,height:K}}finally{U1(G,{recursive:!0,force:!0})}}async function eZ($){if(!C3.has($.udid))await I3();let J=C3.get($.udid),Q=JSON.parse(await c("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((B)=>B.identifier===J)?.bundlePath;if(!Q)k("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function $Q($){let J=await eZ($),Z=o1.get($.udid)??($.state==="booted"?(await T3($),o1.get($.udid)):void 0);if(!Z)k("simulator_not_booted",`${$.name} is not booted.`);let Q=u5.get(J);if(Q)return{text:`Frame of ${y($)}.`,device:$,chrome:Q};let B=E(J,"Contents","Resources"),K=JSON.parse(await c("plutil",["-convert","json","-o","-",E(B,"profile.plist")],"Reading the device profile")),G=K.framebufferMask?E(B,`${K.framebufferMask}.pdf`):null,X=G&&Q0(G)?await F3(G,U3,Z.height):null,W=K.chromeIdentifier?.split(".").pop(),Y=W?E("/Library/Developer/DeviceKit/Chrome",`${W}.devicechrome`,"Contents","Resources"):"";if(!W||!Q0(E(Y,"chrome.json")))k("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let U=JSON.parse(L3(E(Y,"chrome.json"),"utf8")),F={};for(let _ of oZ){let j=U.images[_];if(!j)k("simulator_command_failed",`${$.name}'s frame has no ${_} piece.`);F[_]=await F3(E(Y,`${j}.pdf`),U3)}let{sizing:N}=U.images,z={top:N.topHeight,left:N.leftWidth,bottom:N.bottomHeight,right:N.rightWidth},C=Z.width+z.left+z.right,w=Z.height+z.top+z.bottom,D=[];for(let _ of U.inputs??[]){let j=E(Y,`${_.image}.pdf`);if(!Q0(j))continue;let A=await F3(j,U3),{x:v,y:L}=_.offsets.normal,g=(l,m,D1)=>l<0?m+l-D1:l,P=_.anchor==="left"?{x:v-A.width,y:g(L,w,A.height)}:_.anchor==="right"?{x:C+v,y:g(L,w,A.height)}:_.anchor==="top"?{x:g(v,C,A.width),y:L-A.height}:{x:g(v,C,A.width),y:w+L};D.push({name:_.name,image:A.image,...P,width:A.width,height:A.height})}let O={identifier:U.identifier,screen:{width:Z.width,height:Z.height},inset:z,padding:U.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:F,buttons:D,...X?{screen_mask:X.image}:{}};return u5.set(J,O),{text:`Frame of ${y($)}.`,device:$,chrome:O}}var JQ=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 Y1($){try{return await Z6($)}catch(J){if(J instanceof H&&JQ.has(J.code))return{text:J.message,error:J.code};throw J}}async function Z6($){if(!W1())k("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=Q3.safeParse($.payload);if(!J.success)k("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await I3(),B=Q.filter((K)=>K.state==="booted");return{text:`${B.length} booted (${B.map(y).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await qZ(await t(Z.device,{booted:!1}));return{text:`${y(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await t(Z.device,{booted:!1});C0.get(Q.udid)?.stop(),C0.delete(Q.udid);let B=await y0("xcrun",["simctl","shutdown",Q.udid]);if(B.code!==0&&!/current state: Shutdown/i.test(B.stderr))k("simulator_command_failed",B.stderr.trim().slice(-1000));return{text:`${y(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await y5(Z,$.root);return Z.wait&&Q.build?Y3(Q.build.id):Q}case"build_status":return Z.wait?Y3(Z.build_id):t5(Z.build_id);case"run":{let Q=await y5({...Z,action:"build"},$.root),B=await Y3(Q.build.id,yZ);if(B.build?.status!=="succeeded"||!B.build.app_path)return B;let K=await Z6({root:$.root,payload:{action:"launch",app_path:B.build.app_path,...Z.device?{device:Z.device}:{},...Z.steps?{steps:Z.steps}:{},...Z.observe?{observe:Z.observe}:{},...Z.wait_for?{wait_for:Z.wait_for}:{},...Z.timeout!==void 0?{timeout:Z.timeout}:{}}});return{...K,text:`Built in ${Math.round(B.build.elapsed_ms/1000)} s. ${K.text}`,build:B.build}}case"launch":{let Q=await mZ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await b0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return O0(Q.device,Z,Q)}case"steps":{let Q=await t(Z.device,{booted:!0});return O0(Q,Z,{text:await b0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await t(Z.device,{booted:!0});if(C0.get(Q.udid)?.bundleId===Z.bundle_id)C0.get(Q.udid)?.stop();return await y0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${y(Q)}.`,device:Q}}case"logs":return pZ(await t(Z.device,{booted:!1}),Z.after);case"screenshot":return T3(await t(Z.device,{booted:!0}),Z.scale,Z.save_path?A3($.root,Z.save_path):void 0);case"chrome":return $Q(await t(Z.device,{booted:!1}));case"inspect":return dZ(await t(Z.device,{booted:!0}));case"tap":{let Q=await t(Z.device,{booted:!0}),B=Z.x!==void 0&&Z.y!==void 0;if(B)h5(Q,[Z.x,Z.y]);await b0(Q,[B?{action:"tap",x:Z.x,y:Z.y,...Z.duration&&Z.duration>0?{duration:Z.duration}:{}}:Z.id?{action:"tap",id:Z.id}:{action:"tap",label:Z.label}],3);let K=B?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return O0(Q,Z,{text:`Tapped ${K} on ${y(Q)}.`,device:Q})}case"swipe":{let Q=await t(Z.device,{booted:!0});return h5(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await b0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),O0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${y(Q)}.`,device:Q})}case"type":{let Q=await t(Z.device,{booted:!0});return await b0(Q,[{action:"type",text:Z.text}],3),O0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${y(Q)}.`,device:Q})}case"button":{let Q=await t(Z.device,{booted:!0});return await b0(Q,[{action:"button",name:Z.name}],3),O0(Q,Z,{text:`Pressed ${Z.name} on ${y(Q)}.`,device:Q})}case"open_url":{let Q=await t(Z.device,{booted:!0}),B;try{B=new URL(Z.url)}catch{k("simulator_invalid_request","open_url needs an absolute URL.")}if(_Z.has(B.protocol))k("simulator_invalid_request",`${B.protocol} URLs are not allowed.`);return await c("xcrun",["simctl","openurl",Q.udid,B.href],"Opening the URL"),O0(Q,Z,{text:`Opened ${B.href} on ${y(Q)}.`,device:Q})}case"appearance":{let Q=await t(Z.device,{booted:!0});return await c("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${y(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as ZQ,readFileSync as QQ,rmSync as BQ}from"fs";import{tmpdir as KQ}from"os";import{join as Q6}from"path";import{spawn as G6}from"child_process";var VQ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,F1=1,GQ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],B6=60,XQ=8,X6=W1;var K6={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},UQ=(()=>{let $={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((Z,Q)=>{$[Z]=4+Q,$[Z.toUpperCase()]=4+Q}),"1234567890".split("").forEach((Z,Q)=>{$[Z]=30+Q}),"!@#$%^&*()".split("").forEach((Z,Q)=>{$[Z]=30+Q});let J=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[Z,Q,B]of J)$[Z]=B,$[Q]=B;return $})();function WQ($){if(K6[$]!==void 0)return K6[$];return $>=32&&$<=126?UQ[String.fromCharCode($)]??null:null}function U6($,J){let Z=G6("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function YQ($,J){let Z=0,Q={x:0,y:0},B=(K)=>{J.call(K).catch(()=>{})};return{pointer(K,G,X){let W=(X&F1)!==0;if(W&&!(Z&F1))B({op:"touch",phase:"down",x:K,y:G});else if(W&&(K!==Q.x||G!==Q.y))B({op:"touch",phase:"move",x:K,y:G});else if(!W&&Z&F1)B({op:"touch",phase:"up",x:K,y:G});for(let Y of GQ)if(X&Y.bit&&!(Z&Y.bit))B({op:"swipe",x:K,y:G,x2:K+Y.dx*B6,y2:G+Y.dy*B6,duration:0.08});Z=X,Q={x:K,y:G}},key(K,G){let X=WQ(G);if(X!==null)B({op:"key",usage:X,down:K})},clipboard(K){U6($,K)},close(){if(Z&F1)B({op:"touch",phase:"up",...Q});Z=0}}}function FQ($,J){let Z=null,Q="",B,K=(G)=>{Y1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,X,W){let Y=(W&F1)!==0;if(Y&&!Z)Z={x:G,y:X,at:Date.now()};if(!Y&&Z){let U=(Date.now()-Z.at)/1000;if(Math.hypot(G-Z.x,X-Z.y)>XQ)K({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:X,duration:Math.min(Math.max(U,0.05),1)});else K({action:"tap",x:Z.x,y:Z.y,...U>0.5?{duration:Math.min(U,10)}:{}});Z=null}},key(G,X){if(!G)return;let W=X===65293?`
537
- `:X>=32&&X<=126?String.fromCharCode(X):null;if(W===null)return;Q+=W,clearTimeout(B),B=setTimeout(()=>{let Y=Q;Q="",K({action:"type",text:Y})},250)},clipboard(G){U6($,G)},close(){clearTimeout(B),Z=null}}}function zQ($,J,Z){return new Promise((Q,B)=>{let K=G6($,J,{stdio:"ignore",signal:Z});K.once("error",B),K.once("exit",(G)=>Q(G??-1))})}async function NQ($,J){let Z=ZQ(Q6(KQ(),"reason-simulator-stream-"));try{let Q=Q6(Z,"screen.png");if(await zQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let B=QQ(Q).subarray(16,24);return{width:B.readUInt32BE(0),height:B.readUInt32BE(4)}}finally{BQ(Z,{recursive:!0,force:!0})}}async function W6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!VQ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let B=await r5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),K=await Y1({payload:{action:"screenshot",device:Z},root:$.root});if(K.error||!K.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:K.image.width,height:K.image.height},X=await X3(B),W=X?await r1(B,Z,!0):null,Y=X?null:await V6();if(!X&&!Y)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let U={kind:"simulator",udid:Z,axe:B,points:G,sound:null,size:X?G:await NQ(Z,$.signal),stream:X?(F,N,z)=>b5(X,Z,Math.min(F,60),z,N):null,input:W?YQ(Z,W):FQ(Z,$.root)};return await $2({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>U,...Y?{ffmpeg:()=>Y}:{}}})}var p7=131072,TQ=131072,_Q=128,u7=8192,x3=30000,y3=15000,PQ=/^[a-z][a-z0-9_]{0,63}$/,RQ=new Set(["jobs.control","fs.read","fs.write"]),Y6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function J2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function F6($){return $.map(J2).join("/")}function _3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var qQ=[..._3(j1,4).map(($)=>`/(${$.map(F6).join("|")})(/|$)`),..._3(O1,4).map(($)=>`/(${$.map(F6).join("|")})$`),..._3([...I1],6).map(($)=>`/(${$.map(J2).join("|")})$`),`/${J2(".env")}\\.[^/]+$`,`/[^/]+(${A1.map(J2).join("|")})$`],g3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),d7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function l7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function gQ($){return N7($)}function E3(){if(n()==="darwin")return G0("/usr/bin/sandbox-exec");if(n()==="linux")return D7();return!1}function z6(){if(n()==="linux")return G0("/proc");if(!E3())return!1;if(n()==="darwin")return G0("/usr/sbin/lsof");return!1}function s7(){return n()==="darwin"?"/bin/zsh":M7()}function S3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function EQ($){if(!S3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>N0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function d0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function K2($,J,Z=u7){let Q=d0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function SQ($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function H1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function p0($,J){return J===$||J.startsWith(`${$}${IQ}`)}function m0($){if(H7($))throw new H("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 h($){let J;try{J=X0($.path)}catch(Z){if(process.platform==="darwin"&&U7(Z))throw W7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!C1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return m0(J),J}function h3($,J="."){if(!J||J.includes("\x00")||jQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");let Z=OQ($,J);if(!p0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function u0($,J=".",Z=!1){let Q=h3($,J),B;try{B=X0(Q)}catch(K){if(a7(K))throw i7();throw new H("path_not_found","Path does not exist.")}if(!p0($,B))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)m0(B);return B}function kQ($,J){let Z=h3($,J);if(m0(Z),G0(Z)){let K=X0(Z);if(!p0($,K))throw new H("symlink_escape","Write target resolves outside the granted root.");if(h7(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return m0(K),K}let Q=N1(Z);while(!G0(Q)){let K=N1(Q);if(K===Q)throw new H("path_outside_root","No safe write parent.");Q=K}let B=X0(Q);if(!p0($,B))throw new H("symlink_escape","Write parent resolves outside the granted root.");return m0(B),Z}function c7($,J){return q3($,J)||"."}function fQ($,J=p7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function n7($,J){return{...K7({home:$,temporaryDirectory:J}),ZDOTDIR:J,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 bQ($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...qQ.map((B)=>`(deny file-read* file-write* (regex #"${B}"))`),...C7($,Z),"(deny network*)"].join(`
538
- `)}async function m3($,J,Z){return new Promise((Q,B)=>{let K="",G="",X=!1,W=!1,Y=!1,U;try{U=AQ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],detached:!0})}catch(w){B(w);return}let F=(w,D)=>{if(Y)return;Y=!0,clearTimeout(C),Z.signal.removeEventListener("abort",z),Q({exitCode:w,signal:D,stdout:K,stderr:G,timedOut:W,truncated:X})},N=(w,D)=>{let O=`${w}${String(D)}`,_=fQ(O);return X||=_.truncated,_.value};U.stdout.on("data",(w)=>{K=N(K,w)}),U.stderr.on("data",(w)=>{G=N(G,w)}),U.once("error",B),U.once("exit",F);let z=()=>{try{U.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",z,{once:!0});let C=setTimeout(()=>{W=!0,z()},Z.timeoutMs)})}var N6=null;function xQ(){return N6??=w7({scrubEnvironment:n7,spawnCaptured:m3,isProtectedPath:g0}),N6}var yQ=async($,J,Z)=>{if(n()==="linux")return xQ()($,J,Z);if(n()!=="darwin"||!G0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=CQ(v7(LQ(),"reason-device-"));try{return await m3("/usr/bin/sandbox-exec",["-p",bQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:n7(Z.root,Q)})}finally{MQ(Q,{recursive:!0,force:!0})}};function hQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>_Q)throw new H("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>u7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function r7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let B=h($.root),K=Q.cwd??B,G=await $.runCommand(J,Z,{cwd:K,root:B,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??y3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function a7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var i7=()=>new H("path_unreadable","The path is not readable.");function mQ($){try{return m7($,I0.O_RDONLY)}catch(J){throw a7(J)?i7():J}}function H6($,J){let Z=v0()?Q2():null;return Z?B2(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):vQ($,J)}function vQ($,J){return $==="fs.read"?pQ(J):dQ(J)}async function pQ($){let J=h($.root),Z=u0(J,K2($.payload,"path"));if(!C1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=H1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),B=H1($.payload.max_bytes,65536,1,p7),K=d0($.payload,"encoding");if(K!==void 0&&K!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=mQ(Z),X,W;try{X=y7(G).size;let U=Buffer.alloc(Math.max(0,Math.min(B,X-Q)));W=U.subarray(0,U.byteLength?DQ(G,U,0,U.byteLength,Q):0)}finally{x7(G)}let Y=K==="base64"||W.includes(0);return{path:c7(J,Z),content:Y?W.toString("base64"):W.toString("utf8"),encoding:Y?"base64":"utf8",offset:Q,bytes:W.byteLength,size:X,truncated:Q+W.byteLength<X}}function uQ($,J){let Z=$==="append"?I0.O_APPEND:I0.O_TRUNC;return I0.O_WRONLY|I0.O_NOFOLLOW|Z|(J?0:I0.O_CREAT|I0.O_EXCL)}async function dQ($){let J=h($.root),Z=K2($.payload,"path"),Q=SQ($.payload,"content",TQ),B=d0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(B))throw new H("invalid_payload","mode must be create, overwrite, or append.");let K=kQ(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){HQ(N1(K),{recursive:!0,mode:448});let Y=X0(N1(K));if(!p0(J,Y))throw new H("symlink_escape","Write parent escaped root.")}if(!G0(N1(K)))throw new H("path_not_found","Write parent does not exist.");if(B==="create"&&G0(K))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=G0(K),X=G?h7(K):null,W=m7(K,uQ(B,G),384);try{if(X){let Y=y7(W);if(Y.ino!==X.ino||Y.dev!==X.dev)throw new H("symlink_escape","The write target changed between validation and opening.")}wQ(W,Q,null,"utf8")}finally{x7(W)}return{path:c7(J,K),bytes_written:Buffer.byteLength(Q,"utf8"),mode:B}}async function lQ($){let J=h($.root),Z=K2($.payload,"command",65536),Q=u0(J,d0($.payload,"cwd")??".");if(!C1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let B=H1($.payload.timeout_ms,y3,100,x3);return r7($,s7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:B})}async function sQ($){let J=I4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:n()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=h($.root),B=a6(Q,J.data.workspace),K=B.boundary===Q?Q:u0(B.anchor,q3(B.anchor,B.boundary)||"."),G=u0(K,q3(K,B.path)||".");if(!C1(G).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let X=Math.min(Date.parse(J.data.expires_at),Date.now()+w4);if(!(X>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let W=(O)=>$.emit("progress",{process:O});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await A2({claim:$.claim,root:K,cwd:G,command:J.data.command,mode:"host",shell:E0(),environment:process.env,expiresAtMs:X,signal:$.signal,emit:W})}}let Y={directory:v7(Z.runtimeDirectory,"processes")},U={deniedPorts:r6([$.apiOrigin])},F=V7(),N=G7(),z=v0(),C=J.data.egress?Z2(z):null;if(J.data.egress&&(C===null||!h0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let w=J.data.egress?await o4(J.data.egress.allowed_domains):null,D=w?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((O)=>`${O}=${w.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
539
- `):J.data.command;try{return{...await A2({claim:$.claim,root:G,cwd:G,command:D,mode:"host",shell:N,expiresAtMs:X,signal:$.signal,emit:W,...z?{jobsUser:{...z,...C!==null?{modelGid:C}:{}}}:{},environment:{...F.variables,HOME:F.home,PATH:F.path,TMPDIR:F.temporaryDirectory,SHELL:N},journals:Y,preview:U})}}finally{w?.close()}}async function cQ($){s2();let J=h($.root),Z=c2($.payload.command),Q=u0(J,d0($.payload,"cwd")??".");if(!C1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let B=H1($.payload.timeout_ms,a8,100,d2),{ignored:K}=n2($.payload.env);return await $.emit("progress",{shell:E0(),shell_flags:[...K1],sandbox:"none",ignored_env:K}),o8({command:Z,cwd:Q,timeoutMs:B,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function nQ($){let J=h($.root),Z=hQ($.payload),Q=Z[0];if(!Q||!d7.has(Q)&&!g3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let B=g3.has(Q);if(B&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let K=u0(J,d0($.payload,"cwd")??".");return r7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:K,allowWrite:B,timeoutMs:H1($.payload.timeout_ms,y3,100,x3)})}function o7($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");return Q}}async function rQ($){let J=h($.root);if(n()==="linux")return G5(J);return F5(J,o7($,J))}async function aQ($){let J=h($.root);if(n()==="linux")return X5(J);return z5(J,o7($,J))}async function iQ($){let J=$.worker?O5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&v3({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},...$.worker.ownComputer?{ownComputer:!0}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:h($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(B,K,G)=>$.emit(B,K,G)})}async function oQ($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new H("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=i6($.payload,$.operationId);return $7({root:h($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,B)=>$.emit(Q,B)})}return $.runPtySession({root:h($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function C6($,J){let Z=v0()?Q2():null;return Z?B2(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):tQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function tQ($,J){let Z=h(J.root),Q=$1 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let B=Q?A8(Z,J.payload[$1]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new H("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let X=X8.safeParse(J.payload);if(!X.success)throw new H("invalid_payload","Invalid Cloud export request.");return T8({runtimeRoot:B,source:X.data.source,url:X.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let K=K2(J.payload,"path",4096),G=$==="import"&&Q?h2(B):B;return m0(h3(G,K)),q0({direction:$,root:G,path:K,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var t7={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new H("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return t3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>H6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>H6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>C6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>C6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>n()==="darwin"&&l2(),execute:sQ},"exec.run":{requiredPermission:"execute",available:E3,execute:lQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>l2(),execute:cQ},"git.run":{requiredPermission:"execute",available:()=>E3()&&gQ("git"),execute:nQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:z6,execute:rQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:z6,execute:aQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>n()==="darwin"||Boolean(Y7()),execute:iQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:E7,execute:oQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:b7,execute:($)=>{let J=Q2();return J?B2(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??X7)()},$.signal):$2({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>k7(),execute:($)=>f7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:W1,execute:($)=>Y1({payload:$.payload,root:h($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:X6,execute:($)=>W6({payload:$.payload,root:h($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>J7({root:h($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>n()==="darwin"?G0("/usr/bin/sandbox-exec"):n()==="linux",execute:async($)=>{let J=_1.parse($.payload),Z=f3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!M0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return Z7({root:h($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>z4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>b3({root:h($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>t6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>e6({root:h($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:x2,execute:($)=>w8($.payload,$.signal)}};function eQ($,J){try{let Z=$4($,X0(J)),Q=Z?$.find((B)=>B.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function $B($,J){try{let Z=X0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function JB($,J){try{let Z=X0(J),Q=$.find((B)=>B.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function ZB($,J){try{let Z=X0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&p0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function QB($,J){try{return L1({home:X0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&w1(Z.path)).slice(0,U2).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function PX($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||n()==="darwin",B=Q?JB($,z1()):void 0,K=!J.worker&&n()==="darwin"?eQ($,z1()):void 0,G=Q?$B($,z1()):void 0,X=!J.worker&&n()==="darwin"?ZB($,z1()):void 0,W=Q?QB($,z1()):void 0,Y=u2.filter((U)=>{if(B1.has(U)&&!J.worker)return!1;if(J.worker&&!p1(U,J.worker))return!1;let F=t7[U];if(!F)return!1;return(U==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(U==="pty.start"||U==="preview.serve.v1")&&Boolean(J.worker)||U==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:F.available?.()??!0)&&$.some((z)=>(!J.worker||U!=="pty.start"||z.permissions.read&&z.permissions.write)&&l7(F).every((C)=>z.permissions[C]))});return{supported_operations:Y,...B?{account_root_fingerprint:B}:{},...K?{workspace_root_fingerprint:K}:{},...G?{account_root_path:G}:{},...X?{home_contained_root_fingerprints:X}:{},...W?{root_paths:W}:{},...Y.includes("hands.connect")?{hands_worker_artifact_sha256:P0,hands_worker_entrypoint:o0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:N0,max_result_bytes:N0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":H2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:s7(),sandbox:n()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:x3},...Y.includes("exec.full")?{"exec.full":t8()}:{},"git.run":{read_only_subcommands:[...d7].sort(),mutating_subcommands:[...g3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:e0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:Y0,max_timeout_ms:e0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:i0,protocol_version:R3,worker_artifact_sha256:P0,worker_entrypoint:o0,policy_mode:"full_access",policy_version:1,workspace_base:P3,workspace_layout:Q1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":n()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...Y.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:g7,max_session_ms:R7,max_buffered_output_bytes:q7}}:{},...J.worker?Object.fromEntries(Y.filter((U)=>U!=="browser.pr-proof.v1").map((U)=>[U,{ready:J.worker?.readiness?.[U]===!0,...J.worker?.readiness?.[U]!==!0&&J.worker?.probing?.includes(U)?{probing:!0}:{},execution_mode:p1(U,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...U==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:n6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!v0()?{persistent_terminals:!0}:{}}:{},...U==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...U==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:h6,...J.worker?.ownComputer?{[m6]:v6}:{},workspace_base:P3,workspace_layout:Q1,browser_state:"optional_headless",desktop:!1,worker_version:i0,protocol_version:R3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:w6,[O6]:j6}:{},...J.worker?{[A6]:I6}:{},...J.worker?.handsBrowser?{[q6]:R6}:{},[P6]:_6,[E6]:g6,...h0(J.worker?.executionMode==="unsandboxed")?{[k6]:S6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&Z2()!==null?{[b6]:f6}:{},...h0(J.worker?.executionMode==="unsandboxed")&&v0()?{[y6]:x6}:{}}:{},...U==="fs.export"?{cloud_source_version:f1,source_kinds:["workspace","attachment"],[q2]:g2}:{},...U==="fs.import"?{[q2]:g2}:{},...U===M4&&Z2()!==null&&h0(J.worker?.executionMode==="unsandboxed")?{[O4]:M2}:{},...U==="tunnel.open"?{carried_jobs:p6}:{},...U==="jobs.control"?{[d6]:u6}:{},...U==="display.stream.v1"&&J.worker?.displayVideo?{[j7]:L7,[I7]:O7.join(","),[A7]:T7,[_7]:P7}:{},...U==="automation.call.v1"&&J.worker?.userChrome?{[l6]:!0}:{},...U==="automation.call.v1"&&J.worker?.cloudSessions?{[s6]:!0}:{}}])):{}}}}function v3($,J,Z,Q,B){let K=B7.safeParse(Q);return K.success&&B!==void 0&&B.device_id===$.deviceId&&K.data.device_id===$.deviceId&&K.data.root_id===J&&K.data.run_id===Z&&K.data.binding.kind===B.binding&&K.data.binding.target_revision===B.target_revision&&K.data.binding.root_grant_revision===B.root_grant_revision&&K.data.binding.target_generation===B.target_generation&&K.data.binding.target_fence_id===B.target_fence_id}async function RX($,J,Z,Q,B){if(J.capability!=="hands.connect"||Z.kind!==L6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let K=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof K!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((Y)=>Y.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let X=await Q.operationEnvironment($,J,K,B);if(!v3($,G.id,J.run_id,X.payload,X.authority)||X.payload.snapshot_id!==K)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let W=b3({root:h(G),operationId:J.operation_id,payload:X.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:W.snapshot_id,installed_revision:W.installed_revision,installed:!0},B),!0}async function qX($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==T6)return!1;let{version:B,run_id:K,target_generation:G,target_fence_id:X}=Z.payload;if(B!==1||Object.keys(Z.payload).length!==4||typeof K!=="string"||typeof G!=="number"||typeof X!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let W=$.roots.find((Y)=>Y.id===J.root_id);if(!W)throw new H("root_not_granted","The Hands root is no longer granted.");return await o6({operationId:J.operation_id,root:h(W),runId:K,targetGeneration:G,fenceId:X,...Q?{signal:Q}:{}}),!0}async function gX($,J,Z){if(J.capability!=="github.local.v1")return D6($,J,Z);try{let Q=await D6($,J,Z);if(Q.status==="succeeded"||k3(J.payload,Q.status,Q.error_code))return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function D6($,J,Z){if(B1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!p1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let U=f3.safeParse(J.local_github_authority);if(!U.success||U.data.deviceId!==$.deviceId||U.data.rootId!==J.root_id||U.data.runId!==J.run_id||U.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=t7[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let B=$.roots.find((U)=>U.id===J.root_id);if(!B)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&S3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let U=Boolean(Z.worker||$.worker)&&$1 in J.payload;if(J.capability!=="fs.export"||!U)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!v3($,B.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(l7(Q).some((U)=>!B.permissions[U]))return{status:"failed",error_code:"permission_denied"};let K=0,G=async(U,F,N)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(U==="started"||U==="completed"))return;await Z.emit?.({sequence:K++,kind:U,capability:J.capability,data:F,...(U==="hands.reconnected"||J.capability==="inference.custom.v1")&&N?{deliverySignal:N}:{}})},X=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||RQ.has(J.capability)||J.capability==="pty.start",W,Y=async(U,F,N)=>{let z=W;W=void 0,await Promise.all([z,G(U,F,N)])};try{if(X)W=G("started"),W.catch(()=>{return});else await G("started");let U={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},F=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(N)=>G("pr-proof.started.v1",N))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:B,payload:EQ(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:U,runCommand:Z.runCommand??yQ,spawnFullControl:Z.spawnFullControl??m3,emit:X?Y:G,runHandsRelay:Z.runHandsRelay??((N)=>z7(N,U)),runPtySession:Z.runPtySession??S7});if(J.capability==="github.local.v1")M6.parse(F);if(!S3(F))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(F)??"null","utf8")>N0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(X?Y:G)("completed",{ok:!0}),{status:"succeeded",result:F,error_code:null}}catch(U){let F=Z.signal.reason instanceof H&&Y6.has(Z.signal.reason.code)?Z.signal.reason.code:U instanceof H&&Y6.has(U.code)?U.code:null;if(Z.signal.aborted||F)return{status:"cancelled",...U instanceof a0?{result:{process_terminal_observation:U.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":F??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&U instanceof Error&&"code"in U&&["EACCES","EPERM"].includes(String(U.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let N=J.capability==="inference.custom.v1"?U instanceof H&&c6(U.code)?U.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?U instanceof P1&&k3(J.payload,"failed",U.code)?U.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":U instanceof H&&PQ.test(U.code)?U.code:"capability_failed",z=J.capability==="hands.connect"&&U instanceof F7?Q7(U.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:N,...z?{expiry_diagnostic:z}:{}}),{status:"failed",error_code:N}}}
540
- export{A9 as Ba,T9 as Ca,C4 as Da,yB as Ea,pB as Fa,UK as Ga,WK as Ha,x2 as Ia,VV as Ja,F0 as Ka,p$ as La,u$ as Ma,GV as Na,i$ as Oa,E0 as Pa,hJ as Qa,RQ as Ra,s7 as Sa,n7 as Ta,bQ as Ua,m3 as Va,yQ as Wa,vQ as Xa,tQ as Ya,t7 as Za,eQ as _a,$B as $a,JB as ab,ZB as bb,QB as cb,PX as db,RX as eb,qX as fb,gX as gb};